/ src / test / transaction_tests.cpp
transaction_tests.cpp
   1  // Copyright (c) 2011-present The Bitcoin Core developers
   2  // Distributed under the MIT software license, see the accompanying
   3  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   4  
   5  #include <test/data/tx_invalid.json.h>
   6  #include <test/data/tx_valid.json.h>
   7  #include <test/util/setup_common.h>
   8  
   9  #include <checkqueue.h>
  10  #include <clientversion.h>
  11  #include <consensus/amount.h>
  12  #include <consensus/consensus.h>
  13  #include <consensus/tx_check.h>
  14  #include <consensus/tx_verify.h>
  15  #include <consensus/validation.h>
  16  #include <core_io.h>
  17  #include <key.h>
  18  #include <policy/policy.h>
  19  #include <policy/settings.h>
  20  #include <primitives/transaction_identifier.h>
  21  #include <script/interpreter.h>
  22  #include <script/script.h>
  23  #include <script/script_error.h>
  24  #include <script/sigcache.h>
  25  #include <script/sign.h>
  26  #include <script/signingprovider.h>
  27  #include <script/solver.h>
  28  #include <streams.h>
  29  #include <test/util/common.h>
  30  #include <test/util/json.h>
  31  #include <test/util/random.h>
  32  #include <test/util/script.h>
  33  #include <test/util/transaction_utils.h>
  34  #include <util/strencodings.h>
  35  #include <util/string.h>
  36  #include <validation.h>
  37  
  38  #include <functional>
  39  #include <map>
  40  #include <string>
  41  
  42  #include <boost/test/unit_test.hpp>
  43  
  44  #include <univalue.h>
  45  
  46  using namespace util::hex_literals;
  47  using util::SplitString;
  48  using util::ToString;
  49  
  50  typedef std::vector<unsigned char> valtype;
  51  
  52  static CFeeRate g_dust{DUST_RELAY_TX_FEE};
  53  static bool g_bare_multi{DEFAULT_PERMIT_BAREMULTISIG};
  54  
  55  static const std::map<std::string, script_verify_flag_name>& mapFlagNames = ScriptFlagNamesToEnum();
  56  
  57  script_verify_flags ParseScriptFlags(std::string strFlags)
  58  {
  59      script_verify_flags flags = SCRIPT_VERIFY_NONE;
  60      if (strFlags.empty() || strFlags == "NONE") return flags;
  61  
  62      std::vector<std::string> words = SplitString(strFlags, ',');
  63      for (const std::string& word : words)
  64      {
  65          if (!mapFlagNames.contains(word)) {
  66              BOOST_ERROR("Bad test: unknown verification flag '" << word << "'");
  67              continue;
  68          }
  69          flags |= mapFlagNames.at(word);
  70      }
  71      return flags;
  72  }
  73  
  74  // Check that all flags in STANDARD_SCRIPT_VERIFY_FLAGS are present in mapFlagNames.
  75  bool CheckMapFlagNames()
  76  {
  77      script_verify_flags standard_flags_missing{STANDARD_SCRIPT_VERIFY_FLAGS};
  78      for (const auto& pair : mapFlagNames) {
  79          standard_flags_missing &= ~(pair.second);
  80      }
  81      return standard_flags_missing == 0;
  82  }
  83  
  84  /*
  85  * Check that the input scripts of a transaction are valid/invalid as expected.
  86  */
  87  bool CheckTxScripts(const CTransaction& tx, const std::map<COutPoint, CScript>& map_prevout_scriptPubKeys,
  88      const std::map<COutPoint, int64_t>& map_prevout_values, script_verify_flags flags,
  89      const PrecomputedTransactionData& txdata, const std::string& strTest, bool expect_valid)
  90  {
  91      bool tx_valid = true;
  92      ScriptError err = expect_valid ? SCRIPT_ERR_UNKNOWN_ERROR : SCRIPT_ERR_OK;
  93      for (unsigned int i = 0; i < tx.vin.size() && tx_valid; ++i) {
  94          const CTxIn input = tx.vin[i];
  95          const CAmount amount = map_prevout_values.contains(input.prevout) ? map_prevout_values.at(input.prevout) : 0;
  96          try {
  97              tx_valid = VerifyScript(input.scriptSig, map_prevout_scriptPubKeys.at(input.prevout),
  98                  &input.scriptWitness, flags, TransactionSignatureChecker(&tx, i, amount, txdata, MissingDataBehavior::ASSERT_FAIL), &err);
  99          } catch (...) {
 100              BOOST_ERROR("Bad test: " << strTest);
 101              return true; // The test format is bad and an error is thrown. Return true to silence further error.
 102          }
 103          if (expect_valid) {
 104              BOOST_CHECK_MESSAGE(tx_valid, strTest);
 105              BOOST_CHECK_MESSAGE((err == SCRIPT_ERR_OK), ScriptErrorString(err));
 106              err = SCRIPT_ERR_UNKNOWN_ERROR;
 107          }
 108      }
 109      if (!expect_valid) {
 110          BOOST_CHECK_MESSAGE(!tx_valid, strTest);
 111          BOOST_CHECK_MESSAGE((err != SCRIPT_ERR_OK), ScriptErrorString(err));
 112      }
 113      return (tx_valid == expect_valid);
 114  }
 115  
 116  /*
 117   * Trim or fill flags to make the combination valid:
 118   * WITNESS must be used with P2SH
 119   * CLEANSTACK must be used WITNESS and P2SH
 120   */
 121  
 122  script_verify_flags TrimFlags(script_verify_flags flags)
 123  {
 124      // WITNESS requires P2SH
 125      if (!(flags & SCRIPT_VERIFY_P2SH)) flags &= ~SCRIPT_VERIFY_WITNESS;
 126  
 127      // CLEANSTACK requires WITNESS (and transitively CLEANSTACK requires P2SH)
 128      if (!(flags & SCRIPT_VERIFY_WITNESS)) flags &= ~SCRIPT_VERIFY_CLEANSTACK;
 129      Assert(IsValidFlagCombination(flags));
 130      return flags;
 131  }
 132  
 133  script_verify_flags FillFlags(script_verify_flags flags)
 134  {
 135      // CLEANSTACK implies WITNESS
 136      if (flags & SCRIPT_VERIFY_CLEANSTACK) flags |= SCRIPT_VERIFY_WITNESS;
 137  
 138      // WITNESS implies P2SH (and transitively CLEANSTACK implies P2SH)
 139      if (flags & SCRIPT_VERIFY_WITNESS) flags |= SCRIPT_VERIFY_P2SH;
 140      Assert(IsValidFlagCombination(flags));
 141      return flags;
 142  }
 143  
 144  // Exclude each possible script verify flag from flags. Returns a set of these flag combinations
 145  // that are valid and without duplicates. For example: if flags=1111 and the 4 possible flags are
 146  // 0001, 0010, 0100, and 1000, this should return the set {0111, 1011, 1101, 1110}.
 147  // Assumes that mapFlagNames contains all script verify flags.
 148  std::set<script_verify_flags> ExcludeIndividualFlags(script_verify_flags flags)
 149  {
 150      std::set<script_verify_flags> flags_combos;
 151      for (const auto& pair : mapFlagNames) {
 152          script_verify_flags flags_excluding_one = TrimFlags(flags & ~(pair.second));
 153          if (flags != flags_excluding_one) {
 154              flags_combos.insert(flags_excluding_one);
 155          }
 156      }
 157      return flags_combos;
 158  }
 159  
 160  BOOST_FIXTURE_TEST_SUITE(transaction_tests, BasicTestingSetup)
 161  
 162  BOOST_AUTO_TEST_CASE(tx_valid)
 163  {
 164      BOOST_CHECK_MESSAGE(CheckMapFlagNames(), "mapFlagNames is missing a script verification flag");
 165      // Read tests from test/data/tx_valid.json
 166      UniValue tests = read_json(json_tests::tx_valid);
 167  
 168      for (unsigned int idx = 0; idx < tests.size(); idx++) {
 169          const UniValue& test = tests[idx];
 170          std::string strTest = test.write();
 171          if (test[0].isArray())
 172          {
 173              if (test.size() != 3 || !test[1].isStr() || !test[2].isStr())
 174              {
 175                  BOOST_ERROR("Bad test: " << strTest);
 176                  continue;
 177              }
 178  
 179              std::map<COutPoint, CScript> mapprevOutScriptPubKeys;
 180              std::map<COutPoint, int64_t> mapprevOutValues;
 181              UniValue inputs = test[0].get_array();
 182              bool fValid = true;
 183              for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) {
 184                  const UniValue& input = inputs[inpIdx];
 185                  if (!input.isArray()) {
 186                      fValid = false;
 187                      break;
 188                  }
 189                  const UniValue& vinput = input.get_array();
 190                  if (vinput.size() < 3 || vinput.size() > 4)
 191                  {
 192                      fValid = false;
 193                      break;
 194                  }
 195                  COutPoint outpoint{Txid::FromHex(vinput[0].get_str()).value(), uint32_t(vinput[1].getInt<int>())};
 196                  mapprevOutScriptPubKeys[outpoint] = ParseScript(vinput[2].get_str());
 197                  if (vinput.size() >= 4)
 198                  {
 199                      mapprevOutValues[outpoint] = vinput[3].getInt<int64_t>();
 200                  }
 201              }
 202              if (!fValid)
 203              {
 204                  BOOST_ERROR("Bad test: " << strTest);
 205                  continue;
 206              }
 207  
 208              std::string transaction = test[1].get_str();
 209              DataStream stream(ParseHex(transaction));
 210              CTransaction tx(deserialize, TX_WITH_WITNESS, stream);
 211  
 212              TxValidationState state;
 213              BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest);
 214              BOOST_CHECK(state.IsValid());
 215  
 216              PrecomputedTransactionData txdata(tx);
 217              script_verify_flags verify_flags = ParseScriptFlags(test[2].get_str());
 218  
 219              // Check that the test gives a valid combination of flags (otherwise VerifyScript will throw). Don't edit the flags.
 220              if (~verify_flags != FillFlags(~verify_flags)) {
 221                  BOOST_ERROR("Bad test flags: " << strTest);
 222              }
 223  
 224              BOOST_CHECK_MESSAGE(CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, ~verify_flags, txdata, strTest, /*expect_valid=*/true),
 225                                  "Tx unexpectedly failed: " << strTest);
 226  
 227              // Backwards compatibility of script verification flags: Removing any flag(s) should not invalidate a valid transaction
 228              for (const auto& [name, flag] : mapFlagNames) {
 229                  // Removing individual flags
 230                  script_verify_flags flags = TrimFlags(~(verify_flags | flag));
 231                  if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/true)) {
 232                      BOOST_ERROR("Tx unexpectedly failed with flag " << name << " unset: " << strTest);
 233                  }
 234                  // Removing random combinations of flags
 235                  flags = TrimFlags(~(verify_flags | script_verify_flags::from_int(m_rng.randbits(MAX_SCRIPT_VERIFY_FLAGS_BITS))));
 236                  if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/true)) {
 237                      BOOST_ERROR("Tx unexpectedly failed with random flags " << ToString(flags.as_int()) << ": " << strTest);
 238                  }
 239              }
 240  
 241              // Check that flags are maximal: transaction should fail if any unset flags are set.
 242              for (auto flags_excluding_one : ExcludeIndividualFlags(verify_flags)) {
 243                  if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, ~flags_excluding_one, txdata, strTest, /*expect_valid=*/false)) {
 244                      BOOST_ERROR("Too many flags unset: " << strTest);
 245                  }
 246              }
 247          }
 248      }
 249  }
 250  
 251  BOOST_AUTO_TEST_CASE(tx_invalid)
 252  {
 253      // Read tests from test/data/tx_invalid.json
 254      UniValue tests = read_json(json_tests::tx_invalid);
 255  
 256      for (unsigned int idx = 0; idx < tests.size(); idx++) {
 257          const UniValue& test = tests[idx];
 258          std::string strTest = test.write();
 259          if (test[0].isArray())
 260          {
 261              if (test.size() != 3 || !test[1].isStr() || !test[2].isStr())
 262              {
 263                  BOOST_ERROR("Bad test: " << strTest);
 264                  continue;
 265              }
 266  
 267              std::map<COutPoint, CScript> mapprevOutScriptPubKeys;
 268              std::map<COutPoint, int64_t> mapprevOutValues;
 269              UniValue inputs = test[0].get_array();
 270              bool fValid = true;
 271              for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) {
 272                  const UniValue& input = inputs[inpIdx];
 273                  if (!input.isArray()) {
 274                      fValid = false;
 275                      break;
 276                  }
 277                  const UniValue& vinput = input.get_array();
 278                  if (vinput.size() < 3 || vinput.size() > 4)
 279                  {
 280                      fValid = false;
 281                      break;
 282                  }
 283                  COutPoint outpoint{Txid::FromHex(vinput[0].get_str()).value(), uint32_t(vinput[1].getInt<int>())};
 284                  mapprevOutScriptPubKeys[outpoint] = ParseScript(vinput[2].get_str());
 285                  if (vinput.size() >= 4)
 286                  {
 287                      mapprevOutValues[outpoint] = vinput[3].getInt<int64_t>();
 288                  }
 289              }
 290              if (!fValid)
 291              {
 292                  BOOST_ERROR("Bad test: " << strTest);
 293                  continue;
 294              }
 295  
 296              std::string transaction = test[1].get_str();
 297              DataStream stream(ParseHex(transaction));
 298              CTransaction tx(deserialize, TX_WITH_WITNESS, stream);
 299  
 300              TxValidationState state;
 301              if (!CheckTransaction(tx, state) || state.IsInvalid()) {
 302                  BOOST_CHECK_MESSAGE(test[2].get_str() == "BADTX", strTest);
 303                  continue;
 304              }
 305  
 306              PrecomputedTransactionData txdata(tx);
 307              script_verify_flags verify_flags = ParseScriptFlags(test[2].get_str());
 308  
 309              // Check that the test gives a valid combination of flags (otherwise VerifyScript will throw). Don't edit the flags.
 310              if (verify_flags != FillFlags(verify_flags)) {
 311                  BOOST_ERROR("Bad test flags: " << strTest);
 312              }
 313  
 314              // Not using FillFlags() in the main test, in order to detect invalid verifyFlags combination
 315              BOOST_CHECK_MESSAGE(CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, verify_flags, txdata, strTest, /*expect_valid=*/false),
 316                                  "Tx unexpectedly passed: " << strTest);
 317  
 318              // Backwards compatibility of script verification flags: Adding any flag(s) should not validate an invalid transaction
 319              for (const auto& [name, flag] : mapFlagNames) {
 320                  script_verify_flags flags = FillFlags(verify_flags | flag);
 321                  // Adding individual flags
 322                  if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/false)) {
 323                      BOOST_ERROR("Tx unexpectedly passed with flag " << name << " set: " << strTest);
 324                  }
 325                  // Adding random combinations of flags
 326                  flags = FillFlags(verify_flags | script_verify_flags::from_int(m_rng.randbits(MAX_SCRIPT_VERIFY_FLAGS_BITS)));
 327                  if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/false)) {
 328                      BOOST_ERROR("Tx unexpectedly passed with random flags " << name << ": " << strTest);
 329                  }
 330              }
 331  
 332              // Check that flags are minimal: transaction should succeed if any set flags are unset.
 333              for (auto flags_excluding_one : ExcludeIndividualFlags(verify_flags)) {
 334                  if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags_excluding_one, txdata, strTest, /*expect_valid=*/true)) {
 335                      BOOST_ERROR("Too many flags set: " << strTest);
 336                  }
 337              }
 338          }
 339      }
 340  }
 341  
 342  BOOST_AUTO_TEST_CASE(tx_no_inputs)
 343  {
 344      CMutableTransaction empty;
 345  
 346      TxValidationState state;
 347      BOOST_CHECK_MESSAGE(!CheckTransaction(CTransaction(empty), state), "Transaction with no inputs should be invalid.");
 348      BOOST_CHECK(state.GetRejectReason() == "bad-txns-vin-empty");
 349  }
 350  
 351  BOOST_AUTO_TEST_CASE(tx_oversized)
 352  {
 353      auto createTransaction =[](size_t payloadSize) {
 354          CMutableTransaction tx;
 355          tx.vin.resize(1);
 356          tx.vout.emplace_back(1, CScript() << OP_RETURN << std::vector<unsigned char>(payloadSize));
 357          return CTransaction(tx);
 358      };
 359      const auto maxTransactionSize = MAX_BLOCK_WEIGHT / WITNESS_SCALE_FACTOR;
 360      const auto oversizedTransactionBaseSize = ::GetSerializeSize(TX_NO_WITNESS(createTransaction(maxTransactionSize))) - maxTransactionSize;
 361  
 362      auto maxPayloadSize = maxTransactionSize - oversizedTransactionBaseSize;
 363      {
 364          TxValidationState state;
 365          CheckTransaction(createTransaction(maxPayloadSize), state);
 366          BOOST_CHECK(state.GetRejectReason() != "bad-txns-oversize");
 367      }
 368  
 369      maxPayloadSize += 1;
 370      {
 371          TxValidationState state;
 372          BOOST_CHECK_MESSAGE(!CheckTransaction(createTransaction(maxPayloadSize), state), "Oversized transaction should be invalid");
 373          BOOST_CHECK(state.GetRejectReason() == "bad-txns-oversize");
 374      }
 375  }
 376  
 377  BOOST_AUTO_TEST_CASE(basic_transaction_tests)
 378  {
 379      // Random real transaction (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436)
 380      unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x6b, 0xff, 0x7f, 0xcd, 0x4f, 0x85, 0x65, 0xef, 0x40, 0x6d, 0xd5, 0xd6, 0x3d, 0x4f, 0xf9, 0x4f, 0x31, 0x8f, 0xe8, 0x20, 0x27, 0xfd, 0x4d, 0xc4, 0x51, 0xb0, 0x44, 0x74, 0x01, 0x9f, 0x74, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, 0x0d, 0xc6, 0xae, 0xce, 0xfe, 0x1e, 0x06, 0xef, 0xdf, 0x05, 0x77, 0x37, 0x57, 0xde, 0xb1, 0x68, 0x82, 0x09, 0x30, 0xe3, 0xb0, 0xd0, 0x3f, 0x46, 0xf5, 0xfc, 0xf1, 0x50, 0xbf, 0x99, 0x0c, 0x02, 0x21, 0x00, 0xd2, 0x5b, 0x5c, 0x87, 0x04, 0x00, 0x76, 0xe4, 0xf2, 0x53, 0xf8, 0x26, 0x2e, 0x76, 0x3e, 0x2d, 0xd5, 0x1e, 0x7f, 0xf0, 0xbe, 0x15, 0x77, 0x27, 0xc4, 0xbc, 0x42, 0x80, 0x7f, 0x17, 0xbd, 0x39, 0x01, 0x41, 0x04, 0xe6, 0xc2, 0x6e, 0xf6, 0x7d, 0xc6, 0x10, 0xd2, 0xcd, 0x19, 0x24, 0x84, 0x78, 0x9a, 0x6c, 0xf9, 0xae, 0xa9, 0x93, 0x0b, 0x94, 0x4b, 0x7e, 0x2d, 0xb5, 0x34, 0x2b, 0x9d, 0x9e, 0x5b, 0x9f, 0xf7, 0x9a, 0xff, 0x9a, 0x2e, 0xe1, 0x97, 0x8d, 0xd7, 0xfd, 0x01, 0xdf, 0xc5, 0x22, 0xee, 0x02, 0x28, 0x3d, 0x3b, 0x06, 0xa9, 0xd0, 0x3a, 0xcf, 0x80, 0x96, 0x96, 0x8d, 0x7d, 0xbb, 0x0f, 0x91, 0x78, 0xff, 0xff, 0xff, 0xff, 0x02, 0x8b, 0xa7, 0x94, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xba, 0xde, 0xec, 0xfd, 0xef, 0x05, 0x07, 0x24, 0x7f, 0xc8, 0xf7, 0x42, 0x41, 0xd7, 0x3b, 0xc0, 0x39, 0x97, 0x2d, 0x7b, 0x88, 0xac, 0x40, 0x94, 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xc1, 0x09, 0x32, 0x48, 0x3f, 0xec, 0x93, 0xed, 0x51, 0xf5, 0xfe, 0x95, 0xe7, 0x25, 0x59, 0xf2, 0xcc, 0x70, 0x43, 0xf9, 0x88, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00};
 381      std::vector<unsigned char> vch(ch, ch + sizeof(ch) -1);
 382      CMutableTransaction tx;
 383      SpanReader{vch} >> TX_WITH_WITNESS(tx);
 384      TxValidationState state;
 385      BOOST_CHECK_MESSAGE(CheckTransaction(CTransaction(tx), state) && state.IsValid(), "Simple deserialized transaction should be valid.");
 386  
 387      // Check that duplicate txins fail
 388      tx.vin.push_back(tx.vin[0]);
 389      BOOST_CHECK_MESSAGE(!CheckTransaction(CTransaction(tx), state) || !state.IsValid(), "Transaction with duplicate txins should be invalid.");
 390  }
 391  
 392  BOOST_AUTO_TEST_CASE(test_Get)
 393  {
 394      FillableSigningProvider keystore;
 395      CCoinsViewCache coins{&CoinsViewEmpty::Get()};
 396      std::vector<CMutableTransaction> dummyTransactions =
 397          SetupDummyInputs(keystore, coins, {11*CENT, 50*CENT, 21*CENT, 22*CENT});
 398  
 399      CMutableTransaction t1;
 400      t1.vin.resize(3);
 401      t1.vin[0].prevout.hash = dummyTransactions[0].GetHash();
 402      t1.vin[0].prevout.n = 1;
 403      t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0);
 404      t1.vin[1].prevout.hash = dummyTransactions[1].GetHash();
 405      t1.vin[1].prevout.n = 0;
 406      t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
 407      t1.vin[2].prevout.hash = dummyTransactions[1].GetHash();
 408      t1.vin[2].prevout.n = 1;
 409      t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
 410      t1.vout.resize(2);
 411      t1.vout[0].nValue = 90*CENT;
 412      t1.vout[0].scriptPubKey << OP_1;
 413  
 414      BOOST_CHECK(ValidateInputsStandardness(CTransaction(t1), coins).IsValid());
 415  }
 416  
 417  static void CreateCreditAndSpend(const FillableSigningProvider& keystore, const CScript& outscript, CTransactionRef& output, CMutableTransaction& input, bool success = true)
 418  {
 419      CMutableTransaction outputm;
 420      outputm.version = 1;
 421      outputm.vin.resize(1);
 422      outputm.vin[0].prevout.SetNull();
 423      outputm.vin[0].scriptSig = CScript();
 424      outputm.vout.resize(1);
 425      outputm.vout[0].nValue = 1;
 426      outputm.vout[0].scriptPubKey = outscript;
 427      DataStream ssout;
 428      ssout << TX_WITH_WITNESS(outputm);
 429      ssout >> TX_WITH_WITNESS(output);
 430      assert(output->vin.size() == 1);
 431      assert(output->vin[0] == outputm.vin[0]);
 432      assert(output->vout.size() == 1);
 433      assert(output->vout[0] == outputm.vout[0]);
 434  
 435      CMutableTransaction inputm;
 436      inputm.version = 1;
 437      inputm.vin.resize(1);
 438      inputm.vin[0].prevout.hash = output->GetHash();
 439      inputm.vin[0].prevout.n = 0;
 440      inputm.vout.resize(1);
 441      inputm.vout[0].nValue = 1;
 442      inputm.vout[0].scriptPubKey = CScript();
 443      SignatureData empty;
 444      bool ret = SignSignature(keystore, *output, inputm, 0, SIGHASH_ALL, empty);
 445      assert(ret == success);
 446      DataStream ssin;
 447      ssin << TX_WITH_WITNESS(inputm);
 448      ssin >> TX_WITH_WITNESS(input);
 449      assert(input.vin.size() == 1);
 450      assert(input.vin[0] == inputm.vin[0]);
 451      assert(input.vout.size() == 1);
 452      assert(input.vout[0] == inputm.vout[0]);
 453      assert(input.vin[0].scriptWitness.stack == inputm.vin[0].scriptWitness.stack);
 454  }
 455  
 456  static void CheckWithFlag(const CTransactionRef& output, const CMutableTransaction& input, script_verify_flags flags, bool success)
 457  {
 458      ScriptError error;
 459      CTransaction inputi(input);
 460      bool ret = VerifyScript(inputi.vin[0].scriptSig, output->vout[0].scriptPubKey, &inputi.vin[0].scriptWitness, flags, TransactionSignatureChecker(&inputi, 0, output->vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &error);
 461      assert(ret == success);
 462  }
 463  
 464  static CScript PushAll(const std::vector<valtype>& values)
 465  {
 466      CScript result;
 467      for (const valtype& v : values) {
 468          if (v.size() == 0) {
 469              result << OP_0;
 470          } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
 471              result << CScript::EncodeOP_N(v[0]);
 472          } else if (v.size() == 1 && v[0] == 0x81) {
 473              result << OP_1NEGATE;
 474          } else {
 475              result << v;
 476          }
 477      }
 478      return result;
 479  }
 480  
 481  static void ReplaceRedeemScript(CScript& script, const CScript& redeemScript)
 482  {
 483      std::vector<valtype> stack;
 484      EvalScript(stack, script, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE);
 485      assert(stack.size() > 0);
 486      stack.back() = std::vector<unsigned char>(redeemScript.begin(), redeemScript.end());
 487      script = PushAll(stack);
 488  }
 489  
 490  BOOST_AUTO_TEST_CASE(test_big_witness_transaction)
 491  {
 492      CMutableTransaction mtx;
 493      mtx.version = 1;
 494  
 495      CKey key = GenerateRandomKey(); // Need to use compressed keys in segwit or the signing will fail
 496      FillableSigningProvider keystore;
 497      BOOST_CHECK(keystore.AddKeyPubKey(key, key.GetPubKey()));
 498      CKeyID hash = key.GetPubKey().GetID();
 499      CScript scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(hash.begin(), hash.end());
 500  
 501      std::vector<int> sigHashes;
 502      sigHashes.push_back(SIGHASH_NONE | SIGHASH_ANYONECANPAY);
 503      sigHashes.push_back(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY);
 504      sigHashes.push_back(SIGHASH_ALL | SIGHASH_ANYONECANPAY);
 505      sigHashes.push_back(SIGHASH_NONE);
 506      sigHashes.push_back(SIGHASH_SINGLE);
 507      sigHashes.push_back(SIGHASH_ALL);
 508  
 509      // create a big transaction of 4500 inputs signed by the same key
 510      for(uint32_t ij = 0; ij < 4500; ij++) {
 511          uint32_t i = mtx.vin.size();
 512          COutPoint outpoint{Txid{"0000000000000000000000000000000000000000000000000000000000000100"}, i};
 513  
 514          mtx.vin.resize(mtx.vin.size() + 1);
 515          mtx.vin[i].prevout = outpoint;
 516          mtx.vin[i].scriptSig = CScript();
 517  
 518          mtx.vout.resize(mtx.vout.size() + 1);
 519          mtx.vout[i].nValue = 1000;
 520          mtx.vout[i].scriptPubKey = CScript() << OP_1;
 521      }
 522  
 523      // sign all inputs
 524      for(uint32_t i = 0; i < mtx.vin.size(); i++) {
 525          SignatureData empty;
 526          bool hashSigned = SignSignature(keystore, scriptPubKey, mtx, i, 1000, sigHashes.at(i % sigHashes.size()), empty);
 527          assert(hashSigned);
 528      }
 529  
 530      DataStream ssout;
 531      ssout << TX_WITH_WITNESS(mtx);
 532      CTransaction tx(deserialize, TX_WITH_WITNESS, ssout);
 533  
 534      // check all inputs concurrently, with the cache
 535      PrecomputedTransactionData txdata(tx);
 536      CCheckQueue<CScriptCheck> scriptcheckqueue(/*batch_size=*/128, /*worker_threads_num=*/20);
 537      CCheckQueueControl<CScriptCheck> control(scriptcheckqueue);
 538  
 539      std::vector<Coin> coins;
 540      for(uint32_t i = 0; i < mtx.vin.size(); i++) {
 541          Coin coin;
 542          coin.nHeight = 1;
 543          coin.fCoinBase = false;
 544          coin.out.nValue = 1000;
 545          coin.out.scriptPubKey = scriptPubKey;
 546          coins.emplace_back(std::move(coin));
 547      }
 548  
 549      SignatureCache signature_cache{DEFAULT_SIGNATURE_CACHE_BYTES};
 550  
 551      for(uint32_t i = 0; i < mtx.vin.size(); i++) {
 552          std::vector<CScriptCheck> vChecks;
 553          vChecks.emplace_back(coins[tx.vin[i].prevout.n].out, tx, signature_cache, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false, &txdata);
 554          control.Add(std::move(vChecks));
 555      }
 556  
 557      bool controlCheck = !control.Complete().has_value();
 558      assert(controlCheck);
 559  }
 560  
 561  SignatureData CombineSignatures(const CMutableTransaction& input1, const CMutableTransaction& input2, const CTransactionRef tx)
 562  {
 563      SignatureData sigdata;
 564      sigdata = DataFromTransaction(input1, 0, tx->vout[0]);
 565      sigdata.MergeSignatureData(DataFromTransaction(input2, 0, tx->vout[0]));
 566      ProduceSignature(DUMMY_SIGNING_PROVIDER, MutableTransactionSignatureCreator(input1, 0, tx->vout[0].nValue, {.sighash_type = SIGHASH_DEFAULT}), tx->vout[0].scriptPubKey, sigdata);
 567      return sigdata;
 568  }
 569  
 570  BOOST_AUTO_TEST_CASE(test_witness)
 571  {
 572      FillableSigningProvider keystore, keystore2;
 573      CKey key1 = GenerateRandomKey();
 574      CKey key2 = GenerateRandomKey();
 575      CKey key3 = GenerateRandomKey();
 576      CKey key1L = GenerateRandomKey(/*compressed=*/false);
 577      CKey key2L = GenerateRandomKey(/*compressed=*/false);
 578      CPubKey pubkey1 = key1.GetPubKey();
 579      CPubKey pubkey2 = key2.GetPubKey();
 580      CPubKey pubkey3 = key3.GetPubKey();
 581      CPubKey pubkey1L = key1L.GetPubKey();
 582      CPubKey pubkey2L = key2L.GetPubKey();
 583      BOOST_CHECK(keystore.AddKeyPubKey(key1, pubkey1));
 584      BOOST_CHECK(keystore.AddKeyPubKey(key2, pubkey2));
 585      BOOST_CHECK(keystore.AddKeyPubKey(key1L, pubkey1L));
 586      BOOST_CHECK(keystore.AddKeyPubKey(key2L, pubkey2L));
 587      CScript scriptPubkey1, scriptPubkey2, scriptPubkey1L, scriptPubkey2L, scriptMulti;
 588      scriptPubkey1 << ToByteVector(pubkey1) << OP_CHECKSIG;
 589      scriptPubkey2 << ToByteVector(pubkey2) << OP_CHECKSIG;
 590      scriptPubkey1L << ToByteVector(pubkey1L) << OP_CHECKSIG;
 591      scriptPubkey2L << ToByteVector(pubkey2L) << OP_CHECKSIG;
 592      std::vector<CPubKey> oneandthree;
 593      oneandthree.push_back(pubkey1);
 594      oneandthree.push_back(pubkey3);
 595      scriptMulti = GetScriptForMultisig(2, oneandthree);
 596      BOOST_CHECK(keystore.AddCScript(scriptPubkey1));
 597      BOOST_CHECK(keystore.AddCScript(scriptPubkey2));
 598      BOOST_CHECK(keystore.AddCScript(scriptPubkey1L));
 599      BOOST_CHECK(keystore.AddCScript(scriptPubkey2L));
 600      BOOST_CHECK(keystore.AddCScript(scriptMulti));
 601      CScript destination_script_1, destination_script_2, destination_script_1L, destination_script_2L, destination_script_multi;
 602      destination_script_1 = GetScriptForDestination(WitnessV0KeyHash(pubkey1));
 603      destination_script_2 = GetScriptForDestination(WitnessV0KeyHash(pubkey2));
 604      destination_script_1L = GetScriptForDestination(WitnessV0KeyHash(pubkey1L));
 605      destination_script_2L = GetScriptForDestination(WitnessV0KeyHash(pubkey2L));
 606      destination_script_multi = GetScriptForDestination(WitnessV0ScriptHash(scriptMulti));
 607      BOOST_CHECK(keystore.AddCScript(destination_script_1));
 608      BOOST_CHECK(keystore.AddCScript(destination_script_2));
 609      BOOST_CHECK(keystore.AddCScript(destination_script_1L));
 610      BOOST_CHECK(keystore.AddCScript(destination_script_2L));
 611      BOOST_CHECK(keystore.AddCScript(destination_script_multi));
 612      BOOST_CHECK(keystore2.AddCScript(scriptMulti));
 613      BOOST_CHECK(keystore2.AddCScript(destination_script_multi));
 614      BOOST_CHECK(keystore2.AddKeyPubKey(key3, pubkey3));
 615  
 616      CTransactionRef output1, output2;
 617      CMutableTransaction input1, input2;
 618  
 619      // Normal pay-to-compressed-pubkey.
 620      CreateCreditAndSpend(keystore, scriptPubkey1, output1, input1);
 621      CreateCreditAndSpend(keystore, scriptPubkey2, output2, input2);
 622      CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
 623      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
 624      CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true);
 625      CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
 626      CheckWithFlag(output1, input2, SCRIPT_VERIFY_NONE, false);
 627      CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, false);
 628      CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false);
 629      CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false);
 630  
 631      // P2SH pay-to-compressed-pubkey.
 632      CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptPubkey1)), output1, input1);
 633      CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptPubkey2)), output2, input2);
 634      ReplaceRedeemScript(input2.vin[0].scriptSig, scriptPubkey1);
 635      CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
 636      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
 637      CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true);
 638      CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
 639      CheckWithFlag(output1, input2, SCRIPT_VERIFY_NONE, true);
 640      CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, false);
 641      CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false);
 642      CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false);
 643  
 644      // Witness pay-to-compressed-pubkey (v0).
 645      CreateCreditAndSpend(keystore, destination_script_1, output1, input1);
 646      CreateCreditAndSpend(keystore, destination_script_2, output2, input2);
 647      CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
 648      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
 649      CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true);
 650      CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
 651      CheckWithFlag(output1, input2, SCRIPT_VERIFY_NONE, true);
 652      CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, true);
 653      CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false);
 654      CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false);
 655  
 656      // P2SH witness pay-to-compressed-pubkey (v0).
 657      CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_1)), output1, input1);
 658      CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_2)), output2, input2);
 659      ReplaceRedeemScript(input2.vin[0].scriptSig, destination_script_1);
 660      CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
 661      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
 662      CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true);
 663      CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
 664      CheckWithFlag(output1, input2, SCRIPT_VERIFY_NONE, true);
 665      CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, true);
 666      CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false);
 667      CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false);
 668  
 669      // Normal pay-to-uncompressed-pubkey.
 670      CreateCreditAndSpend(keystore, scriptPubkey1L, output1, input1);
 671      CreateCreditAndSpend(keystore, scriptPubkey2L, output2, input2);
 672      CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
 673      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
 674      CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true);
 675      CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
 676      CheckWithFlag(output1, input2, SCRIPT_VERIFY_NONE, false);
 677      CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, false);
 678      CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false);
 679      CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false);
 680  
 681      // P2SH pay-to-uncompressed-pubkey.
 682      CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptPubkey1L)), output1, input1);
 683      CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptPubkey2L)), output2, input2);
 684      ReplaceRedeemScript(input2.vin[0].scriptSig, scriptPubkey1L);
 685      CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
 686      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
 687      CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true);
 688      CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
 689      CheckWithFlag(output1, input2, SCRIPT_VERIFY_NONE, true);
 690      CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, false);
 691      CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false);
 692      CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false);
 693  
 694      // Signing disabled for witness pay-to-uncompressed-pubkey (v1).
 695      CreateCreditAndSpend(keystore, destination_script_1L, output1, input1, false);
 696      CreateCreditAndSpend(keystore, destination_script_2L, output2, input2, false);
 697  
 698      // Signing disabled for P2SH witness pay-to-uncompressed-pubkey (v1).
 699      CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_1L)), output1, input1, false);
 700      CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_2L)), output2, input2, false);
 701  
 702      // Normal 2-of-2 multisig
 703      CreateCreditAndSpend(keystore, scriptMulti, output1, input1, false);
 704      CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, false);
 705      CreateCreditAndSpend(keystore2, scriptMulti, output2, input2, false);
 706      CheckWithFlag(output2, input2, SCRIPT_VERIFY_NONE, false);
 707      BOOST_CHECK(*output1 == *output2);
 708      UpdateInput(input1.vin[0], CombineSignatures(input1, input2, output1));
 709      CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
 710  
 711      // P2SH 2-of-2 multisig
 712      CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptMulti)), output1, input1, false);
 713      CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
 714      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, false);
 715      CreateCreditAndSpend(keystore2, GetScriptForDestination(ScriptHash(scriptMulti)), output2, input2, false);
 716      CheckWithFlag(output2, input2, SCRIPT_VERIFY_NONE, true);
 717      CheckWithFlag(output2, input2, SCRIPT_VERIFY_P2SH, false);
 718      BOOST_CHECK(*output1 == *output2);
 719      UpdateInput(input1.vin[0], CombineSignatures(input1, input2, output1));
 720      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
 721      CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
 722  
 723      // Witness 2-of-2 multisig
 724      CreateCreditAndSpend(keystore, destination_script_multi, output1, input1, false);
 725      CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
 726      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false);
 727      CreateCreditAndSpend(keystore2, destination_script_multi, output2, input2, false);
 728      CheckWithFlag(output2, input2, SCRIPT_VERIFY_NONE, true);
 729      CheckWithFlag(output2, input2, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false);
 730      BOOST_CHECK(*output1 == *output2);
 731      UpdateInput(input1.vin[0], CombineSignatures(input1, input2, output1));
 732      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, true);
 733      CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
 734  
 735      // P2SH witness 2-of-2 multisig
 736      CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_multi)), output1, input1, false);
 737      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
 738      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false);
 739      CreateCreditAndSpend(keystore2, GetScriptForDestination(ScriptHash(destination_script_multi)), output2, input2, false);
 740      CheckWithFlag(output2, input2, SCRIPT_VERIFY_P2SH, true);
 741      CheckWithFlag(output2, input2, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false);
 742      BOOST_CHECK(*output1 == *output2);
 743      UpdateInput(input1.vin[0], CombineSignatures(input1, input2, output1));
 744      CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, true);
 745      CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
 746  }
 747  
 748  BOOST_AUTO_TEST_CASE(test_IsStandard)
 749  {
 750      FillableSigningProvider keystore;
 751      CCoinsViewCache coins{&CoinsViewEmpty::Get()};
 752      std::vector<CMutableTransaction> dummyTransactions =
 753          SetupDummyInputs(keystore, coins, {11*CENT, 50*CENT, 21*CENT, 22*CENT});
 754  
 755      CMutableTransaction t;
 756      t.vin.resize(1);
 757      t.vin[0].prevout.hash = dummyTransactions[0].GetHash();
 758      t.vin[0].prevout.n = 1;
 759      t.vin[0].scriptSig << std::vector<unsigned char>(65, 0);
 760      t.vout.resize(1);
 761      t.vout[0].nValue = 90*CENT;
 762      CKey key = GenerateRandomKey();
 763      t.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey()));
 764  
 765      constexpr auto CheckIsStandard = [](const auto& t, const unsigned int max_op_return_relay = MAX_OP_RETURN_RELAY) {
 766          std::string reason;
 767          BOOST_CHECK(IsStandardTx(CTransaction{t}, max_op_return_relay, g_bare_multi, g_dust, reason));
 768          BOOST_CHECK(reason.empty());
 769      };
 770      constexpr auto CheckIsNotStandard = [](const auto& t, const std::string& reason_in, const unsigned int max_op_return_relay = MAX_OP_RETURN_RELAY) {
 771          std::string reason;
 772          BOOST_CHECK(!IsStandardTx(CTransaction{t}, max_op_return_relay, g_bare_multi, g_dust, reason));
 773          BOOST_CHECK_EQUAL(reason_in, reason);
 774      };
 775  
 776      CheckIsStandard(t);
 777  
 778      // Check dust with default relay fee:
 779      CAmount nDustThreshold = 182 * g_dust.GetFeePerK() / 1000;
 780      BOOST_CHECK_EQUAL(nDustThreshold, 546);
 781  
 782      // Add dust outputs up to allowed maximum, still standard!
 783      for (size_t i{0}; i < MAX_DUST_OUTPUTS_PER_TX; ++i) {
 784          t.vout.emplace_back(0, t.vout[0].scriptPubKey);
 785          CheckIsStandard(t);
 786      }
 787  
 788      // dust:
 789      t.vout[0].nValue = nDustThreshold - 1;
 790      CheckIsNotStandard(t, "dust");
 791      // not dust:
 792      t.vout[0].nValue = nDustThreshold;
 793      CheckIsStandard(t);
 794  
 795      // Disallowed version
 796      t.version = std::numeric_limits<uint32_t>::max();
 797      CheckIsNotStandard(t, "version");
 798  
 799      t.version = 0;
 800      CheckIsNotStandard(t, "version");
 801  
 802      t.version = TX_MAX_STANDARD_VERSION + 1;
 803      CheckIsNotStandard(t, "version");
 804  
 805      // Allowed version
 806      t.version = 1;
 807      CheckIsStandard(t);
 808  
 809      t.version = 2;
 810      CheckIsStandard(t);
 811  
 812      // Check dust with odd relay fee to verify rounding:
 813      // nDustThreshold = 182 * 3702 / 1000
 814      g_dust = CFeeRate(3702);
 815      // dust:
 816      t.vout[0].nValue = 674 - 1;
 817      CheckIsNotStandard(t, "dust");
 818      // not dust:
 819      t.vout[0].nValue = 674;
 820      CheckIsStandard(t);
 821      g_dust = CFeeRate{DUST_RELAY_TX_FEE};
 822  
 823      t.vout[0].scriptPubKey = CScript() << OP_1;
 824      CheckIsNotStandard(t, "scriptpubkey");
 825  
 826      // Custom 83-byte TxoutType::NULL_DATA (standard with max_op_return_relay of 83)
 827      t.vout[0].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
 828      BOOST_CHECK_EQUAL(83, t.vout[0].scriptPubKey.size());
 829      CheckIsStandard(t, /*max_op_return_relay=*/83);
 830  
 831      // Non-standard if max_op_return_relay datacarrier arg is one less
 832      CheckIsNotStandard(t, "datacarrier", /*max_op_return_relay=*/82);
 833  
 834      // Data payload can be encoded in any way...
 835      t.vout[0].scriptPubKey = CScript() << OP_RETURN << ""_hex;
 836      CheckIsStandard(t);
 837      t.vout[0].scriptPubKey = CScript() << OP_RETURN << "00"_hex << "01"_hex;
 838      CheckIsStandard(t);
 839      // OP_RESERVED *is* considered to be a PUSHDATA type opcode by IsPushOnly()!
 840      t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RESERVED << -1 << 0 << "01"_hex << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16;
 841      CheckIsStandard(t);
 842      t.vout[0].scriptPubKey = CScript() << OP_RETURN << 0 << "01"_hex << 2 << "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"_hex;
 843      CheckIsStandard(t);
 844  
 845      // ...so long as it only contains PUSHDATA's
 846      t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RETURN;
 847      CheckIsNotStandard(t, "scriptpubkey");
 848  
 849      // TxoutType::NULL_DATA w/o PUSHDATA
 850      t.vout.resize(1);
 851      t.vout[0].scriptPubKey = CScript() << OP_RETURN;
 852      CheckIsStandard(t);
 853  
 854      // Multiple TxoutType::NULL_DATA are permitted
 855      t.vout.resize(2);
 856      t.vout[0].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
 857      t.vout[0].nValue = 0;
 858      t.vout[1].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
 859      t.vout[1].nValue = 0;
 860      CheckIsStandard(t);
 861  
 862      t.vout[0].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
 863      t.vout[1].scriptPubKey = CScript() << OP_RETURN;
 864      CheckIsStandard(t);
 865  
 866      t.vout[0].scriptPubKey = CScript() << OP_RETURN;
 867      t.vout[1].scriptPubKey = CScript() << OP_RETURN;
 868      CheckIsStandard(t);
 869  
 870      t.vout[0].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
 871      t.vout[1].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
 872      const auto datacarrier_size = t.vout[0].scriptPubKey.size() + t.vout[1].scriptPubKey.size();
 873      CheckIsStandard(t); // Default max relay should never trigger
 874      CheckIsStandard(t, /*max_op_return_relay=*/datacarrier_size);
 875      CheckIsNotStandard(t, "datacarrier", /*max_op_return_relay=*/datacarrier_size-1);
 876  
 877      // Check large scriptSig (non-standard if size is >1650 bytes)
 878      t.vout.resize(1);
 879      t.vout[0].nValue = MAX_MONEY;
 880      t.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey()));
 881      // OP_PUSHDATA2 with len (3 bytes) + data (1647 bytes) = 1650 bytes
 882      t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(1647, 0); // 1650
 883      CheckIsStandard(t);
 884  
 885      t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(1648, 0); // 1651
 886      CheckIsNotStandard(t, "scriptsig-size");
 887  
 888      // Check scriptSig format (non-standard if there are any other ops than just PUSHs)
 889      t.vin[0].scriptSig = CScript()
 890          << OP_TRUE << OP_0 << OP_1NEGATE << OP_16 // OP_n (single byte pushes: n = 1, 0, -1, 16)
 891          << std::vector<unsigned char>(75, 0)      // OP_PUSHx [...x bytes...]
 892          << std::vector<unsigned char>(235, 0)     // OP_PUSHDATA1 x [...x bytes...]
 893          << std::vector<unsigned char>(1234, 0)    // OP_PUSHDATA2 x [...x bytes...]
 894          << OP_9;
 895      CheckIsStandard(t);
 896  
 897      const std::vector<unsigned char> non_push_ops = { // arbitrary set of non-push operations
 898          OP_NOP, OP_VERIFY, OP_IF, OP_ROT, OP_3DUP, OP_SIZE, OP_EQUAL, OP_ADD, OP_SUB,
 899          OP_HASH256, OP_CODESEPARATOR, OP_CHECKSIG, OP_CHECKLOCKTIMEVERIFY };
 900  
 901      CScript::const_iterator pc = t.vin[0].scriptSig.begin();
 902      while (pc < t.vin[0].scriptSig.end()) {
 903          opcodetype opcode;
 904          CScript::const_iterator prev_pc = pc;
 905          t.vin[0].scriptSig.GetOp(pc, opcode); // advance to next op
 906          // for the sake of simplicity, we only replace single-byte push operations
 907          if (opcode >= 1 && opcode <= OP_PUSHDATA4)
 908              continue;
 909  
 910          int index = prev_pc - t.vin[0].scriptSig.begin();
 911          unsigned char orig_op = *prev_pc; // save op
 912          // replace current push-op with each non-push-op
 913          for (auto op : non_push_ops) {
 914              t.vin[0].scriptSig[index] = op;
 915              CheckIsNotStandard(t, "scriptsig-not-pushonly");
 916          }
 917          t.vin[0].scriptSig[index] = orig_op; // restore op
 918          CheckIsStandard(t);
 919      }
 920  
 921      // Check tx-size (non-standard if transaction weight is > MAX_STANDARD_TX_WEIGHT)
 922      t.vin.clear();
 923      t.vin.resize(2438); // size per input (empty scriptSig): 41 bytes
 924      t.vout[0].scriptPubKey = CScript() << OP_RETURN << std::vector<unsigned char>(19, 0); // output size: 30 bytes
 925      // tx header:                12 bytes =>     48 weight units
 926      // 2438 inputs: 2438*41 = 99958 bytes => 399832 weight units
 927      //    1 output:              30 bytes =>    120 weight units
 928      //                      ======================================
 929      //                                total: 400000 weight units
 930      BOOST_CHECK_EQUAL(GetTransactionWeight(CTransaction(t)), 400000);
 931      CheckIsStandard(t);
 932  
 933      // increase output size by one byte, so we end up with 400004 weight units
 934      t.vout[0].scriptPubKey = CScript() << OP_RETURN << std::vector<unsigned char>(20, 0); // output size: 31 bytes
 935      BOOST_CHECK_EQUAL(GetTransactionWeight(CTransaction(t)), 400004);
 936      CheckIsNotStandard(t, "tx-size");
 937  
 938      // Check bare multisig (standard if policy flag g_bare_multi is set)
 939      g_bare_multi = true;
 940      t.vout[0].scriptPubKey = GetScriptForMultisig(1, {key.GetPubKey()}); // simple 1-of-1
 941      t.vin.resize(1);
 942      t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(65, 0);
 943      CheckIsStandard(t);
 944  
 945      g_bare_multi = false;
 946      CheckIsNotStandard(t, "bare-multisig");
 947      g_bare_multi = DEFAULT_PERMIT_BAREMULTISIG;
 948  
 949      // Add dust outputs up to allowed maximum
 950      assert(t.vout.size() == 1);
 951      t.vout.insert(t.vout.end(), MAX_DUST_OUTPUTS_PER_TX, {0, t.vout[0].scriptPubKey});
 952  
 953      // Check compressed P2PK outputs dust threshold (must have leading 02 or 03)
 954      t.vout[0].scriptPubKey = CScript() << std::vector<unsigned char>(33, 0x02) << OP_CHECKSIG;
 955      t.vout[0].nValue = 576;
 956      CheckIsStandard(t);
 957      t.vout[0].nValue = 575;
 958      CheckIsNotStandard(t, "dust");
 959  
 960      // Check uncompressed P2PK outputs dust threshold (must have leading 04/06/07)
 961      t.vout[0].scriptPubKey = CScript() << std::vector<unsigned char>(65, 0x04) << OP_CHECKSIG;
 962      t.vout[0].nValue = 672;
 963      CheckIsStandard(t);
 964      t.vout[0].nValue = 671;
 965      CheckIsNotStandard(t, "dust");
 966  
 967      // Check P2PKH outputs dust threshold
 968      t.vout[0].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << std::vector<unsigned char>(20, 0) << OP_EQUALVERIFY << OP_CHECKSIG;
 969      t.vout[0].nValue = 546;
 970      CheckIsStandard(t);
 971      t.vout[0].nValue = 545;
 972      CheckIsNotStandard(t, "dust");
 973  
 974      // Check P2SH outputs dust threshold
 975      t.vout[0].scriptPubKey = CScript() << OP_HASH160 << std::vector<unsigned char>(20, 0) << OP_EQUAL;
 976      t.vout[0].nValue = 540;
 977      CheckIsStandard(t);
 978      t.vout[0].nValue = 539;
 979      CheckIsNotStandard(t, "dust");
 980  
 981      // Check P2WPKH outputs dust threshold
 982      t.vout[0].scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(20, 0);
 983      t.vout[0].nValue = 294;
 984      CheckIsStandard(t);
 985      t.vout[0].nValue = 293;
 986      CheckIsNotStandard(t, "dust");
 987  
 988      // Check P2WSH outputs dust threshold
 989      t.vout[0].scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(32, 0);
 990      t.vout[0].nValue = 330;
 991      CheckIsStandard(t);
 992      t.vout[0].nValue = 329;
 993      CheckIsNotStandard(t, "dust");
 994  
 995      // Check P2TR outputs dust threshold (Invalid xonly key ok!)
 996      t.vout[0].scriptPubKey = CScript() << OP_1 << std::vector<unsigned char>(32, 0);
 997      t.vout[0].nValue = 330;
 998      CheckIsStandard(t);
 999      t.vout[0].nValue = 329;
