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