1 // Copyright (c) 2011-2020 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>
7 #include <test/util/setup_common.h>
8
9 #include <checkqueue.h>
10 #include <clientversion.h>
11 #include <consensus/tx_check.h>
12 #include <consensus/validation.h>
13 #include <core_io.h>
14 #include <key.h>
15 #include <policy/policy.h>
16 #include <policy/settings.h>
17 #include <script/script.h>
18 #include <script/script_error.h>
19 #include <script/sign.h>
20 #include <script/signingprovider.h>
21 #include <script/standard.h>
22 #include <streams.h>
23 #include <test/util/script.h>
24 #include <test/util/transaction_utils.h>
25 #include <util/strencodings.h>
26 #include <util/string.h>
27 #include <validation.h>
28
29 #include <functional>
30 #include <map>
31 #include <string>
32
33 #include <boost/algorithm/string/classification.hpp>
34 #include <boost/algorithm/string/split.hpp>
35 #include <boost/test/unit_test.hpp>
36
37 #include <univalue.h>
38
39 typedef std::vector<unsigned char> valtype;
40
41 // In script_tests.cpp
42 UniValue read_json(const std::string& jsondata);
43
44 static std::map<std::string, unsigned int> mapFlagNames = {
45 {std::string("P2SH"), (unsigned int)SCRIPT_VERIFY_P2SH},
46 {std::string("STRICTENC"), (unsigned int)SCRIPT_VERIFY_STRICTENC},
47 {std::string("DERSIG"), (unsigned int)SCRIPT_VERIFY_DERSIG},
48 {std::string("LOW_S"), (unsigned int)SCRIPT_VERIFY_LOW_S},
49 {std::string("SIGPUSHONLY"), (unsigned int)SCRIPT_VERIFY_SIGPUSHONLY},
50 {std::string("MINIMALDATA"), (unsigned int)SCRIPT_VERIFY_MINIMALDATA},
51 {std::string("NULLDUMMY"), (unsigned int)SCRIPT_VERIFY_NULLDUMMY},
52 {std::string("DISCOURAGE_UPGRADABLE_NOPS"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS},
53 {std::string("CLEANSTACK"), (unsigned int)SCRIPT_VERIFY_CLEANSTACK},
54 {std::string("MINIMALIF"), (unsigned int)SCRIPT_VERIFY_MINIMALIF},
55 {std::string("NULLFAIL"), (unsigned int)SCRIPT_VERIFY_NULLFAIL},
56 {std::string("CHECKLOCKTIMEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY},
57 {std::string("CHECKSEQUENCEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKSEQUENCEVERIFY},
58 {std::string("WITNESS"), (unsigned int)SCRIPT_VERIFY_WITNESS},
59 {std::string("DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM},
60 {std::string("WITNESS_PUBKEYTYPE"), (unsigned int)SCRIPT_VERIFY_WITNESS_PUBKEYTYPE},
61 {std::string("CONST_SCRIPTCODE"), (unsigned int)SCRIPT_VERIFY_CONST_SCRIPTCODE},
62 {std::string("TAPROOT"), (unsigned int)SCRIPT_VERIFY_TAPROOT},
63 {std::string("DISCOURAGE_UPGRADABLE_PUBKEYTYPE"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_PUBKEYTYPE},
64 {std::string("DISCOURAGE_OP_SUCCESS"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_OP_SUCCESS},
65 {std::string("DISCOURAGE_UPGRADABLE_TAPROOT_VERSION"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION},
66 };
67
ParseScriptFlags(std::string strFlags)68 unsigned int ParseScriptFlags(std::string strFlags)
69 {
70 if (strFlags.empty() || strFlags == "NONE") return 0;
71 unsigned int flags = 0;
72 std::vector<std::string> words;
73 boost::algorithm::split(words, strFlags, boost::algorithm::is_any_of(","));
74
75 for (const std::string& word : words)
76 {
77 if (!mapFlagNames.count(word))
78 BOOST_ERROR("Bad test: unknown verification flag '" << word << "'");
79 flags |= mapFlagNames[word];
80 }
81
82 return flags;
83 }
84
85 // Check that all flags in STANDARD_SCRIPT_VERIFY_FLAGS are present in mapFlagNames.
CheckMapFlagNames()86 bool CheckMapFlagNames()
87 {
88 unsigned int standard_flags_missing{STANDARD_SCRIPT_VERIFY_FLAGS};
89 for (const auto& pair : mapFlagNames) {
90 standard_flags_missing &= ~(pair.second);
91 }
92 return standard_flags_missing == 0;
93 }
94
FormatScriptFlags(unsigned int flags)95 std::string FormatScriptFlags(unsigned int flags)
96 {
97 if (flags == 0) {
98 return "";
99 }
100 std::string ret;
101 std::map<std::string, unsigned int>::const_iterator it = mapFlagNames.begin();
102 while (it != mapFlagNames.end()) {
103 if (flags & it->second) {
104 ret += it->first + ",";
105 }
106 it++;
107 }
108 return ret.substr(0, ret.size() - 1);
109 }
110
111 /*
112 * Check that the input scripts of a transaction are valid/invalid as expected.
113 */
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)114 bool CheckTxScripts(const CTransaction& tx, const std::map<COutPoint, CScript>& map_prevout_scriptPubKeys,
115 const std::map<COutPoint, int64_t>& map_prevout_values, unsigned int flags,
116 const PrecomputedTransactionData& txdata, const std::string& strTest, bool expect_valid)
117 {
118 bool tx_valid = true;
119 ScriptError err = expect_valid ? SCRIPT_ERR_UNKNOWN_ERROR : SCRIPT_ERR_OK;
120 for (unsigned int i = 0; i < tx.vin.size() && tx_valid; ++i) {
121 const CTxIn input = tx.vin[i];
122 const CAmount amount = map_prevout_values.count(input.prevout) ? map_prevout_values.at(input.prevout) : 0;
123 try {
124 tx_valid = VerifyScript(input.scriptSig, map_prevout_scriptPubKeys.at(input.prevout),
125 &input.scriptWitness, flags, TransactionSignatureChecker(&tx, i, amount, txdata, MissingDataBehavior::ASSERT_FAIL), &err);
126 } catch (...) {
127 BOOST_ERROR("Bad test: " << strTest);
128 return true; // The test format is bad and an error is thrown. Return true to silence further error.
129 }
130 if (expect_valid) {
131 BOOST_CHECK_MESSAGE(tx_valid, strTest);
132 BOOST_CHECK_MESSAGE((err == SCRIPT_ERR_OK), ScriptErrorString(err));
133 err = SCRIPT_ERR_UNKNOWN_ERROR;
134 }
135 }
136 if (!expect_valid) {
137 BOOST_CHECK_MESSAGE(!tx_valid, strTest);
138 BOOST_CHECK_MESSAGE((err != SCRIPT_ERR_OK), ScriptErrorString(err));
139 }
140 return (tx_valid == expect_valid);
141 }
142
143 /*
144 * Trim or fill flags to make the combination valid:
145 * WITNESS must be used with P2SH
146 * CLEANSTACK must be used WITNESS and P2SH
147 */
148
TrimFlags(unsigned int flags)149 unsigned int TrimFlags(unsigned int flags)
150 {
151 // WITNESS requires P2SH
152 if (!(flags & SCRIPT_VERIFY_P2SH)) flags &= ~(unsigned int)SCRIPT_VERIFY_WITNESS;
153
154 // CLEANSTACK requires WITNESS (and transitively CLEANSTACK requires P2SH)
155 if (!(flags & SCRIPT_VERIFY_WITNESS)) flags &= ~(unsigned int)SCRIPT_VERIFY_CLEANSTACK;
156 Assert(IsValidFlagCombination(flags));
157 return flags;
158 }
159
FillFlags(unsigned int flags)160 unsigned int FillFlags(unsigned int flags)
161 {
162 // CLEANSTACK implies WITNESS
163 if (flags & SCRIPT_VERIFY_CLEANSTACK) flags |= SCRIPT_VERIFY_WITNESS;
164
165 // WITNESS implies P2SH (and transitively CLEANSTACK implies P2SH)
166 if (flags & SCRIPT_VERIFY_WITNESS) flags |= SCRIPT_VERIFY_P2SH;
167 Assert(IsValidFlagCombination(flags));
168 return flags;
169 }
170
171 // Exclude each possible script verify flag from flags. Returns a set of these flag combinations
172 // that are valid and without duplicates. For example: if flags=1111 and the 4 possible flags are
173 // 0001, 0010, 0100, and 1000, this should return the set {0111, 1011, 1101, 1110}.
174 // Assumes that mapFlagNames contains all script verify flags.
ExcludeIndividualFlags(unsigned int flags)175 std::set<unsigned int> ExcludeIndividualFlags(unsigned int flags)
176 {
177 std::set<unsigned int> flags_combos;
178 for (const auto& pair : mapFlagNames) {
179 const unsigned int flags_excluding_one = TrimFlags(flags & ~(pair.second));
180 if (flags != flags_excluding_one) {
181 flags_combos.insert(flags_excluding_one);
182 }
183 }
184 return flags_combos;
185 }
186
BOOST_FIXTURE_TEST_SUITE(transaction_tests,BasicTestingSetup)187 BOOST_FIXTURE_TEST_SUITE(transaction_tests, BasicTestingSetup)
188
189 BOOST_AUTO_TEST_CASE(tx_valid)
190 {
191 BOOST_CHECK_MESSAGE(CheckMapFlagNames(), "mapFlagNames is missing a script verification flag");
192 // Read tests from test/data/tx_valid.json
193 UniValue tests = read_json(std::string(json_tests::tx_valid, json_tests::tx_valid + sizeof(json_tests::tx_valid)));
194
195 for (unsigned int idx = 0; idx < tests.size(); idx++) {
196 UniValue test = tests[idx];
197 std::string strTest = test.write();
198 if (test[0].isArray())
199 {
200 if (test.size() != 3 || !test[1].isStr() || !test[2].isStr())
201 {
202 BOOST_ERROR("Bad test: " << strTest);
203 continue;
204 }
205
206 std::map<COutPoint, CScript> mapprevOutScriptPubKeys;
207 std::map<COutPoint, int64_t> mapprevOutValues;
208 UniValue inputs = test[0].get_array();
209 bool fValid = true;
210 for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) {
211 const UniValue& input = inputs[inpIdx];
212 if (!input.isArray()) {
213 fValid = false;
214 break;
215 }
216 UniValue vinput = input.get_array();
217 if (vinput.size() < 3 || vinput.size() > 4)
218 {
219 fValid = false;
220 break;
221 }
222 COutPoint outpoint(uint256S(vinput[0].get_str()), vinput[1].get_int());
223 mapprevOutScriptPubKeys[outpoint] = ParseScript(vinput[2].get_str());
224 if (vinput.size() >= 4)
225 {
226 mapprevOutValues[outpoint] = vinput[3].get_int64();
227 }
228 }
229 if (!fValid)
230 {
231 BOOST_ERROR("Bad test: " << strTest);
232 continue;
233 }
234
235 std::string transaction = test[1].get_str();
236 CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION);
237 CTransaction tx(deserialize, stream);
238
239 TxValidationState state;
240 BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest);
241 BOOST_CHECK(state.IsValid());
242
243 PrecomputedTransactionData txdata(tx);
244 unsigned int verify_flags = ParseScriptFlags(test[2].get_str());
245
246 // Check that the test gives a valid combination of flags (otherwise VerifyScript will throw). Don't edit the flags.
247 if (~verify_flags != FillFlags(~verify_flags)) {
248 BOOST_ERROR("Bad test flags: " << strTest);
249 }
250
251 BOOST_CHECK_MESSAGE(CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, ~verify_flags, txdata, strTest, /* expect_valid */ true),
252 "Tx unexpectedly failed: " << strTest);
253
254 // Backwards compatibility of script verification flags: Removing any flag(s) should not invalidate a valid transaction
255 for (const auto& [name, flag] : mapFlagNames) {
256 // Removing individual flags
257 unsigned int flags = TrimFlags(~(verify_flags | flag));
258 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /* expect_valid */ true)) {
259 BOOST_ERROR("Tx unexpectedly failed with flag " << name << " unset: " << strTest);
260 }
261 // Removing random combinations of flags
262 flags = TrimFlags(~(verify_flags | (unsigned int)InsecureRandBits(mapFlagNames.size())));
263 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /* expect_valid */ true)) {
264 BOOST_ERROR("Tx unexpectedly failed with random flags " << ToString(flags) << ": " << strTest);
265 }
266 }
267
268 // Check that flags are maximal: transaction should fail if any unset flags are set.
269 for (auto flags_excluding_one : ExcludeIndividualFlags(verify_flags)) {
270 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, ~flags_excluding_one, txdata, strTest, /* expect_valid */ false)) {
271 BOOST_ERROR("Too many flags unset: " << strTest);
272 }
273 }
274 }
275 }
276 }
277
BOOST_AUTO_TEST_CASE(tx_invalid)278 BOOST_AUTO_TEST_CASE(tx_invalid)
279 {
280 // Read tests from test/data/tx_invalid.json
281 UniValue tests = read_json(std::string(json_tests::tx_invalid, json_tests::tx_invalid + sizeof(json_tests::tx_invalid)));
282
283 for (unsigned int idx = 0; idx < tests.size(); idx++) {
284 UniValue test = tests[idx];
285 std::string strTest = test.write();
286 if (test[0].isArray())
287 {
288 if (test.size() != 3 || !test[1].isStr() || !test[2].isStr())
289 {
290 BOOST_ERROR("Bad test: " << strTest);
291 continue;
292 }
293
294 std::map<COutPoint, CScript> mapprevOutScriptPubKeys;
295 std::map<COutPoint, int64_t> mapprevOutValues;
296 UniValue inputs = test[0].get_array();
297 bool fValid = true;
298 for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) {
299 const UniValue& input = inputs[inpIdx];
300 if (!input.isArray()) {
301 fValid = false;
302 break;
303 }
304 UniValue vinput = input.get_array();
305 if (vinput.size() < 3 || vinput.size() > 4)
306 {
307 fValid = false;
308 break;
309 }
310 COutPoint outpoint(uint256S(vinput[0].get_str()), vinput[1].get_int());
311 mapprevOutScriptPubKeys[outpoint] = ParseScript(vinput[2].get_str());
312 if (vinput.size() >= 4)
313 {
314 mapprevOutValues[outpoint] = vinput[3].get_int64();
315 }
316 }
317 if (!fValid)
318 {
319 BOOST_ERROR("Bad test: " << strTest);
320 continue;
321 }
322
323 std::string transaction = test[1].get_str();
324 CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION );
325 CTransaction tx(deserialize, stream);
326
327 TxValidationState state;
328 if (!CheckTransaction(tx, state) || state.IsInvalid()) {
329 BOOST_CHECK_MESSAGE(test[2].get_str() == "BADTX", strTest);
330 continue;
331 }
332
333 PrecomputedTransactionData txdata(tx);
334 unsigned int verify_flags = ParseScriptFlags(test[2].get_str());
335
336 // Check that the test gives a valid combination of flags (otherwise VerifyScript will throw). Don't edit the flags.
337 if (verify_flags != FillFlags(verify_flags)) {
338 BOOST_ERROR("Bad test flags: " << strTest);
339 }
340
341 // Not using FillFlags() in the main test, in order to detect invalid verifyFlags combination
342 BOOST_CHECK_MESSAGE(CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, verify_flags, txdata, strTest, /* expect_valid */ false),
343 "Tx unexpectedly passed: " << strTest);
344
345 // Backwards compatibility of script verification flags: Adding any flag(s) should not validate an invalid transaction
346 for (const auto& [name, flag] : mapFlagNames) {
347 unsigned int flags = FillFlags(verify_flags | flag);
348 // Adding individual flags
349 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /* expect_valid */ false)) {
350 BOOST_ERROR("Tx unexpectedly passed with flag " << name << " set: " << strTest);
351 }
352 // Adding random combinations of flags
353 flags = FillFlags(verify_flags | (unsigned int)InsecureRandBits(mapFlagNames.size()));
354 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags, txdata, strTest, /* expect_valid */ false)) {
355 BOOST_ERROR("Tx unexpectedly passed with random flags " << name << ": " << strTest);
356 }
357 }
358
359 // Check that flags are minimal: transaction should succeed if any set flags are unset.
360 for (auto flags_excluding_one : ExcludeIndividualFlags(verify_flags)) {
361 if (!CheckTxScripts(tx, mapprevOutScriptPubKeys, mapprevOutValues, flags_excluding_one, txdata, strTest, /* expect_valid */ true)) {
362 BOOST_ERROR("Too many flags set: " << strTest);
363 }
364 }
365 }
366 }
367 }
368
BOOST_AUTO_TEST_CASE(basic_transaction_tests)369 BOOST_AUTO_TEST_CASE(basic_transaction_tests)
370 {
371 // Random real transaction (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436)
372 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};
373 std::vector<unsigned char> vch(ch, ch + sizeof(ch) -1);
374 CDataStream stream(vch, SER_DISK, CLIENT_VERSION);
375 CMutableTransaction tx;
376 stream >> tx;
377 TxValidationState state;
378 BOOST_CHECK_MESSAGE(CheckTransaction(CTransaction(tx), state) && state.IsValid(), "Simple deserialized transaction should be valid.");
379
380 // Check that duplicate txins fail
381 tx.vin.push_back(tx.vin[0]);
382 BOOST_CHECK_MESSAGE(!CheckTransaction(CTransaction(tx), state) || !state.IsValid(), "Transaction with duplicate txins should be invalid.");
383 }
384
BOOST_AUTO_TEST_CASE(test_Get)385 BOOST_AUTO_TEST_CASE(test_Get)
386 {
387 FillableSigningProvider keystore;
388 CCoinsView coinsDummy;
389 CCoinsViewCache coins(&coinsDummy);
390 std::vector<CMutableTransaction> dummyTransactions =
391 SetupDummyInputs(keystore, coins, {11*CENT, 50*CENT, 21*CENT, 22*CENT});
392
393 CMutableTransaction t1;
394 t1.vin.resize(3);
395 t1.vin[0].prevout.hash = dummyTransactions[0].GetHash();
396 t1.vin[0].prevout.n = 1;
397 t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0);
398 t1.vin[1].prevout.hash = dummyTransactions[1].GetHash();
399 t1.vin[1].prevout.n = 0;
400 t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
401 t1.vin[2].prevout.hash = dummyTransactions[1].GetHash();
402 t1.vin[2].prevout.n = 1;
403 t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
404 t1.vout.resize(2);
405 t1.vout[0].nValue = 90*CENT;
406 t1.vout[0].scriptPubKey << OP_1;
407
408 BOOST_CHECK(AreInputsStandard(CTransaction(t1), coins, false));
409 }
410
CreateCreditAndSpend(const FillableSigningProvider & keystore,const CScript & outscript,CTransactionRef & output,CMutableTransaction & input,bool success=true)411 static void CreateCreditAndSpend(const FillableSigningProvider& keystore, const CScript& outscript, CTransactionRef& output, CMutableTransaction& input, bool success = true)
412 {
413 CMutableTransaction outputm;
414 outputm.nVersion = 1;
415 outputm.vin.resize(1);
416 outputm.vin[0].prevout.SetNull();
417 outputm.vin[0].scriptSig = CScript();
418 outputm.vout.resize(1);
419 outputm.vout[0].nValue = 1;
420 outputm.vout[0].scriptPubKey = outscript;
421 CDataStream ssout(SER_NETWORK, PROTOCOL_VERSION);
422 ssout << outputm;
423 ssout >> output;
424 assert(output->vin.size() == 1);
425 assert(output->vin[0] == outputm.vin[0]);
426 assert(output->vout.size() == 1);
427 assert(output->vout[0] == outputm.vout[0]);
428
429 CMutableTransaction inputm;
430 inputm.nVersion = 1;
431 inputm.vin.resize(1);
432 inputm.vin[0].prevout.hash = output->GetHash();
433 inputm.vin[0].prevout.n = 0;
434 inputm.vout.resize(1);
435 inputm.vout[0].nValue = 1;
436 inputm.vout[0].scriptPubKey = CScript();
437 bool ret = SignSignature(keystore, *output, inputm, 0, SIGHASH_ALL);
438 assert(ret == success);
439 CDataStream ssin(SER_NETWORK, PROTOCOL_VERSION);
440 ssin << inputm;
441 ssin >> input;
442 assert(input.vin.size() == 1);
443 assert(input.vin[0] == inputm.vin[0]);
444 assert(input.vout.size() == 1);
445 assert(input.vout[0] == inputm.vout[0]);
446 assert(input.vin[0].scriptWitness.stack == inputm.vin[0].scriptWitness.stack);
447 }
448
CheckWithFlag(const CTransactionRef & output,const CMutableTransaction & input,int flags,bool success)449 static void CheckWithFlag(const CTransactionRef& output, const CMutableTransaction& input, int flags, bool success)
450 {
451 ScriptError error;
452 CTransaction inputi(input);
453 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);
454 assert(ret == success);
455 }
456
PushAll(const std::vector<valtype> & values)457 static CScript PushAll(const std::vector<valtype>& values)
458 {
459 CScript result;
460 for (const valtype& v : values) {
461 if (v.size() == 0) {
462 result << OP_0;
463 } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
464 result << CScript::EncodeOP_N(v[0]);
465 } else if (v.size() == 1 && v[0] == 0x81) {
466 result << OP_1NEGATE;
467 } else {
468 result << v;
469 }
470 }
471 return result;
472 }
473
ReplaceRedeemScript(CScript & script,const CScript & redeemScript)474 static void ReplaceRedeemScript(CScript& script, const CScript& redeemScript)
475 {
476 std::vector<valtype> stack;
477 EvalScript(stack, script, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE);
478 assert(stack.size() > 0);
479 stack.back() = std::vector<unsigned char>(redeemScript.begin(), redeemScript.end());
480 script = PushAll(stack);
481 }
482
BOOST_AUTO_TEST_CASE(test_big_witness_transaction)483 BOOST_AUTO_TEST_CASE(test_big_witness_transaction)
484 {
485 CMutableTransaction mtx;
486 mtx.nVersion = 1;
487
488 CKey key;
489 key.MakeNewKey(true); // Need to use compressed keys in segwit or the signing will fail
490 FillableSigningProvider keystore;
491 BOOST_CHECK(keystore.AddKeyPubKey(key, key.GetPubKey()));
492 CKeyID hash = key.GetPubKey().GetID();
493 CScript scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(hash.begin(), hash.end());
494
495 std::vector<int> sigHashes;
496 sigHashes.push_back(SIGHASH_NONE | SIGHASH_ANYONECANPAY);
497 sigHashes.push_back(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY);
498 sigHashes.push_back(SIGHASH_ALL | SIGHASH_ANYONECANPAY);
499 sigHashes.push_back(SIGHASH_NONE);
500 sigHashes.push_back(SIGHASH_SINGLE);
501 sigHashes.push_back(SIGHASH_ALL);
502
503 // create a big transaction of 4500 inputs signed by the same key
504 for(uint32_t ij = 0; ij < 4500; ij++) {
505 uint32_t i = mtx.vin.size();
506 uint256 prevId;
507 prevId.SetHex("0000000000000000000000000000000000000000000000000000000000000100");
508 COutPoint outpoint(prevId, i);
509
510 mtx.vin.resize(mtx.vin.size() + 1);
511 mtx.vin[i].prevout = outpoint;
512 mtx.vin[i].scriptSig = CScript();
513
514 mtx.vout.resize(mtx.vout.size() + 1);
515 mtx.vout[i].nValue = 1000;
516 mtx.vout[i].scriptPubKey = CScript() << OP_1;
517 }
518
519 // sign all inputs
520 for(uint32_t i = 0; i < mtx.vin.size(); i++) {
521 bool hashSigned = SignSignature(keystore, scriptPubKey, mtx, i, 1000, sigHashes.at(i % sigHashes.size()));
522 assert(hashSigned);
523 }
524
525 CDataStream ssout(SER_NETWORK, PROTOCOL_VERSION);
526 ssout << mtx;
527 CTransaction tx(deserialize, ssout);
528
529 // check all inputs concurrently, with the cache
530 PrecomputedTransactionData txdata(tx);
531 CCheckQueue<CScriptCheck> scriptcheckqueue(128);
532 CCheckQueueControl<CScriptCheck> control(&scriptcheckqueue);
533
534 scriptcheckqueue.StartWorkerThreads(20);
535
536 std::vector<Coin> coins;
537 for(uint32_t i = 0; i < mtx.vin.size(); i++) {
538 Coin coin;
539 coin.nHeight = 1;
540 coin.fCoinBase = false;
541 coin.out.nValue = 1000;
542 coin.out.scriptPubKey = scriptPubKey;
543 coins.emplace_back(std::move(coin));
544 }
545
546 for(uint32_t i = 0; i < mtx.vin.size(); i++) {
547 std::vector<CScriptCheck> vChecks;
548 CScriptCheck check(coins[tx.vin[i].prevout.n].out, tx, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, false, &txdata);
549 vChecks.push_back(CScriptCheck());
550 check.swap(vChecks.back());
551 control.Add(vChecks);
552 }
553
554 bool controlCheck = control.Wait();
555 assert(controlCheck);
556 scriptcheckqueue.StopWorkerThreads();
557 }
558
CombineSignatures(const CMutableTransaction & input1,const CMutableTransaction & input2,const CTransactionRef tx)559 SignatureData CombineSignatures(const CMutableTransaction& input1, const CMutableTransaction& input2, const CTransactionRef tx)
560 {
561 SignatureData sigdata;
562 sigdata = DataFromTransaction(input1, 0, tx->vout[0]);
563 sigdata.MergeSignatureData(DataFromTransaction(input2, 0, tx->vout[0]));
564 ProduceSignature(DUMMY_SIGNING_PROVIDER, MutableTransactionSignatureCreator(&input1, 0, tx->vout[0].nValue), tx->vout[0].scriptPubKey, sigdata);
565 return sigdata;
566 }
567
BOOST_AUTO_TEST_CASE(test_witness)568 BOOST_AUTO_TEST_CASE(test_witness)
569 {
570 FillableSigningProvider keystore, keystore2;
571 CKey key1, key2, key3, key1L, key2L;
572 CPubKey pubkey1, pubkey2, pubkey3, pubkey1L, pubkey2L;
573 key1.MakeNewKey(true);
574 key2.MakeNewKey(true);
575 key3.MakeNewKey(true);
576 key1L.MakeNewKey(false);
577 key2L.MakeNewKey(false);
578 pubkey1 = key1.GetPubKey();
579 pubkey2 = key2.GetPubKey();
580 pubkey3 = key3.GetPubKey();
581 pubkey1L = key1L.GetPubKey();
582 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, 0, true);
623 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
624 CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true);
625 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
626 CheckWithFlag(output1, input2, 0, 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, 0, true);
636 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
637 CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true);
638 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
639 CheckWithFlag(output1, input2, 0, 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, 0, true);
648 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
649 CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true);
650 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
651 CheckWithFlag(output1, input2, 0, 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, 0, true);
661 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
662 CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true);
663 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
664 CheckWithFlag(output1, input2, 0, 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, 0, true);
673 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
674 CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true);
675 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
676 CheckWithFlag(output1, input2, 0, 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, 0, true);
686 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, true);
687 CheckWithFlag(output1, input1, SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true);
688 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
689 CheckWithFlag(output1, input2, 0, 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, 0, false);
705 CreateCreditAndSpend(keystore2, scriptMulti, output2, input2, false);
706 CheckWithFlag(output2, input2, 0, 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, 0, true);
714 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH, false);
715 CreateCreditAndSpend(keystore2, GetScriptForDestination(ScriptHash(scriptMulti)), output2, input2, false);
716 CheckWithFlag(output2, input2, 0, 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, 0, 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, 0, 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));
732 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, true);
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));
744 CheckWithFlag(output1, input1, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, true);
745 CheckWithFlag(output1, input1, STANDARD_SCRIPT_VERIFY_FLAGS, true);
746 }
747
BOOST_AUTO_TEST_CASE(test_IsStandard)748 BOOST_AUTO_TEST_CASE(test_IsStandard)
749 {
750 LOCK(cs_main);
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
757 CMutableTransaction t;
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 std::string reason;
769 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
770
771 // Check dust with default relay fee:
772 CAmount nDustThreshold = 182 * dustRelayFee.GetFeePerK()/1000;
773 BOOST_CHECK_EQUAL(nDustThreshold, 546);
774 // dust:
775 t.vout[0].nValue = nDustThreshold - 1;
776 reason.clear();
777 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
778 BOOST_CHECK_EQUAL(reason, "dust");
779 // not dust:
780 t.vout[0].nValue = nDustThreshold;
781 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
782
783 // Disallowed nVersion
784 t.nVersion = -1;
785 reason.clear();
786 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
787 BOOST_CHECK_EQUAL(reason, "version");
788
789 t.nVersion = 0;
790 reason.clear();
791 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
792 BOOST_CHECK_EQUAL(reason, "version");
793
794 t.nVersion = 3;
795 reason.clear();
796 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
797 BOOST_CHECK_EQUAL(reason, "version");
798
799 // Allowed nVersion
800 t.nVersion = 1;
801 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
802
803 t.nVersion = 2;
804 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
805
806 // Check dust with odd relay fee to verify rounding:
807 // nDustThreshold = 182 * 3702 / 1000
808 dustRelayFee = CFeeRate(3702);
809 // dust:
810 t.vout[0].nValue = 673 - 1;
811 reason.clear();
812 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
813 BOOST_CHECK_EQUAL(reason, "dust");
814 // not dust:
815 t.vout[0].nValue = 673;
816 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
817 dustRelayFee = CFeeRate(DUST_RELAY_TX_FEE);
818
819 t.vout[0].scriptPubKey = CScript() << OP_1;
820 reason.clear();
821 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
822 BOOST_CHECK_EQUAL(reason, "scriptpubkey");
823
824 // MAX_OP_RETURN_RELAY-byte TxoutType::NULL_DATA (standard)
825 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38");
826 BOOST_CHECK_EQUAL(MAX_OP_RETURN_RELAY, t.vout[0].scriptPubKey.size());
827 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
828
829 // MAX_OP_RETURN_RELAY+1-byte TxoutType::NULL_DATA (non-standard)
830 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3800");
831 BOOST_CHECK_EQUAL(MAX_OP_RETURN_RELAY + 1, t.vout[0].scriptPubKey.size());
832 reason.clear();
833 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
834 BOOST_CHECK_EQUAL(reason, "scriptpubkey");
835
836 // Data payload can be encoded in any way...
837 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("");
838 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
839 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("00") << ParseHex("01");
840 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
841 // OP_RESERVED *is* considered to be a PUSHDATA type opcode by IsPushOnly()!
842 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;
843 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
844 t.vout[0].scriptPubKey = CScript() << OP_RETURN << 0 << ParseHex("01") << 2 << ParseHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
845 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
846
847 // ...so long as it only contains PUSHDATA's
848 t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RETURN;
849 reason.clear();
850 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
851 BOOST_CHECK_EQUAL(reason, "scriptpubkey");
852
853 // TxoutType::NULL_DATA w/o PUSHDATA
854 t.vout.resize(1);
855 t.vout[0].scriptPubKey = CScript() << OP_RETURN;
856 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
857
858 // Only one TxoutType::NULL_DATA permitted in all cases
859 t.vout.resize(2);
860 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38");
861 t.vout[0].nValue = 0;
862 t.vout[1].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38");
863 t.vout[1].nValue = 0;
864 reason.clear();
865 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
866 BOOST_CHECK_EQUAL(reason, "multi-op-return");
867
868 t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38");
869 t.vout[1].scriptPubKey = CScript() << OP_RETURN;
870 reason.clear();
871 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
872 BOOST_CHECK_EQUAL(reason, "multi-op-return");
873
874 t.vout[0].scriptPubKey = CScript() << OP_RETURN;
875 t.vout[1].scriptPubKey = CScript() << OP_RETURN;
876 reason.clear();
877 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
878 BOOST_CHECK_EQUAL(reason, "multi-op-return");
879
880 // Check large scriptSig (non-standard if size is >1650 bytes)
881 t.vout.resize(1);
882 t.vout[0].nValue = MAX_MONEY;
883 t.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey()));
884 // OP_PUSHDATA2 with len (3 bytes) + data (1647 bytes) = 1650 bytes
885 t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(1647, 0); // 1650
886 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
887
888 t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(1648, 0); // 1651
889 reason.clear();
890 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
891 BOOST_CHECK_EQUAL(reason, "scriptsig-size");
892
893 // Check scriptSig format (non-standard if there are any other ops than just PUSHs)
894 t.vin[0].scriptSig = CScript()
895 << OP_TRUE << OP_0 << OP_1NEGATE << OP_16 // OP_n (single byte pushes: n = 1, 0, -1, 16)
896 << std::vector<unsigned char>(75, 0) // OP_PUSHx [...x bytes...]
897 << std::vector<unsigned char>(235, 0) // OP_PUSHDATA1 x [...x bytes...]
898 << std::vector<unsigned char>(1234, 0) // OP_PUSHDATA2 x [...x bytes...]
899 << OP_9;
900 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
901
902 const std::vector<unsigned char> non_push_ops = { // arbitrary set of non-push operations
903 OP_NOP, OP_VERIFY, OP_IF, OP_ROT, OP_3DUP, OP_SIZE, OP_EQUAL, OP_ADD, OP_SUB,
904 OP_HASH256, OP_CODESEPARATOR, OP_CHECKSIG, OP_CHECKLOCKTIMEVERIFY };
905
906 CScript::const_iterator pc = t.vin[0].scriptSig.begin();
907 while (pc < t.vin[0].scriptSig.end()) {
908 opcodetype opcode;
909 CScript::const_iterator prev_pc = pc;
910 t.vin[0].scriptSig.GetOp(pc, opcode); // advance to next op
911 // for the sake of simplicity, we only replace single-byte push operations
912 if (opcode >= 1 && opcode <= OP_PUSHDATA4)
913 continue;
914
915 int index = prev_pc - t.vin[0].scriptSig.begin();
916 unsigned char orig_op = *prev_pc; // save op
917 // replace current push-op with each non-push-op
918 for (auto op : non_push_ops) {
919 t.vin[0].scriptSig[index] = op;
920 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
921 BOOST_CHECK_EQUAL(reason, "scriptsig-not-pushonly");
922 }
923 t.vin[0].scriptSig[index] = orig_op; // restore op
924 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
925 }
926
927 // Check tx-size (non-standard if transaction weight is > MAX_STANDARD_TX_WEIGHT)
928 t.vin.clear();
929 t.vin.resize(2438); // size per input (empty scriptSig): 41 bytes
930 t.vout[0].scriptPubKey = CScript() << OP_RETURN << std::vector<unsigned char>(19, 0); // output size: 30 bytes
931 // tx header: 12 bytes => 48 vbytes
932 // 2438 inputs: 2438*41 = 99958 bytes => 399832 vbytes
933 // 1 output: 30 bytes => 120 vbytes
934 // ===============================
935 // total: 400000 vbytes
936 BOOST_CHECK_EQUAL(GetTransactionWeight(CTransaction(t)), 400000);
937 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
938
939 // increase output size by one byte, so we end up with 400004 vbytes
940 t.vout[0].scriptPubKey = CScript() << OP_RETURN << std::vector<unsigned char>(20, 0); // output size: 31 bytes
941 BOOST_CHECK_EQUAL(GetTransactionWeight(CTransaction(t)), 400004);
942 reason.clear();
943 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
944 BOOST_CHECK_EQUAL(reason, "tx-size");
945
946 // Check bare multisig (standard if policy flag fIsBareMultisigStd is set)
947 fIsBareMultisigStd = true;
948 t.vout[0].scriptPubKey = GetScriptForMultisig(1, {key.GetPubKey()}); // simple 1-of-1
949 t.vin.resize(1);
950 t.vin[0].scriptSig = CScript() << std::vector<unsigned char>(65, 0);
951 BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
952
953 fIsBareMultisigStd = false;
954 reason.clear();
955 BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
956 BOOST_CHECK_EQUAL(reason, "bare-multisig");
957 fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
958 }
959
960 BOOST_AUTO_TEST_SUITE_END()
961