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