1000      CheckIsNotStandard(t, "dust");
1001  
1002      // Check future Witness Program versions dust threshold (non-32-byte pushes are undefined for version 1)
1003      for (int op = OP_1; op <= OP_16; op += 1) {
1004          t.vout[0].scriptPubKey = CScript() << (opcodetype)op << std::vector<unsigned char>(2, 0);
1005          t.vout[0].nValue = 240;
1006          CheckIsStandard(t);
1007  
1008          t.vout[0].nValue = 239;
1009          CheckIsNotStandard(t, "dust");
1010      }
1011  
1012      // Check anchor outputs
1013      t.vout[0].scriptPubKey = CScript() << OP_1 << ANCHOR_BYTES;
1014      BOOST_CHECK(t.vout[0].scriptPubKey.IsPayToAnchor());
1015      t.vout[0].nValue = 240;
1016      CheckIsStandard(t);
1017      t.vout[0].nValue = 239;
1018      CheckIsNotStandard(t, "dust");
1019  }
1020  
1021  BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops)
1022  {
1023      CCoinsViewCache coins{&CoinsViewEmpty::Get()};
1024      CKey key;
1025      key.MakeNewKey(true);
1026  
1027      // Create a pathological P2SH script padded with as many sigops as is standard.
1028      CScript max_sigops_redeem_script{CScript() << std::vector<unsigned char>{} << key.GetPubKey()};
1029      for (unsigned i{0}; i < MAX_P2SH_SIGOPS - 1; ++i) max_sigops_redeem_script << OP_2DUP << OP_CHECKSIG << OP_DROP;
1030      max_sigops_redeem_script << OP_CHECKSIG << OP_NOT;
1031      const CScript max_sigops_p2sh{GetScriptForDestination(ScriptHash(max_sigops_redeem_script))};
1032  
1033      // Create a transaction fanning out as many such P2SH outputs as is standard to spend in a
1034      // single transaction, and a transaction spending them.
1035      CMutableTransaction tx_create, tx_max_sigops;
1036      const unsigned p2sh_inputs_count{MAX_TX_LEGACY_SIGOPS / MAX_P2SH_SIGOPS};
1037      tx_create.vout.reserve(p2sh_inputs_count);
1038      for (unsigned i{0}; i < p2sh_inputs_count; ++i) {
1039          tx_create.vout.emplace_back(424242 + i, max_sigops_p2sh);
1040      }
1041      auto prev_txid{tx_create.GetHash()};
1042      tx_max_sigops.vin.reserve(p2sh_inputs_count);
1043      for (unsigned i{0}; i < p2sh_inputs_count; ++i) {
1044          tx_max_sigops.vin.emplace_back(prev_txid, i, CScript() << ToByteVector(max_sigops_redeem_script));
1045      }
1046  
1047      // p2sh_inputs_count is truncated to 166 (from 166.6666..)
1048      BOOST_CHECK_LT(p2sh_inputs_count * MAX_P2SH_SIGOPS, MAX_TX_LEGACY_SIGOPS);
1049      AddCoins(coins, CTransaction(tx_create), 0, false);
1050  
1051      // 2490 sigops is below the limit.
1052      BOOST_CHECK_EQUAL(GetP2SHSigOpCount(CTransaction(tx_max_sigops), coins), 2490);
1053      BOOST_CHECK(::ValidateInputsStandardness(CTransaction(tx_max_sigops), coins).IsValid());
1054  
1055      // Adding one more input will bump this to 2505, hitting the limit.
1056      tx_create.vout.emplace_back(424242, max_sigops_p2sh);
1057      prev_txid = tx_create.GetHash();
1058      for (unsigned i{0}; i < p2sh_inputs_count; ++i) {
1059          tx_max_sigops.vin[i] = CTxIn(COutPoint(prev_txid, i), CScript() << ToByteVector(max_sigops_redeem_script));
1060      }
1061      tx_max_sigops.vin.emplace_back(prev_txid, p2sh_inputs_count, CScript() << ToByteVector(max_sigops_redeem_script));
1062      AddCoins(coins, CTransaction(tx_create), 0, false);
1063      BOOST_CHECK_GT((p2sh_inputs_count + 1) * MAX_P2SH_SIGOPS, MAX_TX_LEGACY_SIGOPS);
1064      auto legacy_sigops_count = GetP2SHSigOpCount(CTransaction(tx_max_sigops), coins);
1065      BOOST_CHECK_EQUAL(legacy_sigops_count, 2505);
1066      std::string reject_reason("bad-txns-nonstandard-inputs");
1067      std::string sigop_limit_reject_debug_message("non-witness sigops exceed bip54 limit");
1068      {
1069          auto validation_state = ValidateInputsStandardness(CTransaction(tx_max_sigops), coins);
1070          BOOST_CHECK(validation_state.IsInvalid());
1071          BOOST_CHECK_EQUAL(validation_state.GetRejectReason(), reject_reason);
1072          BOOST_CHECK_EQUAL(validation_state.GetDebugMessage(), sigop_limit_reject_debug_message);
1073      }
1074  
1075  
1076      // Now, check the limit can be reached with regular P2PK outputs too. Use a separate
1077      // preparation transaction, to demonstrate spending coins from a single tx is irrelevant.
1078      CMutableTransaction tx_create_p2pk;
1079      const auto p2pk_script{CScript() << key.GetPubKey() << OP_CHECKSIG};
1080      unsigned p2pk_inputs_count{10}; // From 2490 to 2500.
1081      for (unsigned i{0}; i < p2pk_inputs_count; ++i) {
1082          tx_create_p2pk.vout.emplace_back(212121 + i, p2pk_script);
1083      }
1084      prev_txid = tx_create_p2pk.GetHash();
1085      tx_max_sigops.vin.resize(p2sh_inputs_count); // Drop the extra input.
1086      for (unsigned i{0}; i < p2pk_inputs_count; ++i) {
1087          tx_max_sigops.vin.emplace_back(prev_txid, i);
1088      }
1089      AddCoins(coins, CTransaction(tx_create_p2pk), 0, false);
1090  
1091      // The transaction now contains exactly 2500 sigops, the check should pass.
1092      BOOST_CHECK(::ValidateInputsStandardness(CTransaction(tx_max_sigops), coins).IsValid());
1093  
1094      // Now, add some Segwit inputs. We add one for each defined Segwit output type. The limit
1095      // is exclusively on non-witness sigops and therefore those should not be counted.
1096      CMutableTransaction tx_create_segwit;
1097      const auto witness_script{CScript() << key.GetPubKey() << OP_CHECKSIG};
1098      tx_create_segwit.vout.emplace_back(121212, GetScriptForDestination(WitnessV0KeyHash(key.GetPubKey())));
1099      tx_create_segwit.vout.emplace_back(131313, GetScriptForDestination(WitnessV0ScriptHash(witness_script)));
1100      tx_create_segwit.vout.emplace_back(141414, GetScriptForDestination(WitnessV1Taproot{XOnlyPubKey(key.GetPubKey())}));
1101      prev_txid = tx_create_segwit.GetHash();
1102      for (unsigned i{0}; i < tx_create_segwit.vout.size(); ++i) {
1103          tx_max_sigops.vin.emplace_back(prev_txid, i);
1104      }
1105  
1106      // The transaction now still contains exactly 2500 sigops, the check should pass.
1107      AddCoins(coins, CTransaction(tx_create_segwit), 0, false);
1108      BOOST_REQUIRE(::ValidateInputsStandardness(CTransaction(tx_max_sigops), coins).IsValid());
1109  
1110      // Add one more P2PK input. We'll reach the limit.
1111      tx_create_p2pk.vout.emplace_back(212121, p2pk_script);
1112      prev_txid = tx_create_p2pk.GetHash();
1113      tx_max_sigops.vin.resize(p2sh_inputs_count);
1114      ++p2pk_inputs_count;
1115      for (unsigned i{0}; i < p2pk_inputs_count; ++i) {
1116          tx_max_sigops.vin.emplace_back(prev_txid, i);
1117      }
1118      AddCoins(coins, CTransaction(tx_create_p2pk), 0, false);
1119      auto legacy_sigop_count_p2pk = p2sh_inputs_count * MAX_P2SH_SIGOPS + p2pk_inputs_count * 1;
1120      BOOST_CHECK_GT(legacy_sigop_count_p2pk, MAX_TX_LEGACY_SIGOPS);
1121      {
1122          auto validation_state = ValidateInputsStandardness(CTransaction(tx_max_sigops), coins);
1123          BOOST_CHECK(validation_state.IsInvalid());
1124          BOOST_CHECK_EQUAL(validation_state.GetRejectReason(), reject_reason);
1125          BOOST_CHECK_EQUAL(validation_state.GetDebugMessage(), sigop_limit_reject_debug_message);
1126      }
1127  }
1128  
1129  BOOST_AUTO_TEST_CASE(checktxinputs_invalid_transactions_test)
1130  {
1131      auto check_invalid{[](CAmount input_value, CAmount output_value, bool coinbase, int spend_height, TxValidationResult expected_result, std::string_view expected_reason) {
1132          CCoinsViewCache inputs{&CoinsViewEmpty::Get()};
1133  
1134          const COutPoint prevout{Txid::FromUint256(uint256::ONE), 0};
1135          inputs.AddCoin(prevout, Coin{{input_value, CScript() << OP_TRUE}, /*nHeightIn=*/1, coinbase}, /*possible_overwrite=*/false);
1136  
1137          CMutableTransaction mtx;
1138          mtx.vin.emplace_back(prevout);
1139          mtx.vout.emplace_back(output_value, CScript() << OP_TRUE);
1140  
1141          TxValidationState state;
1142          CAmount txfee{0};
1143          BOOST_CHECK(!Consensus::CheckTxInputs(CTransaction{mtx}, state, inputs, spend_height, txfee));
1144          BOOST_CHECK(state.IsInvalid());
1145          BOOST_CHECK_EQUAL(state.GetResult(), expected_result);
1146          BOOST_CHECK_EQUAL(state.GetRejectReason(), expected_reason);
1147      }};
1148  
1149      check_invalid(/*input_value=*/MAX_MONEY + 1,
1150                    /*output_value=*/0,
1151                    /*coinbase=*/false,
1152                    /*spend_height=*/2,
1153                    TxValidationResult::TX_CONSENSUS, /*expected_reason=*/"bad-txns-inputvalues-outofrange");
1154  
1155      check_invalid(/*input_value=*/1 * COIN,
1156                    /*output_value=*/2 * COIN,
1157                    /*coinbase=*/false,
1158                    /*spend_height=*/2,
1159                    TxValidationResult::TX_CONSENSUS, /*expected_reason=*/"bad-txns-in-belowout");
1160  
1161      check_invalid(/*input_value=*/1 * COIN,
1162                    /*output_value=*/0,
1163                    /*coinbase=*/true,
1164                    /*spend_height=*/COINBASE_MATURITY,
1165                    TxValidationResult::TX_PREMATURE_SPEND, /*expected_reason=*/"bad-txns-premature-spend-of-coinbase");
1166  }
1167  
1168  BOOST_AUTO_TEST_CASE(getvalueout_out_of_range_throws)
1169  {
1170      CMutableTransaction mtx;
1171      mtx.vout.emplace_back(MAX_MONEY + 1, CScript() << OP_TRUE);
1172  
1173      const CTransaction tx{mtx};
1174      BOOST_CHECK_EXCEPTION(tx.GetValueOut(), std::runtime_error, HasReason("GetValueOut: value out of range"));
1175  }
1176  
1177  /** Sanity check the return value of SpendsNonAnchorWitnessProg for various output types. */
1178  BOOST_AUTO_TEST_CASE(spends_witness_prog)
1179  {
1180      CCoinsViewCache coins{&CoinsViewEmpty::Get()};
1181      CKey key;
1182      key.MakeNewKey(true);
1183      const CPubKey pubkey{key.GetPubKey()};
1184      CMutableTransaction tx_create{}, tx_spend{};
1185      tx_create.vout.emplace_back(0, CScript{});
1186      tx_spend.vin.emplace_back(Txid{}, 0);
1187      std::vector<std::vector<uint8_t>> sol_dummy;
1188  
1189      // CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash,
1190      // WitnessV1Taproot, PayToAnchor, WitnessUnknown.
1191      static_assert(std::variant_size_v<CTxDestination> == 9);
1192  
1193      // Go through all defined output types and sanity check SpendsNonAnchorWitnessProg.
1194  
1195      // P2PK
1196      tx_create.vout[0].scriptPubKey = GetScriptForDestination(PubKeyDestination{pubkey});
1197      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::PUBKEY);
1198      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1199      AddCoins(coins, CTransaction{tx_create}, 0, false);
1200      BOOST_CHECK(!::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1201  
1202      // P2PKH
1203      tx_create.vout[0].scriptPubKey = GetScriptForDestination(PKHash{pubkey});
1204      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::PUBKEYHASH);
1205      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1206      AddCoins(coins, CTransaction{tx_create}, 0, false);
1207      BOOST_CHECK(!::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1208  
1209      // P2SH
1210      auto redeem_script{CScript{} << OP_1 << OP_CHECKSIG};
1211      tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash{redeem_script});
1212      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1213      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1214      tx_spend.vin[0].scriptSig = CScript{} << OP_0 << ToByteVector(redeem_script);
1215      AddCoins(coins, CTransaction{tx_create}, 0, false);
1216      BOOST_CHECK(!::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1217      tx_spend.vin[0].scriptSig.clear();
1218  
1219      // native P2WSH
1220      const auto witness_script{CScript{} << OP_12 << OP_HASH160 << OP_DUP << OP_EQUAL};
1221      tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash{witness_script});
1222      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::WITNESS_V0_SCRIPTHASH);
1223      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1224      AddCoins(coins, CTransaction{tx_create}, 0, false);
1225      BOOST_CHECK(::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1226  
1227      // P2SH-wrapped P2WSH
1228      redeem_script = tx_create.vout[0].scriptPubKey;
1229      tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1230      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1231      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1232      tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1233      AddCoins(coins, CTransaction{tx_create}, 0, false);
1234      BOOST_CHECK(::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1235      tx_spend.vin[0].scriptSig.clear();
1236      BOOST_CHECK(!::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1237  
1238      // native P2WPKH
1239      tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessV0KeyHash{pubkey});
1240      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::WITNESS_V0_KEYHASH);
1241      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1242      AddCoins(coins, CTransaction{tx_create}, 0, false);
1243      BOOST_CHECK(::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1244  
1245      // P2SH-wrapped P2WPKH
1246      redeem_script = tx_create.vout[0].scriptPubKey;
1247      tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1248      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1249      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1250      tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1251      AddCoins(coins, CTransaction{tx_create}, 0, false);
1252      BOOST_CHECK(::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1253      tx_spend.vin[0].scriptSig.clear();
1254      BOOST_CHECK(!::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1255  
1256      // P2TR
1257      tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessV1Taproot{XOnlyPubKey{pubkey}});
1258      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::WITNESS_V1_TAPROOT);
1259      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1260      AddCoins(coins, CTransaction{tx_create}, 0, false);
1261      BOOST_CHECK(::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1262  
1263      // P2SH-wrapped P2TR (undefined, non-standard)
1264      redeem_script = tx_create.vout[0].scriptPubKey;
1265      tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1266      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1267      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1268      tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1269      AddCoins(coins, CTransaction{tx_create}, 0, false);
1270      BOOST_CHECK(::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1271      tx_spend.vin[0].scriptSig.clear();
1272      BOOST_CHECK(!::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1273  
1274      // P2A
1275      tx_create.vout[0].scriptPubKey = GetScriptForDestination(PayToAnchor{});
1276      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::ANCHOR);
1277      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1278      AddCoins(coins, CTransaction{tx_create}, 0, false);
1279      BOOST_CHECK(!::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1280  
1281      // P2SH-wrapped P2A (undefined, non-standard)
1282      redeem_script = tx_create.vout[0].scriptPubKey;
1283      tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1284      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1285      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1286      tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1287      AddCoins(coins, CTransaction{tx_create}, 0, false);
1288      BOOST_CHECK(::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1289      tx_spend.vin[0].scriptSig.clear();
1290  
1291      // Undefined version 1 witness program
1292      tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessUnknown{1, {0x42, 0x42}});
1293      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::WITNESS_UNKNOWN);
1294      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1295      AddCoins(coins, CTransaction{tx_create}, 0, false);
1296      BOOST_CHECK(::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1297  
1298      // P2SH-wrapped undefined version 1 witness program
1299      redeem_script = tx_create.vout[0].scriptPubKey;
1300      tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1301      BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1302      tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1303      tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1304      AddCoins(coins, CTransaction{tx_create}, 0, false);
1305      BOOST_CHECK(::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1306      tx_spend.vin[0].scriptSig.clear();
1307      BOOST_CHECK(!::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1308  
1309      // Various undefined version >1 32-byte witness programs.
1310      const auto program{ToByteVector(XOnlyPubKey{pubkey})};
1311      for (int i{2}; i <= 16; ++i) {
1312          tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessUnknown{i, program});
1313          BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::WITNESS_UNKNOWN);
1314          tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1315          AddCoins(coins, CTransaction{tx_create}, 0, false);
1316          BOOST_CHECK(::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1317  
1318          // It's also detected within P2SH.
1319          redeem_script = tx_create.vout[0].scriptPubKey;
1320          tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1321          BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1322          tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1323          tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1324          AddCoins(coins, CTransaction{tx_create}, 0, false);
1325          BOOST_CHECK(::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1326          tx_spend.vin[0].scriptSig.clear();
1327          BOOST_CHECK(!::SpendsNonAnchorWitnessProg(CTransaction{tx_spend}, coins));
1328      }
1329  }
1330  
1331  BOOST_AUTO_TEST_SUITE_END()