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