script_tests.cpp raw
1 // Copyright (c) 2011-2022 The Limenka 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 <limenka-build-config.h> // IWYU pragma: keep
6
7 #include <test/data/script_tests.json.h>
8 #include <test/data/bip341_wallet_vectors.json.h>
9
10 #include <common/system.h>
11 #include <core_io.h>
12 #include <key.h>
13 #include <policy/policy.h>
14 #include <rpc/util.h>
15 #include <script/script.h>
16 #include <script/script_error.h>
17 #include <script/sigcache.h>
18 #include <script/sign.h>
19 #include <script/signingprovider.h>
20 #include <script/solver.h>
21 #include <streams.h>
22 #include <test/util/json.h>
23 #include <test/util/random.h>
24 #include <test/util/setup_common.h>
25 #include <test/util/transaction_utils.h>
26 #include <util/fs.h>
27 #include <util/strencodings.h>
28
29 #if defined(HAVE_CONSENSUS_LIB)
30 #include <script/limenkaconsensus.h>
31 #endif
32
33 #include <cstdint>
34 #include <fstream>
35 #include <string>
36 #include <vector>
37
38 #include <boost/test/unit_test.hpp>
39
40 #include <univalue.h>
41
42 // Uncomment if you want to output updated JSON tests.
43 // #define UPDATE_JSON_TESTS
44
45 using namespace util::hex_literals;
46
47 static const unsigned int gFlags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC;
48
49 unsigned int ParseScriptFlags(std::string strFlags);
50 std::string FormatScriptFlags(unsigned int flags);
51
52 struct ScriptErrorDesc
53 {
54 ScriptError_t err;
55 const char *name;
56 };
57
58 static ScriptErrorDesc script_errors[]={
59 {SCRIPT_ERR_OK, "OK"},
60 {SCRIPT_ERR_UNKNOWN_ERROR, "UNKNOWN_ERROR"},
61 {SCRIPT_ERR_EVAL_FALSE, "EVAL_FALSE"},
62 {SCRIPT_ERR_OP_RETURN, "OP_RETURN"},
63 {SCRIPT_ERR_SCRIPT_SIZE, "SCRIPT_SIZE"},
64 {SCRIPT_ERR_PUSH_SIZE, "PUSH_SIZE"},
65 {SCRIPT_ERR_OP_COUNT, "OP_COUNT"},
66 {SCRIPT_ERR_STACK_SIZE, "STACK_SIZE"},
67 {SCRIPT_ERR_SIG_COUNT, "SIG_COUNT"},
68 {SCRIPT_ERR_PUBKEY_COUNT, "PUBKEY_COUNT"},
69 {SCRIPT_ERR_VERIFY, "VERIFY"},
70 {SCRIPT_ERR_EQUALVERIFY, "EQUALVERIFY"},
71 {SCRIPT_ERR_CHECKMULTISIGVERIFY, "CHECKMULTISIGVERIFY"},
72 {SCRIPT_ERR_CHECKSIGVERIFY, "CHECKSIGVERIFY"},
73 {SCRIPT_ERR_NUMEQUALVERIFY, "NUMEQUALVERIFY"},
74 {SCRIPT_ERR_BAD_OPCODE, "BAD_OPCODE"},
75 {SCRIPT_ERR_DISABLED_OPCODE, "DISABLED_OPCODE"},
76 {SCRIPT_ERR_INVALID_STACK_OPERATION, "INVALID_STACK_OPERATION"},
77 {SCRIPT_ERR_INVALID_ALTSTACK_OPERATION, "INVALID_ALTSTACK_OPERATION"},
78 {SCRIPT_ERR_UNBALANCED_CONDITIONAL, "UNBALANCED_CONDITIONAL"},
79 {SCRIPT_ERR_NEGATIVE_LOCKTIME, "NEGATIVE_LOCKTIME"},
80 {SCRIPT_ERR_UNSATISFIED_LOCKTIME, "UNSATISFIED_LOCKTIME"},
81 {SCRIPT_ERR_SIG_HASHTYPE, "SIG_HASHTYPE"},
82 {SCRIPT_ERR_SIG_DER, "SIG_DER"},
83 {SCRIPT_ERR_MINIMALDATA, "MINIMALDATA"},
84 {SCRIPT_ERR_SIG_PUSHONLY, "SIG_PUSHONLY"},
85 {SCRIPT_ERR_SIG_HIGH_S, "SIG_HIGH_S"},
86 {SCRIPT_ERR_SIG_NULLDUMMY, "SIG_NULLDUMMY"},
87 {SCRIPT_ERR_PUBKEYTYPE, "PUBKEYTYPE"},
88 {SCRIPT_ERR_CLEANSTACK, "CLEANSTACK"},
89 {SCRIPT_ERR_MINIMALIF, "MINIMALIF"},
90 {SCRIPT_ERR_SIG_NULLFAIL, "NULLFAIL"},
91 {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS, "DISCOURAGE_UPGRADABLE_NOPS"},
92 {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, "DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"},
93 {SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH, "WITNESS_PROGRAM_WRONG_LENGTH"},
94 {SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY, "WITNESS_PROGRAM_WITNESS_EMPTY"},
95 {SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH, "WITNESS_PROGRAM_MISMATCH"},
96 {SCRIPT_ERR_WITNESS_MALLEATED, "WITNESS_MALLEATED"},
97 {SCRIPT_ERR_WITNESS_MALLEATED_P2SH, "WITNESS_MALLEATED_P2SH"},
98 {SCRIPT_ERR_WITNESS_UNEXPECTED, "WITNESS_UNEXPECTED"},
99 {SCRIPT_ERR_WITNESS_PUBKEYTYPE, "WITNESS_PUBKEYTYPE"},
100 {SCRIPT_ERR_OP_CODESEPARATOR, "OP_CODESEPARATOR"},
101 {SCRIPT_ERR_SIG_FINDANDDELETE, "SIG_FINDANDDELETE"},
102 };
103
104 static std::string FormatScriptError(ScriptError_t err)
105 {
106 for (const auto& se : script_errors)
107 if (se.err == err)
108 return se.name;
109 BOOST_ERROR("Unknown scripterror enumeration value, update script_errors in script_tests.cpp.");
110 return "";
111 }
112
113 static ScriptError_t ParseScriptError(const std::string& name)
114 {
115 for (const auto& se : script_errors)
116 if (se.name == name)
117 return se.err;
118 BOOST_ERROR("Unknown scripterror \"" << name << "\" in test description");
119 return SCRIPT_ERR_UNKNOWN_ERROR;
120 }
121
122 struct ScriptTest : BasicTestingSetup {
123 void DoTest(const CScript& scriptPubKey, const CScript& scriptSig, const CScriptWitness& scriptWitness, uint32_t flags, const std::string& message, int scriptError, CAmount nValue = 0)
124 {
125 bool expect = (scriptError == SCRIPT_ERR_OK);
126 if (flags & SCRIPT_VERIFY_CLEANSTACK) {
127 flags |= SCRIPT_VERIFY_P2SH;
128 flags |= SCRIPT_VERIFY_WITNESS;
129 }
130 ScriptError err;
131 const CTransaction txCredit{BuildCreditingTransaction(scriptPubKey, nValue)};
132 CMutableTransaction tx = BuildSpendingTransaction(scriptSig, scriptWitness, txCredit);
133 #if defined(HAVE_CONSENSUS_LIB)
134 CMutableTransaction tx2 = tx;
135 #endif
136 BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, &scriptWitness, flags, MutableTransactionSignatureChecker(&tx, 0, txCredit.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err) == expect, message);
137 BOOST_CHECK_MESSAGE(err == scriptError, FormatScriptError(err) + " where " + FormatScriptError((ScriptError_t)scriptError) + " expected: " + message);
138
139 // Verify that removing flags from a passing test or adding flags to a failing test does not change the result.
140 for (int i = 0; i < 16; ++i) {
141 uint32_t extra_flags(m_rng.randbits(16));
142 uint32_t combined_flags{expect ? (flags & ~extra_flags) : (flags | extra_flags)};
143 // Weed out some invalid flag combinations.
144 if (combined_flags & SCRIPT_VERIFY_CLEANSTACK && ~combined_flags & (SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS)) continue;
145 if (combined_flags & SCRIPT_VERIFY_WITNESS && ~combined_flags & SCRIPT_VERIFY_P2SH) continue;
146 BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, &scriptWitness, combined_flags, MutableTransactionSignatureChecker(&tx, 0, txCredit.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err) == expect, message + strprintf(" (with flags %x)", combined_flags));
147 }
148
149 #if defined(HAVE_CONSENSUS_LIB)
150 DataStream stream;
151 stream << TX_WITH_WITNESS(tx2);
152 uint32_t libconsensus_flags{flags & limenkaconsensus_SCRIPT_FLAGS_VERIFY_ALL};
153 if (libconsensus_flags == flags) {
154 int expectedSuccessCode = expect ? 1 : 0;
155 if (flags & limenkaconsensus_SCRIPT_FLAGS_VERIFY_WITNESS) {
156 BOOST_CHECK_MESSAGE(limenkaconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), txCredit.vout[0].nValue, UCharCast(stream.data()), stream.size(), 0, libconsensus_flags, nullptr) == expectedSuccessCode, message);
157 } else {
158 BOOST_CHECK_MESSAGE(limenkaconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), 0, UCharCast(stream.data()), stream.size(), 0, libconsensus_flags, nullptr) == expectedSuccessCode, message);
159 BOOST_CHECK_MESSAGE(limenkaconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), 0, libconsensus_flags, nullptr) == expectedSuccessCode, message);
160 }
161 }
162 #endif
163 }
164 }; // struct ScriptTest
165
166 void static NegateSignatureS(std::vector<unsigned char>& vchSig) {
167 // Parse the signature.
168 std::vector<unsigned char> r, s;
169 r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);
170 s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);
171
172 // Really ugly to implement mod-n negation here, but it would be feature creep to expose such functionality from libsecp256k1.
173 static const unsigned char order[33] = {
174 0x00,
175 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
176 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
177 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
178 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41
179 };
180 while (s.size() < 33) {
181 s.insert(s.begin(), 0x00);
182 }
183 int carry = 0;
184 for (int p = 32; p >= 1; p--) {
185 int n = (int)order[p] - s[p] - carry;
186 s[p] = (n + 256) & 0xFF;
187 carry = (n < 0);
188 }
189 assert(carry == 0);
190 if (s.size() > 1 && s[0] == 0 && s[1] < 0x80) {
191 s.erase(s.begin());
192 }
193
194 // Reconstruct the signature.
195 vchSig.clear();
196 vchSig.push_back(0x30);
197 vchSig.push_back(4 + r.size() + s.size());
198 vchSig.push_back(0x02);
199 vchSig.push_back(r.size());
200 vchSig.insert(vchSig.end(), r.begin(), r.end());
201 vchSig.push_back(0x02);
202 vchSig.push_back(s.size());
203 vchSig.insert(vchSig.end(), s.begin(), s.end());
204 }
205
206 namespace
207 {
208 const unsigned char vchKey0[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
209 const unsigned char vchKey1[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0};
210 const unsigned char vchKey2[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0};
211
212 struct KeyData
213 {
214 CKey key0, key0C, key1, key1C, key2, key2C;
215 CPubKey pubkey0, pubkey0C, pubkey0H;
216 CPubKey pubkey1, pubkey1C;
217 CPubKey pubkey2, pubkey2C;
218
219 KeyData()
220 {
221 key0.Set(vchKey0, vchKey0 + 32, false);
222 key0C.Set(vchKey0, vchKey0 + 32, true);
223 pubkey0 = key0.GetPubKey();
224 pubkey0H = key0.GetPubKey();
225 pubkey0C = key0C.GetPubKey();
226 *const_cast<unsigned char*>(pubkey0H.data()) = 0x06 | (pubkey0H[64] & 1);
227
228 key1.Set(vchKey1, vchKey1 + 32, false);
229 key1C.Set(vchKey1, vchKey1 + 32, true);
230 pubkey1 = key1.GetPubKey();
231 pubkey1C = key1C.GetPubKey();
232
233 key2.Set(vchKey2, vchKey2 + 32, false);
234 key2C.Set(vchKey2, vchKey2 + 32, true);
235 pubkey2 = key2.GetPubKey();
236 pubkey2C = key2C.GetPubKey();
237 }
238 };
239
240 enum class WitnessMode {
241 NONE,
242 PKH,
243 SH
244 };
245
246 class TestBuilder
247 {
248 private:
249 //! Actually executed script
250 CScript script;
251 //! The P2SH redeemscript
252 CScript redeemscript;
253 //! The Witness embedded script
254 CScript witscript;
255 CScriptWitness scriptWitness;
256 CTransactionRef creditTx;
257 CMutableTransaction spendTx;
258 bool havePush{false};
259 std::vector<unsigned char> push;
260 std::string comment;
261 uint32_t flags;
262 int scriptError{SCRIPT_ERR_OK};
263 CAmount nValue;
264
265 void DoPush()
266 {
267 if (havePush) {
268 spendTx.vin[0].scriptSig << push;
269 havePush = false;
270 }
271 }
272
273 void DoPush(const std::vector<unsigned char>& data)
274 {
275 DoPush();
276 push = data;
277 havePush = true;
278 }
279
280 public:
281 TestBuilder(const CScript& script_, const std::string& comment_, uint32_t flags_, bool P2SH = false, WitnessMode wm = WitnessMode::NONE, int witnessversion = 0, CAmount nValue_ = 0) : script(script_), comment(comment_), flags(flags_), nValue(nValue_)
282 {
283 CScript scriptPubKey = script;
284 if (wm == WitnessMode::PKH) {
285 uint160 hash;
286 CHash160().Write(Span{script}.subspan(1)).Finalize(hash);
287 script = CScript() << OP_DUP << OP_HASH160 << ToByteVector(hash) << OP_EQUALVERIFY << OP_CHECKSIG;
288 scriptPubKey = CScript() << witnessversion << ToByteVector(hash);
289 } else if (wm == WitnessMode::SH) {
290 witscript = scriptPubKey;
291 uint256 hash;
292 CSHA256().Write(witscript.data(), witscript.size()).Finalize(hash.begin());
293 scriptPubKey = CScript() << witnessversion << ToByteVector(hash);
294 }
295 if (P2SH) {
296 redeemscript = scriptPubKey;
297 scriptPubKey = CScript() << OP_HASH160 << ToByteVector(CScriptID(redeemscript)) << OP_EQUAL;
298 }
299 creditTx = MakeTransactionRef(BuildCreditingTransaction(scriptPubKey, nValue));
300 spendTx = BuildSpendingTransaction(CScript(), CScriptWitness(), *creditTx);
301 }
302
303 TestBuilder& ScriptError(ScriptError_t err)
304 {
305 scriptError = err;
306 return *this;
307 }
308
309 TestBuilder& Opcode(const opcodetype& _op)
310 {
311 DoPush();
312 spendTx.vin[0].scriptSig << _op;
313 return *this;
314 }
315
316 TestBuilder& Num(int num)
317 {
318 DoPush();
319 spendTx.vin[0].scriptSig << num;
320 return *this;
321 }
322
323 TestBuilder& Push(const std::string& hex)
324 {
325 DoPush(ParseHex(hex));
326 return *this;
327 }
328
329 TestBuilder& Push(const CScript& _script)
330 {
331 DoPush(std::vector<unsigned char>(_script.begin(), _script.end()));
332 return *this;
333 }
334
335 TestBuilder& PushSig(const CKey& key, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32, SigVersion sigversion = SigVersion::BASE, CAmount amount = 0)
336 {
337 uint256 hash = SignatureHash(script, spendTx, 0, nHashType, amount, sigversion);
338 std::vector<unsigned char> vchSig, r, s;
339 uint32_t iter = 0;
340 do {
341 key.Sign(hash, vchSig, false, iter++);
342 if ((lenS == 33) != (vchSig[5 + vchSig[3]] == 33)) {
343 NegateSignatureS(vchSig);
344 }
345 r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);
346 s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);
347 } while (lenR != r.size() || lenS != s.size());
348 vchSig.push_back(static_cast<unsigned char>(nHashType));
349 DoPush(vchSig);
350 return *this;
351 }
352
353 TestBuilder& PushWitSig(const CKey& key, CAmount amount = -1, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32, SigVersion sigversion = SigVersion::WITNESS_V0)
354 {
355 if (amount == -1)
356 amount = nValue;
357 return PushSig(key, nHashType, lenR, lenS, sigversion, amount).AsWit();
358 }
359
360 TestBuilder& Push(const CPubKey& pubkey)
361 {
362 DoPush(std::vector<unsigned char>(pubkey.begin(), pubkey.end()));
363 return *this;
364 }
365
366 TestBuilder& PushRedeem()
367 {
368 DoPush(std::vector<unsigned char>(redeemscript.begin(), redeemscript.end()));
369 return *this;
370 }
371
372 TestBuilder& PushWitRedeem()
373 {
374 DoPush(std::vector<unsigned char>(witscript.begin(), witscript.end()));
375 return AsWit();
376 }
377
378 TestBuilder& EditPush(unsigned int pos, const std::string& hexin, const std::string& hexout)
379 {
380 assert(havePush);
381 std::vector<unsigned char> datain = ParseHex(hexin);
382 std::vector<unsigned char> dataout = ParseHex(hexout);
383 assert(pos + datain.size() <= push.size());
384 BOOST_CHECK_MESSAGE(std::vector<unsigned char>(push.begin() + pos, push.begin() + pos + datain.size()) == datain, comment);
385 push.erase(push.begin() + pos, push.begin() + pos + datain.size());
386 push.insert(push.begin() + pos, dataout.begin(), dataout.end());
387 return *this;
388 }
389
390 TestBuilder& DamagePush(unsigned int pos)
391 {
392 assert(havePush);
393 assert(pos < push.size());
394 push[pos] ^= 1;
395 return *this;
396 }
397
398 TestBuilder& Test(ScriptTest& test)
399 {
400 TestBuilder copy = *this; // Make a copy so we can rollback the push.
401 DoPush();
402 test.DoTest(creditTx->vout[0].scriptPubKey, spendTx.vin[0].scriptSig, scriptWitness, flags, comment, scriptError, nValue);
403 *this = copy;
404 return *this;
405 }
406
407 TestBuilder& AsWit()
408 {
409 assert(havePush);
410 scriptWitness.stack.push_back(push);
411 havePush = false;
412 return *this;
413 }
414
415 UniValue GetJSON()
416 {
417 DoPush();
418 UniValue array(UniValue::VARR);
419 if (!scriptWitness.stack.empty()) {
420 UniValue wit(UniValue::VARR);
421 for (unsigned i = 0; i < scriptWitness.stack.size(); i++) {
422 wit.push_back(HexStr(scriptWitness.stack[i]));
423 }
424 wit.push_back(ValueFromAmount(nValue));
425 array.push_back(std::move(wit));
426 }
427 array.push_back(FormatScript(spendTx.vin[0].scriptSig));
428 array.push_back(FormatScript(creditTx->vout[0].scriptPubKey));
429 array.push_back(FormatScriptFlags(flags));
430 array.push_back(FormatScriptError((ScriptError_t)scriptError));
431 array.push_back(comment);
432 return array;
433 }
434
435 std::string GetComment() const
436 {
437 return comment;
438 }
439 };
440
441 std::string JSONPrettyPrint(const UniValue& univalue)
442 {
443 std::string ret = univalue.write(4);
444 // Workaround for libunivalue pretty printer, which puts a space between commas and newlines
445 size_t pos = 0;
446 while ((pos = ret.find(" \n", pos)) != std::string::npos) {
447 ret.replace(pos, 2, "\n");
448 pos++;
449 }
450 return ret;
451 }
452 } // namespace
453
454 BOOST_FIXTURE_TEST_SUITE(script_tests, ScriptTest)
455
456 BOOST_AUTO_TEST_CASE(script_build)
457 {
458 const KeyData keys;
459
460 std::vector<TestBuilder> tests;
461
462 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
463 "P2PK", 0
464 ).PushSig(keys.key0));
465 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
466 "P2PK, bad sig", 0
467 ).PushSig(keys.key0).DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE));
468
469 tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
470 "P2PKH", 0
471 ).PushSig(keys.key1).Push(keys.pubkey1C));
472 tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey2C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
473 "P2PKH, bad pubkey", 0
474 ).PushSig(keys.key2).Push(keys.pubkey2C).DamagePush(5).ScriptError(SCRIPT_ERR_EQUALVERIFY));
475
476 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
477 "P2PK anyonecanpay", 0
478 ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY));
479 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
480 "P2PK anyonecanpay marked with normal hashtype", 0
481 ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY).EditPush(70, "81", "01").ScriptError(SCRIPT_ERR_EVAL_FALSE));
482
483 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
484 "P2SH(P2PK)", SCRIPT_VERIFY_P2SH, true
485 ).PushSig(keys.key0).PushRedeem());
486 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
487 "P2SH(P2PK), bad redeemscript", SCRIPT_VERIFY_P2SH, true
488 ).PushSig(keys.key0).PushRedeem().DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE));
489
490 tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey0.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
491 "P2SH(P2PKH)", SCRIPT_VERIFY_P2SH, true
492 ).PushSig(keys.key0).Push(keys.pubkey0).PushRedeem());
493 tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
494 "P2SH(P2PKH), bad sig but no VERIFY_P2SH", 0, true
495 ).PushSig(keys.key0).DamagePush(10).PushRedeem());
496 tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
497 "P2SH(P2PKH), bad sig", SCRIPT_VERIFY_P2SH, true
498 ).PushSig(keys.key0).DamagePush(10).PushRedeem().ScriptError(SCRIPT_ERR_EQUALVERIFY));
499
500 tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
501 "3-of-3", 0
502 ).Num(0).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
503 tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
504 "3-of-3, 2 sigs", 0
505 ).Num(0).PushSig(keys.key0).PushSig(keys.key1).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
506
507 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
508 "P2SH(2-of-3)", SCRIPT_VERIFY_P2SH, true
509 ).Num(0).PushSig(keys.key1).PushSig(keys.key2).PushRedeem());
510 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
511 "P2SH(2-of-3), 1 sig", SCRIPT_VERIFY_P2SH, true
512 ).Num(0).PushSig(keys.key1).Num(0).PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
513
514 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
515 "P2PK with too much R padding but no DERSIG", 0
516 ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000"));
517 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
518 "P2PK with too much R padding", SCRIPT_VERIFY_DERSIG
519 ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER));
520 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
521 "P2PK with too much S padding but no DERSIG", 0
522 ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100"));
523 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
524 "P2PK with too much S padding", SCRIPT_VERIFY_DERSIG
525 ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100").ScriptError(SCRIPT_ERR_SIG_DER));
526 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
527 "P2PK with too little R padding but no DERSIG", 0
528 ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
529 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
530 "P2PK with too little R padding", SCRIPT_VERIFY_DERSIG
531 ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
532 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
533 "P2PK NOT with bad sig with too much R padding but no DERSIG", 0
534 ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10));
535 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
536 "P2PK NOT with bad sig with too much R padding", SCRIPT_VERIFY_DERSIG
537 ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10).ScriptError(SCRIPT_ERR_SIG_DER));
538 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
539 "P2PK NOT with too much R padding but no DERSIG", 0
540 ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_EVAL_FALSE));
541 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
542 "P2PK NOT with too much R padding", SCRIPT_VERIFY_DERSIG
543 ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER));
544
545 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
546 "BIP66 example 1, without DERSIG", 0
547 ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
548 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
549 "BIP66 example 1, with DERSIG", SCRIPT_VERIFY_DERSIG
550 ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
551 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
552 "BIP66 example 2, without DERSIG", 0
553 ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE));
554 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
555 "BIP66 example 2, with DERSIG", SCRIPT_VERIFY_DERSIG
556 ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
557 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
558 "BIP66 example 3, without DERSIG", 0
559 ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
560 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
561 "BIP66 example 3, with DERSIG", SCRIPT_VERIFY_DERSIG
562 ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
563 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
564 "BIP66 example 4, without DERSIG", 0
565 ).Num(0));
566 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
567 "BIP66 example 4, with DERSIG", SCRIPT_VERIFY_DERSIG
568 ).Num(0));
569 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
570 "BIP66 example 5, without DERSIG", 0
571 ).Num(1).ScriptError(SCRIPT_ERR_EVAL_FALSE));
572 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
573 "BIP66 example 5, with DERSIG", SCRIPT_VERIFY_DERSIG
574 ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER));
575 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
576 "BIP66 example 6, without DERSIG", 0
577 ).Num(1));
578 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
579 "BIP66 example 6, with DERSIG", SCRIPT_VERIFY_DERSIG
580 ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER));
581 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
582 "BIP66 example 7, without DERSIG", 0
583 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2));
584 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
585 "BIP66 example 7, with DERSIG", SCRIPT_VERIFY_DERSIG
586 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER));
587 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
588 "BIP66 example 8, without DERSIG", 0
589 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_EVAL_FALSE));
590 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
591 "BIP66 example 8, with DERSIG", SCRIPT_VERIFY_DERSIG
592 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER));
593 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
594 "BIP66 example 9, without DERSIG", 0
595 ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE));
596 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
597 "BIP66 example 9, with DERSIG", SCRIPT_VERIFY_DERSIG
598 ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
599 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
600 "BIP66 example 10, without DERSIG", 0
601 ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
602 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
603 "BIP66 example 10, with DERSIG", SCRIPT_VERIFY_DERSIG
604 ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
605 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
606 "BIP66 example 11, without DERSIG", 0
607 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
608 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
609 "BIP66 example 11, with DERSIG", SCRIPT_VERIFY_DERSIG
610 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
611 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
612 "BIP66 example 12, without DERSIG", 0
613 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
614 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
615 "BIP66 example 12, with DERSIG", SCRIPT_VERIFY_DERSIG
616 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
617 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
618 "P2PK with multi-byte hashtype, without DERSIG", 0
619 ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101"));
620 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
621 "P2PK with multi-byte hashtype, with DERSIG", SCRIPT_VERIFY_DERSIG
622 ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101").ScriptError(SCRIPT_ERR_SIG_DER));
623
624 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
625 "P2PK with high S but no LOW_S", 0
626 ).PushSig(keys.key2, SIGHASH_ALL, 32, 33));
627 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
628 "P2PK with high S", SCRIPT_VERIFY_LOW_S
629 ).PushSig(keys.key2, SIGHASH_ALL, 32, 33).ScriptError(SCRIPT_ERR_SIG_HIGH_S));
630
631 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,
632 "P2PK with hybrid pubkey but no STRICTENC", 0
633 ).PushSig(keys.key0, SIGHASH_ALL));
634 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,
635 "P2PK with hybrid pubkey", SCRIPT_VERIFY_STRICTENC
636 ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
637 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
638 "P2PK NOT with hybrid pubkey but no STRICTENC", 0
639 ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_EVAL_FALSE));
640 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
641 "P2PK NOT with hybrid pubkey", SCRIPT_VERIFY_STRICTENC
642 ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
643 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
644 "P2PK NOT with invalid hybrid pubkey but no STRICTENC", 0
645 ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10));
646 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
647 "P2PK NOT with invalid hybrid pubkey", SCRIPT_VERIFY_STRICTENC
648 ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
649 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
650 "1-of-2 with the second 1 hybrid pubkey and no STRICTENC", 0
651 ).Num(0).PushSig(keys.key1, SIGHASH_ALL));
652 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
653 "1-of-2 with the second 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC
654 ).Num(0).PushSig(keys.key1, SIGHASH_ALL));
655 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0H) << OP_2 << OP_CHECKMULTISIG,
656 "1-of-2 with the first 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC
657 ).Num(0).PushSig(keys.key1, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
658
659 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
660 "P2PK with undefined hashtype but no STRICTENC", 0
661 ).PushSig(keys.key1, 5));
662 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
663 "P2PK with undefined hashtype", SCRIPT_VERIFY_STRICTENC
664 ).PushSig(keys.key1, 5).ScriptError(SCRIPT_ERR_SIG_HASHTYPE));
665 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,
666 "P2PK NOT with invalid sig and undefined hashtype but no STRICTENC", 0
667 ).PushSig(keys.key1, 5).DamagePush(10));
668 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,
669 "P2PK NOT with invalid sig and undefined hashtype", SCRIPT_VERIFY_STRICTENC
670 ).PushSig(keys.key1, 5).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_HASHTYPE));
671
672 tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
673 "3-of-3 with nonzero dummy but no NULLDUMMY", 0
674 ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
675 tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
676 "3-of-3 with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY
677 ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY));
678 tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,
679 "3-of-3 NOT with invalid sig and nonzero dummy but no NULLDUMMY", 0
680 ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10));
681 tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,
682 "3-of-3 NOT with invalid sig with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY
683 ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY));
684
685 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
686 "2-of-2 with two identical keys and sigs pushed using OP_DUP but no SIGPUSHONLY", 0
687 ).Num(0).PushSig(keys.key1).Opcode(OP_DUP));
688 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
689 "2-of-2 with two identical keys and sigs pushed using OP_DUP", SCRIPT_VERIFY_SIGPUSHONLY
690 ).Num(0).PushSig(keys.key1).Opcode(OP_DUP).ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
691 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
692 "P2SH(P2PK) with non-push scriptSig but no P2SH or SIGPUSHONLY", 0, true
693 ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem());
694 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
695 "P2PK with non-push scriptSig but with P2SH validation", 0
696 ).PushSig(keys.key2).Opcode(OP_NOP8));
697 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
698 "P2SH(P2PK) with non-push scriptSig but no SIGPUSHONLY", SCRIPT_VERIFY_P2SH, true
699 ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
700 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
701 "P2SH(P2PK) with non-push scriptSig but not P2SH", SCRIPT_VERIFY_SIGPUSHONLY, true
702 ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
703 tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
704 "2-of-2 with two identical keys and sigs pushed", SCRIPT_VERIFY_SIGPUSHONLY
705 ).Num(0).PushSig(keys.key1).PushSig(keys.key1));
706 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
707 "P2PK with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH
708 ).Num(11).PushSig(keys.key0));
709 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
710 "P2PK with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH
711 ).Num(11).PushSig(keys.key0).ScriptError(SCRIPT_ERR_CLEANSTACK));
712 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
713 "P2SH with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH, true
714 ).Num(11).PushSig(keys.key0).PushRedeem());
715 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
716 "P2SH with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true
717 ).Num(11).PushSig(keys.key0).PushRedeem().ScriptError(SCRIPT_ERR_CLEANSTACK));
718 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
719 "P2SH with CLEANSTACK", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true
720 ).PushSig(keys.key0).PushRedeem());
721
722 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
723 "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
724 0, 1).PushWitSig(keys.key0).PushWitRedeem());
725 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
726 "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH,
727 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit());
728 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
729 "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
730 0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
731 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
732 "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH,
733 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem());
734 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
735 "Basic P2WSH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
736 ).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
737 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
738 "Basic P2WPKH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
739 ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE));
740 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
741 "Basic P2SH(P2WSH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH
742 ).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
743 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
744 "Basic P2SH(P2WPKH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
745 ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
746 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
747 "Basic P2WSH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
748 ).PushWitSig(keys.key0).PushWitRedeem());
749 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
750 "Basic P2WPKH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
751 ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit());
752 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
753 "Basic P2SH(P2WSH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WitnessMode::SH
754 ).PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
755 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
756 "Basic P2SH(P2WPKH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
757 ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem());
758 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
759 "Basic P2WSH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
760 0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
761 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
762 "Basic P2WPKH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH,
763 0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE));
764 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
765 "Basic P2SH(P2WSH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
766 0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
767 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
768 "Basic P2SH(P2WPKH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH,
769 0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
770
771 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
772 "P2WPKH with future witness version", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH |
773 SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, false, WitnessMode::PKH, 1
774 ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM));
775 {
776 CScript witscript = CScript() << ToByteVector(keys.pubkey0);
777 uint256 hash;
778 CSHA256().Write(witscript.data(), witscript.size()).Finalize(hash.begin());
779 std::vector<unsigned char> hashBytes = ToByteVector(hash);
780 hashBytes.pop_back();
781 tests.push_back(TestBuilder(CScript() << OP_0 << hashBytes,
782 "P2WPKH with wrong witness program length", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false
783 ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH));
784 }
785 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
786 "P2WSH with empty witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
787 ).ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY));
788 {
789 CScript witscript = CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG;
790 tests.push_back(TestBuilder(witscript,
791 "P2WSH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
792 ).PushWitSig(keys.key0).Push(witscript).DamagePush(0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH));
793 }
794 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
795 "P2WPKH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
796 ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH));
797 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
798 "P2WPKH with non-empty scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
799 ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Num(11).ScriptError(SCRIPT_ERR_WITNESS_MALLEATED));
800 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
801 "P2SH(P2WPKH) with superfluous push in scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
802 ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().Num(11).PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_MALLEATED_P2SH));
803 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
804 "P2PK with witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH
805 ).PushSig(keys.key0).Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_UNEXPECTED));
806
807 // Compressed keys should pass SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
808 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
809 "Basic P2WSH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
810 0, 1).PushWitSig(keys.key0C).PushWitRedeem());
811 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C),
812 "Basic P2WPKH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::PKH,
813 0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit());
814 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
815 "Basic P2SH(P2WSH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
816 0, 1).PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
817 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C),
818 "Basic P2SH(P2WPKH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::PKH,
819 0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit().PushRedeem());
820
821 // Testing uncompressed key in witness with SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
822 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
823 "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
824 0, 1).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
825 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
826 "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::PKH,
827 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
828 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
829 "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
830 0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
831 tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
832 "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::PKH,
833 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
834
835 // P2WSH 1-of-2 multisig with compressed keys
836 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
837 "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
838 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
839 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
840 "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
841 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
842 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
843 "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
844 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem());
845 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
846 "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
847 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem());
848
849 // P2WSH 1-of-2 multisig with first key uncompressed
850 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
851 "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
852 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem());
853 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
854 "P2SH(P2WSH) CHECKMULTISIG first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
855 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
856 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
857 "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
858 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
859 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
860 "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
861 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
862 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
863 "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
864 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem());
865 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
866 "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
867 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem());
868 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
869 "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
870 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
871 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
872 "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
873 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
874 // P2WSH 1-of-2 multisig with second key uncompressed
875 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
876 "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
877 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
878 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
879 "P2SH(P2WSH) CHECKMULTISIG second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
880 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
881 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
882 "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key should pass as the uncompressed key is not used", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
883 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
884 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
885 "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the first key should pass as the uncompressed key is not used", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
886 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
887 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
888 "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
889 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem());
890 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
891 "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
892 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem());
893 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
894 "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
895 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
896 tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
897 "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
898 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
899
900 std::set<std::string> tests_set;
901
902 {
903 UniValue json_tests = read_json(json_tests::script_tests);
904
905 for (unsigned int idx = 0; idx < json_tests.size(); idx++) {
906 const UniValue& tv = json_tests[idx];
907 tests_set.insert(JSONPrettyPrint(tv.get_array()));
908 }
909 }
910
911 #ifdef UPDATE_JSON_TESTS
912 std::string strGen;
913 #endif
914 for (TestBuilder& test : tests) {
915 test.Test(*this);
916 std::string str = JSONPrettyPrint(test.GetJSON());
917 #ifdef UPDATE_JSON_TESTS
918 strGen += str + ",\n";
919 #else
920 if (tests_set.count(str) == 0) {
921 BOOST_CHECK_MESSAGE(false, "Missing auto script_valid test: " + test.GetComment());
922 }
923 #endif
924 }
925
926 #ifdef UPDATE_JSON_TESTS
927 FILE* file = fsbridge::fopen("script_tests.json.gen", "w");
928 fputs(strGen.c_str(), file);
929 fclose(file);
930 #endif
931 }
932
933 BOOST_AUTO_TEST_CASE(script_json_test)
934 {
935 // Read tests from test/data/script_tests.json
936 // Format is an array of arrays
937 // Inner arrays are [ ["wit"..., nValue]?, "scriptSig", "scriptPubKey", "flags", "expected_scripterror" ]
938 // ... where scriptSig and scriptPubKey are stringified
939 // scripts.
940 // If a witness is given, then the last value in the array should be the
941 // amount (nValue) to use in the crediting tx
942 UniValue tests = read_json(json_tests::script_tests);
943
944 for (unsigned int idx = 0; idx < tests.size(); idx++) {
945 const UniValue& test = tests[idx];
946 std::string strTest = test.write();
947 CScriptWitness witness;
948 CAmount nValue = 0;
949 unsigned int pos = 0;
950 if (test.size() > 0 && test[pos].isArray()) {
951 unsigned int i=0;
952 for (i = 0; i < test[pos].size()-1; i++) {
953 witness.stack.push_back(ParseHex(test[pos][i].get_str()));
954 }
955 nValue = AmountFromValue(test[pos][i]);
956 pos++;
957 }
958 if (test.size() < 4 + pos) // Allow size > 3; extra stuff ignored (useful for comments)
959 {
960 if (test.size() != 1) {
961 BOOST_ERROR("Bad test: " << strTest);
962 }
963 continue;
964 }
965 std::string scriptSigString = test[pos++].get_str();
966 CScript scriptSig = ParseScript(scriptSigString);
967 std::string scriptPubKeyString = test[pos++].get_str();
968 CScript scriptPubKey = ParseScript(scriptPubKeyString);
969 unsigned int scriptflags = ParseScriptFlags(test[pos++].get_str());
970 int scriptError = ParseScriptError(test[pos++].get_str());
971
972 DoTest(scriptPubKey, scriptSig, witness, scriptflags, strTest, scriptError, nValue);
973 }
974 }
975
976 BOOST_AUTO_TEST_CASE(script_PushData)
977 {
978 // Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on
979 // the stack as the 1-75 opcodes do.
980 static const unsigned char direct[] = { 1, 0x5a };
981 static const unsigned char pushdata1[] = { OP_PUSHDATA1, 1, 0x5a };
982 static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a };
983 static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a };
984
985 ScriptError err;
986 std::vector<std::vector<unsigned char> > directStack;
987 BOOST_CHECK(EvalScript(directStack, CScript(direct, direct + sizeof(direct)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
988 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
989
990 std::vector<std::vector<unsigned char> > pushdata1Stack;
991 BOOST_CHECK(EvalScript(pushdata1Stack, CScript(pushdata1, pushdata1 + sizeof(pushdata1)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
992 BOOST_CHECK(pushdata1Stack == directStack);
993 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
994
995 std::vector<std::vector<unsigned char> > pushdata2Stack;
996 BOOST_CHECK(EvalScript(pushdata2Stack, CScript(pushdata2, pushdata2 + sizeof(pushdata2)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
997 BOOST_CHECK(pushdata2Stack == directStack);
998 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
999
1000 std::vector<std::vector<unsigned char> > pushdata4Stack;
1001 BOOST_CHECK(EvalScript(pushdata4Stack, CScript(pushdata4, pushdata4 + sizeof(pushdata4)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1002 BOOST_CHECK(pushdata4Stack == directStack);
1003 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1004
1005 const std::vector<unsigned char> pushdata1_trunc{OP_PUSHDATA1, 1};
1006 const std::vector<unsigned char> pushdata2_trunc{OP_PUSHDATA2, 1, 0};
1007 const std::vector<unsigned char> pushdata4_trunc{OP_PUSHDATA4, 1, 0, 0, 0};
1008
1009 std::vector<std::vector<unsigned char>> stack_ignore;
1010 BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata1_trunc.begin(), pushdata1_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1011 BOOST_CHECK_EQUAL(err, SCRIPT_ERR_BAD_OPCODE);
1012 BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata2_trunc.begin(), pushdata2_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1013 BOOST_CHECK_EQUAL(err, SCRIPT_ERR_BAD_OPCODE);
1014 BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata4_trunc.begin(), pushdata4_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1015 BOOST_CHECK_EQUAL(err, SCRIPT_ERR_BAD_OPCODE);
1016 }
1017
1018 BOOST_AUTO_TEST_CASE(script_cltv_truncated)
1019 {
1020 const auto script_cltv_trunc = CScript() << OP_CHECKLOCKTIMEVERIFY;
1021
1022 std::vector<std::vector<unsigned char>> stack_ignore;
1023 ScriptError err;
1024 BOOST_CHECK(!EvalScript(stack_ignore, script_cltv_trunc, SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY, BaseSignatureChecker(), SigVersion::BASE, &err));
1025 BOOST_CHECK_EQUAL(err, SCRIPT_ERR_INVALID_STACK_OPERATION);
1026 }
1027
1028 static CScript
1029 sign_multisig(const CScript& scriptPubKey, const std::vector<CKey>& keys, const CTransaction& transaction)
1030 {
1031 uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL, 0, SigVersion::BASE);
1032
1033 CScript result;
1034 //
1035 // NOTE: CHECKMULTISIG has an unfortunate bug; it requires
1036 // one extra item on the stack, before the signatures.
1037 // Putting OP_0 on the stack is the workaround;
1038 // fixing the bug would mean splitting the block chain (old
1039 // clients would not accept new CHECKMULTISIG transactions,
1040 // and vice-versa)
1041 //
1042 result << OP_0;
1043 for (const CKey &key : keys)
1044 {
1045 std::vector<unsigned char> vchSig;
1046 BOOST_CHECK(key.Sign(hash, vchSig));
1047 vchSig.push_back((unsigned char)SIGHASH_ALL);
1048 result << vchSig;
1049 }
1050 return result;
1051 }
1052 static CScript
1053 sign_multisig(const CScript& scriptPubKey, const CKey& key, const CTransaction& transaction)
1054 {
1055 std::vector<CKey> keys;
1056 keys.push_back(key);
1057 return sign_multisig(scriptPubKey, keys, transaction);
1058 }
1059
1060 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)
1061 {
1062 ScriptError err;
1063 CKey key1 = GenerateRandomKey();
1064 CKey key2 = GenerateRandomKey(/*compressed=*/false);
1065 CKey key3 = GenerateRandomKey();
1066
1067 CScript scriptPubKey12;
1068 scriptPubKey12 << OP_1 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
1069
1070 const CTransaction txFrom12{BuildCreditingTransaction(scriptPubKey12)};
1071 CMutableTransaction txTo12 = BuildSpendingTransaction(CScript(), CScriptWitness(), txFrom12);
1072
1073 CScript goodsig1 = sign_multisig(scriptPubKey12, key1, CTransaction(txTo12));
1074 BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1075 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1076 txTo12.vout[0].nValue = 2;
1077 BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1078 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1079
1080 CScript goodsig2 = sign_multisig(scriptPubKey12, key2, CTransaction(txTo12));
1081 BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1082 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1083
1084 CScript badsig1 = sign_multisig(scriptPubKey12, key3, CTransaction(txTo12));
1085 BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1086 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1087 }
1088
1089 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)
1090 {
1091 ScriptError err;
1092 CKey key1 = GenerateRandomKey();
1093 CKey key2 = GenerateRandomKey(/*compressed=*/false);
1094 CKey key3 = GenerateRandomKey();
1095 CKey key4 = GenerateRandomKey(/*compressed=*/false);
1096
1097 CScript scriptPubKey23;
1098 scriptPubKey23 << OP_2 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << ToByteVector(key3.GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
1099
1100 const CTransaction txFrom23{BuildCreditingTransaction(scriptPubKey23)};
1101 CMutableTransaction txTo23 = BuildSpendingTransaction(CScript(), CScriptWitness(), txFrom23);
1102
1103 std::vector<CKey> keys;
1104 keys.push_back(key1); keys.push_back(key2);
1105 CScript goodsig1 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1106 BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1107 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1108
1109 keys.clear();
1110 keys.push_back(key1); keys.push_back(key3);
1111 CScript goodsig2 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1112 BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1113 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1114
1115 keys.clear();
1116 keys.push_back(key2); keys.push_back(key3);
1117 CScript goodsig3 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1118 BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1119 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1120
1121 keys.clear();
1122 keys.push_back(key2); keys.push_back(key2); // Can't reuse sig
1123 CScript badsig1 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1124 BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1125 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1126
1127 keys.clear();
1128 keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order
1129 CScript badsig2 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1130 BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1131 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1132
1133 keys.clear();
1134 keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order
1135 CScript badsig3 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1136 BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1137 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1138
1139 keys.clear();
1140 keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys
1141 CScript badsig4 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1142 BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1143 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1144
1145 keys.clear();
1146 keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys
1147 CScript badsig5 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1148 BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1149 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1150
1151 keys.clear(); // Must have signatures
1152 CScript badsig6 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1153 BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1154 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err));
1155 }
1156
1157 /** Return the TxoutType of a script without exposing Solver details. */
1158 static TxoutType GetTxoutType(const CScript& output_script)
1159 {
1160 std::vector<std::vector<uint8_t>> unused;
1161 return Solver(output_script, unused);
1162 }
1163
1164 #define CHECK_SCRIPT_STATIC_SIZE(script, expected_size) \
1165 do { \
1166 BOOST_CHECK_EQUAL((script).size(), (expected_size)); \
1167 BOOST_CHECK_EQUAL((script).capacity(), CScriptBase::STATIC_SIZE); \
1168 BOOST_CHECK_EQUAL((script).allocated_memory(), 0); \
1169 } while (0)
1170
1171 #define CHECK_SCRIPT_DYNAMIC_SIZE(script, expected_size, expected_extra) \
1172 do { \
1173 BOOST_CHECK_EQUAL((script).size(), (expected_size)); \
1174 BOOST_CHECK_EQUAL((script).capacity(), (expected_extra)); \
1175 BOOST_CHECK_EQUAL((script).allocated_memory(), (expected_extra)); \
1176 } while (0)
1177
1178 BOOST_AUTO_TEST_CASE(script_size_and_capacity_test)
1179 {
1180 BOOST_CHECK_EQUAL(sizeof(CompressedScript), 40);
1181 BOOST_CHECK_EQUAL(sizeof(CScriptBase), 40);
1182 BOOST_CHECK_NE(sizeof(CScriptBase), sizeof(prevector<CScriptBase::STATIC_SIZE + 1, uint8_t>)); // CScriptBase size should be set to avoid wasting space in padding
1183 BOOST_CHECK_EQUAL(sizeof(CScript), 40);
1184 BOOST_CHECK_EQUAL(sizeof(CTxOut), 64);
1185
1186 CKey dummy_key;
1187 dummy_key.MakeNewKey(/*fCompressed=*/true);
1188 const CPubKey dummy_pubkey{dummy_key.GetPubKey()};
1189
1190 // Small OP_RETURN has direct allocation
1191 {
1192 const auto script{CScript() << OP_RETURN << std::vector<uint8_t>(10, 0xaa)};
1193 BOOST_CHECK_EQUAL(GetTxoutType(script), TxoutType::NULL_DATA);
1194 CHECK_SCRIPT_STATIC_SIZE(script, 12);
1195 }
1196
1197 // P2WPKH has direct allocation
1198 {
1199 const auto script{GetScriptForDestination(WitnessV0KeyHash{PKHash{dummy_pubkey}})};
1200 BOOST_CHECK_EQUAL(GetTxoutType(script), TxoutType::WITNESS_V0_KEYHASH);
1201 CHECK_SCRIPT_STATIC_SIZE(script, 22);
1202 }
1203
1204 // P2SH has direct allocation
1205 {
1206 const auto script{GetScriptForDestination(ScriptHash{CScript{} << OP_TRUE})};
1207 BOOST_CHECK(script.IsPayToScriptHash());
1208 CHECK_SCRIPT_STATIC_SIZE(script, 23);
1209 }
1210
1211 // P2PKH has direct allocation
1212 {
1213 const auto script{GetScriptForDestination(PKHash{dummy_pubkey})};
1214 BOOST_CHECK_EQUAL(GetTxoutType(script), TxoutType::PUBKEYHASH);
1215 CHECK_SCRIPT_STATIC_SIZE(script, 25);
1216 }
1217
1218 // P2WSH has direct allocation
1219 {
1220 const auto script{GetScriptForDestination(WitnessV0ScriptHash{CScript{} << OP_TRUE})};
1221 BOOST_CHECK(script.IsPayToWitnessScriptHash());
1222 CHECK_SCRIPT_STATIC_SIZE(script, 34);
1223 }
1224
1225 // P2TR has direct allocation
1226 {
1227 const auto script{GetScriptForDestination(WitnessV1Taproot{XOnlyPubKey{dummy_pubkey}})};
1228 BOOST_CHECK_EQUAL(GetTxoutType(script), TxoutType::WITNESS_V1_TAPROOT);
1229 CHECK_SCRIPT_STATIC_SIZE(script, 34);
1230 }
1231
1232 // Compressed P2PK has direct allocation
1233 {
1234 const auto script{GetScriptForRawPubKey(dummy_pubkey)};
1235 BOOST_CHECK_EQUAL(GetTxoutType(script), TxoutType::PUBKEY);
1236 CHECK_SCRIPT_STATIC_SIZE(script, 35);
1237 }
1238
1239 // Uncompressed P2PK needs extra allocation
1240 {
1241 CKey uncompressed_key;
1242 uncompressed_key.MakeNewKey(/*fCompressed=*/false);
1243 const CPubKey uncompressed_pubkey{uncompressed_key.GetPubKey()};
1244
1245 const auto script{GetScriptForRawPubKey(uncompressed_pubkey)};
1246 BOOST_CHECK_EQUAL(GetTxoutType(script), TxoutType::PUBKEY);
1247 CHECK_SCRIPT_DYNAMIC_SIZE(script, 67, 67);
1248 }
1249
1250 // Bare multisig needs extra allocation
1251 {
1252 const auto script{GetScriptForMultisig(1, std::vector{2, dummy_pubkey})};
1253 BOOST_CHECK_EQUAL(GetTxoutType(script), TxoutType::MULTISIG);
1254 CHECK_SCRIPT_DYNAMIC_SIZE(script, 71, 103);
1255 }
1256 }
1257
1258 /* Wrapper around ProduceSignature to combine two scriptsigs */
1259 SignatureData CombineSignatures(const CTxOut& txout, const CMutableTransaction& tx, const SignatureData& scriptSig1, const SignatureData& scriptSig2)
1260 {
1261 SignatureData data;
1262 data.MergeSignatureData(scriptSig1);
1263 data.MergeSignatureData(scriptSig2);
1264 ProduceSignature(DUMMY_SIGNING_PROVIDER, MutableTransactionSignatureCreator(tx, 0, txout.nValue, SIGHASH_DEFAULT), txout.scriptPubKey, data);
1265 return data;
1266 }
1267
1268 BOOST_AUTO_TEST_CASE(script_combineSigs)
1269 {
1270 // Test the ProduceSignature's ability to combine signatures function
1271 FillableSigningProvider keystore;
1272 std::vector<CKey> keys;
1273 std::vector<CPubKey> pubkeys;
1274 for (int i = 0; i < 3; i++)
1275 {
1276 CKey key = GenerateRandomKey(/*compressed=*/i%2 == 1);
1277 keys.push_back(key);
1278 pubkeys.push_back(key.GetPubKey());
1279 BOOST_CHECK(keystore.AddKey(key));
1280 }
1281
1282 CMutableTransaction txFrom = BuildCreditingTransaction(GetScriptForDestination(PKHash(keys[0].GetPubKey())));
1283 CMutableTransaction txTo = BuildSpendingTransaction(CScript(), CScriptWitness(), CTransaction(txFrom));
1284 CScript& scriptPubKey = txFrom.vout[0].scriptPubKey;
1285 SignatureData scriptSig;
1286
1287 SignatureData empty;
1288 SignatureData combined = CombineSignatures(txFrom.vout[0], txTo, empty, empty);
1289 BOOST_CHECK(combined.scriptSig.empty());
1290
1291 // Single signature case:
1292 SignatureData dummy;
1293 BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy)); // changes scriptSig
1294 scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1295 combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
1296 BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1297 combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
1298 BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1299 SignatureData scriptSigCopy = scriptSig;
1300 // Signing again will give a different, valid signature:
1301 SignatureData dummy_b;
1302 BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_b));
1303 scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1304 combined = CombineSignatures(txFrom.vout[0], txTo, scriptSigCopy, scriptSig);
1305 BOOST_CHECK(combined.scriptSig == scriptSigCopy.scriptSig || combined.scriptSig == scriptSig.scriptSig);
1306
1307 // P2SH, single-signature case:
1308 CScript pkSingle; pkSingle << ToByteVector(keys[0].GetPubKey()) << OP_CHECKSIG;
1309 BOOST_CHECK(keystore.AddCScript(pkSingle));
1310 scriptPubKey = GetScriptForDestination(ScriptHash(pkSingle));
1311 SignatureData dummy_c;
1312 BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_c));
1313 scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1314 combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
1315 BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1316 combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
1317 BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1318 scriptSigCopy = scriptSig;
1319 SignatureData dummy_d;
1320 BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_d));
1321 scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1322 combined = CombineSignatures(txFrom.vout[0], txTo, scriptSigCopy, scriptSig);
1323 BOOST_CHECK(combined.scriptSig == scriptSigCopy.scriptSig || combined.scriptSig == scriptSig.scriptSig);
1324
1325 // Hardest case: Multisig 2-of-3
1326 scriptPubKey = GetScriptForMultisig(2, pubkeys);
1327 BOOST_CHECK(keystore.AddCScript(scriptPubKey));
1328 SignatureData dummy_e;
1329 BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_e));
1330 scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1331 combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
1332 BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1333 combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
1334 BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1335
1336 // A couple of partially-signed versions:
1337 std::vector<unsigned char> sig1;
1338 uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL, 0, SigVersion::BASE);
1339 BOOST_CHECK(keys[0].Sign(hash1, sig1));
1340 sig1.push_back(SIGHASH_ALL);
1341 std::vector<unsigned char> sig2;
1342 uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE, 0, SigVersion::BASE);
1343 BOOST_CHECK(keys[1].Sign(hash2, sig2));
1344 sig2.push_back(SIGHASH_NONE);
1345 std::vector<unsigned char> sig3;
1346 uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE, 0, SigVersion::BASE);
1347 BOOST_CHECK(keys[2].Sign(hash3, sig3));
1348 sig3.push_back(SIGHASH_SINGLE);
1349
1350 // Not fussy about order (or even existence) of placeholders or signatures:
1351 CScript partial1a = CScript() << OP_0 << sig1 << OP_0;
1352 CScript partial1b = CScript() << OP_0 << OP_0 << sig1;
1353 CScript partial2a = CScript() << OP_0 << sig2;
1354 CScript partial2b = CScript() << sig2 << OP_0;
1355 CScript partial3a = CScript() << sig3;
1356 CScript partial3b = CScript() << OP_0 << OP_0 << sig3;
1357 CScript partial3c = CScript() << OP_0 << sig3 << OP_0;
1358 CScript complete12 = CScript() << OP_0 << sig1 << sig2;
1359 CScript complete13 = CScript() << OP_0 << sig1 << sig3;
1360 CScript complete23 = CScript() << OP_0 << sig2 << sig3;
1361 SignatureData partial1_sigs;
1362 partial1_sigs.signatures.emplace(keys[0].GetPubKey().GetID(), SigPair(keys[0].GetPubKey(), sig1));
1363 SignatureData partial2_sigs;
1364 partial2_sigs.signatures.emplace(keys[1].GetPubKey().GetID(), SigPair(keys[1].GetPubKey(), sig2));
1365 SignatureData partial3_sigs;
1366 partial3_sigs.signatures.emplace(keys[2].GetPubKey().GetID(), SigPair(keys[2].GetPubKey(), sig3));
1367
1368 combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial1_sigs);
1369 BOOST_CHECK(combined.scriptSig == partial1a);
1370 combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial2_sigs);
1371 BOOST_CHECK(combined.scriptSig == complete12);
1372 combined = CombineSignatures(txFrom.vout[0], txTo, partial2_sigs, partial1_sigs);
1373 BOOST_CHECK(combined.scriptSig == complete12);
1374 combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial2_sigs);
1375 BOOST_CHECK(combined.scriptSig == complete12);
1376 combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial1_sigs);
1377 BOOST_CHECK(combined.scriptSig == complete13);
1378 combined = CombineSignatures(txFrom.vout[0], txTo, partial2_sigs, partial3_sigs);
1379 BOOST_CHECK(combined.scriptSig == complete23);
1380 combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial2_sigs);
1381 BOOST_CHECK(combined.scriptSig == complete23);
1382 combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial3_sigs);
1383 BOOST_CHECK(combined.scriptSig == partial3c);
1384 }
1385
1386 /**
1387 * Reproduction of an exception incorrectly raised when parsing a public key inside a TapMiniscript.
1388 */
1389 BOOST_AUTO_TEST_CASE(sign_invalid_miniscript)
1390 {
1391 FillableSigningProvider keystore;
1392 SignatureData sig_data;
1393 CMutableTransaction prev, curr;
1394
1395 // Create a Taproot output which contains a leaf in which a non-32 bytes push is used where a public key is expected
1396 // by the Miniscript parser. This offending Script was found by the RPC fuzzer.
1397 const auto invalid_pubkey{"173d36c8c9c9c9ffffffffffff0200000000021e1e37373721361818181818181e1e1e1e19000000000000000000b19292929292926b006c9b9b9292"_hex_u8};
1398 TaprootBuilder builder;
1399 builder.Add(0, {invalid_pubkey}, 0xc0);
1400 builder.Finalize(XOnlyPubKey::NUMS_H);
1401 prev.vout.emplace_back(0, GetScriptForDestination(builder.GetOutput()));
1402 curr.vin.emplace_back(COutPoint{prev.GetHash(), 0});
1403 sig_data.tr_spenddata = builder.GetSpendData();
1404
1405 // SignSignature can fail but it shouldn't raise an exception (nor crash).
1406 BOOST_CHECK(!SignSignature(keystore, CTransaction(prev), curr, 0, SIGHASH_ALL, sig_data));
1407 }
1408
1409 /* P2A input should be considered signed. */
1410 BOOST_AUTO_TEST_CASE(sign_paytoanchor)
1411 {
1412 FillableSigningProvider keystore;
1413 SignatureData sig_data;
1414 CMutableTransaction prev, curr;
1415 prev.vout.emplace_back(0, GetScriptForDestination(PayToAnchor{}));
1416
1417 curr.vin.emplace_back(COutPoint{prev.GetHash(), 0});
1418
1419 BOOST_CHECK(SignSignature(keystore, CTransaction(prev), curr, 0, SIGHASH_ALL, sig_data));
1420 }
1421
1422 BOOST_AUTO_TEST_CASE(script_standard_push)
1423 {
1424 ScriptError err;
1425 for (int i=0; i<67000; i++) {
1426 CScript script;
1427 script << i;
1428 BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Number " << i << " is not pure push.");
1429 BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Number " << i << " push is not minimal data.");
1430 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1431 }
1432
1433 for (unsigned int i=0; i<=MAX_SCRIPT_ELEMENT_SIZE; i++) {
1434 std::vector<unsigned char> data(i, '\111');
1435 CScript script;
1436 script << data;
1437 BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Length " << i << " is not pure push.");
1438 BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Length " << i << " push is not minimal data.");
1439 BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1440 }
1441 }
1442
1443 BOOST_AUTO_TEST_CASE(script_IsPushOnly_on_invalid_scripts)
1444 {
1445 // IsPushOnly returns false when given a script containing only pushes that
1446 // are invalid due to truncation. IsPushOnly() is consensus critical
1447 // because P2SH evaluation uses it, although this specific behavior should
1448 // not be consensus critical as the P2SH evaluation would fail first due to
1449 // the invalid push. Still, it doesn't hurt to test it explicitly.
1450 static const unsigned char direct[] = { 1 };
1451 BOOST_CHECK(!CScript(direct, direct+sizeof(direct)).IsPushOnly());
1452 }
1453
1454 BOOST_AUTO_TEST_CASE(script_GetScriptAsm)
1455 {
1456 BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2, true));
1457 BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY, true));
1458 BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2));
1459 BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY));
1460
1461 std::string derSig("304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c5090");
1462 std::string pubKey("03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2");
1463 std::vector<unsigned char> vchPubKey = ToByteVector(ParseHex(pubKey));
1464
1465 BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey, true));
1466 BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey, true));
1467 BOOST_CHECK_EQUAL(derSig + "[ALL] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey, true));
1468 BOOST_CHECK_EQUAL(derSig + "[NONE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey, true));
1469 BOOST_CHECK_EQUAL(derSig + "[SINGLE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey, true));
1470 BOOST_CHECK_EQUAL(derSig + "[ALL|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey, true));
1471 BOOST_CHECK_EQUAL(derSig + "[NONE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey, true));
1472 BOOST_CHECK_EQUAL(derSig + "[SINGLE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey, true));
1473
1474 BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey));
1475 BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey));
1476 BOOST_CHECK_EQUAL(derSig + "01 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey));
1477 BOOST_CHECK_EQUAL(derSig + "02 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey));
1478 BOOST_CHECK_EQUAL(derSig + "03 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey));
1479 BOOST_CHECK_EQUAL(derSig + "81 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey));
1480 BOOST_CHECK_EQUAL(derSig + "82 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey));
1481 BOOST_CHECK_EQUAL(derSig + "83 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey));
1482 }
1483
1484 template <typename T>
1485 CScript ToScript(const T& byte_container)
1486 {
1487 auto span{MakeUCharSpan(byte_container)};
1488 return {span.begin(), span.end()};
1489 }
1490
1491 static CScript ScriptFromHex(const std::string& str)
1492 {
1493 return ToScript(*Assert(TryParseHex(str)));
1494 }
1495
1496 BOOST_AUTO_TEST_CASE(script_byte_array_u8_vector_equivalence)
1497 {
1498 const CScript scriptPubKey1 = CScript() << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"_hex_v_u8 << OP_CHECKSIG;
1499 const CScript scriptPubKey2 = CScript() << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"_hex << OP_CHECKSIG;
1500 BOOST_CHECK(scriptPubKey1 == scriptPubKey2);
1501 }
1502
1503 BOOST_AUTO_TEST_CASE(script_FindAndDelete)
1504 {
1505 // Exercise the FindAndDelete functionality
1506 CScript s;
1507 CScript d;
1508 CScript expect;
1509
1510 s = CScript() << OP_1 << OP_2;
1511 d = CScript(); // delete nothing should be a no-op
1512 expect = s;
1513 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
1514 BOOST_CHECK(s == expect);
1515
1516 s = CScript() << OP_1 << OP_2 << OP_3;
1517 d = CScript() << OP_2;
1518 expect = CScript() << OP_1 << OP_3;
1519 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1520 BOOST_CHECK(s == expect);
1521
1522 s = CScript() << OP_3 << OP_1 << OP_3 << OP_3 << OP_4 << OP_3;
1523 d = CScript() << OP_3;
1524 expect = CScript() << OP_1 << OP_4;
1525 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 4);
1526 BOOST_CHECK(s == expect);
1527
1528 s = ToScript("0302ff03"_hex); // PUSH 0x02ff03 onto stack
1529 d = ToScript("0302ff03"_hex);
1530 expect = CScript();
1531 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1532 BOOST_CHECK(s == expect);
1533
1534 s = ToScript("0302ff030302ff03"_hex); // PUSH 0x02ff03 PUSH 0x02ff03
1535 d = ToScript("0302ff03"_hex);
1536 expect = CScript();
1537 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 2);
1538 BOOST_CHECK(s == expect);
1539
1540 s = ToScript("0302ff030302ff03"_hex);
1541 d = ToScript("02"_hex);
1542 expect = s; // FindAndDelete matches entire opcodes
1543 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
1544 BOOST_CHECK(s == expect);
1545
1546 s = ToScript("0302ff030302ff03"_hex);
1547 d = ToScript("ff"_hex);
1548 expect = s;
1549 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
1550 BOOST_CHECK(s == expect);
1551
1552 // This is an odd edge case: strip of the push-three-bytes
1553 // prefix, leaving 02ff03 which is push-two-bytes:
1554 s = ToScript("0302ff030302ff03"_hex);
1555 d = ToScript("03"_hex);
1556 expect = CScript() << "ff03"_hex << "ff03"_hex;
1557 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 2);
1558 BOOST_CHECK(s == expect);
1559
1560 // Byte sequence that spans multiple opcodes:
1561 s = ToScript("02feed5169"_hex); // PUSH(0xfeed) OP_1 OP_VERIFY
1562 d = ToScript("feed51"_hex);
1563 expect = s;
1564 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0); // doesn't match 'inside' opcodes
1565 BOOST_CHECK(s == expect);
1566
1567 s = ToScript("02feed5169"_hex); // PUSH(0xfeed) OP_1 OP_VERIFY
1568 d = ToScript("02feed51"_hex);
1569 expect = ToScript("69"_hex);
1570 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1571 BOOST_CHECK(s == expect);
1572
1573 s = ToScript("516902feed5169"_hex);
1574 d = ToScript("feed51"_hex);
1575 expect = s;
1576 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
1577 BOOST_CHECK(s == expect);
1578
1579 s = ToScript("516902feed5169"_hex);
1580 d = ToScript("02feed51"_hex);
1581 expect = ToScript("516969"_hex);
1582 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1583 BOOST_CHECK(s == expect);
1584
1585 s = CScript() << OP_0 << OP_0 << OP_1 << OP_1;
1586 d = CScript() << OP_0 << OP_1;
1587 expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass
1588 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1589 BOOST_CHECK(s == expect);
1590
1591 s = CScript() << OP_0 << OP_0 << OP_1 << OP_0 << OP_1 << OP_1;
1592 d = CScript() << OP_0 << OP_1;
1593 expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass
1594 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 2);
1595 BOOST_CHECK(s == expect);
1596
1597 // Another weird edge case:
1598 // End with invalid push (not enough data)...
1599 s = ToScript("0003feed"_hex);
1600 d = ToScript("03feed"_hex); // ... can remove the invalid push
1601 expect = ToScript("00"_hex);
1602 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1603 BOOST_CHECK(s == expect);
1604
1605 s = ToScript("0003feed"_hex);
1606 d = ToScript("00"_hex);
1607 expect = ToScript("03feed"_hex);
1608 BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1609 BOOST_CHECK(s == expect);
1610 }
1611
1612 BOOST_AUTO_TEST_CASE(script_HasValidOps)
1613 {
1614 // Exercise the HasValidOps functionality
1615 CScript script;
1616 script = ToScript("76a9141234567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac"_hex); // Normal script
1617 BOOST_CHECK(script.HasValidOps());
1618 script = ToScript("76a914ff34567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac"_hex);
1619 BOOST_CHECK(script.HasValidOps());
1620 script = ToScript("ff88ac"_hex); // Script with OP_INVALIDOPCODE explicit
1621 BOOST_CHECK(!script.HasValidOps());
1622 script = ToScript("88acc0"_hex); // Script with undefined opcode
1623 BOOST_CHECK(!script.HasValidOps());
1624 }
1625
1626 static std::string DatacarrierBytesStr(const CScript &script, const size_t remaining_outputs = 0) {
1627 auto dcb = script.DatacarrierBytes(remaining_outputs);
1628 return strprintf("%s+%s", dcb.first, dcb.second);
1629 }
1630
1631 BOOST_AUTO_TEST_CASE(script_DataCarrierBytes)
1632 {
1633 using zeros = std::vector<unsigned char>;
1634
1635 // empty script
1636 BOOST_CHECK_EQUAL("0+0", DatacarrierBytesStr(CScript()));
1637 // series of pushes are not data
1638 BOOST_CHECK_EQUAL("0+0", DatacarrierBytesStr(CScript() << OP_0 << OP_0 << OP_0));
1639 // unspendable if first op is OP_RETURN, then length(1), zeros(11)
1640 BOOST_CHECK_EQUAL("13+0", DatacarrierBytesStr(CScript() << OP_RETURN << zeros(11)));
1641 // invalid script (no data following PUSHDATA) makes it all data
1642 BOOST_CHECK_EQUAL("0+2", DatacarrierBytesStr(CScript() << OP_0 << OP_PUSHDATA4));
1643 // no data here
1644 BOOST_CHECK_EQUAL("0+0", DatacarrierBytesStr(CScript() << OP_TRUE << OP_IF << OP_ENDIF));
1645 // specific data pattern, entire script is data
1646 BOOST_CHECK_EQUAL("0+4", DatacarrierBytesStr(CScript() << OP_FALSE << OP_IF << OP_7 << OP_ENDIF));
1647 // consecutive data
1648 BOOST_CHECK_EQUAL("0+6", DatacarrierBytesStr(CScript() << OP_FALSE << OP_IF << OP_ENDIF << OP_FALSE << OP_IF << OP_ENDIF));
1649 // nested data (all is data)
1650 BOOST_CHECK_EQUAL("0+6", DatacarrierBytesStr(CScript() << OP_FALSE << OP_IF << OP_TRUE << OP_IF << OP_ENDIF << OP_ENDIF));
1651 // pushing then immediately dropping is data: length(1), zero(11), OP_DROP
1652 BOOST_CHECK_EQUAL("0+13", DatacarrierBytesStr(CScript() << zeros(11) << OP_DROP));
1653 // OLGA data obfuscated as p2wsh
1654 const auto olga_header = CScript() << OP_0 << "003e7374616d703a000000000000000000000000000000000000000000000000"_hex;
1655 BOOST_CHECK_EQUAL("0+82", DatacarrierBytesStr(olga_header, 2));
1656 // OLGA missing a second output is p2wsh, not OLGA
1657 BOOST_CHECK_EQUAL("0+0", DatacarrierBytesStr(olga_header, 1));
1658 // OGLA with extra outputs still is OLGA
1659 BOOST_CHECK_EQUAL("0+82", DatacarrierBytesStr(olga_header, 3));
1660 }
1661
1662 BOOST_AUTO_TEST_CASE(script_GetScriptForTransactionInput)
1663 {
1664 using zeros = std::vector<unsigned char>;
1665
1666 { // P2PK - no datacarrier bytes (tx_in doesn't matter)
1667 CScript prev_script; // scriptPubKey
1668 CTxIn tx_in;
1669 prev_script = CScript() << zeros(65) << OP_CHECKSIG;
1670 tx_in.scriptSig = CScript();
1671 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1672 BOOST_CHECK(ret_script == tx_in.scriptSig);
1673 BOOST_CHECK_EQUAL(scale, WITNESS_SCALE_FACTOR);
1674 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "0+0");
1675 }
1676 { // P2PKH - no datacarrier bytes
1677 CScript prev_script; // scriptPubKey
1678 CTxIn tx_in;
1679 prev_script = CScript() << OP_DUP << OP_HASH160 << zeros(20) << OP_EQUALVERIFY << OP_CHECKSIG;
1680 // signature, pubkey
1681 tx_in.scriptSig = CScript() << zeros(72) << zeros(33);
1682 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1683 BOOST_CHECK(ret_script == tx_in.scriptSig);
1684 BOOST_CHECK_EQUAL(scale, WITNESS_SCALE_FACTOR);
1685 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "0+0");
1686 }
1687 { // P2SH - no datacarrier bytes
1688 CScript prev_script; // scriptPubKey
1689 CTxIn tx_in;
1690 CScript redeem_script = CScript() << OP_DROP << OP_TRUE;
1691 prev_script = CScript() << OP_HASH160 << zeros(20) << OP_EQUAL;
1692 // signature, pubkey, redeem_script
1693 tx_in.scriptSig = CScript() << OP_7 << std::vector<unsigned char>(redeem_script.begin(), redeem_script.end());
1694 // this should return the redeem script
1695 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1696 BOOST_CHECK(ret_script == redeem_script);
1697 BOOST_CHECK_EQUAL(scale, WITNESS_SCALE_FACTOR);
1698 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "0+0");
1699 }
1700 { // P2SH - with datacarrier bytes
1701 CScript prev_script; // scriptPubKey
1702 CTxIn tx_in;
1703 // arbitrary amount of data (27 bytes)
1704 CScript redeem_script = CScript() << OP_RETURN << zeros(27);
1705 prev_script = CScript() << OP_HASH160 << zeros(20) << OP_EQUAL;
1706 // signature, pubkey, redeem_script
1707 tx_in.scriptSig = CScript() << OP_7 << std::vector<unsigned char>(redeem_script.begin(), redeem_script.end());
1708 // this should return the redeem script
1709 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1710 BOOST_CHECK(ret_script == redeem_script);
1711 BOOST_CHECK_EQUAL(scale, WITNESS_SCALE_FACTOR);
1712 // OP_RETURN(1), length(1), zeros(27) = 29
1713 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "29+0");
1714 }
1715 { // P2WPKH - no datacarrier bytes
1716 CScript prev_script; // scriptPubKey
1717 CTxIn tx_in;
1718 // P2WPKH is [OP_0, hash160(pubkey)]
1719 prev_script = CScript() << OP_0 << zeros(20);
1720 // segwit: empty scriptsig
1721 tx_in.scriptSig = CScript();
1722 tx_in.scriptWitness.stack.emplace_back(65); // signature
1723 tx_in.scriptWitness.stack.emplace_back(33); // pubkey
1724 // this should return the redeem script
1725 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1726 // should have no script at all since it's wrapped P2WPKH
1727 BOOST_CHECK(ret_script == CScript());
1728 BOOST_CHECK_EQUAL(scale, 0);
1729 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "0+0");
1730 }
1731 { // P2WSH - no datacarrier bytes
1732 CScript prev_script; // scriptPubKey
1733 CTxIn tx_in;
1734 prev_script = CScript() << OP_0 << zeros(32);
1735 // segwit: empty scriptsig
1736 tx_in.scriptSig = CScript();
1737 tx_in.scriptWitness.stack.emplace_back(65); // arbitrary value to satisfy redeem script
1738 CScript redeem_script = CScript() << OP_0;
1739 auto redeem_vec{std::vector<unsigned char>(redeem_script.begin(), redeem_script.end())};
1740 tx_in.scriptWitness.stack.push_back(redeem_vec);
1741 // this should return the redeem script
1742 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1743 BOOST_CHECK(ret_script == redeem_script);
1744 BOOST_CHECK_EQUAL(scale, 1);
1745 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "0+0");
1746 }
1747 { // P2WSH - some datacarrier bytes
1748 CScript prev_script; // scriptPubKey
1749 CTxIn tx_in;
1750 prev_script = CScript() << OP_0 << zeros(32);
1751 // segwit: empty scriptsig
1752 tx_in.scriptSig = CScript();
1753 tx_in.scriptWitness.stack.emplace_back(65); // arbitrary value to satisfy redeem script
1754 CScript redeem_script = CScript() << OP_FALSE << OP_IF << zeros(10) << OP_ENDIF;
1755 auto redeem_vec{std::vector<unsigned char>(redeem_script.begin(), redeem_script.end())};
1756 tx_in.scriptWitness.stack.push_back(redeem_vec);
1757 // this should return the redeem script
1758 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1759 BOOST_CHECK(ret_script == redeem_script);
1760 BOOST_CHECK_EQUAL(scale, 1);
1761 // OP_FALSE(1), OP_IF(1), length(1), zeros(10), OP_ENDIF(1)
1762 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "0+14");
1763 }
1764 { // P2SH-P2WPKH - no datacarrier bytes
1765 CScript prev_script; // scriptPubKey
1766 CTxIn tx_in;
1767 // P2WPKH is [OP_0, hash160(pubkey)]
1768 CScript redeem_script = CScript() << OP_0 << zeros(20);
1769 prev_script = CScript() << OP_HASH160 << zeros(20) << OP_EQUAL;
1770 tx_in.scriptSig = CScript() << std::vector<unsigned char>(redeem_script.begin(), redeem_script.end());
1771 // this should return the redeem script
1772 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1773 // should have no script at all since it's wrapped P2WPKH
1774 BOOST_CHECK(ret_script == CScript());
1775 // data bytes in the witness get discounted (*1 instead of *4)
1776 BOOST_CHECK_EQUAL(scale, 0);
1777 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "0+0");
1778 }
1779 { // P2SH-P2WSH - no datacarrier bytes
1780 CScript prev_script; // scriptPubKey
1781 CTxIn tx_in;
1782 // P2WSH is [OP_0, sha256(redeem_script)]
1783 CScript redeem_script = CScript() << OP_0 << zeros(32);
1784 prev_script = CScript() << OP_HASH160 << zeros(20) << OP_EQUAL;
1785 tx_in.scriptSig = CScript() << std::vector<unsigned char>(redeem_script.begin(), redeem_script.end());
1786 CScript witness_redeem_script = CScript() << OP_TRUE << OP_IF << zeros(10) << OP_ENDIF;
1787
1788 // in real life, one or more values (to satisfy the redeem script) would be pushed to the stack
1789 CScript wit = CScript() << OP_7;
1790 tx_in.scriptWitness.stack.emplace_back(wit.begin(), wit.end());
1791 // and then finally the redeem script itself (as the last stack element)
1792 auto redeem_vec{std::vector<unsigned char>(witness_redeem_script.begin(), witness_redeem_script.end())};
1793 tx_in.scriptWitness.stack.push_back(redeem_vec);
1794
1795 // this should return the witness redeem script
1796 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1797 // should have no script at all since it's wrapped P2WPKH
1798 BOOST_CHECK(ret_script == witness_redeem_script);
1799 // data bytes in the witness get discounted (*1 instead of *4)
1800 BOOST_CHECK_EQUAL(scale, 1);
1801 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "0+0");
1802 }
1803 { // P2SH-P2WSH - some datacarrier bytes
1804 CScript prev_script; // scriptPubKey
1805 CTxIn tx_in;
1806 // P2WSH is [OP_0, sha256(redeem_script)]
1807 CScript redeem_script = CScript() << OP_0 << zeros(32);
1808 prev_script = CScript() << OP_HASH160 << zeros(20) << OP_EQUAL;
1809 tx_in.scriptSig = CScript() << std::vector<unsigned char>(redeem_script.begin(), redeem_script.end());
1810 CScript witness_redeem_script = CScript() << OP_FALSE << OP_IF << zeros(10) << OP_ENDIF;
1811
1812 // in real life, one or more values (to satisfy the redeem script) would be pushed to the stack
1813 CScript wit = CScript() << OP_7;
1814 tx_in.scriptWitness.stack.emplace_back(wit.begin(), wit.end());
1815 // and then finally the redeem script itself (as the last stack element)
1816 auto redeem_vec{std::vector<unsigned char>(witness_redeem_script.begin(), witness_redeem_script.end())};
1817 tx_in.scriptWitness.stack.push_back(redeem_vec);
1818
1819 // this should return the witness redeem script
1820 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1821 // should have no script at all since it's wrapped P2WPKH
1822 BOOST_CHECK(ret_script == witness_redeem_script);
1823 // data bytes in the witness get discounted (*1 instead of *4)
1824 BOOST_CHECK_EQUAL(scale, 1);
1825 // OP_FALSE(1), OP_IF(1), length(1), zeros(10), OP_ENDIF(1) = 14
1826 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "0+14");
1827 }
1828 { // P2TR keypath - no datacarrier bytes
1829 CScript prev_script; // scriptPubKey
1830 CTxIn tx_in;
1831 prev_script = CScript() << OP_1 << zeros(32);
1832 // segwit: empty scriptsig
1833 tx_in.scriptSig = CScript();
1834 tx_in.scriptWitness.stack.emplace_back(65); // signature
1835 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1836 BOOST_CHECK(ret_script == CScript());
1837 BOOST_CHECK_EQUAL(scale, 0);
1838 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "0+0");
1839 }
1840 { // P2TR keypath - annex but no script - no datacarrier bytes
1841 CScript prev_script; // scriptPubKey
1842 CTxIn tx_in;
1843 prev_script = CScript() << OP_1 << zeros(32);
1844 // segwit: empty scriptsig
1845 tx_in.scriptSig = CScript();
1846 tx_in.scriptWitness.stack.emplace_back(65); // signature
1847 std::vector<unsigned char> annex{0x50, 0, 0};
1848 tx_in.scriptWitness.stack.push_back(annex);
1849 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1850 BOOST_CHECK(ret_script == CScript());
1851 BOOST_CHECK_EQUAL(scale, 0);
1852 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "0+0");
1853 }
1854 { // P2TR scriptpath - no datacarrier bytes
1855 CScript prev_script; // scriptPubKey
1856 CTxIn tx_in;
1857 prev_script = CScript() << OP_1 << zeros(32);
1858 // segwit: empty scriptsig
1859 tx_in.scriptSig = CScript();
1860 // stack: zero or more arbitrary values (script arguments); script; control block
1861 // (here we have two arbitrary values)
1862 tx_in.scriptWitness.stack.emplace_back(85); // arbitrary value
1863 tx_in.scriptWitness.stack.emplace_back(10); // arbitrary value
1864 CScript script = CScript() << OP_7 << OP_8;
1865 auto script_vec{std::vector<unsigned char>(script.begin(), script.end())};
1866 tx_in.scriptWitness.stack.push_back(script_vec);
1867 tx_in.scriptWitness.stack.emplace_back(33); // control block
1868 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1869 BOOST_CHECK(ret_script == script);
1870 BOOST_CHECK_EQUAL(scale, 1);
1871 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "0+0");
1872 }
1873 { // P2TR scriptpath - some datacarrier bytes
1874 CScript prev_script; // scriptPubKey
1875 CTxIn tx_in;
1876 prev_script = CScript() << OP_1 << zeros(32);
1877 // segwit: empty scriptsig
1878 tx_in.scriptSig = CScript();
1879 // stack: zero or more arbitrary values (script arguments); script; control block
1880 // (here we have one arbitrary value)
1881 tx_in.scriptWitness.stack.emplace_back(85); // arbitrary value
1882 CScript script = CScript() << OP_RETURN << OP_7 << OP_8;
1883 auto script_vec{std::vector<unsigned char>(script.begin(), script.end())};
1884 tx_in.scriptWitness.stack.push_back(script_vec);
1885 tx_in.scriptWitness.stack.emplace_back(33); // control block
1886 auto [ret_script, scale] = GetScriptForTransactionInput(prev_script, tx_in);
1887 BOOST_CHECK(ret_script == script);
1888 BOOST_CHECK_EQUAL(scale, 1);
1889 BOOST_CHECK_EQUAL(DatacarrierBytesStr(ret_script), "3+0");
1890 }
1891 }
1892
1893 static CMutableTransaction TxFromHex(const std::string& str)
1894 {
1895 CMutableTransaction tx;
1896 SpanReader{ParseHex(str)} >> TX_NO_WITNESS(tx);
1897 return tx;
1898 }
1899
1900 static std::vector<CTxOut> TxOutsFromJSON(const UniValue& univalue)
1901 {
1902 assert(univalue.isArray());
1903 std::vector<CTxOut> prevouts;
1904 for (size_t i = 0; i < univalue.size(); ++i) {
1905 CTxOut txout;
1906 SpanReader{ParseHex(univalue[i].get_str())} >> txout;
1907 prevouts.push_back(std::move(txout));
1908 }
1909 return prevouts;
1910 }
1911
1912 static CScriptWitness ScriptWitnessFromJSON(const UniValue& univalue)
1913 {
1914 assert(univalue.isArray());
1915 CScriptWitness scriptwitness;
1916 for (size_t i = 0; i < univalue.size(); ++i) {
1917 auto bytes = ParseHex(univalue[i].get_str());
1918 scriptwitness.stack.push_back(std::move(bytes));
1919 }
1920 return scriptwitness;
1921 }
1922
1923 #if defined(HAVE_CONSENSUS_LIB)
1924
1925 /* Test simple (successful) usage of limenkaconsensus_verify_script */
1926 BOOST_AUTO_TEST_CASE(limenkaconsensus_verify_script_returns_true)
1927 {
1928 unsigned int libconsensus_flags = 0;
1929 int nIn = 0;
1930
1931 CScript scriptPubKey;
1932 CScript scriptSig;
1933 CScriptWitness wit;
1934
1935 scriptPubKey << OP_1;
1936 CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
1937 CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
1938
1939 DataStream stream;
1940 stream << TX_WITH_WITNESS(spendTx);
1941
1942 limenkaconsensus_error err;
1943 int result = limenkaconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
1944 BOOST_CHECK_EQUAL(result, 1);
1945 BOOST_CHECK_EQUAL(err, limenkaconsensus_ERR_OK);
1946 }
1947
1948 /* Test limenkaconsensus_verify_script returns invalid tx index err*/
1949 BOOST_AUTO_TEST_CASE(limenkaconsensus_verify_script_tx_index_err)
1950 {
1951 unsigned int libconsensus_flags = 0;
1952 int nIn = 3;
1953
1954 CScript scriptPubKey;
1955 CScript scriptSig;
1956 CScriptWitness wit;
1957
1958 scriptPubKey << OP_EQUAL;
1959 CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
1960 CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
1961
1962 DataStream stream;
1963 stream << TX_WITH_WITNESS(spendTx);
1964
1965 limenkaconsensus_error err;
1966 int result = limenkaconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
1967 BOOST_CHECK_EQUAL(result, 0);
1968 BOOST_CHECK_EQUAL(err, limenkaconsensus_ERR_TX_INDEX);
1969 }
1970
1971 /* Test limenkaconsensus_verify_script returns tx size mismatch err*/
1972 BOOST_AUTO_TEST_CASE(limenkaconsensus_verify_script_tx_size)
1973 {
1974 unsigned int libconsensus_flags = 0;
1975 int nIn = 0;
1976
1977 CScript scriptPubKey;
1978 CScript scriptSig;
1979 CScriptWitness wit;
1980
1981 scriptPubKey << OP_EQUAL;
1982 CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
1983 CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
1984
1985 DataStream stream;
1986 stream << TX_WITH_WITNESS(spendTx);
1987
1988 limenkaconsensus_error err;
1989 int result = limenkaconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size() * 2, nIn, libconsensus_flags, &err);
1990 BOOST_CHECK_EQUAL(result, 0);
1991 BOOST_CHECK_EQUAL(err, limenkaconsensus_ERR_TX_SIZE_MISMATCH);
1992 }
1993
1994 /* Test limenkaconsensus_verify_script returns invalid tx serialization error */
1995 BOOST_AUTO_TEST_CASE(limenkaconsensus_verify_script_tx_serialization)
1996 {
1997 unsigned int libconsensus_flags = 0;
1998 int nIn = 0;
1999
2000 CScript scriptPubKey;
2001 CScript scriptSig;
2002 CScriptWitness wit;
2003
2004 scriptPubKey << OP_EQUAL;
2005 CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
2006 CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
2007
2008 DataStream stream;
2009 stream << 0xffffffff;
2010
2011 limenkaconsensus_error err;
2012 int result = limenkaconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
2013 BOOST_CHECK_EQUAL(result, 0);
2014 BOOST_CHECK_EQUAL(err, limenkaconsensus_ERR_TX_DESERIALIZE);
2015 }
2016
2017 /* Test limenkaconsensus_verify_script returns amount required error */
2018 BOOST_AUTO_TEST_CASE(limenkaconsensus_verify_script_amount_required_err)
2019 {
2020 unsigned int libconsensus_flags = limenkaconsensus_SCRIPT_FLAGS_VERIFY_WITNESS;
2021 int nIn = 0;
2022
2023 CScript scriptPubKey;
2024 CScript scriptSig;
2025 CScriptWitness wit;
2026
2027 scriptPubKey << OP_EQUAL;
2028 CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
2029 CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
2030
2031 DataStream stream;
2032 stream << TX_WITH_WITNESS(spendTx);
2033
2034 limenkaconsensus_error err;
2035 int result = limenkaconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
2036 BOOST_CHECK_EQUAL(result, 0);
2037 BOOST_CHECK_EQUAL(err, limenkaconsensus_ERR_AMOUNT_REQUIRED);
2038 }
2039
2040 /* Test limenkaconsensus_verify_script returns invalid flags err */
2041 BOOST_AUTO_TEST_CASE(limenkaconsensus_verify_script_invalid_flags)
2042 {
2043 unsigned int libconsensus_flags = 1 << 3;
2044 int nIn = 0;
2045
2046 CScript scriptPubKey;
2047 CScript scriptSig;
2048 CScriptWitness wit;
2049
2050 scriptPubKey << OP_EQUAL;
2051 CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
2052 CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
2053
2054 DataStream stream;
2055 stream << TX_WITH_WITNESS(spendTx);
2056
2057 limenkaconsensus_error err;
2058 int result = limenkaconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
2059 BOOST_CHECK_EQUAL(result, 0);
2060 BOOST_CHECK_EQUAL(err, limenkaconsensus_ERR_INVALID_FLAGS);
2061 }
2062
2063 /* Test limenkaconsensus_verify_script returns spent outputs required err */
2064 BOOST_AUTO_TEST_CASE(limenkaconsensus_verify_script_spent_outputs_required_err)
2065 {
2066 unsigned int libconsensus_flags{limenkaconsensus_SCRIPT_FLAGS_VERIFY_TAPROOT};
2067 const int nIn{0};
2068
2069 CScript scriptPubKey;
2070 CScript scriptSig;
2071 CScriptWitness wit;
2072
2073 scriptPubKey << OP_EQUAL;
2074 CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
2075 CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
2076
2077 DataStream stream;
2078 stream << TX_WITH_WITNESS(spendTx);
2079
2080 limenkaconsensus_error err;
2081 int result{limenkaconsensus_verify_script_with_spent_outputs(scriptPubKey.data(), scriptPubKey.size(), creditTx.vout[0].nValue, UCharCast(stream.data()), stream.size(), nullptr, 0, nIn, libconsensus_flags, &err)};
2082 BOOST_CHECK_EQUAL(result, 0);
2083 BOOST_CHECK_EQUAL(err, limenkaconsensus_ERR_SPENT_OUTPUTS_REQUIRED);
2084
2085 result = limenkaconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), creditTx.vout[0].nValue, UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
2086 BOOST_CHECK_EQUAL(result, 0);
2087 BOOST_CHECK_EQUAL(err, limenkaconsensus_ERR_SPENT_OUTPUTS_REQUIRED);
2088
2089 result = limenkaconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
2090 BOOST_CHECK_EQUAL(result, 0);
2091 BOOST_CHECK_EQUAL(err, limenkaconsensus_ERR_SPENT_OUTPUTS_REQUIRED);
2092 }
2093
2094 #endif // defined(HAVE_CONSENSUS_LIB)
2095
2096 static std::vector<unsigned int> AllConsensusFlags()
2097 {
2098 std::vector<unsigned int> ret;
2099
2100 for (unsigned int i = 0; i < 128; ++i) {
2101 unsigned int flag = 0;
2102 if (i & 1) flag |= SCRIPT_VERIFY_P2SH;
2103 if (i & 2) flag |= SCRIPT_VERIFY_DERSIG;
2104 if (i & 4) flag |= SCRIPT_VERIFY_NULLDUMMY;
2105 if (i & 8) flag |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2106 if (i & 16) flag |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
2107 if (i & 32) flag |= SCRIPT_VERIFY_WITNESS;
2108 if (i & 64) flag |= SCRIPT_VERIFY_TAPROOT;
2109
2110 // SCRIPT_VERIFY_WITNESS requires SCRIPT_VERIFY_P2SH
2111 if (flag & SCRIPT_VERIFY_WITNESS && !(flag & SCRIPT_VERIFY_P2SH)) continue;
2112 // SCRIPT_VERIFY_TAPROOT requires SCRIPT_VERIFY_WITNESS
2113 if (flag & SCRIPT_VERIFY_TAPROOT && !(flag & SCRIPT_VERIFY_WITNESS)) continue;
2114
2115 ret.push_back(flag);
2116 }
2117
2118 return ret;
2119 }
2120
2121 /** Precomputed list of all valid combinations of consensus-relevant script validation flags. */
2122 static const std::vector<unsigned int> ALL_CONSENSUS_FLAGS = AllConsensusFlags();
2123
2124 static void AssetTest(const UniValue& test, SignatureCache& signature_cache)
2125 {
2126 BOOST_CHECK(test.isObject());
2127
2128 CMutableTransaction mtx = TxFromHex(test["tx"].get_str());
2129 const std::vector<CTxOut> prevouts = TxOutsFromJSON(test["prevouts"]);
2130 BOOST_CHECK(prevouts.size() == mtx.vin.size());
2131 size_t idx = test["index"].getInt<int64_t>();
2132 uint32_t test_flags{ParseScriptFlags(test["flags"].get_str())};
2133 bool fin = test.exists("final") && test["final"].get_bool();
2134
2135 if (test.exists("success")) {
2136 mtx.vin[idx].scriptSig = ScriptFromHex(test["success"]["scriptSig"].get_str());
2137 mtx.vin[idx].scriptWitness = ScriptWitnessFromJSON(test["success"]["witness"]);
2138 CTransaction tx(mtx);
2139 PrecomputedTransactionData txdata;
2140 txdata.Init(tx, std::vector<CTxOut>(prevouts));
2141 CachingTransactionSignatureChecker txcheck(&tx, idx, prevouts[idx].nValue, true, signature_cache, txdata);
2142
2143 #if defined(HAVE_CONSENSUS_LIB)
2144 DataStream stream;
2145 stream << TX_WITH_WITNESS(tx);
2146 std::vector<UTXO> utxos;
2147 utxos.resize(prevouts.size());
2148 for (size_t i = 0; i < prevouts.size(); i++) {
2149 utxos[i].scriptPubKey = prevouts[i].scriptPubKey.data();
2150 utxos[i].scriptPubKeySize = prevouts[i].scriptPubKey.size();
2151 utxos[i].value = prevouts[i].nValue;
2152 }
2153 #endif
2154
2155 for (const auto flags : ALL_CONSENSUS_FLAGS) {
2156 // "final": true tests are valid for all flags. Others are only valid with flags that are
2157 // a subset of test_flags.
2158 if (fin || ((flags & test_flags) == flags)) {
2159 bool ret = VerifyScript(tx.vin[idx].scriptSig, prevouts[idx].scriptPubKey, &tx.vin[idx].scriptWitness, flags, txcheck, nullptr);
2160 BOOST_CHECK(ret);
2161 #if defined(HAVE_CONSENSUS_LIB)
2162 int lib_ret = limenkaconsensus_verify_script_with_spent_outputs(prevouts[idx].scriptPubKey.data(), prevouts[idx].scriptPubKey.size(), prevouts[idx].nValue, UCharCast(stream.data()), stream.size(), utxos.data(), utxos.size(), idx, flags, nullptr);
2163 BOOST_CHECK(lib_ret == 1);
2164 #endif
2165 }
2166 }
2167 }
2168
2169 if (test.exists("failure")) {
2170 mtx.vin[idx].scriptSig = ScriptFromHex(test["failure"]["scriptSig"].get_str());
2171 mtx.vin[idx].scriptWitness = ScriptWitnessFromJSON(test["failure"]["witness"]);
2172 CTransaction tx(mtx);
2173 PrecomputedTransactionData txdata;
2174 txdata.Init(tx, std::vector<CTxOut>(prevouts));
2175 CachingTransactionSignatureChecker txcheck(&tx, idx, prevouts[idx].nValue, true, signature_cache, txdata);
2176
2177 #if defined(HAVE_CONSENSUS_LIB)
2178 DataStream stream;
2179 stream << TX_WITH_WITNESS(tx);
2180 std::vector<UTXO> utxos;
2181 utxos.resize(prevouts.size());
2182 for (size_t i = 0; i < prevouts.size(); i++) {
2183 utxos[i].scriptPubKey = prevouts[i].scriptPubKey.data();
2184 utxos[i].scriptPubKeySize = prevouts[i].scriptPubKey.size();
2185 utxos[i].value = prevouts[i].nValue;
2186 }
2187 #endif
2188
2189 for (const auto flags : ALL_CONSENSUS_FLAGS) {
2190 // If a test is supposed to fail with test_flags, it should also fail with any superset thereof.
2191 if ((flags & test_flags) == test_flags) {
2192 bool ret = VerifyScript(tx.vin[idx].scriptSig, prevouts[idx].scriptPubKey, &tx.vin[idx].scriptWitness, flags, txcheck, nullptr);
2193 BOOST_CHECK(!ret);
2194 #if defined(HAVE_CONSENSUS_LIB)
2195 int lib_ret = limenkaconsensus_verify_script_with_spent_outputs(prevouts[idx].scriptPubKey.data(), prevouts[idx].scriptPubKey.size(), prevouts[idx].nValue, UCharCast(stream.data()), stream.size(), utxos.data(), utxos.size(), idx, flags, nullptr);
2196 BOOST_CHECK(lib_ret == 0);
2197 #endif
2198 }
2199 }
2200 }
2201 }
2202
2203 BOOST_AUTO_TEST_CASE(script_assets_test)
2204 {
2205 // See src/test/fuzz/script_assets_test_minimizer.cpp for information on how to generate
2206 // the script_assets_test.json file used by this test.
2207 SignatureCache signature_cache{DEFAULT_SIGNATURE_CACHE_BYTES};
2208
2209 const char* dir = std::getenv("DIR_UNIT_TEST_DATA");
2210 BOOST_WARN_MESSAGE(dir != nullptr, "Variable DIR_UNIT_TEST_DATA unset, skipping script_assets_test");
2211 if (dir == nullptr) return;
2212 auto path = fs::path(dir) / "script_assets_test.json";
2213 bool exists = fs::exists(path);
2214 BOOST_WARN_MESSAGE(exists, "File $DIR_UNIT_TEST_DATA/script_assets_test.json not found, skipping script_assets_test");
2215 if (!exists) return;
2216 std::ifstream file{path};
2217 BOOST_CHECK(file.is_open());
2218 file.seekg(0, std::ios::end);
2219 size_t length = file.tellg();
2220 file.seekg(0, std::ios::beg);
2221 std::string data(length, '\0');
2222 file.read(data.data(), data.size());
2223 UniValue tests = read_json(data);
2224 BOOST_CHECK(tests.isArray());
2225 BOOST_CHECK(tests.size() > 0);
2226
2227 for (size_t i = 0; i < tests.size(); i++) {
2228 AssetTest(tests[i], signature_cache);
2229 }
2230 file.close();
2231 }
2232
2233 BOOST_AUTO_TEST_CASE(bip341_keypath_test_vectors)
2234 {
2235 UniValue tests;
2236 tests.read(json_tests::bip341_wallet_vectors);
2237
2238 const auto& vectors = tests["keyPathSpending"];
2239
2240 for (const auto& vec : vectors.getValues()) {
2241 auto txhex = ParseHex(vec["given"]["rawUnsignedTx"].get_str());
2242 CMutableTransaction tx;
2243 SpanReader{txhex} >> TX_WITH_WITNESS(tx);
2244 std::vector<CTxOut> utxos;
2245 for (const auto& utxo_spent : vec["given"]["utxosSpent"].getValues()) {
2246 auto script_bytes = ParseHex(utxo_spent["scriptPubKey"].get_str());
2247 CScript script{script_bytes.begin(), script_bytes.end()};
2248 CAmount amount{utxo_spent["amountSats"].getInt<int>()};
2249 utxos.emplace_back(amount, script);
2250 }
2251
2252 PrecomputedTransactionData txdata;
2253 txdata.Init(tx, std::vector<CTxOut>{utxos}, true);
2254
2255 BOOST_CHECK(txdata.m_bip341_taproot_ready);
2256 BOOST_CHECK_EQUAL(HexStr(txdata.m_spent_amounts_single_hash), vec["intermediary"]["hashAmounts"].get_str());
2257 BOOST_CHECK_EQUAL(HexStr(txdata.m_outputs_single_hash), vec["intermediary"]["hashOutputs"].get_str());
2258 BOOST_CHECK_EQUAL(HexStr(txdata.m_prevouts_single_hash), vec["intermediary"]["hashPrevouts"].get_str());
2259 BOOST_CHECK_EQUAL(HexStr(txdata.m_spent_scripts_single_hash), vec["intermediary"]["hashScriptPubkeys"].get_str());
2260 BOOST_CHECK_EQUAL(HexStr(txdata.m_sequences_single_hash), vec["intermediary"]["hashSequences"].get_str());
2261
2262 for (const auto& input : vec["inputSpending"].getValues()) {
2263 int txinpos = input["given"]["txinIndex"].getInt<int>();
2264 int hashtype = input["given"]["hashType"].getInt<int>();
2265
2266 // Load key.
2267 auto privkey = ParseHex(input["given"]["internalPrivkey"].get_str());
2268 CKey key;
2269 key.Set(privkey.begin(), privkey.end(), true);
2270
2271 // Load Merkle root.
2272 uint256 merkle_root;
2273 if (!input["given"]["merkleRoot"].isNull()) {
2274 merkle_root = uint256{ParseHex(input["given"]["merkleRoot"].get_str())};
2275 }
2276
2277 // Compute and verify (internal) public key.
2278 XOnlyPubKey pubkey{key.GetPubKey()};
2279 BOOST_CHECK_EQUAL(HexStr(pubkey), input["intermediary"]["internalPubkey"].get_str());
2280
2281 // Sign and verify signature.
2282 FlatSigningProvider provider;
2283 provider.keys[key.GetPubKey().GetID()] = key;
2284 MutableTransactionSignatureCreator creator(tx, txinpos, utxos[txinpos].nValue, &txdata, hashtype);
2285 std::vector<unsigned char> signature;
2286 BOOST_CHECK(creator.CreateSchnorrSig(provider, signature, pubkey, nullptr, &merkle_root, SigVersion::TAPROOT));
2287 BOOST_CHECK_EQUAL(HexStr(signature), input["expected"]["witness"][0].get_str());
2288
2289 // We can't observe the tweak used inside the signing logic, so verify by recomputing it.
2290 BOOST_CHECK_EQUAL(HexStr(pubkey.ComputeTapTweakHash(merkle_root.IsNull() ? nullptr : &merkle_root)), input["intermediary"]["tweak"].get_str());
2291
2292 // We can't observe the sighash used inside the signing logic, so verify by recomputing it.
2293 ScriptExecutionData sed;
2294 sed.m_annex_init = true;
2295 sed.m_annex_present = false;
2296 uint256 sighash;
2297 BOOST_CHECK(SignatureHashSchnorr(sighash, sed, tx, txinpos, hashtype, SigVersion::TAPROOT, txdata, MissingDataBehavior::FAIL));
2298 BOOST_CHECK_EQUAL(HexStr(sighash), input["intermediary"]["sigHash"].get_str());
2299
2300 // To verify the sigmsg, hash the expected sigmsg, and compare it with the (expected) sighash.
2301 BOOST_CHECK_EQUAL(HexStr((HashWriter{HASHER_TAPSIGHASH} << std::span<const uint8_t>{ParseHex(input["intermediary"]["sigMsg"].get_str())}).GetSHA256()), input["intermediary"]["sigHash"].get_str());
2302 }
2303 }
2304 }
2305
2306 BOOST_AUTO_TEST_CASE(compute_tapbranch)
2307 {
2308 constexpr uint256 hash1{"8ad69ec7cf41c2a4001fd1f738bf1e505ce2277acdcaa63fe4765192497f47a7"};
2309 constexpr uint256 hash2{"f224a923cd0021ab202ab139cc56802ddb92dcfc172b9212261a539df79a112a"};
2310 constexpr uint256 result{"a64c5b7b943315f9b805d7a7296bedfcfd08919270a1f7a1466e98f8693d8cd9"};
2311 BOOST_CHECK_EQUAL(ComputeTapbranchHash(hash1, hash2), result);
2312 }
2313
2314 BOOST_AUTO_TEST_CASE(compute_tapleaf)
2315 {
2316 constexpr uint8_t script[6] = {'f','o','o','b','a','r'};
2317 constexpr uint256 tlc0{"edbc10c272a1215dcdcc11d605b9027b5ad6ed97cd45521203f136767b5b9c06"};
2318 constexpr uint256 tlc2{"8b5c4f90ae6bf76e259dbef5d8a59df06359c391b59263741b25eca76451b27a"};
2319
2320 BOOST_CHECK_EQUAL(ComputeTapleafHash(0xc0, Span(script)), tlc0);
2321 BOOST_CHECK_EQUAL(ComputeTapleafHash(0xc2, Span(script)), tlc2);
2322 }
2323
2324 BOOST_AUTO_TEST_SUITE_END()
2325