LCOV - code coverage report
Current view: top level - src/script - interpreter.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 98.2 % 1154 1133
Test Date: 2026-02-01 05:10:21 Functions: 100.0 % 68 68
Branches: 74.1 % 2015 1493

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-present 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 <tinyformat.h>
      14                 :             : #include <uint256.h>
      15                 :             : 
      16                 :             : typedef std::vector<unsigned char> valtype;
      17                 :             : 
      18                 :             : namespace {
      19                 :             : 
      20                 :     2021530 : inline bool set_success(ScriptError* ret)
      21                 :             : {
      22                 :     2021530 :     if (ret)
      23                 :     1735074 :         *ret = SCRIPT_ERR_OK;
      24                 :             :     return true;
      25                 :             : }
      26                 :             : 
      27                 :     2814835 : inline bool set_error(ScriptError* ret, const ScriptError serror)
      28                 :             : {
      29   [ -  -  -  -  :         803 :     if (ret)
          -  -  -  +  +  
          -  +  -  +  -  
                   +  - ]
      30                 :     2300735 :         *ret = serror;
      31                 :     2523344 :     return false;
      32                 :             : }
      33                 :             : 
      34                 :             : } // namespace
      35                 :             : 
      36                 :      817856 : bool CastToBool(const valtype& vch)
      37                 :             : {
      38   [ -  +  +  + ]:      824040 :     for (unsigned int i = 0; i < vch.size(); i++)
      39                 :             :     {
      40         [ +  + ]:      774592 :         if (vch[i] != 0)
      41                 :             :         {
      42                 :             :             // Can be negative zero
      43   [ +  +  +  + ]:      768408 :             if (i == vch.size()-1 && vch[i] == 0x80)
      44                 :             :                 return false;
      45                 :      768151 :             return true;
      46                 :             :         }
      47                 :             :     }
      48                 :             :     return false;
      49                 :             : }
      50                 :             : 
      51                 :             : /**
      52                 :             :  * Script is a stack machine (like Forth) that evaluates a predicate
      53                 :             :  * returning a bool indicating valid or not.  There are no loops.
      54                 :             :  */
      55                 :             : #define stacktop(i) (stack.at(size_t(int64_t(stack.size()) + int64_t{i})))
      56                 :             : #define altstacktop(i) (altstack.at(size_t(int64_t(altstack.size()) + int64_t{i})))
      57                 :     8886052 : static inline void popstack(std::vector<valtype>& stack)
      58                 :             : {
      59         [ -  + ]:     8886052 :     if (stack.empty())
      60         [ #  # ]:           0 :         throw std::runtime_error("popstack(): stack empty");
      61                 :     8886052 :     stack.pop_back();
      62                 :     8886052 : }
      63                 :             : 
      64                 :       70869 : bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
      65   [ -  +  +  + ]:       70869 :     if (vchPubKey.size() < CPubKey::COMPRESSED_SIZE) {
      66                 :             :         //  Non-canonical public key: too short
      67                 :             :         return false;
      68                 :             :     }
      69         [ +  + ]:       70516 :     if (vchPubKey[0] == 0x04) {
      70         [ +  + ]:        6093 :         if (vchPubKey.size() != CPubKey::SIZE) {
      71                 :             :             //  Non-canonical public key: invalid length for uncompressed key
      72                 :         258 :             return false;
      73                 :             :         }
      74   [ +  +  +  + ]:       64423 :     } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
      75         [ +  + ]:       63233 :         if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
      76                 :             :             //  Non-canonical public key: invalid length for compressed key
      77                 :         123 :             return false;
      78                 :             :         }
      79                 :             :     } else {
      80                 :             :         //  Non-canonical public key: neither compressed nor uncompressed
      81                 :             :         return false;
      82                 :             :     }
      83                 :             :     return true;
      84                 :             : }
      85                 :             : 
      86                 :       42373 : bool static IsCompressedPubKey(const valtype &vchPubKey) {
      87   [ -  +  +  + ]:       42373 :     if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
      88                 :             :         //  Non-canonical public key: invalid length for compressed key
      89                 :             :         return false;
      90                 :             :     }
      91   [ +  +  +  + ]:       35173 :     if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
      92                 :             :         //  Non-canonical public key: invalid prefix for compressed key
      93                 :         140 :         return false;
      94                 :             :     }
      95                 :             :     return true;
      96                 :             : }
      97                 :             : 
      98                 :             : /**
      99                 :             :  * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
     100                 :             :  * Where R and S are not negative (their first byte has its highest bit not set), and not
     101                 :             :  * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
     102                 :             :  * in which case a single 0 byte is necessary and even required).
     103                 :             :  *
     104                 :             :  * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
     105                 :             :  *
     106                 :             :  * This function is consensus-critical since BIP66.
     107                 :             :  */
     108                 :      225090 : bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
     109                 :             :     // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
     110                 :             :     // * total-length: 1-byte length descriptor of everything that follows,
     111                 :             :     //   excluding the sighash byte.
     112                 :             :     // * R-length: 1-byte length descriptor of the R value that follows.
     113                 :             :     // * R: arbitrary-length big-endian encoded R value. It must use the shortest
     114                 :             :     //   possible encoding for a positive integer (which means no null bytes at
     115                 :             :     //   the start, except a single one when the next byte has its highest bit set).
     116                 :             :     // * S-length: 1-byte length descriptor of the S value that follows.
     117                 :             :     // * S: arbitrary-length big-endian encoded S value. The same rules apply.
     118                 :             :     // * sighash: 1-byte value indicating what data is hashed (not part of the DER
     119                 :             :     //   signature)
     120                 :             : 
     121                 :             :     // Minimum and maximum size constraints.
     122   [ -  +  +  + ]:      225090 :     if (sig.size() < 9) return false;
     123         [ +  + ]:      224152 :     if (sig.size() > 73) return false;
     124                 :             : 
     125                 :             :     // A signature is of type 0x30 (compound).
     126         [ +  + ]:      224005 :     if (sig[0] != 0x30) return false;
     127                 :             : 
     128                 :             :     // Make sure the length covers the entire signature.
     129         [ +  + ]:      222498 :     if (sig[1] != sig.size() - 3) return false;
     130                 :             : 
     131                 :             :     // Extract the length of the R element.
     132                 :      213203 :     unsigned int lenR = sig[3];
     133                 :             : 
     134                 :             :     // Make sure the length of the S element is still inside the signature.
     135         [ +  + ]:      213203 :     if (5 + lenR >= sig.size()) return false;
     136                 :             : 
     137                 :             :     // Extract the length of the S element.
     138         [ +  + ]:      213075 :     unsigned int lenS = sig[5 + lenR];
     139                 :             : 
     140                 :             :     // Verify that the length of the signature matches the sum of the length
     141                 :             :     // of the elements.
     142         [ +  + ]:      213075 :     if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
     143                 :             : 
     144                 :             :     // Check whether the R element is an integer.
     145         [ +  + ]:      212926 :     if (sig[2] != 0x02) return false;
     146                 :             : 
     147                 :             :     // Zero-length integers are not allowed for R.
     148         [ +  + ]:      212790 :     if (lenR == 0) return false;
     149                 :             : 
     150                 :             :     // Negative numbers are not allowed for R.
     151         [ +  + ]:      212670 :     if (sig[4] & 0x80) return false;
     152                 :             : 
     153                 :             :     // Null bytes at the start of R are not allowed, unless R would
     154                 :             :     // otherwise be interpreted as a negative number.
     155   [ +  +  +  +  :      210241 :     if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
                   +  + ]
     156                 :             : 
     157                 :             :     // Check whether the S element is an integer.
     158         [ +  + ]:      209275 :     if (sig[lenR + 4] != 0x02) return false;
     159                 :             : 
     160                 :             :     // Zero-length integers are not allowed for S.
     161         [ +  + ]:      209136 :     if (lenS == 0) return false;
     162                 :             : 
     163                 :             :     // Negative numbers are not allowed for S.
     164         [ +  + ]:      209006 :     if (sig[lenR + 6] & 0x80) return false;
     165                 :             : 
     166                 :             :     // Null bytes at the start of S are not allowed, unless S would otherwise be
     167                 :             :     // interpreted as a negative number.
     168   [ +  +  +  +  :      208804 :     if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
                   +  + ]
     169                 :             : 
     170                 :             :     return true;
     171                 :             : }
     172                 :             : 
     173                 :       62385 : bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
     174         [ -  + ]:       62385 :     if (!IsValidSignatureEncoding(vchSig)) {
     175         [ -  - ]:       62385 :         return set_error(serror, SCRIPT_ERR_SIG_DER);
     176                 :             :     }
     177                 :             :     // https://bitcoin.stackexchange.com/a/12556:
     178                 :             :     //     Also note that inside transaction signatures, an extra hashtype byte
     179                 :             :     //     follows the actual signature data.
     180         [ -  + ]:       62385 :     std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
     181                 :             :     // If the S value is above the order of the curve divided by two, its
     182                 :             :     // complement modulo the order could have been used instead, which is
     183                 :             :     // one byte shorter when encoded correctly.
     184   [ +  -  +  + ]:       62385 :     if (!CPubKey::CheckLowS(vchSigCopy)) {
     185         [ +  - ]:       62740 :         return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
     186                 :             :     }
     187                 :             :     return true;
     188                 :       62385 : }
     189                 :             : 
     190                 :       65354 : bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
     191   [ -  +  +  - ]:       65354 :     if (vchSig.size() == 0) {
     192                 :             :         return false;
     193                 :             :     }
     194         [ +  + ]:       65354 :     unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
     195         [ +  + ]:       65354 :     if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
     196                 :         573 :         return false;
     197                 :             : 
     198                 :             :     return true;
     199                 :             : }
     200                 :             : 
     201                 :      220699 : bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, script_verify_flags flags, ScriptError* serror) {
     202                 :             :     // Empty signature. Not strictly DER encoded, but allowed to provide a
     203                 :             :     // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
     204   [ -  +  +  + ]:      220699 :     if (vchSig.size() == 0) {
     205                 :             :         return true;
     206                 :             :     }
     207   [ +  +  +  + ]:      200313 :     if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
     208         [ +  + ]:       16550 :         return set_error(serror, SCRIPT_ERR_SIG_DER);
     209   [ +  +  +  + ]:      183763 :     } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
     210                 :             :         // serror is set
     211                 :             :         return false;
     212   [ +  +  +  + ]:      183408 :     } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
     213         [ +  + ]:         573 :         return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
     214                 :             :     }
     215                 :             :     return true;
     216                 :             : }
     217                 :             : 
     218                 :      201981 : bool static CheckPubKeyEncoding(const valtype &vchPubKey, script_verify_flags flags, const SigVersion &sigversion, ScriptError* serror) {
     219   [ +  +  +  + ]:      201981 :     if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
     220         [ +  - ]:        1924 :         return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
     221                 :             :     }
     222                 :             :     // Only compressed keys are accepted in segwit
     223   [ +  +  +  +  :      200057 :     if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SigVersion::WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
                   +  + ]
     224         [ +  - ]:        7340 :         return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
     225                 :             :     }
     226                 :             :     return true;
     227                 :             : }
     228                 :             : 
     229                 :      230812 : int FindAndDelete(CScript& script, const CScript& b)
     230                 :             : {
     231                 :      230812 :     int nFound = 0;
     232   [ +  +  +  + ]:      356240 :     if (b.empty())
     233                 :             :         return nFound;
     234                 :      230811 :     CScript result;
     235   [ +  +  +  + ]:      692433 :     CScript::const_iterator pc = script.begin(), pc2 = script.begin(), end = script.end();
     236                 :     2660894 :     opcodetype opcode;
     237                 :     2660894 :     do
     238                 :             :     {
     239                 :     2660894 :         result.insert(result.end(), pc2, pc);
     240   [ +  +  +  +  :     5289999 :         while (static_cast<size_t>(end - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
             +  +  +  + ]
     241                 :             :         {
     242                 :       26291 :             pc = pc + b.size();
     243                 :       26291 :             ++nFound;
     244                 :             :         }
     245                 :     2660894 :         pc2 = pc;
     246                 :             :     }
     247   [ +  -  +  + ]:     2660894 :     while (script.GetOp(pc, opcode));
     248                 :             : 
     249         [ +  + ]:      230811 :     if (nFound > 0) {
     250                 :       19807 :         result.insert(result.end(), pc2, end);
     251                 :       19807 :         script = std::move(result);
     252                 :             :     }
     253                 :             : 
     254                 :      230811 :     return nFound;
     255                 :      230811 : }
     256                 :             : 
     257                 :             : namespace {
     258                 :             : /** A data type to abstract out the condition stack during script execution.
     259                 :             :  *
     260                 :             :  * Conceptually it acts like a vector of booleans, one for each level of nested
     261                 :             :  * IF/THEN/ELSE, indicating whether we're in the active or inactive branch of
     262                 :             :  * each.
     263                 :             :  *
     264                 :             :  * The elements on the stack cannot be observed individually; we only need to
     265                 :             :  * expose whether the stack is empty and whether or not any false values are
     266                 :             :  * present at all. To implement OP_ELSE, a toggle_top modifier is added, which
     267                 :             :  * flips the last value without returning it.
     268                 :             :  *
     269                 :             :  * This uses an optimized implementation that does not materialize the
     270                 :             :  * actual stack. Instead, it just stores the size of the would-be stack,
     271                 :             :  * and the position of the first false value in it.
     272                 :             :  */
     273                 :             : class ConditionStack {
     274                 :             : private:
     275                 :             :     //! A constant for m_first_false_pos to indicate there are no falses.
     276                 :             :     static constexpr uint32_t NO_FALSE = std::numeric_limits<uint32_t>::max();
     277                 :             : 
     278                 :             :     //! The size of the implied stack.
     279                 :             :     uint32_t m_stack_size = 0;
     280                 :             :     //! The position of the first false value on the implied stack, or NO_FALSE if all true.
     281                 :             :     uint32_t m_first_false_pos = NO_FALSE;
     282                 :             : 
     283                 :             : public:
     284                 :     1670967 :     bool empty() const { return m_stack_size == 0; }
     285                 :    11427649 :     bool all_true() const { return m_first_false_pos == NO_FALSE; }
     286                 :       71204 :     void push_back(bool f)
     287                 :             :     {
     288         [ +  + ]:       67944 :         if (m_first_false_pos == NO_FALSE && !f) {
     289                 :             :             // The stack consists of all true values, and a false is added.
     290                 :             :             // The first false value will appear at the current size.
     291                 :       39959 :             m_first_false_pos = m_stack_size;
     292                 :             :         }
     293                 :       71204 :         ++m_stack_size;
     294                 :       71204 :     }
     295                 :       52785 :     void pop_back()
     296                 :             :     {
     297         [ -  + ]:       52785 :         assert(m_stack_size > 0);
     298                 :       52785 :         --m_stack_size;
     299         [ +  + ]:       52785 :         if (m_first_false_pos == m_stack_size) {
     300                 :             :             // When popping off the first false value, everything becomes true.
     301                 :       20013 :             m_first_false_pos = NO_FALSE;
     302                 :             :         }
     303                 :       52785 :     }
     304                 :       57727 :     void toggle_top()
     305                 :             :     {
     306         [ -  + ]:       57727 :         assert(m_stack_size > 0);
     307         [ +  + ]:       57727 :         if (m_first_false_pos == NO_FALSE) {
     308                 :             :             // The current stack is all true values; the first false will be the top.
     309                 :       18575 :             m_first_false_pos = m_stack_size - 1;
     310         [ +  + ]:       39152 :         } else if (m_first_false_pos == m_stack_size - 1) {
     311                 :             :             // The top is the first false value; toggling it will make everything true.
     312                 :       35384 :             m_first_false_pos = NO_FALSE;
     313                 :             :         } else {
     314                 :             :             // There is a false value, but not on top. No action is needed as toggling
     315                 :             :             // anything but the first false value is unobservable.
     316                 :             :         }
     317                 :       57727 :     }
     318                 :             : };
     319                 :             : }
     320                 :             : 
     321                 :      188807 : static bool EvalChecksigPreTapscript(const valtype& vchSig, const valtype& vchPubKey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& fSuccess)
     322                 :             : {
     323         [ -  + ]:      188807 :     assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
     324                 :             : 
     325                 :             :     // Subset of script starting at the most recent codeseparator
     326                 :      188807 :     CScript scriptCode(pbegincodehash, pend);
     327                 :             : 
     328                 :             :     // Drop the signature in pre-segwit scripts but not segwit scripts
     329         [ +  + ]:      188807 :     if (sigversion == SigVersion::BASE) {
     330   [ -  +  +  - ]:      123335 :         int found = FindAndDelete(scriptCode, CScript() << vchSig);
     331   [ +  +  +  + ]:      123335 :         if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
     332         [ +  - ]:         114 :             return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
     333                 :             :     }
     334                 :             : 
     335   [ +  -  +  +  :      188693 :     if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
                   +  + ]
     336                 :             :         //serror is set
     337                 :       19606 :         return false;
     338                 :             :     }
     339         [ +  - ]:      169087 :     fSuccess = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
     340                 :             : 
     341   [ +  +  +  +  :      176185 :     if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
                   +  + ]
     342         [ +  + ]:      190364 :         return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
     343                 :             : 
     344                 :             :     return true;
     345                 :      188807 : }
     346                 :             : 
     347                 :      114496 : static bool EvalChecksigTapscript(const valtype& sig, const valtype& pubkey, ScriptExecutionData& execdata, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& success)
     348                 :             : {
     349         [ -  + ]:      114496 :     assert(sigversion == SigVersion::TAPSCRIPT);
     350                 :             : 
     351                 :             :     /*
     352                 :             :      *  The following validation sequence is consensus critical. Please note how --
     353                 :             :      *    upgradable public key versions precede other rules;
     354                 :             :      *    the script execution fails when using empty signature with invalid public key;
     355                 :             :      *    the script execution fails when using non-empty invalid signature.
     356                 :             :      */
     357                 :      114496 :     success = !sig.empty();
     358         [ +  + ]:      114496 :     if (success) {
     359                 :             :         // Implement the sigops/witnesssize ratio test.
     360                 :             :         // Passing with an upgradable public key version is also counted.
     361         [ -  + ]:       21211 :         assert(execdata.m_validation_weight_left_init);
     362                 :       21211 :         execdata.m_validation_weight_left -= VALIDATION_WEIGHT_PER_SIGOP_PASSED;
     363         [ +  + ]:       21211 :         if (execdata.m_validation_weight_left < 0) {
     364         [ +  - ]:          48 :             return set_error(serror, SCRIPT_ERR_TAPSCRIPT_VALIDATION_WEIGHT);
     365                 :             :         }
     366                 :             :     }
     367   [ -  +  +  + ]:      114448 :     if (pubkey.size() == 0) {
     368         [ +  - ]:         268 :         return set_error(serror, SCRIPT_ERR_TAPSCRIPT_EMPTY_PUBKEY);
     369         [ +  + ]:      114180 :     } else if (pubkey.size() == 32) {
     370   [ +  +  -  +  :      109766 :         if (success && !checker.CheckSchnorrSignature(sig, pubkey, sigversion, execdata, serror)) {
                   +  + ]
     371                 :         432 :             return false; // serror is set
     372                 :             :         }
     373                 :             :     } else {
     374                 :             :         /*
     375                 :             :          *  New public key version softforks should be defined before this `else` block.
     376                 :             :          *  Generally, the new code should not do anything but failing the script execution. To avoid
     377                 :             :          *  consensus bugs, it should not modify any existing values (including `success`).
     378                 :             :          */
     379         [ +  + ]:        4414 :         if ((flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_PUBKEYTYPE) != 0) {
     380         [ +  - ]:           8 :             return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_PUBKEYTYPE);
     381                 :             :         }
     382                 :             :     }
     383                 :             : 
     384                 :             :     return true;
     385                 :             : }
     386                 :             : 
     387                 :             : /** Helper for OP_CHECKSIG, OP_CHECKSIGVERIFY, and (in Tapscript) OP_CHECKSIGADD.
     388                 :             :  *
     389                 :             :  * A return value of false means the script fails entirely. When true is returned, the
     390                 :             :  * success variable indicates whether the signature check itself succeeded.
     391                 :             :  */
     392                 :      303303 : static bool EvalChecksig(const valtype& sig, const valtype& pubkey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, ScriptExecutionData& execdata, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& success)
     393                 :             : {
     394      [ +  +  - ]:      303303 :     switch (sigversion) {
     395                 :      188807 :     case SigVersion::BASE:
     396                 :      188807 :     case SigVersion::WITNESS_V0:
     397                 :      188807 :         return EvalChecksigPreTapscript(sig, pubkey, pbegincodehash, pend, flags, checker, sigversion, serror, success);
     398                 :      114496 :     case SigVersion::TAPSCRIPT:
     399                 :      114496 :         return EvalChecksigTapscript(sig, pubkey, execdata, flags, checker, sigversion, serror, success);
     400                 :             :     case SigVersion::TAPROOT:
     401                 :             :         // Key path spending in Taproot has no script, so this is unreachable.
     402                 :             :         break;
     403                 :             :     }
     404                 :           0 :     assert(false);
     405                 :             : }
     406                 :             : 
     407                 :     1756431 : bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror)
     408                 :             : {
     409   [ +  +  +  + ]:     1756431 :     static const CScriptNum bnZero(0);
     410   [ +  +  +  - ]:     1756431 :     static const CScriptNum bnOne(1);
     411                 :             :     // static const CScriptNum bnFalse(0);
     412                 :             :     // static const CScriptNum bnTrue(1);
     413   [ +  +  +  +  :     1757544 :     static const valtype vchFalse(0);
                   +  - ]
     414                 :             :     // static const valtype vchZero(0);
     415   [ +  +  +  +  :     1756908 :     static const valtype vchTrue(1, 1);
                   +  - ]
     416                 :             : 
     417                 :             :     // sigversion cannot be TAPROOT here, as it admits no script execution.
     418   [ +  +  -  + ]:     1756431 :     assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0 || sigversion == SigVersion::TAPSCRIPT);
     419                 :             : 
     420         [ +  + ]:     1756431 :     CScript::const_iterator pc = script.begin();
     421                 :     1756431 :     CScript::const_iterator pend = script.end();
     422         [ +  + ]:     1756431 :     CScript::const_iterator pbegincodehash = script.begin();
     423                 :     1756431 :     opcodetype opcode;
     424                 :     1756431 :     valtype vchPushValue;
     425                 :     1756431 :     ConditionStack vfExec;
     426                 :     1756431 :     std::vector<valtype> altstack;
     427         [ +  + ]:     1756431 :     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
     428   [ +  +  +  +  :     1756431 :     if ((sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) && script.size() > MAX_SCRIPT_SIZE) {
                   +  + ]
     429         [ +  - ]:         109 :         return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
     430                 :             :     }
     431                 :     1756322 :     int nOpCount = 0;
     432                 :     1756322 :     bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
     433                 :     1756322 :     uint32_t opcode_pos = 0;
     434                 :     1756322 :     execdata.m_codeseparator_pos = 0xFFFFFFFFUL;
     435                 :     1756322 :     execdata.m_codeseparator_pos_init = true;
     436                 :             : 
     437                 :     1756322 :     try
     438                 :             :     {
     439   [ +  +  +  + ]:    25972236 :         for (; pc < pend; ++opcode_pos) {
     440                 :    11427649 :             bool fExec = vfExec.all_true();
     441                 :             : 
     442                 :             :             //
     443                 :             :             // Read instruction
     444                 :             :             //
     445   [ +  -  +  + ]:    11427649 :             if (!script.GetOp(pc, opcode, vchPushValue))
     446         [ +  - ]:         273 :                 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
     447   [ -  +  +  + ]:    11427376 :             if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
     448         [ +  - ]:         562 :                 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
     449                 :             : 
     450         [ +  + ]:    11426814 :             if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) {
     451                 :             :                 // Note how OP_RESERVED does not count towards the opcode limit.
     452   [ +  +  +  + ]:     4481597 :                 if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT) {
     453         [ +  - ]:         474 :                     return set_error(serror, SCRIPT_ERR_OP_COUNT);
     454                 :             :                 }
     455                 :             :             }
     456                 :             : 
     457                 :    11426340 :             if (opcode == OP_CAT ||
     458                 :             :                 opcode == OP_SUBSTR ||
     459         [ +  + ]:    11426340 :                 opcode == OP_LEFT ||
     460         [ +  + ]:    11425179 :                 opcode == OP_RIGHT ||
     461         [ +  + ]:    11424975 :                 opcode == OP_INVERT ||
     462         [ +  + ]:    11424880 :                 opcode == OP_AND ||
     463         [ +  + ]:    11424790 :                 opcode == OP_OR ||
     464         [ +  + ]:    11424684 :                 opcode == OP_XOR ||
     465         [ +  + ]:    11424507 :                 opcode == OP_2MUL ||
     466         [ +  + ]:    11424306 :                 opcode == OP_2DIV ||
     467         [ +  + ]:    11424111 :                 opcode == OP_MUL ||
     468         [ +  + ]:    11423910 :                 opcode == OP_DIV ||
     469         [ +  + ]:    11423721 :                 opcode == OP_MOD ||
     470         [ +  + ]:    11423523 :                 opcode == OP_LSHIFT ||
     471                 :             :                 opcode == OP_RSHIFT)
     472         [ +  - ]:        3015 :                 return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes (CVE-2010-5137).
     473                 :             : 
     474                 :             :             // With SCRIPT_VERIFY_CONST_SCRIPTCODE, OP_CODESEPARATOR in non-segwit script is rejected even in an unexecuted branch
     475   [ +  +  +  +  :    11423325 :             if (opcode == OP_CODESEPARATOR && sigversion == SigVersion::BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
                   +  + ]
     476         [ +  - ]:         303 :                 return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
     477                 :             : 
     478   [ +  +  +  -  :    11423022 :             if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
                   +  + ]
     479   [ +  +  +  -  :     2276119 :                 if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
                   +  + ]
     480         [ +  - ]:        2822 :                     return set_error(serror, SCRIPT_ERR_MINIMALDATA);
     481                 :             :                 }
     482         [ +  - ]:     2273297 :                 stack.push_back(vchPushValue);
     483         [ +  + ]:      423333 :             } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
     484   [ +  +  +  +  :     8790044 :             switch (opcode)
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
             +  +  +  +  
                      + ]
     485                 :             :             {
     486                 :             :                 //
     487                 :             :                 // Push value
     488                 :             :                 //
     489                 :      527121 :                 case OP_1NEGATE:
     490                 :      527121 :                 case OP_1:
     491                 :      527121 :                 case OP_2:
     492                 :      527121 :                 case OP_3:
     493                 :      527121 :                 case OP_4:
     494                 :      527121 :                 case OP_5:
     495                 :      527121 :                 case OP_6:
     496                 :      527121 :                 case OP_7:
     497                 :      527121 :                 case OP_8:
     498                 :      527121 :                 case OP_9:
     499                 :      527121 :                 case OP_10:
     500                 :      527121 :                 case OP_11:
     501                 :      527121 :                 case OP_12:
     502                 :      527121 :                 case OP_13:
     503                 :      527121 :                 case OP_14:
     504                 :      527121 :                 case OP_15:
     505                 :      527121 :                 case OP_16:
     506                 :      527121 :                 {
     507                 :             :                     // ( -- value)
     508         [ +  - ]:      527121 :                     CScriptNum bn((int)opcode - (int)(OP_1 - 1));
     509   [ +  -  +  - ]:      527121 :                     stack.push_back(bn.getvch());
     510                 :             :                     // The result of these opcodes should always be the minimal way to push the data
     511                 :             :                     // they push, so no need for a CheckMinimalPush here.
     512                 :             :                 }
     513                 :      527121 :                 break;
     514                 :             : 
     515                 :             : 
     516                 :             :                 //
     517                 :             :                 // Control
     518                 :             :                 //
     519                 :             :                 case OP_NOP:
     520                 :             :                     break;
     521                 :             : 
     522                 :       12646 :                 case OP_CHECKLOCKTIMEVERIFY:
     523                 :       12646 :                 {
     524         [ +  + ]:       12646 :                     if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
     525                 :             :                         // not enabled; treat as a NOP2
     526                 :             :                         break;
     527                 :             :                     }
     528                 :             : 
     529   [ -  +  +  + ]:        6665 :                     if (stack.size() < 1)
     530         [ +  - ]:          76 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     531                 :             : 
     532                 :             :                     // Note that elsewhere numeric opcodes are limited to
     533                 :             :                     // operands in the range -2**31+1 to 2**31-1, however it is
     534                 :             :                     // legal for opcodes to produce results exceeding that
     535                 :             :                     // range. This limitation is implemented by CScriptNum's
     536                 :             :                     // default 4-byte limit.
     537                 :             :                     //
     538                 :             :                     // If we kept to that limit we'd have a year 2038 problem,
     539                 :             :                     // even though the nLockTime field in transactions
     540                 :             :                     // themselves is uint32 which only becomes meaningless
     541                 :             :                     // after the year 2106.
     542                 :             :                     //
     543                 :             :                     // Thus as a special case we tell CScriptNum to accept up
     544                 :             :                     // to 5-byte bignums, which are good until 2**39-1, well
     545                 :             :                     // beyond the 2**32-1 limit of the nLockTime field itself.
     546   [ +  -  +  + ]:        6589 :                     const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
     547                 :             : 
     548                 :             :                     // In the rare event that the argument may be < 0 due to
     549                 :             :                     // some arithmetic being done first, you can always use
     550                 :             :                     // 0 MAX CHECKLOCKTIMEVERIFY.
     551   [ +  +  +  + ]:       13034 :                     if (nLockTime < 0)
     552         [ +  - ]:         120 :                         return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
     553                 :             : 
     554                 :             :                     // Actually compare the specified lock time with the transaction.
     555   [ +  -  +  + ]:        6397 :                     if (!checker.CheckLockTime(nLockTime))
     556         [ +  - ]:        5713 :                         return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
     557                 :             : 
     558                 :             :                     break;
     559                 :             :                 }
     560                 :             : 
     561                 :       20168 :                 case OP_CHECKSEQUENCEVERIFY:
     562                 :       20168 :                 {
     563         [ +  + ]:       20168 :                     if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
     564                 :             :                         // not enabled; treat as a NOP3
     565                 :             :                         break;
     566                 :             :                     }
     567                 :             : 
     568   [ -  +  +  + ]:       13768 :                     if (stack.size() < 1)
     569         [ +  - ]:         163 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     570                 :             : 
     571                 :             :                     // nSequence, like nLockTime, is a 32-bit unsigned integer
     572                 :             :                     // field. See the comment in CHECKLOCKTIMEVERIFY regarding
     573                 :             :                     // 5-byte numeric operands.
     574   [ +  -  +  + ]:       13605 :                     const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
     575                 :             : 
     576                 :             :                     // In the rare event that the argument may be < 0 due to
     577                 :             :                     // some arithmetic being done first, you can always use
     578                 :             :                     // 0 MAX CHECKSEQUENCEVERIFY.
     579   [ +  +  +  + ]:       26830 :                     if (nSequence < 0)
     580         [ +  - ]:         216 :                         return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
     581                 :             : 
     582                 :             :                     // To provide for future soft-fork extensibility, if the
     583                 :             :                     // operand has the disabled lock-time flag set,
     584                 :             :                     // CHECKSEQUENCEVERIFY behaves as a NOP.
     585         [ +  + ]:       13199 :                     if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
     586                 :             :                         break;
     587                 :             : 
     588                 :             :                     // Compare the specified sequence number with the input.
     589   [ +  -  +  + ]:       12502 :                     if (!checker.CheckSequence(nSequence))
     590         [ +  - ]:        5882 :                         return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
     591                 :             : 
     592                 :             :                     break;
     593                 :             :                 }
     594                 :             : 
     595                 :        9978 :                 case OP_NOP1: case OP_NOP4: case OP_NOP5:
     596                 :        9978 :                 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
     597                 :        9978 :                 {
     598         [ +  + ]:        9978 :                     if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
     599         [ +  - ]:        2109 :                         return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
     600                 :             :                 }
     601                 :             :                 break;
     602                 :             : 
     603                 :       77821 :                 case OP_IF:
     604                 :       77821 :                 case OP_NOTIF:
     605                 :       77821 :                 {
     606                 :             :                     // <expression> if [statements] [else [statements]] endif
     607                 :       77821 :                     bool fValue = false;
     608         [ +  + ]:       77821 :                     if (fExec)
     609                 :             :                     {
     610   [ -  +  +  + ]:       74561 :                         if (stack.size() < 1)
     611         [ +  - ]:        2761 :                             return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     612         [ +  - ]:       71800 :                         valtype& vch = stacktop(-1);
     613                 :             :                         // Tapscript requires minimal IF/NOTIF inputs as a consensus rule.
     614         [ +  + ]:       71800 :                         if (sigversion == SigVersion::TAPSCRIPT) {
     615                 :             :                             // The input argument to the OP_IF and OP_NOTIF opcodes must be either
     616                 :             :                             // exactly 0 (the empty vector) or exactly 1 (the one-byte vector with value 1).
     617   [ -  +  +  +  :         886 :                             if (vch.size() > 1 || (vch.size() == 1 && vch[0] != 1)) {
             +  +  +  + ]
     618         [ +  - ]:           5 :                                 return set_error(serror, SCRIPT_ERR_TAPSCRIPT_MINIMALIF);
     619                 :             :                             }
     620                 :             :                         }
     621                 :             :                         // Under witness v0 rules it is only a policy rule, enabled through SCRIPT_VERIFY_MINIMALIF.
     622   [ +  +  +  + ]:       71795 :                         if (sigversion == SigVersion::WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
     623   [ -  +  +  + ]:        6328 :                             if (vch.size() > 1)
     624         [ +  - ]:        1279 :                                 return set_error(serror, SCRIPT_ERR_MINIMALIF);
     625   [ +  +  +  + ]:        5049 :                             if (vch.size() == 1 && vch[0] != 1)
     626         [ +  - ]:        2572 :                                 return set_error(serror, SCRIPT_ERR_MINIMALIF);
     627                 :             :                         }
     628         [ +  - ]:       67944 :                         fValue = CastToBool(vch);
     629         [ +  + ]:       67944 :                         if (opcode == OP_NOTIF)
     630                 :        8571 :                             fValue = !fValue;
     631         [ +  - ]:       67944 :                         popstack(stack);
     632                 :             :                     }
     633         [ +  + ]:       71204 :                     vfExec.push_back(fValue);
     634                 :             :                 }
     635                 :       71204 :                 break;
     636                 :             : 
     637                 :       58398 :                 case OP_ELSE:
     638                 :       58398 :                 {
     639         [ +  + ]:       58398 :                     if (vfExec.empty())
     640         [ +  - ]:         671 :                         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
     641                 :       57727 :                     vfExec.toggle_top();
     642                 :             :                 }
     643                 :       57727 :                 break;
     644                 :             : 
     645                 :       54100 :                 case OP_ENDIF:
     646                 :       54100 :                 {
     647         [ +  + ]:       54100 :                     if (vfExec.empty())
     648         [ +  - ]:        1315 :                         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
     649                 :       52785 :                     vfExec.pop_back();
     650                 :             :                 }
     651                 :       52785 :                 break;
     652                 :             : 
     653                 :        9054 :                 case OP_VERIFY:
     654                 :        9054 :                 {
     655                 :             :                     // (true -- ) or
     656                 :             :                     // (false -- false) and return
     657   [ -  +  +  + ]:        9054 :                     if (stack.size() < 1)
     658         [ +  - ]:          98 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     659   [ +  -  +  - ]:        8956 :                     bool fValue = CastToBool(stacktop(-1));
     660         [ +  + ]:        8956 :                     if (fValue)
     661         [ +  - ]:        8729 :                         popstack(stack);
     662                 :             :                     else
     663         [ +  - ]:         227 :                         return set_error(serror, SCRIPT_ERR_VERIFY);
     664                 :             :                 }
     665                 :             :                 break;
     666                 :             : 
     667                 :        1431 :                 case OP_RETURN:
     668                 :        1431 :                 {
     669         [ +  - ]:        1431 :                     return set_error(serror, SCRIPT_ERR_OP_RETURN);
     670                 :             :                 }
     671                 :        9511 :                 break;
     672                 :             : 
     673                 :             : 
     674                 :             :                 //
     675                 :             :                 // Stack ops
     676                 :             :                 //
     677                 :        9511 :                 case OP_TOALTSTACK:
     678                 :        9511 :                 {
     679   [ -  +  +  + ]:        9511 :                     if (stack.size() < 1)
     680         [ +  - ]:         106 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     681   [ +  -  +  - ]:        9405 :                     altstack.push_back(stacktop(-1));
     682         [ +  - ]:        9405 :                     popstack(stack);
     683                 :             :                 }
     684                 :             :                 break;
     685                 :             : 
     686                 :        5596 :                 case OP_FROMALTSTACK:
     687                 :        5596 :                 {
     688   [ -  +  +  + ]:        5596 :                     if (altstack.size() < 1)
     689         [ +  - ]:         289 :                         return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
     690   [ +  -  +  - ]:        5307 :                     stack.push_back(altstacktop(-1));
     691         [ +  - ]:        5307 :                     popstack(altstack);
     692                 :             :                 }
     693                 :             :                 break;
     694                 :             : 
     695                 :       42722 :                 case OP_2DROP:
     696                 :       42722 :                 {
     697                 :             :                     // (x1 x2 -- )
     698   [ -  +  +  + ]:       42722 :                     if (stack.size() < 2)
     699         [ +  - ]:         195 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     700         [ +  - ]:       42527 :                     popstack(stack);
     701         [ +  - ]:       42527 :                     popstack(stack);
     702                 :             :                 }
     703                 :             :                 break;
     704                 :             : 
     705                 :       54355 :                 case OP_2DUP:
     706                 :       54355 :                 {
     707                 :             :                     // (x1 x2 -- x1 x2 x1 x2)
     708   [ -  +  +  + ]:       54355 :                     if (stack.size() < 2)
     709         [ +  - ]:         500 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     710   [ +  -  +  - ]:       53855 :                     valtype vch1 = stacktop(-2);
     711   [ -  +  +  -  :       53855 :                     valtype vch2 = stacktop(-1);
                   +  - ]
     712         [ +  - ]:       53855 :                     stack.push_back(vch1);
     713         [ +  - ]:       53855 :                     stack.push_back(vch2);
     714                 :       53855 :                 }
     715                 :       53855 :                 break;
     716                 :             : 
     717                 :      321353 :                 case OP_3DUP:
     718                 :      321353 :                 {
     719                 :             :                     // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
     720   [ -  +  +  + ]:      321353 :                     if (stack.size() < 3)
     721         [ +  - ]:         669 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     722   [ +  -  +  - ]:      320684 :                     valtype vch1 = stacktop(-3);
     723   [ -  +  +  -  :      320684 :                     valtype vch2 = stacktop(-2);
                   +  - ]
     724   [ -  +  +  -  :      320684 :                     valtype vch3 = stacktop(-1);
                   +  - ]
     725         [ +  - ]:      320684 :                     stack.push_back(vch1);
     726         [ +  - ]:      320684 :                     stack.push_back(vch2);
     727         [ +  - ]:      320684 :                     stack.push_back(vch3);
     728                 :      320684 :                 }
     729                 :      320684 :                 break;
     730                 :             : 
     731                 :         997 :                 case OP_2OVER:
     732                 :         997 :                 {
     733                 :             :                     // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
     734   [ -  +  +  + ]:         997 :                     if (stack.size() < 4)
     735         [ +  - ]:         483 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     736   [ +  -  +  - ]:         514 :                     valtype vch1 = stacktop(-4);
     737   [ -  +  +  -  :         514 :                     valtype vch2 = stacktop(-3);
                   +  - ]
     738         [ +  - ]:         514 :                     stack.push_back(vch1);
     739         [ +  - ]:         514 :                     stack.push_back(vch2);
     740                 :         514 :                 }
     741                 :         514 :                 break;
     742                 :             : 
     743                 :        3532 :                 case OP_2ROT:
     744                 :        3532 :                 {
     745                 :             :                     // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
     746   [ -  +  +  + ]:        3532 :                     if (stack.size() < 6)
     747         [ +  - ]:         191 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     748   [ +  -  +  - ]:        3341 :                     valtype vch1 = stacktop(-6);
     749   [ -  +  +  -  :        3341 :                     valtype vch2 = stacktop(-5);
                   +  - ]
     750                 :        3341 :                     stack.erase(stack.end()-6, stack.end()-4);
     751         [ +  - ]:        3341 :                     stack.push_back(vch1);
     752         [ +  - ]:        3341 :                     stack.push_back(vch2);
     753                 :        3341 :                 }
     754                 :        3341 :                 break;
     755                 :             : 
     756                 :        1024 :                 case OP_2SWAP:
     757                 :        1024 :                 {
     758                 :             :                     // (x1 x2 x3 x4 -- x3 x4 x1 x2)
     759   [ -  +  +  + ]:        1024 :                     if (stack.size() < 4)
     760         [ +  - ]:         510 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     761   [ +  -  -  +  :         514 :                     swap(stacktop(-4), stacktop(-2));
                   +  - ]
     762   [ -  +  +  -  :         514 :                     swap(stacktop(-3), stacktop(-1));
             -  +  +  - ]
     763                 :             :                 }
     764                 :         514 :                 break;
     765                 :             : 
     766                 :        1338 :                 case OP_IFDUP:
     767                 :        1338 :                 {
     768                 :             :                     // (x - 0 | x x)
     769   [ -  +  +  + ]:        1338 :                     if (stack.size() < 1)
     770         [ +  - ]:         203 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     771   [ +  -  +  - ]:        1135 :                     valtype vch = stacktop(-1);
     772   [ +  -  +  + ]:        1135 :                     if (CastToBool(vch))
     773         [ +  - ]:         834 :                         stack.push_back(vch);
     774                 :           0 :                 }
     775                 :        1135 :                 break;
     776                 :             : 
     777                 :       18624 :                 case OP_DEPTH:
     778                 :       18624 :                 {
     779                 :             :                     // -- stacksize
     780   [ -  +  +  - ]:       18624 :                     CScriptNum bn(stack.size());
     781   [ +  -  +  - ]:       18624 :                     stack.push_back(bn.getvch());
     782                 :             :                 }
     783                 :       18624 :                 break;
     784                 :             : 
     785                 :       44453 :                 case OP_DROP:
     786                 :       44453 :                 {
     787                 :             :                     // (x -- )
     788   [ -  +  +  + ]:       44453 :                     if (stack.size() < 1)
     789         [ +  - ]:         187 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     790         [ +  - ]:       44266 :                     popstack(stack);
     791                 :             :                 }
     792                 :             :                 break;
     793                 :             : 
     794                 :      152780 :                 case OP_DUP:
     795                 :      152780 :                 {
     796                 :             :                     // (x -- x x)
     797   [ -  +  +  + ]:      152780 :                     if (stack.size() < 1)
     798         [ +  + ]:       76836 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     799   [ +  -  +  - ]:       75944 :                     valtype vch = stacktop(-1);
     800         [ +  - ]:       75944 :                     stack.push_back(vch);
     801                 :           0 :                 }
     802                 :       75944 :                 break;
     803                 :             : 
     804                 :        1153 :                 case OP_NIP:
     805                 :        1153 :                 {
     806                 :             :                     // (x1 x2 -- x2)
     807   [ -  +  +  + ]:        1153 :                     if (stack.size() < 2)
     808         [ +  - ]:         380 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     809                 :         773 :                     stack.erase(stack.end() - 2);
     810                 :             :                 }
     811                 :             :                 break;
     812                 :             : 
     813                 :        1202 :                 case OP_OVER:
     814                 :        1202 :                 {
     815                 :             :                     // (x1 x2 -- x1 x2 x1)
     816   [ -  +  +  + ]:        1202 :                     if (stack.size() < 2)
     817         [ +  - ]:         487 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     818   [ +  -  +  - ]:         715 :                     valtype vch = stacktop(-2);
     819         [ +  - ]:         715 :                     stack.push_back(vch);
     820                 :           0 :                 }
     821                 :         715 :                 break;
     822                 :             : 
     823                 :        6376 :                 case OP_PICK:
     824                 :        6376 :                 case OP_ROLL:
     825                 :        6376 :                 {
     826                 :             :                     // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
     827                 :             :                     // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
     828   [ -  +  +  + ]:        6376 :                     if (stack.size() < 2)
     829         [ +  - ]:         589 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     830   [ +  -  +  + ]:        5787 :                     int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
     831         [ +  - ]:        5526 :                     popstack(stack);
     832   [ +  +  +  + ]:       10661 :                     if (n < 0 || n >= (int)stack.size())
     833         [ +  - ]:         965 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     834   [ +  -  +  - ]:        4561 :                     valtype vch = stacktop(-n-1);
     835         [ +  + ]:        4561 :                     if (opcode == OP_ROLL)
     836                 :        2127 :                         stack.erase(stack.end()-n-1);
     837         [ +  - ]:        4561 :                     stack.push_back(vch);
     838                 :           0 :                 }
     839                 :        4561 :                 break;
     840                 :             : 
     841                 :        3157 :                 case OP_ROT:
     842                 :        3157 :                 {
     843                 :             :                     // (x1 x2 x3 -- x2 x3 x1)
     844                 :             :                     //  x2 x1 x3  after first swap
     845                 :             :                     //  x2 x3 x1  after second swap
     846   [ -  +  +  + ]:        3157 :                     if (stack.size() < 3)
     847         [ +  - ]:         496 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     848   [ +  -  -  +  :        2661 :                     swap(stacktop(-3), stacktop(-2));
                   +  - ]
     849   [ -  +  +  -  :        2661 :                     swap(stacktop(-2), stacktop(-1));
             -  +  +  - ]
     850                 :             :                 }
     851                 :        2661 :                 break;
     852                 :             : 
     853                 :        4713 :                 case OP_SWAP:
     854                 :        4713 :                 {
     855                 :             :                     // (x1 x2 -- x2 x1)
     856   [ -  +  +  + ]:        4713 :                     if (stack.size() < 2)
     857         [ +  - ]:         501 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     858   [ +  -  -  +  :        4212 :                     swap(stacktop(-2), stacktop(-1));
                   +  - ]
     859                 :             :                 }
     860                 :        4212 :                 break;
     861                 :             : 
     862                 :       10267 :                 case OP_TUCK:
     863                 :       10267 :                 {
     864                 :             :                     // (x1 x2 -- x2 x1 x2)
     865   [ -  +  +  + ]:       10267 :                     if (stack.size() < 2)
     866         [ +  - ]:         516 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     867   [ +  -  +  - ]:        9751 :                     valtype vch = stacktop(-1);
     868         [ +  - ]:        9751 :                     stack.insert(stack.end()-2, vch);
     869                 :           0 :                 }
     870                 :        9751 :                 break;
     871                 :             : 
     872                 :             : 
     873                 :        8396 :                 case OP_SIZE:
     874                 :        8396 :                 {
     875                 :             :                     // (in -- in size)
     876   [ -  +  +  + ]:        8396 :                     if (stack.size() < 1)
     877         [ +  - ]:         189 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     878   [ +  -  -  +  :        8207 :                     CScriptNum bn(stacktop(-1).size());
                   +  - ]
     879   [ +  -  +  - ]:        8207 :                     stack.push_back(bn.getvch());
     880                 :             :                 }
     881                 :        8207 :                 break;
     882                 :             : 
     883                 :             : 
     884                 :             :                 //
     885                 :             :                 // Bitwise logic
     886                 :             :                 //
     887                 :      199227 :                 case OP_EQUAL:
     888                 :      199227 :                 case OP_EQUALVERIFY:
     889                 :             :                 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
     890                 :      199227 :                 {
     891                 :             :                     // (x1 x2 - bool)
     892   [ -  +  +  + ]:      199227 :                     if (stack.size() < 2)
     893         [ +  - ]:         781 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     894         [ +  - ]:      198446 :                     valtype& vch1 = stacktop(-2);
     895   [ -  +  +  - ]:      198446 :                     valtype& vch2 = stacktop(-1);
     896                 :      198446 :                     bool fEqual = (vch1 == vch2);
     897                 :             :                     // OP_NOTEQUAL is disabled because it would be too easy to say
     898                 :             :                     // something like n != 1 and have some wiseguy pass in 1 with extra
     899                 :             :                     // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
     900                 :             :                     //if (opcode == OP_NOTEQUAL)
     901                 :             :                     //    fEqual = !fEqual;
     902         [ +  - ]:      198446 :                     popstack(stack);
     903         [ +  - ]:      198446 :                     popstack(stack);
     904   [ +  +  +  - ]:      202996 :                     stack.push_back(fEqual ? vchTrue : vchFalse);
     905         [ +  + ]:      198446 :                     if (opcode == OP_EQUALVERIFY)
     906                 :             :                     {
     907         [ +  + ]:       80224 :                         if (fEqual)
     908         [ +  - ]:       78192 :                             popstack(stack);
     909                 :             :                         else
     910         [ +  - ]:        2032 :                             return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
     911                 :             :                     }
     912                 :             :                 }
     913                 :             :                 break;
     914                 :             : 
     915                 :             : 
     916                 :             :                 //
     917                 :             :                 // Numeric
     918                 :             :                 //
     919                 :     6288460 :                 case OP_1ADD:
     920                 :     6288460 :                 case OP_1SUB:
     921                 :     6288460 :                 case OP_NEGATE:
     922                 :     6288460 :                 case OP_ABS:
     923                 :     6288460 :                 case OP_NOT:
     924                 :     6288460 :                 case OP_0NOTEQUAL:
     925                 :     6288460 :                 {
     926                 :             :                     // (in -- out)
     927   [ -  +  +  + ]:     6288460 :                     if (stack.size() < 1)
     928         [ +  - ]:         579 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     929   [ +  -  +  + ]:     6287881 :                     CScriptNum bn(stacktop(-1), fRequireMinimal);
     930   [ +  +  +  +  :     6284505 :                     switch (opcode)
                +  +  - ]
     931                 :             :                     {
     932                 :        1823 :                     case OP_1ADD:       bn += bnOne; break;
     933                 :         814 :                     case OP_1SUB:       bn -= bnOne; break;
     934                 :        1028 :                     case OP_NEGATE:     bn = -bn; break;
     935   [ +  +  +  + ]:        2570 :                     case OP_ABS:        if (bn < bnZero) bn = -bn; break;
     936                 :       18352 :                     case OP_NOT:        bn = (bn == bnZero); break;
     937                 :     6261203 :                     case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
     938                 :           0 :                     default:            assert(!"invalid opcode"); break;
     939                 :             :                     }
     940         [ +  - ]:     6284505 :                     popstack(stack);
     941   [ +  -  +  - ]:     6284505 :                     stack.push_back(bn.getvch());
     942                 :             :                 }
     943                 :     6284505 :                 break;
     944                 :             : 
     945                 :       49862 :                 case OP_ADD:
     946                 :       49862 :                 case OP_SUB:
     947                 :       49862 :                 case OP_BOOLAND:
     948                 :       49862 :                 case OP_BOOLOR:
     949                 :       49862 :                 case OP_NUMEQUAL:
     950                 :       49862 :                 case OP_NUMEQUALVERIFY:
     951                 :       49862 :                 case OP_NUMNOTEQUAL:
     952                 :       49862 :                 case OP_LESSTHAN:
     953                 :       49862 :                 case OP_GREATERTHAN:
     954                 :       49862 :                 case OP_LESSTHANOREQUAL:
     955                 :       49862 :                 case OP_GREATERTHANOREQUAL:
     956                 :       49862 :                 case OP_MIN:
     957                 :       49862 :                 case OP_MAX:
     958                 :       49862 :                 {
     959                 :             :                     // (x1 x2 -- out)
     960   [ -  +  +  + ]:       49862 :                     if (stack.size() < 2)
     961         [ +  - ]:        2504 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
     962   [ +  -  +  + ]:       47358 :                     CScriptNum bn1(stacktop(-2), fRequireMinimal);
     963   [ -  +  +  -  :       44685 :                     CScriptNum bn2(stacktop(-1), fRequireMinimal);
                   +  + ]
     964   [ +  +  +  +  :       43050 :                     CScriptNum bn(0);
          +  +  +  +  +  
             +  +  +  +  
                      - ]
     965   [ +  +  +  +  :       43050 :                     switch (opcode)
          +  +  +  +  +  
             +  +  +  +  
                      - ]
     966                 :             :                     {
     967                 :        8911 :                     case OP_ADD:
     968                 :        8911 :                         bn = bn1 + bn2;
     969                 :        8911 :                         break;
     970                 :             : 
     971                 :        1412 :                     case OP_SUB:
     972                 :        1412 :                         bn = bn1 - bn2;
     973                 :        1412 :                         break;
     974                 :             : 
     975   [ +  +  +  + ]:        7165 :                     case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
     976   [ +  +  +  + ]:        2852 :                     case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
     977                 :        8906 :                     case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
     978                 :        1231 :                     case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
     979                 :        1285 :                     case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
     980         [ +  + ]:        4112 :                     case OP_LESSTHAN:            bn = (bn1 < bn2); break;
     981         [ +  + ]:        4112 :                     case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
     982         [ +  + ]:        4112 :                     case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
     983         [ +  + ]:        4112 :                     case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
     984   [ +  +  +  + ]:        3598 :                     case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
     985   [ +  +  +  + ]:        3598 :                     case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
     986                 :           0 :                     default:                     assert(!"invalid opcode"); break;
     987                 :             :                     }
     988         [ +  - ]:       43050 :                     popstack(stack);
     989         [ +  - ]:       43050 :                     popstack(stack);
     990   [ +  -  +  - ]:       43050 :                     stack.push_back(bn.getvch());
     991                 :             : 
     992         [ +  + ]:       43050 :                     if (opcode == OP_NUMEQUALVERIFY)
     993                 :             :                     {
     994   [ -  +  +  -  :        1231 :                         if (CastToBool(stacktop(-1)))
             +  -  +  + ]
     995         [ +  - ]:        1031 :                             popstack(stack);
     996                 :             :                         else
     997         [ +  - ]:         200 :                             return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
     998                 :             :                     }
     999                 :             :                 }
    1000                 :             :                 break;
    1001                 :             : 
    1002                 :        3503 :                 case OP_WITHIN:
    1003                 :        3503 :                 {
    1004                 :             :                     // (x min max -- out)
    1005   [ -  +  +  + ]:        3503 :                     if (stack.size() < 3)
    1006         [ +  - ]:         193 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1007   [ +  -  +  + ]:        3310 :                     CScriptNum bn1(stacktop(-3), fRequireMinimal);
    1008   [ -  +  +  -  :        3179 :                     CScriptNum bn2(stacktop(-2), fRequireMinimal);
                   +  + ]
    1009   [ -  +  +  -  :        3043 :                     CScriptNum bn3(stacktop(-1), fRequireMinimal);
                   +  + ]
    1010   [ +  +  +  +  :        8488 :                     bool fValue = (bn2 <= bn1 && bn1 < bn3);
                   +  + ]
    1011         [ +  - ]:        2915 :                     popstack(stack);
    1012         [ +  - ]:        2915 :                     popstack(stack);
    1013         [ +  - ]:        2915 :                     popstack(stack);
    1014   [ +  +  +  - ]:        4457 :                     stack.push_back(fValue ? vchTrue : vchFalse);
    1015                 :             :                 }
    1016                 :             :                 break;
    1017                 :             : 
    1018                 :             : 
    1019                 :             :                 //
    1020                 :             :                 // Crypto
    1021                 :             :                 //
    1022                 :      152898 :                 case OP_RIPEMD160:
    1023                 :      152898 :                 case OP_SHA1:
    1024                 :      152898 :                 case OP_SHA256:
    1025                 :      152898 :                 case OP_HASH160:
    1026                 :      152898 :                 case OP_HASH256:
    1027                 :      152898 :                 {
    1028                 :             :                     // (in -- hash)
    1029   [ -  +  +  + ]:      152898 :                     if (stack.size() < 1)
    1030         [ +  + ]:        8140 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1031         [ +  - ]:      144758 :                     valtype& vch = stacktop(-1);
    1032   [ +  +  +  +  :      148202 :                     valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
                   +  - ]
    1033         [ +  + ]:      144758 :                     if (opcode == OP_RIPEMD160)
    1034   [ +  -  +  -  :        2654 :                         CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
                   +  - ]
    1035         [ +  + ]:      143431 :                     else if (opcode == OP_SHA1)
    1036   [ +  -  +  -  :       22676 :                         CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
                   +  - ]
    1037         [ +  + ]:      132093 :                     else if (opcode == OP_SHA256)
    1038   [ +  -  +  -  :        4078 :                         CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
                   +  - ]
    1039         [ +  + ]:      130054 :                     else if (opcode == OP_HASH160)
    1040   [ +  -  -  +  :      128649 :                         CHash160().Write(vch).Finalize(vchHash);
          +  -  -  +  +  
                      - ]
    1041         [ +  - ]:        1405 :                     else if (opcode == OP_HASH256)
    1042   [ +  -  -  +  :        1405 :                         CHash256().Write(vch).Finalize(vchHash);
          +  -  -  +  +  
                      - ]
    1043         [ +  - ]:      144758 :                     popstack(stack);
    1044         [ +  - ]:      144758 :                     stack.push_back(vchHash);
    1045                 :           0 :                 }
    1046                 :      144758 :                 break;
    1047                 :             : 
    1048                 :        2825 :                 case OP_CODESEPARATOR:
    1049                 :        2825 :                 {
    1050                 :             :                     // If SCRIPT_VERIFY_CONST_SCRIPTCODE flag is set, use of OP_CODESEPARATOR is rejected in pre-segwit
    1051                 :             :                     // script, even in an unexecuted branch (this is checked above the opcode case statement).
    1052                 :             : 
    1053                 :             :                     // Hash starts after the code separator
    1054                 :        2825 :                     pbegincodehash = pc;
    1055                 :        2825 :                     execdata.m_codeseparator_pos = opcode_pos;
    1056                 :             :                 }
    1057                 :        2825 :                 break;
    1058                 :             : 
    1059                 :      216339 :                 case OP_CHECKSIG:
    1060                 :      216339 :                 case OP_CHECKSIGVERIFY:
    1061                 :      216339 :                 {
    1062                 :             :                     // (sig pubkey -- bool)
    1063   [ -  +  +  + ]:      216339 :                     if (stack.size() < 2)
    1064         [ +  + ]:        9326 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1065                 :             : 
    1066         [ +  - ]:      207013 :                     valtype& vchSig    = stacktop(-2);
    1067   [ -  +  +  - ]:      207013 :                     valtype& vchPubKey = stacktop(-1);
    1068                 :             : 
    1069                 :      207013 :                     bool fSuccess = true;
    1070   [ +  -  +  + ]:      207013 :                     if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, fSuccess)) return false;
    1071         [ +  - ]:      185389 :                     popstack(stack);
    1072         [ +  - ]:      185389 :                     popstack(stack);
    1073   [ +  +  +  - ]:      207161 :                     stack.push_back(fSuccess ? vchTrue : vchFalse);
    1074         [ +  + ]:      185389 :                     if (opcode == OP_CHECKSIGVERIFY)
    1075                 :             :                     {
    1076         [ +  + ]:       48897 :                         if (fSuccess)
    1077         [ +  - ]:       48710 :                             popstack(stack);
    1078                 :             :                         else
    1079         [ +  - ]:         187 :                             return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
    1080                 :             :                     }
    1081                 :             :                 }
    1082                 :             :                 break;
    1083                 :             : 
    1084                 :       96722 :                 case OP_CHECKSIGADD:
    1085                 :       96722 :                 {
    1086                 :             :                     // OP_CHECKSIGADD is only available in Tapscript
    1087   [ +  +  +  + ]:       96722 :                     if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
    1088                 :             : 
    1089                 :             :                     // (sig num pubkey -- num)
    1090   [ -  +  +  +  :       96293 :                     if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                   +  - ]
    1091                 :             : 
    1092         [ +  - ]:       96292 :                     const valtype& sig = stacktop(-3);
    1093   [ -  +  +  -  :       96292 :                     const CScriptNum num(stacktop(-2), fRequireMinimal);
                   +  + ]
    1094   [ -  +  +  - ]:       96290 :                     const valtype& pubkey = stacktop(-1);
    1095                 :             : 
    1096                 :       96290 :                     bool success = true;
    1097   [ +  -  +  + ]:       96290 :                     if (!EvalChecksig(sig, pubkey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, success)) return false;
    1098         [ +  - ]:       95878 :                     popstack(stack);
    1099         [ +  - ]:       95878 :                     popstack(stack);
    1100         [ +  - ]:       95878 :                     popstack(stack);
    1101   [ +  +  +  -  :      188419 :                     stack.push_back((num + (success ? 1 : 0)).getvch());
                   +  - ]
    1102                 :             :                 }
    1103                 :       95878 :                 break;
    1104                 :             : 
    1105                 :      165019 :                 case OP_CHECKMULTISIG:
    1106                 :      165019 :                 case OP_CHECKMULTISIGVERIFY:
    1107                 :      165019 :                 {
    1108   [ +  +  +  - ]:      165019 :                     if (sigversion == SigVersion::TAPSCRIPT) return set_error(serror, SCRIPT_ERR_TAPSCRIPT_CHECKMULTISIG);
    1109                 :             : 
    1110                 :             :                     // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
    1111                 :             : 
    1112                 :      165017 :                     int i = 1;
    1113   [ -  +  +  + ]:      165017 :                     if ((int)stack.size() < i)
    1114         [ +  - ]:         124 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1115                 :             : 
    1116   [ +  -  +  + ]:      164893 :                     int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
    1117         [ +  + ]:      164658 :                     if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
    1118         [ +  - ]:         321 :                         return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
    1119                 :      164337 :                     nOpCount += nKeysCount;
    1120         [ +  + ]:      164337 :                     if (nOpCount > MAX_OPS_PER_SCRIPT)
    1121         [ +  - ]:         386 :                         return set_error(serror, SCRIPT_ERR_OP_COUNT);
    1122                 :      163951 :                     int ikey = ++i;
    1123                 :             :                     // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
    1124                 :             :                     // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
    1125                 :      163951 :                     int ikey2 = nKeysCount + 2;
    1126                 :      163951 :                     i += nKeysCount;
    1127   [ -  +  +  + ]:      163951 :                     if ((int)stack.size() < i)
    1128         [ +  - ]:         138 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1129                 :             : 
    1130   [ +  -  +  + ]:      163813 :                     int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
    1131         [ +  + ]:      163441 :                     if (nSigsCount < 0 || nSigsCount > nKeysCount)
    1132         [ +  - ]:         303 :                         return set_error(serror, SCRIPT_ERR_SIG_COUNT);
    1133                 :      163138 :                     int isig = ++i;
    1134                 :      163138 :                     i += nSigsCount;
    1135   [ -  +  +  + ]:      163138 :                     if ((int)stack.size() < i)
    1136         [ +  + ]:         344 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1137                 :             : 
    1138                 :             :                     // Subset of script starting at the most recent codeseparator
    1139                 :      162794 :                     CScript scriptCode(pbegincodehash, pend);
    1140                 :             : 
    1141                 :             :                     // Drop the signature in pre-segwit scripts but not segwit scripts
    1142         [ +  + ]:      227162 :                     for (int k = 0; k < nSigsCount; k++)
    1143                 :             :                     {
    1144   [ -  +  +  - ]:       64541 :                         valtype& vchSig = stacktop(-isig-k);
    1145         [ +  + ]:       64541 :                         if (sigversion == SigVersion::BASE) {
    1146   [ -  +  +  - ]:       57442 :                             int found = FindAndDelete(scriptCode, CScript() << vchSig);
    1147   [ +  +  +  + ]:       57442 :                             if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
    1148         [ +  - ]:         173 :                                 return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
    1149                 :             :                         }
    1150                 :             :                     }
    1151                 :             : 
    1152                 :             :                     bool fSuccess = true;
    1153         [ +  + ]:      186251 :                     while (fSuccess && nSigsCount > 0)
    1154                 :             :                     {
    1155   [ -  +  +  - ]:       29258 :                         valtype& vchSig    = stacktop(-isig);
    1156   [ -  +  +  - ]:       29258 :                         valtype& vchPubKey = stacktop(-ikey);
    1157                 :             : 
    1158                 :             :                         // Note how this makes the exact order of pubkey/signature evaluation
    1159                 :             :                         // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
    1160                 :             :                         // See the script_(in)valid tests for details.
    1161   [ +  -  +  +  :       29258 :                         if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
                   +  + ]
    1162                 :             :                             // serror is set
    1163                 :        5628 :                             return false;
    1164                 :             :                         }
    1165                 :             : 
    1166                 :             :                         // Check signature
    1167         [ +  - ]:       23630 :                         bool fOk = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
    1168                 :             : 
    1169         [ +  + ]:       23630 :                         if (fOk) {
    1170                 :       14309 :                             isig++;
    1171                 :       14309 :                             nSigsCount--;
    1172                 :             :                         }
    1173                 :       23630 :                         ikey++;
    1174                 :       23630 :                         nKeysCount--;
    1175                 :             : 
    1176                 :             :                         // If there are more signatures left than keys left,
    1177                 :             :                         // then too many signatures have failed. Exit early,
    1178                 :             :                         // without checking any further signatures.
    1179         [ +  + ]:       23630 :                         if (nSigsCount > nKeysCount)
    1180                 :        6102 :                             fSuccess = false;
    1181                 :             :                     }
    1182                 :             : 
    1183                 :             :                     // Clean up stack of actual arguments
    1184         [ +  + ]:      841564 :                     while (i-- > 1) {
    1185                 :             :                         // If the operation failed, we require that all signatures must be empty vector
    1186   [ +  +  +  +  :      694913 :                         if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
          +  +  +  -  -  
                +  +  + ]
    1187         [ +  + ]:         926 :                             return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
    1188         [ +  + ]:      684571 :                         if (ikey2 > 0)
    1189                 :      634648 :                             ikey2--;
    1190         [ +  - ]:      684571 :                         popstack(stack);
    1191                 :             :                     }
    1192                 :             : 
    1193                 :             :                     // A bug causes CHECKMULTISIG to consume one extra argument
    1194                 :             :                     // whose contents were not checked in any way.
    1195                 :             :                     //
    1196                 :             :                     // Unfortunately this is a potential source of mutability,
    1197                 :             :                     // so optionally verify it is exactly equal to zero prior
    1198                 :             :                     // to removing it from the stack.
    1199   [ -  +  -  + ]:      156067 :                     if (stack.size() < 1)
    1200         [ #  # ]:           0 :                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1201   [ +  +  +  -  :      156067 :                     if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
             -  +  +  + ]
    1202         [ +  - ]:         706 :                         return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
    1203         [ +  - ]:      155361 :                     popstack(stack);
    1204                 :             : 
    1205   [ +  +  +  - ]:      160349 :                     stack.push_back(fSuccess ? vchTrue : vchFalse);
    1206                 :             : 
    1207         [ +  + ]:      155361 :                     if (opcode == OP_CHECKMULTISIGVERIFY)
    1208                 :             :                     {
    1209         [ +  + ]:       62634 :                         if (fSuccess)
    1210         [ +  - ]:       62586 :                             popstack(stack);
    1211                 :             :                         else
    1212         [ +  - ]:        7529 :                             return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
    1213                 :             :                     }
    1214                 :        7481 :                 }
    1215                 :      155313 :                 break;
    1216                 :             : 
    1217                 :       16264 :                 default:
    1218         [ +  - ]:       16264 :                     return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
    1219                 :             :             }
    1220                 :             : 
    1221                 :             :             // Size limits
    1222   [ -  +  -  +  :    11230288 :             if (stack.size() + altstack.size() > MAX_STACK_SIZE)
                   +  + ]
    1223         [ +  - ]:         492 :                 return set_error(serror, SCRIPT_ERR_STACK_SIZE);
    1224                 :             :         }
    1225                 :             :     }
    1226         [ +  - ]:        9211 :     catch (const scriptnum_error&)
    1227                 :             :     {
    1228         [ +  - ]:        9211 :         return set_error(serror, SCRIPT_ERR_SCRIPTNUM);
    1229                 :        9211 :     }
    1230                 :           0 :     catch (...)
    1231                 :             :     {
    1232         [ -  - ]:           0 :         return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
    1233         [ -  - ]:           0 :     }
    1234                 :             : 
    1235         [ +  + ]:     1558469 :     if (!vfExec.empty())
    1236         [ +  - ]:         671 :         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
    1237                 :             : 
    1238         [ +  + ]:     1557798 :     return set_success(serror);
    1239                 :     1756431 : }
    1240                 :             : 
    1241                 :     1610030 : bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
    1242                 :             : {
    1243                 :     1610030 :     ScriptExecutionData execdata;
    1244                 :     1610030 :     return EvalScript(stack, script, flags, checker, sigversion, execdata, serror);
    1245                 :             : }
    1246                 :             : 
    1247                 :             : namespace {
    1248                 :             : 
    1249                 :             : /**
    1250                 :             :  * Wrapper that serializes like CTransaction, but with the modifications
    1251                 :             :  *  required for the signature hash done in-place
    1252                 :             :  */
    1253                 :             : template <class T>
    1254                 :             : class CTransactionSignatureSerializer
    1255                 :             : {
    1256                 :             : private:
    1257                 :             :     const T& txTo;             //!< reference to the spending transaction (the one being serialized)
    1258                 :             :     const CScript& scriptCode; //!< output script being consumed
    1259                 :             :     const unsigned int nIn;    //!< input index of txTo being signed
    1260                 :             :     const bool fAnyoneCanPay;  //!< whether the hashtype has the SIGHASH_ANYONECANPAY flag set
    1261                 :             :     // Temporary workaround for a clang-tidy bug fixed in version 22.
    1262                 :             :     // See: https://github.com/llvm/llvm-project/issues/160394.
    1263                 :             :     // NOLINTBEGIN(modernize-use-default-member-init)
    1264                 :             :     const bool fHashSingle;    //!< whether the hashtype is SIGHASH_SINGLE
    1265                 :             :     const bool fHashNone;      //!< whether the hashtype is SIGHASH_NONE
    1266                 :             :     // NOLINTEND(modernize-use-default-member-init)
    1267                 :             : 
    1268                 :             : public:
    1269                 :      121618 :     CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
    1270                 :      121618 :         txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
    1271                 :      121618 :         fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
    1272                 :      121618 :         fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
    1273                 :      121618 :         fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
    1274                 :             : 
    1275                 :             :     /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
    1276                 :             :     template<typename S>
    1277                 :      121618 :     void SerializeScriptCode(S &s) const {
    1278         [ +  + ]:      121618 :         CScript::const_iterator it = scriptCode.begin();
    1279                 :      121618 :         CScript::const_iterator itBegin = it;
    1280                 :             :         opcodetype opcode;
    1281                 :      121618 :         unsigned int nCodeSeparators = 0;
    1282         [ +  + ]:      684277 :         while (scriptCode.GetOp(it, opcode)) {
    1283         [ +  + ]:      562659 :             if (opcode == OP_CODESEPARATOR)
    1284                 :       26592 :                 nCodeSeparators++;
    1285                 :             :         }
    1286         [ +  + ]:      153010 :         ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
    1287                 :      121618 :         it = itBegin;
    1288         [ +  + ]:      805895 :         while (scriptCode.GetOp(it, opcode)) {
    1289         [ +  + ]:      562659 :             if (opcode == OP_CODESEPARATOR) {
    1290                 :       26592 :                 s.write(std::as_bytes(std::span{&itBegin[0], size_t(it - itBegin - 1)}));
    1291                 :       26592 :                 itBegin = it;
    1292                 :             :             }
    1293                 :             :         }
    1294         [ +  + ]:      121618 :         if (itBegin != scriptCode.end())
    1295                 :      111548 :             s.write(std::as_bytes(std::span{&itBegin[0], size_t(it - itBegin)}));
    1296                 :      121618 :     }
    1297                 :             : 
    1298                 :             :     /** Serialize an input of txTo */
    1299                 :             :     template<typename S>
    1300                 :      860014 :     void SerializeInput(S &s, unsigned int nInput) const {
    1301                 :             :         // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
    1302         [ +  + ]:      860014 :         if (fAnyoneCanPay)
    1303                 :       26392 :             nInput = nIn;
    1304                 :             :         // Serialize the prevout
    1305                 :      860014 :         ::Serialize(s, txTo.vin[nInput].prevout);
    1306                 :             :         // Serialize the script
    1307         [ +  + ]:      860014 :         if (nInput != nIn)
    1308                 :             :             // Blank out other inputs' signatures
    1309         [ +  - ]:     1476792 :             ::Serialize(s, CScript());
    1310                 :             :         else
    1311                 :      121618 :             SerializeScriptCode(s);
    1312                 :             :         // Serialize the nSequence
    1313   [ +  +  +  +  :      860014 :         if (nInput != nIn && (fHashSingle || fHashNone))
                   +  + ]
    1314                 :             :             // let the others update at will
    1315                 :        2939 :             ::Serialize(s, int32_t{0});
    1316                 :             :         else
    1317                 :      857075 :             ::Serialize(s, txTo.vin[nInput].nSequence);
    1318                 :      860014 :     }
    1319                 :             : 
    1320                 :             :     /** Serialize an output of txTo */
    1321                 :             :     template<typename S>
    1322                 :      404696 :     void SerializeOutput(S &s, unsigned int nOutput) const {
    1323   [ +  +  +  + ]:      404696 :         if (fHashSingle && nOutput != nIn)
    1324                 :             :             // Do not lock-in the txout payee at other indices as txin
    1325         [ +  - ]:        3088 :             ::Serialize(s, CTxOut());
    1326                 :             :         else
    1327                 :      403152 :             ::Serialize(s, txTo.vout[nOutput]);
    1328                 :      404696 :     }
    1329                 :             : 
    1330                 :             :     /** Serialize txTo */
    1331                 :             :     template<typename S>
    1332                 :      121618 :     void Serialize(S &s) const {
    1333                 :             :         // Serialize version
    1334                 :      121618 :         ::Serialize(s, txTo.version);
    1335                 :             :         // Serialize vin
    1336   [ +  +  -  + ]:      121618 :         unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
    1337                 :      121618 :         ::WriteCompactSize(s, nInputs);
    1338         [ +  + ]:      981632 :         for (unsigned int nInput = 0; nInput < nInputs; nInput++)
    1339                 :      860014 :              SerializeInput(s, nInput);
    1340                 :             :         // Serialize vout
    1341   [ +  +  +  +  :      121618 :         unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
                   -  + ]
    1342                 :      121618 :         ::WriteCompactSize(s, nOutputs);
    1343         [ +  + ]:      526314 :         for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
    1344                 :      404696 :              SerializeOutput(s, nOutput);
    1345                 :             :         // Serialize nLockTime
    1346                 :      121618 :         ::Serialize(s, txTo.nLockTime);
    1347                 :      121618 :     }
    1348                 :             : };
    1349                 :             : 
    1350                 :             : /** Compute the (single) SHA256 of the concatenation of all prevouts of a tx. */
    1351                 :             : template <class T>
    1352                 :       71201 : uint256 GetPrevoutsSHA256(const T& txTo)
    1353                 :             : {
    1354                 :       71201 :     HashWriter ss{};
    1355         [ +  + ]:    20520514 :     for (const auto& txin : txTo.vin) {
    1356                 :    20449313 :         ss << txin.prevout;
    1357                 :             :     }
    1358                 :       71201 :     return ss.GetSHA256();
    1359                 :             : }
    1360                 :             : 
    1361                 :             : /** Compute the (single) SHA256 of the concatenation of all nSequences of a tx. */
    1362                 :             : template <class T>
    1363                 :       68187 : uint256 GetSequencesSHA256(const T& txTo)
    1364                 :             : {
    1365                 :       68187 :     HashWriter ss{};
    1366         [ +  + ]:     7017444 :     for (const auto& txin : txTo.vin) {
    1367                 :     6949257 :         ss << txin.nSequence;
    1368                 :             :     }
    1369                 :       68187 :     return ss.GetSHA256();
    1370                 :             : }
    1371                 :             : 
    1372                 :             : /** Compute the (single) SHA256 of the concatenation of all txouts of a tx. */
    1373                 :             : template <class T>
    1374                 :       69708 : uint256 GetOutputsSHA256(const T& txTo)
    1375                 :             : {
    1376                 :       69708 :     HashWriter ss{};
    1377         [ +  + ]:    13968662 :     for (const auto& txout : txTo.vout) {
    1378                 :    13898954 :         ss << txout;
    1379                 :             :     }
    1380                 :       69708 :     return ss.GetSHA256();
    1381                 :             : }
    1382                 :             : 
    1383                 :             : /** Compute the (single) SHA256 of the concatenation of all amounts spent by a tx. */
    1384                 :       51709 : uint256 GetSpentAmountsSHA256(const std::vector<CTxOut>& outputs_spent)
    1385                 :             : {
    1386                 :       51709 :     HashWriter ss{};
    1387         [ +  + ]:      170497 :     for (const auto& txout : outputs_spent) {
    1388                 :      118788 :         ss << txout.nValue;
    1389                 :             :     }
    1390                 :       51709 :     return ss.GetSHA256();
    1391                 :             : }
    1392                 :             : 
    1393                 :             : /** Compute the (single) SHA256 of the concatenation of all scriptPubKeys spent by a tx. */
    1394                 :       51709 : uint256 GetSpentScriptsSHA256(const std::vector<CTxOut>& outputs_spent)
    1395                 :             : {
    1396                 :       51709 :     HashWriter ss{};
    1397         [ +  + ]:      170497 :     for (const auto& txout : outputs_spent) {
    1398                 :      118788 :         ss << txout.scriptPubKey;
    1399                 :             :     }
    1400                 :       51709 :     return ss.GetSHA256();
    1401                 :             : }
    1402                 :             : 
    1403                 :             : 
    1404                 :             : } // namespace
    1405                 :             : 
    1406                 :             : template <class T>
    1407                 :       82224 : void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent_outputs, bool force)
    1408                 :             : {
    1409         [ -  + ]:       82224 :     assert(!m_spent_outputs_ready);
    1410                 :             : 
    1411                 :       82224 :     m_spent_outputs = std::move(spent_outputs);
    1412         [ +  + ]:       82224 :     if (!m_spent_outputs.empty()) {
    1413   [ -  +  -  +  :       81751 :         assert(m_spent_outputs.size() == txTo.vin.size());
                   -  + ]
    1414                 :       81751 :         m_spent_outputs_ready = true;
    1415                 :             :     }
    1416                 :             : 
    1417                 :             :     // Determine which precomputation-impacting features this transaction uses.
    1418                 :             :     bool uses_bip143_segwit = force;
    1419                 :             :     bool uses_bip341_taproot = force;
    1420   [ -  +  +  +  :      183684 :     for (size_t inpos = 0; inpos < txTo.vin.size() && !(uses_bip143_segwit && uses_bip341_taproot); ++inpos) {
                   +  + ]
    1421         [ +  + ]:      102440 :         if (!txTo.vin[inpos].scriptWitness.IsNull()) {
    1422   [ +  +  -  +  :       67680 :             if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.size() == 2 + WITNESS_V1_TAPROOT_SIZE &&
                   +  + ]
    1423   [ +  -  +  + ]:      106272 :                 m_spent_outputs[inpos].scriptPubKey[0] == OP_1) {
    1424                 :             :                 // Treat every witness-bearing spend with 34-byte scriptPubKey that starts with OP_1 as a Taproot
    1425                 :             :                 // spend. This only works if spent_outputs was provided as well, but if it wasn't, actual validation
    1426                 :             :                 // will fail anyway. Note that this branch may trigger for scriptPubKeys that aren't actually segwit
    1427                 :             :                 // but in that case validation will fail as SCRIPT_ERR_WITNESS_UNEXPECTED anyway.
    1428                 :             :                 uses_bip341_taproot = true;
    1429                 :             :             } else {
    1430                 :             :                 // Treat every spend that's not known to native witness v1 as a Witness v0 spend. This branch may
    1431                 :             :                 // also be taken for unknown witness versions, but it is harmless, and being precise would require
    1432                 :             :                 // P2SH evaluation to find the redeemScript.
    1433                 :             :                 uses_bip143_segwit = true;
    1434                 :             :             }
    1435                 :             :         }
    1436         [ +  + ]:      102440 :         if (uses_bip341_taproot && uses_bip143_segwit) break; // No need to scan further if we already need all.
    1437                 :             :     }
    1438                 :             : 
    1439         [ +  + ]:       82224 :     if (uses_bip143_segwit || uses_bip341_taproot) {
    1440                 :             :         // Computations shared between both sighash schemes.
    1441                 :       57631 :         m_prevouts_single_hash = GetPrevoutsSHA256(txTo);
    1442                 :       57631 :         m_sequences_single_hash = GetSequencesSHA256(txTo);
    1443                 :       57631 :         m_outputs_single_hash = GetOutputsSHA256(txTo);
    1444                 :             :     }
    1445         [ +  + ]:       57631 :     if (uses_bip143_segwit) {
    1446                 :       28176 :         hashPrevouts = SHA256Uint256(m_prevouts_single_hash);
    1447                 :       28176 :         hashSequence = SHA256Uint256(m_sequences_single_hash);
    1448                 :       28176 :         hashOutputs = SHA256Uint256(m_outputs_single_hash);
    1449                 :       28176 :         m_bip143_segwit_ready = true;
    1450                 :             :     }
    1451   [ +  +  +  + ]:       82224 :     if (uses_bip341_taproot && m_spent_outputs_ready) {
    1452                 :       51709 :         m_spent_amounts_single_hash = GetSpentAmountsSHA256(m_spent_outputs);
    1453                 :       51709 :         m_spent_scripts_single_hash = GetSpentScriptsSHA256(m_spent_outputs);
    1454                 :       51709 :         m_bip341_taproot_ready = true;
    1455                 :             :     }
    1456                 :       82224 : }
    1457                 :             : 
    1458                 :             : template <class T>
    1459         [ +  - ]:         220 : PrecomputedTransactionData::PrecomputedTransactionData(const T& txTo)
    1460                 :             : {
    1461         [ +  - ]:         220 :     Init(txTo, {});
    1462                 :         220 : }
    1463                 :             : 
    1464                 :             : // explicit instantiation
    1465                 :             : template void PrecomputedTransactionData::Init(const CTransaction& txTo, std::vector<CTxOut>&& spent_outputs, bool force);
    1466                 :             : template void PrecomputedTransactionData::Init(const CMutableTransaction& txTo, std::vector<CTxOut>&& spent_outputs, bool force);
    1467                 :             : template PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo);
    1468                 :             : template PrecomputedTransactionData::PrecomputedTransactionData(const CMutableTransaction& txTo);
    1469                 :             : 
    1470                 :             : const HashWriter HASHER_TAPSIGHASH{TaggedHash("TapSighash")};
    1471                 :             : const HashWriter HASHER_TAPLEAF{TaggedHash("TapLeaf")};
    1472                 :             : const HashWriter HASHER_TAPBRANCH{TaggedHash("TapBranch")};
    1473                 :             : 
    1474                 :          46 : static bool HandleMissingData(MissingDataBehavior mdb)
    1475                 :             : {
    1476      [ -  +  - ]:          46 :     switch (mdb) {
    1477                 :           0 :     case MissingDataBehavior::ASSERT_FAIL:
    1478                 :           0 :         assert(!"Missing data");
    1479                 :             :         break;
    1480                 :          46 :     case MissingDataBehavior::FAIL:
    1481                 :          46 :         return false;
    1482                 :             :     }
    1483                 :           0 :     assert(!"Unknown MissingDataBehavior value");
    1484                 :             : }
    1485                 :             : 
    1486                 :             : template<typename T>
    1487                 :       19254 : bool SignatureHashSchnorr(uint256& hash_out, ScriptExecutionData& execdata, const T& tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData& cache, MissingDataBehavior mdb)
    1488                 :             : {
    1489                 :             :     uint8_t ext_flag, key_version;
    1490      [ +  -  + ]:       19254 :     switch (sigversion) {
    1491                 :             :     case SigVersion::TAPROOT:
    1492                 :             :         ext_flag = 0;
    1493                 :             :         // key_version is not used and left uninitialized.
    1494                 :             :         break;
    1495                 :       15621 :     case SigVersion::TAPSCRIPT:
    1496                 :       15621 :         ext_flag = 1;
    1497                 :             :         // key_version must be 0 for now, representing the current version of
    1498                 :             :         // 32-byte public keys in the tapscript signature opcode execution.
    1499                 :             :         // An upgradable public key version (with a size not 32-byte) may
    1500                 :             :         // request a different key_version with a new sigversion.
    1501                 :       15621 :         key_version = 0;
    1502                 :       15621 :         break;
    1503                 :           0 :     default:
    1504                 :           0 :         assert(false);
    1505                 :             :     }
    1506   [ -  +  -  + ]:       19254 :     assert(in_pos < tx_to.vin.size());
    1507   [ +  -  -  + ]:       19254 :     if (!(cache.m_bip341_taproot_ready && cache.m_spent_outputs_ready)) {
    1508                 :           0 :         return HandleMissingData(mdb);
    1509                 :             :     }
    1510                 :             : 
    1511                 :       19254 :     HashWriter ss{HASHER_TAPSIGHASH};
    1512                 :             : 
    1513                 :             :     // Epoch
    1514                 :             :     static constexpr uint8_t EPOCH = 0;
    1515                 :       19254 :     ss << EPOCH;
    1516                 :             : 
    1517                 :             :     // Hash type
    1518         [ +  + ]:       19254 :     const uint8_t output_type = (hash_type == SIGHASH_DEFAULT) ? SIGHASH_ALL : (hash_type & SIGHASH_OUTPUT_MASK); // Default (no sighash byte) is equivalent to SIGHASH_ALL
    1519                 :       18598 :     const uint8_t input_type = hash_type & SIGHASH_INPUT_MASK;
    1520   [ +  +  +  + ]:       11445 :     if (!(hash_type <= 0x03 || (hash_type >= 0x81 && hash_type <= 0x83))) return false;
    1521                 :       18598 :     ss << hash_type;
    1522                 :             : 
    1523                 :             :     // Transaction level data
    1524                 :       18598 :     ss << tx_to.version;
    1525                 :       18598 :     ss << tx_to.nLockTime;
    1526         [ +  + ]:       18598 :     if (input_type != SIGHASH_ANYONECANPAY) {
    1527                 :       14296 :         ss << cache.m_prevouts_single_hash;
    1528                 :       14296 :         ss << cache.m_spent_amounts_single_hash;
    1529                 :       14296 :         ss << cache.m_spent_scripts_single_hash;
    1530                 :       14296 :         ss << cache.m_sequences_single_hash;
    1531                 :             :     }
    1532         [ +  + ]:       18598 :     if (output_type == SIGHASH_ALL) {
    1533                 :       12744 :         ss << cache.m_outputs_single_hash;
    1534                 :             :     }
    1535                 :             : 
    1536                 :             :     // Data about the input/prevout being spent
    1537         [ -  + ]:       18598 :     assert(execdata.m_annex_init);
    1538                 :       18598 :     const bool have_annex = execdata.m_annex_present;
    1539         [ +  + ]:       35153 :     const uint8_t spend_type = (ext_flag << 1) + (have_annex ? 1 : 0); // The low bit indicates whether an annex is present.
    1540                 :       18598 :     ss << spend_type;
    1541         [ +  + ]:       18598 :     if (input_type == SIGHASH_ANYONECANPAY) {
    1542                 :        4302 :         ss << tx_to.vin[in_pos].prevout;
    1543                 :        4302 :         ss << cache.m_spent_outputs[in_pos];
    1544                 :        4302 :         ss << tx_to.vin[in_pos].nSequence;
    1545                 :             :     } else {
    1546                 :       14296 :         ss << in_pos;
    1547                 :             :     }
    1548         [ +  + ]:       18598 :     if (have_annex) {
    1549                 :        2043 :         ss << execdata.m_annex_hash;
    1550                 :             :     }
    1551                 :             : 
    1552                 :             :     // Data about the output (if only one).
    1553         [ +  + ]:       18598 :     if (output_type == SIGHASH_SINGLE) {
    1554   [ -  +  +  + ]:        2486 :         if (in_pos >= tx_to.vout.size()) return false;
    1555         [ +  + ]:        2478 :         if (!execdata.m_output_hash) {
    1556                 :         383 :             HashWriter sha_single_output{};
    1557                 :         383 :             sha_single_output << tx_to.vout[in_pos];
    1558         [ -  + ]:         383 :             execdata.m_output_hash = sha_single_output.GetSHA256();
    1559                 :             :         }
    1560         [ +  - ]:        2478 :         ss << execdata.m_output_hash.value();
    1561                 :             :     }
    1562                 :             : 
    1563                 :             :     // Additional data for BIP 342 signatures
    1564         [ +  + ]:       18590 :     if (sigversion == SigVersion::TAPSCRIPT) {
    1565         [ -  + ]:       15291 :         assert(execdata.m_tapleaf_hash_init);
    1566                 :       15291 :         ss << execdata.m_tapleaf_hash;
    1567                 :       15291 :         ss << key_version;
    1568         [ -  + ]:       15291 :         assert(execdata.m_codeseparator_pos_init);
    1569                 :       15291 :         ss << execdata.m_codeseparator_pos;
    1570                 :             :     }
    1571                 :             : 
    1572                 :       18590 :     hash_out = ss.GetSHA256();
    1573                 :       18590 :     return true;
    1574                 :             : }
    1575                 :             : 
    1576                 :      299946 : int SigHashCache::CacheIndex(int32_t hash_type) const noexcept
    1577                 :             : {
    1578                 :             :     // Note that we do not distinguish between BASE and WITNESS_V0 to determine the cache index,
    1579                 :             :     // because no input can simultaneously use both.
    1580         [ +  + ]:      299946 :     return 3 * !!(hash_type & SIGHASH_ANYONECANPAY) +
    1581         [ +  + ]:      299946 :            2 * ((hash_type & 0x1f) == SIGHASH_SINGLE) +
    1582                 :      299946 :            1 * ((hash_type & 0x1f) == SIGHASH_NONE);
    1583                 :             : }
    1584                 :             : 
    1585                 :      170780 : bool SigHashCache::Load(int32_t hash_type, const CScript& script_code, HashWriter& writer) const noexcept
    1586                 :             : {
    1587                 :      170780 :     auto& entry = m_cache_entries[CacheIndex(hash_type)];
    1588         [ +  + ]:      170780 :     if (entry.has_value()) {
    1589         [ +  + ]:       42483 :         if (script_code == entry->first) {
    1590                 :       41688 :             writer = HashWriter(entry->second);
    1591                 :       41688 :             return true;
    1592                 :             :         }
    1593                 :             :     }
    1594                 :             :     return false;
    1595                 :             : }
    1596                 :             : 
    1597                 :      129166 : void SigHashCache::Store(int32_t hash_type, const CScript& script_code, const HashWriter& writer) noexcept
    1598                 :             : {
    1599                 :      129166 :     auto& entry = m_cache_entries[CacheIndex(hash_type)];
    1600                 :      129166 :     entry.emplace(script_code, writer);
    1601                 :      129166 : }
    1602                 :             : 
    1603                 :             : template <class T>
    1604                 :      238076 : uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int32_t nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache, SigHashCache* sighash_cache)
    1605                 :             : {
    1606   [ -  +  -  + ]:      238076 :     assert(nIn < txTo.vin.size());
    1607                 :             : 
    1608         [ +  + ]:      238076 :     if (sigversion != SigVersion::WITNESS_V0) {
    1609                 :             :         // Check for invalid use of SIGHASH_SINGLE
    1610         [ +  + ]:      160826 :         if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
    1611   [ -  +  +  + ]:        2465 :             if (nIn >= txTo.vout.size()) {
    1612                 :             :                 //  nOut out of range
    1613                 :         297 :                 return uint256::ONE;
    1614                 :             :             }
    1615                 :             :         }
    1616                 :             :     }
    1617                 :             : 
    1618                 :      237779 :     HashWriter ss{};
    1619                 :             : 
    1620                 :             :     // Try to compute using cached SHA256 midstate.
    1621   [ +  +  +  + ]:      237779 :     if (sighash_cache && sighash_cache->Load(nHashType, scriptCode, ss)) {
    1622                 :             :         // Add sighash type and hash.
    1623                 :       41578 :         ss << nHashType;
    1624                 :       41578 :         return ss.GetHash();
    1625                 :             :     }
    1626                 :             : 
    1627         [ +  + ]:      196201 :     if (sigversion == SigVersion::WITNESS_V0) {
    1628                 :       74583 :         uint256 hashPrevouts;
    1629                 :       74583 :         uint256 hashSequence;
    1630                 :       74583 :         uint256 hashOutputs;
    1631   [ +  +  -  + ]:       74583 :         const bool cacheready = cache && cache->m_bip143_segwit_ready;
    1632                 :             : 
    1633         [ +  + ]:       74583 :         if (!(nHashType & SIGHASH_ANYONECANPAY)) {
    1634         [ +  + ]:       62639 :             hashPrevouts = cacheready ? cache->hashPrevouts : SHA256Uint256(GetPrevoutsSHA256(txTo));
    1635                 :             :         }
    1636                 :             : 
    1637   [ +  +  +  + ]:       62639 :         if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
    1638         [ +  + ]:       55811 :             hashSequence = cacheready ? cache->hashSequence : SHA256Uint256(GetSequencesSHA256(txTo));
    1639                 :             :         }
    1640                 :             : 
    1641         [ +  + ]:       74583 :         if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
    1642         [ +  + ]:       60731 :             hashOutputs = cacheready ? cache->hashOutputs : SHA256Uint256(GetOutputsSHA256(txTo));
    1643   [ +  +  -  +  :       13852 :         } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
                   +  + ]
    1644                 :        6339 :             HashWriter inner_ss{};
    1645                 :        6339 :             inner_ss << txTo.vout[nIn];
    1646                 :        6339 :             hashOutputs = inner_ss.GetHash();
    1647                 :             :         }
    1648                 :             : 
    1649                 :             :         // Version
    1650                 :       74583 :         ss << txTo.version;
    1651                 :             :         // Input prevouts/nSequence (none/all, depending on flags)
    1652                 :       74583 :         ss << hashPrevouts;
    1653                 :       74583 :         ss << hashSequence;
    1654                 :             :         // The input being signed (replacing the scriptSig with scriptCode + amount)
    1655                 :             :         // The prevout may already be contained in hashPrevout, and the nSequence
    1656                 :             :         // may already be contain in hashSequence.
    1657                 :       74583 :         ss << txTo.vin[nIn].prevout;
    1658                 :       74583 :         ss << scriptCode;
    1659                 :       74583 :         ss << amount;
    1660                 :       74583 :         ss << txTo.vin[nIn].nSequence;
    1661                 :             :         // Outputs (none/one/all, depending on flags)
    1662                 :       74583 :         ss << hashOutputs;
    1663                 :             :         // Locktime
    1664                 :       74583 :         ss << txTo.nLockTime;
    1665                 :             :     } else {
    1666                 :             :         // Wrapper to serialize only the necessary parts of the transaction being signed
    1667                 :      121618 :         CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
    1668                 :             : 
    1669                 :             :         // Serialize
    1670                 :      121618 :         ss << txTmp;
    1671                 :             :     }
    1672                 :             : 
    1673                 :             :     // If a cache object was provided, store the midstate there.
    1674         [ +  + ]:      196201 :     if (sighash_cache != nullptr) {
    1675                 :      129090 :         sighash_cache->Store(nHashType, scriptCode, ss);
    1676                 :             :     }
    1677                 :             : 
    1678                 :             :     // Add sighash type and hash.
    1679                 :      196201 :     ss << nHashType;
    1680                 :      196201 :     return ss.GetHash();
    1681                 :             : }
    1682                 :             : 
    1683                 :             : template <class T>
    1684                 :      123859 : bool GenericTransactionSignatureChecker<T>::VerifyECDSASignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
    1685                 :             : {
    1686                 :      123859 :     return pubkey.Verify(sighash, vchSig);
    1687                 :             : }
    1688                 :             : 
    1689                 :             : template <class T>
    1690                 :       15866 : bool GenericTransactionSignatureChecker<T>::VerifySchnorrSignature(std::span<const unsigned char> sig, const XOnlyPubKey& pubkey, const uint256& sighash) const
    1691                 :             : {
    1692                 :       15866 :     return pubkey.VerifySchnorr(sighash, sig);
    1693                 :             : }
    1694                 :             : 
    1695                 :             : template <class T>
    1696         [ -  + ]:      193227 : bool GenericTransactionSignatureChecker<T>::CheckECDSASignature(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
    1697                 :             : {
    1698         [ +  + ]:      193227 :     CPubKey pubkey(vchPubKey);
    1699         [ +  + ]:      193227 :     if (!pubkey.IsValid())
    1700                 :             :         return false;
    1701                 :             : 
    1702                 :             :     // Hash type is one byte tacked on to the end of the signature
    1703                 :      189610 :     std::vector<unsigned char> vchSig(vchSigIn);
    1704         [ +  + ]:      189610 :     if (vchSig.empty())
    1705                 :             :         return false;
    1706         [ +  + ]:      170697 :     int nHashType = vchSig.back();
    1707                 :      170697 :     vchSig.pop_back();
    1708                 :             : 
    1709                 :             :     // Witness sighashes need the amount.
    1710   [ +  +  -  + ]:      170697 :     if (sigversion == SigVersion::WITNESS_V0 && amount < 0) return HandleMissingData(m_mdb);
    1711                 :             : 
    1712         [ +  - ]:      170697 :     uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata, &m_sighash_cache);
    1713                 :             : 
    1714   [ +  -  +  + ]:      170697 :     if (!VerifyECDSASignature(vchSig, pubkey, sighash))
    1715                 :        9888 :         return false;
    1716                 :             : 
    1717                 :             :     return true;
    1718                 :      189610 : }
    1719                 :             : 
    1720                 :             : template <class T>
    1721                 :       18082 : bool GenericTransactionSignatureChecker<T>::CheckSchnorrSignature(std::span<const unsigned char> sig, std::span<const unsigned char> pubkey_in, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) const
    1722                 :             : {
    1723         [ -  + ]:       18082 :     assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
    1724                 :             :     // Schnorr signatures have 32-byte public keys. The caller is responsible for enforcing this.
    1725         [ -  + ]:       18082 :     assert(pubkey_in.size() == 32);
    1726                 :             :     // Note that in Tapscript evaluation, empty signatures are treated specially (invalid signature that does not
    1727                 :             :     // abort script execution). This is implemented in EvalChecksigTapscript, which won't invoke
    1728                 :             :     // CheckSchnorrSignature in that case. In other contexts, they are invalid like every other signature with
    1729                 :             :     // size different from 64 or 65.
    1730   [ +  +  +  + ]:       18082 :     if (sig.size() != 64 && sig.size() != 65) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_SIZE);
    1731                 :             : 
    1732                 :       18054 :     XOnlyPubKey pubkey{pubkey_in};
    1733                 :             : 
    1734         [ +  + ]:       18054 :     uint8_t hashtype = SIGHASH_DEFAULT;
    1735         [ +  + ]:       18054 :     if (sig.size() == 65) {
    1736                 :       11429 :         hashtype = SpanPopBack(sig);
    1737         [ +  + ]:       11429 :         if (hashtype == SIGHASH_DEFAULT) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
    1738                 :             :     }
    1739                 :       18044 :     uint256 sighash;
    1740         [ +  + ]:       18044 :     if (!this->txdata) return HandleMissingData(m_mdb);
    1741         [ +  + ]:       17998 :     if (!SignatureHashSchnorr(sighash, execdata, *txTo, nIn, hashtype, sigversion, *this->txdata, m_mdb)) {
    1742                 :       18082 :         return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
    1743                 :             :     }
    1744         [ +  + ]:       17334 :     if (!VerifySchnorrSignature(sig, pubkey, sighash)) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG);
    1745                 :             :     return true;
    1746                 :             : }
    1747                 :             : 
    1748                 :             : template <class T>
    1749                 :        6396 : bool GenericTransactionSignatureChecker<T>::CheckLockTime(const CScriptNum& nLockTime) const
    1750                 :             : {
    1751                 :             :     // There are two kinds of nLockTime: lock-by-blockheight
    1752                 :             :     // and lock-by-blocktime, distinguished by whether
    1753                 :             :     // nLockTime < LOCKTIME_THRESHOLD.
    1754                 :             :     //
    1755                 :             :     // We want to compare apples to apples, so fail the script
    1756                 :             :     // unless the type of nLockTime being tested is the same as
    1757                 :             :     // the nLockTime in the transaction.
    1758                 :             :     if (!(
    1759   [ +  +  +  +  :       12376 :         (txTo->nLockTime <  LOCKTIME_THRESHOLD && nLockTime <  LOCKTIME_THRESHOLD) ||
             +  +  +  + ]
    1760   [ +  +  +  + ]:         832 :         (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
    1761                 :             :     ))
    1762                 :         179 :         return false;
    1763                 :             : 
    1764                 :             :     // Now that we know we're comparing apples-to-apples, the
    1765                 :             :     // comparison is a simple numeric one.
    1766   [ +  +  +  + ]:       12434 :     if (nLockTime > (int64_t)txTo->nLockTime)
    1767                 :             :         return false;
    1768                 :             : 
    1769                 :             :     // Finally the nLockTime feature can be disabled in IsFinalTx()
    1770                 :             :     // and thus CHECKLOCKTIMEVERIFY bypassed if every txin has
    1771                 :             :     // been finalized by setting nSequence to maxint. The
    1772                 :             :     // transaction would be allowed into the blockchain, making
    1773                 :             :     // the opcode ineffective.
    1774                 :             :     //
    1775                 :             :     // Testing if this vin is not final is sufficient to
    1776                 :             :     // prevent this condition. Alternatively we could test all
    1777                 :             :     // inputs, but testing just this input minimizes the data
    1778                 :             :     // required to prove correct CHECKLOCKTIMEVERIFY execution.
    1779         [ +  + ]:         624 :     if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
    1780                 :          92 :         return false;
    1781                 :             : 
    1782                 :             :     return true;
    1783                 :             : }
    1784                 :             : 
    1785                 :             : template <class T>
    1786                 :        6474 : bool GenericTransactionSignatureChecker<T>::CheckSequence(const CScriptNum& nSequence) const
    1787                 :             : {
    1788                 :             :     // Relative lock times are supported by comparing the passed
    1789                 :             :     // in operand to the sequence number of the input.
    1790         [ +  + ]:        6474 :     const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
    1791                 :             : 
    1792                 :             :     // Fail if the transaction's version number is not set high
    1793                 :             :     // enough to trigger BIP 68 rules.
    1794         [ +  + ]:        6474 :     if (txTo->version < 2)
    1795                 :             :         return false;
    1796                 :             : 
    1797                 :             :     // Sequence numbers with their most significant bit set are not
    1798                 :             :     // consensus constrained. Testing that the transaction's sequence
    1799                 :             :     // number do not have this bit set prevents using this property
    1800                 :             :     // to get around a CHECKSEQUENCEVERIFY check.
    1801         [ +  + ]:        6049 :     if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
    1802                 :             :         return false;
    1803                 :             : 
    1804                 :             :     // Mask off any bits that do not have consensus-enforced meaning
    1805                 :             :     // before doing the integer comparisons
    1806                 :        6013 :     const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
    1807                 :        6013 :     const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
    1808         [ +  + ]:        6013 :     const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
    1809                 :             : 
    1810                 :             :     // There are two kinds of nSequence: lock-by-blockheight
    1811                 :             :     // and lock-by-blocktime, distinguished by whether
    1812                 :             :     // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
    1813                 :             :     //
    1814                 :             :     // We want to compare apples to apples, so fail the script
    1815                 :             :     // unless the type of nSequenceMasked being tested is the same as
    1816                 :             :     // the nSequenceMasked in the transaction.
    1817                 :             :     if (!(
    1818   [ +  +  +  +  :       11644 :         (txToSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
                   +  + ]
    1819   [ +  +  +  + ]:         764 :         (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
    1820                 :             :     )) {
    1821                 :         188 :         return false;
    1822                 :             :     }
    1823                 :             : 
    1824                 :             :     // Now that we know we're comparing apples-to-apples, the
    1825                 :             :     // comparison is a simple numeric one.
    1826         [ +  + ]:        5825 :     if (nSequenceMasked > txToSequenceMasked)
    1827                 :        5259 :         return false;
    1828                 :             : 
    1829                 :             :     return true;
    1830                 :             : }
    1831                 :             : 
    1832                 :             : // explicit instantiation
    1833                 :             : template class GenericTransactionSignatureChecker<CTransaction>;
    1834                 :             : template class GenericTransactionSignatureChecker<CMutableTransaction>;
    1835                 :             : 
    1836                 :      148978 : static bool ExecuteWitnessScript(const std::span<const valtype>& stack_span, const CScript& exec_script, script_verify_flags flags, SigVersion sigversion, const BaseSignatureChecker& checker, ScriptExecutionData& execdata, ScriptError* serror)
    1837                 :             : {
    1838                 :      148978 :     std::vector<valtype> stack{stack_span.begin(), stack_span.end()};
    1839                 :             : 
    1840         [ +  + ]:      148978 :     if (sigversion == SigVersion::TAPSCRIPT) {
    1841                 :             :         // OP_SUCCESSx processing overrides everything, including stack element size limits
    1842         [ +  + ]:      133600 :         CScript::const_iterator pc = exec_script.begin();
    1843   [ +  +  +  + ]:    14463806 :         while (pc < exec_script.end()) {
    1844                 :     7167352 :             opcodetype opcode;
    1845   [ +  -  +  + ]:     7167352 :             if (!exec_script.GetOp(pc, opcode)) {
    1846                 :             :                 // Note how this condition would not be reached if an unknown OP_SUCCESSx was found
    1847         [ +  - ]:         395 :                 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
    1848                 :             :             }
    1849                 :             :             // New opcodes will be listed here. May use a different sigversion to modify existing opcodes.
    1850   [ +  -  +  + ]:     7166957 :             if (IsOpSuccess(opcode)) {
    1851         [ +  + ]:        1854 :                 if (flags & SCRIPT_VERIFY_DISCOURAGE_OP_SUCCESS) {
    1852         [ +  - ]:         444 :                     return set_error(serror, SCRIPT_ERR_DISCOURAGE_OP_SUCCESS);
    1853                 :             :                 }
    1854         [ +  - ]:        1410 :                 return set_success(serror);
    1855                 :             :             }
    1856                 :             :         }
    1857                 :             : 
    1858                 :             :         // Tapscript enforces initial stack size limits (altstack is empty here)
    1859   [ -  +  +  +  :       64551 :         if (stack.size() > MAX_STACK_SIZE) return set_error(serror, SCRIPT_ERR_STACK_SIZE);
                   +  - ]
    1860                 :             :     }
    1861                 :             : 
    1862                 :             :     // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
    1863         [ +  + ]:      442600 :     for (const valtype& elem : stack) {
    1864   [ -  +  +  +  :      296199 :         if (elem.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
                   +  - ]
    1865                 :             :     }
    1866                 :             : 
    1867                 :             :     // Run the script interpreter.
    1868   [ +  -  +  + ]:      146401 :     if (!EvalScript(stack, exec_script, flags, checker, sigversion, execdata, serror)) return false;
    1869                 :             : 
    1870                 :             :     // Scripts inside witness implicitly require cleanstack behaviour
    1871   [ -  +  +  +  :      129955 :     if (stack.size() != 1) return set_error(serror, SCRIPT_ERR_CLEANSTACK);
                   +  + ]
    1872   [ +  -  +  +  :      126594 :     if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
                   +  - ]
    1873                 :             :     return true;
    1874                 :      148978 : }
    1875                 :             : 
    1876                 :      112866 : uint256 ComputeTapleafHash(uint8_t leaf_version, std::span<const unsigned char> script)
    1877                 :             : {
    1878                 :      112866 :     return (HashWriter{HASHER_TAPLEAF} << leaf_version << CompactSizeWriter(script.size()) << script).GetSHA256();
    1879                 :             : }
    1880                 :             : 
    1881                 :       61782 : uint256 ComputeTapbranchHash(std::span<const unsigned char> a, std::span<const unsigned char> b)
    1882                 :             : {
    1883                 :       61782 :     HashWriter ss_branch{HASHER_TAPBRANCH};
    1884         [ +  + ]:       61782 :     if (std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end())) {
    1885                 :       25113 :         ss_branch << a << b;
    1886                 :             :     } else {
    1887                 :       36669 :         ss_branch << b << a;
    1888                 :             :     }
    1889                 :       61782 :     return ss_branch.GetSHA256();
    1890                 :             : }
    1891                 :             : 
    1892                 :       71936 : uint256 ComputeTaprootMerkleRoot(std::span<const unsigned char> control, const uint256& tapleaf_hash)
    1893                 :             : {
    1894         [ -  + ]:       71936 :     assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE);
    1895         [ -  + ]:       71936 :     assert(control.size() <= TAPROOT_CONTROL_MAX_SIZE);
    1896         [ -  + ]:       71936 :     assert((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE == 0);
    1897                 :             : 
    1898                 :       71936 :     const int path_len = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
    1899                 :       71936 :     uint256 k = tapleaf_hash;
    1900         [ +  + ]:      111142 :     for (int i = 0; i < path_len; ++i) {
    1901                 :       39206 :         std::span node{std::span{control}.subspan(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * i, TAPROOT_CONTROL_NODE_SIZE)};
    1902                 :       39206 :         k = ComputeTapbranchHash(k, node);
    1903                 :             :     }
    1904                 :       71936 :     return k;
    1905                 :             : }
    1906                 :             : 
    1907                 :       68404 : static bool VerifyTaprootCommitment(const std::vector<unsigned char>& control, const std::vector<unsigned char>& program, const uint256& tapleaf_hash)
    1908                 :             : {
    1909   [ -  +  -  + ]:       68404 :     assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE);
    1910   [ -  +  -  + ]:       68404 :     assert(program.size() >= uint256::size());
    1911                 :             :     //! The internal pubkey (x-only, so no Y coordinate parity).
    1912                 :       68404 :     const XOnlyPubKey p{std::span{control}.subspan(1, TAPROOT_CONTROL_BASE_SIZE - 1)};
    1913                 :             :     //! The output pubkey (taken from the scriptPubKey).
    1914         [ -  + ]:       68404 :     const XOnlyPubKey q{program};
    1915                 :             :     // Compute the Merkle root from the leaf and the provided path.
    1916         [ -  + ]:       68404 :     const uint256 merkle_root = ComputeTaprootMerkleRoot(control, tapleaf_hash);
    1917                 :             :     // Verify that the output pubkey matches the tweaked internal pubkey, after correcting for parity.
    1918                 :       68404 :     return q.CheckTapTweak(p, merkle_root, control[0] & 1);
    1919                 :             : }
    1920                 :             : 
    1921                 :      222222 : static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, script_verify_flags flags, const BaseSignatureChecker& checker, ScriptError* serror, bool is_p2sh)
    1922                 :             : {
    1923                 :      222222 :     CScript exec_script; //!< Actually executed script (last stack item in P2WSH; implied P2PKH script in P2WPKH; leaf script in P2TR)
    1924         [ -  + ]:      222222 :     std::span stack{witness.stack};
    1925         [ +  + ]:      222222 :     ScriptExecutionData execdata;
    1926                 :             : 
    1927         [ +  + ]:      222222 :     if (witversion == 0) {
    1928   [ -  +  +  + ]:      140551 :         if (program.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
    1929                 :             :             // BIP141 P2WSH: 32-byte witness v0 program (which encodes SHA256(script))
    1930         [ +  + ]:       30985 :             if (stack.size() == 0) {
    1931         [ +  + ]:        1198 :                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
    1932                 :             :             }
    1933                 :       29787 :             const valtype& script_bytes = SpanPopBack(stack);
    1934                 :       29787 :             exec_script = CScript(script_bytes.begin(), script_bytes.end());
    1935                 :       29787 :             uint256 hash_exec_script;
    1936   [ +  -  +  +  :       70846 :             CSHA256().Write(exec_script.data(), exec_script.size()).Finalize(hash_exec_script.begin());
             +  -  +  - ]
    1937         [ +  + ]:       29787 :             if (memcmp(hash_exec_script.begin(), program.data(), 32)) {
    1938         [ +  - ]:         771 :                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
    1939                 :             :             }
    1940         [ +  - ]:       29016 :             return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
    1941         [ +  + ]:      109566 :         } else if (program.size() == WITNESS_V0_KEYHASH_SIZE) {
    1942                 :             :             // BIP141 P2WPKH: 20-byte witness v0 program (which encodes Hash160(pubkey))
    1943         [ +  + ]:      108966 :             if (stack.size() != 2) {
    1944         [ +  + ]:       55804 :                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
    1945                 :             :             }
    1946   [ +  -  +  -  :       53162 :             exec_script << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
          -  +  +  -  +  
                      - ]
    1947         [ +  - ]:       53162 :             return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
    1948                 :             :         } else {
    1949         [ +  - ]:         600 :             return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
    1950                 :             :         }
    1951   [ +  +  +  +  :      162725 :     } else if (witversion == 1 && program.size() == WITNESS_V1_TAPROOT_SIZE && !is_p2sh) {
                   +  + ]
    1952                 :             :         // BIP341 Taproot: 32-byte non-P2SH witness v1 program (which encodes a P2C-tweaked pubkey)
    1953   [ +  +  +  + ]:       80494 :         if (!(flags & SCRIPT_VERIFY_TAPROOT)) return set_success(serror);
    1954   [ +  +  +  + ]:       80395 :         if (stack.size() == 0) return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
    1955   [ +  +  +  +  :       71377 :         if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
                   +  + ]
    1956                 :             :             // Drop annex (this is non-standard; see IsWitnessStandard)
    1957                 :         161 :             const valtype& annex = SpanPopBack(stack);
    1958   [ +  -  +  -  :         161 :             execdata.m_annex_hash = (HashWriter{} << annex).GetSHA256();
                   +  - ]
    1959                 :         161 :             execdata.m_annex_present = true;
    1960                 :             :         } else {
    1961                 :       71216 :             execdata.m_annex_present = false;
    1962                 :             :         }
    1963                 :       71377 :         execdata.m_annex_init = true;
    1964         [ +  + ]:       71377 :         if (stack.size() == 1) {
    1965                 :             :             // Key path spending (stack size is 1 after removing optional annex)
    1966   [ -  +  -  +  :        2967 :             if (!checker.CheckSchnorrSignature(stack.front(), program, SigVersion::TAPROOT, execdata, serror)) {
             +  -  +  + ]
    1967                 :             :                 return false; // serror is set
    1968                 :             :             }
    1969         [ +  + ]:        2550 :             return set_success(serror);
    1970                 :             :         } else {
    1971                 :             :             // Script path spending (stack size is >1 after removing optional annex)
    1972                 :       68410 :             const valtype& control = SpanPopBack(stack);
    1973                 :       68410 :             const valtype& script = SpanPopBack(stack);
    1974   [ -  +  +  +  :       68410 :             if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE || ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) {
             +  +  +  + ]
    1975         [ +  - ]:           6 :                 return set_error(serror, SCRIPT_ERR_TAPROOT_WRONG_CONTROL_SIZE);
    1976                 :             :             }
    1977   [ -  +  +  - ]:       68404 :             execdata.m_tapleaf_hash = ComputeTapleafHash(control[0] & TAPROOT_LEAF_MASK, script);
    1978   [ +  -  +  + ]:       68404 :             if (!VerifyTaprootCommitment(control, program, execdata.m_tapleaf_hash)) {
    1979         [ +  - ]:           4 :                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
    1980                 :             :             }
    1981                 :       68400 :             execdata.m_tapleaf_hash_init = true;
    1982         [ +  + ]:       68400 :             if ((control[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
    1983                 :             :                 // Tapscript (leaf version 0xc0)
    1984                 :       66800 :                 exec_script = CScript(script.begin(), script.end());
    1985                 :       66800 :                 execdata.m_validation_weight_left = ::GetSerializeSize(witness.stack) + VALIDATION_WEIGHT_OFFSET;
    1986                 :       66800 :                 execdata.m_validation_weight_left_init = true;
    1987         [ +  - ]:       66800 :                 return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::TAPSCRIPT, checker, execdata, serror);
    1988                 :             :             }
    1989         [ +  + ]:        1600 :             if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION) {
    1990         [ +  - ]:         393 :                 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION);
    1991                 :             :             }
    1992         [ +  - ]:        1207 :             return set_success(serror);
    1993                 :             :         }
    1994   [ +  +  +  -  :        1177 :     } else if (!is_p2sh && CScript::IsPayToAnchor(witversion, program)) {
                   +  + ]
    1995                 :             :         return true;
    1996                 :             :     } else {
    1997         [ +  + ]:        1167 :         if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
    1998         [ +  - ]:      222895 :             return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
    1999                 :             :         }
    2000                 :             :         // Other version/size/p2sh combinations return true for future softfork compatibility
    2001                 :             :         return true;
    2002                 :             :     }
    2003                 :             :     // There is intentionally no return statement here, to be able to use "control reaches end of non-void function" warnings to detect gaps in the logic above.
    2004                 :      222222 : }
    2005                 :             : 
    2006                 :      757702 : bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, script_verify_flags flags, const BaseSignatureChecker& checker, ScriptError* serror)
    2007                 :             : {
    2008   [ +  +  +  + ]:      758179 :     static const CScriptWitness emptyWitness;
    2009         [ +  + ]:      757702 :     if (witness == nullptr) {
    2010                 :       67568 :         witness = &emptyWitness;
    2011                 :             :     }
    2012                 :      757702 :     bool hadWitness = false;
    2013                 :             : 
    2014         [ +  + ]:      757702 :     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
    2015                 :             : 
    2016   [ +  +  +  + ]:      757702 :     if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
    2017         [ +  - ]:      767166 :         return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
    2018                 :             :     }
    2019                 :             : 
    2020                 :             :     // scriptSig and scriptPubKey must be evaluated sequentially on the same stack
    2021                 :             :     // rather than being simply concatenated (see CVE-2010-5141)
    2022                 :      748238 :     std::vector<std::vector<unsigned char> > stack, stackCopy;
    2023   [ +  -  +  + ]:      748238 :     if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
    2024                 :             :         // serror is set
    2025                 :             :         return false;
    2026         [ +  + ]:      741427 :     if (flags & SCRIPT_VERIFY_P2SH)
    2027         [ +  - ]:      541338 :         stackCopy = stack;
    2028   [ +  -  +  + ]:      741427 :     if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
    2029                 :             :         // serror is set
    2030                 :             :         return false;
    2031         [ +  + ]:      576814 :     if (stack.empty())
    2032         [ +  - ]:        2732 :         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    2033   [ +  -  +  + ]:      574082 :     if (CastToBool(stack.back()) == false)
    2034         [ +  - ]:        7731 :         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    2035                 :             : 
    2036                 :             :     // Bare witness programs
    2037                 :      566351 :     int witnessversion;
    2038                 :      566351 :     std::vector<unsigned char> witnessprogram;
    2039         [ +  + ]:      566351 :     if (flags & SCRIPT_VERIFY_WITNESS) {
    2040   [ +  -  +  + ]:      300341 :         if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
    2041                 :      207874 :             hadWitness = true;
    2042   [ +  +  +  + ]:      207876 :             if (scriptSig.size() != 0) {
    2043                 :             :                 // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
    2044         [ +  - ]:        1074 :                 return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
    2045                 :             :             }
    2046   [ +  -  +  + ]:      206800 :             if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /*is_p2sh=*/false)) {
    2047                 :             :                 return false;
    2048                 :             :             }
    2049                 :             :             // Bypass the cleanstack check at the end. The actual stack is obviously not clean
    2050                 :             :             // for witness programs.
    2051         [ +  - ]:      124359 :             stack.resize(1);
    2052                 :             :         }
    2053                 :             :     }
    2054                 :             : 
    2055                 :             :     // Additional validation for spend-to-script-hash transactions:
    2056   [ +  +  +  -  :      482836 :     if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
                   +  + ]
    2057                 :             :     {
    2058                 :             :         // scriptSig must be literals-only or validation fails
    2059   [ +  -  +  + ]:       50218 :         if (!scriptSig.IsPushOnly())
    2060         [ +  - ]:         260 :             return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
    2061                 :             : 
    2062                 :             :         // Restore stack.
    2063                 :       49958 :         swap(stack, stackCopy);
    2064                 :             : 
    2065                 :             :         // stack cannot be empty here, because if it was the
    2066                 :             :         // P2SH  HASH <> EQUAL  scriptPubKey would be evaluated with
    2067                 :             :         // an empty stack and the EvalScript above would return false.
    2068         [ -  + ]:       49958 :         assert(!stack.empty());
    2069                 :             : 
    2070                 :       49958 :         const valtype& pubKeySerialized = stack.back();
    2071                 :       49958 :         CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
    2072         [ +  - ]:       49958 :         popstack(stack);
    2073                 :             : 
    2074   [ +  -  +  + ]:       49958 :         if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
    2075                 :             :             // serror is set
    2076                 :             :             return false;
    2077         [ +  + ]:       39199 :         if (stack.empty())
    2078         [ +  - ]:        1285 :             return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    2079   [ +  -  +  + ]:       37914 :         if (!CastToBool(stack.back()))
    2080         [ +  - ]:         281 :             return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
    2081                 :             : 
    2082                 :             :         // P2SH witness program
    2083         [ +  + ]:       37633 :         if (flags & SCRIPT_VERIFY_WITNESS) {
    2084   [ +  -  +  + ]:       32399 :             if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
    2085                 :       15936 :                 hadWitness = true;
    2086   [ -  +  +  -  :       31872 :                 if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
                   +  + ]
    2087                 :             :                     // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
    2088                 :             :                     // reintroduce malleability.
    2089         [ +  - ]:       22541 :                     return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
    2090                 :             :                 }
    2091   [ +  -  +  + ]:       15422 :                 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /*is_p2sh=*/true)) {
    2092                 :             :                     return false;
    2093                 :             :                 }
    2094                 :             :                 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
    2095                 :             :                 // for witness programs.
    2096         [ +  - ]:        6234 :                 stack.resize(1);
    2097                 :             :             }
    2098                 :             :         }
    2099                 :       49958 :     }
    2100                 :             : 
    2101                 :             :     // The CLEANSTACK check is only performed after potential P2SH evaluation,
    2102                 :             :     // as the non-P2SH evaluation of a P2SH script will obviously not result in
    2103                 :             :     // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
    2104         [ +  + ]:      460549 :     if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
    2105                 :             :         // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
    2106                 :             :         // would be possible, which is not a softfork (and P2SH should be one).
    2107         [ -  + ]:       95474 :         assert((flags & SCRIPT_VERIFY_P2SH) != 0);
    2108         [ -  + ]:       95474 :         assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
    2109   [ -  +  +  + ]:       95474 :         if (stack.size() != 1) {
    2110         [ +  - ]:        1177 :             return set_error(serror, SCRIPT_ERR_CLEANSTACK);
    2111                 :             :         }
    2112                 :             :     }
    2113                 :             : 
    2114         [ +  + ]:      459372 :     if (flags & SCRIPT_VERIFY_WITNESS) {
    2115                 :             :         // We can't check for correct unexpected witness data if P2SH was off, so require
    2116                 :             :         // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
    2117                 :             :         // possible, which is not a softfork.
    2118         [ -  + ]:      195302 :         assert((flags & SCRIPT_VERIFY_P2SH) != 0);
    2119   [ +  +  +  + ]:      195302 :         if (!hadWitness && !witness->IsNull()) {
    2120         [ +  - ]:         906 :             return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
    2121                 :             :         }
    2122                 :             :     }
    2123                 :             : 
    2124         [ +  + ]:     1001292 :     return set_success(serror);
    2125                 :      748238 : }
    2126                 :             : 
    2127                 :      112356 : size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness)
    2128                 :             : {
    2129         [ +  + ]:      112356 :     if (witversion == 0) {
    2130   [ -  +  +  + ]:       26133 :         if (witprogram.size() == WITNESS_V0_KEYHASH_SIZE)
    2131                 :             :             return 1;
    2132                 :             : 
    2133   [ +  -  -  +  :       10420 :         if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.stack.size() > 0) {
                   +  + ]
    2134                 :       10406 :             CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
    2135         [ +  - ]:       10406 :             return subscript.GetSigOpCount(true);
    2136                 :       10406 :         }
    2137                 :             :     }
    2138                 :             : 
    2139                 :             :     // Future flags may be implemented here.
    2140                 :             :     return 0;
    2141                 :             : }
    2142                 :             : 
    2143                 :      149971 : size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness& witness, script_verify_flags flags)
    2144                 :             : {
    2145         [ +  + ]:      149971 :     if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
    2146                 :             :         return 0;
    2147                 :             :     }
    2148         [ -  + ]:      149968 :     assert((flags & SCRIPT_VERIFY_P2SH) != 0);
    2149                 :             : 
    2150                 :      149968 :     int witnessversion;
    2151                 :      149968 :     std::vector<unsigned char> witnessprogram;
    2152   [ +  -  +  + ]:      149968 :     if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
    2153         [ +  - ]:      109309 :         return WitnessSigOps(witnessversion, witnessprogram, witness);
    2154                 :             :     }
    2155                 :             : 
    2156   [ +  -  +  +  :       40659 :     if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
             +  -  +  - ]
    2157         [ +  + ]:       10674 :         CScript::const_iterator pc = scriptSig.begin();
    2158                 :       10674 :         std::vector<unsigned char> data;
    2159   [ +  +  +  + ]:       59468 :         while (pc < scriptSig.end()) {
    2160                 :       19060 :             opcodetype opcode;
    2161         [ +  - ]:       19060 :             scriptSig.GetOp(pc, opcode, data);
    2162                 :             :         }
    2163                 :       10674 :         CScript subscript(data.begin(), data.end());
    2164   [ +  -  +  + ]:       10674 :         if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
    2165         [ +  - ]:        3047 :             return WitnessSigOps(witnessversion, witnessprogram, witness);
    2166                 :             :         }
    2167                 :       10674 :     }
    2168                 :             : 
    2169                 :             :     return 0;
    2170                 :      149968 : }
    2171                 :             : 
    2172                 :         340 : const std::map<std::string, script_verify_flag_name>& ScriptFlagNamesToEnum()
    2173                 :             : {
    2174                 :             : #define FLAG_NAME(flag) {std::string(#flag), SCRIPT_VERIFY_##flag}
    2175                 :         340 :     static const std::map<std::string, script_verify_flag_name> g_names_to_enum{
    2176         [ +  - ]:         318 :         FLAG_NAME(P2SH),
    2177                 :         318 :         FLAG_NAME(STRICTENC),
    2178                 :         318 :         FLAG_NAME(DERSIG),
    2179                 :         318 :         FLAG_NAME(LOW_S),
    2180                 :         318 :         FLAG_NAME(SIGPUSHONLY),
    2181                 :         318 :         FLAG_NAME(MINIMALDATA),
    2182                 :         318 :         FLAG_NAME(NULLDUMMY),
    2183                 :         318 :         FLAG_NAME(DISCOURAGE_UPGRADABLE_NOPS),
    2184                 :         318 :         FLAG_NAME(CLEANSTACK),
    2185                 :         318 :         FLAG_NAME(MINIMALIF),
    2186                 :         318 :         FLAG_NAME(NULLFAIL),
    2187                 :         318 :         FLAG_NAME(CHECKLOCKTIMEVERIFY),
    2188                 :         318 :         FLAG_NAME(CHECKSEQUENCEVERIFY),
    2189                 :         318 :         FLAG_NAME(WITNESS),
    2190                 :         318 :         FLAG_NAME(DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM),
    2191                 :         318 :         FLAG_NAME(WITNESS_PUBKEYTYPE),
    2192                 :         318 :         FLAG_NAME(CONST_SCRIPTCODE),
    2193                 :         318 :         FLAG_NAME(TAPROOT),
    2194                 :         318 :         FLAG_NAME(DISCOURAGE_UPGRADABLE_PUBKEYTYPE),
    2195                 :         318 :         FLAG_NAME(DISCOURAGE_OP_SUCCESS),
    2196                 :         318 :         FLAG_NAME(DISCOURAGE_UPGRADABLE_TAPROOT_VERSION),
    2197   [ +  +  +  -  :        3838 :     };
             +  +  -  - ]
    2198                 :             : #undef FLAG_NAME
    2199                 :         340 :     return g_names_to_enum;
    2200   [ +  -  +  -  :        3339 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  -  +  -  
                      - ]
    2201                 :             : 
    2202                 :         231 : std::vector<std::string> GetScriptFlagNames(script_verify_flags flags)
    2203                 :             : {
    2204                 :         231 :     std::vector<std::string> res;
    2205         [ +  + ]:         231 :     if (flags == SCRIPT_VERIFY_NONE) {
    2206                 :             :         return res;
    2207                 :             :     }
    2208                 :         193 :     script_verify_flags leftover = flags;
    2209   [ +  -  +  +  :        4246 :     for (const auto& [name, flag] : ScriptFlagNamesToEnum()) {
                   +  + ]
    2210         [ +  + ]:        4053 :         if ((flags & flag) != 0) {
    2211         [ +  - ]:         766 :             res.push_back(name);
    2212                 :         766 :             leftover &= ~flag;
    2213                 :             :         }
    2214                 :             :     }
    2215         [ +  + ]:         193 :     if (leftover != 0) {
    2216         [ +  - ]:           8 :         res.push_back(strprintf("0x%08x", leftover.as_int()));
    2217                 :             :     }
    2218                 :             :     return res;
    2219                 :           0 : }
        

Generated by: LCOV version 2.0-1