LCOV - code coverage report
Current view: top level - src/script - interpreter.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 798 810 98.5 %
Date: 2026-06-25 07:23:43 Functions: 49 55 89.1 %

          Line data    Source code
       1             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2             : // Copyright (c) 2009-2021 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     4027970 : inline bool set_success(ScriptError* ret)
      20             : {
      21     4027970 :     if (ret)
      22     1676105 :         *ret = SCRIPT_ERR_OK;
      23     4027970 :     return true;
      24             : }
      25             : 
      26     4598463 : inline bool set_error(ScriptError* ret, const ScriptError serror)
      27             : {
      28     4598463 :     if (ret)
      29     1974851 :         *ret = serror;
      30     4598463 :     return false;
      31             : }
      32             : 
      33             : } // namespace
      34             : 
      35     1304212 : bool CastToBool(const valtype& vch)
      36             : {
      37     1305374 :     for (unsigned int i = 0; i < vch.size(); i++)
      38             :     {
      39     1302035 :         if (vch[i] != 0)
      40             :         {
      41             :             // Can be negative zero
      42     1300873 :             if (i == vch.size()-1 && vch[i] == 0x80)
      43          17 :                 return false;
      44     1300856 :             return true;
      45             :         }
      46        1162 :     }
      47        3339 :     return false;
      48     1304212 : }
      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     6611094 : static inline void popstack(std::vector<valtype>& stack)
      57             : {
      58     6611094 :     if (stack.empty())
      59           0 :         throw std::runtime_error("popstack(): stack empty");
      60     6611094 :     stack.pop_back();
      61     6611094 : }
      62             : 
      63      877906 : bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
      64      877906 :     if (vchPubKey.size() < CPubKey::COMPRESSED_SIZE) {
      65             :         //  Non-canonical public key: too short
      66          60 :         return false;
      67             :     }
      68      877846 :     if (vchPubKey[0] == 0x04) {
      69        8873 :         if (vchPubKey.size() != CPubKey::SIZE) {
      70             :             //  Non-canonical public key: invalid length for uncompressed key
      71           0 :             return false;
      72             :         }
      73      877846 :     } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
      74      864654 :         if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
      75             :             //  Non-canonical public key: invalid length for compressed key
      76           0 :             return false;
      77             :         }
      78      864654 :     } else {
      79             :         //  Non-canonical public key: neither compressed nor uncompressed
      80        4319 :         return false;
      81             :     }
      82      873527 :     return true;
      83      877906 : }
      84             : 
      85             : [[maybe_unused]] bool static IsCompressedPubKey(const valtype &vchPubKey) {
      86             :     if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
      87             :         //  Non-canonical public key: invalid length for compressed key
      88             :         return false;
      89             :     }
      90             :     if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
      91             :         //  Non-canonical public key: invalid prefix for compressed key
      92             :         return false;
      93             :     }
      94             :     return true;
      95             : }
      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     1971859 : 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     1971859 :     if (sig.size() < 9) return false;
     122     1971753 :     if (sig.size() > 73) return false;
     123             : 
     124             :     // A signature is of type 0x30 (compound).
     125     1971720 :     if (sig[0] != 0x30) return false;
     126             : 
     127             :     // Make sure the length covers the entire signature.
     128     1964470 :     if (sig[1] != sig.size() - 3) return false;
     129             : 
     130             :     // Extract the length of the R element.
     131     1948377 :     unsigned int lenR = sig[3];
     132             : 
     133             :     // Make sure the length of the S element is still inside the signature.
     134     1948377 :     if (5 + lenR >= sig.size()) return false;
     135             : 
     136             :     // Extract the length of the S element.
     137     1948363 :     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     1948363 :     if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
     142             : 
     143             :     // Check whether the R element is an integer.
     144     1948352 :     if (sig[2] != 0x02) return false;
     145             : 
     146             :     // Zero-length integers are not allowed for R.
     147     1948339 :     if (lenR == 0) return false;
     148             : 
     149             :     // Negative numbers are not allowed for R.
     150     1948324 :     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     1948005 :     if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
     155             : 
     156             :     // Check whether the S element is an integer.
     157     1947906 :     if (sig[lenR + 4] != 0x02) return false;
     158             : 
     159             :     // Zero-length integers are not allowed for S.
     160     1947891 :     if (lenS == 0) return false;
     161             : 
     162             :     // Negative numbers are not allowed for S.
     163     1947880 :     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     1947819 :     if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
     168             : 
     169     1947789 :     return true;
     170     1971859 : }
     171             : 
     172      870362 : bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
     173      870362 :     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      870362 :     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      870362 :     if (!CPubKey::CheckLowS(vchSigCopy)) {
     184        4121 :         return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
     185             :     }
     186      866241 :     return true;
     187      870362 : }
     188             : 
     189      876738 : bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
     190      876738 :     if (vchSig.size() == 0) {
     191           0 :         return false;
     192             :     }
     193      876738 :     unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
     194      876738 :     if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
     195          56 :         return false;
     196             : 
     197      876682 :     return true;
     198      876738 : }
     199             : 
     200     1146348 : 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     1146348 :     if (vchSig.size() == 0) {
     204       17267 :         return true;
     205             :     }
     206     1129081 :     if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
     207       24070 :         return set_error(serror, SCRIPT_ERR_SIG_DER);
     208     1105011 :     } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
     209             :         // serror is set
     210        4121 :         return false;
     211     1100890 :     } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
     212          56 :         return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
     213             :     }
     214     1100834 :     return true;
     215     1146348 : }
     216             : 
     217     1110510 : bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
     218     1110510 :     if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
     219        4379 :         return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
     220             :     }
     221     1106131 :     return true;
     222     1110510 : }
     223             : 
     224     1274618 : int FindAndDelete(CScript& script, const CScript& b)
     225             : {
     226     1274618 :     int nFound = 0;
     227     1274618 :     if (b.empty())
     228           1 :         return nFound;
     229     1274617 :     CScript result;
     230     1274617 :     CScript::const_iterator pc = script.begin(), pc2 = script.begin(), end = script.end();
     231             :     opcodetype opcode;
     232     1134201 :     do
     233             :     {
     234     7410317 :         result.insert(result.end(), pc2, pc);
     235     7776728 :         while (static_cast<size_t>(end - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
     236             :         {
     237       25364 :             pc = pc + b.size();
     238       25364 :             ++nFound;
     239             :         }
     240     7434036 :         pc2 = pc;
     241    14844027 :     }
     242     7434036 :     while (script.GetOp(pc, opcode));
     243             : 
     244     1133875 :     if (nFound > 0) {
     245       19105 :         result.insert(result.end(), pc2, end);
     246       19105 :         script = std::move(result);
     247       19105 :     }
     248             : 
     249     1133875 :     return nFound;
     250     1416170 : }
     251             : 
     252             : namespace {
     253             : /** A data type to abstract out the condition stack during script execution.
     254             :  *
     255             :  * Conceptually it acts like a vector of booleans, one for each level of nested
     256             :  * IF/THEN/ELSE, indicating whether we're in the active or inactive branch of
     257             :  * each.
     258             :  *
     259             :  * The elements on the stack cannot be observed individually; we only need to
     260             :  * expose whether the stack is empty and whether or not any false values are
     261             :  * present at all. To implement OP_ELSE, a toggle_top modifier is added, which
     262             :  * flips the last value without returning it.
     263             :  *
     264             :  * This uses an optimized implementation that does not materialize the
     265             :  * actual stack. Instead, it just stores the size of the would-be stack,
     266             :  * and the position of the first false value in it.
     267             :  */
     268     3049544 : class ConditionStack {
     269             : private:
     270             :     //! A constant for m_first_false_pos to indicate there are no falses.
     271             :     static constexpr uint32_t NO_FALSE = std::numeric_limits<uint32_t>::max();
     272             : 
     273             :     //! The size of the implied stack.
     274     3049544 :     uint32_t m_stack_size = 0;
     275             :     //! The position of the first false value on the implied stack, or NO_FALSE if all true.
     276     3049544 :     uint32_t m_first_false_pos = NO_FALSE;
     277             : 
     278             : public:
     279     2855338 :     bool empty() const { return m_stack_size == 0; }
     280     8176872 :     bool all_true() const { return m_first_false_pos == NO_FALSE; }
     281        4589 :     void push_back(bool f)
     282             :     {
     283        4589 :         if (m_first_false_pos == NO_FALSE && !f) {
     284             :             // The stack consists of all true values, and a false is added.
     285             :             // The first false value will appear at the current size.
     286        2339 :             m_first_false_pos = m_stack_size;
     287        2339 :         }
     288        4589 :         ++m_stack_size;
     289        4589 :     }
     290        3073 :     void pop_back()
     291             :     {
     292        3073 :         assert(m_stack_size > 0);
     293        3073 :         --m_stack_size;
     294        3073 :         if (m_first_false_pos == m_stack_size) {
     295             :             // When popping off the first false value, everything becomes true.
     296         933 :             m_first_false_pos = NO_FALSE;
     297         933 :         }
     298        3073 :     }
     299        3897 :     void toggle_top()
     300             :     {
     301        3897 :         assert(m_stack_size > 0);
     302        3897 :         if (m_first_false_pos == NO_FALSE) {
     303             :             // The current stack is all true values; the first false will be the top.
     304        1208 :             m_first_false_pos = m_stack_size - 1;
     305        3897 :         } else if (m_first_false_pos == m_stack_size - 1) {
     306             :             // The top is the first false value; toggling it will make everything true.
     307        2417 :             m_first_false_pos = NO_FALSE;
     308        2417 :         } else {
     309             :             // There is a false value, but not on top. No action is needed as toggling
     310             :             // anything but the first false value is unobservable.
     311             :         }
     312        3897 :     }
     313             : };
     314             : }
     315             : 
     316             : /** Helper for OP_CHECKSIG and OP_CHECKSIGVERIFY
     317             :  *
     318             :  * A return value of false means the script fails entirely. When true is returned, the
     319             :  * fSuccess variable indicates whether the signature check itself succeeded.
     320             :  */
     321     1080075 : 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)
     322             : {
     323             :     // Subset of script starting at the most recent codeseparator
     324     1080075 :     CScript scriptCode(pbegincodehash, pend);
     325             : 
     326             :     // Drop the signature, since there's no way for a signature to sign itself
     327     1080075 :     if (sigversion == SigVersion::BASE) {
     328     1076909 :         int found = FindAndDelete(scriptCode, CScript() << vchSig);
     329     1076169 :         if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
     330          58 :             return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
     331     1076111 :     }
     332             : 
     333     1079277 :     if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
     334             :         //serror is set
     335        9489 :         return false;
     336             :     }
     337     1067062 :     fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
     338             : 
     339     1067754 :     if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
     340        1090 :         return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
     341             : 
     342     1066664 :     return true;
     343     1084779 : }
     344             : 
     345             : 
     346     3067086 : bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
     347             : {
     348     3067086 :     static const CScriptNum bnZero(0);
     349     3067086 :     static const CScriptNum bnOne(1);
     350             :     // static const CScriptNum bnFalse(0);
     351             :     // static const CScriptNum bnTrue(1);
     352             :     static const valtype vchFalse(0);
     353             :     // static const valtype vchZero(0);
     354     3067086 :     static const valtype vchTrue(1, 1);
     355             : 
     356     3067086 :     CScript::const_iterator pc = script.begin();
     357     3067086 :     CScript::const_iterator pend = script.end();
     358     3067086 :     CScript::const_iterator pbegincodehash = script.begin();
     359             :     opcodetype opcode;
     360     3067086 :     valtype vchPushValue;
     361     3067086 :     ConditionStack vfExec;
     362     3067086 :     std::vector<valtype> altstack;
     363     3067086 :     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
     364     3049940 :     if (script.size() > MAX_SCRIPT_SIZE)
     365           9 :         return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
     366     3067015 :     int nOpCount = 0;
     367     3067015 :     bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
     368             : 
     369             :     try
     370             :     {
     371    11046117 :         while (pc < pend)
     372             :         {
     373     8176702 :             bool fExec = vfExec.all_true();
     374             : 
     375             :             //
     376             :             // Read instruction
     377             :             //
     378     8176731 :             if (!script.GetOp(pc, opcode, vchPushValue))
     379          30 :                 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
     380     8170600 :             if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
     381          43 :                 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
     382             : 
     383             :             // Note how OP_RESERVED does not count towards the opcode limit.
     384     8170557 :             if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
     385          45 :                 return set_error(serror, SCRIPT_ERR_OP_COUNT);
     386             : 
     387    16340606 :             if (opcode == OP_INVERT ||
     388     8170455 :                 opcode == OP_2MUL ||
     389     8170415 :                 opcode == OP_2DIV ||
     390     8170386 :                 opcode == OP_MUL ||
     391     8170128 :                 opcode == OP_LSHIFT ||
     392     8170094 :                 opcode == OP_RSHIFT)
     393         500 :                 return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes (CVE-2010-5137).
     394             : 
     395             :             // With SCRIPT_VERIFY_CONST_SCRIPTCODE, OP_CODESEPARATOR is rejected even in an unexecuted branch
     396     8170012 :             if (opcode == OP_CODESEPARATOR && sigversion == SigVersion::BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
     397         175 :                 return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
     398             : 
     399     8169837 :             if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
     400     3368157 :                 if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
     401         285 :                     return set_error(serror, SCRIPT_ERR_MINIMALDATA);
     402             :                 }
     403     3367872 :                 stack.push_back(vchPushValue);
     404     8170236 :             } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
     405     4793969 :             switch (opcode)
     406             :             {
     407             :                 //
     408             :                 // Push value
     409             :                 //
     410             :                 case OP_1NEGATE:
     411             :                 case OP_1:
     412             :                 case OP_2:
     413             :                 case OP_3:
     414             :                 case OP_4:
     415             :                 case OP_5:
     416             :                 case OP_6:
     417             :                 case OP_7:
     418             :                 case OP_8:
     419             :                 case OP_9:
     420             :                 case OP_10:
     421             :                 case OP_11:
     422             :                 case OP_12:
     423             :                 case OP_13:
     424             :                 case OP_14:
     425             :                 case OP_15:
     426             :                 case OP_16:
     427             :                 {
     428             :                     // ( -- value)
     429      220674 :                     CScriptNum bn((int)opcode - (int)(OP_1 - 1));
     430      229893 :                     stack.push_back(bn.getvch());
     431             :                     // The result of these opcodes should always be the minimal way to push the data
     432             :                     // they push, so no need for a CheckMinimalPush here.
     433             :                 }
     434      229911 :                 break;
     435             : 
     436             : 
     437             :                 //
     438             :                 // Control
     439             :                 //
     440             :                 case OP_NOP:
     441       11954 :                     break;
     442             : 
     443             :                 case OP_CHECKLOCKTIMEVERIFY:
     444             :                 {
     445       15627 :                     if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
     446             :                         // not enabled; treat as a NOP2
     447        9880 :                         break;
     448             :                     }
     449             : 
     450        5747 :                     if (stack.size() < 1)
     451          54 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     452             : 
     453             :                     // Note that elsewhere numeric opcodes are limited to
     454             :                     // operands in the range -2**31+1 to 2**31-1, however it is
     455             :                     // legal for opcodes to produce results exceeding that
     456             :                     // range. This limitation is implemented by CScriptNum's
     457             :                     // default 4-byte limit.
     458             :                     //
     459             :                     // If we kept to that limit we'd have a year 2038 problem,
     460             :                     // even though the nLockTime field in transactions
     461             :                     // themselves is uint32 which only becomes meaningless
     462             :                     // after the year 2106.
     463             :                     //
     464             :                     // Thus as a special case we tell CScriptNum to accept up
     465             :                     // to 5-byte bignums, which are good until 2**39-1, well
     466             :                     // beyond the 2**32-1 limit of the nLockTime field itself.
     467        5693 :                     const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
     468             : 
     469             :                     // In the rare event that the argument may be < 0 due to
     470             :                     // some arithmetic being done first, you can always use
     471             :                     // 0 MAX CHECKLOCKTIMEVERIFY.
     472        5666 :                     if (nLockTime < 0)
     473          75 :                         return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
     474             : 
     475             :                     // Actually compare the specified lock time with the transaction.
     476        5591 :                     if (!checker.CheckLockTime(nLockTime))
     477        5346 :                         return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
     478             : 
     479         245 :                     break;
     480             :                 }
     481             : 
     482             :                 case OP_CHECKSEQUENCEVERIFY:
     483             :                 {
     484       16789 :                     if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
     485             :                         // not enabled; treat as a NOP3
     486       10479 :                         break;
     487             :                     }
     488             : 
     489        6310 :                     if (stack.size() < 1)
     490          46 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     491             : 
     492             :                     // nSequence, like nLockTime, is a 32-bit unsigned integer
     493             :                     // field. See the comment in CHECKLOCKTIMEVERIFY regarding
     494             :                     // 5-byte numeric operands.
     495        6264 :                     const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
     496             : 
     497             :                     // In the rare event that the argument may be < 0 due to
     498             :                     // some arithmetic being done first, you can always use
     499             :                     // 0 MAX CHECKSEQUENCEVERIFY.
     500        6223 :                     if (nSequence < 0)
     501          71 :                         return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
     502             : 
     503             :                     // To provide for future soft-fork extensibility, if the
     504             :                     // operand has the disabled lock-time flag set,
     505             :                     // CHECKSEQUENCEVERIFY behaves as a NOP.
     506        6152 :                     if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
     507         393 :                         break;
     508             : 
     509             :                     // Compare the specified sequence number with the input.
     510        5759 :                     if (!checker.CheckSequence(nSequence))
     511        5502 :                         return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
     512             : 
     513         257 :                     break;
     514             :                 }
     515             : 
     516             :                 case OP_NOP1: case OP_NOP4: case OP_NOP5:
     517             :                 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
     518             :                 {
     519         763 :                     if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
     520         190 :                         return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
     521             :                 }
     522         573 :                 break;
     523             : 
     524             :                 case OP_IF:
     525             :                 case OP_NOTIF:
     526             :                 {
     527             :                     // <expression> if [statements] [else [statements]] endif
     528        4376 :                     bool fValue = false;
     529        4376 :                     if (fExec)
     530             :                     {
     531        4376 :                         if (stack.size() < 1)
     532          25 :                             return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
     533        4351 :                         valtype& vch = stacktop(-1);
     534        4351 :                         fValue = CastToBool(vch);
     535        4351 :                         if (opcode == OP_NOTIF)
     536         297 :                             fValue = !fValue;
     537        4351 :                         popstack(stack);
     538        4351 :                     }
     539        4351 :                     vfExec.push_back(fValue);
     540             :                 }
     541        4589 :                 break;
     542             : 
     543             :                 case OP_ELSE:
     544             :                 {
     545        3955 :                     if (vfExec.empty())
     546          58 :                         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
     547        3897 :                     vfExec.toggle_top();
     548             :                 }
     549        3897 :                 break;
     550             : 
     551             :                 case OP_ENDIF:
     552             :                 {
     553        3211 :                     if (vfExec.empty())
     554         138 :                         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
     555        3073 :                     vfExec.pop_back();
     556             :                 }
     557        3073 :                 break;
     558             : 
     559             :                 case OP_VERIFY:
     560             :                 {
     561             :                     // (true -- ) or
     562             :                     // (false -- false) and return
     563       12077 :                     if (stack.size() < 1)
     564           9 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     565       12068 :                     bool fValue = CastToBool(stacktop(-1));
     566       12068 :                     if (fValue)
     567       12033 :                         popstack(stack);
     568             :                     else
     569          35 :                         return set_error(serror, SCRIPT_ERR_VERIFY);
     570             :                 }
     571       12033 :                 break;
     572             : 
     573             :                 case OP_RETURN:
     574             :                 {
     575          85 :                     return set_error(serror, SCRIPT_ERR_OP_RETURN);
     576             :                 }
     577             :                 break;
     578             : 
     579             : 
     580             :                 //
     581             :                 // Stack ops
     582             :                 //
     583             :                 case OP_TOALTSTACK:
     584             :                 {
     585         143 :                     if (stack.size() < 1)
     586          14 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     587         129 :                     altstack.push_back(stacktop(-1));
     588         129 :                     popstack(stack);
     589             :                 }
     590         129 :                 break;
     591             : 
     592             :                 case OP_FROMALTSTACK:
     593             :                 {
     594          75 :                     if (altstack.size() < 1)
     595          24 :                         return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
     596          51 :                     stack.push_back(altstacktop(-1));
     597          51 :                     popstack(altstack);
     598             :                 }
     599          51 :                 break;
     600             : 
     601             :                 case OP_2DROP:
     602             :                 {
     603             :                     // (x1 x2 -- )
     604         187 :                     if (stack.size() < 2)
     605          17 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     606         170 :                     popstack(stack);
     607         170 :                     popstack(stack);
     608             :                 }
     609         170 :                 break;
     610             : 
     611             :                 case OP_2DUP:
     612             :                 {
     613             :                     // (x1 x2 -- x1 x2 x1 x2)
     614       99255 :                     if (stack.size() < 2)
     615          44 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     616       99211 :                     valtype vch1 = stacktop(-2);
     617       99212 :                     valtype vch2 = stacktop(-1);
     618       99212 :                     stack.push_back(vch1);
     619       99135 :                     stack.push_back(vch2);
     620       99212 :                 }
     621       99058 :                 break;
     622             : 
     623             :                 case OP_3DUP:
     624             :                 {
     625             :                     // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
     626       23026 :                     if (stack.size() < 3)
     627          62 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     628       22964 :                     valtype vch1 = stacktop(-3);
     629       22964 :                     valtype vch2 = stacktop(-2);
     630       22964 :                     valtype vch3 = stacktop(-1);
     631       22964 :                     stack.push_back(vch1);
     632       22964 :                     stack.push_back(vch2);
     633       22964 :                     stack.push_back(vch3);
     634       22964 :                 }
     635       22964 :                 break;
     636             : 
     637             :                 case OP_2OVER:
     638             :                 {
     639             :                     // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
     640          76 :                     if (stack.size() < 4)
     641          42 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     642          34 :                     valtype vch1 = stacktop(-4);
     643          34 :                     valtype vch2 = stacktop(-3);
     644          34 :                     stack.push_back(vch1);
     645          34 :                     stack.push_back(vch2);
     646          34 :                 }
     647          34 :                 break;
     648             : 
     649             :                 case OP_2ROT:
     650             :                 {
     651             :                     // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
     652         221 :                     if (stack.size() < 6)
     653          17 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     654         204 :                     valtype vch1 = stacktop(-6);
     655         204 :                     valtype vch2 = stacktop(-5);
     656         204 :                     stack.erase(stack.end()-6, stack.end()-4);
     657         204 :                     stack.push_back(vch1);
     658         204 :                     stack.push_back(vch2);
     659         204 :                 }
     660         204 :                 break;
     661             : 
     662             :                 case OP_2SWAP:
     663             :                 {
     664             :                     // (x1 x2 x3 x4 -- x3 x4 x1 x2)
     665          76 :                     if (stack.size() < 4)
     666          42 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     667          34 :                     swap(stacktop(-4), stacktop(-2));
     668          34 :                     swap(stacktop(-3), stacktop(-1));
     669             :                 }
     670          34 :                 break;
     671             : 
     672             :                 case OP_IFDUP:
     673             :                 {
     674             :                     // (x - 0 | x x)
     675          87 :                     if (stack.size() < 1)
     676          19 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     677          68 :                     valtype vch = stacktop(-1);
     678          68 :                     if (CastToBool(vch))
     679          51 :                         stack.push_back(vch);
     680          68 :                 }
     681          68 :                 break;
     682             : 
     683             :                 case OP_DEPTH:
     684             :                 {
     685             :                     // -- stacksize
     686        1322 :                     CScriptNum bn(stack.size());
     687        1322 :                     stack.push_back(bn.getvch());
     688             :                 }
     689        1322 :                 break;
     690             : 
     691             :                 case OP_DROP:
     692             :                 {
     693             :                     // (x -- )
     694       24204 :                     if (stack.size() < 1)
     695          15 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     696       24189 :                     popstack(stack);
     697             :                 }
     698       24191 :                 break;
     699             : 
     700             :                 case OP_DUP:
     701             :                 {
     702             :                     // (x -- x x)
     703     1019349 :                     if (stack.size() < 1)
     704      111205 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     705      908144 :                     valtype vch = stacktop(-1);
     706      908205 :                     stack.push_back(vch);
     707      908205 :                 }
     708      908205 :                 break;
     709             : 
     710             :                 case OP_NIP:
     711             :                 {
     712             :                     // (x1 x2 -- x2)
     713         189 :                     if (stack.size() < 2)
     714          37 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     715         152 :                     stack.erase(stack.end() - 2);
     716             :                 }
     717         152 :                 break;
     718             : 
     719             :                 case OP_OVER:
     720             :                 {
     721             :                     // (x1 x2 -- x1 x2 x1)
     722          93 :                     if (stack.size() < 2)
     723          42 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     724          51 :                     valtype vch = stacktop(-2);
     725          51 :                     stack.push_back(vch);
     726          51 :                 }
     727          51 :                 break;
     728             : 
     729             :                 case OP_PICK:
     730             :                 case OP_ROLL:
     731             :                 {
     732             :                     // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
     733             :                     // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
     734         658 :                     if (stack.size() < 2)
     735          55 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     736         603 :                     int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
     737         582 :                     popstack(stack);
     738         582 :                     if (n < 0 || n >= (int)stack.size())
     739          85 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     740         497 :                     valtype vch = stacktop(-n-1);
     741         497 :                     if (opcode == OP_ROLL)
     742         154 :                         stack.erase(stack.end()-n-1);
     743         497 :                     stack.push_back(vch);
     744         497 :                 }
     745         497 :                 break;
     746             : 
     747             :                 case OP_ROT:
     748             :                 {
     749             :                     // (x1 x2 x3 -- x2 x3 x1)
     750             :                     //  x2 x1 x3  after first swap
     751             :                     //  x2 x3 x1  after second swap
     752         224 :                     if (stack.size() < 3)
     753          43 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     754         181 :                     swap(stacktop(-3), stacktop(-2));
     755         181 :                     swap(stacktop(-2), stacktop(-1));
     756             :                 }
     757         181 :                 break;
     758             : 
     759             :                 case OP_SWAP:
     760             :                 {
     761             :                     // (x1 x2 -- x2 x1)
     762         316 :                     if (stack.size() < 2)
     763          41 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     764         275 :                     swap(stacktop(-2), stacktop(-1));
     765             :                 }
     766         275 :                 break;
     767             : 
     768             :                 case OP_TUCK:
     769             :                 {
     770             :                     // (x1 x2 -- x2 x1 x2)
     771          97 :                     if (stack.size() < 2)
     772          46 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     773          51 :                     valtype vch = stacktop(-1);
     774          51 :                     stack.insert(stack.end()-2, vch);
     775          51 :                 }
     776          51 :                 break;
     777             : 
     778             : 
     779             :                 case OP_SIZE:
     780             :                 {
     781             :                     // (in -- in size)
     782         616 :                     if (stack.size() < 1)
     783          15 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     784         601 :                     CScriptNum bn(stacktop(-1).size());
     785         601 :                     stack.push_back(bn.getvch());
     786             :                 }
     787         601 :                 break;
     788             : 
     789             : 
     790             :                 //
     791             :                 // Bitwise logic
     792             :                 //
     793             :                 case OP_EQUAL:
     794             :                 case OP_EQUALVERIFY:
     795             :                 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
     796             :                 {
     797             :                     // (x1 x2 - bool)
     798     1023156 :                     if (stack.size() < 2)
     799          68 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     800     1023088 :                     valtype& vch1 = stacktop(-2);
     801     1023097 :                     valtype& vch2 = stacktop(-1);
     802     1023097 :                     bool fEqual = (vch1 == vch2);
     803             :                     // OP_NOTEQUAL is disabled because it would be too easy to say
     804             :                     // something like n != 1 and have some wiseguy pass in 1 with extra
     805             :                     // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
     806             :                     //if (opcode == OP_NOTEQUAL)
     807             :                     //    fEqual = !fEqual;
     808     1023130 :                     popstack(stack);
     809     1023132 :                     popstack(stack);
     810     1023152 :                     stack.push_back(fEqual ? vchTrue : vchFalse);
     811     1023085 :                     if (opcode == OP_EQUALVERIFY)
     812             :                     {
     813      908451 :                         if (fEqual)
     814      908255 :                             popstack(stack);
     815             :                         else
     816         196 :                             return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
     817      908266 :                     }
     818             :                 }
     819     1022900 :                 break;
     820             : 
     821             :                 case OP_AND:
     822             :                 case OP_OR:
     823             :                 case OP_XOR: {
     824             :                     // (x1 x2 - out)
     825       51228 :                     if (stack.size() < 2) {
     826         342 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     827             :                     }
     828       50886 :                     valtype &vch1 = stacktop(-2);
     829       50886 :                     valtype &vch2 = stacktop(-1);
     830             : 
     831             :                     // Inputs must be the same size
     832       50886 :                     if (vch1.size() != vch2.size()) {
     833         393 :                         return set_error(serror, SCRIPT_ERR_INVALID_OPERAND_SIZE);
     834             :                     }
     835             : 
     836             :                     // To avoid allocating, we modify vch1 in place.
     837       50493 :                     switch (opcode) {
     838             :                         case OP_AND:
     839     4395836 :                             for (size_t i = 0; i < vch1.size(); ++i) {
     840     4379005 :                                 vch1[i] &= vch2[i];
     841     4379005 :                             }
     842       16831 :                             break;
     843             :                         case OP_OR:
     844     4395836 :                             for (size_t i = 0; i < vch1.size(); ++i) {
     845     4379005 :                                 vch1[i] |= vch2[i];
     846     4379005 :                             }
     847       16831 :                             break;
     848             :                         case OP_XOR:
     849     4395836 :                             for (size_t i = 0; i < vch1.size(); ++i) {
     850     4379005 :                                 vch1[i] ^= vch2[i];
     851     4379005 :                             }
     852       16831 :                             break;
     853             :                         default:
     854           0 :                             break;
     855             :                     }
     856             : 
     857             :                     // And pop vch2.
     858       50493 :                     popstack(stack);
     859             :                 }
     860       50493 :                 break;
     861             : 
     862             : 
     863             :                 //
     864             :                 // Numeric
     865             :                 //
     866             :                 case OP_1ADD:
     867             :                 case OP_1SUB:
     868             :                 case OP_NEGATE:
     869             :                 case OP_ABS:
     870             :                 case OP_NOT:
     871             :                 case OP_0NOTEQUAL:
     872             :                 {
     873             :                     // (in -- out)
     874       13856 :                     if (stack.size() < 1)
     875          56 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     876       13800 :                     CScriptNum bn(stacktop(-1), fRequireMinimal);
     877       13481 :                     switch (opcode)
     878             :                     {
     879         174 :                     case OP_1ADD:       bn += bnOne; break;
     880          79 :                     case OP_1SUB:       bn -= bnOne; break;
     881          69 :                     case OP_NEGATE:     bn = -bn; break;
     882          86 :                     case OP_ABS:        if (bn < bnZero) bn = -bn; break;
     883       12970 :                     case OP_NOT:        bn = (bn == bnZero); break;
     884         103 :                     case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
     885           0 :                     default:            assert(!"invalid opcode"); break;
     886             :                     }
     887       13481 :                     popstack(stack);
     888       13481 :                     stack.push_back(bn.getvch());
     889             :                 }
     890       13481 :                 break;
     891             : 
     892             :                 case OP_ADD:
     893             :                 case OP_SUB:
     894             :                 case OP_DIV:
     895             :                 case OP_MOD:
     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        4479 :                     if (stack.size() < 2)
     910         297 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     911        4182 :                     CScriptNum bn1(stacktop(-2), fRequireMinimal);
     912        3883 :                     CScriptNum bn2(stacktop(-1), fRequireMinimal);
     913        3599 :                     CScriptNum bn(0);
     914        3599 :                     switch (opcode)
     915             :                     {
     916             :                     case OP_ADD:
     917         650 :                         bn = bn1 + bn2;
     918         650 :                         break;
     919             : 
     920             :                     case OP_SUB:
     921         111 :                         bn = bn1 - bn2;
     922         111 :                         break;
     923             : 
     924             :                     case OP_DIV:
     925             :                         // denominator must not be 0
     926         655 :                         if (bn2 == 0) {
     927         137 :                             return set_error(serror, SCRIPT_ERR_DIV_BY_ZERO);
     928             :                         }
     929         518 :                         bn = bn1 / bn2;
     930         518 :                         break;
     931             : 
     932             :                     case OP_MOD:
     933             :                         // divisor must not be 0
     934         256 :                         if (bn2 == 0) {
     935          17 :                             return set_error(serror, SCRIPT_ERR_MOD_BY_ZERO);
     936             :                         }
     937         239 :                         bn = bn1 % bn2;
     938         239 :                         break;
     939             : 
     940         417 :                     case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
     941         176 :                     case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
     942         549 :                     case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
     943          70 :                     case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
     944          87 :                     case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
     945         138 :                     case OP_LESSTHAN:            bn = (bn1 < bn2); break;
     946         138 :                     case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
     947         138 :                     case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
     948         138 :                     case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
     949         121 :                     case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
     950         121 :                     case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
     951           0 :                     default:                     assert(!"invalid opcode"); break;
     952             :                     }
     953        3445 :                     popstack(stack);
     954        3445 :                     popstack(stack);
     955        3445 :                     stack.push_back(bn.getvch());
     956             : 
     957        3445 :                     if (opcode == OP_NUMEQUALVERIFY)
     958             :                     {
     959          70 :                         if (CastToBool(stacktop(-1)))
     960          70 :                             popstack(stack);
     961             :                         else
     962           0 :                             return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
     963          70 :                     }
     964             :                 }
     965        3445 :                 break;
     966             : 
     967             :                 case OP_WITHIN:
     968             :                 {
     969             :                     // (x min max -- out)
     970         303 :                     if (stack.size() < 3)
     971          17 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     972         286 :                     CScriptNum bn1(stacktop(-3), fRequireMinimal);
     973         270 :                     CScriptNum bn2(stacktop(-2), fRequireMinimal);
     974         257 :                     CScriptNum bn3(stacktop(-1), fRequireMinimal);
     975         471 :                     bool fValue = (bn2 <= bn1 && bn1 < bn3);
     976         244 :                     popstack(stack);
     977         244 :                     popstack(stack);
     978         244 :                     popstack(stack);
     979         244 :                     stack.push_back(fValue ? vchTrue : vchFalse);
     980             :                 }
     981         244 :                 break;
     982             : 
     983             : 
     984             :                 //
     985             :                 // Crypto
     986             :                 //
     987             :                 case OP_RIPEMD160:
     988             :                 case OP_SHA1:
     989             :                 case OP_SHA256:
     990             :                 case OP_HASH160:
     991             :                 case OP_HASH256:
     992             :                 {
     993             :                     // (in -- hash)
     994     1018188 :                     if (stack.size() < 1)
     995         339 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     996     1017849 :                     valtype& vch = stacktop(-1);
     997     1017829 :                     valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
     998     1017857 :                     if (opcode == OP_RIPEMD160)
     999          85 :                         CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
    1000     1017772 :                     else if (opcode == OP_SHA1)
    1001         748 :                         CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
    1002     1017024 :                     else if (opcode == OP_SHA256)
    1003         173 :                         CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
    1004     1016851 :                     else if (opcode == OP_HASH160)
    1005     1016766 :                         CHash160().Write(vch).Finalize(vchHash);
    1006          85 :                     else if (opcode == OP_HASH256)
    1007          85 :                         CHash256().Write(vch).Finalize(vchHash);
    1008     1017863 :                     popstack(stack);
    1009     1017862 :                     stack.push_back(vchHash);
    1010     1018123 :                 }
    1011     1017601 :                 break;
    1012             : 
    1013             :                 case OP_CODESEPARATOR:
    1014             :                 {
    1015             :                     // If SCRIPT_VERIFY_CONST_SCRIPTCODE flag is set, use of OP_CODESEPARATOR is rejected,
    1016             :                     // even in an unexecuted branch (this is checked above the opcode case statement).
    1017             : 
    1018             :                     // Hash starts after the code separator
    1019         341 :                     pbegincodehash = pc;
    1020             :                 }
    1021         341 :                 break;
    1022             : 
    1023             :                 case OP_CHECKSIG:
    1024             :                 case OP_CHECKSIGVERIFY:
    1025             :                 {
    1026             :                     // (sig pubkey -- bool)
    1027     1091813 :                     if (stack.size() < 2)
    1028       15224 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1029             : 
    1030     1076589 :                     valtype& vchSig    = stacktop(-2);
    1031     1076758 :                     valtype& vchPubKey = stacktop(-1);
    1032             : 
    1033     1076889 :                     bool fSuccess = true;
    1034     1076889 :                     if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, flags, checker, sigversion, serror, fSuccess)) return false;
    1035     1065960 :                     popstack(stack);
    1036     1066658 :                     popstack(stack);
    1037     1066592 :                     stack.push_back(fSuccess ? vchTrue : vchFalse);
    1038     1065210 :                     if (opcode == OP_CHECKSIGVERIFY)
    1039             :                     {
    1040       98973 :                         if (fSuccess)
    1041       98853 :                             popstack(stack);
    1042             :                         else
    1043         120 :                             return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
    1044       99862 :                     }
    1045             :                 }
    1046     1066099 :                 break;
    1047             : 
    1048             :                 case OP_CHECKDATASIG:
    1049             :                 case OP_CHECKDATASIGVERIFY: {
    1050             :                     // (sig message pubkey -- bool)
    1051       50184 :                     if (stack.size() < 3) {
    1052         122 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1053             :                     }
    1054             : 
    1055       50062 :                     valtype &vchSig = stacktop(-3);
    1056       50062 :                     valtype &vchMessage = stacktop(-2);
    1057       50062 :                     valtype &vchPubKey = stacktop(-1);
    1058             : 
    1059       50062 :                     if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
    1060             :                         // serror is set
    1061       15590 :                         return false;
    1062             :                     }
    1063             : 
    1064       34472 :                     bool fSuccess = false;
    1065       34472 :                     if (vchSig.size()) {
    1066       22076 :                         valtype vchHash(32);
    1067       22076 :                         CSHA256()
    1068       22076 :                             .Write(vchMessage.data(), vchMessage.size())
    1069       22076 :                             .Finalize(vchHash.data());
    1070       22076 :                         fSuccess = CPubKey(vchPubKey).Verify(uint256(vchHash), vchSig);
    1071       22076 :                     }
    1072             : 
    1073       34472 :                     if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size()) {
    1074       10861 :                         return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
    1075             :                     }
    1076             : 
    1077       23611 :                     popstack(stack);
    1078       23611 :                     popstack(stack);
    1079       23611 :                     popstack(stack);
    1080       23611 :                     stack.push_back(fSuccess ? vchTrue : vchFalse);
    1081       23611 :                     if (opcode == OP_CHECKDATASIGVERIFY) {
    1082       11780 :                         if (fSuccess) {
    1083         138 :                             popstack(stack);
    1084         138 :                         } else {
    1085       11642 :                             return set_error(serror, SCRIPT_ERR_CHECKDATASIGVERIFY);
    1086             :                         }
    1087         138 :                     }
    1088             :                 }
    1089       11969 :                 break;
    1090             : 
    1091             :                 case OP_CHECKMULTISIG:
    1092             :                 case OP_CHECKMULTISIGVERIFY:
    1093             :                 {
    1094             :                     // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
    1095             : 
    1096       14233 :                     int i = 1;
    1097       14233 :                     if ((int)stack.size() < i)
    1098          14 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1099             : 
    1100       14219 :                     int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
    1101       14193 :                     if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
    1102          32 :                         return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
    1103       14161 :                     nOpCount += nKeysCount;
    1104       14161 :                     if (nOpCount > MAX_OPS_PER_SCRIPT)
    1105          34 :                         return set_error(serror, SCRIPT_ERR_OP_COUNT);
    1106       14127 :                     int ikey = ++i;
    1107             :                     // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
    1108             :                     // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
    1109       14127 :                     int ikey2 = nKeysCount + 2;
    1110       14127 :                     i += nKeysCount;
    1111       14127 :                     if ((int)stack.size() < i)
    1112          13 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1113             : 
    1114       14114 :                     int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
    1115       14079 :                     if (nSigsCount < 0 || nSigsCount > nKeysCount)
    1116          30 :                         return set_error(serror, SCRIPT_ERR_SIG_COUNT);
    1117       14049 :                     int isig = ++i;
    1118       14049 :                     i += nSigsCount;
    1119       14049 :                     if ((int)stack.size() < i)
    1120          80 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1121             : 
    1122             :                     // Subset of script starting at the most recent codeseparator
    1123       13969 :                     CScript scriptCode(pbegincodehash, pend);
    1124             : 
    1125             :                     // Drop the signatures, since there's no way for a signature to sign itself
    1126       21244 :                     for (int k = 0; k < nSigsCount; k++)
    1127             :                     {
    1128        7329 :                         valtype& vchSig = stacktop(-isig-k);
    1129        7328 :                         if (sigversion == SigVersion::BASE) {
    1130        7328 :                             int found = FindAndDelete(scriptCode, CScript() << vchSig);
    1131        7328 :                             if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
    1132          54 :                                 return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
    1133        7274 :                         }
    1134        7274 :                     }
    1135             : 
    1136       13915 :                     bool fSuccess = true;
    1137       18337 :                     while (fSuccess && nSigsCount > 0)
    1138             :                     {
    1139        4713 :                         valtype& vchSig    = stacktop(-isig);
    1140        4713 :                         valtype& vchPubKey = stacktop(-ikey);
    1141             : 
    1142             :                         // Note how this makes the exact order of pubkey/signature evaluation
    1143             :                         // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
    1144             :                         // See the script_(in)valid tests for details.
    1145        4713 :                         if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
    1146             :                             // serror is set
    1147         291 :                             return false;
    1148             :                         }
    1149             : 
    1150             :                         // Check signature
    1151        4422 :                         bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
    1152             : 
    1153        4422 :                         if (fOk) {
    1154        3298 :                             isig++;
    1155        3298 :                             nSigsCount--;
    1156        3298 :                         }
    1157        4422 :                         ikey++;
    1158        4422 :                         nKeysCount--;
    1159             : 
    1160             :                         // If there are more signatures left than keys left,
    1161             :                         // then too many signatures have failed. Exit early,
    1162             :                         // without checking any further signatures.
    1163        4422 :                         if (nSigsCount > nKeysCount)
    1164         617 :                             fSuccess = false;
    1165             :                     }
    1166             : 
    1167             :                     // Clean up stack of actual arguments
    1168       73475 :                     while (i-- > 1) {
    1169             :                         // If the operation failed, we require that all signatures must be empty vector
    1170       59990 :                         if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
    1171         139 :                             return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
    1172       59851 :                         if (ikey2 > 0)
    1173       53747 :                             ikey2--;
    1174       59851 :                         popstack(stack);
    1175             :                     }
    1176             : 
    1177             :                     // A bug causes CHECKMULTISIG to consume one extra argument
    1178             :                     // whose contents were not checked in any way.
    1179             :                     //
    1180             :                     // Unfortunately this is a potential source of mutability,
    1181             :                     // so optionally verify it is exactly equal to zero prior
    1182             :                     // to removing it from the stack.
    1183       13485 :                     if (stack.size() < 1)
    1184           0 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1185       13485 :                     if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
    1186         103 :                         return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
    1187       13382 :                     popstack(stack);
    1188             : 
    1189       13382 :                     stack.push_back(fSuccess ? vchTrue : vchFalse);
    1190             : 
    1191       13381 :                     if (opcode == OP_CHECKMULTISIGVERIFY)
    1192             :                     {
    1193        4175 :                         if (fSuccess)
    1194        4175 :                             popstack(stack);
    1195             :                         else
    1196           0 :                             return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
    1197        4175 :                     }
    1198       13968 :                 }
    1199       13382 :                 break;
    1200             : 
    1201             :                 //
    1202             :                 // Splice operations
    1203             :                 //
    1204             :                 case OP_CAT:
    1205             :                 {
    1206             :                     // (x1 x2 -- out)
    1207       10688 :                     if (stack.size() < 2) {
    1208          42 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1209             :                     }
    1210             : 
    1211       10646 :                     valtype &vch1 = stacktop(-2);
    1212       10646 :                     valtype &vch2 = stacktop(-1);
    1213       10646 :                     if (vch1.size() + vch2.size() > MAX_SCRIPT_ELEMENT_SIZE) {
    1214        3160 :                         return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
    1215             :                     }
    1216             : 
    1217        7486 :                     vch1.insert(vch1.end(), vch2.begin(), vch2.end());
    1218        7486 :                     popstack(stack);
    1219             :                 }
    1220        7486 :                 break;
    1221             : 
    1222             :                 case OP_SPLIT:
    1223             :                 {
    1224             :                     // (in position -- x1 x2)
    1225       11830 :                     if (stack.size() < 2) {
    1226          42 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1227             :                     }
    1228             : 
    1229       11788 :                     valtype vch = stacktop(-2);
    1230       11788 :                     int64_t nPosition = CScriptNum(stacktop(-1), fRequireMinimal).getint();
    1231             : 
    1232             :                     // if nPosition is less than 0 or is larger than the input then throw error
    1233       11754 :                     if (nPosition < 0 || static_cast<size_t>(nPosition) > vch.size()) {
    1234        4251 :                         return set_error(serror, SCRIPT_ERR_INVALID_SPLIT_RANGE);
    1235             :                     }
    1236             : 
    1237        7503 :                     popstack(stack);
    1238        7503 :                     popstack(stack);
    1239             : 
    1240             :                     // initialize outputs
    1241        7503 :                     if (nPosition == 0) {
    1242        2188 :                         stack.push_back(valtype());
    1243        2188 :                         stack.push_back(vch);
    1244        7503 :                     } else if (static_cast<size_t>(nPosition) == vch.size()) {
    1245        2132 :                         stack.push_back(vch);
    1246        2132 :                         stack.push_back(valtype());
    1247        2132 :                     } else {
    1248        3183 :                         valtype vchOut1, vchOut2;
    1249        3183 :                         vchOut1.insert(vchOut1.end(), vch.begin(), vch.begin() + nPosition);
    1250        3183 :                         vchOut2.insert(vchOut2.end(), vch.begin() + nPosition, vch.end());
    1251        3183 :                         stack.emplace_back(std::move(vchOut1));
    1252        3183 :                         stack.emplace_back(std::move(vchOut2));
    1253        3183 :                     }
    1254       11788 :                 }
    1255        7503 :                 break;
    1256             : 
    1257             : 
    1258             :                 //
    1259             :                 // Conversion operations
    1260             :                 //
    1261             :                 case OP_NUM2BIN: {
    1262             :                     // (in size -- out)
    1263       25312 :                     if (stack.size() < 2) {
    1264          38 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1265             :                     }
    1266             : 
    1267       25274 :                     uint64_t size = CScriptNum(stacktop(-1), fRequireMinimal).getint();
    1268       25274 :                     if (size > MAX_SCRIPT_ELEMENT_SIZE) {
    1269          36 :                         return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
    1270             :                     }
    1271             : 
    1272       25238 :                     popstack(stack);
    1273       25238 :                     valtype &rawnum = stacktop(-1);
    1274             : 
    1275             :                     // Try to see if we can fit that number in the number of
    1276             :                     // bytes requested.
    1277       25238 :                     CScriptNum::MinimallyEncode(rawnum);
    1278       25238 :                     if (rawnum.size() > size) {
    1279             :                         // We definitively cannot.
    1280           2 :                         return set_error(serror, SCRIPT_ERR_IMPOSSIBLE_ENCODING);
    1281             :                     }
    1282             : 
    1283             :                     // We already have an element of the right size, we
    1284             :                     // don't need to do anything.
    1285       25236 :                     if (rawnum.size() == size) {
    1286         142 :                         break;
    1287             :                     }
    1288             : 
    1289       25094 :                     uint8_t signbit = 0x00;
    1290       25094 :                     if (rawnum.size() > 0) {
    1291       12555 :                         signbit = rawnum.back() & 0x80;
    1292       12555 :                         rawnum[rawnum.size() - 1] &= 0x7f;
    1293       12555 :                     }
    1294             : 
    1295       25094 :                     rawnum.reserve(size);
    1296     8670264 :                     while (rawnum.size() < size - 1) {
    1297     8645170 :                         rawnum.push_back(0x00);
    1298             :                     }
    1299             : 
    1300       25094 :                     rawnum.push_back(signbit);
    1301             :                 }
    1302       25094 :                 break;
    1303             : 
    1304             :                 case OP_BIN2NUM: {
    1305             :                     // (in -- out)
    1306       17204 :                     if (stack.size() < 1) {
    1307          19 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1308             :                     }
    1309             : 
    1310       17185 :                     valtype &n = stacktop(-1);
    1311       17185 :                     CScriptNum::MinimallyEncode(n);
    1312             : 
    1313             :                     // The resulting number must be a valid number.
    1314       17185 :                     if (!CScriptNum::IsMinimallyEncoded(n)) {
    1315          21 :                         return set_error(serror, SCRIPT_ERR_INVALID_NUMBER_RANGE);
    1316             :                     }
    1317             :                 }
    1318       17164 :                 break;
    1319             : 
    1320             :                 default:
    1321        1429 :                     return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
    1322     4602866 :             }
    1323             : 
    1324             :             // Size limits
    1325     7979121 :             if (stack.size() + altstack.size() > MAX_STACK_SIZE)
    1326          19 :                 return set_error(serror, SCRIPT_ERR_STACK_SIZE);
    1327             :         }
    1328     2849360 :     }
    1329             :     catch (...)
    1330             :     {
    1331        1129 :         return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
    1332        1129 :     }
    1333             : 
    1334     2848231 :     if (!vfExec.empty())
    1335          51 :         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
    1336             : 
    1337     2848159 :     return set_success(serror);
    1338     3128153 : }
    1339             : 
    1340             : namespace {
    1341             : 
    1342             : /**
    1343             :  * Wrapper that serializes like CTransaction, but with the modifications
    1344             :  *  required for the signature hash done in-place
    1345             :  */
    1346             : template <class T>
    1347             : class CTransactionSignatureSerializer
    1348             : {
    1349             : private:
    1350             :     const T& txTo;             //!< reference to the spending transaction (the one being serialized)
    1351             :     const CScript& scriptCode; //!< output script being consumed
    1352             :     const unsigned int nIn;    //!< input index of txTo being signed
    1353             :     const bool fAnyoneCanPay;  //!< whether the hashtype has the SIGHASH_ANYONECANPAY flag set
    1354             :     const bool fHashSingle;    //!< whether the hashtype is SIGHASH_SINGLE
    1355             :     const bool fHashNone;      //!< whether the hashtype is SIGHASH_NONE
    1356             : 
    1357             : public:
    1358     1072932 :     CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
    1359      536471 :         txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
    1360      536471 :         fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
    1361      536471 :         fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
    1362     1072932 :         fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
    1363             : 
    1364             :     /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
    1365             :     template<typename S>
    1366      537209 :     void SerializeScriptCode(S &s) const {
    1367      537209 :         CScript::const_iterator it = scriptCode.begin();
    1368      537209 :         CScript::const_iterator itBegin = it;
    1369             :         opcodetype opcode;
    1370      537209 :         unsigned int nCodeSeparators = 0;
    1371     3886732 :         while (scriptCode.GetOp(it, opcode)) {
    1372     3349523 :             if (opcode == OP_CODESEPARATOR)
    1373       25379 :                 nCodeSeparators++;
    1374             :         }
    1375      537209 :         ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
    1376      537209 :         it = itBegin;
    1377     3887982 :         while (scriptCode.GetOp(it, opcode)) {
    1378     3350773 :             if (opcode == OP_CODESEPARATOR) {
    1379       25379 :                 s.write(AsBytes(Span{&itBegin[0], size_t(it - itBegin - 1)}));
    1380       25379 :                 itBegin = it;
    1381       25379 :             }
    1382             :         }
    1383      537209 :         if (itBegin != scriptCode.end())
    1384      527184 :             s.write(AsBytes(Span{&itBegin[0], size_t(it - itBegin)}));
    1385      537481 :     }
    1386             : 
    1387             :     /** Serialize an input of txTo */
    1388             :     template<typename S>
    1389    14280703 :     void SerializeInput(S &s, unsigned int nInput) const {
    1390             :         // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
    1391    14280703 :         if (fAnyoneCanPay)
    1392       25468 :             nInput = nIn;
    1393             :         // Serialize the prevout
    1394    14280703 :         ::Serialize(s, txTo.vin[nInput].prevout);
    1395             :         // Serialize the script
    1396    14280703 :         if (nInput != nIn)
    1397             :             // Blank out other inputs' signatures
    1398    13742984 :             ::Serialize(s, CScript());
    1399             :         else
    1400      537719 :             SerializeScriptCode(s);
    1401             :         // Serialize the nSequence
    1402    14280703 :         if (nInput != nIn && (fHashSingle || fHashNone))
    1403             :             // let the others update at will
    1404        2836 :             ::Serialize(s, int{0});
    1405             :         else
    1406    14278145 :             ::Serialize(s, txTo.vin[nInput].nSequence);
    1407    14280703 :     }
    1408             : 
    1409             :     /** Serialize an output of txTo */
    1410             :     template<typename S>
    1411     4714087 :     void SerializeOutput(S &s, unsigned int nOutput) const {
    1412     4714087 :         if (fHashSingle && nOutput != nIn)
    1413             :             // Do not lock-in the txout payee at other indices as txin
    1414        1238 :             ::Serialize(s, CTxOut());
    1415             :         else
    1416     4712849 :             ::Serialize(s, txTo.vout[nOutput]);
    1417     4714087 :     }
    1418             : 
    1419             :     /** Serialize txTo */
    1420             :     template<typename S>
    1421      537524 :     void Serialize(S &s) const {
    1422             :         // Serialize nVersion
    1423      537524 :         int32_t n32bitVersion = txTo.nVersion | (txTo.nType << 16);
    1424      537524 :         ::Serialize(s, n32bitVersion);
    1425             :         // Serialize vin
    1426      537524 :         unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
    1427      537524 :         ::WriteCompactSize(s, nInputs);
    1428    14813117 :         for (unsigned int nInput = 0; nInput < nInputs; nInput++)
    1429    14275593 :              SerializeInput(s, nInput);
    1430             :         // Serialize vout
    1431      537524 :         unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
    1432      537524 :         ::WriteCompactSize(s, nOutputs);
    1433     5251720 :         for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
    1434     4714196 :              SerializeOutput(s, nOutput);
    1435             :         // Serialize nLockTime
    1436      537524 :         ::Serialize(s, txTo.nLockTime);
    1437      537524 :         if (txTo.nVersion >= CTransaction::SPECIAL_VERSION && txTo.nType != TRANSACTION_NORMAL)
    1438       18032 :             ::Serialize(s, txTo.vExtraPayload);
    1439      537524 :     }
    1440             : };
    1441             : 
    1442             : /** Compute the (single) SHA256 of the concatenation of all prevouts of a tx. */
    1443             : template <class T>
    1444             : uint256 GetPrevoutsSHA256(const T& txTo)
    1445             : {
    1446             :     HashWriter ss{};
    1447             :     for (const auto& txin : txTo.vin) {
    1448             :         ss << txin.prevout;
    1449             :     }
    1450             :     return ss.GetSHA256();
    1451             : }
    1452             : 
    1453             : /** Compute the (single) SHA256 of the concatenation of all nSequences of a tx. */
    1454             : template <class T>
    1455             : uint256 GetSequencesSHA256(const T& txTo)
    1456             : {
    1457             :     HashWriter ss{};
    1458             :     for (const auto& txin : txTo.vin) {
    1459             :         ss << txin.nSequence;
    1460             :     }
    1461             :     return ss.GetSHA256();
    1462             : }
    1463             : 
    1464             : /** Compute the (single) SHA256 of the concatenation of all txouts of a tx. */
    1465             : template <class T>
    1466             : uint256 GetOutputsSHA256(const T& txTo)
    1467             : {
    1468             :     HashWriter ss{};
    1469             :     for (const auto& txout : txTo.vout) {
    1470             :         ss << txout;
    1471             :     }
    1472             :     return ss.GetSHA256();
    1473             : }
    1474             : 
    1475             : } // namespace
    1476             : 
    1477             : template <class T>
    1478      736722 : void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent_outputs, bool force)
    1479             : {
    1480      736722 :     assert(!m_ready);
    1481             : 
    1482      736722 :     m_spent_outputs = std::move(spent_outputs);
    1483             : 
    1484      736722 :     m_ready = true;
    1485      736722 : }
    1486             : 
    1487             : template <class T>
    1488      710391 : PrecomputedTransactionData::PrecomputedTransactionData(const T& txTo)
    1489      355193 : {
    1490             :     Init(txTo, {});
    1491      355193 : }
    1492             : 
    1493             : // explicit instantiation
    1494             : template void PrecomputedTransactionData::Init(const CTransaction& txTo, std::vector<CTxOut>&& spent_outputs, bool force);
    1495             : template void PrecomputedTransactionData::Init(const CMutableTransaction& txTo, std::vector<CTxOut>&& spent_outputs, bool force);
    1496             : template PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo);
    1497             : template PrecomputedTransactionData::PrecomputedTransactionData(const CMutableTransaction& txTo);
    1498             : 
    1499             : [[maybe_unused]] static bool HandleMissingData(MissingDataBehavior mdb)
    1500             : {
    1501             :     switch (mdb) {
    1502             :     case MissingDataBehavior::ASSERT_FAIL:
    1503             :         assert(!"Missing data");
    1504             :         break;
    1505             :     case MissingDataBehavior::FAIL:
    1506             :         return false;
    1507             :     }
    1508             :     assert(!"Unknown MissingDataBehavior value");
    1509             : }
    1510             : 
    1511             : template <class T>
    1512      536547 : uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
    1513             : {
    1514      536547 :     assert(nIn < txTo.vin.size());
    1515             : 
    1516             :     // Check for invalid use of SIGHASH_SINGLE
    1517      536547 :     if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
    1518        1758 :         if (nIn >= txTo.vout.size()) {
    1519             :             //  nOut out of range
    1520         100 :             return uint256::ONE;
    1521             :         }
    1522        1658 :     }
    1523             : 
    1524             :     // Wrapper to serialize only the necessary parts of the transaction being signed
    1525      536447 :     CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
    1526             : 
    1527             :     // Serialize and hash
    1528      536447 :     HashWriter ss{};
    1529      536447 :     ss << txTmp << nHashType;
    1530      536447 :     return ss.GetHash();
    1531      536547 : }
    1532             : 
    1533             : template uint256 SignatureHash<CMutableTransaction>(const CScript& scriptCode, const CMutableTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache);
    1534             : template uint256 SignatureHash<CTransaction>(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache);
    1535             : 
    1536             : template <class T>
    1537      319327 : bool GenericTransactionSignatureChecker<T>::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
    1538             : {
    1539      319327 :     return pubkey.Verify(sighash, vchSig);
    1540             : }
    1541             : 
    1542             : template <class T>
    1543      424091 : bool GenericTransactionSignatureChecker<T>::CheckSig(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
    1544             : {
    1545      424091 :     CPubKey pubkey(vchPubKey);
    1546      424091 :     if (!pubkey.IsValid())
    1547         313 :         return false;
    1548             : 
    1549             :     // Hash type is one byte tacked on to the end of the signature
    1550      423778 :     std::vector<unsigned char> vchSig(vchSigIn);
    1551      423778 :     if (vchSig.empty())
    1552         740 :         return false;
    1553      423038 :     int nHashType = vchSig.back();
    1554      423038 :     vchSig.pop_back();
    1555             : 
    1556      421133 :     uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
    1557             : 
    1558      422778 :     if (!VerifySignature(vchSig, pubkey, sighash))
    1559        1996 :         return false;
    1560             : 
    1561      420526 :     return true;
    1562      427385 : }
    1563             : 
    1564             : template <class T>
    1565        5591 : bool GenericTransactionSignatureChecker<T>::CheckLockTime(const CScriptNum& nLockTime) const
    1566             : {
    1567             :     // There are two kinds of nLockTime: lock-by-blockheight
    1568             :     // and lock-by-blocktime, distinguished by whether
    1569             :     // nLockTime < LOCKTIME_THRESHOLD.
    1570             :     //
    1571             :     // We want to compare apples to apples, so fail the script
    1572             :     // unless the type of nLockTime being tested is the same as
    1573             :     // the nLockTime in the transaction.
    1574        5591 :     if (!(
    1575        5926 :         (txTo->nLockTime <  LOCKTIME_THRESHOLD && nLockTime <  LOCKTIME_THRESHOLD) ||
    1576         335 :         (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
    1577             :     ))
    1578         131 :         return false;
    1579             : 
    1580             :     // Now that we know we're comparing apples-to-apples, the
    1581             :     // comparison is a simple numeric one.
    1582        5460 :     if (nLockTime > (int64_t)txTo->nLockTime)
    1583        5135 :         return false;
    1584             : 
    1585             :     // Finally the nLockTime feature can be disabled in IsFinalTx()
    1586             :     // and thus CHECKLOCKTIMEVERIFY bypassed if every txin has
    1587             :     // been finalized by setting nSequence to maxint. The
    1588             :     // transaction would be allowed into the blockchain, making
    1589             :     // the opcode ineffective.
    1590             :     //
    1591             :     // Testing if this vin is not final is sufficient to
    1592             :     // prevent this condition. Alternatively we could test all
    1593             :     // inputs, but testing just this input minimizes the data
    1594             :     // required to prove correct CHECKLOCKTIMEVERIFY execution.
    1595         325 :     if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
    1596          80 :         return false;
    1597             : 
    1598         245 :     return true;
    1599        5591 : }
    1600             : 
    1601             : template <class T>
    1602        5759 : bool GenericTransactionSignatureChecker<T>::CheckSequence(const CScriptNum& nSequence) const
    1603             : {
    1604             :     // Relative lock times are supported by comparing the passed
    1605             :     // in operand to the sequence number of the input.
    1606        5759 :     const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
    1607             : 
    1608             :     // Fail if the transaction's version number is not set high
    1609             :     // enough to trigger BIP 68 rules.
    1610        5759 :     if (static_cast<uint32_t>(txTo->nVersion) < 2)
    1611         178 :         return false;
    1612             : 
    1613             :     // Sequence numbers with their most significant bit set are not
    1614             :     // consensus constrained. Testing that the transaction's sequence
    1615             :     // number do not have this bit set prevents using this property
    1616             :     // to get around a CHECKSEQUENCEVERIFY check.
    1617        5581 :     if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
    1618          32 :         return false;
    1619             : 
    1620             :     // Mask off any bits that do not have consensus-enforced meaning
    1621             :     // before doing the integer comparisons
    1622        5549 :     const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
    1623        5549 :     const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
    1624        5549 :     const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
    1625             : 
    1626             :     // There are two kinds of nSequence: lock-by-blockheight
    1627             :     // and lock-by-blocktime, distinguished by whether
    1628             :     // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
    1629             :     //
    1630             :     // We want to compare apples to apples, so fail the script
    1631             :     // unless the type of nSequenceMasked being tested is the same as
    1632             :     // the nSequenceMasked in the transaction.
    1633        5549 :     if (!(
    1634        5860 :         (txToSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
    1635         311 :         (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
    1636             :     )) {
    1637         140 :         return false;
    1638             :     }
    1639             : 
    1640             :     // Now that we know we're comparing apples-to-apples, the
    1641             :     // comparison is a simple numeric one.
    1642        5409 :     if (nSequenceMasked > txToSequenceMasked)
    1643        5152 :         return false;
    1644             : 
    1645         257 :     return true;
    1646        5759 : }
    1647             : 
    1648             : // explicit instantiation
    1649             : template class GenericTransactionSignatureChecker<CTransaction>;
    1650             : template class GenericTransactionSignatureChecker<CMutableTransaction>;
    1651             : 
    1652     1338683 : bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
    1653             : {
    1654     1338683 :     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
    1655             : 
    1656     1338683 :     if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
    1657         816 :         return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
    1658             :     }
    1659             : 
    1660             :     // scriptSig and scriptPubKey must be evaluated sequentially on the same stack
    1661             :     // rather than being simply concatenated (see CVE-2010-5141)
    1662     1337867 :     std::vector<std::vector<unsigned char> > stack, stackCopy;
    1663     1337867 :     if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
    1664             :         // serror is set
    1665         986 :         return false;
    1666     1336759 :     if (flags & SCRIPT_VERIFY_P2SH)
    1667     1244935 :         stackCopy = stack;
    1668     1336781 :     if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
    1669             :         // serror is set
    1670      139709 :         return false;
    1671     1197056 :     if (stack.empty())
    1672         126 :         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    1673     1196930 :     if (CastToBool(stack.back()) == false)
    1674         828 :         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    1675             : 
    1676             :     // Additional validation for spend-to-script-hash transactions:
    1677     1196102 :     if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
    1678             :     {
    1679             :         // scriptSig must be literals-only or validation fails
    1680      106205 :         if (!scriptSig.IsPushOnly())
    1681          23 :             return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
    1682             : 
    1683             :         // Restore stack.
    1684      106186 :         swap(stack, stackCopy);
    1685             : 
    1686             :         // stack cannot be empty here, because if it was the
    1687             :         // P2SH  HASH <> EQUAL  scriptPubKey would be evaluated with
    1688             :         // an empty stack and the EvalScript above would return false.
    1689      106186 :         assert(!stack.empty());
    1690             : 
    1691      106186 :         const valtype& pubKeySerialized = stack.back();
    1692      106186 :         CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
    1693      106218 :         popstack(stack);
    1694             : 
    1695      106190 :         if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
    1696             :             // serror is set
    1697       15319 :             return false;
    1698       90843 :         if (stack.empty())
    1699           0 :             return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    1700       90843 :         if (!CastToBool(stack.back()))
    1701          44 :             return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    1702      106218 :     }
    1703             : 
    1704             :     // The CLEANSTACK check is only performed after potential P2SH evaluation,
    1705             :     // as the non-P2SH evaluation of a P2SH script will obviously not result in
    1706             :     // a clean stack (the P2SH inputs remain).
    1707     1180662 :     if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
    1708             :         // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
    1709             :         // would be possible, which is not a softfork (and P2SH should be one).
    1710      892932 :         assert((flags & SCRIPT_VERIFY_P2SH) != 0);
    1711      892932 :         if (stack.size() != 1) {
    1712          68 :             return set_error(serror, SCRIPT_ERR_CLEANSTACK);
    1713             :         }
    1714      892864 :     }
    1715             : 
    1716     1180594 :     return set_success(serror);
    1717     1338825 : }

Generated by: LCOV version 1.16