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