LCOV - code coverage report
Current view: top level - src/script - interpreter.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 846 859 98.5 %
Date: 2020-09-26 01:30:44 Functions: 61 67 91.0 %

          Line data    Source code
       1             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2             : // Copyright (c) 2009-2020 The Bitcoin Core developers
       3             : // Distributed under the MIT software license, see the accompanying
       4             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5             : 
       6             : #include <script/interpreter.h>
       7             : 
       8             : #include <crypto/ripemd160.h>
       9             : #include <crypto/sha1.h>
      10             : #include <crypto/sha256.h>
      11             : #include <pubkey.h>
      12             : #include <script/script.h>
      13             : #include <uint256.h>
      14             : 
      15             : typedef std::vector<unsigned char> valtype;
      16             : 
      17             : namespace {
      18             : 
      19     3941422 : inline bool set_success(ScriptError* ret)
      20             : {
      21     3941422 :     if (ret)
      22     1359074 :         *ret = SCRIPT_ERR_OK;
      23     3941439 :     return true;
      24             : }
      25             : 
      26     4303844 : inline bool set_error(ScriptError* ret, const ScriptError serror)
      27             : {
      28     4303844 :     if (ret)
      29     1616228 :         *ret = serror;
      30     4303967 :     return false;
      31             : }
      32             : 
      33             : } // namespace
      34             : 
      35     1609135 : bool CastToBool(const valtype& vch)
      36             : {
      37     1609595 :     for (unsigned int i = 0; i < vch.size(); i++)
      38             :     {
      39     1606249 :         if (vch[i] != 0)
      40             :         {
      41             :             // Can be negative zero
      42     1605868 :             if (i == vch.size()-1 && vch[i] == 0x80)
      43          17 :                 return false;
      44     1605938 :             return true;
      45             :         }
      46             :     }
      47        3390 :     return false;
      48     1609351 : }
      49             : 
      50             : /**
      51             :  * Script is a stack machine (like Forth) that evaluates a predicate
      52             :  * returning a bool indicating valid or not.  There are no loops.
      53             :  */
      54             : #define stacktop(i)  (stack.at(stack.size()+(i)))
      55             : #define altstacktop(i)  (altstack.at(altstack.size()+(i)))
      56     5944820 : static inline void popstack(std::vector<valtype>& stack)
      57             : {
      58     5944820 :     if (stack.empty())
      59           0 :         throw std::runtime_error("popstack(): stack empty");
      60     5944762 :     stack.pop_back();
      61     5944762 : }
      62             : 
      63      818212 : bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
      64      818212 :     if (vchPubKey.size() < CPubKey::COMPRESSED_SIZE) {
      65             :         //  Non-canonical public key: too short
      66          18 :         return false;
      67             :     }
      68      818194 :     if (vchPubKey[0] == 0x04) {
      69        2024 :         if (vchPubKey.size() != CPubKey::SIZE) {
      70             :             //  Non-canonical public key: invalid length for uncompressed key
      71           0 :             return false;
      72             :         }
      73      816170 :     } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
      74      816091 :         if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
      75             :             //  Non-canonical public key: invalid length for compressed key
      76           0 :             return false;
      77             :         }
      78             :     } else {
      79             :         //  Non-canonical public key: neither compressed nor uncompressed
      80          79 :         return false;
      81             :     }
      82      818115 :     return true;
      83      818212 : }
      84             : 
      85      319491 : bool static IsCompressedPubKey(const valtype &vchPubKey) {
      86      319491 :     if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
      87             :         //  Non-canonical public key: invalid length for compressed key
      88         467 :         return false;
      89             :     }
      90      319024 :     if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
      91             :         //  Non-canonical public key: invalid prefix for compressed key
      92           0 :         return false;
      93             :     }
      94      319024 :     return true;
      95      319491 : }
      96             : 
      97             : /**
      98             :  * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
      99             :  * Where R and S are not negative (their first byte has its highest bit not set), and not
     100             :  * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
     101             :  * in which case a single 0 byte is necessary and even required).
     102             :  *
     103             :  * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
     104             :  *
     105             :  * This function is consensus-critical since BIP66.
     106             :  */
     107     1797180 : bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
     108             :     // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
     109             :     // * total-length: 1-byte length descriptor of everything that follows,
     110             :     //   excluding the sighash byte.
     111             :     // * R-length: 1-byte length descriptor of the R value that follows.
     112             :     // * R: arbitrary-length big-endian encoded R value. It must use the shortest
     113             :     //   possible encoding for a positive integer (which means no null bytes at
     114             :     //   the start, except a single one when the next byte has its highest bit set).
     115             :     // * S-length: 1-byte length descriptor of the S value that follows.
     116             :     // * S: arbitrary-length big-endian encoded S value. The same rules apply.
     117             :     // * sighash: 1-byte value indicating what data is hashed (not part of the DER
     118             :     //   signature)
     119             : 
     120             :     // Minimum and maximum size constraints.
     121     1797180 :     if (sig.size() < 9) return false;
     122     1797106 :     if (sig.size() > 73) return false;
     123             : 
     124         803 :     // A signature is of type 0x30 (compound).
     125     1788017 :     if (sig[0] != 0x30) return false;
     126             : 
     127             :     // Make sure the length covers the entire signature.
     128     1742129 :     if (sig[1] != sig.size() - 3) return false;
     129             : 
     130             :     // Extract the length of the R element.
     131     1725960 :     unsigned int lenR = sig[3];
     132             : 
     133             :     // Make sure the length of the S element is still inside the signature.
     134     1725960 :     if (5 + lenR >= sig.size()) return false;
     135             : 
     136             :     // Extract the length of the S element.
     137     1725952 :     unsigned int lenS = sig[5 + lenR];
     138             : 
     139             :     // Verify that the length of the signature matches the sum of the length
     140             :     // of the elements.
     141     1725952 :     if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
     142             : 
     143             :     // Check whether the R element is an integer.
     144     1725939 :     if (sig[2] != 0x02) return false;
     145             : 
     146             :     // Zero-length integers are not allowed for R.
     147     1725931 :     if (lenR == 0) return false;
     148             : 
     149             :     // Negative numbers are not allowed for R.
     150     1725921 :     if (sig[4] & 0x80) return false;
     151             : 
     152             :     // Null bytes at the start of R are not allowed, unless R would
     153             :     // otherwise be interpreted as a negative number.
     154     1725732 :     if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
     155             : 
     156             :     // Check whether the S element is an integer.
     157     1725649 :     if (sig[lenR + 4] != 0x02) return false;
     158             : 
     159             :     // Zero-length integers are not allowed for S.
     160     1725641 :     if (lenS == 0) return false;
     161             : 
     162             :     // Negative numbers are not allowed for S.
     163     1725631 :     if (sig[lenR + 6] & 0x80) return false;
     164             : 
     165             :     // Null bytes at the start of S are not allowed, unless S would otherwise be
     166             :     // interpreted as a negative number.
     167     1725623 :     if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
     168             : 
     169     1725601 :     return true;
     170     1797180 : }
     171             : 
     172      817681 : bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
     173      817681 :     if (!IsValidSignatureEncoding(vchSig)) {
     174           0 :         return set_error(serror, SCRIPT_ERR_SIG_DER);
     175             :     }
     176             :     // https://bitcoin.stackexchange.com/a/12556:
     177             :     //     Also note that inside transaction signatures, an extra hashtype byte
     178             :     //     follows the actual signature data.
     179      817681 :     std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
     180             :     // If the S value is above the order of the curve divided by two, its
     181             :     // complement modulo the order could have been used instead, which is
     182             :     // one byte shorter when encoded correctly.
     183      817681 :     if (!CPubKey::CheckLowS(vchSigCopy)) {
     184          21 :         return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
     185             :     }
     186      817660 :     return true;
     187      817681 : }
     188             : 
     189      882955 : bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
     190      882955 :     if (vchSig.size() == 0) {
     191           0 :         return false;
     192             :     }
     193      882955 :     unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
     194      882955 :     if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
     195          33 :         return false;
     196             : 
     197      882922 :     return true;
     198      882955 : }
     199             : 
     200     1100836 : bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
     201             :     // Empty signature. Not strictly DER encoded, but allowed to provide a
     202             :     // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
     203     1100836 :     if (vchSig.size() == 0) {
     204         826 :         return true;
     205             :     }
     206     1100089 :     if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
     207       71579 :         return set_error(serror, SCRIPT_ERR_SIG_DER);
     208     1028478 :     } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
     209             :         // serror is set
     210          21 :         return false;
     211     1028457 :     } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
     212          33 :         return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
     213             :     }
     214     1028423 :     return true;
     215     1100883 : }
     216             : 
     217      964067 : bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
     218      964067 :     if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
     219          97 :         return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
     220             :     }
     221             :     // Only compressed keys are accepted in segwit
     222      963969 :     if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SigVersion::WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
     223         467 :         return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
     224             :     }
     225      963524 :     return true;
     226      964087 : }
     227             : 
     228     2698251 : bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
     229             :     // Excludes OP_1NEGATE, OP_1-16 since they are by definition minimal
     230     2698251 :     assert(0 <= opcode && opcode <= OP_PUSHDATA4);
     231     2698251 :     if (data.size() == 0) {
     232             :         // Should have used OP_0.
     233      348486 :         return opcode == OP_0;
     234     2349765 :     } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
     235             :         // Should have used OP_1 .. OP_16.
     236         147 :         return false;
     237     2349618 :     } else if (data.size() == 1 && data[0] == 0x81) {
     238             :         // Should have used OP_1NEGATE.
     239          14 :         return false;
     240     2349604 :     } else if (data.size() <= 75) {
     241             :         // Must have used a direct push (opcode indicating number of bytes pushed + those bytes).
     242     2348693 :         return opcode == data.size();
     243         911 :     } else if (data.size() <= 255) {
     244             :         // Must have used OP_PUSHDATA.
     245         640 :         return opcode == OP_PUSHDATA1;
     246         271 :     } else if (data.size() <= 65535) {
     247             :         // Must have used OP_PUSHDATA2.
     248         271 :         return opcode == OP_PUSHDATA2;
     249             :     }
     250           0 :     return true;
     251     2698251 : }
     252             : 
     253      670312 : int FindAndDelete(CScript& script, const CScript& b)
     254             : {
     255     4093648 :     int nFound = 0;
     256      670312 :     if (b.empty())
     257           1 :         return nFound;
     258      670263 :     CScript result;
     259      670263 :     CScript::const_iterator pc = script.begin(), pc2 = script.begin(), end = script.end();
     260      670347 :     opcodetype opcode;
     261      670347 :     do
     262             :     {
     263     4093648 :         result.insert(result.end(), pc2, pc);
     264     4118602 :         while (static_cast<size_t>(end - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
     265             :         {
     266       25023 :             pc = pc + b.size();
     267       25023 :             ++nFound;
     268             :         }
     269     4093720 :         pc2 = pc;
     270     4093471 :     }
     271     4093720 :     while (script.GetOp(pc, opcode));
     272             : 
     273      670349 :     if (nFound > 0) {
     274       18868 :         result.insert(result.end(), pc2, end);
     275       18868 :         script = std::move(result);
     276             :     }
     277             : 
     278             :     return nFound;
     279      670349 : }
     280             : 
     281             : namespace {
     282             : /** A data type to abstract out the condition stack during script execution.
     283             :  *
     284             :  * Conceptually it acts like a vector of booleans, one for each level of nested
     285             :  * IF/THEN/ELSE, indicating whether we're in the active or inactive branch of
     286             :  * each.
     287             :  *
     288             :  * The elements on the stack cannot be observed individually; we only need to
     289             :  * expose whether the stack is empty and whether or not any false values are
     290             :  * present at all. To implement OP_ELSE, a toggle_top modifier is added, which
     291             :  * flips the last value without returning it.
     292             :  *
     293             :  * This uses an optimized implementation that does not materialize the
     294             :  * actual stack. Instead, it just stores the size of the would-be stack,
     295             :  * and the position of the first false value in it.
     296             :  */
     297     5841262 : class ConditionStack {
     298             : private:
     299             :     //! A constant for m_first_false_pos to indicate there are no falses.
     300             :     static constexpr uint32_t NO_FALSE = std::numeric_limits<uint32_t>::max();
     301             : 
     302             :     //! The size of the implied stack.
     303     2920502 :     uint32_t m_stack_size = 0;
     304             :     //! The position of the first false value on the implied stack, or NO_FALSE if all true.
     305     2920502 :     uint32_t m_first_false_pos = NO_FALSE;
     306             : 
     307             : public:
     308     2849911 :     bool empty() { return m_stack_size == 0; }
     309     7805209 :     bool all_true() { return m_first_false_pos == NO_FALSE; }
     310        7300 :     void push_back(bool f)
     311             :     {
     312        7300 :         if (m_first_false_pos == NO_FALSE && !f) {
     313             :             // The stack consists of all true values, and a false is added.
     314             :             // The first false value will appear at the current size.
     315        2580 :             m_first_false_pos = m_stack_size;
     316        2580 :         }
     317        7300 :         ++m_stack_size;
     318        7300 :     }
     319        6083 :     void pop_back()
     320             :     {
     321        6083 :         assert(m_stack_size > 0);
     322        6084 :         --m_stack_size;
     323        6084 :         if (m_first_false_pos == m_stack_size) {
     324             :             // When popping off the first false value, everything becomes true.
     325        2820 :             m_first_false_pos = NO_FALSE;
     326        2820 :         }
     327        6084 :     }
     328        5287 :     void toggle_top()
     329             :     {
     330        5287 :         assert(m_stack_size > 0);
     331        5289 :         if (m_first_false_pos == NO_FALSE) {
     332             :             // The current stack is all true values; the first false will be the top.
     333        2717 :             m_first_false_pos = m_stack_size - 1;
     334        5291 :         } else if (m_first_false_pos == m_stack_size - 1) {
     335             :             // The top is the first false value; toggling it will make everything true.
     336        2322 :             m_first_false_pos = NO_FALSE;
     337        2322 :         } else {
     338             :             // There is a false value, but not on top. No action is needed as toggling
     339             :             // anything but the first false value is unobservable.
     340             :         }
     341        5291 :     }
     342             : };
     343             : }
     344             : 
     345             : /** Helper for OP_CHECKSIG and OP_CHECKSIGVERIFY
     346             :  *
     347             :  * A return value of false means the script fails entirely. When true is returned, the
     348             :  * fSuccess variable indicates whether the signature check itself succeeded.
     349             :  */
     350      969136 : static bool EvalChecksig(const valtype& vchSig, const valtype& vchPubKey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& fSuccess)
     351             : {
     352             :     // Subset of script starting at the most recent codeseparator
     353      969136 :     CScript scriptCode(pbegincodehash, pend);
     354             : 
     355             :     // Drop the signature in pre-segwit scripts but not segwit scripts
     356      969136 :     if (sigversion == SigVersion::BASE) {
     357      612470 :         int found = FindAndDelete(scriptCode, CScript() << vchSig);
     358      612472 :         if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
     359           3 :             return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
     360      612455 :     }
     361             : 
     362      969367 :     if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
     363             :         //serror is set
     364       16859 :         return false;
     365             :     }
     366      952400 :     fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
     367             : 
     368      952457 :     if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
     369         268 :         return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
     370             : 
     371      952179 :     return true;
     372      969331 : }
     373             : 
     374     2920227 : bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
     375             : {
     376     2920227 :     static const CScriptNum bnZero(0);
     377     2920174 :     static const CScriptNum bnOne(1);
     378             :     // static const CScriptNum bnFalse(0);
     379             :     // static const CScriptNum bnTrue(1);
     380     2920223 :     static const valtype vchFalse(0);
     381             :     // static const valtype vchZero(0);
     382     2920215 :     static const valtype vchTrue(1, 1);
     383             : 
     384     2920230 :     CScript::const_iterator pc = script.begin();
     385     2920230 :     CScript::const_iterator pend = script.end();
     386    13645952 :     CScript::const_iterator pbegincodehash = script.begin();
     387     2920230 :     opcodetype opcode;
     388     2920230 :     valtype vchPushValue;
     389     2920230 :     ConditionStack vfExec;
     390     2920230 :     std::vector<valtype> altstack;
     391     2920230 :     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
     392     2920230 :     if (script.size() > MAX_SCRIPT_SIZE)
     393          12 :         return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
     394    10645418 :     int nOpCount = 0;
     395     2920636 :     bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
     396             : 
     397             :     try
     398             :     {
     399    10645469 :         while (pc < pend)
     400             :         {
     401     7807363 :             bool fExec = vfExec.all_true();
     402             : 
     403             :             //
     404             :             // Read instruction
     405             :             //
     406     7807363 :             if (!script.GetOp(pc, opcode, vchPushValue))
     407          21 :                 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
     408     7804713 :             if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
     409          21 :                 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
     410             : 
     411             :             // Note how OP_RESERVED does not count towards the opcode limit.
     412    15530075 :             if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
     413          33 :                 return set_error(serror, SCRIPT_ERR_OP_COUNT);
     414             : 
     415   117075975 :             if (opcode == OP_CAT ||
     416     7805065 :                 opcode == OP_SUBSTR ||
     417     7805065 :                 opcode == OP_LEFT ||
     418     7805065 :                 opcode == OP_RIGHT ||
     419     7805065 :                 opcode == OP_INVERT ||
     420     7805065 :                 opcode == OP_AND ||
     421     7805065 :                 opcode == OP_OR ||
     422     7805065 :                 opcode == OP_XOR ||
     423     7805065 :                 opcode == OP_2MUL ||
     424     7805065 :                 opcode == OP_2DIV ||
     425     7805065 :                 opcode == OP_MUL ||
     426     7805065 :                 opcode == OP_DIV ||
     427     7805065 :                 opcode == OP_MOD ||
     428     7805065 :                 opcode == OP_LSHIFT ||
     429     7805065 :                 opcode == OP_RSHIFT)
     430         263 :                 return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes (CVE-2010-5137).
     431             : 
     432             :             // With SCRIPT_VERIFY_CONST_SCRIPTCODE, OP_CODESEPARATOR in non-segwit script is rejected even in an unexecuted branch
     433     7804285 :             if (opcode == OP_CODESEPARATOR && sigversion == SigVersion::BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
     434           7 :                 return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
     435             : 
     436     7804957 :             if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
     437     3320914 :                 if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
     438         192 :                     return set_error(serror, SCRIPT_ERR_MINIMALDATA);
     439             :                 }
     440     3320713 :                 stack.push_back(vchPushValue);
     441     4484383 :             } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
     442     4219653 :             switch (opcode)
     443             :             {
     444             :                 //
     445             :                 // Push value
     446             :                 //
     447             :                 case OP_1NEGATE:
     448             :                 case OP_1:
     449             :                 case OP_2:
     450             :                 case OP_3:
     451             :                 case OP_4:
     452             :                 case OP_5:
     453             :                 case OP_6:
     454             :                 case OP_7:
     455             :                 case OP_8:
     456             :                 case OP_9:
     457             :                 case OP_10:
     458             :                 case OP_11:
     459             :                 case OP_12:
     460             :                 case OP_13:
     461             :                 case OP_14:
     462             :                 case OP_15:
     463             :                 case OP_16:
     464             :                 {
     465             :                     // ( -- value)
     466      222031 :                     CScriptNum bn((int)opcode - (int)(OP_1 - 1));
     467      222011 :                     stack.push_back(bn.getvch());
     468             :                     // The result of these opcodes should always be the minimal way to push the data
     469             :                     // they push, so no need for a CheckMinimalPush here.
     470      222118 :                 }
     471      222118 :                 break;
     472             : 
     473             : 
     474             :                 //
     475             :                 // Control
     476             :                 //
     477             :                 case OP_NOP:
     478             :                     break;
     479             : 
     480             :                 case OP_CHECKLOCKTIMEVERIFY:
     481             :                 {
     482       26732 :                     if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
     483             :                         // not enabled; treat as a NOP2
     484             :                         break;
     485             :                     }
     486             : 
     487        8236 :                     if (stack.size() < 1)
     488           3 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     489             : 
     490             :                     // Note that elsewhere numeric opcodes are limited to
     491             :                     // operands in the range -2**31+1 to 2**31-1, however it is
     492             :                     // legal for opcodes to produce results exceeding that
     493             :                     // range. This limitation is implemented by CScriptNum's
     494             :                     // default 4-byte limit.
     495             :                     //
     496             :                     // If we kept to that limit we'd have a year 2038 problem,
     497             :                     // even though the nLockTime field in transactions
     498             :                     // themselves is uint32 which only becomes meaningless
     499             :                     // after the year 2106.
     500             :                     //
     501             :                     // Thus as a special case we tell CScriptNum to accept up
     502             :                     // to 5-byte bignums, which are good until 2**39-1, well
     503             :                     // beyond the 2**32-1 limit of the nLockTime field itself.
     504        8233 :                     const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
     505             : 
     506             :                     // In the rare event that the argument may be < 0 due to
     507             :                     // some arithmetic being done first, you can always use
     508             :                     // 0 MAX CHECKLOCKTIMEVERIFY.
     509        8231 :                     if (nLockTime < 0)
     510           7 :                         return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
     511             : 
     512             :                     // Actually compare the specified lock time with the transaction.
     513        8224 :                     if (!checker.CheckLockTime(nLockTime))
     514        8210 :                         return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
     515             : 
     516          14 :                     break;
     517        8233 :                 }
     518             : 
     519             :                 case OP_CHECKSEQUENCEVERIFY:
     520             :                 {
     521       27168 :                     if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
     522             :                         // not enabled; treat as a NOP3
     523             :                         break;
     524             :                     }
     525             : 
     526        8446 :                     if (stack.size() < 1)
     527          16 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     528             : 
     529             :                     // nSequence, like nLockTime, is a 32-bit unsigned integer
     530             :                     // field. See the comment in CHECKLOCKTIMEVERIFY regarding
     531             :                     // 5-byte numeric operands.
     532        8430 :                     const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
     533             : 
     534             :                     // In the rare event that the argument may be < 0 due to
     535             :                     // some arithmetic being done first, you can always use
     536             :                     // 0 MAX CHECKSEQUENCEVERIFY.
     537        8420 :                     if (nSequence < 0)
     538          15 :                         return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
     539             : 
     540             :                     // To provide for future soft-fork extensibility, if the
     541             :                     // operand has the disabled lock-time flag set,
     542             :                     // CHECKSEQUENCEVERIFY behaves as a NOP.
     543        8405 :                     if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
     544          60 :                         break;
     545             : 
     546             :                     // Compare the specified sequence number with the input.
     547        8345 :                     if (!checker.CheckSequence(nSequence))
     548        8322 :                         return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
     549             : 
     550          23 :                     break;
     551        8430 :                 }
     552             : 
     553             :                 case OP_NOP1: case OP_NOP4: case OP_NOP5:
     554             :                 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
     555             :                 {
     556         701 :                     if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
     557         154 :                         return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
     558             :                 }
     559             :                 break;
     560             : 
     561             :                 case OP_IF:
     562             :                 case OP_NOTIF:
     563             :                 {
     564             :                     // <expression> if [statements] [else [statements]] endif
     565        7301 :                     bool fValue = false;
     566        7706 :                     if (fExec)
     567             :                     {
     568        7485 :                         if (stack.size() < 1)
     569         195 :                             return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
     570        7290 :                         valtype& vch = stacktop(-1);
     571        7298 :                         if (sigversion == SigVersion::WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
     572         365 :                             if (vch.size() > 1)
     573          80 :                                 return set_error(serror, SCRIPT_ERR_MINIMALIF);
     574         285 :                             if (vch.size() == 1 && vch[0] != 1)
     575         169 :                                 return set_error(serror, SCRIPT_ERR_MINIMALIF);
     576             :                         }
     577        7050 :                         fValue = CastToBool(vch);
     578        7050 :                         if (opcode == OP_NOTIF)
     579         578 :                             fValue = !fValue;
     580        7062 :                         popstack(stack);
     581        7076 :                     }
     582        7301 :                     vfExec.push_back(fValue);
     583        7301 :                 }
     584             :                 break;
     585             : 
     586             :                 case OP_ELSE:
     587             :                 {
     588        5344 :                     if (vfExec.empty())
     589          48 :                         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
     590        5289 :                     vfExec.toggle_top();
     591             :                 }
     592             :                 break;
     593             : 
     594             :                 case OP_ENDIF:
     595             :                 {
     596        6170 :                     if (vfExec.empty())
     597          84 :                         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
     598        6084 :                     vfExec.pop_back();
     599             :                 }
     600             :                 break;
     601             : 
     602             :                 case OP_VERIFY:
     603             :                 {
     604             :                     // (true -- ) or
     605             :                     // (false -- false) and return
     606         488 :                     if (stack.size() < 1)
     607           7 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     608         481 :                     bool fValue = CastToBool(stacktop(-1));
     609         481 :                     if (fValue)
     610         465 :                         popstack(stack);
     611             :                     else
     612          16 :                         return set_error(serror, SCRIPT_ERR_VERIFY);
     613         465 :                 }
     614             :                 break;
     615             : 
     616             :                 case OP_RETURN:
     617             :                 {
     618          67 :                     return set_error(serror, SCRIPT_ERR_OP_RETURN);
     619             :                 }
     620             :                 break;
     621             : 
     622             : 
     623             :                 //
     624             :                 // Stack ops
     625             :                 //
     626             :                 case OP_TOALTSTACK:
     627             :                 {
     628         131 :                     if (stack.size() < 1)
     629           9 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     630         122 :                     altstack.push_back(stacktop(-1));
     631         122 :                     popstack(stack);
     632             :                 }
     633             :                 break;
     634             : 
     635             :                 case OP_FROMALTSTACK:
     636             :                 {
     637          74 :                     if (altstack.size() < 1)
     638          23 :                         return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
     639          51 :                     stack.push_back(altstacktop(-1));
     640          51 :                     popstack(altstack);
     641             :                 }
     642             :                 break;
     643             : 
     644             :                 case OP_2DROP:
     645             :                 {
     646             :                     // (x1 x2 -- )
     647       29686 :                     if (stack.size() < 2)
     648          13 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     649       29653 :                     popstack(stack);
     650       29940 :                     popstack(stack);
     651             :                 }
     652             :                 break;
     653             : 
     654             :                 case OP_2DUP:
     655             :                 {
     656             :                     // (x1 x2 -- x1 x2 x1 x2)
     657       33316 :                     if (stack.size() < 2)
     658          34 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     659       33221 :                     valtype vch1 = stacktop(-2);
     660       33374 :                     valtype vch2 = stacktop(-1);
     661       33370 :                     stack.push_back(vch1);
     662       33369 :                     stack.push_back(vch2);
     663       33373 :                 }
     664       33373 :                 break;
     665             : 
     666             :                 case OP_3DUP:
     667             :                 {
     668             :                     // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
     669       21695 :                     if (stack.size() < 3)
     670          51 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     671       21644 :                     valtype vch1 = stacktop(-3);
     672       21644 :                     valtype vch2 = stacktop(-2);
     673       21644 :                     valtype vch3 = stacktop(-1);
     674       21644 :                     stack.push_back(vch1);
     675       21644 :                     stack.push_back(vch2);
     676       21644 :                     stack.push_back(vch3);
     677       21644 :                 }
     678       21644 :                 break;
     679             : 
     680             :                 case OP_2OVER:
     681             :                 {
     682             :                     // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
     683          68 :                     if (stack.size() < 4)
     684          34 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     685          34 :                     valtype vch1 = stacktop(-4);
     686          34 :                     valtype vch2 = stacktop(-3);
     687          34 :                     stack.push_back(vch1);
     688          34 :                     stack.push_back(vch2);
     689          34 :                 }
     690          34 :                 break;
     691             : 
     692             :                 case OP_2ROT:
     693             :                 {
     694             :                     // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
     695         217 :                     if (stack.size() < 6)
     696          13 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     697         204 :                     valtype vch1 = stacktop(-6);
     698         204 :                     valtype vch2 = stacktop(-5);
     699         204 :                     stack.erase(stack.end()-6, stack.end()-4);
     700         204 :                     stack.push_back(vch1);
     701         204 :                     stack.push_back(vch2);
     702         204 :                 }
     703         204 :                 break;
     704             : 
     705             :                 case OP_2SWAP:
     706             :                 {
     707             :                     // (x1 x2 x3 x4 -- x3 x4 x1 x2)
     708          69 :                     if (stack.size() < 4)
     709          35 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     710          34 :                     swap(stacktop(-4), stacktop(-2));
     711          34 :                     swap(stacktop(-3), stacktop(-1));
     712             :                 }
     713          34 :                 break;
     714             : 
     715             :                 case OP_IFDUP:
     716             :                 {
     717             :                     // (x - 0 | x x)
     718          77 :                     if (stack.size() < 1)
     719           9 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     720          68 :                     valtype vch = stacktop(-1);
     721          68 :                     if (CastToBool(vch))
     722          51 :                         stack.push_back(vch);
     723          68 :                 }
     724          68 :                 break;
     725             : 
     726             :                 case OP_DEPTH:
     727             :                 {
     728             :                     // -- stacksize
     729        1209 :                     CScriptNum bn(stack.size());
     730        1209 :                     stack.push_back(bn.getvch());
     731        1209 :                 }
     732        1209 :                 break;
     733             : 
     734             :                 case OP_DROP:
     735             :                 {
     736             :                     // (x -- )
     737       88415 :                     if (stack.size() < 1)
     738          16 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     739       88392 :                     popstack(stack);
     740             :                 }
     741             :                 break;
     742             : 
     743             :                 case OP_DUP:
     744             :                 {
     745             :                     // (x -- x x)
     746      835506 :                     if (stack.size() < 1)
     747       10077 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     748      825419 :                     valtype vch = stacktop(-1);
     749      825538 :                     stack.push_back(vch);
     750      825510 :                 }
     751      825510 :                 break;
     752             : 
     753             :                 case OP_NIP:
     754             :                 {
     755             :                     // (x1 x2 -- x2)
     756          74 :                     if (stack.size() < 2)
     757          30 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     758          44 :                     stack.erase(stack.end() - 2);
     759             :                 }
     760          44 :                 break;
     761             : 
     762             :                 case OP_OVER:
     763             :                 {
     764             :                     // (x1 x2 -- x1 x2 x1)
     765          76 :                     if (stack.size() < 2)
     766          30 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     767          46 :                     valtype vch = stacktop(-2);
     768          46 :                     stack.push_back(vch);
     769          46 :                 }
     770          46 :                 break;
     771             : 
     772             :                 case OP_PICK:
     773             :                 case OP_ROLL:
     774             :                 {
     775             :                     // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
     776             :                     // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
     777         408 :                     if (stack.size() < 2)
     778          38 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     779         370 :                     int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
     780         352 :                     popstack(stack);
     781         352 :                     if (n < 0 || n >= (int)stack.size())
     782          62 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     783         290 :                     valtype vch = stacktop(-n-1);
     784         290 :                     if (opcode == OP_ROLL)
     785         145 :                         stack.erase(stack.end()-n-1);
     786         290 :                     stack.push_back(vch);
     787         308 :                 }
     788             :                 break;
     789             : 
     790             :                 case OP_ROT:
     791             :                 {
     792             :                     // (x1 x2 x3 -- x2 x3 x1)
     793             :                     //  x2 x1 x3  after first swap
     794             :                     //  x2 x3 x1  after second swap
     795         207 :                     if (stack.size() < 3)
     796          31 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     797         176 :                     swap(stacktop(-3), stacktop(-2));
     798         176 :                     swap(stacktop(-2), stacktop(-1));
     799             :                 }
     800         176 :                 break;
     801             : 
     802             :                 case OP_SWAP:
     803             :                 {
     804             :                     // (x1 x2 -- x2 x1)
     805         145 :                     if (stack.size() < 2)
     806          37 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     807         108 :                     swap(stacktop(-2), stacktop(-1));
     808             :                 }
     809         108 :                 break;
     810             : 
     811             :                 case OP_TUCK:
     812             :                 {
     813             :                     // (x1 x2 -- x2 x1 x2)
     814          82 :                     if (stack.size() < 2)
     815          35 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     816          47 :                     valtype vch = stacktop(-1);
     817          47 :                     stack.insert(stack.end()-2, vch);
     818          47 :                 }
     819          47 :                 break;
     820             : 
     821             : 
     822             :                 case OP_SIZE:
     823             :                 {
     824             :                     // (in -- in size)
     825         513 :                     if (stack.size() < 1)
     826          16 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     827         497 :                     CScriptNum bn(stacktop(-1).size());
     828         497 :                     stack.push_back(bn.getvch());
     829         497 :                 }
     830         497 :                 break;
     831             : 
     832             : 
     833             :                 //
     834             :                 // Bitwise logic
     835             :                 //
     836             :                 case OP_EQUAL:
     837             :                 case OP_EQUALVERIFY:
     838             :                 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
     839             :                 {
     840             :                     // (x1 x2 - bool)
     841      939554 :                     if (stack.size() < 2)
     842          52 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     843      939482 :                     valtype& vch1 = stacktop(-2);
     844      939510 :                     valtype& vch2 = stacktop(-1);
     845      939542 :                     bool fEqual = (vch1 == vch2);
     846             :                     // OP_NOTEQUAL is disabled because it would be too easy to say
     847             :                     // something like n != 1 and have some wiseguy pass in 1 with extra
     848             :                     // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
     849             :                     //if (opcode == OP_NOTEQUAL)
     850             :                     //    fEqual = !fEqual;
     851      939555 :                     popstack(stack);
     852      939539 :                     popstack(stack);
     853      939557 :                     stack.push_back(fEqual ? vchTrue : vchFalse);
     854      939527 :                     if (opcode == OP_EQUALVERIFY)
     855             :                     {
     856      825790 :                         if (fEqual)
     857      825634 :                             popstack(stack);
     858             :                         else
     859         157 :                             return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
     860             :                     }
     861      939384 :                 }
     862             :                 break;
     863             : 
     864             : 
     865             :                 //
     866             :                 // Numeric
     867             :                 //
     868             :                 case OP_1ADD:
     869             :                 case OP_1SUB:
     870             :                 case OP_NEGATE:
     871             :                 case OP_ABS:
     872             :                 case OP_NOT:
     873             :                 case OP_0NOTEQUAL:
     874             :                 {
     875             :                     // (in -- out)
     876        1942 :                     if (stack.size() < 1)
     877          37 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     878        1905 :                     CScriptNum bn(stacktop(-1), fRequireMinimal);
     879        1671 :                     switch (opcode)
     880             :                     {
     881         119 :                     case OP_1ADD:       bn += bnOne; break;
     882          54 :                     case OP_1SUB:       bn -= bnOne; break;
     883          70 :                     case OP_NEGATE:     bn = -bn; break;
     884          87 :                     case OP_ABS:        if (bn < bnZero) bn = -bn; break;
     885        1237 :                     case OP_NOT:        bn = (bn == bnZero); break;
     886         104 :                     case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
     887           0 :                     default:            assert(!"invalid opcode"); break;
     888             :                     }
     889        1671 :                     popstack(stack);
     890        1671 :                     stack.push_back(bn.getvch());
     891        1905 :                 }
     892        1671 :                 break;
     893             : 
     894             :                 case OP_ADD:
     895             :                 case OP_SUB:
     896             :                 case OP_BOOLAND:
     897             :                 case OP_BOOLOR:
     898             :                 case OP_NUMEQUAL:
     899             :                 case OP_NUMEQUALVERIFY:
     900             :                 case OP_NUMNOTEQUAL:
     901             :                 case OP_LESSTHAN:
     902             :                 case OP_GREATERTHAN:
     903             :                 case OP_LESSTHANOREQUAL:
     904             :                 case OP_GREATERTHANOREQUAL:
     905             :                 case OP_MIN:
     906             :                 case OP_MAX:
     907             :                 {
     908             :                     // (x1 x2 -- out)
     909        3009 :                     if (stack.size() < 2)
     910         168 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     911        2841 :                     CScriptNum bn1(stacktop(-2), fRequireMinimal);
     912        2652 :                     CScriptNum bn2(stacktop(-1), fRequireMinimal);
     913        2526 :                     CScriptNum bn(0);
     914        2526 :                     switch (opcode)
     915             :                     {
     916             :                     case OP_ADD:
     917         563 :                         bn = bn1 + bn2;
     918         563 :                         break;
     919             : 
     920             :                     case OP_SUB:
     921          97 :                         bn = bn1 - bn2;
     922          97 :                         break;
     923             : 
     924         176 :                     case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
     925         166 :                     case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
     926         557 :                     case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
     927          72 :                     case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
     928          89 :                     case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
     929         140 :                     case OP_LESSTHAN:            bn = (bn1 < bn2); break;
     930         140 :                     case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
     931         140 :                     case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
     932         140 :                     case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
     933         123 :                     case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
     934         123 :                     case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
     935           0 :                     default:                     assert(!"invalid opcode"); break;
     936             :                     }
     937        2526 :                     popstack(stack);
     938        2526 :                     popstack(stack);
     939        2526 :                     stack.push_back(bn.getvch());
     940             : 
     941        2526 :                     if (opcode == OP_NUMEQUALVERIFY)
     942             :                     {
     943          72 :                         if (CastToBool(stacktop(-1)))
     944          72 :                             popstack(stack);
     945             :                         else
     946           0 :                             return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
     947             :                     }
     948        2841 :                 }
     949             :                 break;
     950             : 
     951             :                 case OP_WITHIN:
     952             :                 {
     953             :                     // (x min max -- out)
     954         232 :                     if (stack.size() < 3)
     955          13 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     956         219 :                     CScriptNum bn1(stacktop(-3), fRequireMinimal);
     957         209 :                     CScriptNum bn2(stacktop(-2), fRequireMinimal);
     958         202 :                     CScriptNum bn3(stacktop(-1), fRequireMinimal);
     959         195 :                     bool fValue = (bn2 <= bn1 && bn1 < bn3);
     960         195 :                     popstack(stack);
     961         195 :                     popstack(stack);
     962         195 :                     popstack(stack);
     963         195 :                     stack.push_back(fValue ? vchTrue : vchFalse);
     964         219 :                 }
     965         195 :                 break;
     966             : 
     967             : 
     968             :                 //
     969             :                 // Crypto
     970             :                 //
     971             :                 case OP_RIPEMD160:
     972             :                 case OP_SHA1:
     973             :                 case OP_SHA256:
     974             :                 case OP_HASH160:
     975             :                 case OP_HASH256:
     976             :                 {
     977             :                     // (in -- hash)
     978      936369 :                     if (stack.size() < 1)
     979         278 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     980      936073 :                     valtype& vch = stacktop(-1);
     981      936112 :                     valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
     982      936179 :                     if (opcode == OP_RIPEMD160)
     983          85 :                         CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
     984      936092 :                     else if (opcode == OP_SHA1)
     985         748 :                         CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
     986      935229 :                     else if (opcode == OP_SHA256)
     987         121 :                         CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
     988      935096 :                     else if (opcode == OP_HASH160)
     989      935015 :                         CHash160().Write(vch).Finalize(vchHash);
     990          85 :                     else if (opcode == OP_HASH256)
     991          85 :                         CHash256().Write(vch).Finalize(vchHash);
     992      936157 :                     popstack(stack);
     993      936159 :                     stack.push_back(vchHash);
     994      936159 :                 }
     995      936159 :                 break;
     996             : 
     997             :                 case OP_CODESEPARATOR:
     998             :                 {
     999             :                     // If SCRIPT_VERIFY_CONST_SCRIPTCODE flag is set, use of OP_CODESEPARATOR is rejected in pre-segwit
    1000             :                     // script, even in an unexecuted branch (this is checked above the opcode case statement).
    1001             : 
    1002             :                     // Hash starts after the code separator
    1003          32 :                     pbegincodehash = pc;
    1004             :                 }
    1005          32 :                 break;
    1006             : 
    1007             :                 case OP_CHECKSIG:
    1008             :                 case OP_CHECKSIGVERIFY:
    1009             :                 {
    1010             :                     // (sig pubkey -- bool)
    1011     1002056 :                     if (stack.size() < 2)
    1012       32807 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1013             : 
    1014      969193 :                     valtype& vchSig    = stacktop(-2);
    1015      969251 :                     valtype& vchPubKey = stacktop(-1);
    1016             : 
    1017      969418 :                     bool fSuccess = true;
    1018      969418 :                     if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, flags, checker, sigversion, serror, fSuccess)) return false;
    1019      952197 :                     popstack(stack);
    1020      952257 :                     popstack(stack);
    1021      952276 :                     stack.push_back(fSuccess ? vchTrue : vchFalse);
    1022      952154 :                     if (opcode == OP_CHECKSIGVERIFY)
    1023             :                     {
    1024       33329 :                         if (fSuccess)
    1025       33246 :                             popstack(stack);
    1026             :                         else
    1027           7 :                             return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
    1028             :                     }
    1029      969189 :                 }
    1030             :                 break;
    1031             : 
    1032             :                 case OP_CHECKMULTISIG:
    1033             :                 case OP_CHECKMULTISIGVERIFY:
    1034             :                 {
    1035             :                     // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
    1036             : 
    1037             :                     int i = 1;
    1038       17017 :                     if ((int)stack.size() < i)
    1039           8 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1040             : 
    1041       17009 :                     int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
    1042       16994 :                     if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
    1043          23 :                         return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
    1044       16971 :                     nOpCount += nKeysCount;
    1045       16971 :                     if (nOpCount > MAX_OPS_PER_SCRIPT)
    1046          25 :                         return set_error(serror, SCRIPT_ERR_OP_COUNT);
    1047             :                     int ikey = ++i;
    1048             :                     // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
    1049             :                     // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
    1050       16946 :                     int ikey2 = nKeysCount + 2;
    1051             :                     i += nKeysCount;
    1052       16946 :                     if ((int)stack.size() < i)
    1053           9 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1054             : 
    1055       16937 :                     int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
    1056       16915 :                     if (nSigsCount < 0 || nSigsCount > nKeysCount)
    1057          23 :                         return set_error(serror, SCRIPT_ERR_SIG_COUNT);
    1058       16892 :                     int isig = ++i;
    1059       16892 :                     i += nSigsCount;
    1060       16892 :                     if ((int)stack.size() < i)
    1061          38 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1062             : 
    1063             :                     // Subset of script starting at the most recent codeseparator
    1064       16854 :                     CScript scriptCode(pbegincodehash, pend);
    1065             : 
    1066             :                     // Drop the signature in pre-segwit scripts but not segwit scripts
    1067       30632 :                     for (int k = 0; k < nSigsCount; k++)
    1068             :                     {
    1069       13781 :                         valtype& vchSig = stacktop(-isig-k);
    1070       13781 :                         if (sigversion == SigVersion::BASE) {
    1071        7866 :                             int found = FindAndDelete(scriptCode, CScript() << vchSig);
    1072        7866 :                             if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
    1073       58626 :                                 return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
    1074        7864 :                         }
    1075       13779 :                     }
    1076             : 
    1077             :                     bool fSuccess = true;
    1078       27989 :                     while (fSuccess && nSigsCount > 0)
    1079             :                     {
    1080       11521 :                         valtype& vchSig    = stacktop(-isig);
    1081       11521 :                         valtype& vchPubKey = stacktop(-ikey);
    1082             : 
    1083             :                         // Note how this makes the exact order of pubkey/signature evaluation
    1084             :                         // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
    1085             :                         // See the script_(in)valid tests for details.
    1086       11521 :                         if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
    1087             :                             // serror is set
    1088         383 :                             return false;
    1089             :                         }
    1090             : 
    1091             :                         // Check signature
    1092       11138 :                         bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
    1093             : 
    1094       11138 :                         if (fOk) {
    1095        9906 :                             isig++;
    1096        9906 :                             nSigsCount--;
    1097        9906 :                         }
    1098       11138 :                         ikey++;
    1099       11138 :                         nKeysCount--;
    1100             : 
    1101             :                         // If there are more signatures left than keys left,
    1102             :                         // then too many signatures have failed. Exit early,
    1103             :                         // without checking any further signatures.
    1104       11138 :                         if (nSigsCount > nKeysCount)
    1105         620 :                             fSuccess = false;
    1106       11138 :                     }
    1107             : 
    1108             :                     // Clean up stack of actual arguments
    1109       93890 :                     while (i-- > 1) {
    1110             :                         // If the operation failed, we require that all signatures must be empty vector
    1111       77600 :                         if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
    1112         179 :                             return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
    1113       77421 :                         if (ikey2 > 0)
    1114       64671 :                             ikey2--;
    1115       77421 :                         popstack(stack);
    1116             :                     }
    1117             : 
    1118             :                     // A bug causes CHECKMULTISIG to consume one extra argument
    1119             :                     // whose contents were not checked in any way.
    1120             :                     //
    1121             :                     // Unfortunately this is a potential source of mutability,
    1122             :                     // so optionally verify it is exactly equal to zero prior
    1123             :                     // to removing it from the stack.
    1124       16290 :                     if (stack.size() < 1)
    1125           0 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1126       16290 :                     if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
    1127          60 :                         return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
    1128       16230 :                     popstack(stack);
    1129             : 
    1130       16230 :                     stack.push_back(fSuccess ? vchTrue : vchFalse);
    1131             : 
    1132       16230 :                     if (opcode == OP_CHECKMULTISIGVERIFY)
    1133             :                     {
    1134        4158 :                         if (fSuccess)
    1135        4152 :                             popstack(stack);
    1136             :                         else
    1137           6 :                             return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
    1138             :                     }
    1139       33115 :                 }
    1140             :                 break;
    1141             : 
    1142             :                 default:
    1143        1124 :                     return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
    1144             :             }
    1145             : 
    1146             :             // Size limits
    1147     7726944 :             if (stack.size() + altstack.size() > MAX_STACK_SIZE)
    1148          15 :                 return set_error(serror, SCRIPT_ERR_STACK_SIZE);
    1149     7723549 :         }
    1150         640 :     }
    1151             :     catch (...)
    1152             :     {
    1153         640 :         return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
    1154         640 :     }
    1155             : 
    1156     2838466 :     if (!vfExec.empty())
    1157          45 :         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
    1158             : 
    1159     2838405 :     return set_success(serror);
    1160     2920730 : }
    1161             : 
    1162             : namespace {
    1163             : 
    1164             : /**
    1165             :  * Wrapper that serializes like CTransaction, but with the modifications
    1166             :  *  required for the signature hash done in-place
    1167             :  */
    1168             : template <class T>
    1169             : class CTransactionSignatureSerializer
    1170             : {
    1171             : private:
    1172             :     const T& txTo;             //!< reference to the spending transaction (the one being serialized)
    1173             :     const CScript& scriptCode; //!< output script being consumed
    1174             :     const unsigned int nIn;    //!< input index of txTo being signed
    1175             :     const bool fAnyoneCanPay;  //!< whether the hashtype has the SIGHASH_ANYONECANPAY flag set
    1176             :     const bool fHashSingle;    //!< whether the hashtype is SIGHASH_SINGLE
    1177             :     const bool fHashNone;      //!< whether the hashtype is SIGHASH_NONE
    1178             : 
    1179             : public:
    1180      380294 :     CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
    1181      190152 :         txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
    1182      190152 :         fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
    1183      190152 :         fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
    1184      380294 :         fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
    1185             : 
    1186             :     /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
    1187             :     template<typename S>
    1188      190192 :     void SerializeScriptCode(S &s) const {
    1189      190192 :         CScript::const_iterator it = scriptCode.begin();
    1190      190192 :         CScript::const_iterator itBegin = it;
    1191      190192 :         opcodetype opcode;
    1192             :         unsigned int nCodeSeparators = 0;
    1193     1246376 :         while (scriptCode.GetOp(it, opcode)) {
    1194     1056151 :             if (opcode == OP_CODESEPARATOR)
    1195       25268 :                 nCodeSeparators++;
    1196             :         }
    1197      190413 :         ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
    1198      190413 :         it = itBegin;
    1199     1246701 :         while (scriptCode.GetOp(it, opcode)) {
    1200     1056263 :             if (opcode == OP_CODESEPARATOR) {
    1201       25268 :                 s.write((char*)&itBegin[0], it-itBegin-1);
    1202       25268 :                 itBegin = it;
    1203       25268 :             }
    1204             :         }
    1205      190408 :         if (itBegin != scriptCode.end())
    1206      180353 :             s.write((char*)&itBegin[0], it-itBegin);
    1207      190400 :     }
    1208             : 
    1209             :     /** Serialize an input of txTo */
    1210             :     template<typename S>
    1211      753531 :     void SerializeInput(S &s, unsigned int nInput) const {
    1212             :         // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
    1213      753531 :         if (fAnyoneCanPay)
    1214       25429 :             nInput = nIn;
    1215             :         // Serialize the prevout
    1216      753548 :         ::Serialize(s, txTo.vin[nInput].prevout);
    1217             :         // Serialize the script
    1218      753548 :         if (nInput != nIn)
    1219             :             // Blank out other inputs' signatures
    1220      563311 :             ::Serialize(s, CScript());
    1221             :         else
    1222      190388 :             SerializeScriptCode(s);
    1223             :         // Serialize the nSequence
    1224      753717 :         if (nInput != nIn && (fHashSingle || fHashNone))
    1225             :             // let the others update at will
    1226        2262 :             ::Serialize(s, (int)0);
    1227             :         else
    1228      751456 :             ::Serialize(s, txTo.vin[nInput].nSequence);
    1229      753817 :     }
    1230             : 
    1231             :     /** Serialize an output of txTo */
    1232             :     template<typename S>
    1233      361449 :     void SerializeOutput(S &s, unsigned int nOutput) const {
    1234      361449 :         if (fHashSingle && nOutput != nIn)
    1235             :             // Do not lock-in the txout payee at other indices as txin
    1236        1137 :             ::Serialize(s, CTxOut());
    1237             :         else
    1238      360336 :             ::Serialize(s, txTo.vout[nOutput]);
    1239      361497 :     }
    1240             : 
    1241             :     /** Serialize txTo */
    1242             :     template<typename S>
    1243      190163 :     void Serialize(S &s) const {
    1244             :         // Serialize nVersion
    1245      190163 :         ::Serialize(s, txTo.nVersion);
    1246             :         // Serialize vin
    1247      190163 :         unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
    1248      190105 :         ::WriteCompactSize(s, nInputs);
    1249      943662 :         for (unsigned int nInput = 0; nInput < nInputs; nInput++)
    1250      753557 :              SerializeInput(s, nInput);
    1251             :         // Serialize vout
    1252      190395 :         unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
    1253      190233 :         ::WriteCompactSize(s, nOutputs);
    1254      551680 :         for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
    1255      361447 :              SerializeOutput(s, nOutput);
    1256             :         // Serialize nLockTime
    1257      190408 :         ::Serialize(s, txTo.nLockTime);
    1258      190408 :     }
    1259             : };
    1260             : 
    1261             : /** Compute the (single) SHA256 of the concatenation of all prevouts of a tx. */
    1262             : template <class T>
    1263       48966 : uint256 GetPrevoutsSHA256(const T& txTo)
    1264             : {
    1265       48966 :     CHashWriter ss(SER_GETHASH, 0);
    1266    21866368 :     for (const auto& txin : txTo.vin) {
    1267    21817402 :         ss << txin.prevout;
    1268             :     }
    1269       48966 :     return ss.GetSHA256();
    1270       48966 : }
    1271             : 
    1272             : /** Compute the (single) SHA256 of the concatenation of all nSequences of a tx. */
    1273             : template <class T>
    1274       45441 : uint256 GetSequencesSHA256(const T& txTo)
    1275             : {
    1276       45441 :     CHashWriter ss(SER_GETHASH, 0);
    1277     8362318 :     for (const auto& txin : txTo.vin) {
    1278     8316877 :         ss << txin.nSequence;
    1279             :     }
    1280       45441 :     return ss.GetSHA256();
    1281       45441 : }
    1282             : 
    1283             : /** Compute the (single) SHA256 of the concatenation of all txouts of a tx. */
    1284             : template <class T>
    1285       46944 : uint256 GetOutputsSHA256(const T& txTo)
    1286             : {
    1287       46944 :     CHashWriter ss(SER_GETHASH, 0);
    1288    14582305 :     for (const auto& txout : txTo.vout) {
    1289    14535361 :         ss << txout;
    1290             :     }
    1291       46944 :     return ss.GetSHA256();
    1292       46944 : }
    1293             : 
    1294             : } // namespace
    1295             : 
    1296             : template <class T>
    1297       52250 : void PrecomputedTransactionData::Init(const T& txTo)
    1298             : {
    1299       52250 :     assert(!m_ready);
    1300             : 
    1301             :     // Cache is calculated only for transactions with witness
    1302       52250 :     if (txTo.HasWitness()) {
    1303        6607 :         hashPrevouts = SHA256Uint256(GetPrevoutsSHA256(txTo));
    1304        6607 :         hashSequence = SHA256Uint256(GetSequencesSHA256(txTo));
    1305        6607 :         hashOutputs = SHA256Uint256(GetOutputsSHA256(txTo));
    1306        6607 :     }
    1307             : 
    1308       52250 :     m_ready = true;
    1309       52250 : }
    1310             : 
    1311             : template <class T>
    1312        1606 : PrecomputedTransactionData::PrecomputedTransactionData(const T& txTo)
    1313         803 : {
    1314         803 :     Init(txTo);
    1315        1606 : }
    1316             : 
    1317             : // explicit instantiation
    1318             : template void PrecomputedTransactionData::Init(const CTransaction& txTo);
    1319             : template void PrecomputedTransactionData::Init(const CMutableTransaction& txTo);
    1320             : template PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo);
    1321             : template PrecomputedTransactionData::PrecomputedTransactionData(const CMutableTransaction& txTo);
    1322             : 
    1323             : template <class T>
    1324      307228 : uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
    1325             : {
    1326      307228 :     assert(nIn < txTo.vin.size());
    1327             : 
    1328      306770 :     if (sigversion == SigVersion::WITNESS_V0) {
    1329      116611 :         uint256 hashPrevouts;
    1330      116611 :         uint256 hashSequence;
    1331      116611 :         uint256 hashOutputs;
    1332      116611 :         const bool cacheready = cache && cache->m_ready;
    1333             : 
    1334      116877 :         if (!(nHashType & SIGHASH_ANYONECANPAY)) {
    1335      103645 :             hashPrevouts = cacheready ? cache->hashPrevouts : SHA256Uint256(GetPrevoutsSHA256(txTo));
    1336      103642 :         }
    1337             : 
    1338      116885 :         if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
    1339       95380 :             hashSequence = cacheready ? cache->hashSequence : SHA256Uint256(GetSequencesSHA256(txTo));
    1340       95381 :         }
    1341             : 
    1342             : 
    1343      116863 :         if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
    1344      101336 :             hashOutputs = cacheready ? cache->hashOutputs : SHA256Uint256(GetOutputsSHA256(txTo));
    1345      116862 :         } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
    1346        6567 :             CHashWriter ss(SER_GETHASH, 0);
    1347        6567 :             ss << txTo.vout[nIn];
    1348        6567 :             hashOutputs = ss.GetHash();
    1349        6567 :         }
    1350             : 
    1351      116869 :         CHashWriter ss(SER_GETHASH, 0);
    1352             :         // Version
    1353      116869 :         ss << txTo.nVersion;
    1354             :         // Input prevouts/nSequence (none/all, depending on flags)
    1355      116869 :         ss << hashPrevouts;
    1356      116869 :         ss << hashSequence;
    1357             :         // The input being signed (replacing the scriptSig with scriptCode + amount)
    1358             :         // The prevout may already be contained in hashPrevout, and the nSequence
    1359             :         // may already be contain in hashSequence.
    1360      116869 :         ss << txTo.vin[nIn].prevout;
    1361      116869 :         ss << scriptCode;
    1362      116869 :         ss << amount;
    1363      116869 :         ss << txTo.vin[nIn].nSequence;
    1364             :         // Outputs (none/one/all, depending on flags)
    1365      116869 :         ss << hashOutputs;
    1366             :         // Locktime
    1367      116869 :         ss << txTo.nLockTime;
    1368             :         // Sighash type
    1369      116869 :         ss << nHashType;
    1370             : 
    1371      116869 :         return ss.GetHash();
    1372      116869 :     }
    1373             : 
    1374             :     // Check for invalid use of SIGHASH_SINGLE
    1375      190218 :     if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
    1376        1538 :         if (nIn >= txTo.vout.size()) {
    1377             :             //  nOut out of range
    1378           5 :             return UINT256_ONE();
    1379             :         }
    1380             :     }
    1381             : 
    1382             :     // Wrapper to serialize only the necessary parts of the transaction being signed
    1383      190220 :     CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
    1384             : 
    1385             :     // Serialize and hash
    1386      190220 :     CHashWriter ss(SER_GETHASH, 0);
    1387      190220 :     ss << txTmp << nHashType;
    1388      190220 :     return ss.GetHash();
    1389      307103 : }
    1390             : 
    1391             : template <class T>
    1392      118404 : bool GenericTransactionSignatureChecker<T>::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
    1393             : {
    1394      118404 :     return pubkey.Verify(sighash, vchSig);
    1395             : }
    1396             : 
    1397             : template <class T>
    1398      235156 : bool GenericTransactionSignatureChecker<T>::CheckSig(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
    1399             : {
    1400      235156 :     CPubKey pubkey(vchPubKey);
    1401      235156 :     if (!pubkey.IsValid())
    1402         264 :         return false;
    1403             : 
    1404             :     // Hash type is one byte tacked on to the end of the signature
    1405      234622 :     std::vector<unsigned char> vchSig(vchSigIn);
    1406      234622 :     if (vchSig.empty())
    1407         952 :         return false;
    1408      233927 :     int nHashType = vchSig.back();
    1409      233927 :     vchSig.pop_back();
    1410             : 
    1411      233927 :     uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
    1412             : 
    1413      234048 :     if (!VerifySignature(vchSig, pubkey, sighash))
    1414        1166 :         return false;
    1415             : 
    1416      232996 :     return true;
    1417      235378 : }
    1418             : 
    1419             : template <class T>
    1420        8224 : bool GenericTransactionSignatureChecker<T>::CheckLockTime(const CScriptNum& nLockTime) const
    1421             : {
    1422             :     // There are two kinds of nLockTime: lock-by-blockheight
    1423             :     // and lock-by-blocktime, distinguished by whether
    1424             :     // nLockTime < LOCKTIME_THRESHOLD.
    1425             :     //
    1426             :     // We want to compare apples to apples, so fail the script
    1427             :     // unless the type of nLockTime being tested is the same as
    1428             :     // the nLockTime in the transaction.
    1429        8224 :     if (!(
    1430        8236 :         (txTo->nLockTime <  LOCKTIME_THRESHOLD && nLockTime <  LOCKTIME_THRESHOLD) ||
    1431          14 :         (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
    1432             :     ))
    1433           5 :         return false;
    1434             : 
    1435             :     // Now that we know we're comparing apples-to-apples, the
    1436             :     // comparison is a simple numeric one.
    1437        8219 :     if (nLockTime > (int64_t)txTo->nLockTime)
    1438        8202 :         return false;
    1439             : 
    1440             :     // Finally the nLockTime feature can be disabled and thus
    1441             :     // CHECKLOCKTIMEVERIFY bypassed if every txin has been
    1442             :     // finalized by setting nSequence to maxint. The
    1443             :     // transaction would be allowed into the blockchain, making
    1444             :     // the opcode ineffective.
    1445             :     //
    1446             :     // Testing if this vin is not final is sufficient to
    1447             :     // prevent this condition. Alternatively we could test all
    1448             :     // inputs, but testing just this input minimizes the data
    1449             :     // required to prove correct CHECKLOCKTIMEVERIFY execution.
    1450          17 :     if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
    1451           3 :         return false;
    1452             : 
    1453          14 :     return true;
    1454        8224 : }
    1455             : 
    1456             : template <class T>
    1457        8341 : bool GenericTransactionSignatureChecker<T>::CheckSequence(const CScriptNum& nSequence) const
    1458             : {
    1459             :     // Relative lock times are supported by comparing the passed
    1460             :     // in operand to the sequence number of the input.
    1461        8341 :     const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
    1462             : 
    1463             :     // Fail if the transaction's version number is not set high
    1464             :     // enough to trigger BIP 68 rules.
    1465        8341 :     if (static_cast<uint32_t>(txTo->nVersion) < 2)
    1466          76 :         return false;
    1467             : 
    1468             :     // Sequence numbers with their most significant bit set are not
    1469             :     // consensus constrained. Testing that the transaction's sequence
    1470             :     // number do not have this bit set prevents using this property
    1471             :     // to get around a CHECKSEQUENCEVERIFY check.
    1472        8265 :     if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
    1473          16 :         return false;
    1474             : 
    1475             :     // Mask off any bits that do not have consensus-enforced meaning
    1476             :     // before doing the integer comparisons
    1477             :     const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
    1478        8249 :     const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
    1479        8249 :     const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
    1480             : 
    1481             :     // There are two kinds of nSequence: lock-by-blockheight
    1482             :     // and lock-by-blocktime, distinguished by whether
    1483             :     // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
    1484             :     //
    1485             :     // We want to compare apples to apples, so fail the script
    1486             :     // unless the type of nSequenceMasked being tested is the same as
    1487             :     // the nSequenceMasked in the transaction.
    1488        8249 :     if (!(
    1489        8267 :         (txToSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
    1490          28 :         (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
    1491             :     )) {
    1492          20 :         return false;
    1493             :     }
    1494             : 
    1495             :     // Now that we know we're comparing apples-to-apples, the
    1496             :     // comparison is a simple numeric one.
    1497        8229 :     if (nSequenceMasked > txToSequenceMasked)
    1498        8206 :         return false;
    1499             : 
    1500          23 :     return true;
    1501        8341 : }
    1502             : 
    1503             : // explicit instantiation
    1504           0 : template class GenericTransactionSignatureChecker<CTransaction>;
    1505           0 : template class GenericTransactionSignatureChecker<CMutableTransaction>;
    1506             : 
    1507      363065 : static bool ExecuteWitnessScript(const Span<const valtype>& stack_span, const CScript& scriptPubKey, unsigned int flags, SigVersion sigversion, const BaseSignatureChecker& checker, ScriptError* serror)
    1508             : {
    1509      363065 :     std::vector<valtype> stack{stack_span.begin(), stack_span.end()};
    1510             : 
    1511             :     // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
    1512     1137585 :     for (const valtype& elem : stack) {
    1513      774554 :         if (elem.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
    1514      774482 :     }
    1515             : 
    1516             :     // Run the script interpreter.
    1517      363193 :     if (!EvalScript(stack, scriptPubKey, flags, checker, sigversion, serror)) return false;
    1518             : 
    1519             :     // Scripts inside witness implicitly require cleanstack behaviour
    1520      362128 :     if (stack.size() != 1) return set_error(serror, SCRIPT_ERR_CLEANSTACK);
    1521      361909 :     if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    1522      361795 :     return true;
    1523      363173 : }
    1524             : 
    1525      391644 : static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
    1526             : {
    1527      391644 :     CScript scriptPubKey;
    1528      391644 :     Span<const valtype> stack{witness.stack};
    1529             : 
    1530      391644 :     if (witversion == 0) {
    1531      391401 :         if (program.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
    1532             :             // Version 0 segregated witness program: SHA256(CScript) inside the program, CScript + inputs in witness
    1533       18109 :             if (stack.size() == 0) {
    1534         122 :                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
    1535             :             }
    1536       17961 :             const valtype& script_bytes = SpanPopBack(stack);
    1537       17961 :             scriptPubKey = CScript(script_bytes.begin(), script_bytes.end());
    1538       18171 :             uint256 hashScriptPubKey;
    1539       18055 :             CSHA256().Write(&scriptPubKey[0], scriptPubKey.size()).Finalize(hashScriptPubKey.begin());
    1540       18206 :             if (memcmp(hashScriptPubKey.begin(), program.data(), 32)) {
    1541          54 :                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
    1542             :             }
    1543       18087 :             return ExecuteWitnessScript(stack, scriptPubKey, flags, SigVersion::WITNESS_V0, checker, serror);
    1544      391503 :         } else if (program.size() == WITNESS_V0_KEYHASH_SIZE) {
    1545             :             // Special case for pay-to-pubkeyhash; signature + pubkey in witness
    1546      373292 :             if (stack.size() != 2) {
    1547       28283 :                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
    1548             :             }
    1549      345020 :             scriptPubKey << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
    1550      345089 :             return ExecuteWitnessScript(stack, scriptPubKey, flags, SigVersion::WITNESS_V0, checker, serror);
    1551             :         } else {
    1552          38 :             return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
    1553             :         }
    1554             :     } else {
    1555          90 :         if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
    1556          37 :             return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
    1557             :         }
    1558             :         // Higher version witness scripts return true for future softfork compatibility
    1559          53 :         return true;
    1560             :     }
    1561             :     // There is intentionally no return statement here, to be able to use "control reaches end of non-void function" warnings to detect gaps in the logic above.
    1562      391759 : }
    1563             : 
    1564     1215933 : bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
    1565             : {
    1566     1215933 :     static const CScriptWitness emptyWitness;
    1567     1215952 :     if (witness == nullptr) {
    1568             :         witness = &emptyWitness;
    1569       67568 :     }
    1570             :     bool hadWitness = false;
    1571             : 
    1572     1215960 :     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
    1573             : 
    1574     1215960 :     if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
    1575         599 :         return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
    1576             :     }
    1577             : 
    1578             :     // scriptSig and scriptPubKey must be evaluated sequentially on the same stack
    1579             :     // rather than being simply concatenated (see CVE-2010-5141)
    1580     1215393 :     std::vector<std::vector<unsigned char> > stack, stackCopy;
    1581     1215393 :     if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
    1582             :         // serror is set
    1583         617 :         return false;
    1584     1214887 :     if (flags & SCRIPT_VERIFY_P2SH)
    1585     1120950 :         stackCopy = stack;
    1586     1214952 :     if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
    1587             :         // serror is set
    1588       47187 :         return false;
    1589     1167615 :     if (stack.empty())
    1590         184 :         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    1591     1167355 :     if (CastToBool(stack.back()) == false)
    1592         658 :         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    1593             : 
    1594             :     // Bare witness programs
    1595     1166754 :     int witnessversion;
    1596     1166754 :     std::vector<unsigned char> witnessprogram;
    1597     1166754 :     if (flags & SCRIPT_VERIFY_WITNESS) {
    1598      990900 :         if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
    1599     1103326 :             hadWitness = true;
    1600      387521 :             if (scriptSig.size() != 0) {
    1601             :                 // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
    1602          40 :                 return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
    1603             :             }
    1604      387394 :             if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
    1605       29247 :                 return false;
    1606             :             }
    1607             :             // Bypass the cleanstack check at the end. The actual stack is obviously not clean
    1608             :             // for witness programs.
    1609      358150 :             stack.resize(1);
    1610             :         }
    1611             :     }
    1612             : 
    1613             :     // Additional validation for spend-to-script-hash transactions:
    1614     1137480 :     if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
    1615             :     {
    1616             :         // scriptSig must be literals-only or validation fails
    1617      105364 :         if (!scriptSig.IsPushOnly())
    1618          22 :             return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
    1619             : 
    1620             :         // Restore stack.
    1621      105339 :         swap(stack, stackCopy);
    1622             : 
    1623             :         // stack cannot be empty here, because if it was the
    1624             :         // P2SH  HASH <> EQUAL  scriptPubKey would be evaluated with
    1625             :         // an empty stack and the EvalScript above would return false.
    1626      105339 :         assert(!stack.empty());
    1627             : 
    1628      105339 :         const valtype& pubKeySerialized = stack.back();
    1629      105339 :         CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
    1630      105341 :         popstack(stack);
    1631             : 
    1632      105340 :         if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
    1633             :             // serror is set
    1634       32937 :             return false;
    1635       72399 :         if (stack.empty())
    1636          85 :             return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    1637       72313 :         if (!CastToBool(stack.back()))
    1638          27 :             return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    1639             : 
    1640             :         // P2SH witness program
    1641       72290 :         if (flags & SCRIPT_VERIFY_WITNESS) {
    1642       69911 :             if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
    1643             :                 hadWitness = true;
    1644        4330 :                 if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
    1645             :                     // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
    1646             :                     // reintroduce malleability.
    1647          36 :                     return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
    1648             :                 }
    1649        4294 :                 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
    1650         664 :                     return false;
    1651             :                 }
    1652             :                 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
    1653             :                 // for witness programs.
    1654        3630 :                 stack.resize(1);
    1655             :             }
    1656             :         }
    1657      105339 :     }
    1658             : 
    1659             :     // The CLEANSTACK check is only performed after potential P2SH evaluation,
    1660             :     // as the non-P2SH evaluation of a P2SH script will obviously not result in
    1661             :     // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
    1662     1103326 :     if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
    1663             :         // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
    1664             :         // would be possible, which is not a softfork (and P2SH should be one).
    1665      834168 :         assert((flags & SCRIPT_VERIFY_P2SH) != 0);
    1666      834168 :         assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
    1667      834168 :         if (stack.size() != 1) {
    1668          68 :             return set_error(serror, SCRIPT_ERR_CLEANSTACK);
    1669             :         }
    1670             :     }
    1671             : 
    1672     1103233 :     if (flags & SCRIPT_VERIFY_WITNESS) {
    1673             :         // We can't check for correct unexpected witness data if P2SH was off, so require
    1674             :         // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
    1675             :         // possible, which is not a softfork.
    1676      945841 :         assert((flags & SCRIPT_VERIFY_P2SH) != 0);
    1677      945852 :         if (!hadWitness && !witness->IsNull()) {
    1678          42 :             return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
    1679             :         }
    1680             :     }
    1681             : 
    1682     1103208 :     return set_success(serror);
    1683     1215664 : }
    1684             : 
    1685       44009 : size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness)
    1686             : {
    1687       44009 :     if (witversion == 0) {
    1688       43937 :         if (witprogram.size() == WITNESS_V0_KEYHASH_SIZE)
    1689       28137 :             return 1;
    1690             : 
    1691       15800 :         if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.stack.size() > 0) {
    1692       15792 :             CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
    1693       15792 :             return subscript.GetSigOpCount(true);
    1694       15792 :         }
    1695             :     }
    1696             : 
    1697             :     // Future flags may be implemented here.
    1698          80 :     return 0;
    1699       44009 : }
    1700             : 
    1701      137235 : size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags)
    1702             : {
    1703      137235 :     static const CScriptWitness witnessEmpty;
    1704             : 
    1705      137235 :     if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
    1706        3656 :         return 0;
    1707             :     }
    1708      133579 :     assert((flags & SCRIPT_VERIFY_P2SH) != 0);
    1709             : 
    1710      133579 :     int witnessversion;
    1711      133579 :     std::vector<unsigned char> witnessprogram;
    1712      133579 :     if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
    1713       43380 :         return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
    1714             :     }
    1715             : 
    1716       90199 :     if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
    1717       57636 :         CScript::const_iterator pc = scriptSig.begin();
    1718       57636 :         std::vector<unsigned char> data;
    1719      172707 :         while (pc < scriptSig.end()) {
    1720      115071 :             opcodetype opcode;
    1721      115071 :             scriptSig.GetOp(pc, opcode, data);
    1722      115071 :         }
    1723       57636 :         CScript subscript(data.begin(), data.end());
    1724       57636 :         if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
    1725         629 :             return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
    1726             :         }
    1727       57636 :     }
    1728             : 
    1729       89570 :     return 0;
    1730      137235 : }

Generated by: LCOV version 1.15