Bitcoin Core 30.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>
13#include <consensus/tx_verify.h>
15#include <core_io.h>
16#include <key.h>
17#include <policy/policy.h>
18#include <policy/settings.h>
20#include <script/interpreter.h>
21#include <script/script.h>
22#include <script/script_error.h>
23#include <script/sigcache.h>
24#include <script/sign.h>
26#include <script/solver.h>
27#include <streams.h>
28#include <test/util/json.h>
29#include <test/util/random.h>
30#include <test/util/script.h>
32#include <util/strencodings.h>
33#include <util/string.h>
34#include <validation.h>
35
36#include <functional>
37#include <map>
38#include <string>
39
40#include <boost/test/unit_test.hpp>
41
42#include <univalue.h>
43
44using namespace util::hex_literals;
46using util::ToString;
47
48typedef std::vector<unsigned char> valtype;
49
52
53static const std::map<std::string, script_verify_flag_name>& mapFlagNames = g_verify_flag_names;
54
56{
58 if (strFlags.empty() || strFlags == "NONE") return flags;
59
60 std::vector<std::string> words = SplitString(strFlags, ',');
61 for (const std::string& word : words)
62 {
63 if (!mapFlagNames.count(word)) {
64 BOOST_ERROR("Bad test: unknown verification flag '" << word << "'");
65 continue;
66 }
67 flags |= mapFlagNames.at(word);
68 }
69 return flags;
70}
71
72// Check that all flags in STANDARD_SCRIPT_VERIFY_FLAGS are present in mapFlagNames.
74{
76 for (const auto& pair : mapFlagNames) {
77 standard_flags_missing &= ~(pair.second);
78 }
79 return standard_flags_missing == 0;
80}
81
82/*
83* Check that the input scripts of a transaction are valid/invalid as expected.
84*/
85bool CheckTxScripts(const CTransaction& tx, const std::map<COutPoint, CScript>& map_prevout_scriptPubKeys,
86 const std::map<COutPoint, int64_t>& map_prevout_values, script_verify_flags flags,
87 const PrecomputedTransactionData& txdata, const std::string& strTest, bool expect_valid)
88{
89 bool tx_valid = true;
91 for (unsigned int i = 0; i < tx.vin.size() && tx_valid; ++i) {
92 const CTxIn input = tx.vin[i];
93 const CAmount amount = map_prevout_values.count(input.prevout) ? map_prevout_values.at(input.prevout) : 0;
94 try {
95 tx_valid = VerifyScript(input.scriptSig, map_prevout_scriptPubKeys.at(input.prevout),
97 } catch (...) {
98 BOOST_ERROR("Bad test: " << strTest);
99 return true; // The test format is bad and an error is thrown. Return true to silence further error.
100 }
101 if (expect_valid) {
102 BOOST_CHECK_MESSAGE(tx_valid, strTest);
103 BOOST_CHECK_MESSAGE((err == SCRIPT_ERR_OK), ScriptErrorString(err));
105 }
106 }
107 if (!expect_valid) {
108 BOOST_CHECK_MESSAGE(!tx_valid, strTest);
109 BOOST_CHECK_MESSAGE((err != SCRIPT_ERR_OK), ScriptErrorString(err));
110 }
111 return (tx_valid == expect_valid);
112}
113
114/*
115 * Trim or fill flags to make the combination valid:
116 * WITNESS must be used with P2SH
117 * CLEANSTACK must be used WITNESS and P2SH
118 */
119
121{
122 // WITNESS requires P2SH
123 if (!(flags & SCRIPT_VERIFY_P2SH)) flags &= ~SCRIPT_VERIFY_WITNESS;
124
125 // CLEANSTACK requires WITNESS (and transitively CLEANSTACK requires P2SH)
126 if (!(flags & SCRIPT_VERIFY_WITNESS)) flags &= ~SCRIPT_VERIFY_CLEANSTACK;
128 return flags;
129}
130
132{
133 // CLEANSTACK implies WITNESS
135
136 // WITNESS implies P2SH (and transitively CLEANSTACK implies P2SH)
139 return flags;
140}
141
142// Exclude each possible script verify flag from flags. Returns a set of these flag combinations
143// that are valid and without duplicates. For example: if flags=1111 and the 4 possible flags are
144// 0001, 0010, 0100, and 1000, this should return the set {0111, 1011, 1101, 1110}.
145// Assumes that mapFlagNames contains all script verify flags.
147{
148 std::set<script_verify_flags> flags_combos;
149 for (const auto& pair : mapFlagNames) {
150 script_verify_flags flags_excluding_one = TrimFlags(flags & ~(pair.second));
151 if (flags != flags_excluding_one) {
152 flags_combos.insert(flags_excluding_one);
153 }
154 }
155 return flags_combos;
156}
157
159
161{
162 BOOST_CHECK_MESSAGE(CheckMapFlagNames(), "mapFlagNames is missing a script verification flag");
163 // Read tests from test/data/tx_valid.json
164 UniValue tests = read_json(json_tests::tx_valid);
165
166 for (unsigned int idx = 0; idx < tests.size(); idx++) {
167 const UniValue& test = tests[idx];
168 std::string strTest = test.write();
169 if (test[0].isArray())
170 {
171 if (test.size() != 3 || !test[1].isStr() || !test[2].isStr())
172 {
173 BOOST_ERROR("Bad test: " << strTest);
174 continue;
175 }
176
177 std::map<COutPoint, CScript> mapprevOutScriptPubKeys;
178 std::map<COutPoint, int64_t> mapprevOutValues;
179 UniValue inputs = test[0].get_array();
180 bool fValid = true;
181 for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) {
182 const UniValue& input = inputs[inpIdx];
183 if (!input.isArray()) {
184 fValid = false;
185 break;
186 }
187 const UniValue& vinput = input.get_array();
188 if (vinput.size() < 3 || vinput.size() > 4)
189 {
190 fValid = false;
191 break;
192 }
193 COutPoint outpoint{Txid::FromHex(vinput[0].get_str()).value(), uint32_t(vinput[1].getInt<int>())};
194 mapprevOutScriptPubKeys[outpoint] = ParseScript(vinput[2].get_str());
195 if (vinput.size() >= 4)
196 {
197 mapprevOutValues[outpoint] = vinput[3].getInt<int64_t>();
198 }
199 }
200 if (!fValid)
201 {
202 BOOST_ERROR("Bad test: " << strTest);
203 continue;
204 }
205
206 std::string transaction = test[1].get_str();
207 DataStream stream(ParseHex(transaction));
209
210 TxValidationState state;
211 BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest);
212 BOOST_CHECK(state.IsValid());
213
215 script_verify_flags verify_flags = ParseScriptFlags(test[2].get_str());
216
217 // Check that the test gives a valid combination of flags (otherwise VerifyScript will throw). Don't edit the flags.
218 if (~verify_flags != FillFlags(~verify_flags)) {
219 BOOST_ERROR("Bad test flags: " << strTest);
220 }
221
222 BOOST_CHECK_MESSAGE(CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, ~verify_flags, txdata, strTest, /*expect_valid=*/true),
223 "Tx unexpectedly failed: " << strTest);
224
225 // Backwards compatibility of script verification flags: Removing any flag(s) should not invalidate a valid transaction
226 for (const auto& [name, flag] : mapFlagNames) {
227 // Removing individual flags
228 script_verify_flags flags = TrimFlags(~(verify_flags | flag));
229 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/true)) {
230 BOOST_ERROR("Tx unexpectedly failed with flag " << name << " unset: " << strTest);
231 }
232 // Removing random combinations of flags
234 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/true)) {
235 BOOST_ERROR("Tx unexpectedly failed with random flags " << ToString(flags.as_int()) << ": " << strTest);
236 }
237 }
238
239 // Check that flags are maximal: transaction should fail if any unset flags are set.
240 for (auto flags_excluding_one : ExcludeIndividualFlags(verify_flags)) {
241 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, ~flags_excluding_one, txdata, strTest, /*expect_valid=*/false)) {
242 BOOST_ERROR("Too many flags unset: " << strTest);
243 }
244 }
245 }
246 }
247}
248
250{
251 // Read tests from test/data/tx_invalid.json
252 UniValue tests = read_json(json_tests::tx_invalid);
253
254 for (unsigned int idx = 0; idx < tests.size(); idx++) {
255 const UniValue& test = tests[idx];
256 std::string strTest = test.write();
257 if (test[0].isArray())
258 {
259 if (test.size() != 3 || !test[1].isStr() || !test[2].isStr())
260 {
261 BOOST_ERROR("Bad test: " << strTest);
262 continue;
263 }
264
265 std::map<COutPoint, CScript> mapprevOutScriptPubKeys;
266 std::map<COutPoint, int64_t> mapprevOutValues;
267 UniValue inputs = test[0].get_array();
268 bool fValid = true;
269 for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) {
270 const UniValue& input = inputs[inpIdx];
271 if (!input.isArray()) {
272 fValid = false;
273 break;
274 }
275 const UniValue& vinput = input.get_array();
276 if (vinput.size() < 3 || vinput.size() > 4)
277 {
278 fValid = false;
279 break;
280 }
281 COutPoint outpoint{Txid::FromHex(vinput[0].get_str()).value(), uint32_t(vinput[1].getInt<int>())};
282 mapprevOutScriptPubKeys[outpoint] = ParseScript(vinput[2].get_str());
283 if (vinput.size() >= 4)
284 {
285 mapprevOutValues[outpoint] = vinput[3].getInt<int64_t>();
286 }
287 }
288 if (!fValid)
289 {
290 BOOST_ERROR("Bad test: " << strTest);
291 continue;
292 }
293
294 std::string transaction = test[1].get_str();
295 DataStream stream(ParseHex(transaction));
297
298 TxValidationState state;
299 if (!CheckTransaction(tx, state) || state.IsInvalid()) {
300 BOOST_CHECK_MESSAGE(test[2].get_str() == "BADTX", strTest);
301 continue;
302 }
303
305 script_verify_flags verify_flags = ParseScriptFlags(test[2].get_str());
306
307 // Check that the test gives a valid combination of flags (otherwise VerifyScript will throw). Don't edit the flags.
308 if (verify_flags != FillFlags(verify_flags)) {
309 BOOST_ERROR("Bad test flags: " << strTest);
310 }
311
312 // Not using FillFlags() in the main test, in order to detect invalid verifyFlags combination
313 BOOST_CHECK_MESSAGE(CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, verify_flags, txdata, strTest, /*expect_valid=*/false),
314 "Tx unexpectedly passed: " << strTest);
315
316 // Backwards compatibility of script verification flags: Adding any flag(s) should not validate an invalid transaction
317 for (const auto& [name, flag] : mapFlagNames) {
318 script_verify_flags flags = FillFlags(verify_flags | flag);
319 // Adding individual flags
320 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/false)) {
321 BOOST_ERROR("Tx unexpectedly passed with flag " << name << " set: " << strTest);
322 }
323 // Adding random combinations of flags
325 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /*expect_valid=*/false)) {
326 BOOST_ERROR("Tx unexpectedly passed with random flags " << name << ": " << strTest);
327 }
328 }
329
330 // Check that flags are minimal: transaction should succeed if any set flags are unset.
331 for (auto flags_excluding_one : ExcludeIndividualFlags(verify_flags)) {
332 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags_excluding_one, txdata, strTest, /*expect_valid=*/true)) {
333 BOOST_ERROR("Too many flags set: " << strTest);
334 }
335 }
336 }
337 }
338}
339
341{
343
344 TxValidationState state;
345 BOOST_CHECK_MESSAGE(!CheckTransaction(CTransaction(empty), state), "Transaction with no inputs should be invalid.");
346 BOOST_CHECK(state.GetRejectReason() == "bad-txns-vin-empty");
347}
348
350{
351 auto createTransaction =[](size_t payloadSize) {
353 tx.vin.resize(1);
354 tx.vout.emplace_back(1, CScript() << OP_RETURN << std::vector<unsigned char>(payloadSize));
355 return CTransaction(tx);
356 };
357 const auto maxTransactionSize = MAX_BLOCK_WEIGHT / WITNESS_SCALE_FACTOR;
358 const auto oversizedTransactionBaseSize = ::GetSerializeSize(TX_NO_WITNESS(createTransaction(maxTransactionSize))) - maxTransactionSize;
359
360 auto maxPayloadSize = maxTransactionSize - oversizedTransactionBaseSize;
361 {
362 TxValidationState state;
363 CheckTransaction(createTransaction(maxPayloadSize), state);
364 BOOST_CHECK(state.GetRejectReason() != "bad-txns-oversize");
365 }
366
367 maxPayloadSize += 1;
368 {
369 TxValidationState state;
370 BOOST_CHECK_MESSAGE(!CheckTransaction(createTransaction(maxPayloadSize), state), "Oversized transaction should be invalid");
371 BOOST_CHECK(state.GetRejectReason() == "bad-txns-oversize");
372 }
373}
374
375BOOST_AUTO_TEST_CASE(basic_transaction_tests)
376{
377 // Random real transaction (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436)
378 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};
379 std::vector<unsigned char> vch(ch, ch + sizeof(ch) -1);
380 DataStream stream(vch);
382 stream >> TX_WITH_WITNESS(tx);
383 TxValidationState state;
384 BOOST_CHECK_MESSAGE(CheckTransaction(CTransaction(tx), state) && state.IsValid(), "Simple deserialized transaction should be valid.");
385
386 // Check that duplicate txins fail
387 tx.vin.push_back(tx.vin[0]);
388 BOOST_CHECK_MESSAGE(!CheckTransaction(CTransaction(tx), state) || !state.IsValid(), "Transaction with duplicate txins should be invalid.");
389}
390
392{
394 CCoinsView coinsDummy;
395 CCoinsViewCache coins(&coinsDummy);
396 std::vector<CMutableTransaction> dummyTransactions =
397 SetupDummyInputs(keystore, coins, {11*CENT, 50*CENT, 21*CENT, 22*CENT});
398
400 t1.vin.resize(3);
401 t1.vin[0].prevout.hash = dummyTransactions[0].GetHash();
402 t1.vin[0].prevout.n = 1;
403 t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0);
404 t1.vin[1].prevout.hash = dummyTransactions[1].GetHash();
405 t1.vin[1].prevout.n = 0;
406 t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
407 t1.vin[2].prevout.hash = dummyTransactions[1].GetHash();
408 t1.vin[2].prevout.n = 1;
409 t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
410 t1.vout.resize(2);
411 t1.vout[0].nValue = 90*CENT;
412 t1.vout[0].scriptPubKey << OP_1;
413
415}
416
417static void CreateCreditAndSpend(const FillableSigningProvider& keystore, const CScript& outscript, CTransactionRef& output, CMutableTransaction& input, bool success = true)
418{
419 CMutableTransaction outputm;
420 outputm.version = 1;
421 outputm.vin.resize(1);
422 outputm.vin[0].prevout.SetNull();
423 outputm.vin[0].scriptSig = CScript();
424 outputm.vout.resize(1);
425 outputm.vout[0].nValue = 1;
426 outputm.vout[0].scriptPubKey = outscript;
427 DataStream ssout;
428 ssout << TX_WITH_WITNESS(outputm);
429 ssout >> TX_WITH_WITNESS(output);
430 assert(output->vin.size() == 1);
431 assert(output->vin[0] == outputm.vin[0]);
432 assert(output->vout.size() == 1);
433 assert(output->vout[0] == outputm.vout[0]);
434
435 CMutableTransaction inputm;
436 inputm.version = 1;
437 inputm.vin.resize(1);
438 inputm.vin[0].prevout.hash = output->GetHash();
439 inputm.vin[0].prevout.n = 0;
440 inputm.vout.resize(1);
441 inputm.vout[0].nValue = 1;
442 inputm.vout[0].scriptPubKey = CScript();
443 SignatureData empty;
444 bool ret = SignSignature(keystore, *output, inputm, 0, SIGHASH_ALL, empty);
445 assert(ret == success);
446 DataStream ssin;
447 ssin << TX_WITH_WITNESS(inputm);
448 ssin >> TX_WITH_WITNESS(input);
449 assert(input.vin.size() == 1);
450 assert(input.vin[0] == inputm.vin[0]);
451 assert(input.vout.size() == 1);
452 assert(input.vout[0] == inputm.vout[0]);
453 assert(input.vin[0].scriptWitness.stack == inputm.vin[0].scriptWitness.stack);
454}
455
456static void CheckWithFlag(const CTransactionRef& output, const CMutableTransaction& input, script_verify_flags flags, bool success)
457{
458 ScriptError error;
459 CTransaction inputi(input);
460 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);
461 assert(ret == success);
462}
463
464static CScript PushAll(const std::vector<valtype>& values)
465{
466 CScript result;
467 for (const valtype& v : values) {
468 if (v.size() == 0) {
469 result << OP_0;
470 } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
471 result << CScript::EncodeOP_N(v[0]);
472 } else if (v.size() == 1 && v[0] == 0x81) {
473 result << OP_1NEGATE;
474 } else {
475 result << v;
476 }
477 }
478 return result;
479}
480
481static void ReplaceRedeemScript(CScript& script, const CScript& redeemScript)
482{
483 std::vector<valtype> stack;
485 assert(stack.size() > 0);
486 stack.back() = std::vector<unsigned char>(redeemScript.begin(), redeemScript.end());
487 script = PushAll(stack);
488}
489
490BOOST_AUTO_TEST_CASE(test_big_witness_transaction)
491{
493 mtx.version = 1;
494
495 CKey key = GenerateRandomKey(); // Need to use compressed keys in segwit or the signing will fail
497 BOOST_CHECK(keystore.AddKeyPubKey(key, key.GetPubKey()));
498 CKeyID hash = key.GetPubKey().GetID();
499 CScript scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(hash.begin(), hash.end());
500
501 std::vector<int> sigHashes;
502 sigHashes.push_back(SIGHASH_NONE | SIGHASH_ANYONECANPAY);
503 sigHashes.push_back(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY);
504 sigHashes.push_back(SIGHASH_ALL | SIGHASH_ANYONECANPAY);
505 sigHashes.push_back(SIGHASH_NONE);
506 sigHashes.push_back(SIGHASH_SINGLE);
507 sigHashes.push_back(SIGHASH_ALL);
508
509 // create a big transaction of 4500 inputs signed by the same key
510 for(uint32_t ij = 0; ij < 4500; ij++) {
511 uint32_t i = mtx.vin.size();
512 COutPoint outpoint(Txid::FromHex("0000000000000000000000000000000000000000000000000000000000000100").value(), i);
513
514 mtx.vin.resize(mtx.vin.size() + 1);
515 mtx.vin[i].prevout = outpoint;
516 mtx.vin[i].scriptSig = CScript();
517
518 mtx.vout.resize(mtx.vout.size() + 1);
519 mtx.vout[i].nValue = 1000;
520 mtx.vout[i].scriptPubKey = CScript() << OP_1;
521 }
522
523 // sign all inputs
524 for(uint32_t i = 0; i < mtx.vin.size(); i++) {
525 SignatureData empty;
526 bool hashSigned = SignSignature(keystore, scriptPubKey, mtx, i, 1000, sigHashes.at(i % sigHashes.size()), empty);
527 assert(hashSigned);
528 }
529
530 DataStream ssout;
531 ssout << TX_WITH_WITNESS(mtx);
533
534 // check all inputs concurrently, with the cache
536 CCheckQueue<CScriptCheck> scriptcheckqueue(/*batch_size=*/128, /*worker_threads_num=*/20);
537 CCheckQueueControl<CScriptCheck> control(scriptcheckqueue);
538
539 std::vector<Coin> coins;
540 for(uint32_t i = 0; i < mtx.vin.size(); i++) {
541 Coin coin;
542 coin.nHeight = 1;
543 coin.fCoinBase = false;
544 coin.out.nValue = 1000;
545 coin.out.scriptPubKey = scriptPubKey;
546 coins.emplace_back(std::move(coin));
547 }
548
550
551 for(uint32_t i = 0; i < mtx.vin.size(); i++) {
552 std::vector<CScriptCheck> vChecks;
553 vChecks.emplace_back(coins[tx.vin[i].prevout.n].out, tx, signature_cache, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false, &txdata);
554 control.Add(std::move(vChecks));
555 }
556
557 bool controlCheck = !control.Complete().has_value();
558 assert(controlCheck);
559}
560
562{
563 SignatureData sigdata;
564 sigdata = DataFromTransaction(input1, 0, tx->vout[0]);
565 sigdata.MergeSignatureData(DataFromTransaction(input2, 0, tx->vout[0]));
566 ProduceSignature(DUMMY_SIGNING_PROVIDER, MutableTransactionSignatureCreator(input1, 0, tx->vout[0].nValue, SIGHASH_ALL), tx->vout[0].scriptPubKey, sigdata);
567 return sigdata;
568}
569
571{
572 FillableSigningProvider keystore, keystore2;
573 CKey key1 = GenerateRandomKey();
574 CKey key2 = GenerateRandomKey();
575 CKey key3 = GenerateRandomKey();
576 CKey key1L = GenerateRandomKey(/*compressed=*/false);
577 CKey key2L = GenerateRandomKey(/*compressed=*/false);
578 CPubKey pubkey1 = key1.GetPubKey();
579 CPubKey pubkey2 = key2.GetPubKey();
580 CPubKey pubkey3 = key3.GetPubKey();
581 CPubKey pubkey1L = key1L.GetPubKey();
582 CPubKey pubkey2L = key2L.GetPubKey();
583 BOOST_CHECK(keystore.AddKeyPubKey(key1, pubkey1));
584 BOOST_CHECK(keystore.AddKeyPubKey(key2, pubkey2));
585 BOOST_CHECK(keystore.AddKeyPubKey(key1L, pubkey1L));
586 BOOST_CHECK(keystore.AddKeyPubKey(key2L, pubkey2L));
587 CScript scriptPubkey1, scriptPubkey2, scriptPubkey1L, scriptPubkey2L, scriptMulti;
588 scriptPubkey1 << ToByteVector(pubkey1) << OP_CHECKSIG;
589 scriptPubkey2 << ToByteVector(pubkey2) << OP_CHECKSIG;
590 scriptPubkey1L << ToByteVector(pubkey1L) << OP_CHECKSIG;
591 scriptPubkey2L << ToByteVector(pubkey2L) << OP_CHECKSIG;
592 std::vector<CPubKey> oneandthree;
593 oneandthree.push_back(pubkey1);
594 oneandthree.push_back(pubkey3);
595 scriptMulti = GetScriptForMultisig(2, oneandthree);
596 BOOST_CHECK(keystore.AddCScript(scriptPubkey1));
597 BOOST_CHECK(keystore.AddCScript(scriptPubkey2));
598 BOOST_CHECK(keystore.AddCScript(scriptPubkey1L));
599 BOOST_CHECK(keystore.AddCScript(scriptPubkey2L));
600 BOOST_CHECK(keystore.AddCScript(scriptMulti));
601 CScript destination_script_1, destination_script_2, destination_script_1L, destination_script_2L, destination_script_multi;
602 destination_script_1 = GetScriptForDestination(WitnessV0KeyHash(pubkey1));
603 destination_script_2 = GetScriptForDestination(WitnessV0KeyHash(pubkey2));
604 destination_script_1L = GetScriptForDestination(WitnessV0KeyHash(pubkey1L));
605 destination_script_2L = GetScriptForDestination(WitnessV0KeyHash(pubkey2L));
606 destination_script_multi = GetScriptForDestination(WitnessV0ScriptHash(scriptMulti));
607 BOOST_CHECK(keystore.AddCScript(destination_script_1));
608 BOOST_CHECK(keystore.AddCScript(destination_script_2));
609 BOOST_CHECK(keystore.AddCScript(destination_script_1L));
610 BOOST_CHECK(keystore.AddCScript(destination_script_2L));
611 BOOST_CHECK(keystore.AddCScript(destination_script_multi));
612 BOOST_CHECK(keystore2.AddCScript(scriptMulti));
613 BOOST_CHECK(keystore2.AddCScript(destination_script_multi));
614 BOOST_CHECK(keystore2.AddKeyPubKey(key3, pubkey3));
615
616 CTransactionRef output1, output2;
617 CMutableTransaction input1, input2;
618
619 // Normal pay-to-compressed-pubkey.
620 CreateCreditAndSpend(keystore, scriptPubkey1, output1, input1);
621 CreateCreditAndSpend(keystore, scriptPubkey2, output2, input2);
622 CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
623 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
625 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
626 CheckWithFlag(output1, input2, SCRIPT_VERIFY_NONE, false);
627 CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, false);
628 CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false);
629 CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false);
630
631 // P2SH pay-to-compressed-pubkey.
632 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptPubkey1)), output1, input1);
633 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptPubkey2)), output2, input2);
634 ReplaceRedeemScript(input2.vin[0].scriptSig, scriptPubkey1);
635 CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
636 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
638 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
639 CheckWithFlag(output1, input2, SCRIPT_VERIFY_NONE, true);
640 CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, false);
641 CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false);
642 CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false);
643
644 // Witness pay-to-compressed-pubkey (v0).
645 CreateCreditAndSpend(keystore, destination_script_1, output1, input1);
646 CreateCreditAndSpend(keystore, destination_script_2, output2, input2);
647 CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
648 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
650 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
651 CheckWithFlag(output1, input2, SCRIPT_VERIFY_NONE, true);
652 CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, true);
653 CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false);
654 CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false);
655
656 // P2SH witness pay-to-compressed-pubkey (v0).
657 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_1)), output1, input1);
658 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_2)), output2, input2);
659 ReplaceRedeemScript(input2.vin[0].scriptSig, destination_script_1);
660 CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
661 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
663 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
664 CheckWithFlag(output1, input2, SCRIPT_VERIFY_NONE, true);
665 CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, true);
666 CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false);
667 CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false);
668
669 // Normal pay-to-uncompressed-pubkey.
670 CreateCreditAndSpend(keystore, scriptPubkey1L, output1, input1);
671 CreateCreditAndSpend(keystore, scriptPubkey2L, output2, input2);
672 CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
673 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
675 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
676 CheckWithFlag(output1, input2, SCRIPT_VERIFY_NONE, false);
677 CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, false);
678 CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false);
679 CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false);
680
681 // P2SH pay-to-uncompressed-pubkey.
682 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptPubkey1L)), output1, input1);
683 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptPubkey2L)), output2, input2);
684 ReplaceRedeemScript(input2.vin[0].scriptSig, scriptPubkey1L);
685 CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
686 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
688 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
689 CheckWithFlag(output1, input2, SCRIPT_VERIFY_NONE, true);
690 CheckWithFlag(output1, input2, SCRIPT_VERIFY_P2SH, false);
691 CheckWithFlag(output1, input2, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false);
692 CheckWithFlag(output1, input2, STANDARD_SCRIPT_VERIFY_FLAGS, false);
693
694 // Signing disabled for witness pay-to-uncompressed-pubkey (v1).
695 CreateCreditAndSpend(keystore, destination_script_1L, output1, input1, false);
696 CreateCreditAndSpend(keystore, destination_script_2L, output2, input2, false);
697
698 // Signing disabled for P2SH witness pay-to-uncompressed-pubkey (v1).
699 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_1L)), output1, input1, false);
700 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_2L)), output2, input2, false);
701
702 // Normal 2-of-2 multisig
703 CreateCreditAndSpend(keystore, scriptMulti, output1, input1, false);
704 CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, false);
705 CreateCreditAndSpend(keystore2, scriptMulti, output2, input2, false);
706 CheckWithFlag(output2, input2, SCRIPT_VERIFY_NONE, false);
707 BOOST_CHECK(*output1 == *output2);
708 UpdateInput(input1.vin[0], CombineSignatures(input1, input2, output1));
709 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
710
711 // P2SH 2-of-2 multisig
712 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(scriptMulti)), output1, input1, false);
713 CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
714 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, false);
715 CreateCreditAndSpend(keystore2, GetScriptForDestination(ScriptHash(scriptMulti)), output2, input2, false);
716 CheckWithFlag(output2, input2, SCRIPT_VERIFY_NONE, true);
717 CheckWithFlag(output2, input2, SCRIPT_VERIFY_P2SH, false);
718 BOOST_CHECK(*output1 == *output2);
719 UpdateInput(input1.vin[0], CombineSignatures(input1, input2, output1));
720 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
721 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
722
723 // Witness 2-of-2 multisig
724 CreateCreditAndSpend(keystore, destination_script_multi, output1, input1, false);
725 CheckWithFlag(output1, input1, SCRIPT_VERIFY_NONE, true);
726 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false);
727 CreateCreditAndSpend(keystore2, destination_script_multi, output2, input2, false);
728 CheckWithFlag(output2, input2, SCRIPT_VERIFY_NONE, true);
729 CheckWithFlag(output2, input2, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false);
730 BOOST_CHECK(*output1 == *output2);
731 UpdateInput(input1.vin[0], CombineSignatures(input1, input2, output1));
733 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
734
735 // P2SH witness 2-of-2 multisig
736 CreateCreditAndSpend(keystore, GetScriptForDestination(ScriptHash(destination_script_multi)), output1, input1, false);
737 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
738 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false);
739 CreateCreditAndSpend(keystore2, GetScriptForDestination(ScriptHash(destination_script_multi)), output2, input2, false);
740 CheckWithFlag(output2, input2, SCRIPT_VERIFY_P2SH, true);
741 CheckWithFlag(output2, input2, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false);
742 BOOST_CHECK(*output1 == *output2);
743 UpdateInput(input1.vin[0], CombineSignatures(input1, input2, output1));
745 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
746}
747
748BOOST_AUTO_TEST_CASE(test_IsStandard)
749{
751 CCoinsView coinsDummy;
752 CCoinsViewCache coins(&coinsDummy);
753 std::vector<CMutableTransaction> dummyTransactions =
754 SetupDummyInputs(keystore, coins, {11*CENT, 50*CENT, 21*CENT, 22*CENT});
755
757 t.vin.resize(1);
758 t.vin[0].prevout.hash = dummyTransactions[0].GetHash();
759 t.vin[0].prevout.n = 1;
760 t.vin[0].scriptSig << std::vector<unsigned char>(65, 0);
761 t.vout.resize(1);
762 t.vout[0].nValue = 90*CENT;
763 CKey key = GenerateRandomKey();
764 t.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey()));
765
766 constexpr auto CheckIsStandard = [](const auto& t, const unsigned int max_op_return_relay = MAX_OP_RETURN_RELAY) {
767 std::string reason;
768 BOOST_CHECK(IsStandardTx(CTransaction{t}, max_op_return_relay, g_bare_multi, g_dust, reason));
769 BOOST_CHECK(reason.empty());
770 };
771 constexpr auto CheckIsNotStandard = [](const auto& t, const std::string& reason_in, const unsigned int max_op_return_relay = MAX_OP_RETURN_RELAY) {
772 std::string reason;
773 BOOST_CHECK(!IsStandardTx(CTransaction{t}, max_op_return_relay, g_bare_multi, g_dust, reason));
774 BOOST_CHECK_EQUAL(reason_in, reason);
775 };
776
777 CheckIsStandard(t);
778
779 // Check dust with default relay fee:
780 CAmount nDustThreshold = 182 * g_dust.GetFeePerK() / 1000;
781 BOOST_CHECK_EQUAL(nDustThreshold, 546);
782
783 // Add dust outputs up to allowed maximum, still standard!
784 for (size_t i{0}; i < MAX_DUST_OUTPUTS_PER_TX; ++i) {
785 t.vout.emplace_back(0, t.vout[0].scriptPubKey);
786 CheckIsStandard(t);
787 }
788
789 // dust:
790 t.vout[0].nValue = nDustThreshold - 1;
791 CheckIsNotStandard(t, "dust");
792 // not dust:
793 t.vout[0].nValue = nDustThreshold;
794 CheckIsStandard(t);
795
796 // Disallowed version
797 t.version = std::numeric_limits<uint32_t>::max();
798 CheckIsNotStandard(t, "version");
799
800 t.version = 0;
801 CheckIsNotStandard(t, "version");
802
803 t.version = TX_MAX_STANDARD_VERSION + 1;
804 CheckIsNotStandard(t, "version");
805
806 // Allowed version
807 t.version = 1;
808 CheckIsStandard(t);
809
810 t.version = 2;
811 CheckIsStandard(t);
812
813 // Check dust with odd relay fee to verify rounding:
814 // nDustThreshold = 182 * 3702 / 1000
815 g_dust = CFeeRate(3702);
816 // dust:
817 t.vout[0].nValue = 674 - 1;
818 CheckIsNotStandard(t, "dust");
819 // not dust:
820 t.vout[0].nValue = 674;
821 CheckIsStandard(t);
823
824 t.vout[0].scriptPubKey = CScript() << OP_1;
825 CheckIsNotStandard(t, "scriptpubkey");
826
827 // Custom 83-byte TxoutType::NULL_DATA (standard with max_op_return_relay of 83)
828 t.vout[0].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
829 BOOST_CHECK_EQUAL(83, t.vout[0].scriptPubKey.size());
830 CheckIsStandard(t, /*max_op_return_relay=*/83);
831
832 // Non-standard if max_op_return_relay datacarrier arg is one less
833 CheckIsNotStandard(t, "datacarrier", /*max_op_return_relay=*/82);
834
835 // Data payload can be encoded in any way...
836 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ""_hex;
837 CheckIsStandard(t);
838 t.vout[0].scriptPubKey = CScript() << OP_RETURN << "00"_hex << "01"_hex;
839 CheckIsStandard(t);
840 // OP_RESERVED *is* considered to be a PUSHDATA type opcode by IsPushOnly()!
841 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;
842 CheckIsStandard(t);
843 t.vout[0].scriptPubKey = CScript() << OP_RETURN << 0 << "01"_hex << 2 << "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"_hex;
844 CheckIsStandard(t);
845
846 // ...so long as it only contains PUSHDATA's
847 t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RETURN;
848 CheckIsNotStandard(t, "scriptpubkey");
849
850 // TxoutType::NULL_DATA w/o PUSHDATA
851 t.vout.resize(1);
852 t.vout[0].scriptPubKey = CScript() << OP_RETURN;
853 CheckIsStandard(t);
854
855 // Multiple TxoutType::NULL_DATA are permitted
856 t.vout.resize(2);
857 t.vout[0].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
858 t.vout[0].nValue = 0;
859 t.vout[1].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
860 t.vout[1].nValue = 0;
861 CheckIsStandard(t);
862
863 t.vout[0].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
864 t.vout[1].scriptPubKey = CScript() << OP_RETURN;
865 CheckIsStandard(t);
866
867 t.vout[0].scriptPubKey = CScript() << OP_RETURN;
868 t.vout[1].scriptPubKey = CScript() << OP_RETURN;
869 CheckIsStandard(t);
870
871 t.vout[0].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
872 t.vout[1].scriptPubKey = CScript() << OP_RETURN << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"_hex;
873 const auto datacarrier_size = t.vout[0].scriptPubKey.size() + t.vout[1].scriptPubKey.size();
874 CheckIsStandard(t); // Default max relay should never trigger
875 CheckIsStandard(t, /*max_op_return_relay=*/datacarrier_size);
876 CheckIsNotStandard(t, "datacarrier", /*max_op_return_relay=*/datacarrier_size-1);
877
878 // Check large scriptSig (non-standard if size is >1650 bytes)
879 t.vout.resize(1);
880 t.vout[0].nValue = MAX_MONEY;
881 t.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey()));
882 // OP_PUSHDATA2 with len (3 bytes) + data (1647 bytes) = 1650 bytes
883 t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(1647, 0); // 1650
884 CheckIsStandard(t);
885
886 t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(1648, 0); // 1651
887 CheckIsNotStandard(t, "scriptsig-size");
888
889 // Check scriptSig format (non-standard if there are any other ops than just PUSHs)
890 t.vin[0].scriptSig = CScript()
891 << OP_TRUE << OP_0 << OP_1NEGATE << OP_16 // OP_n (single byte pushes: n = 1, 0, -1, 16)
892 << std::vector<unsigned char>(75, 0) // OP_PUSHx [...x bytes...]
893 << std::vector<unsigned char>(235, 0) // OP_PUSHDATA1 x [...x bytes...]
894 << std::vector<unsigned char>(1234, 0) // OP_PUSHDATA2 x [...x bytes...]
895 << OP_9;
896 CheckIsStandard(t);
897
898 const std::vector<unsigned char> non_push_ops = { // arbitrary set of non-push operations
901
902 CScript::const_iterator pc = t.vin[0].scriptSig.begin();
903 while (pc < t.vin[0].scriptSig.end()) {
904 opcodetype opcode;
905 CScript::const_iterator prev_pc = pc;
906 t.vin[0].scriptSig.GetOp(pc, opcode); // advance to next op
907 // for the sake of simplicity, we only replace single-byte push operations
908 if (opcode >= 1 && opcode <= OP_PUSHDATA4)
909 continue;
910
911 int index = prev_pc - t.vin[0].scriptSig.begin();
912 unsigned char orig_op = *prev_pc; // save op
913 // replace current push-op with each non-push-op
914 for (auto op : non_push_ops) {
915 t.vin[0].scriptSig[index] = op;
916 CheckIsNotStandard(t, "scriptsig-not-pushonly");
917 }
918 t.vin[0].scriptSig[index] = orig_op; // restore op
919 CheckIsStandard(t);
920 }
921
922 // Check tx-size (non-standard if transaction weight is > MAX_STANDARD_TX_WEIGHT)
923 t.vin.clear();
924 t.vin.resize(2438); // size per input (empty scriptSig): 41 bytes
925 t.vout[0].scriptPubKey = CScript() << OP_RETURN << std::vector<unsigned char>(19, 0); // output size: 30 bytes
926 // tx header: 12 bytes => 48 weight units
927 // 2438 inputs: 2438*41 = 99958 bytes => 399832 weight units
928 // 1 output: 30 bytes => 120 weight units
929 // ======================================
930 // total: 400000 weight units
932 CheckIsStandard(t);
933
934 // increase output size by one byte, so we end up with 400004 weight units
935 t.vout[0].scriptPubKey = CScript() << OP_RETURN << std::vector<unsigned char>(20, 0); // output size: 31 bytes
937 CheckIsNotStandard(t, "tx-size");
938
939 // Check bare multisig (standard if policy flag g_bare_multi is set)
940 g_bare_multi = true;
941 t.vout[0].scriptPubKey = GetScriptForMultisig(1, {key.GetPubKey()}); // simple 1-of-1
942 t.vin.resize(1);
943 t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(65, 0);
944 CheckIsStandard(t);
945
946 g_bare_multi = false;
947 CheckIsNotStandard(t, "bare-multisig");
949
950 // Add dust outputs up to allowed maximum
951 assert(t.vout.size() == 1);
952 t.vout.insert(t.vout.end(), MAX_DUST_OUTPUTS_PER_TX, {0, t.vout[0].scriptPubKey});
953
954 // Check compressed P2PK outputs dust threshold (must have leading 02 or 03)
955 t.vout[0].scriptPubKey = CScript() << std::vector<unsigned char>(33, 0x02) << OP_CHECKSIG;
956 t.vout[0].nValue = 576;
957 CheckIsStandard(t);
958 t.vout[0].nValue = 575;
959 CheckIsNotStandard(t, "dust");
960
961 // Check uncompressed P2PK outputs dust threshold (must have leading 04/06/07)
962 t.vout[0].scriptPubKey = CScript() << std::vector<unsigned char>(65, 0x04) << OP_CHECKSIG;
963 t.vout[0].nValue = 672;
964 CheckIsStandard(t);
965 t.vout[0].nValue = 671;
966 CheckIsNotStandard(t, "dust");
967
968 // Check P2PKH outputs dust threshold
969 t.vout[0].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << std::vector<unsigned char>(20, 0) << OP_EQUALVERIFY << OP_CHECKSIG;
970 t.vout[0].nValue = 546;
971 CheckIsStandard(t);
972 t.vout[0].nValue = 545;
973 CheckIsNotStandard(t, "dust");
974
975 // Check P2SH outputs dust threshold
976 t.vout[0].scriptPubKey = CScript() << OP_HASH160 << std::vector<unsigned char>(20, 0) << OP_EQUAL;
977 t.vout[0].nValue = 540;
978 CheckIsStandard(t);
979 t.vout[0].nValue = 539;
980 CheckIsNotStandard(t, "dust");
981
982 // Check P2WPKH outputs dust threshold
983 t.vout[0].scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(20, 0);
984 t.vout[0].nValue = 294;
985 CheckIsStandard(t);
986 t.vout[0].nValue = 293;
987 CheckIsNotStandard(t, "dust");
988
989 // Check P2WSH outputs dust threshold
990 t.vout[0].scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(32, 0);
991 t.vout[0].nValue = 330;
992 CheckIsStandard(t);
993 t.vout[0].nValue = 329;
994 CheckIsNotStandard(t, "dust");
995
996 // Check P2TR outputs dust threshold (Invalid xonly key ok!)
997 t.vout[0].scriptPubKey = CScript() << OP_1 << std::vector<unsigned char>(32, 0);
998 t.vout[0].nValue = 330;
999 CheckIsStandard(t);
1000 t.vout[0].nValue = 329;
1001 CheckIsNotStandard(t, "dust");
1002
1003 // Check future Witness Program versions dust threshold (non-32-byte pushes are undefined for version 1)
1004 for (int op = OP_1; op <= OP_16; op += 1) {
1005 t.vout[0].scriptPubKey = CScript() << (opcodetype)op << std::vector<unsigned char>(2, 0);
1006 t.vout[0].nValue = 240;
1007 CheckIsStandard(t);
1008
1009 t.vout[0].nValue = 239;
1010 CheckIsNotStandard(t, "dust");
1011 }
1012
1013 // Check anchor outputs
1014 t.vout[0].scriptPubKey = CScript() << OP_1 << ANCHOR_BYTES;
1015 BOOST_CHECK(t.vout[0].scriptPubKey.IsPayToAnchor());
1016 t.vout[0].nValue = 240;
1017 CheckIsStandard(t);
1018 t.vout[0].nValue = 239;
1019 CheckIsNotStandard(t, "dust");
1020}
1021
1022BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops)
1023{
1024 CCoinsView coins_dummy;
1025 CCoinsViewCache coins(&coins_dummy);
1026 CKey key;
1027 key.MakeNewKey(true);
1028
1029 // Create a pathological P2SH script padded with as many sigops as is standard.
1030 CScript max_sigops_redeem_script{CScript() << std::vector<unsigned char>{} << key.GetPubKey()};
1031 for (unsigned i{0}; i < MAX_P2SH_SIGOPS - 1; ++i) max_sigops_redeem_script << OP_2DUP << OP_CHECKSIG << OP_DROP;
1032 max_sigops_redeem_script << OP_CHECKSIG << OP_NOT;
1033 const CScript max_sigops_p2sh{GetScriptForDestination(ScriptHash(max_sigops_redeem_script))};
1034
1035 // Create a transaction fanning out as many such P2SH outputs as is standard to spend in a
1036 // single transaction, and a transaction spending them.
1037 CMutableTransaction tx_create, tx_max_sigops;
1038 const unsigned p2sh_inputs_count{MAX_TX_LEGACY_SIGOPS / MAX_P2SH_SIGOPS};
1039 tx_create.vout.reserve(p2sh_inputs_count);
1040 for (unsigned i{0}; i < p2sh_inputs_count; ++i) {
1041 tx_create.vout.emplace_back(424242 + i, max_sigops_p2sh);
1042 }
1043 auto prev_txid{tx_create.GetHash()};
1044 tx_max_sigops.vin.reserve(p2sh_inputs_count);
1045 for (unsigned i{0}; i < p2sh_inputs_count; ++i) {
1046 tx_max_sigops.vin.emplace_back(prev_txid, i, CScript() << ToByteVector(max_sigops_redeem_script));
1047 }
1048
1049 // p2sh_inputs_count is truncated to 166 (from 166.6666..)
1050 BOOST_CHECK_LT(p2sh_inputs_count * MAX_P2SH_SIGOPS, MAX_TX_LEGACY_SIGOPS);
1051 AddCoins(coins, CTransaction(tx_create), 0, false);
1052
1053 // 2490 sigops is below the limit.
1054 BOOST_CHECK_EQUAL(GetP2SHSigOpCount(CTransaction(tx_max_sigops), coins), 2490);
1055 BOOST_CHECK(::AreInputsStandard(CTransaction(tx_max_sigops), coins));
1056
1057 // Adding one more input will bump this to 2505, hitting the limit.
1058 tx_create.vout.emplace_back(424242, max_sigops_p2sh);
1059 prev_txid = tx_create.GetHash();
1060 for (unsigned i{0}; i < p2sh_inputs_count; ++i) {
1061 tx_max_sigops.vin[i] = CTxIn(COutPoint(prev_txid, i), CScript() << ToByteVector(max_sigops_redeem_script));
1062 }
1063 tx_max_sigops.vin.emplace_back(prev_txid, p2sh_inputs_count, CScript() << ToByteVector(max_sigops_redeem_script));
1064 AddCoins(coins, CTransaction(tx_create), 0, false);
1065 BOOST_CHECK_GT((p2sh_inputs_count + 1) * MAX_P2SH_SIGOPS, MAX_TX_LEGACY_SIGOPS);
1066 BOOST_CHECK_EQUAL(GetP2SHSigOpCount(CTransaction(tx_max_sigops), coins), 2505);
1067 BOOST_CHECK(!::AreInputsStandard(CTransaction(tx_max_sigops), coins));
1068
1069 // Now, check the limit can be reached with regular P2PK outputs too. Use a separate
1070 // preparation transaction, to demonstrate spending coins from a single tx is irrelevant.
1071 CMutableTransaction tx_create_p2pk;
1072 const auto p2pk_script{CScript() << key.GetPubKey() << OP_CHECKSIG};
1073 unsigned p2pk_inputs_count{10}; // From 2490 to 2500.
1074 for (unsigned i{0}; i < p2pk_inputs_count; ++i) {
1075 tx_create_p2pk.vout.emplace_back(212121 + i, p2pk_script);
1076 }
1077 prev_txid = tx_create_p2pk.GetHash();
1078 tx_max_sigops.vin.resize(p2sh_inputs_count); // Drop the extra input.
1079 for (unsigned i{0}; i < p2pk_inputs_count; ++i) {
1080 tx_max_sigops.vin.emplace_back(prev_txid, i);
1081 }
1082 AddCoins(coins, CTransaction(tx_create_p2pk), 0, false);
1083
1084 // The transaction now contains exactly 2500 sigops, the check should pass.
1085 BOOST_CHECK_EQUAL(p2sh_inputs_count * MAX_P2SH_SIGOPS + p2pk_inputs_count * 1, MAX_TX_LEGACY_SIGOPS);
1086 BOOST_CHECK(::AreInputsStandard(CTransaction(tx_max_sigops), coins));
1087
1088 // Now, add some Segwit inputs. We add one for each defined Segwit output type. The limit
1089 // is exclusively on non-witness sigops and therefore those should not be counted.
1090 CMutableTransaction tx_create_segwit;
1091 const auto witness_script{CScript() << key.GetPubKey() << OP_CHECKSIG};
1092 tx_create_segwit.vout.emplace_back(121212, GetScriptForDestination(WitnessV0KeyHash(key.GetPubKey())));
1093 tx_create_segwit.vout.emplace_back(131313, GetScriptForDestination(WitnessV0ScriptHash(witness_script)));
1094 tx_create_segwit.vout.emplace_back(141414, GetScriptForDestination(WitnessV1Taproot{XOnlyPubKey(key.GetPubKey())}));
1095 prev_txid = tx_create_segwit.GetHash();
1096 for (unsigned i{0}; i < tx_create_segwit.vout.size(); ++i) {
1097 tx_max_sigops.vin.emplace_back(prev_txid, i);
1098 }
1099
1100 // The transaction now still contains exactly 2500 sigops, the check should pass.
1101 AddCoins(coins, CTransaction(tx_create_segwit), 0, false);
1102 BOOST_REQUIRE(::AreInputsStandard(CTransaction(tx_max_sigops), coins));
1103
1104 // Add one more P2PK input. We'll reach the limit.
1105 tx_create_p2pk.vout.emplace_back(212121, p2pk_script);
1106 prev_txid = tx_create_p2pk.GetHash();
1107 tx_max_sigops.vin.resize(p2sh_inputs_count);
1108 ++p2pk_inputs_count;
1109 for (unsigned i{0}; i < p2pk_inputs_count; ++i) {
1110 tx_max_sigops.vin.emplace_back(prev_txid, i);
1111 }
1112 AddCoins(coins, CTransaction(tx_create_p2pk), 0, false);
1113 BOOST_CHECK_GT(p2sh_inputs_count * MAX_P2SH_SIGOPS + p2pk_inputs_count * 1, MAX_TX_LEGACY_SIGOPS);
1114 BOOST_CHECK(!::AreInputsStandard(CTransaction(tx_max_sigops), coins));
1115}
1116
1118BOOST_AUTO_TEST_CASE(spends_witness_prog)
1119{
1120 CCoinsView coins_dummy;
1121 CCoinsViewCache coins(&coins_dummy);
1122 CKey key;
1123 key.MakeNewKey(true);
1124 const CPubKey pubkey{key.GetPubKey()};
1125 CMutableTransaction tx_create{}, tx_spend{};
1126 tx_create.vout.emplace_back(0, CScript{});
1127 tx_spend.vin.emplace_back(Txid{}, 0);
1128 std::vector<std::vector<uint8_t>> sol_dummy;
1129
1130 // CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash,
1131 // WitnessV1Taproot, PayToAnchor, WitnessUnknown.
1132 static_assert(std::variant_size_v<CTxDestination> == 9);
1133
1134 // Go through all defined output types and sanity check SpendsNonAnchorWitnessProg.
1135
1136 // P2PK
1137 tx_create.vout[0].scriptPubKey = GetScriptForDestination(PubKeyDestination{pubkey});
1138 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::PUBKEY);
1139 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1140 AddCoins(coins, CTransaction{tx_create}, 0, false);
1142
1143 // P2PKH
1144 tx_create.vout[0].scriptPubKey = GetScriptForDestination(PKHash{pubkey});
1145 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::PUBKEYHASH);
1146 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1147 AddCoins(coins, CTransaction{tx_create}, 0, false);
1149
1150 // P2SH
1151 auto redeem_script{CScript{} << OP_1 << OP_CHECKSIG};
1152 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash{redeem_script});
1153 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1154 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1155 tx_spend.vin[0].scriptSig = CScript{} << OP_0 << ToByteVector(redeem_script);
1156 AddCoins(coins, CTransaction{tx_create}, 0, false);
1158 tx_spend.vin[0].scriptSig.clear();
1159
1160 // native P2WSH
1161 const auto witness_script{CScript{} << OP_12 << OP_HASH160 << OP_DUP << OP_EQUAL};
1162 tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash{witness_script});
1163 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::WITNESS_V0_SCRIPTHASH);
1164 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1165 AddCoins(coins, CTransaction{tx_create}, 0, false);
1167
1168 // P2SH-wrapped P2WSH
1169 redeem_script = tx_create.vout[0].scriptPubKey;
1170 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1171 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1172 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1173 tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1174 AddCoins(coins, CTransaction{tx_create}, 0, false);
1176 tx_spend.vin[0].scriptSig.clear();
1178
1179 // native P2WPKH
1180 tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessV0KeyHash{pubkey});
1181 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::WITNESS_V0_KEYHASH);
1182 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1183 AddCoins(coins, CTransaction{tx_create}, 0, false);
1185
1186 // P2SH-wrapped P2WPKH
1187 redeem_script = tx_create.vout[0].scriptPubKey;
1188 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1189 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1190 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1191 tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1192 AddCoins(coins, CTransaction{tx_create}, 0, false);
1194 tx_spend.vin[0].scriptSig.clear();
1196
1197 // P2TR
1198 tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessV1Taproot{XOnlyPubKey{pubkey}});
1199 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::WITNESS_V1_TAPROOT);
1200 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1201 AddCoins(coins, CTransaction{tx_create}, 0, false);
1203
1204 // P2SH-wrapped P2TR (undefined, non-standard)
1205 redeem_script = tx_create.vout[0].scriptPubKey;
1206 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1207 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1208 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1209 tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1210 AddCoins(coins, CTransaction{tx_create}, 0, false);
1212 tx_spend.vin[0].scriptSig.clear();
1214
1215 // P2A
1216 tx_create.vout[0].scriptPubKey = GetScriptForDestination(PayToAnchor{});
1217 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::ANCHOR);
1218 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1219 AddCoins(coins, CTransaction{tx_create}, 0, false);
1221
1222 // P2SH-wrapped P2A (undefined, non-standard)
1223 redeem_script = tx_create.vout[0].scriptPubKey;
1224 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1225 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1226 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1227 tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1228 AddCoins(coins, CTransaction{tx_create}, 0, false);
1230 tx_spend.vin[0].scriptSig.clear();
1231
1232 // Undefined version 1 witness program
1233 tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessUnknown{1, {0x42, 0x42}});
1234 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::WITNESS_UNKNOWN);
1235 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1236 AddCoins(coins, CTransaction{tx_create}, 0, false);
1238
1239 // P2SH-wrapped undefined version 1 witness program
1240 redeem_script = tx_create.vout[0].scriptPubKey;
1241 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1242 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1243 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1244 tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1245 AddCoins(coins, CTransaction{tx_create}, 0, false);
1247 tx_spend.vin[0].scriptSig.clear();
1249
1250 // Various undefined version >1 32-byte witness programs.
1251 const auto program{ToByteVector(XOnlyPubKey{pubkey})};
1252 for (int i{2}; i <= 16; ++i) {
1253 tx_create.vout[0].scriptPubKey = GetScriptForDestination(WitnessUnknown{i, program});
1254 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::WITNESS_UNKNOWN);
1255 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1256 AddCoins(coins, CTransaction{tx_create}, 0, false);
1258
1259 // It's also detected within P2SH.
1260 redeem_script = tx_create.vout[0].scriptPubKey;
1261 tx_create.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(redeem_script));
1262 BOOST_CHECK_EQUAL(Solver(tx_create.vout[0].scriptPubKey, sol_dummy), TxoutType::SCRIPTHASH);
1263 tx_spend.vin[0].prevout.hash = tx_create.GetHash();
1264 tx_spend.vin[0].scriptSig = CScript{} << ToByteVector(redeem_script);
1265 AddCoins(coins, CTransaction{tx_create}, 0, false);
1267 tx_spend.vin[0].scriptSig.clear();
1269 }
1270}
1271
std::vector< unsigned char > valtype
Definition: addresstype.cpp:18
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
static const std::vector< unsigned char > ANCHOR_BYTES
Witness program for Pay-to-Anchor output script type.
Definition: addresstype.h:121
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:529
#define Assert(val)
Identity function.
Definition: check.h:106
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:221
void Add(std::vector< T > &&vChecks)
Definition: checkqueue.h:228
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 virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:35
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
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:161
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:413
static opcodetype EncodeOP_N(int n)
Definition: script.h:522
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:130
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:87
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
size_t size() const
Definition: univalue.h:71
bool isStr() const
Definition: univalue.h:85
Int getInt() const
Definition: univalue.h:140
const UniValue & get_array() const
bool IsValid() const
Definition: validation.h:105
std::string GetRejectReason() const
Definition: validation.h:109
bool IsInvalid() const
Definition: validation.h:106
constexpr unsigned char * end()
Definition: uint256.h:102
constexpr unsigned char * begin()
Definition: uint256.h:101
void emplace_back(Args &&... args)
Definition: prevector.h:391
iterator begin()
Definition: prevector.h:263
iterator end()
Definition: prevector.h:265
static constexpr script_verify_flags from_int(value_type f)
Definition: verify_flags.h:35
static std::optional< transaction_identifier > FromHex(std::string_view hex)
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
Utility function to add all of a transaction's outputs to a cache.
Definition: coins.cpp:119
static int32_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:132
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, script_verify_flags flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror)
const std::map< std::string, script_verify_flag_name > g_verify_flag_names
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, script_verify_flags flags, const BaseSignatureChecker &checker, ScriptError *serror)
static constexpr int MAX_SCRIPT_VERIFY_FLAGS_BITS
Definition: interpreter.h:154
@ BASE
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
@ SIGHASH_ANYONECANPAY
Definition: interpreter.h:34
@ SIGHASH_ALL
Definition: interpreter.h:31
@ SIGHASH_NONE
Definition: interpreter.h:32
@ SIGHASH_SINGLE
Definition: interpreter.h:33
@ ASSERT_FAIL
Abort execution through assertion failure (for consensus code)
static constexpr script_verify_flags SCRIPT_VERIFY_NONE
Script verification flags.
Definition: interpreter.h:47
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:384
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:148
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:245
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
bool SpendsNonAnchorWitnessProg(const CTransaction &tx, const CCoinsViewCache &prevouts)
Check whether this transaction spends any witness program but P2A, including not-yet-defined ones.
Definition: policy.cpp:340
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs.
Definition: policy.cpp:213
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:99
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for -datacarriersize in vbytes.
Definition: policy.h:80
static constexpr unsigned int MAX_TX_LEGACY_SIGOPS
The maximum number of potentially executed legacy signature operations in a single standard tx.
Definition: policy.h:42
static constexpr script_verify_flags STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:115
static constexpr decltype(CTransaction::version) TX_MAX_STANDARD_VERSION
Definition: policy.h:149
static constexpr bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
Definition: policy.h:48
static constexpr unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
Definition: policy.h:64
static constexpr unsigned int MAX_DUST_OUTPUTS_PER_TX
Maximum number of ephemeral dust outputs allowed.
Definition: policy.h:91
static constexpr unsigned int MAX_P2SH_SIGOPS
Maximum number of signature check operations in an IsStandard() P2SH script.
Definition: policy.h:38
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:50
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_NOT
Definition: script.h:158
@ OP_EQUAL
Definition: script.h:146
@ OP_SIZE
Definition: script.h:139
@ OP_3DUP
Definition: script.h:118
@ OP_DUP
Definition: script.h:125
@ 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_HASH160
Definition: script.h:187
@ OP_2DUP
Definition: script.h:117
@ OP_1
Definition: script.h:83
@ OP_TRUE
Definition: script.h:84
@ OP_VERIFY
Definition: script.h:110
@ OP_12
Definition: script.h:95
@ OP_ADD
Definition: script.h:161
@ OP_DROP
Definition: script.h:124
@ 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:1094
constexpr deserialize_type deserialize
Definition: serialize.h:49
static constexpr CAmount CENT
Definition: setup_common.h:47
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
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: solver.cpp:141
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition: solver.cpp:218
@ WITNESS_V1_TAPROOT
@ WITNESS_UNKNOWN
Only for Witness versions not already defined above.
@ ANCHOR
anyone can spend script
@ WITNESS_V0_SCRIPTHASH
@ WITNESS_V0_KEYHASH
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:68
Basic testing setup.
Definition: setup_common.h:64
A mutable version of CTransaction.
Definition: transaction.h:378
std::vector< CTxOut > vout
Definition: transaction.h:380
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:69
std::vector< CTxIn > vin
Definition: transaction.h:379
void MergeSignatureData(SignatureData sigdata)
Definition: sign.cpp:681
CTxDestination subtype to encode any future Witness version.
Definition: addresstype.h:96
bool IsValidFlagCombination(script_verify_flags flags)
Flags that are not forbidden by an assert in script validation.
Definition: script.cpp:8
SignatureData CombineSignatures(const CMutableTransaction &input1, const CMutableTransaction &input2, const CTransactionRef tx)
std::set< script_verify_flags > ExcludeIndividualFlags(script_verify_flags flags)
script_verify_flags FillFlags(script_verify_flags flags)
bool CheckTxScripts(const CTransaction &tx, const std::map< COutPoint, CScript > &map_prevout_scriptPubKeys, const std::map< COutPoint, int64_t > &map_prevout_values, script_verify_flags flags, const PrecomputedTransactionData &txdata, const std::string &strTest, bool expect_valid)
static bool g_bare_multi
static const std::map< std::string, script_verify_flag_name > & mapFlagNames
script_verify_flags TrimFlags(script_verify_flags flags)
std::vector< unsigned char > valtype
BOOST_AUTO_TEST_CASE(tx_valid)
script_verify_flags ParseScriptFlags(std::string strFlags)
static void ReplaceRedeemScript(CScript &script, const CScript &redeemScript)
bool CheckMapFlagNames()
static void CreateCreditAndSpend(const FillableSigningProvider &keystore, const CScript &outscript, CTransactionRef &output, CMutableTransaction &input, bool success=true)
static CScript PushAll(const std::vector< valtype > &values)
static CFeeRate g_dust
static void CheckWithFlag(const CTransactionRef &output, const CMutableTransaction &input, script_verify_flags flags, bool success)
std::vector< CMutableTransaction > SetupDummyInputs(FillableSigningProvider &keystoreRet, CCoinsViewCache &coinsRet, const std::array< CAmount, 4 > &nValues)
bool SignSignature(const SigningProvider &provider, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, const CAmount &amount, int nHashType, SignatureData &sig_data)
Produce a satisfying script (scriptSig or witness).
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
Definition: tx_check.cpp:11
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
Definition: tx_verify.cpp:126
constexpr std::array tests
Definition: unitester.cpp:100
assert(!tx.IsCoinBase())