Bitcoin Core  31.0.0
P2P Digital Currency
script_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-present 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 #include <test/data/bip341_wallet_vectors.json.h>
7 
8 #include <common/system.h>
9 #include <core_io.h>
10 #include <key.h>
11 #include <rpc/util.h>
12 #include <script/interpreter.h>
13 #include <script/script.h>
14 #include <script/script_error.h>
15 #include <script/sigcache.h>
16 #include <script/sign.h>
17 #include <script/signingprovider.h>
18 #include <script/solver.h>
19 #include <streams.h>
20 #include <test/util/json.h>
21 #include <test/util/random.h>
22 #include <test/util/common.h>
23 #include <test/util/setup_common.h>
25 #include <util/fs.h>
26 #include <util/strencodings.h>
27 #include <util/string.h>
28 
29 #include <cstdint>
30 #include <string>
31 #include <vector>
32 
33 #include <boost/test/unit_test.hpp>
34 
35 #include <secp256k1.h>
36 #include <univalue.h>
37 
38 // Uncomment if you want to output updated JSON tests.
39 // #define UPDATE_JSON_TESTS
40 
41 using namespace util::hex_literals;
42 
44 
45 script_verify_flags ParseScriptFlags(std::string strFlags);
46 
48 {
50  const char *name;
51 };
52 
54  {SCRIPT_ERR_OK, "OK"},
55  {SCRIPT_ERR_EVAL_FALSE, "EVAL_FALSE"},
56  {SCRIPT_ERR_OP_RETURN, "OP_RETURN"},
57  {SCRIPT_ERR_SCRIPT_SIZE, "SCRIPT_SIZE"},
58  {SCRIPT_ERR_PUSH_SIZE, "PUSH_SIZE"},
59  {SCRIPT_ERR_OP_COUNT, "OP_COUNT"},
60  {SCRIPT_ERR_STACK_SIZE, "STACK_SIZE"},
61  {SCRIPT_ERR_SIG_COUNT, "SIG_COUNT"},
62  {SCRIPT_ERR_PUBKEY_COUNT, "PUBKEY_COUNT"},
63  {SCRIPT_ERR_VERIFY, "VERIFY"},
64  {SCRIPT_ERR_EQUALVERIFY, "EQUALVERIFY"},
65  {SCRIPT_ERR_CHECKMULTISIGVERIFY, "CHECKMULTISIGVERIFY"},
66  {SCRIPT_ERR_CHECKSIGVERIFY, "CHECKSIGVERIFY"},
67  {SCRIPT_ERR_NUMEQUALVERIFY, "NUMEQUALVERIFY"},
68  {SCRIPT_ERR_BAD_OPCODE, "BAD_OPCODE"},
69  {SCRIPT_ERR_DISABLED_OPCODE, "DISABLED_OPCODE"},
70  {SCRIPT_ERR_INVALID_STACK_OPERATION, "INVALID_STACK_OPERATION"},
71  {SCRIPT_ERR_INVALID_ALTSTACK_OPERATION, "INVALID_ALTSTACK_OPERATION"},
72  {SCRIPT_ERR_UNBALANCED_CONDITIONAL, "UNBALANCED_CONDITIONAL"},
73  {SCRIPT_ERR_NEGATIVE_LOCKTIME, "NEGATIVE_LOCKTIME"},
74  {SCRIPT_ERR_UNSATISFIED_LOCKTIME, "UNSATISFIED_LOCKTIME"},
75  {SCRIPT_ERR_SIG_HASHTYPE, "SIG_HASHTYPE"},
76  {SCRIPT_ERR_SIG_DER, "SIG_DER"},
77  {SCRIPT_ERR_MINIMALDATA, "MINIMALDATA"},
78  {SCRIPT_ERR_SIG_PUSHONLY, "SIG_PUSHONLY"},
79  {SCRIPT_ERR_SIG_HIGH_S, "SIG_HIGH_S"},
80  {SCRIPT_ERR_SIG_NULLDUMMY, "SIG_NULLDUMMY"},
81  {SCRIPT_ERR_PUBKEYTYPE, "PUBKEYTYPE"},
82  {SCRIPT_ERR_CLEANSTACK, "CLEANSTACK"},
83  {SCRIPT_ERR_MINIMALIF, "MINIMALIF"},
84  {SCRIPT_ERR_SIG_NULLFAIL, "NULLFAIL"},
85  {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS, "DISCOURAGE_UPGRADABLE_NOPS"},
86  {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, "DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"},
87  {SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH, "WITNESS_PROGRAM_WRONG_LENGTH"},
88  {SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY, "WITNESS_PROGRAM_WITNESS_EMPTY"},
89  {SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH, "WITNESS_PROGRAM_MISMATCH"},
90  {SCRIPT_ERR_WITNESS_MALLEATED, "WITNESS_MALLEATED"},
91  {SCRIPT_ERR_WITNESS_MALLEATED_P2SH, "WITNESS_MALLEATED_P2SH"},
92  {SCRIPT_ERR_WITNESS_UNEXPECTED, "WITNESS_UNEXPECTED"},
93  {SCRIPT_ERR_WITNESS_PUBKEYTYPE, "WITNESS_PUBKEYTYPE"},
94  {SCRIPT_ERR_TAPSCRIPT_EMPTY_PUBKEY, "TAPSCRIPT_EMPTY_PUBKEY"},
95  {SCRIPT_ERR_OP_CODESEPARATOR, "OP_CODESEPARATOR"},
96  {SCRIPT_ERR_SIG_FINDANDDELETE, "SIG_FINDANDDELETE"},
97  {SCRIPT_ERR_SCRIPTNUM, "SCRIPTNUM"}
98 };
99 
101 {
102  return util::Join(GetScriptFlagNames(flags), ",");
103 }
104 
105 static std::string FormatScriptError(ScriptError_t err)
106 {
107  for (const auto& se : script_errors)
108  if (se.err == err)
109  return se.name;
110  BOOST_ERROR("Unknown scripterror enumeration value, update script_errors in script_tests.cpp.");
111  return "";
112 }
113 
114 static ScriptError_t ParseScriptError(const std::string& name)
115 {
116  for (const auto& se : script_errors)
117  if (se.name == name)
118  return se.err;
119  BOOST_ERROR("Unknown scripterror \"" << name << "\" in test description");
121 }
122 
124 void DoTest(const CScript& scriptPubKey, const CScript& scriptSig, const CScriptWitness& scriptWitness, script_verify_flags flags, const std::string& message, int scriptError, CAmount nValue = 0)
125 {
126  bool expect = (scriptError == SCRIPT_ERR_OK);
130  }
131  ScriptError err;
132  const CTransaction txCredit{BuildCreditingTransaction(scriptPubKey, nValue)};
133  CMutableTransaction tx = BuildSpendingTransaction(scriptSig, scriptWitness, txCredit);
134  BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, &scriptWitness, flags, MutableTransactionSignatureChecker(&tx, 0, txCredit.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err) == expect, message);
135  BOOST_CHECK_MESSAGE(err == scriptError, FormatScriptError(err) + " where " + FormatScriptError((ScriptError_t)scriptError) + " expected: " + message);
136 
137  // Verify that removing flags from a passing test or adding flags to a failing test does not change the result.
138  for (int i = 0; i < 256; ++i) {
140  script_verify_flags combined_flags{expect ? (flags & ~extra_flags) : (flags | extra_flags)};
141  // Weed out some invalid flag combinations.
142  if (combined_flags & SCRIPT_VERIFY_CLEANSTACK && ~combined_flags & (SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS)) continue;
143  if (combined_flags & SCRIPT_VERIFY_WITNESS && ~combined_flags & SCRIPT_VERIFY_P2SH) continue;
144  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.as_int()));
145  }
146 }
147 }; // struct ScriptTest
148 
149 void static NegateSignatureS(std::vector<unsigned char>& vchSig) {
150  // Parse the signature.
151  std::vector<unsigned char> r, s;
152  r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);
153  s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);
154 
155  while (s.size() < 33) {
156  s.insert(s.begin(), 0x00);
157  }
158  assert(s[0] == 0);
159  // Perform mod-n negation of s by (ab)using libsecp256k1
160  // (note that this function is meant to be used for negating secret keys,
161  // but it works for any non-zero scalar modulo the group order, i.e. also for s)
163  assert(ret);
164 
165  if (s[1] < 0x80) {
166  s.erase(s.begin());
167  }
168 
169  // Reconstruct the signature.
170  vchSig.clear();
171  vchSig.push_back(0x30);
172  vchSig.push_back(4 + r.size() + s.size());
173  vchSig.push_back(0x02);
174  vchSig.push_back(r.size());
175  vchSig.insert(vchSig.end(), r.begin(), r.end());
176  vchSig.push_back(0x02);
177  vchSig.push_back(s.size());
178  vchSig.insert(vchSig.end(), s.begin(), s.end());
179 }
180 
181 namespace
182 {
183 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};
184 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};
185 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};
186 
187 struct KeyData
188 {
189  CKey key0, key0C, key1, key1C, key2, key2C;
190  CPubKey pubkey0, pubkey0C, pubkey0H;
191  CPubKey pubkey1, pubkey1C;
192  CPubKey pubkey2, pubkey2C;
193 
194  KeyData()
195  {
196  key0.Set(vchKey0, vchKey0 + 32, false);
197  key0C.Set(vchKey0, vchKey0 + 32, true);
198  pubkey0 = key0.GetPubKey();
199  pubkey0H = key0.GetPubKey();
200  pubkey0C = key0C.GetPubKey();
201  *const_cast<unsigned char*>(pubkey0H.data()) = 0x06 | (pubkey0H[64] & 1);
202 
203  key1.Set(vchKey1, vchKey1 + 32, false);
204  key1C.Set(vchKey1, vchKey1 + 32, true);
205  pubkey1 = key1.GetPubKey();
206  pubkey1C = key1C.GetPubKey();
207 
208  key2.Set(vchKey2, vchKey2 + 32, false);
209  key2C.Set(vchKey2, vchKey2 + 32, true);
210  pubkey2 = key2.GetPubKey();
211  pubkey2C = key2C.GetPubKey();
212  }
213 };
214 
215 enum class WitnessMode {
216  NONE,
217  PKH,
218  SH
219 };
220 
221 class TestBuilder
222 {
223 private:
225  CScript script;
227  CScript redeemscript;
229  CScript witscript;
230  CScriptWitness scriptWitness;
231  CTransactionRef creditTx;
232  CMutableTransaction spendTx;
233  bool havePush{false};
234  std::vector<unsigned char> push;
235  std::string comment;
237  int scriptError{SCRIPT_ERR_OK};
238  CAmount nValue;
239 
240  void DoPush()
241  {
242  if (havePush) {
243  spendTx.vin[0].scriptSig << push;
244  havePush = false;
245  }
246  }
247 
248  void DoPush(const std::vector<unsigned char>& data)
249  {
250  DoPush();
251  push = data;
252  havePush = true;
253  }
254 
255 public:
256  TestBuilder(const CScript& script_, const std::string& comment_, script_verify_flags flags_, bool P2SH = false, WitnessMode wm = WitnessMode::NONE, int witnessversion = 0, CAmount nValue_ = 0) : script(script_), comment(comment_), flags(flags_), nValue(nValue_)
257  {
258  CScript scriptPubKey = script;
259  if (wm == WitnessMode::PKH) {
260  uint160 hash;
261  CHash160().Write(std::span{script}.subspan(1)).Finalize(hash);
263  scriptPubKey = CScript() << witnessversion << ToByteVector(hash);
264  } else if (wm == WitnessMode::SH) {
265  witscript = scriptPubKey;
266  uint256 hash;
267  CSHA256().Write(witscript.data(), witscript.size()).Finalize(hash.begin());
268  scriptPubKey = CScript() << witnessversion << ToByteVector(hash);
269  }
270  if (P2SH) {
271  redeemscript = scriptPubKey;
272  scriptPubKey = CScript() << OP_HASH160 << ToByteVector(CScriptID(redeemscript)) << OP_EQUAL;
273  }
274  creditTx = MakeTransactionRef(BuildCreditingTransaction(scriptPubKey, nValue));
275  spendTx = BuildSpendingTransaction(CScript(), CScriptWitness(), *creditTx);
276  }
277 
278  TestBuilder& ScriptError(ScriptError_t err)
279  {
280  scriptError = err;
281  return *this;
282  }
283 
284  TestBuilder& Opcode(const opcodetype& _op)
285  {
286  DoPush();
287  spendTx.vin[0].scriptSig << _op;
288  return *this;
289  }
290 
291  TestBuilder& Num(int num)
292  {
293  DoPush();
294  spendTx.vin[0].scriptSig << num;
295  return *this;
296  }
297 
298  TestBuilder& Push(const std::string& hex)
299  {
300  DoPush(ParseHex(hex));
301  return *this;
302  }
303 
304  TestBuilder& Push(const CScript& _script)
305  {
306  DoPush(std::vector<unsigned char>(_script.begin(), _script.end()));
307  return *this;
308  }
309 
310  TestBuilder& PushSig(const CKey& key, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32, SigVersion sigversion = SigVersion::BASE, CAmount amount = 0)
311  {
312  uint256 hash = SignatureHash(script, spendTx, 0, nHashType, amount, sigversion);
313  std::vector<unsigned char> vchSig, r, s;
314  uint32_t iter = 0;
315  do {
316  key.Sign(hash, vchSig, false, iter++);
317  if ((lenS == 33) != (vchSig[5 + vchSig[3]] == 33)) {
318  NegateSignatureS(vchSig);
319  }
320  r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);
321  s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);
322  } while (lenR != r.size() || lenS != s.size());
323  vchSig.push_back(static_cast<unsigned char>(nHashType));
324  DoPush(vchSig);
325  return *this;
326  }
327 
328  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)
329  {
330  if (amount == -1)
331  amount = nValue;
332  return PushSig(key, nHashType, lenR, lenS, sigversion, amount).AsWit();
333  }
334 
335  TestBuilder& Push(const CPubKey& pubkey)
336  {
337  DoPush(std::vector<unsigned char>(pubkey.begin(), pubkey.end()));
338  return *this;
339  }
340 
341  TestBuilder& PushRedeem()
342  {
343  DoPush(std::vector<unsigned char>(redeemscript.begin(), redeemscript.end()));
344  return *this;
345  }
346 
347  TestBuilder& PushWitRedeem()
348  {
349  DoPush(std::vector<unsigned char>(witscript.begin(), witscript.end()));
350  return AsWit();
351  }
352 
353  TestBuilder& EditPush(unsigned int pos, const std::string& hexin, const std::string& hexout)
354  {
355  assert(havePush);
356  std::vector<unsigned char> datain = ParseHex(hexin);
357  std::vector<unsigned char> dataout = ParseHex(hexout);
358  assert(pos + datain.size() <= push.size());
359  BOOST_CHECK_MESSAGE(std::vector<unsigned char>(push.begin() + pos, push.begin() + pos + datain.size()) == datain, comment);
360  push.erase(push.begin() + pos, push.begin() + pos + datain.size());
361  push.insert(push.begin() + pos, dataout.begin(), dataout.end());
362  return *this;
363  }
364 
365  TestBuilder& DamagePush(unsigned int pos)
366  {
367  assert(havePush);
368  assert(pos < push.size());
369  push[pos] ^= 1;
370  return *this;
371  }
372 
373  TestBuilder& Test(ScriptTest& test)
374  {
375  TestBuilder copy = *this; // Make a copy so we can rollback the push.
376  DoPush();
377  test.DoTest(creditTx->vout[0].scriptPubKey, spendTx.vin[0].scriptSig, scriptWitness, flags, comment, scriptError, nValue);
378  *this = copy;
379  return *this;
380  }
381 
382  TestBuilder& AsWit()
383  {
384  assert(havePush);
385  scriptWitness.stack.push_back(push);
386  havePush = false;
387  return *this;
388  }
389 
390  UniValue GetJSON()
391  {
392  DoPush();
393  UniValue array(UniValue::VARR);
394  if (!scriptWitness.stack.empty()) {
396  for (unsigned i = 0; i < scriptWitness.stack.size(); i++) {
397  wit.push_back(HexStr(scriptWitness.stack[i]));
398  }
399  wit.push_back(ValueFromAmount(nValue));
400  array.push_back(std::move(wit));
401  }
402  array.push_back(FormatScript(spendTx.vin[0].scriptSig));
403  array.push_back(FormatScript(creditTx->vout[0].scriptPubKey));
404  array.push_back(FormatScriptFlags(flags));
405  array.push_back(FormatScriptError((ScriptError_t)scriptError));
406  array.push_back(comment);
407  return array;
408  }
409 
410  std::string GetComment() const
411  {
412  return comment;
413  }
414 };
415 
416 std::string JSONPrettyPrint(const UniValue& univalue)
417 {
418  std::string ret = univalue.write(4);
419  // Workaround for libunivalue pretty printer, which puts a space between commas and newlines
420  size_t pos = 0;
421  while ((pos = ret.find(" \n", pos)) != std::string::npos) {
422  ret.replace(pos, 2, "\n");
423  pos++;
424  }
425  return ret;
426 }
427 } // namespace
428 
430 
431 BOOST_AUTO_TEST_CASE(script_build)
432 {
433  const KeyData keys;
434 
435  std::vector<TestBuilder> tests;
436 
437  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
438  "P2PK", 0
439  ).PushSig(keys.key0));
440  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
441  "P2PK, bad sig", 0
442  ).PushSig(keys.key0).DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE));
443 
444  tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
445  "P2PKH", 0
446  ).PushSig(keys.key1).Push(keys.pubkey1C));
447  tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey2C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
448  "P2PKH, bad pubkey", 0
449  ).PushSig(keys.key2).Push(keys.pubkey2C).DamagePush(5).ScriptError(SCRIPT_ERR_EQUALVERIFY));
450 
451  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
452  "P2PK anyonecanpay", 0
453  ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY));
454  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
455  "P2PK anyonecanpay marked with normal hashtype", 0
456  ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY).EditPush(70, "81", "01").ScriptError(SCRIPT_ERR_EVAL_FALSE));
457 
458  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
459  "P2SH(P2PK)", SCRIPT_VERIFY_P2SH, true
460  ).PushSig(keys.key0).PushRedeem());
461  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
462  "P2SH(P2PK), bad redeemscript", SCRIPT_VERIFY_P2SH, true
463  ).PushSig(keys.key0).PushRedeem().DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE));
464 
465  tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey0.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
466  "P2SH(P2PKH)", SCRIPT_VERIFY_P2SH, true
467  ).PushSig(keys.key0).Push(keys.pubkey0).PushRedeem());
468  tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
469  "P2SH(P2PKH), bad sig but no VERIFY_P2SH", 0, true
470  ).PushSig(keys.key0).DamagePush(10).PushRedeem());
471  tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
472  "P2SH(P2PKH), bad sig", SCRIPT_VERIFY_P2SH, true
473  ).PushSig(keys.key0).DamagePush(10).PushRedeem().ScriptError(SCRIPT_ERR_EQUALVERIFY));
474 
475  tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
476  "3-of-3", 0
477  ).Num(0).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
478  tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
479  "3-of-3, 2 sigs", 0
480  ).Num(0).PushSig(keys.key0).PushSig(keys.key1).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
481 
482  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
483  "P2SH(2-of-3)", SCRIPT_VERIFY_P2SH, true
484  ).Num(0).PushSig(keys.key1).PushSig(keys.key2).PushRedeem());
485  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
486  "P2SH(2-of-3), 1 sig", SCRIPT_VERIFY_P2SH, true
487  ).Num(0).PushSig(keys.key1).Num(0).PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
488 
489  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
490  "P2PK with too much R padding but no DERSIG", 0
491  ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000"));
492  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
493  "P2PK with too much R padding", SCRIPT_VERIFY_DERSIG
494  ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER));
495  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
496  "P2PK with too much S padding but no DERSIG", 0
497  ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100"));
498  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
499  "P2PK with too much S padding", SCRIPT_VERIFY_DERSIG
500  ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100").ScriptError(SCRIPT_ERR_SIG_DER));
501  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
502  "P2PK with too little R padding but no DERSIG", 0
503  ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
504  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
505  "P2PK with too little R padding", SCRIPT_VERIFY_DERSIG
506  ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
507  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
508  "P2PK NOT with bad sig with too much R padding but no DERSIG", 0
509  ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10));
510  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
511  "P2PK NOT with bad sig with too much R padding", SCRIPT_VERIFY_DERSIG
512  ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10).ScriptError(SCRIPT_ERR_SIG_DER));
513  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
514  "P2PK NOT with too much R padding but no DERSIG", 0
515  ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_EVAL_FALSE));
516  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
517  "P2PK NOT with too much R padding", SCRIPT_VERIFY_DERSIG
518  ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER));
519 
520  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
521  "BIP66 example 1, without DERSIG", 0
522  ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
523  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
524  "BIP66 example 1, with DERSIG", SCRIPT_VERIFY_DERSIG
525  ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
526  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
527  "BIP66 example 2, without DERSIG", 0
528  ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE));
529  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
530  "BIP66 example 2, with DERSIG", SCRIPT_VERIFY_DERSIG
531  ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
532  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
533  "BIP66 example 3, without DERSIG", 0
534  ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
535  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
536  "BIP66 example 3, with DERSIG", SCRIPT_VERIFY_DERSIG
537  ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
538  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
539  "BIP66 example 4, without DERSIG", 0
540  ).Num(0));
541  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
542  "BIP66 example 4, with DERSIG", SCRIPT_VERIFY_DERSIG
543  ).Num(0));
544  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
545  "BIP66 example 5, without DERSIG", 0
546  ).Num(1).ScriptError(SCRIPT_ERR_EVAL_FALSE));
547  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
548  "BIP66 example 5, with DERSIG", SCRIPT_VERIFY_DERSIG
549  ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER));
550  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
551  "BIP66 example 6, without DERSIG", 0
552  ).Num(1));
553  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
554  "BIP66 example 6, with DERSIG", SCRIPT_VERIFY_DERSIG
555  ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER));
556  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
557  "BIP66 example 7, without DERSIG", 0
558  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2));
559  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
560  "BIP66 example 7, with DERSIG", SCRIPT_VERIFY_DERSIG
561  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER));
562  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
563  "BIP66 example 8, without DERSIG", 0
564  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_EVAL_FALSE));
565  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
566  "BIP66 example 8, with DERSIG", SCRIPT_VERIFY_DERSIG
567  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER));
568  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
569  "BIP66 example 9, without DERSIG", 0
570  ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE));
571  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
572  "BIP66 example 9, with DERSIG", SCRIPT_VERIFY_DERSIG
573  ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
574  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
575  "BIP66 example 10, without DERSIG", 0
576  ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
577  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
578  "BIP66 example 10, with DERSIG", SCRIPT_VERIFY_DERSIG
579  ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
580  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
581  "BIP66 example 11, without DERSIG", 0
582  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
583  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
584  "BIP66 example 11, with DERSIG", SCRIPT_VERIFY_DERSIG
585  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
586  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
587  "BIP66 example 12, without DERSIG", 0
588  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
589  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
590  "BIP66 example 12, with DERSIG", SCRIPT_VERIFY_DERSIG
591  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
592  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
593  "P2PK with multi-byte hashtype, without DERSIG", 0
594  ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101"));
595  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
596  "P2PK with multi-byte hashtype, with DERSIG", SCRIPT_VERIFY_DERSIG
597  ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101").ScriptError(SCRIPT_ERR_SIG_DER));
598 
599  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
600  "P2PK with high S but no LOW_S", 0
601  ).PushSig(keys.key2, SIGHASH_ALL, 32, 33));
602  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
603  "P2PK with high S", SCRIPT_VERIFY_LOW_S
604  ).PushSig(keys.key2, SIGHASH_ALL, 32, 33).ScriptError(SCRIPT_ERR_SIG_HIGH_S));
605 
606  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,
607  "P2PK with hybrid pubkey but no STRICTENC", 0
608  ).PushSig(keys.key0, SIGHASH_ALL));
609  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,
610  "P2PK with hybrid pubkey", SCRIPT_VERIFY_STRICTENC
611  ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
612  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
613  "P2PK NOT with hybrid pubkey but no STRICTENC", 0
614  ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_EVAL_FALSE));
615  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
616  "P2PK NOT with hybrid pubkey", SCRIPT_VERIFY_STRICTENC
617  ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
618  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
619  "P2PK NOT with invalid hybrid pubkey but no STRICTENC", 0
620  ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10));
621  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
622  "P2PK NOT with invalid hybrid pubkey", SCRIPT_VERIFY_STRICTENC
623  ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
624  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
625  "1-of-2 with the second 1 hybrid pubkey and no STRICTENC", 0
626  ).Num(0).PushSig(keys.key1, SIGHASH_ALL));
627  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
628  "1-of-2 with the second 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC
629  ).Num(0).PushSig(keys.key1, SIGHASH_ALL));
630  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0H) << OP_2 << OP_CHECKMULTISIG,
631  "1-of-2 with the first 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC
632  ).Num(0).PushSig(keys.key1, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
633 
634  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
635  "P2PK with undefined hashtype but no STRICTENC", 0
636  ).PushSig(keys.key1, 5));
637  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
638  "P2PK with undefined hashtype", SCRIPT_VERIFY_STRICTENC
639  ).PushSig(keys.key1, 5).ScriptError(SCRIPT_ERR_SIG_HASHTYPE));
640  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,
641  "P2PK NOT with invalid sig and undefined hashtype but no STRICTENC", 0
642  ).PushSig(keys.key1, 5).DamagePush(10));
643  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,
644  "P2PK NOT with invalid sig and undefined hashtype", SCRIPT_VERIFY_STRICTENC
645  ).PushSig(keys.key1, 5).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_HASHTYPE));
646 
647  tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
648  "3-of-3 with nonzero dummy but no NULLDUMMY", 0
649  ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
650  tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
651  "3-of-3 with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY
652  ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY));
653  tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,
654  "3-of-3 NOT with invalid sig and nonzero dummy but no NULLDUMMY", 0
655  ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10));
656  tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,
657  "3-of-3 NOT with invalid sig with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY
658  ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY));
659 
660  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
661  "2-of-2 with two identical keys and sigs pushed using OP_DUP but no SIGPUSHONLY", 0
662  ).Num(0).PushSig(keys.key1).Opcode(OP_DUP));
663  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
664  "2-of-2 with two identical keys and sigs pushed using OP_DUP", SCRIPT_VERIFY_SIGPUSHONLY
665  ).Num(0).PushSig(keys.key1).Opcode(OP_DUP).ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
666  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
667  "P2SH(P2PK) with non-push scriptSig but no P2SH or SIGPUSHONLY", 0, true
668  ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem());
669  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
670  "P2PK with non-push scriptSig but with P2SH validation", SCRIPT_VERIFY_P2SH
671  ).PushSig(keys.key2).Opcode(OP_NOP8));
672  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
673  "P2SH(P2PK) with non-push scriptSig but no SIGPUSHONLY", SCRIPT_VERIFY_P2SH, true
674  ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
675  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
676  "P2SH(P2PK) with non-push scriptSig but not P2SH", SCRIPT_VERIFY_SIGPUSHONLY, true
677  ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
678  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
679  "2-of-2 with two identical keys and sigs pushed", SCRIPT_VERIFY_SIGPUSHONLY
680  ).Num(0).PushSig(keys.key1).PushSig(keys.key1));
681  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
682  "P2PK with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH
683  ).Num(11).PushSig(keys.key0));
684  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
685  "P2PK with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH
686  ).Num(11).PushSig(keys.key0).ScriptError(SCRIPT_ERR_CLEANSTACK));
687  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
688  "P2SH with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH, true
689  ).Num(11).PushSig(keys.key0).PushRedeem());
690  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
691  "P2SH with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true
692  ).Num(11).PushSig(keys.key0).PushRedeem().ScriptError(SCRIPT_ERR_CLEANSTACK));
693  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
694  "P2SH with CLEANSTACK", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true
695  ).PushSig(keys.key0).PushRedeem());
696 
697  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
698  "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
699  0, 1).PushWitSig(keys.key0).PushWitRedeem());
700  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
701  "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH,
702  0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit());
703  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
704  "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
705  0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
706  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
707  "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH,
708  0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem());
709  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
710  "Basic P2WSH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
711  ).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
712  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
713  "Basic P2WPKH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
714  ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE));
715  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
716  "Basic P2SH(P2WSH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH
717  ).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
718  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
719  "Basic P2SH(P2WPKH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
720  ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
721  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
722  "Basic P2WSH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
723  ).PushWitSig(keys.key0).PushWitRedeem());
724  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
725  "Basic P2WPKH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
726  ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit());
727  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
728  "Basic P2SH(P2WSH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WitnessMode::SH
729  ).PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
730  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
731  "Basic P2SH(P2WPKH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
732  ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem());
733  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
734  "Basic P2WSH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
735  0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
736  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
737  "Basic P2WPKH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH,
738  0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE));
739  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
740  "Basic P2SH(P2WSH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
741  0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
742  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
743  "Basic P2SH(P2WPKH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH,
744  0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
745 
746  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
747  "P2WPKH with future witness version", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH |
748  SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, false, WitnessMode::PKH, 1
749  ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM));
750  {
751  CScript witscript = CScript() << ToByteVector(keys.pubkey0);
752  uint256 hash;
753  CSHA256().Write(witscript.data(), witscript.size()).Finalize(hash.begin());
754  std::vector<unsigned char> hashBytes = ToByteVector(hash);
755  hashBytes.pop_back();
756  tests.push_back(TestBuilder(CScript() << OP_0 << hashBytes,
757  "P2WPKH with wrong witness program length", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false
758  ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH));
759  }
760  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
761  "P2WSH with empty witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
763  {
764  CScript witscript = CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG;
765  tests.push_back(TestBuilder(witscript,
766  "P2WSH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
767  ).PushWitSig(keys.key0).Push(witscript).DamagePush(0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH));
768  }
769  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
770  "P2WPKH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
771  ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH));
772  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
773  "P2WPKH with non-empty scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
774  ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Num(11).ScriptError(SCRIPT_ERR_WITNESS_MALLEATED));
775  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
776  "P2SH(P2WPKH) with superfluous push in scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
777  ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().Num(11).PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_MALLEATED_P2SH));
778  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
779  "P2PK with witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH
780  ).PushSig(keys.key0).Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_UNEXPECTED));
781 
782  // Compressed keys should pass SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
783  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
784  "Basic P2WSH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
785  0, 1).PushWitSig(keys.key0C).PushWitRedeem());
786  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C),
787  "Basic P2WPKH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::PKH,
788  0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit());
789  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
790  "Basic P2SH(P2WSH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
791  0, 1).PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
792  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C),
793  "Basic P2SH(P2WPKH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::PKH,
794  0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit().PushRedeem());
795 
796  // Testing uncompressed key in witness with SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
797  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
798  "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
799  0, 1).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
800  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
801  "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::PKH,
802  0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
803  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
804  "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
805  0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
806  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
807  "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::PKH,
808  0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
809 
810  // P2WSH 1-of-2 multisig with compressed keys
811  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
812  "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
813  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
814  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
815  "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
816  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
817  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
818  "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
819  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem());
820  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
821  "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
822  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem());
823 
824  // P2WSH 1-of-2 multisig with first key uncompressed
825  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
826  "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
827  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem());
828  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
829  "P2SH(P2WSH) CHECKMULTISIG first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
830  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
831  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
832  "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,
833  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
834  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
835  "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,
836  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
837  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
838  "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
839  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem());
840  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
841  "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
842  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem());
843  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
844  "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,
845  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
846  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
847  "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,
848  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
849  // P2WSH 1-of-2 multisig with second key uncompressed
850  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
851  "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
852  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
853  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
854  "P2SH(P2WSH) CHECKMULTISIG second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
855  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
856  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
857  "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,
858  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
859  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
860  "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,
861  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
862  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
863  "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
864  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem());
865  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
866  "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
867  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem());
868  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
869  "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,
870  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
871  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
872  "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,
873  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
874 
875  std::set<std::string> tests_set;
876 
877  {
878  UniValue json_tests = read_json(json_tests::script_tests);
879 
880  for (unsigned int idx = 0; idx < json_tests.size(); idx++) {
881  const UniValue& tv = json_tests[idx];
882  tests_set.insert(JSONPrettyPrint(tv.get_array()));
883  }
884  }
885 
886 #ifdef UPDATE_JSON_TESTS
887  std::string strGen;
888 #endif
889  for (TestBuilder& test : tests) {
890  test.Test(*this);
891  std::string str = JSONPrettyPrint(test.GetJSON());
892 #ifdef UPDATE_JSON_TESTS
893  strGen += str + ",\n";
894 #else
895  if (!tests_set.contains(str)) {
896  BOOST_CHECK_MESSAGE(false, "Missing auto script_valid test: " + test.GetComment());
897  }
898 #endif
899  }
900 
901 #ifdef UPDATE_JSON_TESTS
902  FILE* file = fsbridge::fopen("script_tests.json.gen", "w");
903  fputs(strGen.c_str(), file);
904  fclose(file);
905 #endif
906 }
907 
908 BOOST_AUTO_TEST_CASE(script_json_test)
909 {
910  // Read tests from test/data/script_tests.json
911  // Format is an array of arrays
912  // Inner arrays are [ ["wit"..., nValue]?, "scriptSig", "scriptPubKey", "flags", "expected_scripterror" ]
913  // ... where scriptSig and scriptPubKey are stringified
914  // scripts.
915  // If a witness is given, then the last value in the array should be the
916  // amount (nValue) to use in the crediting tx
917  UniValue tests = read_json(json_tests::script_tests);
918 
919  const KeyData keys;
920  for (unsigned int idx = 0; idx < tests.size(); idx++) {
921  const UniValue& test = tests[idx];
922  std::string strTest = test.write();
923  CScriptWitness witness;
924  TaprootBuilder taprootBuilder;
925  CAmount nValue = 0;
926  unsigned int pos = 0;
927  if (test.size() > 0 && test[pos].isArray()) {
928  unsigned int i=0;
929  for (i = 0; i < test[pos].size()-1; i++) {
930  auto element = test[pos][i].get_str();
931  // We use #SCRIPT# to flag a non-hex script that we can read using ParseScript
932  // Taproot script must be third from the last element in witness stack
933  static const std::string SCRIPT_FLAG{"#SCRIPT#"};
934  if (element.starts_with(SCRIPT_FLAG)) {
935  CScript script = ParseScript(element.substr(SCRIPT_FLAG.size()));
936  witness.stack.push_back(ToByteVector(script));
937  } else if (element == "#CONTROLBLOCK#") {
938  // Taproot script control block - second from the last element in witness stack
939  // If #CONTROLBLOCK# we auto-generate the control block
940  taprootBuilder.Add(/*depth=*/0, witness.stack.back(), TAPROOT_LEAF_TAPSCRIPT, /*track=*/true);
941  taprootBuilder.Finalize(XOnlyPubKey(keys.key0.GetPubKey()));
942  auto controlblocks = taprootBuilder.GetSpendData().scripts[{witness.stack.back(), TAPROOT_LEAF_TAPSCRIPT}];
943  witness.stack.push_back(*(controlblocks.begin()));
944  } else {
945  const auto witness_value{TryParseHex<unsigned char>(element)};
946  if (!witness_value.has_value()) {
947  BOOST_ERROR("Bad witness in test: " << strTest << " witness is not hex: " << element);
948  }
949  witness.stack.push_back(witness_value.value());
950  }
951  }
952  nValue = AmountFromValue(test[pos][i]);
953  pos++;
954  }
955  if (test.size() < 4 + pos) // Allow size > 3; extra stuff ignored (useful for comments)
956  {
957  if (test.size() != 1) {
958  BOOST_ERROR("Bad test: " << strTest);
959  }
960  continue;
961  }
962  std::string scriptSigString = test[pos++].get_str();
963  CScript scriptSig = ParseScript(scriptSigString);
964  std::string scriptPubKeyString = test[pos++].get_str();
965  CScript scriptPubKey;
966  // If requested, auto-generate the taproot output
967  if (scriptPubKeyString == "0x51 0x20 #TAPROOTOUTPUT#") {
968  BOOST_CHECK_MESSAGE(taprootBuilder.IsComplete(), "Failed to autogenerate Tapscript output key");
969  scriptPubKey = CScript() << OP_1 << ToByteVector(taprootBuilder.GetOutput());
970  } else {
971  scriptPubKey = ParseScript(scriptPubKeyString);
972  }
973  script_verify_flags scriptflags = ParseScriptFlags(test[pos++].get_str());
974  int scriptError = ParseScriptError(test[pos++].get_str());
975 
976  DoTest(scriptPubKey, scriptSig, witness, scriptflags, strTest, scriptError, nValue);
977  }
978 }
979 
980 BOOST_AUTO_TEST_CASE(script_PushData)
981 {
982  // Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on
983  // the stack as the 1-75 opcodes do.
984  static const unsigned char direct[] = { 1, 0x5a };
985  static const unsigned char pushdata1[] = { OP_PUSHDATA1, 1, 0x5a };
986  static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a };
987  static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a };
988 
989  ScriptError err;
990  std::vector<std::vector<unsigned char> > directStack;
991  BOOST_CHECK(EvalScript(directStack, CScript(direct, direct + sizeof(direct)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
992  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
993 
994  std::vector<std::vector<unsigned char> > pushdata1Stack;
995  BOOST_CHECK(EvalScript(pushdata1Stack, CScript(pushdata1, pushdata1 + sizeof(pushdata1)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
996  BOOST_CHECK(pushdata1Stack == directStack);
997  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
998 
999  std::vector<std::vector<unsigned char> > pushdata2Stack;
1000  BOOST_CHECK(EvalScript(pushdata2Stack, CScript(pushdata2, pushdata2 + sizeof(pushdata2)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1001  BOOST_CHECK(pushdata2Stack == directStack);
1002  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1003 
1004  std::vector<std::vector<unsigned char> > pushdata4Stack;
1005  BOOST_CHECK(EvalScript(pushdata4Stack, CScript(pushdata4, pushdata4 + sizeof(pushdata4)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1006  BOOST_CHECK(pushdata4Stack == directStack);
1007  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1008 
1009  const std::vector<unsigned char> pushdata1_trunc{OP_PUSHDATA1, 1};
1010  const std::vector<unsigned char> pushdata2_trunc{OP_PUSHDATA2, 1, 0};
1011  const std::vector<unsigned char> pushdata4_trunc{OP_PUSHDATA4, 1, 0, 0, 0};
1012 
1013  std::vector<std::vector<unsigned char>> stack_ignore;
1014  BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata1_trunc.begin(), pushdata1_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1016  BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata2_trunc.begin(), pushdata2_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1018  BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata4_trunc.begin(), pushdata4_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1020 }
1021 
1022 BOOST_AUTO_TEST_CASE(script_cltv_truncated)
1023 {
1024  const auto script_cltv_trunc = CScript() << OP_CHECKLOCKTIMEVERIFY;
1025 
1026  std::vector<std::vector<unsigned char>> stack_ignore;
1027  ScriptError err;
1030 }
1031 
1032 static CScript
1033 sign_multisig(const CScript& scriptPubKey, const std::vector<CKey>& keys, const CTransaction& transaction)
1034 {
1035  uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL, 0, SigVersion::BASE);
1036 
1037  CScript result;
1038  //
1039  // NOTE: CHECKMULTISIG has an unfortunate bug; it requires
1040  // one extra item on the stack, before the signatures.
1041  // Putting OP_0 on the stack is the workaround;
1042  // fixing the bug would mean splitting the block chain (old
1043  // clients would not accept new CHECKMULTISIG transactions,
1044  // and vice-versa)
1045  //
1046  result << OP_0;
1047  for (const CKey &key : keys)
1048  {
1049  std::vector<unsigned char> vchSig;
1050  BOOST_CHECK(key.Sign(hash, vchSig));
1051  vchSig.push_back((unsigned char)SIGHASH_ALL);
1052  result << vchSig;
1053  }
1054  return result;
1055 }
1056 static CScript
1057 sign_multisig(const CScript& scriptPubKey, const CKey& key, const CTransaction& transaction)
1058 {
1059  std::vector<CKey> keys;
1060  keys.push_back(key);
1061  return sign_multisig(scriptPubKey, keys, transaction);
1062 }
1063 
1064 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)
1065 {
1066  ScriptError err;
1067  CKey key1 = GenerateRandomKey();
1068  CKey key2 = GenerateRandomKey(/*compressed=*/false);
1069  CKey key3 = GenerateRandomKey();
1070 
1071  CScript scriptPubKey12;
1072  scriptPubKey12 << OP_1 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
1073 
1074  const CTransaction txFrom12{BuildCreditingTransaction(scriptPubKey12)};
1076 
1077  CScript goodsig1 = sign_multisig(scriptPubKey12, key1, CTransaction(txTo12));
1078  BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1079  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1080  txTo12.vout[0].nValue = 2;
1081  BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1082  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1083 
1084  CScript goodsig2 = sign_multisig(scriptPubKey12, key2, CTransaction(txTo12));
1085  BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1086  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1087 
1088  CScript badsig1 = sign_multisig(scriptPubKey12, key3, CTransaction(txTo12));
1089  BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1090  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1091 }
1092 
1093 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)
1094 {
1095  ScriptError err;
1096  CKey key1 = GenerateRandomKey();
1097  CKey key2 = GenerateRandomKey(/*compressed=*/false);
1098  CKey key3 = GenerateRandomKey();
1099  CKey key4 = GenerateRandomKey(/*compressed=*/false);
1100 
1101  CScript scriptPubKey23;
1102  scriptPubKey23 << OP_2 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << ToByteVector(key3.GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
1103 
1104  const CTransaction txFrom23{BuildCreditingTransaction(scriptPubKey23)};
1106 
1107  std::vector<CKey> keys;
1108  keys.push_back(key1); keys.push_back(key2);
1109  CScript goodsig1 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1110  BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1111  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1112 
1113  keys.clear();
1114  keys.push_back(key1); keys.push_back(key3);
1115  CScript goodsig2 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1116  BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1117  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1118 
1119  keys.clear();
1120  keys.push_back(key2); keys.push_back(key3);
1121  CScript goodsig3 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1122  BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1123  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1124 
1125  keys.clear();
1126  keys.push_back(key2); keys.push_back(key2); // Can't reuse sig
1127  CScript badsig1 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1128  BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1129  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1130 
1131  keys.clear();
1132  keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order
1133  CScript badsig2 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1134  BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1135  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1136 
1137  keys.clear();
1138  keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order
1139  CScript badsig3 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1140  BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1141  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1142 
1143  keys.clear();
1144  keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys
1145  CScript badsig4 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1146  BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1147  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1148 
1149  keys.clear();
1150  keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys
1151  CScript badsig5 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1152  BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1153  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1154 
1155  keys.clear(); // Must have signatures
1156  CScript badsig6 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1157  BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1158  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err));
1159 }
1160 
1162 static TxoutType GetTxoutType(const CScript& output_script)
1163 {
1164  std::vector<std::vector<uint8_t>> unused;
1165  return Solver(output_script, unused);
1166 }
1167 
1168 #define CHECK_SCRIPT_STATIC_SIZE(script, expected_size) \
1169  do { \
1170  BOOST_CHECK_EQUAL((script).size(), (expected_size)); \
1171  BOOST_CHECK_EQUAL((script).capacity(), CScriptBase::STATIC_SIZE); \
1172  BOOST_CHECK_EQUAL((script).allocated_memory(), 0); \
1173  } while (0)
1174 
1175 #define CHECK_SCRIPT_DYNAMIC_SIZE(script, expected_size, expected_extra) \
1176  do { \
1177  BOOST_CHECK_EQUAL((script).size(), (expected_size)); \
1178  BOOST_CHECK_EQUAL((script).capacity(), (expected_extra)); \
1179  BOOST_CHECK_EQUAL((script).allocated_memory(), (expected_extra)); \
1180  } while (0)
1181 
1182 BOOST_AUTO_TEST_CASE(script_size_and_capacity_test)
1183 {
1184  BOOST_CHECK_EQUAL(sizeof(CompressedScript), 40);
1185  BOOST_CHECK_EQUAL(sizeof(CScriptBase), 40);
1186  BOOST_CHECK_NE(sizeof(CScriptBase), sizeof(prevector<CScriptBase::STATIC_SIZE + 1, uint8_t>)); // CScriptBase size should be set to avoid wasting space in padding
1187  BOOST_CHECK_EQUAL(sizeof(CScript), 40);
1188  BOOST_CHECK_EQUAL(sizeof(CTxOut), 48);
1189 
1190  CKey dummy_key;
1191  dummy_key.MakeNewKey(/*fCompressed=*/true);
1192  const CPubKey dummy_pubkey{dummy_key.GetPubKey()};
1193 
1194  // Small OP_RETURN has direct allocation
1195  {
1196  const auto script{CScript() << OP_RETURN << std::vector<uint8_t>(10, 0xaa)};
1199  }
1200 
1201  // P2WPKH has direct allocation
1202  {
1203  const auto script{GetScriptForDestination(WitnessV0KeyHash{PKHash{dummy_pubkey}})};
1206  }
1207 
1208  // P2SH has direct allocation
1209  {
1211  BOOST_CHECK(script.IsPayToScriptHash());
1213  }
1214 
1215  // P2PKH has direct allocation
1216  {
1217  const auto script{GetScriptForDestination(PKHash{dummy_pubkey})};
1220  }
1221 
1222  // P2WSH has direct allocation
1223  {
1225  BOOST_CHECK(script.IsPayToWitnessScriptHash());
1227  }
1228 
1229  // P2TR has direct allocation
1230  {
1231  const auto script{GetScriptForDestination(WitnessV1Taproot{XOnlyPubKey{dummy_pubkey}})};
1234  }
1235 
1236  // Compressed P2PK has direct allocation
1237  {
1238  const auto script{GetScriptForRawPubKey(dummy_pubkey)};
1241  }
1242 
1243  // Uncompressed P2PK needs extra allocation
1244  {
1245  CKey uncompressed_key;
1246  uncompressed_key.MakeNewKey(/*fCompressed=*/false);
1247  const CPubKey uncompressed_pubkey{uncompressed_key.GetPubKey()};
1248 
1249  const auto script{GetScriptForRawPubKey(uncompressed_pubkey)};
1252  }
1253 
1254  // Bare multisig needs extra allocation
1255  {
1256  const auto script{GetScriptForMultisig(1, std::vector{2, dummy_pubkey})};
1259  }
1260 }
1261 
1262 /* Wrapper around ProduceSignature to combine two scriptsigs */
1263 SignatureData CombineSignatures(const CTxOut& txout, const CMutableTransaction& tx, const SignatureData& scriptSig1, const SignatureData& scriptSig2)
1264 {
1266  data.MergeSignatureData(scriptSig1);
1267  data.MergeSignatureData(scriptSig2);
1269  return data;
1270 }
1271 
1272 BOOST_AUTO_TEST_CASE(script_combineSigs)
1273 {
1274  // Test the ProduceSignature's ability to combine signatures function
1275  FillableSigningProvider keystore;
1276  std::vector<CKey> keys;
1277  std::vector<CPubKey> pubkeys;
1278  for (int i = 0; i < 3; i++)
1279  {
1280  CKey key = GenerateRandomKey(/*compressed=*/i%2 == 1);
1281  keys.push_back(key);
1282  pubkeys.push_back(key.GetPubKey());
1283  BOOST_CHECK(keystore.AddKey(key));
1284  }
1285 
1288  CScript& scriptPubKey = txFrom.vout[0].scriptPubKey;
1289  SignatureData scriptSig;
1290 
1291  SignatureData empty;
1292  SignatureData combined = CombineSignatures(txFrom.vout[0], txTo, empty, empty);
1293  BOOST_CHECK(combined.scriptSig.empty());
1294 
1295  // Single signature case:
1296  SignatureData dummy;
1297  BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy)); // changes scriptSig
1298  scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1299  combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
1300  BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1301  combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
1302  BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1303  SignatureData scriptSigCopy = scriptSig;
1304  // Signing again will give a different, valid signature:
1305  SignatureData dummy_b;
1306  BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_b));
1307  scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1308  combined = CombineSignatures(txFrom.vout[0], txTo, scriptSigCopy, scriptSig);
1309  BOOST_CHECK(combined.scriptSig == scriptSigCopy.scriptSig || combined.scriptSig == scriptSig.scriptSig);
1310 
1311  // P2SH, single-signature case:
1312  CScript pkSingle; pkSingle << ToByteVector(keys[0].GetPubKey()) << OP_CHECKSIG;
1313  BOOST_CHECK(keystore.AddCScript(pkSingle));
1314  scriptPubKey = GetScriptForDestination(ScriptHash(pkSingle));
1315  SignatureData dummy_c;
1316  BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_c));
1317  scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1318  combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
1319  BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1320  combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
1321  BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1322  scriptSigCopy = scriptSig;
1323  SignatureData dummy_d;
1324  BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_d));
1325  scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1326  combined = CombineSignatures(txFrom.vout[0], txTo, scriptSigCopy, scriptSig);
1327  BOOST_CHECK(combined.scriptSig == scriptSigCopy.scriptSig || combined.scriptSig == scriptSig.scriptSig);
1328 
1329  // Hardest case: Multisig 2-of-3
1330  scriptPubKey = GetScriptForMultisig(2, pubkeys);
1331  BOOST_CHECK(keystore.AddCScript(scriptPubKey));
1332  SignatureData dummy_e;
1333  BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_e));
1334  scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1335  combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
1336  BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1337  combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
1338  BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1339 
1340  // A couple of partially-signed versions:
1341  std::vector<unsigned char> sig1;
1342  uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL, 0, SigVersion::BASE);
1343  BOOST_CHECK(keys[0].Sign(hash1, sig1));
1344  sig1.push_back(SIGHASH_ALL);
1345  std::vector<unsigned char> sig2;
1346  uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE, 0, SigVersion::BASE);
1347  BOOST_CHECK(keys[1].Sign(hash2, sig2));
1348  sig2.push_back(SIGHASH_NONE);
1349  std::vector<unsigned char> sig3;
1350  uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE, 0, SigVersion::BASE);
1351  BOOST_CHECK(keys[2].Sign(hash3, sig3));
1352  sig3.push_back(SIGHASH_SINGLE);
1353 
1354  // Not fussy about order (or even existence) of placeholders or signatures:
1355  CScript partial1a = CScript() << OP_0 << sig1 << OP_0;
1356  CScript partial1b = CScript() << OP_0 << OP_0 << sig1;
1357  CScript partial2a = CScript() << OP_0 << sig2;
1358  CScript partial2b = CScript() << sig2 << OP_0;
1359  CScript partial3a = CScript() << sig3;
1360  CScript partial3b = CScript() << OP_0 << OP_0 << sig3;
1361  CScript partial3c = CScript() << OP_0 << sig3 << OP_0;
1362  CScript complete12 = CScript() << OP_0 << sig1 << sig2;
1363  CScript complete13 = CScript() << OP_0 << sig1 << sig3;
1364  CScript complete23 = CScript() << OP_0 << sig2 << sig3;
1365  SignatureData partial1_sigs;
1366  partial1_sigs.signatures.emplace(keys[0].GetPubKey().GetID(), SigPair(keys[0].GetPubKey(), sig1));
1367  SignatureData partial2_sigs;
1368  partial2_sigs.signatures.emplace(keys[1].GetPubKey().GetID(), SigPair(keys[1].GetPubKey(), sig2));
1369  SignatureData partial3_sigs;
1370  partial3_sigs.signatures.emplace(keys[2].GetPubKey().GetID(), SigPair(keys[2].GetPubKey(), sig3));
1371 
1372  combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial1_sigs);
1373  BOOST_CHECK(combined.scriptSig == partial1a);
1374  combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial2_sigs);
1375  BOOST_CHECK(combined.scriptSig == complete12);
1376  combined = CombineSignatures(txFrom.vout[0], txTo, partial2_sigs, partial1_sigs);
1377  BOOST_CHECK(combined.scriptSig == complete12);
1378  combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial2_sigs);
1379  BOOST_CHECK(combined.scriptSig == complete12);
1380  combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial1_sigs);
1381  BOOST_CHECK(combined.scriptSig == complete13);
1382  combined = CombineSignatures(txFrom.vout[0], txTo, partial2_sigs, partial3_sigs);
1383  BOOST_CHECK(combined.scriptSig == complete23);
1384  combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial2_sigs);
1385  BOOST_CHECK(combined.scriptSig == complete23);
1386  combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial3_sigs);
1387  BOOST_CHECK(combined.scriptSig == partial3c);
1388 }
1389 
1393 BOOST_AUTO_TEST_CASE(sign_invalid_miniscript)
1394 {
1395  FillableSigningProvider keystore;
1396  SignatureData sig_data;
1397  CMutableTransaction prev, curr;
1398 
1399  // Create a Taproot output which contains a leaf in which a non-32 bytes push is used where a public key is expected
1400  // by the Miniscript parser. This offending Script was found by the RPC fuzzer.
1401  const auto invalid_pubkey{"173d36c8c9c9c9ffffffffffff0200000000021e1e37373721361818181818181e1e1e1e19000000000000000000b19292929292926b006c9b9b9292"_hex_u8};
1402  TaprootBuilder builder;
1403  builder.Add(0, {invalid_pubkey}, 0xc0);
1404  builder.Finalize(XOnlyPubKey::NUMS_H);
1405  prev.vout.emplace_back(0, GetScriptForDestination(builder.GetOutput()));
1406  curr.vin.emplace_back(COutPoint{prev.GetHash(), 0});
1407  sig_data.tr_spenddata = builder.GetSpendData();
1408 
1409  // SignSignature can fail but it shouldn't raise an exception (nor crash).
1410  BOOST_CHECK(!SignSignature(keystore, CTransaction(prev), curr, 0, SIGHASH_ALL, sig_data));
1411 }
1412 
1413 /* P2A input should be considered signed. */
1414 BOOST_AUTO_TEST_CASE(sign_paytoanchor)
1415 {
1416  FillableSigningProvider keystore;
1417  SignatureData sig_data;
1418  CMutableTransaction prev, curr;
1419  prev.vout.emplace_back(0, GetScriptForDestination(PayToAnchor{}));
1420 
1421  curr.vin.emplace_back(COutPoint{prev.GetHash(), 0});
1422 
1423  BOOST_CHECK(SignSignature(keystore, CTransaction(prev), curr, 0, SIGHASH_ALL, sig_data));
1424 }
1425 
1426 BOOST_AUTO_TEST_CASE(script_standard_push)
1427 {
1428  ScriptError err;
1429  for (int i=0; i<67000; i++) {
1430  CScript script;
1431  script << i;
1432  BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Number " << i << " is not pure push.");
1433  BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Number " << i << " push is not minimal data.");
1434  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1435  }
1436 
1437  for (unsigned int i=0; i<=MAX_SCRIPT_ELEMENT_SIZE; i++) {
1438  std::vector<unsigned char> data(i, '\111');
1439  CScript script;
1440  script << data;
1441  BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Length " << i << " is not pure push.");
1442  BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Length " << i << " push is not minimal data.");
1443  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1444  }
1445 }
1446 
1447 BOOST_AUTO_TEST_CASE(script_IsPushOnly_on_invalid_scripts)
1448 {
1449  // IsPushOnly returns false when given a script containing only pushes that
1450  // are invalid due to truncation. IsPushOnly() is consensus critical
1451  // because P2SH evaluation uses it, although this specific behavior should
1452  // not be consensus critical as the P2SH evaluation would fail first due to
1453  // the invalid push. Still, it doesn't hurt to test it explicitly.
1454  static const unsigned char direct[] = { 1 };
1455  BOOST_CHECK(!CScript(direct, direct+sizeof(direct)).IsPushOnly());
1456 }
1457 
1458 BOOST_AUTO_TEST_CASE(script_GetScriptAsm)
1459 {
1460  BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2, true));
1461  BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY, true));
1462  BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2));
1463  BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY));
1464 
1465  std::string derSig("304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c5090");
1466  std::string pubKey("03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2");
1467  std::vector<unsigned char> vchPubKey = ToByteVector(ParseHex(pubKey));
1468 
1469  BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey, true));
1470  BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey, true));
1471  BOOST_CHECK_EQUAL(derSig + "[ALL] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey, true));
1472  BOOST_CHECK_EQUAL(derSig + "[NONE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey, true));
1473  BOOST_CHECK_EQUAL(derSig + "[SINGLE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey, true));
1474  BOOST_CHECK_EQUAL(derSig + "[ALL|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey, true));
1475  BOOST_CHECK_EQUAL(derSig + "[NONE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey, true));
1476  BOOST_CHECK_EQUAL(derSig + "[SINGLE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey, true));
1477 
1478  BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey));
1479  BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey));
1480  BOOST_CHECK_EQUAL(derSig + "01 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey));
1481  BOOST_CHECK_EQUAL(derSig + "02 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey));
1482  BOOST_CHECK_EQUAL(derSig + "03 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey));
1483  BOOST_CHECK_EQUAL(derSig + "81 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey));
1484  BOOST_CHECK_EQUAL(derSig + "82 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey));
1485  BOOST_CHECK_EQUAL(derSig + "83 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey));
1486 }
1487 
1488 template <typename T>
1489 CScript ToScript(const T& byte_container)
1490 {
1491  auto span{MakeUCharSpan(byte_container)};
1492  return {span.begin(), span.end()};
1493 }
1494 
1495 BOOST_AUTO_TEST_CASE(script_byte_array_u8_vector_equivalence)
1496 {
1497  const CScript scriptPubKey1 = CScript() << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"_hex_v_u8 << OP_CHECKSIG;
1498  const CScript scriptPubKey2 = CScript() << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"_hex << OP_CHECKSIG;
1499  BOOST_CHECK(scriptPubKey1 == scriptPubKey2);
1500 }
1501 
1502 BOOST_AUTO_TEST_CASE(script_FindAndDelete)
1503 {
1504  // Exercise the FindAndDelete functionality
1505  CScript s;
1506  CScript d;
1507  CScript expect;
1508 
1509  s = CScript() << OP_1 << OP_2;
1510  d = CScript(); // delete nothing should be a no-op
1511  expect = s;
1513  BOOST_CHECK(s == expect);
1514 
1515  s = CScript() << OP_1 << OP_2 << OP_3;
1516  d = CScript() << OP_2;
1517  expect = CScript() << OP_1 << OP_3;
1519  BOOST_CHECK(s == expect);
1520 
1521  s = CScript() << OP_3 << OP_1 << OP_3 << OP_3 << OP_4 << OP_3;
1522  d = CScript() << OP_3;
1523  expect = CScript() << OP_1 << OP_4;
1525  BOOST_CHECK(s == expect);
1526 
1527  s = ToScript("0302ff03"_hex); // PUSH 0x02ff03 onto stack
1528  d = ToScript("0302ff03"_hex);
1529  expect = CScript();
1531  BOOST_CHECK(s == expect);
1532 
1533  s = ToScript("0302ff030302ff03"_hex); // PUSH 0x02ff03 PUSH 0x02ff03
1534  d = ToScript("0302ff03"_hex);
1535  expect = CScript();
1537  BOOST_CHECK(s == expect);
1538 
1539  s = ToScript("0302ff030302ff03"_hex);
1540  d = ToScript("02"_hex);
1541  expect = s; // FindAndDelete matches entire opcodes
1543  BOOST_CHECK(s == expect);
1544 
1545  s = ToScript("0302ff030302ff03"_hex);
1546  d = ToScript("ff"_hex);
1547  expect = s;
1549  BOOST_CHECK(s == expect);
1550 
1551  // This is an odd edge case: strip of the push-three-bytes
1552  // prefix, leaving 02ff03 which is push-two-bytes:
1553  s = ToScript("0302ff030302ff03"_hex);
1554  d = ToScript("03"_hex);
1555  expect = CScript() << "ff03"_hex << "ff03"_hex;
1557  BOOST_CHECK(s == expect);
1558 
1559  // Byte sequence that spans multiple opcodes:
1560  s = ToScript("02feed5169"_hex); // PUSH(0xfeed) OP_1 OP_VERIFY
1561  d = ToScript("feed51"_hex);
1562  expect = s;
1563  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0); // doesn't match 'inside' opcodes
1564  BOOST_CHECK(s == expect);
1565 
1566  s = ToScript("02feed5169"_hex); // PUSH(0xfeed) OP_1 OP_VERIFY
1567  d = ToScript("02feed51"_hex);
1568  expect = ToScript("69"_hex);
1570  BOOST_CHECK(s == expect);
1571 
1572  s = ToScript("516902feed5169"_hex);
1573  d = ToScript("feed51"_hex);
1574  expect = s;
1576  BOOST_CHECK(s == expect);
1577 
1578  s = ToScript("516902feed5169"_hex);
1579  d = ToScript("02feed51"_hex);
1580  expect = ToScript("516969"_hex);
1582  BOOST_CHECK(s == expect);
1583 
1584  s = CScript() << OP_0 << OP_0 << OP_1 << OP_1;
1585  d = CScript() << OP_0 << OP_1;
1586  expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass
1588  BOOST_CHECK(s == expect);
1589 
1590  s = CScript() << OP_0 << OP_0 << OP_1 << OP_0 << OP_1 << OP_1;
1591  d = CScript() << OP_0 << OP_1;
1592  expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass
1594  BOOST_CHECK(s == expect);
1595 
1596  // Another weird edge case:
1597  // End with invalid push (not enough data)...
1598  s = ToScript("0003feed"_hex);
1599  d = ToScript("03feed"_hex); // ... can remove the invalid push
1600  expect = ToScript("00"_hex);
1602  BOOST_CHECK(s == expect);
1603 
1604  s = ToScript("0003feed"_hex);
1605  d = ToScript("00"_hex);
1606  expect = ToScript("03feed"_hex);
1608  BOOST_CHECK(s == expect);
1609 }
1610 
1611 BOOST_AUTO_TEST_CASE(script_HasValidOps)
1612 {
1613  // Exercise the HasValidOps functionality
1614  CScript script;
1615  script = ToScript("76a9141234567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac"_hex); // Normal script
1616  BOOST_CHECK(script.HasValidOps());
1617  script = ToScript("76a914ff34567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac"_hex);
1618  BOOST_CHECK(script.HasValidOps());
1619  script = ToScript("ff88ac"_hex); // Script with OP_INVALIDOPCODE explicit
1620  BOOST_CHECK(!script.HasValidOps());
1621  script = ToScript("88acc0"_hex); // Script with undefined opcode
1622  BOOST_CHECK(!script.HasValidOps());
1623 }
1624 
1625 BOOST_AUTO_TEST_CASE(bip341_keypath_test_vectors)
1626 {
1627  UniValue tests;
1628  tests.read(json_tests::bip341_wallet_vectors);
1629 
1630  const auto& vectors = tests["keyPathSpending"];
1631 
1632  for (const auto& vec : vectors.getValues()) {
1633  auto txhex = ParseHex(vec["given"]["rawUnsignedTx"].get_str());
1635  SpanReader{txhex} >> TX_WITH_WITNESS(tx);
1636  std::vector<CTxOut> utxos;
1637  for (const auto& utxo_spent : vec["given"]["utxosSpent"].getValues()) {
1638  auto script_bytes = ParseHex(utxo_spent["scriptPubKey"].get_str());
1639  CScript script{script_bytes.begin(), script_bytes.end()};
1640  CAmount amount{utxo_spent["amountSats"].getInt<int>()};
1641  utxos.emplace_back(amount, script);
1642  }
1643 
1645  txdata.Init(tx, std::vector<CTxOut>{utxos}, true);
1646 
1648  BOOST_CHECK_EQUAL(HexStr(txdata.m_spent_amounts_single_hash), vec["intermediary"]["hashAmounts"].get_str());
1649  BOOST_CHECK_EQUAL(HexStr(txdata.m_outputs_single_hash), vec["intermediary"]["hashOutputs"].get_str());
1650  BOOST_CHECK_EQUAL(HexStr(txdata.m_prevouts_single_hash), vec["intermediary"]["hashPrevouts"].get_str());
1651  BOOST_CHECK_EQUAL(HexStr(txdata.m_spent_scripts_single_hash), vec["intermediary"]["hashScriptPubkeys"].get_str());
1652  BOOST_CHECK_EQUAL(HexStr(txdata.m_sequences_single_hash), vec["intermediary"]["hashSequences"].get_str());
1653 
1654  for (const auto& input : vec["inputSpending"].getValues()) {
1655  int txinpos = input["given"]["txinIndex"].getInt<int>();
1656  int hashtype = input["given"]["hashType"].getInt<int>();
1657 
1658  // Load key.
1659  auto privkey = ParseHex(input["given"]["internalPrivkey"].get_str());
1660  CKey key;
1661  key.Set(privkey.begin(), privkey.end(), true);
1662 
1663  // Load Merkle root.
1664  uint256 merkle_root;
1665  if (!input["given"]["merkleRoot"].isNull()) {
1666  merkle_root = uint256{ParseHex(input["given"]["merkleRoot"].get_str())};
1667  }
1668 
1669  // Compute and verify (internal) public key.
1670  XOnlyPubKey pubkey{key.GetPubKey()};
1671  BOOST_CHECK_EQUAL(HexStr(pubkey), input["intermediary"]["internalPubkey"].get_str());
1672 
1673  // Sign and verify signature.
1674  FlatSigningProvider provider;
1675  provider.keys[key.GetPubKey().GetID()] = key;
1676  MutableTransactionSignatureCreator creator(tx, txinpos, utxos[txinpos].nValue, &txdata, hashtype);
1677  std::vector<unsigned char> signature;
1678  BOOST_CHECK(creator.CreateSchnorrSig(provider, signature, pubkey, nullptr, &merkle_root, SigVersion::TAPROOT));
1679  BOOST_CHECK_EQUAL(HexStr(signature), input["expected"]["witness"][0].get_str());
1680 
1681  // We can't observe the tweak used inside the signing logic, so verify by recomputing it.
1682  BOOST_CHECK_EQUAL(HexStr(pubkey.ComputeTapTweakHash(merkle_root.IsNull() ? nullptr : &merkle_root)), input["intermediary"]["tweak"].get_str());
1683 
1684  // We can't observe the sighash used inside the signing logic, so verify by recomputing it.
1685  ScriptExecutionData sed;
1686  sed.m_annex_init = true;
1687  sed.m_annex_present = false;
1688  uint256 sighash;
1689  BOOST_CHECK(SignatureHashSchnorr(sighash, sed, tx, txinpos, hashtype, SigVersion::TAPROOT, txdata, MissingDataBehavior::FAIL));
1690  BOOST_CHECK_EQUAL(HexStr(sighash), input["intermediary"]["sigHash"].get_str());
1691 
1692  // To verify the sigmsg, hash the expected sigmsg, and compare it with the (expected) sighash.
1693  BOOST_CHECK_EQUAL(HexStr((HashWriter{HASHER_TAPSIGHASH} << std::span<const uint8_t>{ParseHex(input["intermediary"]["sigMsg"].get_str())}).GetSHA256()), input["intermediary"]["sigHash"].get_str());
1694  }
1695  }
1696 }
1697 
1698 BOOST_AUTO_TEST_CASE(compute_tapbranch)
1699 {
1700  constexpr uint256 hash1{"8ad69ec7cf41c2a4001fd1f738bf1e505ce2277acdcaa63fe4765192497f47a7"};
1701  constexpr uint256 hash2{"f224a923cd0021ab202ab139cc56802ddb92dcfc172b9212261a539df79a112a"};
1702  constexpr uint256 result{"a64c5b7b943315f9b805d7a7296bedfcfd08919270a1f7a1466e98f8693d8cd9"};
1704 }
1705 
1706 BOOST_AUTO_TEST_CASE(compute_tapleaf)
1707 {
1708  constexpr uint8_t script[6] = {'f','o','o','b','a','r'};
1709  constexpr uint256 tlc0{"edbc10c272a1215dcdcc11d605b9027b5ad6ed97cd45521203f136767b5b9c06"};
1710  constexpr uint256 tlc2{"8b5c4f90ae6bf76e259dbef5d8a59df06359c391b59263741b25eca76451b27a"};
1711 
1712  BOOST_CHECK_EQUAL(ComputeTapleafHash(0xc0, std::span(script)), tlc0);
1713  BOOST_CHECK_EQUAL(ComputeTapleafHash(0xc2, std::span(script)), tlc2);
1714 }
1715 
1716 BOOST_AUTO_TEST_CASE(formatscriptflags)
1717 {
1718  // quick check that FormatScriptFlags reports any unknown/unexpected bits
1723  BOOST_CHECK_EQUAL(FormatScriptFlags(SCRIPT_VERIFY_TAPROOT | script_verify_flags::from_int((1u<<28) | (1ull<<58))), "TAPROOT,0x400000010000000");
1725 }
1726 
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
CAmount nValue
Definition: transaction.h:142
CMutableTransaction BuildCreditingTransaction(const CScript &scriptPubKey, int nValue)
Witness v0 (P2WPKH and P2WSH); see BIP 141.
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:699
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition: solver.cpp:218
int ret
Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, key path spending; see BIP 341...
uint256 SignatureHash(const CScript &scriptCode, const T &txTo, unsigned int nIn, int32_t nHashType, const CAmount &amount, SigVersion sigversion, const PrecomputedTransactionData *cache, SigHashCache *sighash_cache)
bool SignatureHashSchnorr(uint256 &hash_out, ScriptExecutionData &execdata, const T &tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData &cache, MissingDataBehavior mdb)
constexpr auto MakeUCharSpan(const V &v) -> decltype(UCharSpanCast(std::span
Like the std::span constructor, but for (const) unsigned char member types only.
Definition: span.h:111
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:69
assert(!tx.IsCoinBase())
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:25
enum ScriptError_t ScriptError
CScript scriptPubKey
Definition: transaction.h:143
UniValue ValueFromAmount(const CAmount amount)
Definition: core_io.cpp:285
CHash160 & Write(std::span< const unsigned char > input)
Definition: hash.h:62
SECP256K1_API const secp256k1_context *const secp256k1_context_static
A built-in constant secp256k1 context object with static storage duration, to be used in conjunction ...
Definition: secp256k1.h:245
Definition: script.h:125
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:36
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:183
CScript scriptSig
The scriptSig of an input. Contains complete signatures or the traditional partial signatures format...
Definition: sign.h:80
std::vector< CTxIn > vin
Definition: transaction.h:359
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: solver.cpp:141
std::map< CKeyID, CKey > keys
script_verify_flags ParseScriptFlags(std::string strFlags)
virtual bool AddCScript(const CScript &redeemScript)
static const script_verify_flags gFlags
#define expect(bit)
std::vector< std::vector< unsigned char > > stack
Definition: script.h:580
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_negate(const secp256k1_context *ctx, unsigned char *seckey) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2)
Negates a secret key in place.
Definition: secp256k1.c:630
ScriptError_t err
CMutableTransaction BuildSpendingTransaction(const CScript &scriptSig, const CScriptWitness &scriptWitness, const CTransaction &txCredit)
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Definition: interpreter.h:242
static const XOnlyPubKey NUMS_H
Nothing Up My Sleeve point H Used as an internal key for provably disabling the key path spend see BI...
Definition: pubkey.h:235
const std::string & get_str() const
const UniValue & get_array() const
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
void DoTest(const CScript &scriptPubKey, const CScript &scriptSig, const CScriptWitness &scriptWitness, script_verify_flags flags, const std::string &message, int scriptError, CAmount nValue=0)
static constexpr int MAX_SCRIPT_VERIFY_FLAGS_BITS
Definition: interpreter.h:154
UniValue read_json(std::string_view jsondata)
Definition: json.cpp:12
Definition: script.h:76
A signature creator for transactions.
Definition: sign.h:43
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, script_verify_flags flags, const BaseSignatureChecker &checker, ScriptError *serror)
const HashWriter HASHER_TAPSIGHASH
Hasher with tag "TapSighash" pre-fed to it.
std::string FormatScript(const CScript &script)
Definition: core_io.cpp:298
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:160
std::pair< opcodetype, std::vector< unsigned char > > Opcode
Definition: miniscript.h:191
const unsigned char * begin() const
Definition: pubkey.h:114
value_type * data()
Definition: prevector.h:477
Basic testing setup.
Definition: setup_common.h:64
constexpr unsigned char * begin()
Definition: uint256.h:100
Minimal stream for reading from an existing byte array by std::span.
Definition: streams.h:82
Definition: script.h:83
CKey GenerateRandomKey(bool compressed) noexcept
Definition: key.cpp:475
SignatureData CombineSignatures(const CTxOut &txout, const CMutableTransaction &tx, const SignatureData &scriptSig1, const SignatureData &scriptSig2)
constexpr std::array tests
Definition: unitester.cpp:101
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static void NegateSignatureS(std::vector< unsigned char > &vchSig)
bool Sign(const uint256 &hash, std::vector< unsigned char > &vchSig, bool grind=true, uint32_t test_case=0) const
Create a DER-serialized signature.
Definition: key.cpp:209
bool m_annex_init
Whether m_annex_present and (when needed) m_annex_hash are initialized.
Definition: interpreter.h:221
iterator end()
Definition: prevector.h:257
void push_back(const T &value)
Definition: prevector.h:392
Abort execution through assertion failure (for consensus code)
void Init(const T &tx, std::vector< CTxOut > &&spent_outputs, bool force=false)
Initialize this PrecomputedTransactionData with transaction data.
Definition: script.h:84
static CAmount AmountFromValue(const UniValue &value)
Definition: bitcoin-tx.cpp:554
std::map< std::pair< std::vector< unsigned char >, int >, std::set< std::vector< unsigned char >, ShortestVectorFirstComparator > > scripts
Map from (script, leaf_version) to (sets of) control blocks.
const unsigned char * end() const
Definition: pubkey.h:115
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
static ScriptError_t ParseScriptError(const std::string &name)
const char * name
Definition: rest.cpp:48
const SigningProvider & DUMMY_SIGNING_PROVIDER
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:100
BOOST_AUTO_TEST_SUITE_END()
TaprootBuilder & Finalize(const XOnlyPubKey &internal_key)
Finalize the construction.
An encapsulated public key.
Definition: pubkey.h:33
Fillable signing provider that keeps keys in an address->secret map.
uint256 ComputeTapbranchHash(std::span< const unsigned char > a, std::span< const unsigned char > b)
Compute the BIP341 tapbranch hash from two branches.
std::string ScriptErrorString(const ScriptError serror)
ScriptError_t
Definition: script_error.h:11
std::pair< CPubKey, std::vector< unsigned char > > SigPair
Definition: sign.h:72
opcodetype
Script opcodes.
Definition: script.h:73
WitnessV1Taproot GetOutput()
Compute scriptPubKey (after Finalize()).
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:162
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
Just act as if the signature was invalid.
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode)
Create the assembly string representation of a CScript object.
Definition: core_io.cpp:357
An output of a transaction.
Definition: transaction.h:139
""_hex is a compile-time user-defined literal returning a std::array<std::byte>, equivalent to ParseH...
Definition: strencodings.h:400
GenericTransactionSignatureChecker< CMutableTransaction > MutableTransactionSignatureChecker
Definition: interpreter.h:337
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:69
static std::string FormatScriptFlags(script_verify_flags flags)
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:28
bool m_bip341_taproot_ready
Whether the 5 fields above are initialized.
Definition: interpreter.h:173
std::vector< CTxOut > vout
Definition: transaction.h:360
constexpr bool IsNull() const
Definition: uint256.h:48
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:104
A type to represent integers in the type system.
Definition: lintrans.h:13
bool SignSignature(const SigningProvider &provider, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, const CAmount &amount, int nHashType, SignatureData &sig_data)
Produce a satisfying script (scriptSig or witness).
Implements a drop-in replacement for std::vector<T> which stores up to N elements directly (without h...
Definition: prevector.h:37
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:404
CScript ParseScript(const std::string &s)
Definition: core_io.cpp:94
TaprootSpendData GetSpendData() const
Compute spending data (after Finalize()).
Utility class to construct Taproot outputs from internal key and script tree.
int flags
Definition: bitcoin-tx.cpp:529
static ScriptErrorDesc script_errors[]
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:67
BOOST_AUTO_TEST_CASE(script_build)
256-bit opaque blob.
Definition: uint256.h:195
WitnessMode
TaprootBuilder & Add(int depth, std::span< const unsigned char > script, int leaf_version, bool track=true)
Add a new script at a certain depth in the tree.
TxoutType
Definition: solver.h:22
auto result
Definition: common-types.h:74
static constexpr script_verify_flags from_int(value_type f)
Definition: verify_flags.h:35
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition: sign.cpp:837
#define CHECK_SCRIPT_STATIC_SIZE(script, expected_size)
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:17
CScript ToScript(const T &byte_container)
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
Definition: sign.cpp:221
bool CreateSchnorrSig(const SigningProvider &provider, std::vector< unsigned char > &sig, const XOnlyPubKey &pubkey, const uint256 *leaf_hash, const uint256 *merkle_root, SigVersion sigversion) const override
Definition: sign.cpp:88
bool empty() const
Definition: prevector.h:251
Definition: script.h:86
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:28
const char * name
#define CHECK_SCRIPT_DYNAMIC_SIZE(script, expected_size, expected_extra)
160-bit opaque blob.
Definition: uint256.h:183
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:729
iterator begin()
Definition: prevector.h:255
A reference to a CScript: the Hash160 of its serialization.
Definition: script.h:593
A mutable version of CTransaction.
Definition: transaction.h:357
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: solver.cpp:213
size_type size() const
Definition: prevector.h:247
Definition: script.h:85
bool IsComplete() const
Return whether there were either no leaves, or the leaves form a Huffman tree.
static std::string FormatScriptError(ScriptError_t err)
size_t size() const
Definition: univalue.h:71
const unsigned char * data() const
Definition: pubkey.h:113
An encapsulated private key.
Definition: key.h:35
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:280
A hasher class for Bitcoin&#39;s 160-bit hash (SHA-256 + RIPEMD-160).
Definition: hash.h:49
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, script_verify_flags flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror)
std::vector< std::string > GetScriptFlagNames(script_verify_flags flags)
A hasher class for SHA-256.
Definition: sha256.h:13
uint256 ComputeTapleafHash(uint8_t leaf_version, std::span< const unsigned char > script)
Compute the BIP341 tapleaf hash from leaf version & script.
int FindAndDelete(CScript &script, const CScript &b)
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:205
Definition: script.h:158
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
bool isArray() const
Definition: univalue.h:87
virtual bool AddKey(const CKey &key)
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
Definition: sign.h:86
Definition: script.h:87
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:180
#define BOOST_CHECK(expr)
Definition: object.cpp:16
static CScript sign_multisig(const CScript &scriptPubKey, const std::vector< CKey > &keys, const CTransaction &transaction)
SigVersion
Definition: interpreter.h:200
static TxoutType GetTxoutType(const CScript &output_script)
Return the TxoutType of a script without exposing Solver details.
unspendable OP_RETURN script that carries data
TaprootSpendData tr_spenddata
Taproot spending data.
Definition: sign.h:84