transaction_tests.cpp
1 // Copyright (c) 2011-2022 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/tx_check.h> 13 #include <consensus/validation.h> 14 #include <core_io.h> 15 #include <key.h> 16 #include <policy/policy.h> 17 #include <policy/settings.h> 18 #include <script/script.h> 19 #include <script/script_error.h> 20 #include <script/sign.h> 21 #include <script/signingprovider.h> 22 #include <script/solver.h> 23 #include <streams.h> 24 #include <test/util/json.h> 25 #include <test/util/random.h> 26 #include <test/util/script.h> 27 #include <test/util/transaction_utils.h> 28 #include <util/strencodings.h> 29 #include <util/string.h> 30 #include <util/transaction_identifier.h> 31 #include <validation.h> 32 33 #include <functional> 34 #include <map> 35 #include <string> 36 37 #include <boost/test/unit_test.hpp> 38 39 #include <univalue.h> 40 41 typedef std::vector<unsigned char> valtype; 42 43 static CFeeRate g_dust{DUST_RELAY_TX_FEE}; 44 static bool g_bare_multi{DEFAULT_PERMIT_BAREMULTISIG}; 45 46 static std::map<std::string, unsigned int> mapFlagNames = { 47 {std::string("P2SH"), (unsigned int)SCRIPT_VERIFY_P2SH}, 48 {std::string("STRICTENC"), (unsigned int)SCRIPT_VERIFY_STRICTENC}, 49 {std::string("DERSIG"), (unsigned int)SCRIPT_VERIFY_DERSIG}, 50 {std::string("LOW_S"), (unsigned int)SCRIPT_VERIFY_LOW_S}, 51 {std::string("SIGPUSHONLY"), (unsigned int)SCRIPT_VERIFY_SIGPUSHONLY}, 52 {std::string("MINIMALDATA"), (unsigned int)SCRIPT_VERIFY_MINIMALDATA}, 53 {std::string("NULLDUMMY"), (unsigned int)SCRIPT_VERIFY_NULLDUMMY}, 54 {std::string("DISCOURAGE_UPGRADABLE_NOPS"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS}, 55 {std::string("CLEANSTACK"), (unsigned int)SCRIPT_VERIFY_CLEANSTACK}, 56 {std::string("MINIMALIF"), (unsigned int)SCRIPT_VERIFY_MINIMALIF}, 57 {std::string("NULLFAIL"), (unsigned int)SCRIPT_VERIFY_NULLFAIL}, 58 {std::string("CHECKLOCKTIMEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY}, 59 {std::string("CHECKSEQUENCEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKSEQUENCEVERIFY}, 60 {std::string("WITNESS"), (unsigned int)SCRIPT_VERIFY_WITNESS}, 61 {std::string("DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM}, 62 {std::string("WITNESS_PUBKEYTYPE"), (unsigned int)SCRIPT_VERIFY_WITNESS_PUBKEYTYPE}, 63 {std::string("CONST_SCRIPTCODE"), (unsigned int)SCRIPT_VERIFY_CONST_SCRIPTCODE}, 64 {std::string("TAPROOT"), (unsigned int)SCRIPT_VERIFY_TAPROOT}, 65 {std::string("DISCOURAGE_UPGRADABLE_PUBKEYTYPE"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_PUBKEYTYPE}, 66 {std::string("DISCOURAGE_OP_SUCCESS"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_OP_SUCCESS}, 67 {std::string("DISCOURAGE_UPGRADABLE_TAPROOT_VERSION"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION}, 68 }; 69 70 unsigned int ParseScriptFlags(std::string strFlags) 71 { 72 if (strFlags.empty() || strFlags == "NONE") return 0; 73 unsigned int flags = 0; 74 std::vector<std::string> words = SplitString(strFlags, ','); 75 76 for (const std::string& word : words) 77 { 78 if (!mapFlagNames.count(word)) 79 BOOST_ERROR("Bad test: unknown verification flag '" << word << "'"); 80 flags |= mapFlagNames[word]; 81 } 82 83 return flags; 84 } 85 86 // Check that all flags in STANDARD_SCRIPT_VERIFY_FLAGS are present in mapFlagNames. 87 bool CheckMapFlagNames() 88 { 89 unsigned int standard_flags_missing{STANDARD_SCRIPT_VERIFY_FLAGS}; 90 for (const auto& pair : mapFlagNames) { 91 standard_flags_missing &= ~(pair.second); 92 } 93 return standard_flags_missing == 0; 94 } 95 96 std::string FormatScriptFlags(unsigned int flags) 97 { 98 if (flags == 0) { 99 return ""; 100 } 101 std::string ret; 102 std::map<std::string, unsigned int>::const_iterator it = mapFlagNames.begin(); 103 while (it != mapFlagNames.end()) { 104 if (flags & it->second) { 105 ret += it->first + ","; 106 } 107 it++; 108 } 109 return ret.substr(0, ret.size() - 1); 110 } 111 112 /* 113 * Check that the input scripts of a transaction are valid/invalid as expected. 114 */ 115 bool CheckTxScripts(const CTransaction& tx, const std::map<COutPoint, CScript>& map_prevout_scriptPubKeys, 116 const std::map<COutPoint, int64_t>& map_prevout_values, unsigned int flags, 117 const PrecomputedTransactionData& txdata, const std::string& strTest, bool expect_valid) 118 { 119 bool tx_valid = true; 120 ScriptError err = expect_valid ? SCRIPT_ERR_UNKNOWN_ERROR : SCRIPT_ERR_OK; 121 for (unsigned int i = 0; i < tx.vin.size() && tx_valid; ++i) { 122 const CTxIn input = tx.vin[i]; 123 const CAmount amount = map_prevout_values.count(input.prevout) ? map_prevout_values.at(input.prevout) : 0; 124 try { 125 tx_valid = VerifyScript(input.scriptSig, map_prevout_scriptPubKeys.at(input.prevout), 126 &input.scriptWitness, flags, TransactionSignatureChecker(&tx, i, amount, txdata, MissingDataBehavior::ASSERT_FAIL), &err); 127 } catch (...) { 128 BOOST_ERROR("Bad test: " << strTest); 129 return true; // The test format is bad and an error is thrown. Return true to silence further error. 130 } 131 if (expect_valid) { 132 BOOST_CHECK_MESSAGE(tx_valid, strTest); 133 BOOST_CHECK_MESSAGE((err == SCRIPT_ERR_OK), ScriptErrorString(err)); 134 err = SCRIPT_ERR_UNKNOWN_ERROR; 135 } 136 } 137 if (!expect_valid) { 138 BOOST_CHECK_MESSAGE(!tx_valid, strTest); 139 BOOST_CHECK_MESSAGE((err != SCRIPT_ERR_OK), ScriptErrorString(err)); 140 } 141 return (tx_valid == expect_valid); 142 } 143 144 /* 145 * Trim or fill flags to make the combination valid: 146 * WITNESS must be used with P2SH 147 * CLEANSTACK must be used WITNESS and P2SH 148 */ 149 150 unsigned int TrimFlags(unsigned int flags) 151 { 152 // WITNESS requires P2SH 153 if (!(flags & SCRIPT_VERIFY_P2SH)) flags &= ~(unsigned int)SCRIPT_VERIFY_WITNESS; 154 155 // CLEANSTACK requires WITNESS (and transitively CLEANSTACK requires P2SH) 156 if (!(flags & SCRIPT_VERIFY_WITNESS)) flags &= ~(unsigned int)SCRIPT_VERIFY_CLEANSTACK; 157 Assert(IsValidFlagCombination(flags)); 158 return flags; 159 } 160 161 unsigned int FillFlags(unsigned int flags) 162 { 163 // CLEANSTACK implies WITNESS 164 if (flags & SCRIPT_VERIFY_CLEANSTACK) flags |= SCRIPT_VERIFY_WITNESS; 165 166 // WITNESS implies P2SH (and transitively CLEANSTACK implies P2SH) 167 if (flags & SCRIPT_VERIFY_WITNESS) flags |= SCRIPT_VERIFY_P2SH; 168 Assert(IsValidFlagCombination(flags)); 169 return flags; 170 } 171 172 // Exclude each possible script verify flag from flags. Returns a set of these flag combinations 173 // that are valid and without duplicates. For example: if flags=1111 and the 4 possible flags are 174 // 0001, 0010, 0100, and 1000, this should return the set {0111, 1011, 1101, 1110}. 175 // Assumes that mapFlagNames contains all script verify flags. 176 std::set<unsigned int> ExcludeIndividualFlags(unsigned int flags) 177 { 178 std::set<unsigned int> flags_combos; 179 for (const auto& pair : mapFlagNames) { 180 const unsigned int flags_excluding_one = TrimFlags(flags & ~(pair.second)); 181 if (flags != flags_excluding_one) { 182 flags_combos.insert(flags_excluding_one); 183 } 184 } 185 return flags_combos; 186 } 187 188 BOOST_FIXTURE_TEST_SUITE(transaction_tests, BasicTestingSetup) 189 190 BOOST_AUTO_TEST_CASE(tx_valid) 191 { 192 BOOST_CHECK_MESSAGE(CheckMapFlagNames(), "mapFlagNames is missing a script verification flag"); 193 // Read tests from test/data/tx_valid.json 194 UniValue tests = read_json(json_tests::tx_valid); 195 196 for (unsigned int idx = 0; idx < tests.size(); idx++) { 197 const UniValue& test = tests[idx]; 198 std::string strTest = test.write(); 199 if (test[0].isArray()) 200 { 201 if (test.size() != 3 || !test[1].isStr() || !test[2].isStr()) 202 { 203 BOOST_ERROR("Bad test: " << strTest); 204 continue; 205 } 206 207 std::map<COutPoint, CScript> mapprevOutScriptPubKeys; 208 std::map<COutPoint, int64_t> mapprevOutValues; 209 UniValue inputs = test[0].get_array(); 210 bool fValid = true; 211 for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) { 212 const UniValue& input = inputs[inpIdx]; 213 if (!input.isArray()) { 214 fValid = false; 215 break; 216 } 217 const UniValue& vinput = input.get_array(); 218 if (vinput.size() < 3 || vinput.size() > 4) 219 { 220 fValid = false; 221 break; 222 } 223 COutPoint outpoint{TxidFromString(vinput[0].get_str()), uint32_t(vinput[1].getInt<int>())}; 224 mapprevOutScriptPubKeys[outpoint] = ParseScript(vinput[2].get_str()); 225 if (vinput.size() >= 4) 226 { 227 mapprevOutValues[outpoint] = vinput[3].getInt<int64_t>(); 228 } 229 } 230 if (!fValid) 231 { 232 BOOST_ERROR("Bad test: " << strTest); 233 continue; 234 } 235 236 std::string transaction = test[1].get_str(); 237 DataStream stream(ParseHex(transaction)); 238 CTransaction tx(deserialize, TX_WITH_WITNESS, stream); 239 240 TxValidationState state; 241 BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest); 242 BOOST_CHECK(state.IsValid()); 243 244 PrecomputedTransactionData txdata(tx); 245 unsigned int verify_flags = ParseScriptFlags(test[2].get_str()); 246 247 // Check that the test gives a valid combination of flags (otherwise VerifyScript will throw). Don't edit the flags. 248 if (~verify_flags != FillFlags(~verify_flags)) { 249 BOOST_ERROR("Bad test flags: " << strTest); 250 } 251 252 BOOST_CHECK_MESSAGE(CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, ~verify_flags, txdata, strTest, /*expect_valid=*/true), 253 "Tx unexpectedly failed: " << strTest); 254 255 // Backwards compatibility of script verification flags: Removing any flag(s) should not invalidate a valid transaction 256 for (const auto& [name, flag] : mapFlagNames) { 257 // Removing individual flags 258 unsigned int flags = TrimFlags(~(verify_flags | flag)); 259 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/true)) { 260 BOOST_ERROR("Tx unexpectedly failed with flag " << name << " unset: " << strTest); 261 } 262 // Removing random combinations of flags 263 flags = TrimFlags(~(verify_flags | (unsigned int)InsecureRandBits(mapFlagNames.size()))); 264 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/true)) { 265 BOOST_ERROR("Tx unexpectedly failed with random flags " << ToString(flags) << ": " << strTest); 266 } 267 } 268 269 // Check that flags are maximal: transaction should fail if any unset flags are set. 270 for (auto flags_excluding_one : ExcludeIndividualFlags(verify_flags)) { 271 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, ~flags_excluding_one, txdata, strTest, /*expect_valid=*/false)) { 272 BOOST_ERROR("Too many flags unset: " << strTest); 273 } 274 } 275 } 276 } 277 } 278 279 BOOST_AUTO_TEST_CASE(tx_invalid) 280 { 281 // Read tests from test/data/tx_invalid.json 282 UniValue tests = read_json(json_tests::tx_invalid); 283 284 for (unsigned int idx = 0; idx < tests.size(); idx++) { 285 const UniValue& test = tests[idx]; 286 std::string strTest = test.write(); 287 if (test[0].isArray()) 288 { 289 if (test.size() != 3 || !test[1].isStr() || !test[2].isStr()) 290 { 291 BOOST_ERROR("Bad test: " << strTest); 292 continue; 293 } 294 295 std::map<COutPoint, CScript> mapprevOutScriptPubKeys; 296 std::map<COutPoint, int64_t> mapprevOutValues; 297 UniValue inputs = test[0].get_array(); 298 bool fValid = true; 299 for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) { 300 const UniValue& input = inputs[inpIdx]; 301 if (!input.isArray()) { 302 fValid = false; 303 break; 304 } 305 const UniValue& vinput = input.get_array(); 306 if (vinput.size() < 3 || vinput.size() > 4) 307 { 308 fValid = false; 309 break; 310 } 311 COutPoint outpoint{TxidFromString(vinput[0].get_str()), uint32_t(vinput[1].getInt<int>())}; 312 mapprevOutScriptPubKeys[outpoint] = ParseScript(vinput[2].get_str()); 313 if (vinput.size() >= 4) 314 { 315 mapprevOutValues[outpoint] = vinput[3].getInt<int64_t>(); 316 } 317 } 318 if (!fValid) 319 { 320 BOOST_ERROR("Bad test: " << strTest); 321 continue; 322 } 323 324 std::string transaction = test[1].get_str(); 325 DataStream stream(ParseHex(transaction)); 326 CTransaction tx(deserialize, TX_WITH_WITNESS, stream); 327 328 TxValidationState state; 329 if (!CheckTransaction(tx, state) || state.IsInvalid()) { 330 BOOST_CHECK_MESSAGE(test[2].get_str() == "BADTX", strTest); 331 continue; 332 } 333 334 PrecomputedTransactionData txdata(tx); 335 unsigned int verify_flags = ParseScriptFlags(test[2].get_str()); 336 337 // Check that the test gives a valid combination of flags (otherwise VerifyScript will throw). Don't edit the flags. 338 if (verify_flags != FillFlags(verify_flags)) { 339 BOOST_ERROR("Bad test flags: " << strTest); 340 } 341 342 // Not using FillFlags() in the main test, in order to detect invalid verifyFlags combination 343 BOOST_CHECK_MESSAGE(CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, verify_flags, txdata, strTest, /*expect_valid=*/false), 344 "Tx unexpectedly passed: " << strTest); 345 346 // Backwards compatibility of script verification flags: Adding any flag(s) should not validate an invalid transaction 347 for (const auto& [name, flag] : mapFlagNames) { 348 unsigned int flags = FillFlags(verify_flags | flag); 349 // Adding individual flags 350 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/false)) { 351 BOOST_ERROR("Tx unexpectedly passed with flag " << name << " set: " << strTest); 352 } 353 // Adding random combinations of flags 354 flags = FillFlags(verify_flags | (unsigned int)InsecureRandBits(mapFlagNames.size())); 355 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/false)) { 356 BOOST_ERROR("Tx unexpectedly passed with random flags " << name << ": " << strTest); 357 } 358 } 359 360 // Check that flags are minimal: transaction should succeed if any set flags are unset. 361 for (auto flags_excluding_one : ExcludeIndividualFlags(verify_flags)) { 362 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags_excluding_one, txdata, strTest, /*expect_valid=*/true)) { 363 BOOST_ERROR("Too many flags set: " << strTest); 364 } 365 } 366 } 367 } 368 } 369 370 BOOST_AUTO_TEST_CASE(basic_transaction_tests) 371 { 372 // Random real transaction (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436) 373 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}; 374 std::vector<unsigned char> vch(ch, ch + sizeof(ch) -1); 375 DataStream stream(vch); 376 CMutableTransaction tx; 377 stream >> TX_WITH_WITNESS(tx); 378 TxValidationState state; 379 BOOST_CHECK_MESSAGE(CheckTransaction(CTransaction(tx), state) && state.IsValid(), "Simple deserialized transaction should be valid."); 380 381 // Check that duplicate txins fail 382 tx.vin.push_back(tx.vin[0]); 383 BOOST_CHECK_MESSAGE(!CheckTransaction(CTransaction(tx), state) || !state.IsValid(), "Transaction with duplicate txins should be invalid."); 384 } 385 386 BOOST_AUTO_TEST_CASE(test_Get) 387 { 388 FillableSigningProvider keystore; 389 CCoinsView coinsDummy; 390 CCoinsViewCache coins(&coinsDummy); 391 std::vector<CMutableTransaction> dummyTransactions = 392 SetupDummyInputs(keystore, coins, {11*CENT, 50*CENT, 21*CENT, 22*CENT}); 393 394 CMutableTransaction t1; 395 t1.vin.resize(3); 396 t1.vin[0].prevout.hash = dummyTransactions[0].GetHash(); 397 t1.vin[0].prevout.n = 1; 398 t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0); 399 t1.vin[1].prevout.hash = dummyTransactions[1].GetHash(); 400 t1.vin[1].prevout.n = 0; 401 t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); 402 t1.vin[2].prevout.hash = dummyTransactions[1].GetHash(); 403 t1.vin[2].prevout.n = 1; 404 t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); 405 t1.vout.resize(2); 406 t1.vout[0].nValue = 90*CENT; 407 t1.vout[0].scriptPubKey << OP_1; 408 409 BOOST_CHECK(AreInputsStandard(CTransaction(t1), coins)); 410 } 411 412 static void CreateCreditAndSpend(const FillableSigningProvider& keystore, const CScript& outscript, CTransactionRef& output, CMutableTransaction& input, bool success = true) 413 { 414 CMutableTransaction outputm; 415 outputm.nVersion = 1; 416 outputm.vin.resize(1); 417 outputm.vin[0].prevout.SetNull(); 418 outputm.vin[0].scriptSig = CScript(); 419 outputm.vout.resize(1); 420 outputm.vout[0].nValue = 1; 421 outputm.vout[0].scriptPubKey = outscript; 422 DataStream ssout; 423 ssout << TX_WITH_WITNESS(outputm); 424 ssout >> TX_WITH_WITNESS(output); 425 assert(output->vin.size() == 1); 426 assert(output->vin[0] == outputm.vin[0]); 427 assert(output->vout.size() == 1); 428 assert(output->vout[0] == outputm.vout[0]); 429 430 CMutableTransaction inputm; 431 inputm.nVersion = 1; 432 inputm.vin.resize(1); 433 inputm.vin[0].prevout.hash = output->GetHash(); 434 inputm.vin[0].prevout.n = 0; 435 inputm.vout.resize(1); 436 inputm.vout[0].nValue = 1; 437 inputm.vout[0].scriptPubKey = CScript(); 438 SignatureData empty; 439 bool ret = SignSignature(keystore, *output, inputm, 0, SIGHASH_ALL, empty); 440 assert(ret == success); 441 DataStream ssin; 442 ssin << TX_WITH_WITNESS(inputm); 443 ssin >> TX_WITH_WITNESS(input); 444 assert(input.vin.size() == 1); 445 assert(input.vin[0] == inputm.vin[0]); 446 assert(input.vout.size() == 1); 447 assert(input.vout[0] == inputm.vout[0]); 448 assert(input.vin[0].scriptWitness.stack == inputm.vin[0].scriptWitness.stack); 449 } 450 451 static void CheckWithFlag(const CTransactionRef& output, const CMutableTransaction& input, uint32_t flags, bool success) 452 { 453 ScriptError error; 454 CTransaction inputi(input); 455 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); 456 assert(ret == success); 457 } 458 459 static CScript PushAll(const std::vector<valtype>& values) 460 { 461 CScript result; 462 for (const valtype& v : values) { 463 if (v.size() == 0) { 464 result << OP_0; 465 } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) { 466 result << CScript::EncodeOP_N(v[0]); 467 } else if (v.size() == 1 && v[0] == 0x81) { 468 result << OP_1NEGATE; 469 } else { 470 result << v; 471 } 472 } 473 return result; 474 } 475 476 static void ReplaceRedeemScript(CScript& script, const CScript& redeemScript) 477 { 478 std::vector<valtype> stack; 479 EvalScript(stack, script, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE); 480 assert(stack.size() > 0); 481 stack.back() = std::vector<unsigned char>(redeemScript.begin(), redeemScript.end()); 482 script = PushAll(stack); 483 } 484 485 BOOST_AUTO_TEST_CASE(test_big_witness_transaction) 486 { 487 CMutableTransaction mtx; 488 mtx.nVersion = 1; 489 490 CKey key = GenerateRandomKey(); // Need to use compressed keys in segwit or the signing will fail 491 FillableSigningProvider keystore; 492 BOOST_CHECK(keystore.AddKeyPubKey(key, key.GetPubKey())); 493 CKeyID hash = key.GetPubKey().GetID(); 494 CScript scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(hash.begin(), hash.end()); 495 496 std::vector<int> sigHashes; 497 sigHashes.push_back(SIGHASH_NONE | SIGHASH_ANYONECANPAY); 498 sigHashes.push_back(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY); 499 sigHashes.push_back(SIGHASH_ALL | SIGHASH_ANYONECANPAY); 500 sigHashes.push_back(SIGHASH_NONE); 501 sigHashes.push_back(SIGHASH_SINGLE); 502 sigHashes.push_back(SIGHASH_ALL); 503 504 // create a big transaction of 4500 inputs signed by the same key 505 for(uint32_t ij = 0; ij < 4500; ij++) { 506 uint32_t i = mtx.vin.size(); 507 COutPoint outpoint(TxidFromString("0000000000000000000000000000000000000000000000000000000000000100"), i); 508 509 mtx.vin.resize(mtx.vin.size() + 1); 510 mtx.vin[i].prevout = outpoint; 511 mtx.vin[i].scriptSig = CScript(); 512 513 mtx.vout.resize(mtx.vout.size() + 1); 514 mtx.vout[i].nValue = 1000; 515 mtx.vout[i].scriptPubKey = CScript() << OP_1; 516 } 517 518 // sign all inputs 519 for(uint32_t i = 0; i < mtx.vin.size(); i++) { 520 SignatureData empty; 521 bool hashSigned = SignSignature(keystore, scriptPubKey, mtx, i, 1000, sigHashes.at(i % sigHashes.size()), empty); 522 assert(hashSigned); 523 } 524 525 DataStream ssout; 526 ssout << TX_WITH_WITNESS(mtx); 527 CTransaction tx(deserialize, TX_WITH_WITNESS, ssout); 528 529 // check all inputs concurrently, with the cache 530 PrecomputedTransactionData txdata(tx); 531 CCheckQueue<CScriptCheck> scriptcheckqueue(/*batch_size=*/128, /*worker_threads_num=*/20); 532 CCheckQueueControl<CScriptCheck> control(&scriptcheckqueue); 533 534 std::vector<Coin> coins; 535 for(uint32_t i = 0; i < mtx.vin.size(); i++) { 536 Coin coin; 537 coin.nHeight = 1; 538 coin.fCoinBase = false; 539 coin.out.nValue = 1000; 540 coin.out.scriptPubKey = scriptPubKey; 541 coins.emplace_back(std::move(coin)); 542 } 543 544 for(uint32_t i = 0; i < mtx.vin.size(); i++) { 545 std::vector<CScriptCheck> vChecks; 546 vChecks.emplace_back(coins[tx.vin[i].prevout.n].out, tx, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false, &txdata); 547 control.Add(std::move(vChecks)); 548 } 549 550 bool controlCheck = control.Wait(); 551 assert(controlCheck); 552 } 553 554 SignatureData CombineSignatures(const CMutableTransaction& input1, const CMutableTransaction& input2, const CTransactionRef tx) 555 { 556 SignatureData sigdata; 557 sigdata = DataFromTransaction(input1, 0, tx->vout[0]); 558 sigdata.MergeSignatureData(DataFromTransaction(input2, 0, tx->vout[0])); 559 ProduceSignature(DUMMY_SIGNING_PROVIDER, MutableTransactionSignatureCreator(input1, 0, tx->vout[0].nValue, SIGHASH_ALL), tx->vout[0].scriptPubKey, sigdata); 560 return sigdata; 561 } 562 563 BOOST_AUTO_TEST_CASE(test_witness) 564 { 565 FillableSigningProvider keystore, keystore2; 566 CKey key1 = GenerateRandomKey(); 567 CKey key2 = GenerateRandomKey(); 568 CKey key3 = GenerateRandomKey(); 569 CKey key1L = GenerateRandomKey(/*compressed=*/false); 570 CKey key2L = GenerateRandomKey(/*compressed=*/false); 571 CPubKey pubkey1 = key1.GetPubKey(); 572 CPubKey pubkey2 = key2.GetPubKey(); 573 CPubKey pubkey3 = key3.GetPubKey(); 574 CPubKey pubkey1L = key1L.GetPubKey(); 575 CPubKey pubkey2L = key2L.GetPubKey(); 576 BOOST_CHECK(keystore.AddKeyPubKey(key1, pubkey1)); 577 BOOST_CHECK(keystore.AddKeyPubKey(key2, pubkey2)); 578 BOOST_CHECK(keystore.AddKeyPubKey(key1L, pubkey1L)); 579 BOOST_CHECK(keystore.AddKeyPubKey(key2L, pubkey2L)); 580 CScript scriptPubkey1, scriptPubkey2, scriptPubkey1L, scriptPubkey2L, scriptMulti; 581 scriptPubkey1 << ToByteVector(pubkey1) << OP_CHECKSIG; 582 scriptPubkey2 << ToByteVector(pubkey2) << OP_CHECKSIG; 583 scriptPubkey1L << ToByteVector(pubkey1L) << OP_CHECKSIG; 584 scriptPubkey2L << ToByteVector(pubkey2L) << OP_CHECKSIG; 585 std::vector<CPubKey> oneandthree; 586 oneandthree.push_back(pubkey1); 587 oneandthree.push_back(pubkey3); 588 scriptMulti = GetScriptForMultisig(2, oneandthree); 589 BOOST_CHECK(keystore.AddCScript(scriptPubkey1)); 590 BOOST_CHECK(keystore.AddCScript(scriptPubkey2)); 591 BOOST_CHECK(keystore.AddCScript(scriptPubkey1L)); 592 BOOST_CHECK(keystore.AddCScript(scriptPubkey2L)); 593 BOOST_CHECK(keystore.AddCScript(scriptMulti)); 594 CScript destination_script_1, destination_script_2, destination_script_1L, destination_script_2L, destination_script_multi; 595 destination_script_1 = GetScriptForDestination(WitnessV0KeyHash(pubkey1)); 596 destination_script_2 = GetScriptForDestination(WitnessV0KeyHash(pubkey2)); 597 destination_script_1L = GetScriptForDestination(WitnessV0KeyHash(pubkey1L)); 598 destination_script_2L = GetScriptForDestination(WitnessV0KeyHash(pubkey2L)); 599 destination_script_multi = GetScriptForDestination(WitnessV0ScriptHash(scriptMulti)); 600 BOOST_CHECK(keystore.AddCScript(destination_script_1)); 601 BOOST_CHECK(keystore.AddCScript(destination_script_2)); 602 BOOST_CHECK(keystore.AddCScript(destination_script_1L)); 603 BOOST_CHECK(keystore.AddCScript(destination_script_2L)); 604 BOOST_CHECK(keystore.AddCScript(destination_script_multi)); 605 BOOST_CHECK(keystore2.AddCScript(scriptMulti)); 606 BOOST_CHECK(keystore2.AddCScript(destination_script_multi)); 607 BOOST_CHECK(keystore2.AddKeyPubKey(key3, pubkey3)); 608 609 CTransactionRef output1, output2; 610 CMutableTransaction input1, input2; 611 612 // Normal pay-to-compressed-pubkey. 613 CreateCreditAndSpend(keystore, scriptPubkey1, output1, input1); 614 CreateCreditAndSpend(keystore, scriptPubkey2, output2, input2); 615 CheckWithFlag(output1, input1, 0, true); 616 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true); 617 CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true); 618 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true); 619 CheckWithFlag(output1, input2, 0, false); 620 CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, false); 621 CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false); 622 CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false); 623 624 // P2SH pay-to-compressed-pubkey. 625 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptPubkey1)), output1, input1); 626 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptPubkey2)), output2, input2); 627 ReplaceRedeemScript(input2.vin[0].scriptSig, scriptPubkey1); 628 CheckWithFlag(output1, input1, 0, true); 629 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true); 630 CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true); 631 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true); 632 CheckWithFlag(output1, input2, 0, true); 633 CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, false); 634 CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false); 635 CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false); 636 637 // Witness pay-to-compressed-pubkey (v0). 638 CreateCreditAndSpend(keystore, destination_script_1, output1, input1); 639 CreateCreditAndSpend(keystore, destination_script_2, output2, input2); 640 CheckWithFlag(output1, input1, 0, true); 641 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true); 642 CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true); 643 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true); 644 CheckWithFlag(output1, input2, 0, true); 645 CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, true); 646 CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false); 647 CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false); 648 649 // P2SH witness pay-to-compressed-pubkey (v0). 650 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_1)), output1, input1); 651 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_2)), output2, input2); 652 ReplaceRedeemScript(input2.vin[0].scriptSig, destination_script_1); 653 CheckWithFlag(output1, input1, 0, true); 654 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true); 655 CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true); 656 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true); 657 CheckWithFlag(output1, input2, 0, true); 658 CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, true); 659 CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false); 660 CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false); 661 662 // Normal pay-to-uncompressed-pubkey. 663 CreateCreditAndSpend(keystore, scriptPubkey1L, output1, input1); 664 CreateCreditAndSpend(keystore, scriptPubkey2L, output2, input2); 665 CheckWithFlag(output1, input1, 0, true); 666 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true); 667 CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true); 668 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true); 669 CheckWithFlag(output1, input2, 0, false); 670 CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, false); 671 CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false); 672 CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false); 673 674 // P2SH pay-to-uncompressed-pubkey. 675 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptPubkey1L)), output1, input1); 676 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptPubkey2L)), output2, input2); 677 ReplaceRedeemScript(input2.vin[0].scriptSig, scriptPubkey1L); 678 CheckWithFlag(output1, input1, 0, true); 679 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true); 680 CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true); 681 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true); 682 CheckWithFlag(output1, input2, 0, true); 683 CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, false); 684 CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false); 685 CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false); 686 687 // Signing disabled for witness pay-to-uncompressed-pubkey (v1). 688 CreateCreditAndSpend(keystore, destination_script_1L, output1, input1, false); 689 CreateCreditAndSpend(keystore, destination_script_2L, output2, input2, false); 690 691 // Signing disabled for P2SH witness pay-to-uncompressed-pubkey (v1). 692 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_1L)), output1, input1, false); 693 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_2L)), output2, input2, false); 694 695 // Normal 2-of-2 multisig 696 CreateCreditAndSpend(keystore, scriptMulti, output1, input1, false); 697 CheckWithFlag(output1, input1, 0, false); 698 CreateCreditAndSpend(keystore2, scriptMulti, output2, input2, false); 699 CheckWithFlag(output2, input2, 0, false); 700 BOOST_CHECK(*output1 == *output2); 701 UpdateInput(input1.vin[0], CombineSignatures(input1, input2, output1)); 702 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true); 703 704 // P2SH 2-of-2 multisig 705 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptMulti)), output1, input1, false); 706 CheckWithFlag(output1, input1, 0, true); 707 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, false); 708 CreateCreditAndSpend(keystore2, GetScriptForDestination(ScriptHash(scriptMulti)), output2, input2, false); 709 CheckWithFlag(output2, input2, 0, true); 710 CheckWithFlag(output2, input2, SCRIPT_VERIFY_P2SH, false); 711 BOOST_CHECK(*output1 == *output2); 712 UpdateInput(input1.vin[0], CombineSignatures(input1, input2, output1)); 713 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true); 714 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true); 715 716 // Witness 2-of-2 multisig 717 CreateCreditAndSpend(keystore, destination_script_multi, output1, input1, false); 718 CheckWithFlag(output1, input1, 0, true); 719 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false); 720 CreateCreditAndSpend(keystore2, destination_script_multi, output2, input2, false); 721 CheckWithFlag(output2, input2, 0, true); 722 CheckWithFlag(output2, input2, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false); 723 BOOST_CHECK(*output1 == *output2); 724 UpdateInput(input1.vin[0], CombineSignatures(input1, input2, output1)); 725 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, true); 726 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true); 727 728 // P2SH witness 2-of-2 multisig 729 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_multi)), output1, input1, false); 730 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true); 731 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false); 732 CreateCreditAndSpend(keystore2, GetScriptForDestination(ScriptHash(destination_script_multi)), output2, input2, false); 733 CheckWithFlag(output2, input2, SCRIPT_VERIFY_P2SH, true); 734 CheckWithFlag(output2, input2, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false); 735 BOOST_CHECK(*output1 == *output2); 736 UpdateInput(input1.vin[0], CombineSignatures(input1, input2, output1)); 737 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, true); 738 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true); 739 } 740 741 BOOST_AUTO_TEST_CASE(test_IsStandard) 742 { 743 FillableSigningProvider keystore; 744 CCoinsView coinsDummy; 745 CCoinsViewCache coins(&coinsDummy); 746 std::vector<CMutableTransaction> dummyTransactions = 747 SetupDummyInputs(keystore, coins, {11*CENT, 50*CENT, 21*CENT, 22*CENT}); 748 749 CMutableTransaction t; 750 t.vin.resize(1); 751 t.vin[0].prevout.hash = dummyTransactions[0].GetHash(); 752 t.vin[0].prevout.n = 1; 753 t.vin[0].scriptSig << std::vector<unsigned char>(65, 0); 754 t.vout.resize(1); 755 t.vout[0].nValue = 90*CENT; 756 CKey key = GenerateRandomKey(); 757 t.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey())); 758 759 constexpr auto CheckIsStandard = [](const auto& t) { 760 std::string reason; 761 BOOST_CHECK(IsStandardTx(CTransaction{t}, MAX_OP_RETURN_RELAY, g_bare_multi, g_dust, reason)); 762 BOOST_CHECK(reason.empty()); 763 }; 764 constexpr auto CheckIsNotStandard = [](const auto& t, const std::string& reason_in) { 765 std::string reason; 766 BOOST_CHECK(!IsStandardTx(CTransaction{t}, MAX_OP_RETURN_RELAY, g_bare_multi, g_dust, reason)); 767 BOOST_CHECK_EQUAL(reason_in, reason); 768 }; 769 770 CheckIsStandard(t); 771 772 // Check dust with default relay fee: 773 CAmount nDustThreshold = 182 * g_dust.GetFeePerK() / 1000; 774 BOOST_CHECK_EQUAL(nDustThreshold, 546); 775 // dust: 776 t.vout[0].nValue = nDustThreshold - 1; 777 CheckIsNotStandard(t, "dust"); 778 // not dust: 779 t.vout[0].nValue = nDustThreshold; 780 CheckIsStandard(t); 781 782 // Disallowed nVersion 783 t.nVersion = -1; 784 CheckIsNotStandard(t, "version"); 785 786 t.nVersion = 0; 787 CheckIsNotStandard(t, "version"); 788 789 t.nVersion = TX_MAX_STANDARD_VERSION + 1; 790 CheckIsNotStandard(t, "version"); 791 792 // Allowed nVersion 793 t.nVersion = 1; 794 CheckIsStandard(t); 795 796 t.nVersion = 2; 797 CheckIsStandard(t); 798 799 // Check dust with odd relay fee to verify rounding: 800 // nDustThreshold = 182 * 3702 / 1000 801 g_dust = CFeeRate(3702); 802 // dust: 803 t.vout[0].nValue = 674 - 1; 804 CheckIsNotStandard(t, "dust"); 805 // not dust: 806 t.vout[0].nValue = 674; 807 CheckIsStandard(t); 808 g_dust = CFeeRate{DUST_RELAY_TX_FEE}; 809 810 t.vout[0].scriptPubKey = CScript() << OP_1; 811 CheckIsNotStandard(t, "scriptpubkey"); 812 813 // MAX_OP_RETURN_RELAY-byte TxoutType::NULL_DATA (standard) 814 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); 815 BOOST_CHECK_EQUAL(MAX_OP_RETURN_RELAY, t.vout[0].scriptPubKey.size()); 816 CheckIsStandard(t); 817 818 // MAX_OP_RETURN_RELAY+1-byte TxoutType::NULL_DATA (non-standard) 819 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3800"); 820 BOOST_CHECK_EQUAL(MAX_OP_RETURN_RELAY + 1, t.vout[0].scriptPubKey.size()); 821 CheckIsNotStandard(t, "scriptpubkey"); 822 823 // Data payload can be encoded in any way... 824 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex(""); 825 CheckIsStandard(t); 826 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("00") << ParseHex("01"); 827 CheckIsStandard(t); 828 // OP_RESERVED *is* considered to be a PUSHDATA type opcode by IsPushOnly()! 829 t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RESERVED << -1 << 0 << ParseHex("01") << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16; 830 CheckIsStandard(t); 831 t.vout[0].scriptPubKey = CScript() << OP_RETURN << 0 << ParseHex("01") << 2 << ParseHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); 832 CheckIsStandard(t); 833 834 // ...so long as it only contains PUSHDATA's 835 t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RETURN; 836 CheckIsNotStandard(t, "scriptpubkey"); 837 838 // TxoutType::NULL_DATA w/o PUSHDATA 839 t.vout.resize(1); 840 t.vout[0].scriptPubKey = CScript() << OP_RETURN; 841 CheckIsStandard(t); 842 843 // Only one TxoutType::NULL_DATA permitted in all cases 844 t.vout.resize(2); 845 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); 846 t.vout[0].nValue = 0; 847 t.vout[1].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); 848 t.vout[1].nValue = 0; 849 CheckIsNotStandard(t, "multi-op-return"); 850 851 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); 852 t.vout[1].scriptPubKey = CScript() << OP_RETURN; 853 CheckIsNotStandard(t, "multi-op-return"); 854 855 t.vout[0].scriptPubKey = CScript() << OP_RETURN; 856 t.vout[1].scriptPubKey = CScript() << OP_RETURN; 857 CheckIsNotStandard(t, "multi-op-return"); 858 859 // Check large scriptSig (non-standard if size is >1650 bytes) 860 t.vout.resize(1); 861 t.vout[0].nValue = MAX_MONEY; 862 t.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey())); 863 // OP_PUSHDATA2 with len (3 bytes) + data (1647 bytes) = 1650 bytes 864 t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(1647, 0); // 1650 865 CheckIsStandard(t); 866 867 t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(1648, 0); // 1651 868 CheckIsNotStandard(t, "scriptsig-size"); 869 870 // Check scriptSig format (non-standard if there are any other ops than just PUSHs) 871 t.vin[0].scriptSig = CScript() 872 << OP_TRUE << OP_0 << OP_1NEGATE << OP_16 // OP_n (single byte pushes: n = 1, 0, -1, 16) 873 << std::vector<unsigned char>(75, 0) // OP_PUSHx [...x bytes...] 874 << std::vector<unsigned char>(235, 0) // OP_PUSHDATA1 x [...x bytes...] 875 << std::vector<unsigned char>(1234, 0) // OP_PUSHDATA2 x [...x bytes...] 876 << OP_9; 877 CheckIsStandard(t); 878 879 const std::vector<unsigned char> non_push_ops = { // arbitrary set of non-push operations 880 OP_NOP, OP_VERIFY, OP_IF, OP_ROT, OP_3DUP, OP_SIZE, OP_EQUAL, OP_ADD, OP_SUB, 881 OP_HASH256, OP_CODESEPARATOR, OP_CHECKSIG, OP_CHECKLOCKTIMEVERIFY }; 882 883 CScript::const_iterator pc = t.vin[0].scriptSig.begin(); 884 while (pc < t.vin[0].scriptSig.end()) { 885 opcodetype opcode; 886 CScript::const_iterator prev_pc = pc; 887 t.vin[0].scriptSig.GetOp(pc, opcode); // advance to next op 888 // for the sake of simplicity, we only replace single-byte push operations 889 if (opcode >= 1 && opcode <= OP_PUSHDATA4) 890 continue; 891 892 int index = prev_pc - t.vin[0].scriptSig.begin(); 893 unsigned char orig_op = *prev_pc; // save op 894 // replace current push-op with each non-push-op 895 for (auto op : non_push_ops) { 896 t.vin[0].scriptSig[index] = op; 897 CheckIsNotStandard(t, "scriptsig-not-pushonly"); 898 } 899 t.vin[0].scriptSig[index] = orig_op; // restore op 900 CheckIsStandard(t); 901 } 902 903 // Check tx-size (non-standard if transaction weight is > MAX_STANDARD_TX_WEIGHT) 904 t.vin.clear(); 905 t.vin.resize(2438); // size per input (empty scriptSig): 41 bytes 906 t.vout[0].scriptPubKey = CScript() << OP_RETURN << std::vector<unsigned char>(19, 0); // output size: 30 bytes 907 // tx header: 12 bytes => 48 vbytes 908 // 2438 inputs: 2438*41 = 99958 bytes => 399832 vbytes 909 // 1 output: 30 bytes => 120 vbytes 910 // =============================== 911 // total: 400000 vbytes 912 BOOST_CHECK_EQUAL(GetTransactionWeight(CTransaction(t)), 400000); 913 CheckIsStandard(t); 914 915 // increase output size by one byte, so we end up with 400004 vbytes 916 t.vout[0].scriptPubKey = CScript() << OP_RETURN << std::vector<unsigned char>(20, 0); // output size: 31 bytes 917 BOOST_CHECK_EQUAL(GetTransactionWeight(CTransaction(t)), 400004); 918 CheckIsNotStandard(t, "tx-size"); 919 920 // Check bare multisig (standard if policy flag g_bare_multi is set) 921 g_bare_multi = true; 922 t.vout[0].scriptPubKey = GetScriptForMultisig(1, {key.GetPubKey()}); // simple 1-of-1 923 t.vin.resize(1); 924 t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(65, 0); 925 CheckIsStandard(t); 926 927 g_bare_multi = false; 928 CheckIsNotStandard(t, "bare-multisig"); 929 g_bare_multi = DEFAULT_PERMIT_BAREMULTISIG; 930 931 // Check compressed P2PK outputs dust threshold (must have leading 02 or 03) 932 t.vout[0].scriptPubKey = CScript() << std::vector<unsigned char>(33, 0x02) << OP_CHECKSIG; 933 t.vout[0].nValue = 576; 934 CheckIsStandard(t); 935 t.vout[0].nValue = 575; 936 CheckIsNotStandard(t, "dust"); 937 938 // Check uncompressed P2PK outputs dust threshold (must have leading 04/06/07) 939 t.vout[0].scriptPubKey = CScript() << std::vector<unsigned char>(65, 0x04) << OP_CHECKSIG; 940 t.vout[0].nValue = 672; 941 CheckIsStandard(t); 942 t.vout[0].nValue = 671; 943 CheckIsNotStandard(t, "dust"); 944 945 // Check P2PKH outputs dust threshold 946 t.vout[0].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << std::vector<unsigned char>(20, 0) << OP_EQUALVERIFY << OP_CHECKSIG; 947 t.vout[0].nValue = 546; 948 CheckIsStandard(t); 949 t.vout[0].nValue = 545; 950 CheckIsNotStandard(t, "dust"); 951 952 // Check P2SH outputs dust threshold 953 t.vout[0].scriptPubKey = CScript() << OP_HASH160 << std::vector<unsigned char>(20, 0) << OP_EQUAL; 954 t.vout[0].nValue = 540; 955 CheckIsStandard(t); 956 t.vout[0].nValue = 539; 957 CheckIsNotStandard(t, "dust"); 958 959 // Check P2WPKH outputs dust threshold 960 t.vout[0].scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(20, 0); 961 t.vout[0].nValue = 294; 962 CheckIsStandard(t); 963 t.vout[0].nValue = 293; 964 CheckIsNotStandard(t, "dust"); 965 966 // Check P2WSH outputs dust threshold 967 t.vout[0].scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(32, 0); 968 t.vout[0].nValue = 330; 969 CheckIsStandard(t); 970 t.vout[0].nValue = 329; 971 CheckIsNotStandard(t, "dust"); 972 973 // Check P2TR outputs dust threshold (Invalid xonly key ok!) 974 t.vout[0].scriptPubKey = CScript() << OP_1 << std::vector<unsigned char>(32, 0); 975 t.vout[0].nValue = 330; 976 CheckIsStandard(t); 977 t.vout[0].nValue = 329; 978 CheckIsNotStandard(t, "dust"); 979 980 // Check future Witness Program versions dust threshold (non-32-byte pushes are undefined for version 1) 981 for (int op = OP_1; op <= OP_16; op += 1) { 982 t.vout[0].scriptPubKey = CScript() << (opcodetype)op << std::vector<unsigned char>(2, 0); 983 t.vout[0].nValue = 240; 984 CheckIsStandard(t); 985 986 t.vout[0].nValue = 239; 987 CheckIsNotStandard(t, "dust"); 988 } 989 } 990 991 BOOST_AUTO_TEST_SUITE_END()