interpreter.cpp raw

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