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-06-01 07:42:23 Functions: 100.0 % 68 68
Branches: 73.9 % 2015 1489

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

Generated by: LCOV version 2.0-1