Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
transaction_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <test/data/tx_invalid.json.h>
6#include <test/data/tx_valid.json.h>
8
9#include <chain.h>
10#include <checkqueue.h>
11#include <clientversion.h>
12#include <consensus/amount.h>
13#include <consensus/consensus.h>
14#include <consensus/tx_check.h>
15#include <consensus/tx_verify.h>
17#include <core_io.h>
18#include <key.h>
19#include <policy/policy.h>
20#include <policy/settings.h>
22#include <script/interpreter.h>
23#include <script/script.h>
24#include <script/script_error.h>
25#include <script/sigcache.h>
26#include <script/sign.h>
28#include <script/solver.h>
29#include <streams.h>
30#include <test/util/common.h>
31#include <test/util/json.h>
32#include <test/util/random.h>
33#include <test/util/script.h>
35#include <util/strencodings.h>
36#include <util/string.h>
37#include <validation.h>
38
39#include <functional>
40#include <map>
41#include <string>
42
43#include <boost/test/unit_test.hpp>
44
45#include <univalue.h>
46
47using namespace util::hex_literals;
49using util::ToString;
50
51typedef std::vector<unsigned char> valtype;
52
55
56static const std::map<std::string, script_verify_flag_name>& mapFlagNames = ScriptFlagNamesToEnum();
57
59{
61 if (strFlags.empty() || strFlags == "NONE") return flags;
62
63 std::vector<std::string> words = SplitString(strFlags, ',');
64 for (const std::string& word : words)
65 {
66 if (!mapFlagNames.contains(word)) {
67 BOOST_ERROR("Bad test: unknown verification flag '" << word << "'");
68 continue;
69 }
70 flags |= mapFlagNames.at(word);
71 }
72 return flags;
73}
74
75// Check that all flags in STANDARD_SCRIPT_VERIFY_FLAGS are present in mapFlagNames.
84
85/*
86* Check that the input scripts of a transaction are valid/invalid as expected.
87*/
88bool CheckTxScripts(const CTransaction& tx, const std::map<COutPoint, CScript>& map_prevout_scriptPubKeys,
89 const std::map<COutPoint, int64_t>& map_prevout_values, script_verify_flags flags,
90 const PrecomputedTransactionData& txdata, const std::string& strTest, bool expect_valid)
91{
92 bool tx_valid = true;
94 for (unsigned int i = 0; i < tx.vin.size() && tx_valid; ++i) {
95 const CTxIn input = tx.vin[i];
96 const CAmount amount = map_prevout_values.contains(input.prevout) ? map_prevout_values.at(input.prevout) : 0;
97 try {
100 } catch (...) {
101 BOOST_ERROR("Bad test: " << strTest);
102 return true; // The test format is bad and an error is thrown. Return true to silence further error.
103 }
104 if (expect_valid) {
108 }
109 }
110 if (!expect_valid) {
113 }
114 return (tx_valid == expect_valid);
115}
116
117/*
118 * Trim or fill flags to make the combination valid:
119 * WITNESS must be used with P2SH
120 * CLEANSTACK must be used WITNESS and P2SH
121 */
122
124{
125 // WITNESS requires P2SH
127
128 // CLEANSTACK requires WITNESS (and transitively CLEANSTACK requires P2SH)
131 return flags;
132}
133
135{
136 // CLEANSTACK implies WITNESS
138
139 // WITNESS implies P2SH (and transitively CLEANSTACK implies P2SH)
142 return flags;
143}
144
145// Exclude each possible script verify flag from flags. Returns a set of these flag combinations
146// that are valid and without duplicates. For example: if flags=1111 and the 4 possible flags are
147// 0001, 0010, 0100, and 1000, this should return the set {0111, 1011, 1101, 1110}.
148// Assumes that mapFlagNames contains all script verify flags.
150{
151 std::set<script_verify_flags> flags_combos;
152 for (const auto& pair : mapFlagNames) {
154 if (flags != flags_excluding_one) {
156 }
157 }
158 return flags_combos;
159}
160
162
164{
165 BOOST_CHECK_MESSAGE(CheckMapFlagNames(), "mapFlagNames is missing a script verification flag");
166 // Read tests from test/data/tx_valid.json
167 UniValue tests = read_json(json_tests::tx_valid);
168
169 for (unsigned int idx = 0; idx < tests.size(); idx++) {
170 const UniValue& test = tests[idx];
171 std::string strTest = test.write();
172 if (test[0].isArray())
173 {
174 if (test.size() != 3 || !test[1].isStr() || !test[2].isStr())
175 {
176 BOOST_ERROR("Bad test: " << strTest);
177 continue;
178 }
179
180 std::map<COutPoint, CScript> mapprevOutScriptPubKeys;
181 std::map<COutPoint, int64_t> mapprevOutValues;
182 UniValue inputs = test[0].get_array();
183 bool fValid = true;
184 for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) {
185 const UniValue& input = inputs[inpIdx];
186 if (!input.isArray()) {
187 fValid = false;
188 break;
189 }
190 const UniValue& vinput = input.get_array();
191 if (vinput.size() < 3 || vinput.size() > 4)
192 {
193 fValid = false;
194 break;
195 }
196 COutPoint outpoint{Txid::FromHex(vinput[0].get_str()).value(), uint32_t(vinput[1].getInt<int>())};
197 mapprevOutScriptPubKeys[outpoint] = ParseScript(vinput[2].get_str());
198 if (vinput.size() >= 4)
199 {
200 mapprevOutValues[outpoint] = vinput[3].getInt<int64_t>();
201 }
202 }
203 if (!fValid)
204 {
205 BOOST_ERROR("Bad test: " << strTest);
206 continue;
207 }
208
209 std::string transaction = test[1].get_str();
212
213 TxValidationState state;
215 BOOST_CHECK(state.IsValid());
216
219
220 // Check that the test gives a valid combination of flags (otherwise VerifyScript will throw). Don't edit the flags.
222 BOOST_ERROR("Bad test flags: " << strTest);
223 }
224
226 "Tx unexpectedly failed: " << strTest);
227
228 // Backwards compatibility of script verification flags: Removing any flag(s) should not invalidate a valid transaction
229 for (const auto& [name, flag] : mapFlagNames) {
230 // Removing individual flags
232 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/true)) {
233 BOOST_ERROR("Tx unexpectedly failed with flag " << name << " unset: " << strTest);
234 }
235 // Removing random combinations of flags
237 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/true)) {
238 BOOST_ERROR("Tx unexpectedly failed with random flags " << ToString(flags.as_int()) << ": " << strTest);
239 }
240 }
241
242 // Check that flags are maximal: transaction should fail if any unset flags are set.
244 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, ~flags_excluding_one, txdata, strTest, /*expect_valid=*/false)) {
245 BOOST_ERROR("Too many flags unset: " << strTest);
246 }
247 }
248 }
249 }
250}
251
253{
254 // Read tests from test/data/tx_invalid.json
255 UniValue tests = read_json(json_tests::tx_invalid);
256
257 for (unsigned int idx = 0; idx < tests.size(); idx++) {
258 const UniValue& test = tests[idx];
259 std::string strTest = test.write();
260 if (test[0].isArray())
261 {
262 if (test.size() != 3 || !test[1].isStr() || !test[2].isStr())
263 {
264 BOOST_ERROR("Bad test: " << strTest);
265 continue;
266 }
267
268 std::map<COutPoint, CScript> mapprevOutScriptPubKeys;
269 std::map<COutPoint, int64_t> mapprevOutValues;
270 UniValue inputs = test[0].get_array();
271 bool fValid = true;
272 for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) {
273 const UniValue& input = inputs[inpIdx];
274 if (!input.isArray()) {
275 fValid = false;
276 break;
277 }
278 const UniValue& vinput = input.get_array();
279 if (vinput.size() < 3 || vinput.size() > 4)
280 {
281 fValid = false;
282 break;
283 }
284 COutPoint outpoint{Txid::FromHex(vinput[0].get_str()).value(), uint32_t(vinput[1].getInt<int>())};
285 mapprevOutScriptPubKeys[outpoint] = ParseScript(vinput[2].get_str());
286 if (vinput.size() >= 4)
287 {
288 mapprevOutValues[outpoint] = vinput[3].getInt<int64_t>();
289 }
290 }
291 if (!fValid)
292 {
293 BOOST_ERROR("Bad test: " << strTest);
294 continue;
295 }
296
297 std::string transaction = test[1].get_str();
300
301 TxValidationState state;
302 if (!CheckTransaction(tx, state) || state.IsInvalid()) {
303 BOOST_CHECK_MESSAGE(test[2].get_str() == "BADTX", strTest);
304 continue;
305 }
306
309
310 // Check that the test gives a valid combination of flags (otherwise VerifyScript will throw). Don't edit the flags.
312 BOOST_ERROR("Bad test flags: " << strTest);
313 }
314
315 // Not using FillFlags() in the main test, in order to detect invalid verifyFlags combination
317 "Tx unexpectedly passed: " << strTest);
318
319 // Backwards compatibility of script verification flags: Adding any flag(s) should not validate an invalid transaction
320 for (const auto& [name, flag] : mapFlagNames) {
322 // Adding individual flags
323 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/false)) {
324 BOOST_ERROR("Tx unexpectedly passed with flag " << name << " set: " << strTest);
325 }
326 // Adding random combinations of flags
328 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/false)) {
329 BOOST_ERROR("Tx unexpectedly passed with random flags " << name << ": " << strTest);
330 }
331 }
332
333 // Check that flags are minimal: transaction should succeed if any set flags are unset.
335 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags_excluding_one, txdata, strTest, /*expect_valid=*/true)) {
336 BOOST_ERROR("Too many flags set: " << strTest);
337 }
338 }
339 }
340 }
341}
342
344{
346
347 TxValidationState state;
348 BOOST_CHECK_MESSAGE(!CheckTransaction(CTransaction(empty), state), "Transaction with no inputs should be invalid.");
349 BOOST_CHECK(state.GetRejectReason() == "bad-txns-vin-empty");
350}
351
353{
354 auto createTransaction =[](size_t payloadSize) {
356 tx.vin.resize(1);
358 return CTransaction(tx);
359 };
362
364 {
365 TxValidationState state;
366 CheckTransaction(createTransaction(maxPayloadSize), state);
367 BOOST_CHECK(state.GetRejectReason() != "bad-txns-oversize");
368 }
369
370 maxPayloadSize += 1;
371 {
372 TxValidationState state;
373 BOOST_CHECK_MESSAGE(!CheckTransaction(createTransaction(maxPayloadSize), state), "Oversized transaction should be invalid");
374 BOOST_CHECK(state.GetRejectReason() == "bad-txns-oversize");
375 }
376}
377
379{
380 // Random real transaction (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436)
381 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};
382 std::vector<unsigned char> vch(ch, ch + sizeof(ch) -1);
384 SpanReader{vch} >> TX_WITH_WITNESS(tx);
385 TxValidationState state;
386 BOOST_CHECK_MESSAGE(CheckTransaction(CTransaction(tx), state), "Simple deserialized transaction should be valid.");
387 BOOST_CHECK_MESSAGE(state.IsValid(), "Simple deserialized transaction should be valid.");
388
389 // Check that duplicate txins fail
390 tx.vin.push_back(tx.vin[0]);
391 BOOST_CHECK_MESSAGE(!CheckTransaction(CTransaction(tx), state) || !state.IsValid(), "Transaction with duplicate txins should be invalid.");
392}
393
395{
398 std::vector<CMutableTransaction> dummyTransactions =
399 SetupDummyInputs(keystore, coins, {11*CENT, 50*CENT, 21*CENT, 22*CENT});
400
402 t1.vin = {
403 CTxIn{COutPoint{dummyTransactions[0].GetHash(), 1}, CScript{} << std::vector<unsigned char>(65, 0)},
404 CTxIn{COutPoint{dummyTransactions[1].GetHash(), 0}, CScript{} << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4)},
405 CTxIn{COutPoint{dummyTransactions[1].GetHash(), 1}, CScript{} << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4)},
406 };
407 t1.vout = {
408 CTxOut{90 * CENT, CScript{} << OP_1},
409 CTxOut{},
410 };
411
413}
414
415static void CreateCreditAndSpend(const FillableSigningProvider& keystore, const CScript& outscript, CTransactionRef& output, CMutableTransaction& input, bool success = true)
416{
418 outputm.version = 1;
419 outputm.vin.resize(1);
420 outputm.vin[0].prevout.SetNull();
421 outputm.vin[0].scriptSig = CScript();
422 outputm.vout.resize(1);
423 outputm.vout[0].nValue = 1;
424 outputm.vout[0].scriptPubKey = outscript;
427 ssout >> TX_WITH_WITNESS(output);
428 assert(output->vin.size() == 1);
429 assert(output->vin[0] == outputm.vin[0]);
430 assert(output->vout.size() == 1);
431 assert(output->vout[0] == outputm.vout[0]);
432
434 inputm.version = 1;
435 inputm.vin.resize(1);
436 inputm.vin[0].prevout.hash = output->GetHash();
437 inputm.vin[0].prevout.n = 0;
438 inputm.vout.resize(1);
439 inputm.vout[0].nValue = 1;
440 inputm.vout[0].scriptPubKey = CScript();
441 SignatureData empty;
442 bool ret = SignSignature(keystore, *output, inputm, 0, SIGHASH_ALL, empty);
443 assert(ret == success);
446 ssin >> TX_WITH_WITNESS(input);
447 assert(input.vin.size() == 1);
448 assert(input.vin[0] == inputm.vin[0]);
449 assert(input.vout.size() == 1);
450 assert(input.vout[0] == inputm.vout[0]);
451 assert(input.vin[0].scriptWitness.stack == inputm.vin[0].scriptWitness.stack);
452}
453
454static void CheckWithFlag(const CTransactionRef& output, const CMutableTransaction& input, script_verify_flags flags, bool success)
455{
456 ScriptError error;
457 CTransaction inputi(input);
458 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);
459 assert(ret == success);
460}
461
462static CScript PushAll(const std::vector<valtype>& values)
463{
464 CScript result;
465 for (const valtype& v : values) {
466 if (v.size() == 0) {
467 result << OP_0;
468 } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
469 result << CScript::EncodeOP_N(v[0]);
470 } else if (v.size() == 1 && v[0] == 0x81) {
471 result << OP_1NEGATE;
472 } else {
473 result << v;
474 }
475 }
476 return result;
477}
478
480{
481 std::vector<valtype> stack;
483 assert(stack.size() > 0);
484 stack.back() = std::vector<unsigned char>(redeemScript.begin(), redeemScript.end());
485 script = PushAll(stack);
486}
487
489{
491 mtx.version = 1;
492
493 CKey key = GenerateRandomKey(); // Need to use compressed keys in segwit or the signing will fail
495 BOOST_CHECK(keystore.AddKeyPubKey(key, key.GetPubKey()));
496 CKeyID hash = key.GetPubKey().GetID();
497 CScript scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(hash.begin(), hash.end());
498
499 std::vector<int> sigHashes;
503 sigHashes.push_back(SIGHASH_NONE);
504 sigHashes.push_back(SIGHASH_SINGLE);
505 sigHashes.push_back(SIGHASH_ALL);
506
507 // create a big transaction of 4500 inputs signed by the same key
508 for(uint32_t ij = 0; ij < 4500; ij++) {
509 uint32_t i = mtx.vin.size();
510 COutPoint outpoint{Txid{"0000000000000000000000000000000000000000000000000000000000000100"}, i};
511
512 mtx.vin.resize(mtx.vin.size() + 1);
513 mtx.vin[i].prevout = outpoint;
514 mtx.vin[i].scriptSig = CScript();
515
516 mtx.vout.resize(mtx.vout.size() + 1);
517 mtx.vout[i].nValue = 1000;
518 mtx.vout[i].scriptPubKey = CScript() << OP_1;
519 }
520
521 // sign all inputs
522 for(uint32_t i = 0; i < mtx.vin.size(); i++) {
523 SignatureData empty;
524 bool hashSigned = SignSignature(keystore, scriptPubKey, mtx, i, 1000, sigHashes.at(i % sigHashes.size()), empty);
526 }
527
531
532 // check all inputs concurrently, with the cache
534 CCheckQueue<CScriptCheck> scriptcheckqueue(/*batch_size=*/128, /*worker_threads_num=*/20);
536
537 std::vector<Coin> coins;
538 for(uint32_t i = 0; i < mtx.vin.size(); i++) {
539 Coin coin;
540 coin.nHeight = 1;
541 coin.fCoinBase = false;
542 coin.out.nValue = 1000;
543 coin.out.scriptPubKey = scriptPubKey;
544 coins.emplace_back(std::move(coin));
545 }
546
548
549 for(uint32_t i = 0; i < mtx.vin.size(); i++) {
550 std::vector<CScriptCheck> vChecks;
551 vChecks.emplace_back(coins[tx.vin[i].prevout.n].out, tx, signature_cache, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false, &txdata);
552 control.Add(std::move(vChecks));
553 }
554
555 bool controlCheck = !control.Complete().has_value();
557}
558
560{
561 SignatureData sigdata;
562 sigdata = DataFromTransaction(input1, 0, tx->vout[0]);
563 sigdata.MergeSignatureData(DataFromTransaction(input2, 0, tx->vout[0]));
564 ProduceSignature(DUMMY_SIGNING_PROVIDER, MutableTransactionSignatureCreator(input1, 0, tx->vout[0].nValue, {.sighash_type = SIGHASH_DEFAULT}), tx->vout[0].scriptPubKey, sigdata);
565 return sigdata;
566}
567
569{
571 CKey key1 = GenerateRandomKey();
572 CKey key2 = GenerateRandomKey();
574 CKey key1L = GenerateRandomKey(/*compressed=*/false);
575 CKey key2L = GenerateRandomKey(/*compressed=*/false);
576 CPubKey pubkey1 = key1.GetPubKey();
577 CPubKey pubkey2 = key2.GetPubKey();
578 CPubKey pubkey3 = key3.GetPubKey();
579 CPubKey pubkey1L = key1L.GetPubKey();
580 CPubKey pubkey2L = key2L.GetPubKey();
581 BOOST_CHECK(keystore.AddKeyPubKey(key1, pubkey1));
582 BOOST_CHECK(keystore.AddKeyPubKey(key2, pubkey2));
583 BOOST_CHECK(keystore.AddKeyPubKey(key1L, pubkey1L));
584 BOOST_CHECK(keystore.AddKeyPubKey(key2L, pubkey2L));
590 std::vector<CPubKey> oneandthree;
591 oneandthree.push_back(pubkey1);
592 oneandthree.push_back(pubkey3);
598 BOOST_CHECK(keystore.AddCScript(scriptMulti));
610 BOOST_CHECK(keystore2.AddCScript(scriptMulti));
612 BOOST_CHECK(keystore2.AddKeyPubKey(key3, pubkey3));
613
616
617 // Normal pay-to-compressed-pubkey.
628
629 // P2SH pay-to-compressed-pubkey.
632 ReplaceRedeemScript(input2.vin[0].scriptSig, scriptPubkey1);
641
642 // Witness pay-to-compressed-pubkey (v0).
653
654 // P2SH witness pay-to-compressed-pubkey (v0).
666
667 // Normal pay-to-uncompressed-pubkey.
678
679 // P2SH pay-to-uncompressed-pubkey.
682 ReplaceRedeemScript(input2.vin[0].scriptSig, scriptPubkey1L);
691
692 // Signing disabled for witness pay-to-uncompressed-pubkey (v1).
695
696 // Signing disabled for P2SH witness pay-to-uncompressed-pubkey (v1).
699
700 // Normal 2-of-2 multisig
705 BOOST_CHECK(output1->Equals(*output2));
708
709 // P2SH 2-of-2 multisig
716 BOOST_CHECK(output1->Equals(*output2));
720
721 // Witness 2-of-2 multisig
728 BOOST_CHECK(output1->Equals(*output2));
732
733 // P2SH witness 2-of-2 multisig
740 BOOST_CHECK(output1->Equals(*output2));
744}
745
747{
750 std::vector<CMutableTransaction> dummyTransactions =
751 SetupDummyInputs(keystore, coins, {11*CENT, 50*CENT, 21*CENT, 22*CENT});
752
754 t.vin.resize(1);
755 t.vin[0].prevout.hash = dummyTransactions[0].GetHash();
756 t.vin[0].prevout.n = 1;
757 t.vin[0].scriptSig << std::vector<unsigned char>(65, 0);
758 t.vout.resize(1);
759 t.vout[0].nValue = 90*CENT;
760 CKey key = GenerateRandomKey();
761 t.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey()));
762
763 constexpr auto CheckIsStandard = [](const auto& t, const unsigned int max_op_return_relay = MAX_OP_RETURN_RELAY) {
764 std::string reason;
766 BOOST_CHECK(reason.empty());
767 };
768 constexpr auto CheckIsNotStandard = [](const auto& t, const std::string& reason_in, const unsigned int max_op_return_relay = MAX_OP_RETURN_RELAY) {
769 std::string reason;
772 };
773
775
776 // Check dust with default relay fee:
777 CAmount nDustThreshold = 182 * g_dust.GetFeePerK() / 1000;
779
780 // Add dust outputs up to allowed maximum, still standard!
781 for (size_t i{0}; i < MAX_DUST_OUTPUTS_PER_TX; ++i) {
782 t.vout.emplace_back(0, t.vout[0].scriptPubKey);
784 }
785
786 // dust:
787 t.vout[0].nValue = nDustThreshold - 1;
788 CheckIsNotStandard(t, "dust");
789 // not dust:
790 t.vout[0].nValue = nDustThreshold;
792
793 // Disallowed version
794 t.version = std::numeric_limits<uint32_t>::max();
795 CheckIsNotStandard(t, "version");
796
797 t.version = 0;
798 CheckIsNotStandard(t, "version");
799
800 t.version = TX_MAX_STANDARD_VERSION + 1;
801 CheckIsNotStandard(t, "version");
802
803 // Allowed version
804 t.version = 1;
806
807 t.version = 2;
809
810 // Check dust with odd relay fee to verify rounding:
811 // nDustThreshold = 182 * 3702 / 1000
812 g_dust = CFeeRate(3702);
813 // dust:
814 t.vout[0].nValue = 674 - 1;
815 CheckIsNotStandard(t, "dust");
816 // not dust:
817 t.vout[0].nValue = 674;
820
821 t.vout[0].scriptPubKey = CScript() << OP_1;
822 CheckIsNotStandard(t, "scriptpubkey");
823
824 // Custom 83-byte TxoutType::NULL_DATA (standard with max_op_return_relay of 83)
825 t.vout[0].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
826 BOOST_CHECK_EQUAL(83, t.vout[0].scriptPubKey.size());
827 CheckIsStandard(t, /*max_op_return_relay=*/83);
828
829 // Non-standard if max_op_return_relay datacarrier arg is one less
830 CheckIsNotStandard(t, "datacarrier", /*max_op_return_relay=*/82);
831
832 // Data payload can be encoded in any way...
833 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ""_hex;
835 t.vout[0].scriptPubKey = CScript() << OP_RETURN << "00"_hex << "01"_hex;
837 // OP_RESERVED *is* considered to be a PUSHDATA type opcode by IsPushOnly()!
838 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;
840 t.vout[0].scriptPubKey = CScript() << OP_RETURN << 0 << "01"_hex << 2 << "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"_hex;
842
843 // ...so long as it only contains PUSHDATA's
844 t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RETURN;
845 CheckIsNotStandard(t, "scriptpubkey");
846
847 // TxoutType::NULL_DATA w/o PUSHDATA
848 t.vout.resize(1);
849 t.vout[0].scriptPubKey = CScript() << OP_RETURN;
851
852 // Multiple TxoutType::NULL_DATA are permitted
853 t.vout.resize(2);
854 t.vout[0].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
855 t.vout[0].nValue = 0;
856 t.vout[1].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
857 t.vout[1].nValue = 0;
859
860 t.vout[0].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
861 t.vout[1].scriptPubKey = CScript() << OP_RETURN;
863
864 t.vout[0].scriptPubKey = CScript() << OP_RETURN;
865 t.vout[1].scriptPubKey = CScript() << OP_RETURN;
867
868 t.vout[0].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
869 t.vout[1].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
870 const auto datacarrier_size = t.vout[0].scriptPubKey.size() + t.vout[1].scriptPubKey.size();
871 CheckIsStandard(t); // Default max relay should never trigger
872 CheckIsStandard(t, /*max_op_return_relay=*/datacarrier_size);
873 CheckIsNotStandard(t, "datacarrier", /*max_op_return_relay=*/datacarrier_size-1);
874
875 // Check large scriptSig (non-standard if size is >1650 bytes)
876 t.vout.resize(1);
877 t.vout[0].nValue = MAX_MONEY;
878 t.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey()));
879 // OP_PUSHDATA2 with len (3 bytes) + data (1647 bytes) = 1650 bytes
880 t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(1647, 0); // 1650
882
883 t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(1648, 0); // 1651
884 CheckIsNotStandard(t, "scriptsig-size");
885
886 // Check scriptSig format (non-standard if there are any other ops than just PUSHs)
887 t.vin[0].scriptSig = CScript()
888 << OP_TRUE << OP_0 << OP_1NEGATE << OP_16 // OP_n (single byte pushes: n = 1, 0, -1, 16)
889 << std::vector<unsigned char>(75, 0) // OP_PUSHx [...x bytes...]
890 << std::vector<unsigned char>(235, 0) // OP_PUSHDATA1 x [...x bytes...]
891 << std::vector<unsigned char>(1234, 0) // OP_PUSHDATA2 x [...x bytes...]
892 << OP_9;
894
895 const std::vector<unsigned char> non_push_ops = { // arbitrary set of non-push operations
898
899 CScript::const_iterator pc = t.vin[0].scriptSig.begin();
900 while (pc < t.vin[0].scriptSig.end()) {
903 t.vin[0].scriptSig.GetOp(pc, opcode); // advance to next op
904 // for the sake of simplicity, we only replace single-byte push operations
905 if (opcode >= 1 && opcode <= OP_PUSHDATA4)
906 continue;
907
908 int index = prev_pc - t.vin[0].scriptSig.begin();
909 unsigned char orig_op = *prev_pc; // save op
910 // replace current push-op with each non-push-op
911 for (auto op : non_push_ops) {
912 t.vin[0].scriptSig[index] = op;
913 CheckIsNotStandard(t, "scriptsig-not-pushonly");
914 }
915 t.vin[0].scriptSig[index] = orig_op; // restore op
917 }
918
919 // Check tx-size (non-standard if transaction weight is > MAX_STANDARD_TX_WEIGHT)
920 t.vin.clear();
921 t.vin.resize(2438); // size per input (empty scriptSig): 41 bytes
922 t.vout[0].scriptPubKey = CScript() << OP_RETURN << std::vector<unsigned char>(19, 0); // output size: 30 bytes
923 // tx header: 12 bytes => 48 weight units
924 // 2438 inputs: 2438*41 = 99958 bytes => 399832 weight units
925 // 1 output: 30 bytes => 120 weight units
926 // ======================================
927 // total: 400000 weight units
930
931 // increase output size by one byte, so we end up with 400004 weight units
932 t.vout[0].scriptPubKey = CScript() << OP_RETURN << std::vector<unsigned char>(20, 0); // output size: 31 bytes
934 CheckIsNotStandard(t, "tx-size");
935
936 // Check bare multisig (standard if policy flag g_bare_multi is set)
937 g_bare_multi = true;
938 t.vout[0].scriptPubKey = GetScriptForMultisig(1, {key.GetPubKey()}); // simple 1-of-1
939 t.vin.resize(1);
940 t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(65, 0);
942
943 g_bare_multi = false;
944 CheckIsNotStandard(t, "bare-multisig");
946
947 // Add dust outputs up to allowed maximum
948 assert(t.vout.size() == 1);
949 t.vout.insert(t.vout.end(), MAX_DUST_OUTPUTS_PER_TX, {0, t.vout[0].scriptPubKey});
950
951 // Check compressed P2PK outputs dust threshold (must have leading 02 or 03)
952 t.vout[0].scriptPubKey = CScript() << std::vector<unsigned char>(33, 0x02) << OP_CHECKSIG;
953 t.vout[0].nValue = 576;
955 t.vout[0].nValue = 575;
956 CheckIsNotStandard(t, "dust");
957
958 // Check uncompressed P2PK outputs dust threshold (must have leading 04/06/07)
959 t.vout[0].scriptPubKey = CScript() << std::vector<unsigned char>(65, 0x04) << OP_CHECKSIG;
960 t.vout[0].nValue = 672;
962 t.vout[0].nValue = 671;
963 CheckIsNotStandard(t, "dust");
964
965 // Check P2PKH outputs dust threshold
967 t.vout[0].nValue = 546;
969 t.vout[0].nValue = 545;
970 CheckIsNotStandard(t, "dust");
971
972 // Check P2SH outputs dust threshold
973 t.vout[0].scriptPubKey = CScript() << OP_HASH160 << std::vector<unsigned char>(20, 0) << OP_EQUAL;
974 t.vout[0].nValue = 540;
976 t.vout[0].nValue = 539;
977 CheckIsNotStandard(t, "dust");
978
979 // Check P2WPKH outputs dust threshold
980 t.vout[0].scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(20, 0);
981 t.vout[0].nValue = 294;
983 t.vout[0].nValue = 293;
984 CheckIsNotStandard(t, "dust");
985
986 // Check P2WSH outputs dust threshold
987 t.vout[0].scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(32, 0);
988 t.vout[0].nValue = 330;
990 t.vout[0].nValue = 329;
991 CheckIsNotStandard(t, "dust");
992
993 // Check P2TR outputs dust threshold (Invalid xonly key ok!)
994 t.vout[0].scriptPubKey = CScript() << OP_1 << std::vector<unsigned char>(32, 0);
995 t.vout[0].nValue = 330;
997 t.vout[0].nValue = 329;
998 CheckIsNotStandard(t, "dust");
999
1000 // Check future Witness Program versions dust threshold (non-32-byte pushes are undefined for version 1)
1001 for (int op = OP_1; op <= OP_16; op += 1) {
1002 t.vout[0].scriptPubKey = CScript() << (opcodetype)op << std::vector<unsigned char>(2, 0);
1003 t.vout[0].nValue = 240;
1005
1006 t.vout[0].nValue = 239;
1007 CheckIsNotStandard(t, "dust");
1008 }
1009
1010 // Check anchor outputs
1011 t.vout[0].scriptPubKey = CScript() << OP_1 << ANCHOR_BYTES;
1012 BOOST_CHECK(t.vout[0].scriptPubKey.IsPayToAnchor());
1013 t.vout[0].nValue = 240;
1015 t.vout[0].nValue = 239;
1016 CheckIsNotStandard(t, "dust");
1017}
1018
1020{
1022 CKey key;
1023 key.MakeNewKey(true);
1024
1025 // Create a pathological P2SH script padded with as many sigops as is standard.
1026 CScript max_sigops_redeem_script{CScript() << std::vector<unsigned char>{} << key.GetPubKey()};
1027 for (unsigned i{0}; i < MAX_P2SH_SIGOPS - 1; ++i) max_sigops_redeem_script << OP_2DUP << OP_CHECKSIG << OP_DROP;
1030
1031 // Create a transaction fanning out as many such P2SH outputs as is standard to spend in a
1032 // single transaction, and a transaction spending them.
1036 for (unsigned i{0}; i < p2sh_inputs_count; ++i) {
1037 tx_create.vout.emplace_back(424242 + i, max_sigops_p2sh);
1038 }
1039 auto prev_txid{tx_create.GetHash()};
1040 tx_max_sigops.vin.reserve(p2sh_inputs_count);
1041 for (unsigned i{0}; i < p2sh_inputs_count; ++i) {
1042 tx_max_sigops.vin.emplace_back(prev_txid, i, CScript() << ToByteVector(max_sigops_redeem_script));
1043 }
1044
1045 // p2sh_inputs_count is truncated to 166 (from 166.6666..)
1047 AddCoins(coins, CTransaction(tx_create), 0, false);
1048
1049 // 2490 sigops is below the limit.
1052
1053 // Adding one more input will bump this to 2505, hitting the limit.
1054 tx_create.vout.emplace_back(424242, max_sigops_p2sh);
1055 prev_txid = tx_create.GetHash();
1056 for (unsigned i{0}; i < p2sh_inputs_count; ++i) {
1058 }
1060 AddCoins(coins, CTransaction(tx_create), 0, false);
1064 std::string reject_reason("bad-txns-nonstandard-inputs");
1065 std::string sigop_limit_reject_debug_message("non-witness sigops exceed bip54 limit");
1066 {
1068 BOOST_CHECK(validation_state.IsInvalid());
1071 }
1072
1073
1074 // Now, check the limit can be reached with regular P2PK outputs too. Use a separate
1075 // preparation transaction, to demonstrate spending coins from a single tx is irrelevant.
1077 const auto p2pk_script{CScript() << key.GetPubKey() << OP_CHECKSIG};
1078 unsigned p2pk_inputs_count{10}; // From 2490 to 2500.
1079 for (unsigned i{0}; i < p2pk_inputs_count; ++i) {
1080 tx_create_p2pk.vout.emplace_back(212121 + i, p2pk_script);
1081 }
1082 prev_txid = tx_create_p2pk.GetHash();
1083 tx_max_sigops.vin.resize(p2sh_inputs_count); // Drop the extra input.
1084 for (unsigned i{0}; i < p2pk_inputs_count; ++i) {
1085 tx_max_sigops.vin.emplace_back(prev_txid, i);
1086 }
1087 AddCoins(coins, CTransaction(tx_create_p2pk), 0, false);
1088
1089 // The transaction now contains exactly 2500 sigops, the check should pass.
1092
1093 // Now, add some Segwit inputs. We add one for each defined Segwit output type. The limit
1094 // is exclusively on non-witness sigops and therefore those should not be counted.
1096 const auto witness_script{CScript() << key.GetPubKey() << OP_CHECKSIG};
1097 tx_create_segwit.vout.emplace_back(121212, GetScriptForDestination(WitnessV0KeyHash(key.GetPubKey())));
1098 tx_create_segwit.vout.emplace_back(131313, GetScriptForDestination(WitnessV0ScriptHash(witness_script)));
1100 prev_txid = tx_create_segwit.GetHash();
1101 for (unsigned i{0}; i < tx_create_segwit.vout.size(); ++i) {
1102 tx_max_sigops.vin.emplace_back(prev_txid, i);
1103 }
1104
1105 // The transaction now still contains exactly 2500 sigops, the check should pass.
1106 AddCoins(coins, CTransaction(tx_create_segwit), 0, false);
1108
1109 // Add one more P2PK input. We'll reach the limit.
1110 tx_create_p2pk.vout.emplace_back(212121, p2pk_script);
1111 prev_txid = tx_create_p2pk.GetHash();
1112 tx_max_sigops.vin.resize(p2sh_inputs_count);
1114 for (unsigned i{0}; i < p2pk_inputs_count; ++i) {
1115 tx_max_sigops.vin.emplace_back(prev_txid, i);
1116 }
1117 AddCoins(coins, CTransaction(tx_create_p2pk), 0, false);
1120 {
1122 BOOST_CHECK(validation_state.IsInvalid());
1125 }
1126}
1127
1129{
1130 // Legacy sigops are counted inaccurately in both the scriptSig and the
1131 // scriptPubKey: a CHECKMULTISIG counts as MAX_PUBKEYS_PER_MULTISIG even when the
1132 // preceding OP_N says it takes fewer keys. Counting it accurately would
1133 // undercount, letting a block over the sigop limit through.
1135
1137 mtx.vin.emplace_back(COutPoint{}, multisig);
1139
1140 mtx.vout.emplace_back(0, multisig);
1142}
1143
1145{
1146 auto check_invalid{[](CAmount input_value, CAmount output_value, bool coinbase, int spend_height, TxValidationResult expected_result, std::string_view expected_reason) {
1148
1149 const COutPoint prevout{Txid::FromUint256(uint256::ONE), 0};
1150 inputs.AddCoin(prevout, Coin{{input_value, CScript() << OP_TRUE}, /*nHeightIn=*/1, coinbase}, /*possible_overwrite=*/false);
1151
1153 mtx.vin.emplace_back(prevout);
1154 mtx.vout.emplace_back(output_value, CScript() << OP_TRUE);
1155
1156 TxValidationState state;
1157 CAmount txfee{0};
1159 BOOST_CHECK(state.IsInvalid());
1160 BOOST_CHECK_EQUAL(state.GetResult(), expected_result);
1162 }};
1163
1164 check_invalid(/*input_value=*/MAX_MONEY + 1,
1165 /*output_value=*/0,
1166 /*coinbase=*/false,
1167 /*spend_height=*/2,
1168 TxValidationResult::TX_CONSENSUS, /*expected_reason=*/"bad-txns-inputvalues-outofrange");
1169
1170 check_invalid(/*input_value=*/1 * COIN,
1171 /*output_value=*/2 * COIN,
1172 /*coinbase=*/false,
1173 /*spend_height=*/2,
1174 TxValidationResult::TX_CONSENSUS, /*expected_reason=*/"bad-txns-in-belowout");
1175
1176 check_invalid(/*input_value=*/1 * COIN,
1177 /*output_value=*/0,
1178 /*coinbase=*/true,
1179 /*spend_height=*/COINBASE_MATURITY,
1180 TxValidationResult::TX_PREMATURE_SPEND, /*expected_reason=*/"bad-txns-premature-spend-of-coinbase");
1181}
1182
1184{
1185 constexpr int height{100};
1186
1187 // Every transaction here has the same unsatisfied nLockTime, so only the
1188 // sequences decide the outcome.
1189 auto check_final{[](const std::vector<uint32_t>& sequences, bool expected_final) {
1191 mtx.nLockTime = height;
1192 for (const uint32_t sequence : sequences) {
1193 mtx.vin.emplace_back(COutPoint{}, CScript{}, sequence);
1194 }
1195
1196 BOOST_CHECK_EQUAL(IsFinalTx(CTransaction{mtx}, /*nBlockHeight=*/height, /*nBlockTime=*/0), expected_final);
1197 }};
1198
1199 check_final(/*sequences=*/{CTxIn::SEQUENCE_FINAL, CTxIn::SEQUENCE_FINAL}, /*expected_final=*/true);
1200
1201 // nLockTime is only ignored when every input is SEQUENCE_FINAL
1202 check_final(/*sequences=*/{CTxIn::SEQUENCE_FINAL, CTxIn::MAX_SEQUENCE_NONFINAL}, /*expected_final=*/false);
1203 check_final(/*sequences=*/{CTxIn::MAX_SEQUENCE_NONFINAL, CTxIn::SEQUENCE_FINAL}, /*expected_final=*/false);
1204}
1205
1207{
1208 constexpr int coin_height{100};
1209
1210 // A single input with a height-based relative locktime of one block. Only the
1211 // height branch is taken, so the block index is never dereferenced.
1212 auto check_min_height{[](uint32_t version, int expected_min_height) {
1214 mtx.version = version;
1215 mtx.vin.emplace_back(COutPoint{}, CScript{}, /*nSequenceIn=*/1);
1216
1217 std::vector<int> prev_heights{coin_height};
1218 const CBlockIndex block{};
1221 }};
1222
1223 // BIP68 only applies to versions 2 and up
1224 check_min_height(/*version=*/0, /*expected_min_height=*/-1);
1225 check_min_height(/*version=*/1, /*expected_min_height=*/-1);
1226 check_min_height(/*version=*/2, /*expected_min_height=*/coin_height);
1227 check_min_height(/*version=*/std::numeric_limits<uint32_t>::max(), /*expected_min_height=*/coin_height);
1228}
1229
1231{
1233 mtx.vout.emplace_back(MAX_MONEY + 1, CScript() << OP_TRUE);
1234
1235 const CTransaction tx{mtx};
1236 BOOST_CHECK_EXCEPTION(tx.GetValueOut(), std::runtime_error, HasReason("GetValueOut: value out of range"));
1237}
1238
1241{
1243 CKey key;
1244 key.MakeNewKey(true);
1245 const CPubKey pubkey{key.GetPubKey()};
1247 tx_create.vout.emplace_back(0, CScript{});
1248 tx_spend.vin.emplace_back(Txid{}, 0);
1249 std::vector<std::vector<uint8_t>> sol_dummy;
1250
1251 // CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash,
1252 // WitnessV1Taproot, PayToAnchor, WitnessUnknown.
1253 static_assert(std::variant_size_v<CTxDestination> == 9);
1254
1255 // Go through all defined output types and sanity check SpendsNonAnchorWitnessProg.
1256
1257 // P2PK
1258 tx_create.vout[0].scriptPubKey = GetScriptForDestination(PubKeyDestination{pubkey});
1260 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1261 AddCoins(coins, CTransaction{tx_create}, 0, false);
1263
1264 // P2PKH
1265 tx_create.vout[0].scriptPubKey = GetScriptForDestination(PKHash{pubkey});
1267 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1268 AddCoins(coins, CTransaction{tx_create}, 0, false);
1270
1271 // P2SH
1272 auto redeem_script{CScript{} << OP_1 << OP_CHECKSIG};
1273 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash{redeem_script});
1275 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1276 tx_spend.vin[0].scriptSig = CScript{} << OP_0 << ToByteVector(redeem_script);
1277 AddCoins(coins, CTransaction{tx_create}, 0, false);
1279 tx_spend.vin[0].scriptSig.clear();
1280
1281 // native P2WSH
1282 const auto witness_script{CScript{} << OP_12 << OP_HASH160 << OP_DUP << OP_EQUAL};
1283 tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash{witness_script});
1285 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1286 AddCoins(coins, CTransaction{tx_create}, 0, false);
1288
1289 // P2SH-wrapped P2WSH
1290 redeem_script = tx_create.vout[0].scriptPubKey;
1291 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1293 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1294 tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1295 AddCoins(coins, CTransaction{tx_create}, 0, false);
1297 tx_spend.vin[0].scriptSig.clear();
1299
1300 // native P2WPKH
1301 tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessV0KeyHash{pubkey});
1303 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1304 AddCoins(coins, CTransaction{tx_create}, 0, false);
1306
1307 // P2SH-wrapped P2WPKH
1308 redeem_script = tx_create.vout[0].scriptPubKey;
1309 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1311 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1312 tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1313 AddCoins(coins, CTransaction{tx_create}, 0, false);
1315 tx_spend.vin[0].scriptSig.clear();
1317
1318 // P2TR
1319 tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessV1Taproot{XOnlyPubKey{pubkey}});
1321 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1322 AddCoins(coins, CTransaction{tx_create}, 0, false);
1324
1325 // P2SH-wrapped P2TR (undefined, non-standard)
1326 redeem_script = tx_create.vout[0].scriptPubKey;
1327 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1329 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1330 tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1331 AddCoins(coins, CTransaction{tx_create}, 0, false);
1333 tx_spend.vin[0].scriptSig.clear();
1335
1336 // P2A
1337 tx_create.vout[0].scriptPubKey = GetScriptForDestination(PayToAnchor{});
1339 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1340 AddCoins(coins, CTransaction{tx_create}, 0, false);
1342
1343 // P2SH-wrapped P2A (undefined, non-standard)
1344 redeem_script = tx_create.vout[0].scriptPubKey;
1345 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1347 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1348 tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1349 AddCoins(coins, CTransaction{tx_create}, 0, false);
1351 tx_spend.vin[0].scriptSig.clear();
1352
1353 // Undefined version 1 witness program
1354 tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessUnknown{1, {0x42, 0x42}});
1356 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1357 AddCoins(coins, CTransaction{tx_create}, 0, false);
1359
1360 // P2SH-wrapped undefined version 1 witness program
1361 redeem_script = tx_create.vout[0].scriptPubKey;
1362 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1364 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1365 tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1366 AddCoins(coins, CTransaction{tx_create}, 0, false);
1368 tx_spend.vin[0].scriptSig.clear();
1370
1371 // Various undefined version >1 32-byte witness programs.
1372 const auto program{ToByteVector(XOnlyPubKey{pubkey})};
1373 for (int i{2}; i <= 16; ++i) {
1374 tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessUnknown{i, program});
1376 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1377 AddCoins(coins, CTransaction{tx_create}, 0, false);
1379
1380 // It's also detected within P2SH.
1381 redeem_script = tx_create.vout[0].scriptPubKey;
1382 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1384 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1385 tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1386 AddCoins(coins, CTransaction{tx_create}, 0, false);
1388 tx_spend.vin[0].scriptSig.clear();
1390 }
1391}
1392
1394{
1395 // A transaction with one input, one output and a one-element witness.
1397 mtx.vin.resize(1);
1398 mtx.vin[0].scriptWitness.stack = {{0xaa}};
1399 mtx.vout.emplace_back(1, CScript{} << OP_TRUE);
1402
1404 DataStream{std::span{ser}} >> TX_WITH_WITNESS(tx);
1406
1407 // Every strict prefix ends inside some field, such as a CompactSize, an output
1408 // script, a witness element or the locktime, and fails to deserialize.
1409 for (size_t len{0}; len < ser.size(); ++len) {
1410 BOOST_CHECK_EXCEPTION(DataStream{std::span{ser}.first(len)} >> TX_WITH_WITNESS(tx), std::ios_base::failure, HasReason{"end of data"});
1411 }
1412
1413 // A flag other than 1 is unknown, including one without the witness bit.
1415 bad_flag << mtx.version << uint8_t{0x00} << uint8_t{0x02} << mtx.vin << mtx.vout << mtx.vin[0].scriptWitness.stack << mtx.nLockTime;
1416 BOOST_CHECK_EXCEPTION(bad_flag >> TX_WITH_WITNESS(tx), std::ios_base::failure, HasReason{"Unknown transaction optional data"});
1417}
1418
std::vector< unsigned char > valtype
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
const std::vector< unsigned char > ANCHOR_BYTES
Witness program for Pay-to-Anchor output script type.
constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition amount.h:26
int64_t CAmount
Amount in satoshis (Can be negative)
Definition amount.h:12
constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition amount.h:15
BOOST_CHECK_LT(ZeroL, OneL)
int ret
int flags
#define Assert(val)
Identity function.
Definition check.h:119
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition chain.h:94
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
Definition checkqueue.h:210
Queue for verifications that have to be performed.
Definition checkqueue.h:34
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition coins.h:437
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition feerate.h:32
CAmount GetFeePerK() const
Return the fee in satoshis for a vsize of 1000 vbytes.
Definition feerate.h:71
An encapsulated private key.
Definition key.h:46
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition key.cpp:163
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition key.cpp:184
A reference to a CKey: the Hash160 of its serialized public key.
Definition pubkey.h:29
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition transaction.h:30
An encapsulated public key.
Definition pubkey.h:43
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition pubkey.h:169
uint256 GetHash() const
Get the 256-bit hash of this public key.
Definition pubkey.h:175
Serialized script, used inside transaction inputs and outputs.
Definition script.h:406
static opcodetype EncodeOP_N(int n)
Definition script.h:515
The basic transaction that is broadcasted on the network and contained in blocks.
const std::vector< CTxIn > vin
An input of a transaction.
Definition transaction.h:63
static constexpr uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition transaction.h:77
CScript scriptSig
Definition transaction.h:66
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition transaction.h:68
static constexpr uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65).
Definition transaction.h:83
COutPoint prevout
Definition transaction.h:65
An output of a transaction.
CScript scriptPubKey
CAmount nValue
A UTXO entry.
Definition coins.h:46
CTxOut out
unspent transaction output
Definition coins.h:49
bool fCoinBase
whether containing transaction was a coinbase
Definition coins.h:52
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition coins.h:55
static CoinsViewEmpty & Get()
Definition coins.cpp:29
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:165
Fillable signing provider that keeps keys in an address->secret map.
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition common.h:19
A signature creator for transactions.
Definition sign.h:54
Valid signature cache, to avoid doing expensive ECDSA signature checking twice for every transaction ...
Definition sigcache.h:40
Minimal stream for reading from an existing byte array by std::span.
Definition streams.h:83
const std::string & get_str() const
bool isArray() const
Definition univalue.h:87
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
size_t size() const
Definition univalue.h:71
bool isStr() const
Definition univalue.h:85
const UniValue & get_array() const
bool IsValid() const
Definition validation.h:112
std::string GetRejectReason() const
Definition validation.h:116
Result GetResult() const
Definition validation.h:115
bool IsInvalid() const
Definition validation.h:113
constexpr unsigned char * end()
Definition uint256.h:102
constexpr unsigned char * begin()
Definition uint256.h:101
size_type size() const
Definition prevector.h:247
void emplace_back(Args &&... args)
Definition prevector.h:383
void resize(size_type new_size)
Definition prevector.h:276
void push_back(const T &value)
Definition prevector.h:392
static constexpr script_verify_flags from_int(value_type f)
static transaction_identifier FromUint256(const uint256 &id)
static std::optional< transaction_identifier > FromHex(std::string_view hex)
static const uint256 ONE
Definition uint256.h:205
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
Utility function to add all of a transaction's outputs to a cache.
Definition coins.cpp:133
static int32_t GetTransactionWeight(const CTransaction &tx)
Definition validation.h:139
TxValidationResult
A "reason" why a transaction was invalid, suitable for determining whether the provider of the transa...
Definition validation.h:30
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_CONSENSUS
invalid by consensus rules
constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE
Flags for nSequence and nLockTime locks.
Definition consensus.h:28
constexpr int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
Definition consensus.h:19
constexpr unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition consensus.h:15
constexpr int WITNESS_SCALE_FACTOR
Definition consensus.h:21
CScript ParseScript(const std::string &s)
Definition core_io.cpp:92
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
BOOST_CHECK_GT(excessive_headers.size(), MAX_HEADERS_SIZE)
BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"Empty HTTP header name"})
const std::map< std::string, script_verify_flag_name > & ScriptFlagNamesToEnum()
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, script_verify_flags flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror)
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, script_verify_flags flags, const BaseSignatureChecker &checker, ScriptError *serror)
constexpr int MAX_SCRIPT_VERIFY_FLAGS_BITS
@ BASE
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
@ SIGHASH_ANYONECANPAY
Definition interpreter.h:35
@ SIGHASH_ALL
Definition interpreter.h:32
@ SIGHASH_NONE
Definition interpreter.h:33
@ SIGHASH_SINGLE
Definition interpreter.h:34
@ ASSERT_FAIL
Abort execution through assertion failure (for consensus code)
constexpr script_verify_flags SCRIPT_VERIFY_NONE
Script verification flags.
Definition interpreter.h:48
UniValue read_json(std::string_view jsondata)
Definition json.cpp:12
CKey GenerateRandomKey(bool compressed) noexcept
Definition key.cpp:354
uint64_t sequence
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, CAmount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
""_hex is a compile-time user-defined literal returning a std::array<std::byte>, equivalent to ParseH...
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition string.h:153
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition string.h:250
#define BOOST_CHECK_EQUAL(v1, v2)
Definition object.cpp:17
#define BOOST_CHECK(expr)
Definition object.cpp:16
TxValidationState ValidateInputsStandardness(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs.
Definition policy.cpp:214
bool SpendsNonAnchorWitnessProg(const CTransaction &tx, const CCoinsViewCache &prevouts)
Check whether this transaction spends any witness program but P2A, including not-yet-defined ones.
Definition policy.cpp:354
bool IsStandardTx(const CTransaction &tx, const std::optional< unsigned > &max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate &dust_relay_fee, std::string &reason)
Check for standard transaction types.
Definition policy.cpp:100
constexpr unsigned int MAX_OP_RETURN_RELAY
Default setting for -datacarriersize in vbytes.
Definition policy.h:84
constexpr unsigned int MAX_TX_LEGACY_SIGOPS
The maximum number of potentially executed legacy signature operations in a single standard tx.
Definition policy.h:46
constexpr script_verify_flags STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition policy.h:112
constexpr decltype(CTransaction::version) TX_MAX_STANDARD_VERSION
Definition policy.h:146
constexpr bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
Definition policy.h:52
constexpr unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
Definition policy.h:68
constexpr unsigned int MAX_DUST_OUTPUTS_PER_TX
Maximum number of ephemeral dust outputs allowed.
Definition policy.h:89
constexpr unsigned int MAX_P2SH_SIGOPS
Maximum number of signature check operations in an IsStandard() P2SH script.
Definition policy.h:42
constexpr TransactionSerParams TX_NO_WITNESS
constexpr TransactionSerParams TX_WITH_WITNESS
std::shared_ptr< const CTransaction > CTransactionRef
const char * name
Definition rest.cpp:71
opcodetype
Script opcodes.
Definition script.h:75
@ OP_PUSHDATA4
Definition script.h:81
@ OP_CHECKMULTISIG
Definition script.h:193
@ OP_IF
Definition script.h:105
@ OP_ROT
Definition script.h:131
@ OP_1NEGATE
Definition script.h:82
@ OP_CHECKSIG
Definition script.h:191
@ OP_CHECKLOCKTIMEVERIFY
Definition script.h:198
@ OP_16
Definition script.h:100
@ OP_NOT
Definition script.h:159
@ OP_EQUAL
Definition script.h:147
@ OP_SIZE
Definition script.h:140
@ OP_3DUP
Definition script.h:119
@ OP_DUP
Definition script.h:126
@ OP_NOP
Definition script.h:103
@ OP_CODESEPARATOR
Definition script.h:190
@ OP_HASH256
Definition script.h:189
@ OP_SUB
Definition script.h:163
@ OP_HASH160
Definition script.h:188
@ OP_2DUP
Definition script.h:118
@ OP_1
Definition script.h:84
@ OP_TRUE
Definition script.h:85
@ OP_VERIFY
Definition script.h:111
@ OP_12
Definition script.h:96
@ OP_ADD
Definition script.h:162
@ OP_DROP
Definition script.h:125
@ OP_9
Definition script.h:93
@ OP_0
Definition script.h:77
@ OP_RETURN
Definition script.h:112
@ OP_EQUALVERIFY
Definition script.h:148
@ OP_RESERVED
Definition script.h:83
constexpr int MAX_PUBKEYS_PER_MULTISIG
Definition script.h:35
std::vector< unsigned char > ToByteVector(const T &in)
Definition script.h:68
std::string ScriptErrorString(const ScriptError serror)
enum ScriptError_t ScriptError
@ SCRIPT_ERR_UNKNOWN_ERROR
@ SCRIPT_ERR_OK
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
constexpr deserialize_type deserialize
Definition serialize.h:52
uint64_t GetSerializeSize(const T &t)
Definition serialize.h:1157
constexpr CAmount CENT
constexpr size_t DEFAULT_SIGNATURE_CACHE_BYTES
Definition sigcache.h:30
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition sign.cpp:750
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition sign.cpp:923
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition sign.cpp:858
const SigningProvider & DUMMY_SIGNING_PROVIDER
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition solver.cpp:141
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition solver.cpp:218
@ WITNESS_V1_TAPROOT
@ WITNESS_UNKNOWN
Only for Witness versions not already defined above.
@ ANCHOR
anyone can spend script
@ WITNESS_V0_SCRIPTHASH
@ WITNESS_V0_KEYHASH
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Basic testing setup.
A mutable version of CTransaction.
bool HasWitness() const
std::vector< CTxOut > vout
std::vector< CTxIn > vin
void MergeSignatureData(SignatureData sigdata)
Definition sign.cpp:929
CTxDestination subtype to encode any future Witness version.
Definition addresstype.h:95
bool IsValidFlagCombination(script_verify_flags flags)
Flags that are not forbidden by an assert in script validation.
Definition script.cpp:8
SignatureData CombineSignatures(const CMutableTransaction &input1, const CMutableTransaction &input2, const CTransactionRef tx)
std::set< script_verify_flags > ExcludeIndividualFlags(script_verify_flags flags)
script_verify_flags FillFlags(script_verify_flags flags)
bool CheckTxScripts(const CTransaction &tx, const std::map< COutPoint, CScript > &map_prevout_scriptPubKeys, const std::map< COutPoint, int64_t > &map_prevout_values, script_verify_flags flags, const PrecomputedTransactionData &txdata, const std::string &strTest, bool expect_valid)
static bool g_bare_multi
static const std::map< std::string, script_verify_flag_name > & mapFlagNames
script_verify_flags TrimFlags(script_verify_flags flags)
std::vector< unsigned char > valtype
BOOST_AUTO_TEST_CASE(tx_valid)
script_verify_flags ParseScriptFlags(std::string strFlags)
static void ReplaceRedeemScript(CScript &script, const CScript &redeemScript)
bool CheckMapFlagNames()
static void CreateCreditAndSpend(const FillableSigningProvider &keystore, const CScript &outscript, CTransactionRef &output, CMutableTransaction &input, bool success=true)
static CScript PushAll(const std::vector< valtype > &values)
static CFeeRate g_dust
static void CheckWithFlag(const CTransactionRef &output, const CMutableTransaction &input, script_verify_flags flags, bool success)
std::vector< CMutableTransaction > SetupDummyInputs(FillableSigningProvider &keystoreRet, CCoinsViewCache &coinsRet, const std::array< CAmount, 4 > &nValues)
bool SignSignature(const SigningProvider &provider, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, const CAmount &amount, int nHashType, SignatureData &sig_data)
Produce a satisfying script (scriptSig or witness).
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
Definition tx_check.cpp:19
std::pair< int, int64_t > CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
Calculates the block height and previous block's median time past at which the transaction will be co...
Definition tx_verify.cpp:45
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
Definition tx_verify.cpp:23
constexpr std::array tests
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
assert(!tx.IsCoinBase())