1 // Copyright (c) 2011-2020 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <test/data/script_tests.json.h>
6 
7 #include <core_io.h>
8 #include <fs.h>
9 #include <key.h>
10 #include <rpc/util.h>
11 #include <script/script.h>
12 #include <script/script_error.h>
13 #include <script/sigcache.h>
14 #include <script/sign.h>
15 #include <script/signingprovider.h>
16 #include <streams.h>
17 #include <test/util/setup_common.h>
18 #include <test/util/transaction_utils.h>
19 #include <util/strencodings.h>
20 #include <util/system.h>
21 
22 #if defined(HAVE_CONSENSUS_LIB)
23 #include <script/bitcoinconsensus.h>
24 #endif
25 
26 #include <stdint.h>
27 #include <string>
28 #include <vector>
29 
30 #include <boost/test/unit_test.hpp>
31 
32 #include <univalue.h>
33 
34 // Uncomment if you want to output updated JSON tests.
35 // #define UPDATE_JSON_TESTS
36 
37 static const unsigned int gFlags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC;
38 
39 unsigned int ParseScriptFlags(std::string strFlags);
40 std::string FormatScriptFlags(unsigned int flags);
41 
read_json(const std::string & jsondata)42 UniValue read_json(const std::string& jsondata)
43 {
44     UniValue v;
45 
46     if (!v.read(jsondata) || !v.isArray())
47     {
48         BOOST_ERROR("Parse error.");
49         return UniValue(UniValue::VARR);
50     }
51     return v.get_array();
52 }
53 
54 struct ScriptErrorDesc
55 {
56     ScriptError_t err;
57     const char *name;
58 };
59 
60 static ScriptErrorDesc script_errors[]={
61     {SCRIPT_ERR_OK, "OK"},
62     {SCRIPT_ERR_UNKNOWN_ERROR, "UNKNOWN_ERROR"},
63     {SCRIPT_ERR_EVAL_FALSE, "EVAL_FALSE"},
64     {SCRIPT_ERR_OP_RETURN, "OP_RETURN"},
65     {SCRIPT_ERR_SCRIPT_SIZE, "SCRIPT_SIZE"},
66     {SCRIPT_ERR_PUSH_SIZE, "PUSH_SIZE"},
67     {SCRIPT_ERR_OP_COUNT, "OP_COUNT"},
68     {SCRIPT_ERR_STACK_SIZE, "STACK_SIZE"},
69     {SCRIPT_ERR_SIG_COUNT, "SIG_COUNT"},
70     {SCRIPT_ERR_PUBKEY_COUNT, "PUBKEY_COUNT"},
71     {SCRIPT_ERR_VERIFY, "VERIFY"},
72     {SCRIPT_ERR_EQUALVERIFY, "EQUALVERIFY"},
73     {SCRIPT_ERR_CHECKMULTISIGVERIFY, "CHECKMULTISIGVERIFY"},
74     {SCRIPT_ERR_CHECKSIGVERIFY, "CHECKSIGVERIFY"},
75     {SCRIPT_ERR_NUMEQUALVERIFY, "NUMEQUALVERIFY"},
76     {SCRIPT_ERR_BAD_OPCODE, "BAD_OPCODE"},
77     {SCRIPT_ERR_DISABLED_OPCODE, "DISABLED_OPCODE"},
78     {SCRIPT_ERR_INVALID_STACK_OPERATION, "INVALID_STACK_OPERATION"},
79     {SCRIPT_ERR_INVALID_ALTSTACK_OPERATION, "INVALID_ALTSTACK_OPERATION"},
80     {SCRIPT_ERR_UNBALANCED_CONDITIONAL, "UNBALANCED_CONDITIONAL"},
81     {SCRIPT_ERR_NEGATIVE_LOCKTIME, "NEGATIVE_LOCKTIME"},
82     {SCRIPT_ERR_UNSATISFIED_LOCKTIME, "UNSATISFIED_LOCKTIME"},
83     {SCRIPT_ERR_SIG_HASHTYPE, "SIG_HASHTYPE"},
84     {SCRIPT_ERR_SIG_DER, "SIG_DER"},
85     {SCRIPT_ERR_MINIMALDATA, "MINIMALDATA"},
86     {SCRIPT_ERR_SIG_PUSHONLY, "SIG_PUSHONLY"},
87     {SCRIPT_ERR_SIG_HIGH_S, "SIG_HIGH_S"},
88     {SCRIPT_ERR_SIG_NULLDUMMY, "SIG_NULLDUMMY"},
89     {SCRIPT_ERR_PUBKEYTYPE, "PUBKEYTYPE"},
90     {SCRIPT_ERR_CLEANSTACK, "CLEANSTACK"},
91     {SCRIPT_ERR_MINIMALIF, "MINIMALIF"},
92     {SCRIPT_ERR_SIG_NULLFAIL, "NULLFAIL"},
93     {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS, "DISCOURAGE_UPGRADABLE_NOPS"},
94     {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, "DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"},
95     {SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH, "WITNESS_PROGRAM_WRONG_LENGTH"},
96     {SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY, "WITNESS_PROGRAM_WITNESS_EMPTY"},
97     {SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH, "WITNESS_PROGRAM_MISMATCH"},
98     {SCRIPT_ERR_WITNESS_MALLEATED, "WITNESS_MALLEATED"},
99     {SCRIPT_ERR_WITNESS_MALLEATED_P2SH, "WITNESS_MALLEATED_P2SH"},
100     {SCRIPT_ERR_WITNESS_UNEXPECTED, "WITNESS_UNEXPECTED"},
101     {SCRIPT_ERR_WITNESS_PUBKEYTYPE, "WITNESS_PUBKEYTYPE"},
102     {SCRIPT_ERR_OP_CODESEPARATOR, "OP_CODESEPARATOR"},
103     {SCRIPT_ERR_SIG_FINDANDDELETE, "SIG_FINDANDDELETE"},
104 };
105 
FormatScriptError(ScriptError_t err)106 static std::string FormatScriptError(ScriptError_t err)
107 {
108     for (const auto& se : script_errors)
109         if (se.err == err)
110             return se.name;
111     BOOST_ERROR("Unknown scripterror enumeration value, update script_errors in script_tests.cpp.");
112     return "";
113 }
114 
ParseScriptError(const std::string & name)115 static ScriptError_t ParseScriptError(const std::string& name)
116 {
117     for (const auto& se : script_errors)
118         if (se.name == name)
119             return se.err;
120     BOOST_ERROR("Unknown scripterror \"" << name << "\" in test description");
121     return SCRIPT_ERR_UNKNOWN_ERROR;
122 }
123 
BOOST_FIXTURE_TEST_SUITE(script_tests,BasicTestingSetup)124 BOOST_FIXTURE_TEST_SUITE(script_tests, BasicTestingSetup)
125 
126 void DoTest(const CScript& scriptPubKey, const CScript& scriptSig, const CScriptWitness& scriptWitness, int flags, const std::string& message, int scriptError, CAmount nValue = 0)
127 {
128     bool expect = (scriptError == SCRIPT_ERR_OK);
129     if (flags & SCRIPT_VERIFY_CLEANSTACK) {
130         flags |= SCRIPT_VERIFY_P2SH;
131         flags |= SCRIPT_VERIFY_WITNESS;
132     }
133     ScriptError err;
134     const CTransaction txCredit{BuildCreditingTransaction(scriptPubKey, nValue)};
135     CMutableTransaction tx = BuildSpendingTransaction(scriptSig, scriptWitness, txCredit);
136     CMutableTransaction tx2 = tx;
137     BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, &scriptWitness, flags, MutableTransactionSignatureChecker(&tx, 0, txCredit.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err) == expect, message);
138     BOOST_CHECK_MESSAGE(err == scriptError, FormatScriptError(err) + " where " + FormatScriptError((ScriptError_t)scriptError) + " expected: " + message);
139 
140     // Verify that removing flags from a passing test or adding flags to a failing test does not change the result.
141     for (int i = 0; i < 16; ++i) {
142         int extra_flags = InsecureRandBits(16);
143         int combined_flags = expect ? (flags & ~extra_flags) : (flags | extra_flags);
144         // Weed out some invalid flag combinations.
145         if (combined_flags & SCRIPT_VERIFY_CLEANSTACK && ~combined_flags & (SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS)) continue;
146         if (combined_flags & SCRIPT_VERIFY_WITNESS && ~combined_flags & SCRIPT_VERIFY_P2SH) continue;
147         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));
148     }
149 
150 #if defined(HAVE_CONSENSUS_LIB)
151     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
152     stream << tx2;
153     int libconsensus_flags = flags & bitcoinconsensus_SCRIPT_FLAGS_VERIFY_ALL;
154     if (libconsensus_flags == flags) {
155         int expectedSuccessCode = expect ? 1 : 0;
156         if (flags & bitcoinconsensus_SCRIPT_FLAGS_VERIFY_WITNESS) {
157             BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), txCredit.vout[0].nValue, stream.data(), stream.size(), 0, libconsensus_flags, nullptr) == expectedSuccessCode, message);
158         } else {
159             BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), 0, stream.data(), stream.size(), 0, libconsensus_flags, nullptr) == expectedSuccessCode, message);
160             BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), stream.data(), stream.size(), 0, libconsensus_flags, nullptr) == expectedSuccessCode, message);
161         }
162     }
163 #endif
164 }
165 
NegateSignatureS(std::vector<unsigned char> & vchSig)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 
KeyData__anon6965c89a0111::KeyData219     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;
259     std::vector<unsigned char> push;
260     std::string comment;
261     int flags;
262     int scriptError;
263     CAmount nValue;
264 
DoPush()265     void DoPush()
266     {
267         if (havePush) {
268             spendTx.vin[0].scriptSig << push;
269             havePush = false;
270         }
271     }
272 
DoPush(const std::vector<unsigned char> & data)273     void DoPush(const std::vector<unsigned char>& data)
274     {
275         DoPush();
276         push = data;
277         havePush = true;
278     }
279 
280 public:
TestBuilder(const CScript & script_,const std::string & comment_,int flags_,bool P2SH=false,WitnessMode wm=WitnessMode::NONE,int witnessversion=0,CAmount nValue_=0)281     TestBuilder(const CScript& script_, const std::string& comment_, int flags_, bool P2SH = false, WitnessMode wm = WitnessMode::NONE, int witnessversion = 0, CAmount nValue_ = 0) : script(script_), havePush(false), comment(comment_), flags(flags_), scriptError(SCRIPT_ERR_OK), nValue(nValue_)
282     {
283         CScript scriptPubKey = script;
284         if (wm == WitnessMode::PKH) {
285             uint160 hash;
286             CHash160().Write(MakeSpan(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 
ScriptError(ScriptError_t err)303     TestBuilder& ScriptError(ScriptError_t err)
304     {
305         scriptError = err;
306         return *this;
307     }
308 
Opcode(const opcodetype & _op)309     TestBuilder& Opcode(const opcodetype& _op)
310     {
311         DoPush();
312         spendTx.vin[0].scriptSig << _op;
313         return *this;
314     }
315 
Num(int num)316     TestBuilder& Num(int num)
317     {
318         DoPush();
319         spendTx.vin[0].scriptSig << num;
320         return *this;
321     }
322 
Push(const std::string & hex)323     TestBuilder& Push(const std::string& hex)
324     {
325         DoPush(ParseHex(hex));
326         return *this;
327     }
328 
Push(const CScript & _script)329     TestBuilder& Push(const CScript& _script)
330     {
331         DoPush(std::vector<unsigned char>(_script.begin(), _script.end()));
332         return *this;
333     }
334 
PushSig(const CKey & key,int nHashType=SIGHASH_ALL,unsigned int lenR=32,unsigned int lenS=32,SigVersion sigversion=SigVersion::BASE,CAmount amount=0)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 
PushWitSig(const CKey & key,CAmount amount=-1,int nHashType=SIGHASH_ALL,unsigned int lenR=32,unsigned int lenS=32,SigVersion sigversion=SigVersion::WITNESS_V0)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 
Push(const CPubKey & pubkey)360     TestBuilder& Push(const CPubKey& pubkey)
361     {
362         DoPush(std::vector<unsigned char>(pubkey.begin(), pubkey.end()));
363         return *this;
364     }
365 
PushRedeem()366     TestBuilder& PushRedeem()
367     {
368         DoPush(std::vector<unsigned char>(redeemscript.begin(), redeemscript.end()));
369         return *this;
370     }
371 
PushWitRedeem()372     TestBuilder& PushWitRedeem()
373     {
374         DoPush(std::vector<unsigned char>(witscript.begin(), witscript.end()));
375         return AsWit();
376     }
377 
EditPush(unsigned int pos,const std::string & hexin,const std::string & hexout)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 
DamagePush(unsigned int pos)390     TestBuilder& DamagePush(unsigned int pos)
391     {
392         assert(havePush);
393         assert(pos < push.size());
394         push[pos] ^= 1;
395         return *this;
396     }
397 
Test()398     TestBuilder& Test()
399     {
400         TestBuilder copy = *this; // Make a copy so we can rollback the push.
401         DoPush();
402         DoTest(creditTx->vout[0].scriptPubKey, spendTx.vin[0].scriptSig, scriptWitness, flags, comment, scriptError, nValue);
403         *this = copy;
404         return *this;
405     }
406 
AsWit()407     TestBuilder& AsWit()
408     {
409         assert(havePush);
410         scriptWitness.stack.push_back(push);
411         havePush = false;
412         return *this;
413     }
414 
GetJSON()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(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 
GetComment() const435     std::string GetComment() const
436     {
437         return comment;
438     }
439 };
440 
JSONPrettyPrint(const UniValue & univalue)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 
BOOST_AUTO_TEST_CASE(script_build)454 BOOST_AUTO_TEST_CASE(script_build)
455 {
456     const KeyData keys;
457 
458     std::vector<TestBuilder> tests;
459 
460     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
461                                 "P2PK", 0
462                                ).PushSig(keys.key0));
463     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
464                                 "P2PK, bad sig", 0
465                                ).PushSig(keys.key0).DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE));
466 
467     tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
468                                 "P2PKH", 0
469                                ).PushSig(keys.key1).Push(keys.pubkey1C));
470     tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey2C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
471                                 "P2PKH, bad pubkey", 0
472                                ).PushSig(keys.key2).Push(keys.pubkey2C).DamagePush(5).ScriptError(SCRIPT_ERR_EQUALVERIFY));
473 
474     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
475                                 "P2PK anyonecanpay", 0
476                                ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY));
477     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
478                                 "P2PK anyonecanpay marked with normal hashtype", 0
479                                ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY).EditPush(70, "81", "01").ScriptError(SCRIPT_ERR_EVAL_FALSE));
480 
481     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
482                                 "P2SH(P2PK)", SCRIPT_VERIFY_P2SH, true
483                                ).PushSig(keys.key0).PushRedeem());
484     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
485                                 "P2SH(P2PK), bad redeemscript", SCRIPT_VERIFY_P2SH, true
486                                ).PushSig(keys.key0).PushRedeem().DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE));
487 
488     tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey0.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
489                                 "P2SH(P2PKH)", SCRIPT_VERIFY_P2SH, true
490                                ).PushSig(keys.key0).Push(keys.pubkey0).PushRedeem());
491     tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
492                                 "P2SH(P2PKH), bad sig but no VERIFY_P2SH", 0, true
493                                ).PushSig(keys.key0).DamagePush(10).PushRedeem());
494     tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
495                                 "P2SH(P2PKH), bad sig", SCRIPT_VERIFY_P2SH, true
496                                ).PushSig(keys.key0).DamagePush(10).PushRedeem().ScriptError(SCRIPT_ERR_EQUALVERIFY));
497 
498     tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
499                                 "3-of-3", 0
500                                ).Num(0).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
501     tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
502                                 "3-of-3, 2 sigs", 0
503                                ).Num(0).PushSig(keys.key0).PushSig(keys.key1).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
504 
505     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
506                                 "P2SH(2-of-3)", SCRIPT_VERIFY_P2SH, true
507                                ).Num(0).PushSig(keys.key1).PushSig(keys.key2).PushRedeem());
508     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
509                                 "P2SH(2-of-3), 1 sig", SCRIPT_VERIFY_P2SH, true
510                                ).Num(0).PushSig(keys.key1).Num(0).PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
511 
512     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
513                                 "P2PK with too much R padding but no DERSIG", 0
514                                ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000"));
515     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
516                                 "P2PK with too much R padding", SCRIPT_VERIFY_DERSIG
517                                ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER));
518     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
519                                 "P2PK with too much S padding but no DERSIG", 0
520                                ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100"));
521     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
522                                 "P2PK with too much S padding", SCRIPT_VERIFY_DERSIG
523                                ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100").ScriptError(SCRIPT_ERR_SIG_DER));
524     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
525                                 "P2PK with too little R padding but no DERSIG", 0
526                                ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
527     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
528                                 "P2PK with too little R padding", SCRIPT_VERIFY_DERSIG
529                                ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
530     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
531                                 "P2PK NOT with bad sig with too much R padding but no DERSIG", 0
532                                ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10));
533     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
534                                 "P2PK NOT with bad sig with too much R padding", SCRIPT_VERIFY_DERSIG
535                                ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10).ScriptError(SCRIPT_ERR_SIG_DER));
536     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
537                                 "P2PK NOT with too much R padding but no DERSIG", 0
538                                ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_EVAL_FALSE));
539     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
540                                 "P2PK NOT with too much R padding", SCRIPT_VERIFY_DERSIG
541                                ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER));
542 
543     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
544                                 "BIP66 example 1, without DERSIG", 0
545                                ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
546     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
547                                 "BIP66 example 1, with DERSIG", SCRIPT_VERIFY_DERSIG
548                                ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
549     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
550                                 "BIP66 example 2, without DERSIG", 0
551                                ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE));
552     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
553                                 "BIP66 example 2, with DERSIG", SCRIPT_VERIFY_DERSIG
554                                ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
555     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
556                                 "BIP66 example 3, without DERSIG", 0
557                                ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
558     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
559                                 "BIP66 example 3, with DERSIG", SCRIPT_VERIFY_DERSIG
560                                ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
561     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
562                                 "BIP66 example 4, without DERSIG", 0
563                                ).Num(0));
564     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
565                                 "BIP66 example 4, with DERSIG", SCRIPT_VERIFY_DERSIG
566                                ).Num(0));
567     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
568                                 "BIP66 example 5, without DERSIG", 0
569                                ).Num(1).ScriptError(SCRIPT_ERR_EVAL_FALSE));
570     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
571                                 "BIP66 example 5, with DERSIG", SCRIPT_VERIFY_DERSIG
572                                ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER));
573     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
574                                 "BIP66 example 6, without DERSIG", 0
575                                ).Num(1));
576     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
577                                 "BIP66 example 6, with DERSIG", SCRIPT_VERIFY_DERSIG
578                                ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER));
579     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
580                                 "BIP66 example 7, without DERSIG", 0
581                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2));
582     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
583                                 "BIP66 example 7, with DERSIG", SCRIPT_VERIFY_DERSIG
584                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER));
585     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
586                                 "BIP66 example 8, without DERSIG", 0
587                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_EVAL_FALSE));
588     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
589                                 "BIP66 example 8, with DERSIG", SCRIPT_VERIFY_DERSIG
590                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER));
591     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
592                                 "BIP66 example 9, without DERSIG", 0
593                                ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE));
594     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
595                                 "BIP66 example 9, with DERSIG", SCRIPT_VERIFY_DERSIG
596                                ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
597     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
598                                 "BIP66 example 10, without DERSIG", 0
599                                ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
600     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
601                                 "BIP66 example 10, with DERSIG", SCRIPT_VERIFY_DERSIG
602                                ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
603     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
604                                 "BIP66 example 11, without DERSIG", 0
605                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
606     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
607                                 "BIP66 example 11, with DERSIG", SCRIPT_VERIFY_DERSIG
608                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
609     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
610                                 "BIP66 example 12, without DERSIG", 0
611                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
612     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
613                                 "BIP66 example 12, with DERSIG", SCRIPT_VERIFY_DERSIG
614                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
615     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
616                                 "P2PK with multi-byte hashtype, without DERSIG", 0
617                                ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101"));
618     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
619                                 "P2PK with multi-byte hashtype, with DERSIG", SCRIPT_VERIFY_DERSIG
620                                ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101").ScriptError(SCRIPT_ERR_SIG_DER));
621 
622     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
623                                 "P2PK with high S but no LOW_S", 0
624                                ).PushSig(keys.key2, SIGHASH_ALL, 32, 33));
625     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
626                                 "P2PK with high S", SCRIPT_VERIFY_LOW_S
627                                ).PushSig(keys.key2, SIGHASH_ALL, 32, 33).ScriptError(SCRIPT_ERR_SIG_HIGH_S));
628 
629     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,
630                                 "P2PK with hybrid pubkey but no STRICTENC", 0
631                                ).PushSig(keys.key0, SIGHASH_ALL));
632     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,
633                                 "P2PK with hybrid pubkey", SCRIPT_VERIFY_STRICTENC
634                                ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
635     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
636                                 "P2PK NOT with hybrid pubkey but no STRICTENC", 0
637                                ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_EVAL_FALSE));
638     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
639                                 "P2PK NOT with hybrid pubkey", SCRIPT_VERIFY_STRICTENC
640                                ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
641     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
642                                 "P2PK NOT with invalid hybrid pubkey but no STRICTENC", 0
643                                ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10));
644     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
645                                 "P2PK NOT with invalid hybrid pubkey", SCRIPT_VERIFY_STRICTENC
646                                ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
647     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
648                                 "1-of-2 with the second 1 hybrid pubkey and no STRICTENC", 0
649                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL));
650     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
651                                 "1-of-2 with the second 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC
652                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL));
653     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0H) << OP_2 << OP_CHECKMULTISIG,
654                                 "1-of-2 with the first 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC
655                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
656 
657     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
658                                 "P2PK with undefined hashtype but no STRICTENC", 0
659                                ).PushSig(keys.key1, 5));
660     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
661                                 "P2PK with undefined hashtype", SCRIPT_VERIFY_STRICTENC
662                                ).PushSig(keys.key1, 5).ScriptError(SCRIPT_ERR_SIG_HASHTYPE));
663     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,
664                                 "P2PK NOT with invalid sig and undefined hashtype but no STRICTENC", 0
665                                ).PushSig(keys.key1, 5).DamagePush(10));
666     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,
667                                 "P2PK NOT with invalid sig and undefined hashtype", SCRIPT_VERIFY_STRICTENC
668                                ).PushSig(keys.key1, 5).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_HASHTYPE));
669 
670     tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
671                                 "3-of-3 with nonzero dummy but no NULLDUMMY", 0
672                                ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
673     tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
674                                 "3-of-3 with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY
675                                ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY));
676     tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,
677                                 "3-of-3 NOT with invalid sig and nonzero dummy but no NULLDUMMY", 0
678                                ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10));
679     tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,
680                                 "3-of-3 NOT with invalid sig with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY
681                                ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY));
682 
683     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
684                                 "2-of-2 with two identical keys and sigs pushed using OP_DUP but no SIGPUSHONLY", 0
685                                ).Num(0).PushSig(keys.key1).Opcode(OP_DUP));
686     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
687                                 "2-of-2 with two identical keys and sigs pushed using OP_DUP", SCRIPT_VERIFY_SIGPUSHONLY
688                                ).Num(0).PushSig(keys.key1).Opcode(OP_DUP).ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
689     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
690                                 "P2SH(P2PK) with non-push scriptSig but no P2SH or SIGPUSHONLY", 0, true
691                                ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem());
692     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
693                                 "P2PK with non-push scriptSig but with P2SH validation", 0
694                                ).PushSig(keys.key2).Opcode(OP_NOP8));
695     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
696                                 "P2SH(P2PK) with non-push scriptSig but no SIGPUSHONLY", SCRIPT_VERIFY_P2SH, true
697                                ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
698     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
699                                 "P2SH(P2PK) with non-push scriptSig but not P2SH", SCRIPT_VERIFY_SIGPUSHONLY, true
700                                ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
701     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
702                                 "2-of-2 with two identical keys and sigs pushed", SCRIPT_VERIFY_SIGPUSHONLY
703                                ).Num(0).PushSig(keys.key1).PushSig(keys.key1));
704     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
705                                 "P2PK with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH
706                                ).Num(11).PushSig(keys.key0));
707     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
708                                 "P2PK with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH
709                                ).Num(11).PushSig(keys.key0).ScriptError(SCRIPT_ERR_CLEANSTACK));
710     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
711                                 "P2SH with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH, true
712                                ).Num(11).PushSig(keys.key0).PushRedeem());
713     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
714                                 "P2SH with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true
715                                ).Num(11).PushSig(keys.key0).PushRedeem().ScriptError(SCRIPT_ERR_CLEANSTACK));
716     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
717                                 "P2SH with CLEANSTACK", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true
718                                ).PushSig(keys.key0).PushRedeem());
719 
720     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
721                                 "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
722                                 0, 1).PushWitSig(keys.key0).PushWitRedeem());
723     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
724                                 "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH,
725                                 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit());
726     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
727                                 "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
728                                 0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
729     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
730                                 "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH,
731                                 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem());
732     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
733                                 "Basic P2WSH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
734                                ).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
735     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
736                                 "Basic P2WPKH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
737                                ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE));
738     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
739                                 "Basic P2SH(P2WSH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH
740                                ).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
741     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
742                                 "Basic P2SH(P2WPKH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
743                                ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
744     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
745                                 "Basic P2WSH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
746                                ).PushWitSig(keys.key0).PushWitRedeem());
747     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
748                                 "Basic P2WPKH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
749                                ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit());
750     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
751                                 "Basic P2SH(P2WSH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WitnessMode::SH
752                                ).PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
753     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
754                                 "Basic P2SH(P2WPKH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
755                                ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem());
756     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
757                                 "Basic P2WSH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
758                                 0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
759     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
760                                 "Basic P2WPKH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH,
761                                 0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE));
762     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
763                                 "Basic P2SH(P2WSH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
764                                 0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
765     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
766                                 "Basic P2SH(P2WPKH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH,
767                                 0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
768 
769     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
770                                 "P2WPKH with future witness version", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH |
771                                 SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, false, WitnessMode::PKH, 1
772                                ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM));
773     {
774         CScript witscript = CScript() << ToByteVector(keys.pubkey0);
775         uint256 hash;
776         CSHA256().Write(witscript.data(), witscript.size()).Finalize(hash.begin());
777         std::vector<unsigned char> hashBytes = ToByteVector(hash);
778         hashBytes.pop_back();
779         tests.push_back(TestBuilder(CScript() << OP_0 << hashBytes,
780                                     "P2WPKH with wrong witness program length", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false
781                                    ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH));
782     }
783     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
784                                 "P2WSH with empty witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
785                                ).ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY));
786     {
787         CScript witscript = CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG;
788         tests.push_back(TestBuilder(witscript,
789                                     "P2WSH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
790                                    ).PushWitSig(keys.key0).Push(witscript).DamagePush(0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH));
791     }
792     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
793                                 "P2WPKH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
794                                ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH));
795     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
796                                 "P2WPKH with non-empty scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
797                                ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Num(11).ScriptError(SCRIPT_ERR_WITNESS_MALLEATED));
798     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
799                                 "P2SH(P2WPKH) with superfluous push in scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
800                                ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().Num(11).PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_MALLEATED_P2SH));
801     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
802                                 "P2PK with witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH
803                                ).PushSig(keys.key0).Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_UNEXPECTED));
804 
805     // Compressed keys should pass SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
806     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
807                                 "Basic P2WSH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
808                                 0, 1).PushWitSig(keys.key0C).PushWitRedeem());
809     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C),
810                                 "Basic P2WPKH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::PKH,
811                                 0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit());
812     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
813                                 "Basic P2SH(P2WSH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
814                                 0, 1).PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
815     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C),
816                                 "Basic P2SH(P2WPKH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::PKH,
817                                 0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit().PushRedeem());
818 
819     // Testing uncompressed key in witness with SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
820     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
821                                 "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
822                                 0, 1).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
823     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
824                                 "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::PKH,
825                                 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
826     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
827                                 "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
828                                 0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
829     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
830                                 "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::PKH,
831                                 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
832 
833     // P2WSH 1-of-2 multisig with compressed keys
834     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
835                                 "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
836                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
837     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
838                                 "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
839                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
840     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
841                                 "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
842                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem());
843     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
844                                 "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
845                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem());
846 
847     // P2WSH 1-of-2 multisig with first key uncompressed
848     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
849                                 "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
850                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem());
851     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
852                                 "P2SH(P2WSH) CHECKMULTISIG first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
853                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
854     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
855                                 "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,
856                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
857     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
858                                 "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,
859                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
860     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
861                                 "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
862                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem());
863     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
864                                 "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
865                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem());
866     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
867                                 "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,
868                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
869     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
870                                 "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,
871                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
872     // P2WSH 1-of-2 multisig with second key uncompressed
873     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
874                                 "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
875                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
876     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
877                                 "P2SH(P2WSH) CHECKMULTISIG second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
878                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
879     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
880                                 "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,
881                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
882     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
883                                 "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,
884                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
885     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
886                                 "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
887                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem());
888     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
889                                 "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
890                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem());
891     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
892                                 "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,
893                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
894     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
895                                 "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,
896                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
897 
898     std::set<std::string> tests_set;
899 
900     {
901         UniValue json_tests = read_json(std::string(json_tests::script_tests, json_tests::script_tests + sizeof(json_tests::script_tests)));
902 
903         for (unsigned int idx = 0; idx < json_tests.size(); idx++) {
904             const UniValue& tv = json_tests[idx];
905             tests_set.insert(JSONPrettyPrint(tv.get_array()));
906         }
907     }
908 
909 #ifdef UPDATE_JSON_TESTS
910     std::string strGen;
911 #endif
912     for (TestBuilder& test : tests) {
913         test.Test();
914         std::string str = JSONPrettyPrint(test.GetJSON());
915 #ifdef UPDATE_JSON_TESTS
916         strGen += str + ",\n";
917 #else
918         if (tests_set.count(str) == 0) {
919             BOOST_CHECK_MESSAGE(false, "Missing auto script_valid test: " + test.GetComment());
920         }
921 #endif
922     }
923 
924 #ifdef UPDATE_JSON_TESTS
925     FILE* file = fopen("script_tests.json.gen", "w");
926     fputs(strGen.c_str(), file);
927     fclose(file);
928 #endif
929 }
930 
BOOST_AUTO_TEST_CASE(script_json_test)931 BOOST_AUTO_TEST_CASE(script_json_test)
932 {
933     // Read tests from test/data/script_tests.json
934     // Format is an array of arrays
935     // Inner arrays are [ ["wit"..., nValue]?, "scriptSig", "scriptPubKey", "flags", "expected_scripterror" ]
936     // ... where scriptSig and scriptPubKey are stringified
937     // scripts.
938     // If a witness is given, then the last value in the array should be the
939     // amount (nValue) to use in the crediting tx
940     UniValue tests = read_json(std::string(json_tests::script_tests, json_tests::script_tests + sizeof(json_tests::script_tests)));
941 
942     for (unsigned int idx = 0; idx < tests.size(); idx++) {
943         UniValue test = tests[idx];
944         std::string strTest = test.write();
945         CScriptWitness witness;
946         CAmount nValue = 0;
947         unsigned int pos = 0;
948         if (test.size() > 0 && test[pos].isArray()) {
949             unsigned int i=0;
950             for (i = 0; i < test[pos].size()-1; i++) {
951                 witness.stack.push_back(ParseHex(test[pos][i].get_str()));
952             }
953             nValue = AmountFromValue(test[pos][i]);
954             pos++;
955         }
956         if (test.size() < 4 + pos) // Allow size > 3; extra stuff ignored (useful for comments)
957         {
958             if (test.size() != 1) {
959                 BOOST_ERROR("Bad test: " << strTest);
960             }
961             continue;
962         }
963         std::string scriptSigString = test[pos++].get_str();
964         CScript scriptSig = ParseScript(scriptSigString);
965         std::string scriptPubKeyString = test[pos++].get_str();
966         CScript scriptPubKey = ParseScript(scriptPubKeyString);
967         unsigned int scriptflags = ParseScriptFlags(test[pos++].get_str());
968         int scriptError = ParseScriptError(test[pos++].get_str());
969 
970         DoTest(scriptPubKey, scriptSig, witness, scriptflags, strTest, scriptError, nValue);
971     }
972 }
973 
BOOST_AUTO_TEST_CASE(script_PushData)974 BOOST_AUTO_TEST_CASE(script_PushData)
975 {
976     // Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on
977     // the stack as the 1-75 opcodes do.
978     static const unsigned char direct[] = { 1, 0x5a };
979     static const unsigned char pushdata1[] = { OP_PUSHDATA1, 1, 0x5a };
980     static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a };
981     static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a };
982 
983     ScriptError err;
984     std::vector<std::vector<unsigned char> > directStack;
985     BOOST_CHECK(EvalScript(directStack, CScript(direct, direct + sizeof(direct)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
986     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
987 
988     std::vector<std::vector<unsigned char> > pushdata1Stack;
989     BOOST_CHECK(EvalScript(pushdata1Stack, CScript(pushdata1, pushdata1 + sizeof(pushdata1)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
990     BOOST_CHECK(pushdata1Stack == directStack);
991     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
992 
993     std::vector<std::vector<unsigned char> > pushdata2Stack;
994     BOOST_CHECK(EvalScript(pushdata2Stack, CScript(pushdata2, pushdata2 + sizeof(pushdata2)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
995     BOOST_CHECK(pushdata2Stack == directStack);
996     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
997 
998     std::vector<std::vector<unsigned char> > pushdata4Stack;
999     BOOST_CHECK(EvalScript(pushdata4Stack, CScript(pushdata4, pushdata4 + sizeof(pushdata4)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1000     BOOST_CHECK(pushdata4Stack == directStack);
1001     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1002 
1003     const std::vector<unsigned char> pushdata1_trunc{OP_PUSHDATA1, 1};
1004     const std::vector<unsigned char> pushdata2_trunc{OP_PUSHDATA2, 1, 0};
1005     const std::vector<unsigned char> pushdata4_trunc{OP_PUSHDATA4, 1, 0, 0, 0};
1006 
1007     std::vector<std::vector<unsigned char>> stack_ignore;
1008     BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata1_trunc.begin(), pushdata1_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1009     BOOST_CHECK_EQUAL(err, SCRIPT_ERR_BAD_OPCODE);
1010     BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata2_trunc.begin(), pushdata2_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(pushdata4_trunc.begin(), pushdata4_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1013     BOOST_CHECK_EQUAL(err, SCRIPT_ERR_BAD_OPCODE);
1014 }
1015 
BOOST_AUTO_TEST_CASE(script_cltv_truncated)1016 BOOST_AUTO_TEST_CASE(script_cltv_truncated)
1017 {
1018     const auto script_cltv_trunc = CScript() << OP_CHECKLOCKTIMEVERIFY;
1019 
1020     std::vector<std::vector<unsigned char>> stack_ignore;
1021     ScriptError err;
1022     BOOST_CHECK(!EvalScript(stack_ignore, script_cltv_trunc, SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY, BaseSignatureChecker(), SigVersion::BASE, &err));
1023     BOOST_CHECK_EQUAL(err, SCRIPT_ERR_INVALID_STACK_OPERATION);
1024 }
1025 
1026 static CScript
sign_multisig(const CScript & scriptPubKey,const std::vector<CKey> & keys,const CTransaction & transaction)1027 sign_multisig(const CScript& scriptPubKey, const std::vector<CKey>& keys, const CTransaction& transaction)
1028 {
1029     uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL, 0, SigVersion::BASE);
1030 
1031     CScript result;
1032     //
1033     // NOTE: CHECKMULTISIG has an unfortunate bug; it requires
1034     // one extra item on the stack, before the signatures.
1035     // Putting OP_0 on the stack is the workaround;
1036     // fixing the bug would mean splitting the block chain (old
1037     // clients would not accept new CHECKMULTISIG transactions,
1038     // and vice-versa)
1039     //
1040     result << OP_0;
1041     for (const CKey &key : keys)
1042     {
1043         std::vector<unsigned char> vchSig;
1044         BOOST_CHECK(key.Sign(hash, vchSig));
1045         vchSig.push_back((unsigned char)SIGHASH_ALL);
1046         result << vchSig;
1047     }
1048     return result;
1049 }
1050 static CScript
sign_multisig(const CScript & scriptPubKey,const CKey & key,const CTransaction & transaction)1051 sign_multisig(const CScript& scriptPubKey, const CKey& key, const CTransaction& transaction)
1052 {
1053     std::vector<CKey> keys;
1054     keys.push_back(key);
1055     return sign_multisig(scriptPubKey, keys, transaction);
1056 }
1057 
BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)1058 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)
1059 {
1060     ScriptError err;
1061     CKey key1, key2, key3;
1062     key1.MakeNewKey(true);
1063     key2.MakeNewKey(false);
1064     key3.MakeNewKey(true);
1065 
1066     CScript scriptPubKey12;
1067     scriptPubKey12 << OP_1 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
1068 
1069     const CTransaction txFrom12{BuildCreditingTransaction(scriptPubKey12)};
1070     CMutableTransaction txTo12 = BuildSpendingTransaction(CScript(), CScriptWitness(), txFrom12);
1071 
1072     CScript goodsig1 = sign_multisig(scriptPubKey12, key1, CTransaction(txTo12));
1073     BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1074     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1075     txTo12.vout[0].nValue = 2;
1076     BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1077     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1078 
1079     CScript goodsig2 = sign_multisig(scriptPubKey12, key2, CTransaction(txTo12));
1080     BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1081     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1082 
1083     CScript badsig1 = sign_multisig(scriptPubKey12, key3, CTransaction(txTo12));
1084     BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1085     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1086 }
1087 
BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)1088 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)
1089 {
1090     ScriptError err;
1091     CKey key1, key2, key3, key4;
1092     key1.MakeNewKey(true);
1093     key2.MakeNewKey(false);
1094     key3.MakeNewKey(true);
1095     key4.MakeNewKey(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 re-use 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 /* Wrapper around ProduceSignature to combine two scriptsigs */
CombineSignatures(const CTxOut & txout,const CMutableTransaction & tx,const SignatureData & scriptSig1,const SignatureData & scriptSig2)1158 SignatureData CombineSignatures(const CTxOut& txout, const CMutableTransaction& tx, const SignatureData& scriptSig1, const SignatureData& scriptSig2)
1159 {
1160     SignatureData data;
1161     data.MergeSignatureData(scriptSig1);
1162     data.MergeSignatureData(scriptSig2);
1163     ProduceSignature(DUMMY_SIGNING_PROVIDER, MutableTransactionSignatureCreator(&tx, 0, txout.nValue), txout.scriptPubKey, data);
1164     return data;
1165 }
1166 
BOOST_AUTO_TEST_CASE(script_combineSigs)1167 BOOST_AUTO_TEST_CASE(script_combineSigs)
1168 {
1169     // Test the ProduceSignature's ability to combine signatures function
1170     FillableSigningProvider keystore;
1171     std::vector<CKey> keys;
1172     std::vector<CPubKey> pubkeys;
1173     for (int i = 0; i < 3; i++)
1174     {
1175         CKey key;
1176         key.MakeNewKey(i%2 == 1);
1177         keys.push_back(key);
1178         pubkeys.push_back(key.GetPubKey());
1179         BOOST_CHECK(keystore.AddKey(key));
1180     }
1181 
1182     CMutableTransaction txFrom = BuildCreditingTransaction(GetScriptForDestination(PKHash(keys[0].GetPubKey())));
1183     CMutableTransaction txTo = BuildSpendingTransaction(CScript(), CScriptWitness(), CTransaction(txFrom));
1184     CScript& scriptPubKey = txFrom.vout[0].scriptPubKey;
1185     SignatureData scriptSig;
1186 
1187     SignatureData empty;
1188     SignatureData combined = CombineSignatures(txFrom.vout[0], txTo, empty, empty);
1189     BOOST_CHECK(combined.scriptSig.empty());
1190 
1191     // Single signature case:
1192     BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL)); // changes scriptSig
1193     scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1194     combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
1195     BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1196     combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
1197     BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1198     SignatureData scriptSigCopy = scriptSig;
1199     // Signing again will give a different, valid signature:
1200     BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL));
1201     scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1202     combined = CombineSignatures(txFrom.vout[0], txTo, scriptSigCopy, scriptSig);
1203     BOOST_CHECK(combined.scriptSig == scriptSigCopy.scriptSig || combined.scriptSig == scriptSig.scriptSig);
1204 
1205     // P2SH, single-signature case:
1206     CScript pkSingle; pkSingle << ToByteVector(keys[0].GetPubKey()) << OP_CHECKSIG;
1207     BOOST_CHECK(keystore.AddCScript(pkSingle));
1208     scriptPubKey = GetScriptForDestination(ScriptHash(pkSingle));
1209     BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL));
1210     scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1211     combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
1212     BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1213     combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
1214     BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1215     scriptSigCopy = scriptSig;
1216     BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL));
1217     scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1218     combined = CombineSignatures(txFrom.vout[0], txTo, scriptSigCopy, scriptSig);
1219     BOOST_CHECK(combined.scriptSig == scriptSigCopy.scriptSig || combined.scriptSig == scriptSig.scriptSig);
1220 
1221     // Hardest case:  Multisig 2-of-3
1222     scriptPubKey = GetScriptForMultisig(2, pubkeys);
1223     BOOST_CHECK(keystore.AddCScript(scriptPubKey));
1224     BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL));
1225     scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1226     combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
1227     BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1228     combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
1229     BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1230 
1231     // A couple of partially-signed versions:
1232     std::vector<unsigned char> sig1;
1233     uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL, 0, SigVersion::BASE);
1234     BOOST_CHECK(keys[0].Sign(hash1, sig1));
1235     sig1.push_back(SIGHASH_ALL);
1236     std::vector<unsigned char> sig2;
1237     uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE, 0, SigVersion::BASE);
1238     BOOST_CHECK(keys[1].Sign(hash2, sig2));
1239     sig2.push_back(SIGHASH_NONE);
1240     std::vector<unsigned char> sig3;
1241     uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE, 0, SigVersion::BASE);
1242     BOOST_CHECK(keys[2].Sign(hash3, sig3));
1243     sig3.push_back(SIGHASH_SINGLE);
1244 
1245     // Not fussy about order (or even existence) of placeholders or signatures:
1246     CScript partial1a = CScript() << OP_0 << sig1 << OP_0;
1247     CScript partial1b = CScript() << OP_0 << OP_0 << sig1;
1248     CScript partial2a = CScript() << OP_0 << sig2;
1249     CScript partial2b = CScript() << sig2 << OP_0;
1250     CScript partial3a = CScript() << sig3;
1251     CScript partial3b = CScript() << OP_0 << OP_0 << sig3;
1252     CScript partial3c = CScript() << OP_0 << sig3 << OP_0;
1253     CScript complete12 = CScript() << OP_0 << sig1 << sig2;
1254     CScript complete13 = CScript() << OP_0 << sig1 << sig3;
1255     CScript complete23 = CScript() << OP_0 << sig2 << sig3;
1256     SignatureData partial1_sigs;
1257     partial1_sigs.signatures.emplace(keys[0].GetPubKey().GetID(), SigPair(keys[0].GetPubKey(), sig1));
1258     SignatureData partial2_sigs;
1259     partial2_sigs.signatures.emplace(keys[1].GetPubKey().GetID(), SigPair(keys[1].GetPubKey(), sig2));
1260     SignatureData partial3_sigs;
1261     partial3_sigs.signatures.emplace(keys[2].GetPubKey().GetID(), SigPair(keys[2].GetPubKey(), sig3));
1262 
1263     combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial1_sigs);
1264     BOOST_CHECK(combined.scriptSig == partial1a);
1265     combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial2_sigs);
1266     BOOST_CHECK(combined.scriptSig == complete12);
1267     combined = CombineSignatures(txFrom.vout[0], txTo, partial2_sigs, partial1_sigs);
1268     BOOST_CHECK(combined.scriptSig == complete12);
1269     combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial2_sigs);
1270     BOOST_CHECK(combined.scriptSig == complete12);
1271     combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial1_sigs);
1272     BOOST_CHECK(combined.scriptSig == complete13);
1273     combined = CombineSignatures(txFrom.vout[0], txTo, partial2_sigs, partial3_sigs);
1274     BOOST_CHECK(combined.scriptSig == complete23);
1275     combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial2_sigs);
1276     BOOST_CHECK(combined.scriptSig == complete23);
1277     combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial3_sigs);
1278     BOOST_CHECK(combined.scriptSig == partial3c);
1279 }
1280 
BOOST_AUTO_TEST_CASE(script_standard_push)1281 BOOST_AUTO_TEST_CASE(script_standard_push)
1282 {
1283     ScriptError err;
1284     for (int i=0; i<67000; i++) {
1285         CScript script;
1286         script << i;
1287         BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Number " << i << " is not pure push.");
1288         BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Number " << i << " push is not minimal data.");
1289         BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1290     }
1291 
1292     for (unsigned int i=0; i<=MAX_SCRIPT_ELEMENT_SIZE; i++) {
1293         std::vector<unsigned char> data(i, '\111');
1294         CScript script;
1295         script << data;
1296         BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Length " << i << " is not pure push.");
1297         BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Length " << i << " push is not minimal data.");
1298         BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1299     }
1300 }
1301 
BOOST_AUTO_TEST_CASE(script_IsPushOnly_on_invalid_scripts)1302 BOOST_AUTO_TEST_CASE(script_IsPushOnly_on_invalid_scripts)
1303 {
1304     // IsPushOnly returns false when given a script containing only pushes that
1305     // are invalid due to truncation. IsPushOnly() is consensus critical
1306     // because P2SH evaluation uses it, although this specific behavior should
1307     // not be consensus critical as the P2SH evaluation would fail first due to
1308     // the invalid push. Still, it doesn't hurt to test it explicitly.
1309     static const unsigned char direct[] = { 1 };
1310     BOOST_CHECK(!CScript(direct, direct+sizeof(direct)).IsPushOnly());
1311 }
1312 
BOOST_AUTO_TEST_CASE(script_GetScriptAsm)1313 BOOST_AUTO_TEST_CASE(script_GetScriptAsm)
1314 {
1315     BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2, true));
1316     BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY, true));
1317     BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2));
1318     BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY));
1319 
1320     std::string derSig("304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c5090");
1321     std::string pubKey("03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2");
1322     std::vector<unsigned char> vchPubKey = ToByteVector(ParseHex(pubKey));
1323 
1324     BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey, true));
1325     BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey, true));
1326     BOOST_CHECK_EQUAL(derSig + "[ALL] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey, true));
1327     BOOST_CHECK_EQUAL(derSig + "[NONE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey, true));
1328     BOOST_CHECK_EQUAL(derSig + "[SINGLE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey, true));
1329     BOOST_CHECK_EQUAL(derSig + "[ALL|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey, true));
1330     BOOST_CHECK_EQUAL(derSig + "[NONE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey, true));
1331     BOOST_CHECK_EQUAL(derSig + "[SINGLE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey, true));
1332 
1333     BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey));
1334     BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey));
1335     BOOST_CHECK_EQUAL(derSig + "01 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey));
1336     BOOST_CHECK_EQUAL(derSig + "02 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey));
1337     BOOST_CHECK_EQUAL(derSig + "03 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey));
1338     BOOST_CHECK_EQUAL(derSig + "81 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey));
1339     BOOST_CHECK_EQUAL(derSig + "82 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey));
1340     BOOST_CHECK_EQUAL(derSig + "83 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey));
1341 }
1342 
ScriptFromHex(const std::string & str)1343 static CScript ScriptFromHex(const std::string& str)
1344 {
1345     std::vector<unsigned char> data = ParseHex(str);
1346     return CScript(data.begin(), data.end());
1347 }
1348 
BOOST_AUTO_TEST_CASE(script_FindAndDelete)1349 BOOST_AUTO_TEST_CASE(script_FindAndDelete)
1350 {
1351     // Exercise the FindAndDelete functionality
1352     CScript s;
1353     CScript d;
1354     CScript expect;
1355 
1356     s = CScript() << OP_1 << OP_2;
1357     d = CScript(); // delete nothing should be a no-op
1358     expect = s;
1359     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
1360     BOOST_CHECK(s == expect);
1361 
1362     s = CScript() << OP_1 << OP_2 << OP_3;
1363     d = CScript() << OP_2;
1364     expect = CScript() << OP_1 << OP_3;
1365     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1366     BOOST_CHECK(s == expect);
1367 
1368     s = CScript() << OP_3 << OP_1 << OP_3 << OP_3 << OP_4 << OP_3;
1369     d = CScript() << OP_3;
1370     expect = CScript() << OP_1 << OP_4;
1371     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 4);
1372     BOOST_CHECK(s == expect);
1373 
1374     s = ScriptFromHex("0302ff03"); // PUSH 0x02ff03 onto stack
1375     d = ScriptFromHex("0302ff03");
1376     expect = CScript();
1377     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1378     BOOST_CHECK(s == expect);
1379 
1380     s = ScriptFromHex("0302ff030302ff03"); // PUSH 0x2ff03 PUSH 0x2ff03
1381     d = ScriptFromHex("0302ff03");
1382     expect = CScript();
1383     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 2);
1384     BOOST_CHECK(s == expect);
1385 
1386     s = ScriptFromHex("0302ff030302ff03");
1387     d = ScriptFromHex("02");
1388     expect = s; // FindAndDelete matches entire opcodes
1389     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
1390     BOOST_CHECK(s == expect);
1391 
1392     s = ScriptFromHex("0302ff030302ff03");
1393     d = ScriptFromHex("ff");
1394     expect = s;
1395     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
1396     BOOST_CHECK(s == expect);
1397 
1398     // This is an odd edge case: strip of the push-three-bytes
1399     // prefix, leaving 02ff03 which is push-two-bytes:
1400     s = ScriptFromHex("0302ff030302ff03");
1401     d = ScriptFromHex("03");
1402     expect = CScript() << ParseHex("ff03") << ParseHex("ff03");
1403     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 2);
1404     BOOST_CHECK(s == expect);
1405 
1406     // Byte sequence that spans multiple opcodes:
1407     s = ScriptFromHex("02feed5169"); // PUSH(0xfeed) OP_1 OP_VERIFY
1408     d = ScriptFromHex("feed51");
1409     expect = s;
1410     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0); // doesn't match 'inside' opcodes
1411     BOOST_CHECK(s == expect);
1412 
1413     s = ScriptFromHex("02feed5169"); // PUSH(0xfeed) OP_1 OP_VERIFY
1414     d = ScriptFromHex("02feed51");
1415     expect = ScriptFromHex("69");
1416     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1417     BOOST_CHECK(s == expect);
1418 
1419     s = ScriptFromHex("516902feed5169");
1420     d = ScriptFromHex("feed51");
1421     expect = s;
1422     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
1423     BOOST_CHECK(s == expect);
1424 
1425     s = ScriptFromHex("516902feed5169");
1426     d = ScriptFromHex("02feed51");
1427     expect = ScriptFromHex("516969");
1428     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1429     BOOST_CHECK(s == expect);
1430 
1431     s = CScript() << OP_0 << OP_0 << OP_1 << OP_1;
1432     d = CScript() << OP_0 << OP_1;
1433     expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass
1434     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1435     BOOST_CHECK(s == expect);
1436 
1437     s = CScript() << OP_0 << OP_0 << OP_1 << OP_0 << OP_1 << OP_1;
1438     d = CScript() << OP_0 << OP_1;
1439     expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass
1440     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 2);
1441     BOOST_CHECK(s == expect);
1442 
1443     // Another weird edge case:
1444     // End with invalid push (not enough data)...
1445     s = ScriptFromHex("0003feed");
1446     d = ScriptFromHex("03feed"); // ... can remove the invalid push
1447     expect = ScriptFromHex("00");
1448     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1449     BOOST_CHECK(s == expect);
1450 
1451     s = ScriptFromHex("0003feed");
1452     d = ScriptFromHex("00");
1453     expect = ScriptFromHex("03feed");
1454     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1455     BOOST_CHECK(s == expect);
1456 }
1457 
BOOST_AUTO_TEST_CASE(script_HasValidOps)1458 BOOST_AUTO_TEST_CASE(script_HasValidOps)
1459 {
1460     // Exercise the HasValidOps functionality
1461     CScript script;
1462     script = ScriptFromHex("76a9141234567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac"); // Normal script
1463     BOOST_CHECK(script.HasValidOps());
1464     script = ScriptFromHex("76a914ff34567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac");
1465     BOOST_CHECK(script.HasValidOps());
1466     script = ScriptFromHex("ff88ac"); // Script with OP_INVALIDOPCODE explicit
1467     BOOST_CHECK(!script.HasValidOps());
1468     script = ScriptFromHex("88acc0"); // Script with undefined opcode
1469     BOOST_CHECK(!script.HasValidOps());
1470 }
1471 
TxFromHex(const std::string & str)1472 static CMutableTransaction TxFromHex(const std::string& str)
1473 {
1474     CMutableTransaction tx;
1475     VectorReader(SER_DISK, SERIALIZE_TRANSACTION_NO_WITNESS, ParseHex(str), 0) >> tx;
1476     return tx;
1477 }
1478 
TxOutsFromJSON(const UniValue & univalue)1479 static std::vector<CTxOut> TxOutsFromJSON(const UniValue& univalue)
1480 {
1481     assert(univalue.isArray());
1482     std::vector<CTxOut> prevouts;
1483     for (size_t i = 0; i < univalue.size(); ++i) {
1484         CTxOut txout;
1485         VectorReader(SER_DISK, 0, ParseHex(univalue[i].get_str()), 0) >> txout;
1486         prevouts.push_back(std::move(txout));
1487     }
1488     return prevouts;
1489 }
1490 
ScriptWitnessFromJSON(const UniValue & univalue)1491 static CScriptWitness ScriptWitnessFromJSON(const UniValue& univalue)
1492 {
1493     assert(univalue.isArray());
1494     CScriptWitness scriptwitness;
1495     for (size_t i = 0; i < univalue.size(); ++i) {
1496         auto bytes = ParseHex(univalue[i].get_str());
1497         scriptwitness.stack.push_back(std::move(bytes));
1498     }
1499     return scriptwitness;
1500 }
1501 
1502 #if defined(HAVE_CONSENSUS_LIB)
1503 
1504 /* Test simple (successful) usage of bitcoinconsensus_verify_script */
BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_returns_true)1505 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_returns_true)
1506 {
1507     unsigned int libconsensus_flags = 0;
1508     int nIn = 0;
1509 
1510     CScript scriptPubKey;
1511     CScript scriptSig;
1512     CScriptWitness wit;
1513 
1514     scriptPubKey << OP_1;
1515     CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1);
1516     CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx);
1517 
1518     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
1519     stream << spendTx;
1520 
1521     bitcoinconsensus_error err;
1522     int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), stream.data(), stream.size(), nIn, libconsensus_flags, &err);
1523     BOOST_CHECK_EQUAL(result, 1);
1524     BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_OK);
1525 }
1526 
1527 /* Test bitcoinconsensus_verify_script returns invalid tx index err*/
BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_index_err)1528 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_index_err)
1529 {
1530     unsigned int libconsensus_flags = 0;
1531     int nIn = 3;
1532 
1533     CScript scriptPubKey;
1534     CScript scriptSig;
1535     CScriptWitness wit;
1536 
1537     scriptPubKey << OP_EQUAL;
1538     CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1);
1539     CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx);
1540 
1541     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
1542     stream << spendTx;
1543 
1544     bitcoinconsensus_error err;
1545     int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), stream.data(), stream.size(), nIn, libconsensus_flags, &err);
1546     BOOST_CHECK_EQUAL(result, 0);
1547     BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_TX_INDEX);
1548 }
1549 
1550 /* Test bitcoinconsensus_verify_script returns tx size mismatch err*/
BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_size)1551 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_size)
1552 {
1553     unsigned int libconsensus_flags = 0;
1554     int nIn = 0;
1555 
1556     CScript scriptPubKey;
1557     CScript scriptSig;
1558     CScriptWitness wit;
1559 
1560     scriptPubKey << OP_EQUAL;
1561     CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1);
1562     CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx);
1563 
1564     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
1565     stream << spendTx;
1566 
1567     bitcoinconsensus_error err;
1568     int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), stream.data(), stream.size() * 2, nIn, libconsensus_flags, &err);
1569     BOOST_CHECK_EQUAL(result, 0);
1570     BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_TX_SIZE_MISMATCH);
1571 }
1572 
1573 /* Test bitcoinconsensus_verify_script returns invalid tx serialization error */
BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_serialization)1574 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_serialization)
1575 {
1576     unsigned int libconsensus_flags = 0;
1577     int nIn = 0;
1578 
1579     CScript scriptPubKey;
1580     CScript scriptSig;
1581     CScriptWitness wit;
1582 
1583     scriptPubKey << OP_EQUAL;
1584     CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1);
1585     CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx);
1586 
1587     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
1588     stream << 0xffffffff;
1589 
1590     bitcoinconsensus_error err;
1591     int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), stream.data(), stream.size(), nIn, libconsensus_flags, &err);
1592     BOOST_CHECK_EQUAL(result, 0);
1593     BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_TX_DESERIALIZE);
1594 }
1595 
1596 /* Test bitcoinconsensus_verify_script returns amount required error */
BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_amount_required_err)1597 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_amount_required_err)
1598 {
1599     unsigned int libconsensus_flags = bitcoinconsensus_SCRIPT_FLAGS_VERIFY_WITNESS;
1600     int nIn = 0;
1601 
1602     CScript scriptPubKey;
1603     CScript scriptSig;
1604     CScriptWitness wit;
1605 
1606     scriptPubKey << OP_EQUAL;
1607     CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1);
1608     CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx);
1609 
1610     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
1611     stream << spendTx;
1612 
1613     bitcoinconsensus_error err;
1614     int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), stream.data(), stream.size(), nIn, libconsensus_flags, &err);
1615     BOOST_CHECK_EQUAL(result, 0);
1616     BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_AMOUNT_REQUIRED);
1617 }
1618 
1619 /* Test bitcoinconsensus_verify_script returns invalid flags err */
BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_invalid_flags)1620 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_invalid_flags)
1621 {
1622     unsigned int libconsensus_flags = 1 << 3;
1623     int nIn = 0;
1624 
1625     CScript scriptPubKey;
1626     CScript scriptSig;
1627     CScriptWitness wit;
1628 
1629     scriptPubKey << OP_EQUAL;
1630     CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1);
1631     CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx);
1632 
1633     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
1634     stream << spendTx;
1635 
1636     bitcoinconsensus_error err;
1637     int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), stream.data(), stream.size(), nIn, libconsensus_flags, &err);
1638     BOOST_CHECK_EQUAL(result, 0);
1639     BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_INVALID_FLAGS);
1640 }
1641 
1642 #endif // defined(HAVE_CONSENSUS_LIB)
1643 
AllConsensusFlags()1644 static std::vector<unsigned int> AllConsensusFlags()
1645 {
1646     std::vector<unsigned int> ret;
1647 
1648     for (unsigned int i = 0; i < 128; ++i) {
1649         unsigned int flag = 0;
1650         if (i & 1) flag |= SCRIPT_VERIFY_P2SH;
1651         if (i & 2) flag |= SCRIPT_VERIFY_DERSIG;
1652         if (i & 4) flag |= SCRIPT_VERIFY_NULLDUMMY;
1653         if (i & 8) flag |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1654         if (i & 16) flag |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1655         if (i & 32) flag |= SCRIPT_VERIFY_WITNESS;
1656         if (i & 64) flag |= SCRIPT_VERIFY_TAPROOT;
1657 
1658         // SCRIPT_VERIFY_WITNESS requires SCRIPT_VERIFY_P2SH
1659         if (flag & SCRIPT_VERIFY_WITNESS && !(flag & SCRIPT_VERIFY_P2SH)) continue;
1660         // SCRIPT_VERIFY_TAPROOT requires SCRIPT_VERIFY_WITNESS
1661         if (flag & SCRIPT_VERIFY_TAPROOT && !(flag & SCRIPT_VERIFY_WITNESS)) continue;
1662 
1663         ret.push_back(flag);
1664     }
1665 
1666     return ret;
1667 }
1668 
1669 /** Precomputed list of all valid combinations of consensus-relevant script validation flags. */
1670 static const std::vector<unsigned int> ALL_CONSENSUS_FLAGS = AllConsensusFlags();
1671 
AssetTest(const UniValue & test)1672 static void AssetTest(const UniValue& test)
1673 {
1674     BOOST_CHECK(test.isObject());
1675 
1676     CMutableTransaction mtx = TxFromHex(test["tx"].get_str());
1677     const std::vector<CTxOut> prevouts = TxOutsFromJSON(test["prevouts"]);
1678     BOOST_CHECK(prevouts.size() == mtx.vin.size());
1679     size_t idx = test["index"].get_int64();
1680     unsigned int test_flags = ParseScriptFlags(test["flags"].get_str());
1681     bool fin = test.exists("final") && test["final"].get_bool();
1682 
1683     if (test.exists("success")) {
1684         mtx.vin[idx].scriptSig = ScriptFromHex(test["success"]["scriptSig"].get_str());
1685         mtx.vin[idx].scriptWitness = ScriptWitnessFromJSON(test["success"]["witness"]);
1686         CTransaction tx(mtx);
1687         PrecomputedTransactionData txdata;
1688         txdata.Init(tx, std::vector<CTxOut>(prevouts));
1689         CachingTransactionSignatureChecker txcheck(&tx, idx, prevouts[idx].nValue, true, txdata);
1690         for (const auto flags : ALL_CONSENSUS_FLAGS) {
1691             // "final": true tests are valid for all flags. Others are only valid with flags that are
1692             // a subset of test_flags.
1693             if (fin || ((flags & test_flags) == flags)) {
1694                 bool ret = VerifyScript(tx.vin[idx].scriptSig, prevouts[idx].scriptPubKey, &tx.vin[idx].scriptWitness, flags, txcheck, nullptr);
1695                 BOOST_CHECK(ret);
1696             }
1697         }
1698     }
1699 
1700     if (test.exists("failure")) {
1701         mtx.vin[idx].scriptSig = ScriptFromHex(test["failure"]["scriptSig"].get_str());
1702         mtx.vin[idx].scriptWitness = ScriptWitnessFromJSON(test["failure"]["witness"]);
1703         CTransaction tx(mtx);
1704         PrecomputedTransactionData txdata;
1705         txdata.Init(tx, std::vector<CTxOut>(prevouts));
1706         CachingTransactionSignatureChecker txcheck(&tx, idx, prevouts[idx].nValue, true, txdata);
1707         for (const auto flags : ALL_CONSENSUS_FLAGS) {
1708             // If a test is supposed to fail with test_flags, it should also fail with any superset thereof.
1709             if ((flags & test_flags) == test_flags) {
1710                 bool ret = VerifyScript(tx.vin[idx].scriptSig, prevouts[idx].scriptPubKey, &tx.vin[idx].scriptWitness, flags, txcheck, nullptr);
1711                 BOOST_CHECK(!ret);
1712             }
1713         }
1714     }
1715 }
1716 
BOOST_AUTO_TEST_CASE(script_assets_test)1717 BOOST_AUTO_TEST_CASE(script_assets_test)
1718 {
1719     // See src/test/fuzz/script_assets_test_minimizer.cpp for information on how to generate
1720     // the script_assets_test.json file used by this test.
1721 
1722     const char* dir = std::getenv("DIR_UNIT_TEST_DATA");
1723     BOOST_WARN_MESSAGE(dir != nullptr, "Variable DIR_UNIT_TEST_DATA unset, skipping script_assets_test");
1724     if (dir == nullptr) return;
1725     auto path = fs::path(dir) / "script_assets_test.json";
1726     bool exists = fs::exists(path);
1727     BOOST_WARN_MESSAGE(exists, "File $DIR_UNIT_TEST_DATA/script_assets_test.json not found, skipping script_assets_test");
1728     if (!exists) return;
1729     fs::ifstream file(path);
1730     BOOST_CHECK(file.is_open());
1731     file.seekg(0, std::ios::end);
1732     size_t length = file.tellg();
1733     file.seekg(0, std::ios::beg);
1734     std::string data(length, '\0');
1735     file.read(data.data(), data.size());
1736     UniValue tests = read_json(data);
1737     BOOST_CHECK(tests.isArray());
1738     BOOST_CHECK(tests.size() > 0);
1739 
1740     for (size_t i = 0; i < tests.size(); i++) {
1741         AssetTest(tests[i]);
1742     }
1743     file.close();
1744 }
1745 
1746 BOOST_AUTO_TEST_SUITE_END()
1747