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