Bitcoin Core  27.1.0
P2P Digital Currency
script_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2022 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 #if defined(HAVE_CONFIG_H)
7 #endif
8 
11 
12 #include <common/system.h>
13 #include <core_io.h>
14 #include <key.h>
15 #include <rpc/util.h>
16 #include <script/script.h>
17 #include <script/script_error.h>
18 #include <script/sigcache.h>
19 #include <script/sign.h>
20 #include <script/signingprovider.h>
21 #include <script/solver.h>
22 #include <streams.h>
23 #include <test/util/json.h>
24 #include <test/util/random.h>
25 #include <test/util/setup_common.h>
27 #include <util/fs.h>
28 #include <util/strencodings.h>
29 
30 #if defined(HAVE_CONSENSUS_LIB)
32 #endif
33 
34 #include <cstdint>
35 #include <fstream>
36 #include <string>
37 #include <vector>
38 
39 #include <boost/test/unit_test.hpp>
40 
41 #include <univalue.h>
42 
43 // Uncomment if you want to output updated JSON tests.
44 // #define UPDATE_JSON_TESTS
45 
46 static const unsigned int gFlags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC;
47 
48 unsigned int ParseScriptFlags(std::string strFlags);
49 std::string FormatScriptFlags(unsigned int flags);
50 
52 {
54  const char *name;
55 };
56 
58  {SCRIPT_ERR_OK, "OK"},
59  {SCRIPT_ERR_UNKNOWN_ERROR, "UNKNOWN_ERROR"},
60  {SCRIPT_ERR_EVAL_FALSE, "EVAL_FALSE"},
61  {SCRIPT_ERR_OP_RETURN, "OP_RETURN"},
62  {SCRIPT_ERR_SCRIPT_SIZE, "SCRIPT_SIZE"},
63  {SCRIPT_ERR_PUSH_SIZE, "PUSH_SIZE"},
64  {SCRIPT_ERR_OP_COUNT, "OP_COUNT"},
65  {SCRIPT_ERR_STACK_SIZE, "STACK_SIZE"},
66  {SCRIPT_ERR_SIG_COUNT, "SIG_COUNT"},
67  {SCRIPT_ERR_PUBKEY_COUNT, "PUBKEY_COUNT"},
68  {SCRIPT_ERR_VERIFY, "VERIFY"},
69  {SCRIPT_ERR_EQUALVERIFY, "EQUALVERIFY"},
70  {SCRIPT_ERR_CHECKMULTISIGVERIFY, "CHECKMULTISIGVERIFY"},
71  {SCRIPT_ERR_CHECKSIGVERIFY, "CHECKSIGVERIFY"},
72  {SCRIPT_ERR_NUMEQUALVERIFY, "NUMEQUALVERIFY"},
73  {SCRIPT_ERR_BAD_OPCODE, "BAD_OPCODE"},
74  {SCRIPT_ERR_DISABLED_OPCODE, "DISABLED_OPCODE"},
75  {SCRIPT_ERR_INVALID_STACK_OPERATION, "INVALID_STACK_OPERATION"},
76  {SCRIPT_ERR_INVALID_ALTSTACK_OPERATION, "INVALID_ALTSTACK_OPERATION"},
77  {SCRIPT_ERR_UNBALANCED_CONDITIONAL, "UNBALANCED_CONDITIONAL"},
78  {SCRIPT_ERR_NEGATIVE_LOCKTIME, "NEGATIVE_LOCKTIME"},
79  {SCRIPT_ERR_UNSATISFIED_LOCKTIME, "UNSATISFIED_LOCKTIME"},
80  {SCRIPT_ERR_SIG_HASHTYPE, "SIG_HASHTYPE"},
81  {SCRIPT_ERR_SIG_DER, "SIG_DER"},
82  {SCRIPT_ERR_MINIMALDATA, "MINIMALDATA"},
83  {SCRIPT_ERR_SIG_PUSHONLY, "SIG_PUSHONLY"},
84  {SCRIPT_ERR_SIG_HIGH_S, "SIG_HIGH_S"},
85  {SCRIPT_ERR_SIG_NULLDUMMY, "SIG_NULLDUMMY"},
86  {SCRIPT_ERR_PUBKEYTYPE, "PUBKEYTYPE"},
87  {SCRIPT_ERR_CLEANSTACK, "CLEANSTACK"},
88  {SCRIPT_ERR_MINIMALIF, "MINIMALIF"},
89  {SCRIPT_ERR_SIG_NULLFAIL, "NULLFAIL"},
90  {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS, "DISCOURAGE_UPGRADABLE_NOPS"},
91  {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, "DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"},
92  {SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH, "WITNESS_PROGRAM_WRONG_LENGTH"},
93  {SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY, "WITNESS_PROGRAM_WITNESS_EMPTY"},
94  {SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH, "WITNESS_PROGRAM_MISMATCH"},
95  {SCRIPT_ERR_WITNESS_MALLEATED, "WITNESS_MALLEATED"},
96  {SCRIPT_ERR_WITNESS_MALLEATED_P2SH, "WITNESS_MALLEATED_P2SH"},
97  {SCRIPT_ERR_WITNESS_UNEXPECTED, "WITNESS_UNEXPECTED"},
98  {SCRIPT_ERR_WITNESS_PUBKEYTYPE, "WITNESS_PUBKEYTYPE"},
99  {SCRIPT_ERR_OP_CODESEPARATOR, "OP_CODESEPARATOR"},
100  {SCRIPT_ERR_SIG_FINDANDDELETE, "SIG_FINDANDDELETE"},
101 };
102 
103 static std::string FormatScriptError(ScriptError_t err)
104 {
105  for (const auto& se : script_errors)
106  if (se.err == err)
107  return se.name;
108  BOOST_ERROR("Unknown scripterror enumeration value, update script_errors in script_tests.cpp.");
109  return "";
110 }
111 
112 static ScriptError_t ParseScriptError(const std::string& name)
113 {
114  for (const auto& se : script_errors)
115  if (se.name == name)
116  return se.err;
117  BOOST_ERROR("Unknown scripterror \"" << name << "\" in test description");
119 }
120 
121 BOOST_FIXTURE_TEST_SUITE(script_tests, BasicTestingSetup)
122 
123 void DoTest(const CScript& scriptPubKey, const CScript& scriptSig, const CScriptWitness& scriptWitness, uint32_t flags, const std::string& message, int scriptError, CAmount nValue = 0)
124 {
125  bool expect = (scriptError == SCRIPT_ERR_OK);
129  }
130  ScriptError err;
131  const CTransaction txCredit{BuildCreditingTransaction(scriptPubKey, nValue)};
132  CMutableTransaction tx = BuildSpendingTransaction(scriptSig, scriptWitness, txCredit);
133  CMutableTransaction tx2 = tx;
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 < 16; ++i) {
139  uint32_t extra_flags(InsecureRandBits(16));
140  uint32_t 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));
145  }
146 
147 #if defined(HAVE_CONSENSUS_LIB)
148  DataStream stream;
149  stream << TX_WITH_WITNESS(tx2);
150  uint32_t libconsensus_flags{flags & bitcoinconsensus_SCRIPT_FLAGS_VERIFY_ALL};
151  if (libconsensus_flags == flags) {
152  int expectedSuccessCode = expect ? 1 : 0;
154  BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), txCredit.vout[0].nValue, UCharCast(stream.data()), stream.size(), 0, libconsensus_flags, nullptr) == expectedSuccessCode, message);
155  } else {
156  BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), 0, UCharCast(stream.data()), stream.size(), 0, libconsensus_flags, nullptr) == expectedSuccessCode, message);
157  BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), 0, libconsensus_flags, nullptr) == expectedSuccessCode, message);
158  }
159  }
160 #endif
161 }
162 
163 void static NegateSignatureS(std::vector<unsigned char>& vchSig) {
164  // Parse the signature.
165  std::vector<unsigned char> r, s;
166  r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);
167  s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);
168 
169  // Really ugly to implement mod-n negation here, but it would be feature creep to expose such functionality from libsecp256k1.
170  static const unsigned char order[33] = {
171  0x00,
172  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
173  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
174  0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
175  0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41
176  };
177  while (s.size() < 33) {
178  s.insert(s.begin(), 0x00);
179  }
180  int carry = 0;
181  for (int p = 32; p >= 1; p--) {
182  int n = (int)order[p] - s[p] - carry;
183  s[p] = (n + 256) & 0xFF;
184  carry = (n < 0);
185  }
186  assert(carry == 0);
187  if (s.size() > 1 && s[0] == 0 && s[1] < 0x80) {
188  s.erase(s.begin());
189  }
190 
191  // Reconstruct the signature.
192  vchSig.clear();
193  vchSig.push_back(0x30);
194  vchSig.push_back(4 + r.size() + s.size());
195  vchSig.push_back(0x02);
196  vchSig.push_back(r.size());
197  vchSig.insert(vchSig.end(), r.begin(), r.end());
198  vchSig.push_back(0x02);
199  vchSig.push_back(s.size());
200  vchSig.insert(vchSig.end(), s.begin(), s.end());
201 }
202 
203 namespace
204 {
205 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};
206 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};
207 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};
208 
209 struct KeyData
210 {
211  CKey key0, key0C, key1, key1C, key2, key2C;
212  CPubKey pubkey0, pubkey0C, pubkey0H;
213  CPubKey pubkey1, pubkey1C;
214  CPubKey pubkey2, pubkey2C;
215 
216  KeyData()
217  {
218  key0.Set(vchKey0, vchKey0 + 32, false);
219  key0C.Set(vchKey0, vchKey0 + 32, true);
220  pubkey0 = key0.GetPubKey();
221  pubkey0H = key0.GetPubKey();
222  pubkey0C = key0C.GetPubKey();
223  *const_cast<unsigned char*>(pubkey0H.data()) = 0x06 | (pubkey0H[64] & 1);
224 
225  key1.Set(vchKey1, vchKey1 + 32, false);
226  key1C.Set(vchKey1, vchKey1 + 32, true);
227  pubkey1 = key1.GetPubKey();
228  pubkey1C = key1C.GetPubKey();
229 
230  key2.Set(vchKey2, vchKey2 + 32, false);
231  key2C.Set(vchKey2, vchKey2 + 32, true);
232  pubkey2 = key2.GetPubKey();
233  pubkey2C = key2C.GetPubKey();
234  }
235 };
236 
237 enum class WitnessMode {
238  NONE,
239  PKH,
240  SH
241 };
242 
243 class TestBuilder
244 {
245 private:
247  CScript script;
249  CScript redeemscript;
251  CScript witscript;
252  CScriptWitness scriptWitness;
253  CTransactionRef creditTx;
254  CMutableTransaction spendTx;
255  bool havePush{false};
256  std::vector<unsigned char> push;
257  std::string comment;
258  uint32_t flags;
259  int scriptError{SCRIPT_ERR_OK};
260  CAmount nValue;
261 
262  void DoPush()
263  {
264  if (havePush) {
265  spendTx.vin[0].scriptSig << push;
266  havePush = false;
267  }
268  }
269 
270  void DoPush(const std::vector<unsigned char>& data)
271  {
272  DoPush();
273  push = data;
274  havePush = true;
275  }
276 
277 public:
278  TestBuilder(const CScript& script_, const std::string& comment_, uint32_t flags_, bool P2SH = false, WitnessMode wm = WitnessMode::NONE, int witnessversion = 0, CAmount nValue_ = 0) : script(script_), comment(comment_), flags(flags_), nValue(nValue_)
279  {
280  CScript scriptPubKey = script;
281  if (wm == WitnessMode::PKH) {
282  uint160 hash;
283  CHash160().Write(Span{script}.subspan(1)).Finalize(hash);
284  script = CScript() << OP_DUP << OP_HASH160 << ToByteVector(hash) << OP_EQUALVERIFY << OP_CHECKSIG;
285  scriptPubKey = CScript() << witnessversion << ToByteVector(hash);
286  } else if (wm == WitnessMode::SH) {
287  witscript = scriptPubKey;
288  uint256 hash;
289  CSHA256().Write(witscript.data(), witscript.size()).Finalize(hash.begin());
290  scriptPubKey = CScript() << witnessversion << ToByteVector(hash);
291  }
292  if (P2SH) {
293  redeemscript = scriptPubKey;
294  scriptPubKey = CScript() << OP_HASH160 << ToByteVector(CScriptID(redeemscript)) << OP_EQUAL;
295  }
296  creditTx = MakeTransactionRef(BuildCreditingTransaction(scriptPubKey, nValue));
297  spendTx = BuildSpendingTransaction(CScript(), CScriptWitness(), *creditTx);
298  }
299 
300  TestBuilder& ScriptError(ScriptError_t err)
301  {
302  scriptError = err;
303  return *this;
304  }
305 
306  TestBuilder& Opcode(const opcodetype& _op)
307  {
308  DoPush();
309  spendTx.vin[0].scriptSig << _op;
310  return *this;
311  }
312 
313  TestBuilder& Num(int num)
314  {
315  DoPush();
316  spendTx.vin[0].scriptSig << num;
317  return *this;
318  }
319 
320  TestBuilder& Push(const std::string& hex)
321  {
322  DoPush(ParseHex(hex));
323  return *this;
324  }
325 
326  TestBuilder& Push(const CScript& _script)
327  {
328  DoPush(std::vector<unsigned char>(_script.begin(), _script.end()));
329  return *this;
330  }
331 
332  TestBuilder& PushSig(const CKey& key, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32, SigVersion sigversion = SigVersion::BASE, CAmount amount = 0)
333  {
334  uint256 hash = SignatureHash(script, spendTx, 0, nHashType, amount, sigversion);
335  std::vector<unsigned char> vchSig, r, s;
336  uint32_t iter = 0;
337  do {
338  key.Sign(hash, vchSig, false, iter++);
339  if ((lenS == 33) != (vchSig[5 + vchSig[3]] == 33)) {
340  NegateSignatureS(vchSig);
341  }
342  r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);
343  s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);
344  } while (lenR != r.size() || lenS != s.size());
345  vchSig.push_back(static_cast<unsigned char>(nHashType));
346  DoPush(vchSig);
347  return *this;
348  }
349 
350  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)
351  {
352  if (amount == -1)
353  amount = nValue;
354  return PushSig(key, nHashType, lenR, lenS, sigversion, amount).AsWit();
355  }
356 
357  TestBuilder& Push(const CPubKey& pubkey)
358  {
359  DoPush(std::vector<unsigned char>(pubkey.begin(), pubkey.end()));
360  return *this;
361  }
362 
363  TestBuilder& PushRedeem()
364  {
365  DoPush(std::vector<unsigned char>(redeemscript.begin(), redeemscript.end()));
366  return *this;
367  }
368 
369  TestBuilder& PushWitRedeem()
370  {
371  DoPush(std::vector<unsigned char>(witscript.begin(), witscript.end()));
372  return AsWit();
373  }
374 
375  TestBuilder& EditPush(unsigned int pos, const std::string& hexin, const std::string& hexout)
376  {
377  assert(havePush);
378  std::vector<unsigned char> datain = ParseHex(hexin);
379  std::vector<unsigned char> dataout = ParseHex(hexout);
380  assert(pos + datain.size() <= push.size());
381  BOOST_CHECK_MESSAGE(std::vector<unsigned char>(push.begin() + pos, push.begin() + pos + datain.size()) == datain, comment);
382  push.erase(push.begin() + pos, push.begin() + pos + datain.size());
383  push.insert(push.begin() + pos, dataout.begin(), dataout.end());
384  return *this;
385  }
386 
387  TestBuilder& DamagePush(unsigned int pos)
388  {
389  assert(havePush);
390  assert(pos < push.size());
391  push[pos] ^= 1;
392  return *this;
393  }
394 
395  TestBuilder& Test()
396  {
397  TestBuilder copy = *this; // Make a copy so we can rollback the push.
398  DoPush();
399  DoTest(creditTx->vout[0].scriptPubKey, spendTx.vin[0].scriptSig, scriptWitness, flags, comment, scriptError, nValue);
400  *this = copy;
401  return *this;
402  }
403 
404  TestBuilder& AsWit()
405  {
406  assert(havePush);
407  scriptWitness.stack.push_back(push);
408  havePush = false;
409  return *this;
410  }
411 
412  UniValue GetJSON()
413  {
414  DoPush();
415  UniValue array(UniValue::VARR);
416  if (!scriptWitness.stack.empty()) {
418  for (unsigned i = 0; i < scriptWitness.stack.size(); i++) {
419  wit.push_back(HexStr(scriptWitness.stack[i]));
420  }
421  wit.push_back(ValueFromAmount(nValue));
422  array.push_back(wit);
423  }
424  array.push_back(FormatScript(spendTx.vin[0].scriptSig));
425  array.push_back(FormatScript(creditTx->vout[0].scriptPubKey));
426  array.push_back(FormatScriptFlags(flags));
427  array.push_back(FormatScriptError((ScriptError_t)scriptError));
428  array.push_back(comment);
429  return array;
430  }
431 
432  std::string GetComment() const
433  {
434  return comment;
435  }
436 };
437 
438 std::string JSONPrettyPrint(const UniValue& univalue)
439 {
440  std::string ret = univalue.write(4);
441  // Workaround for libunivalue pretty printer, which puts a space between commas and newlines
442  size_t pos = 0;
443  while ((pos = ret.find(" \n", pos)) != std::string::npos) {
444  ret.replace(pos, 2, "\n");
445  pos++;
446  }
447  return ret;
448 }
449 } // namespace
450 
451 BOOST_AUTO_TEST_CASE(script_build)
452 {
453  const KeyData keys;
454 
455  std::vector<TestBuilder> tests;
456 
457  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
458  "P2PK", 0
459  ).PushSig(keys.key0));
460  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
461  "P2PK, bad sig", 0
462  ).PushSig(keys.key0).DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE));
463 
464  tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
465  "P2PKH", 0
466  ).PushSig(keys.key1).Push(keys.pubkey1C));
467  tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey2C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
468  "P2PKH, bad pubkey", 0
469  ).PushSig(keys.key2).Push(keys.pubkey2C).DamagePush(5).ScriptError(SCRIPT_ERR_EQUALVERIFY));
470 
471  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
472  "P2PK anyonecanpay", 0
473  ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY));
474  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
475  "P2PK anyonecanpay marked with normal hashtype", 0
476  ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY).EditPush(70, "81", "01").ScriptError(SCRIPT_ERR_EVAL_FALSE));
477 
478  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
479  "P2SH(P2PK)", SCRIPT_VERIFY_P2SH, true
480  ).PushSig(keys.key0).PushRedeem());
481  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
482  "P2SH(P2PK), bad redeemscript", SCRIPT_VERIFY_P2SH, true
483  ).PushSig(keys.key0).PushRedeem().DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE));
484 
485  tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey0.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
486  "P2SH(P2PKH)", SCRIPT_VERIFY_P2SH, true
487  ).PushSig(keys.key0).Push(keys.pubkey0).PushRedeem());
488  tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
489  "P2SH(P2PKH), bad sig but no VERIFY_P2SH", 0, true
490  ).PushSig(keys.key0).DamagePush(10).PushRedeem());
491  tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
492  "P2SH(P2PKH), bad sig", SCRIPT_VERIFY_P2SH, true
493  ).PushSig(keys.key0).DamagePush(10).PushRedeem().ScriptError(SCRIPT_ERR_EQUALVERIFY));
494 
495  tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
496  "3-of-3", 0
497  ).Num(0).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
498  tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
499  "3-of-3, 2 sigs", 0
500  ).Num(0).PushSig(keys.key0).PushSig(keys.key1).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
501 
502  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
503  "P2SH(2-of-3)", SCRIPT_VERIFY_P2SH, true
504  ).Num(0).PushSig(keys.key1).PushSig(keys.key2).PushRedeem());
505  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
506  "P2SH(2-of-3), 1 sig", SCRIPT_VERIFY_P2SH, true
507  ).Num(0).PushSig(keys.key1).Num(0).PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
508 
509  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
510  "P2PK with too much R padding but no DERSIG", 0
511  ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000"));
512  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
513  "P2PK with too much R padding", SCRIPT_VERIFY_DERSIG
514  ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER));
515  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
516  "P2PK with too much S padding but no DERSIG", 0
517  ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100"));
518  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
519  "P2PK with too much S padding", SCRIPT_VERIFY_DERSIG
520  ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100").ScriptError(SCRIPT_ERR_SIG_DER));
521  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
522  "P2PK with too little R padding but no DERSIG", 0
523  ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
524  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
525  "P2PK with too little R padding", SCRIPT_VERIFY_DERSIG
526  ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
527  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
528  "P2PK NOT with bad sig with too much R padding but no DERSIG", 0
529  ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10));
530  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
531  "P2PK NOT with bad sig with too much R padding", SCRIPT_VERIFY_DERSIG
532  ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10).ScriptError(SCRIPT_ERR_SIG_DER));
533  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
534  "P2PK NOT with too much R padding but no DERSIG", 0
535  ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_EVAL_FALSE));
536  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
537  "P2PK NOT with too much R padding", SCRIPT_VERIFY_DERSIG
538  ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER));
539 
540  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
541  "BIP66 example 1, without DERSIG", 0
542  ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
543  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
544  "BIP66 example 1, with DERSIG", SCRIPT_VERIFY_DERSIG
545  ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
546  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
547  "BIP66 example 2, without DERSIG", 0
548  ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE));
549  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
550  "BIP66 example 2, with DERSIG", SCRIPT_VERIFY_DERSIG
551  ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
552  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
553  "BIP66 example 3, without DERSIG", 0
554  ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
555  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
556  "BIP66 example 3, with DERSIG", SCRIPT_VERIFY_DERSIG
557  ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
558  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
559  "BIP66 example 4, without DERSIG", 0
560  ).Num(0));
561  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
562  "BIP66 example 4, with DERSIG", SCRIPT_VERIFY_DERSIG
563  ).Num(0));
564  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
565  "BIP66 example 5, without DERSIG", 0
566  ).Num(1).ScriptError(SCRIPT_ERR_EVAL_FALSE));
567  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
568  "BIP66 example 5, with DERSIG", SCRIPT_VERIFY_DERSIG
569  ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER));
570  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
571  "BIP66 example 6, without DERSIG", 0
572  ).Num(1));
573  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
574  "BIP66 example 6, with DERSIG", SCRIPT_VERIFY_DERSIG
575  ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER));
576  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
577  "BIP66 example 7, without DERSIG", 0
578  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2));
579  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
580  "BIP66 example 7, with DERSIG", SCRIPT_VERIFY_DERSIG
581  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER));
582  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
583  "BIP66 example 8, without DERSIG", 0
584  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_EVAL_FALSE));
585  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
586  "BIP66 example 8, with DERSIG", SCRIPT_VERIFY_DERSIG
587  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER));
588  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
589  "BIP66 example 9, without DERSIG", 0
590  ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE));
591  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
592  "BIP66 example 9, with DERSIG", SCRIPT_VERIFY_DERSIG
593  ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
594  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
595  "BIP66 example 10, without DERSIG", 0
596  ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
597  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
598  "BIP66 example 10, with DERSIG", SCRIPT_VERIFY_DERSIG
599  ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
600  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
601  "BIP66 example 11, without DERSIG", 0
602  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
603  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
604  "BIP66 example 11, with DERSIG", SCRIPT_VERIFY_DERSIG
605  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
606  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
607  "BIP66 example 12, without DERSIG", 0
608  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
609  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
610  "BIP66 example 12, with DERSIG", SCRIPT_VERIFY_DERSIG
611  ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
612  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
613  "P2PK with multi-byte hashtype, without DERSIG", 0
614  ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101"));
615  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
616  "P2PK with multi-byte hashtype, with DERSIG", SCRIPT_VERIFY_DERSIG
617  ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101").ScriptError(SCRIPT_ERR_SIG_DER));
618 
619  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
620  "P2PK with high S but no LOW_S", 0
621  ).PushSig(keys.key2, SIGHASH_ALL, 32, 33));
622  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
623  "P2PK with high S", SCRIPT_VERIFY_LOW_S
624  ).PushSig(keys.key2, SIGHASH_ALL, 32, 33).ScriptError(SCRIPT_ERR_SIG_HIGH_S));
625 
626  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,
627  "P2PK with hybrid pubkey but no STRICTENC", 0
628  ).PushSig(keys.key0, SIGHASH_ALL));
629  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,
630  "P2PK with hybrid pubkey", SCRIPT_VERIFY_STRICTENC
631  ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
632  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
633  "P2PK NOT with hybrid pubkey but no STRICTENC", 0
634  ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_EVAL_FALSE));
635  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
636  "P2PK NOT with hybrid pubkey", SCRIPT_VERIFY_STRICTENC
637  ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
638  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
639  "P2PK NOT with invalid hybrid pubkey but no STRICTENC", 0
640  ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10));
641  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
642  "P2PK NOT with invalid hybrid pubkey", SCRIPT_VERIFY_STRICTENC
643  ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
644  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
645  "1-of-2 with the second 1 hybrid pubkey and no STRICTENC", 0
646  ).Num(0).PushSig(keys.key1, SIGHASH_ALL));
647  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
648  "1-of-2 with the second 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC
649  ).Num(0).PushSig(keys.key1, SIGHASH_ALL));
650  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0H) << OP_2 << OP_CHECKMULTISIG,
651  "1-of-2 with the first 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC
652  ).Num(0).PushSig(keys.key1, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
653 
654  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
655  "P2PK with undefined hashtype but no STRICTENC", 0
656  ).PushSig(keys.key1, 5));
657  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
658  "P2PK with undefined hashtype", SCRIPT_VERIFY_STRICTENC
659  ).PushSig(keys.key1, 5).ScriptError(SCRIPT_ERR_SIG_HASHTYPE));
660  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,
661  "P2PK NOT with invalid sig and undefined hashtype but no STRICTENC", 0
662  ).PushSig(keys.key1, 5).DamagePush(10));
663  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,
664  "P2PK NOT with invalid sig and undefined hashtype", SCRIPT_VERIFY_STRICTENC
665  ).PushSig(keys.key1, 5).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_HASHTYPE));
666 
667  tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
668  "3-of-3 with nonzero dummy but no NULLDUMMY", 0
669  ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
670  tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
671  "3-of-3 with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY
672  ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY));
673  tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,
674  "3-of-3 NOT with invalid sig and nonzero dummy but no NULLDUMMY", 0
675  ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10));
676  tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,
677  "3-of-3 NOT with invalid sig with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY
678  ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY));
679 
680  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
681  "2-of-2 with two identical keys and sigs pushed using OP_DUP but no SIGPUSHONLY", 0
682  ).Num(0).PushSig(keys.key1).Opcode(OP_DUP));
683  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
684  "2-of-2 with two identical keys and sigs pushed using OP_DUP", SCRIPT_VERIFY_SIGPUSHONLY
685  ).Num(0).PushSig(keys.key1).Opcode(OP_DUP).ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
686  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
687  "P2SH(P2PK) with non-push scriptSig but no P2SH or SIGPUSHONLY", 0, true
688  ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem());
689  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
690  "P2PK with non-push scriptSig but with P2SH validation", 0
691  ).PushSig(keys.key2).Opcode(OP_NOP8));
692  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
693  "P2SH(P2PK) with non-push scriptSig but no SIGPUSHONLY", SCRIPT_VERIFY_P2SH, true
694  ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
695  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
696  "P2SH(P2PK) with non-push scriptSig but not P2SH", SCRIPT_VERIFY_SIGPUSHONLY, true
697  ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
698  tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
699  "2-of-2 with two identical keys and sigs pushed", SCRIPT_VERIFY_SIGPUSHONLY
700  ).Num(0).PushSig(keys.key1).PushSig(keys.key1));
701  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
702  "P2PK with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH
703  ).Num(11).PushSig(keys.key0));
704  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
705  "P2PK with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH
706  ).Num(11).PushSig(keys.key0).ScriptError(SCRIPT_ERR_CLEANSTACK));
707  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
708  "P2SH with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH, true
709  ).Num(11).PushSig(keys.key0).PushRedeem());
710  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
711  "P2SH with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true
712  ).Num(11).PushSig(keys.key0).PushRedeem().ScriptError(SCRIPT_ERR_CLEANSTACK));
713  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
714  "P2SH with CLEANSTACK", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true
715  ).PushSig(keys.key0).PushRedeem());
716 
717  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
718  "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
719  0, 1).PushWitSig(keys.key0).PushWitRedeem());
720  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
721  "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH,
722  0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit());
723  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
724  "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
725  0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
726  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
727  "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH,
728  0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem());
729  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
730  "Basic P2WSH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
731  ).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
732  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
733  "Basic P2WPKH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
734  ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE));
735  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
736  "Basic P2SH(P2WSH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH
737  ).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
738  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
739  "Basic P2SH(P2WPKH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
740  ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
741  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
742  "Basic P2WSH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
743  ).PushWitSig(keys.key0).PushWitRedeem());
744  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
745  "Basic P2WPKH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
746  ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit());
747  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
748  "Basic P2SH(P2WSH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WitnessMode::SH
749  ).PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
750  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
751  "Basic P2SH(P2WPKH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
752  ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem());
753  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
754  "Basic P2WSH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
755  0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
756  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
757  "Basic P2WPKH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH,
758  0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE));
759  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
760  "Basic P2SH(P2WSH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
761  0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
762  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
763  "Basic P2SH(P2WPKH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH,
764  0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
765 
766  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
767  "P2WPKH with future witness version", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH |
768  SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, false, WitnessMode::PKH, 1
769  ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM));
770  {
771  CScript witscript = CScript() << ToByteVector(keys.pubkey0);
772  uint256 hash;
773  CSHA256().Write(witscript.data(), witscript.size()).Finalize(hash.begin());
774  std::vector<unsigned char> hashBytes = ToByteVector(hash);
775  hashBytes.pop_back();
776  tests.push_back(TestBuilder(CScript() << OP_0 << hashBytes,
777  "P2WPKH with wrong witness program length", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false
778  ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH));
779  }
780  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
781  "P2WSH with empty witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
783  {
784  CScript witscript = CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG;
785  tests.push_back(TestBuilder(witscript,
786  "P2WSH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
787  ).PushWitSig(keys.key0).Push(witscript).DamagePush(0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH));
788  }
789  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
790  "P2WPKH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
791  ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH));
792  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
793  "P2WPKH with non-empty scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
794  ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Num(11).ScriptError(SCRIPT_ERR_WITNESS_MALLEATED));
795  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
796  "P2SH(P2WPKH) with superfluous push in scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
797  ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().Num(11).PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_MALLEATED_P2SH));
798  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
799  "P2PK with witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH
800  ).PushSig(keys.key0).Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_UNEXPECTED));
801 
802  // Compressed keys should pass SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
803  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
804  "Basic P2WSH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
805  0, 1).PushWitSig(keys.key0C).PushWitRedeem());
806  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C),
807  "Basic P2WPKH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::PKH,
808  0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit());
809  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
810  "Basic P2SH(P2WSH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
811  0, 1).PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
812  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C),
813  "Basic P2SH(P2WPKH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::PKH,
814  0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit().PushRedeem());
815 
816  // Testing uncompressed key in witness with SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
817  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
818  "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
819  0, 1).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
820  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
821  "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::PKH,
822  0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
823  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
824  "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
825  0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
826  tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
827  "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::PKH,
828  0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
829 
830  // P2WSH 1-of-2 multisig with compressed keys
831  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
832  "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
833  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
834  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
835  "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
836  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
837  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
838  "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, 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.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
841  "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
842  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem());
843 
844  // P2WSH 1-of-2 multisig with first key uncompressed
845  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
846  "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
847  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem());
848  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
849  "P2SH(P2WSH) CHECKMULTISIG first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
850  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
851  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
852  "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,
853  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
854  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
855  "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,
856  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
857  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
858  "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
859  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem());
860  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
861  "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
862  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem());
863  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
864  "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,
865  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
866  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
867  "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,
868  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
869  // P2WSH 1-of-2 multisig with second key uncompressed
870  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
871  "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
872  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
873  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
874  "P2SH(P2WSH) CHECKMULTISIG second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
875  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
876  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
877  "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,
878  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
879  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
880  "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,
881  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
882  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
883  "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
884  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem());
885  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
886  "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
887  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem());
888  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
889  "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,
890  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
891  tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
892  "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,
893  0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
894 
895  std::set<std::string> tests_set;
896 
897  {
899 
900  for (unsigned int idx = 0; idx < json_tests.size(); idx++) {
901  const UniValue& tv = json_tests[idx];
902  tests_set.insert(JSONPrettyPrint(tv.get_array()));
903  }
904  }
905 
906 #ifdef UPDATE_JSON_TESTS
907  std::string strGen;
908 #endif
909  for (TestBuilder& test : tests) {
910  test.Test();
911  std::string str = JSONPrettyPrint(test.GetJSON());
912 #ifdef UPDATE_JSON_TESTS
913  strGen += str + ",\n";
914 #else
915  if (tests_set.count(str) == 0) {
916  BOOST_CHECK_MESSAGE(false, "Missing auto script_valid test: " + test.GetComment());
917  }
918 #endif
919  }
920 
921 #ifdef UPDATE_JSON_TESTS
922  FILE* file = fsbridge::fopen("script_tests.json.gen", "w");
923  fputs(strGen.c_str(), file);
924  fclose(file);
925 #endif
926 }
927 
928 BOOST_AUTO_TEST_CASE(script_json_test)
929 {
930  // Read tests from test/data/script_tests.json
931  // Format is an array of arrays
932  // Inner arrays are [ ["wit"..., nValue]?, "scriptSig", "scriptPubKey", "flags", "expected_scripterror" ]
933  // ... where scriptSig and scriptPubKey are stringified
934  // scripts.
935  // If a witness is given, then the last value in the array should be the
936  // amount (nValue) to use in the crediting tx
938 
939  for (unsigned int idx = 0; idx < tests.size(); idx++) {
940  const UniValue& test = tests[idx];
941  std::string strTest = test.write();
942  CScriptWitness witness;
943  CAmount nValue = 0;
944  unsigned int pos = 0;
945  if (test.size() > 0 && test[pos].isArray()) {
946  unsigned int i=0;
947  for (i = 0; i < test[pos].size()-1; i++) {
948  witness.stack.push_back(ParseHex(test[pos][i].get_str()));
949  }
950  nValue = AmountFromValue(test[pos][i]);
951  pos++;
952  }
953  if (test.size() < 4 + pos) // Allow size > 3; extra stuff ignored (useful for comments)
954  {
955  if (test.size() != 1) {
956  BOOST_ERROR("Bad test: " << strTest);
957  }
958  continue;
959  }
960  std::string scriptSigString = test[pos++].get_str();
961  CScript scriptSig = ParseScript(scriptSigString);
962  std::string scriptPubKeyString = test[pos++].get_str();
963  CScript scriptPubKey = ParseScript(scriptPubKeyString);
964  unsigned int scriptflags = ParseScriptFlags(test[pos++].get_str());
965  int scriptError = ParseScriptError(test[pos++].get_str());
966 
967  DoTest(scriptPubKey, scriptSig, witness, scriptflags, strTest, scriptError, nValue);
968  }
969 }
970 
971 BOOST_AUTO_TEST_CASE(script_PushData)
972 {
973  // Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on
974  // the stack as the 1-75 opcodes do.
975  static const unsigned char direct[] = { 1, 0x5a };
976  static const unsigned char pushdata1[] = { OP_PUSHDATA1, 1, 0x5a };
977  static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a };
978  static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a };
979 
980  ScriptError err;
981  std::vector<std::vector<unsigned char> > directStack;
982  BOOST_CHECK(EvalScript(directStack, CScript(direct, direct + sizeof(direct)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
983  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
984 
985  std::vector<std::vector<unsigned char> > pushdata1Stack;
986  BOOST_CHECK(EvalScript(pushdata1Stack, CScript(pushdata1, pushdata1 + sizeof(pushdata1)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
987  BOOST_CHECK(pushdata1Stack == directStack);
988  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
989 
990  std::vector<std::vector<unsigned char> > pushdata2Stack;
991  BOOST_CHECK(EvalScript(pushdata2Stack, CScript(pushdata2, pushdata2 + sizeof(pushdata2)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
992  BOOST_CHECK(pushdata2Stack == directStack);
993  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
994 
995  std::vector<std::vector<unsigned char> > pushdata4Stack;
996  BOOST_CHECK(EvalScript(pushdata4Stack, CScript(pushdata4, pushdata4 + sizeof(pushdata4)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
997  BOOST_CHECK(pushdata4Stack == directStack);
998  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
999 
1000  const std::vector<unsigned char> pushdata1_trunc{OP_PUSHDATA1, 1};
1001  const std::vector<unsigned char> pushdata2_trunc{OP_PUSHDATA2, 1, 0};
1002  const std::vector<unsigned char> pushdata4_trunc{OP_PUSHDATA4, 1, 0, 0, 0};
1003 
1004  std::vector<std::vector<unsigned char>> stack_ignore;
1005  BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata1_trunc.begin(), pushdata1_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1007  BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata2_trunc.begin(), pushdata2_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1009  BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata4_trunc.begin(), pushdata4_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
1011 }
1012 
1013 BOOST_AUTO_TEST_CASE(script_cltv_truncated)
1014 {
1015  const auto script_cltv_trunc = CScript() << OP_CHECKLOCKTIMEVERIFY;
1016 
1017  std::vector<std::vector<unsigned char>> stack_ignore;
1018  ScriptError err;
1021 }
1022 
1023 static CScript
1024 sign_multisig(const CScript& scriptPubKey, const std::vector<CKey>& keys, const CTransaction& transaction)
1025 {
1026  uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL, 0, SigVersion::BASE);
1027 
1028  CScript result;
1029  //
1030  // NOTE: CHECKMULTISIG has an unfortunate bug; it requires
1031  // one extra item on the stack, before the signatures.
1032  // Putting OP_0 on the stack is the workaround;
1033  // fixing the bug would mean splitting the block chain (old
1034  // clients would not accept new CHECKMULTISIG transactions,
1035  // and vice-versa)
1036  //
1037  result << OP_0;
1038  for (const CKey &key : keys)
1039  {
1040  std::vector<unsigned char> vchSig;
1041  BOOST_CHECK(key.Sign(hash, vchSig));
1042  vchSig.push_back((unsigned char)SIGHASH_ALL);
1043  result << vchSig;
1044  }
1045  return result;
1046 }
1047 static CScript
1048 sign_multisig(const CScript& scriptPubKey, const CKey& key, const CTransaction& transaction)
1049 {
1050  std::vector<CKey> keys;
1051  keys.push_back(key);
1052  return sign_multisig(scriptPubKey, keys, transaction);
1053 }
1054 
1055 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)
1056 {
1057  ScriptError err;
1058  CKey key1 = GenerateRandomKey();
1059  CKey key2 = GenerateRandomKey(/*compressed=*/false);
1060  CKey key3 = GenerateRandomKey();
1061 
1062  CScript scriptPubKey12;
1063  scriptPubKey12 << OP_1 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
1064 
1065  const CTransaction txFrom12{BuildCreditingTransaction(scriptPubKey12)};
1067 
1068  CScript goodsig1 = sign_multisig(scriptPubKey12, key1, CTransaction(txTo12));
1069  BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1070  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1071  txTo12.vout[0].nValue = 2;
1072  BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1073  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1074 
1075  CScript goodsig2 = sign_multisig(scriptPubKey12, key2, CTransaction(txTo12));
1076  BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1077  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1078 
1079  CScript badsig1 = sign_multisig(scriptPubKey12, key3, CTransaction(txTo12));
1080  BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1081  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1082 }
1083 
1084 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)
1085 {
1086  ScriptError err;
1087  CKey key1 = GenerateRandomKey();
1088  CKey key2 = GenerateRandomKey(/*compressed=*/false);
1089  CKey key3 = GenerateRandomKey();
1090  CKey key4 = GenerateRandomKey(/*compressed=*/false);
1091 
1092  CScript scriptPubKey23;
1093  scriptPubKey23 << OP_2 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << ToByteVector(key3.GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
1094 
1095  const CTransaction txFrom23{BuildCreditingTransaction(scriptPubKey23)};
1097 
1098  std::vector<CKey> keys;
1099  keys.push_back(key1); keys.push_back(key2);
1100  CScript goodsig1 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1101  BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1102  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1103 
1104  keys.clear();
1105  keys.push_back(key1); keys.push_back(key3);
1106  CScript goodsig2 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1107  BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1108  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1109 
1110  keys.clear();
1111  keys.push_back(key2); keys.push_back(key3);
1112  CScript goodsig3 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1113  BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1114  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1115 
1116  keys.clear();
1117  keys.push_back(key2); keys.push_back(key2); // Can't reuse sig
1118  CScript badsig1 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1119  BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1120  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1121 
1122  keys.clear();
1123  keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order
1124  CScript badsig2 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1125  BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1126  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1127 
1128  keys.clear();
1129  keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order
1130  CScript badsig3 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1131  BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1132  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1133 
1134  keys.clear();
1135  keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys
1136  CScript badsig4 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1137  BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1138  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1139 
1140  keys.clear();
1141  keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys
1142  CScript badsig5 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1143  BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1144  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
1145 
1146  keys.clear(); // Must have signatures
1147  CScript badsig6 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
1148  BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL), &err));
1149  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err));
1150 }
1151 
1152 /* Wrapper around ProduceSignature to combine two scriptsigs */
1153 SignatureData CombineSignatures(const CTxOut& txout, const CMutableTransaction& tx, const SignatureData& scriptSig1, const SignatureData& scriptSig2)
1154 {
1155  SignatureData data;
1156  data.MergeSignatureData(scriptSig1);
1157  data.MergeSignatureData(scriptSig2);
1159  return data;
1160 }
1161 
1162 BOOST_AUTO_TEST_CASE(script_combineSigs)
1163 {
1164  // Test the ProduceSignature's ability to combine signatures function
1165  FillableSigningProvider keystore;
1166  std::vector<CKey> keys;
1167  std::vector<CPubKey> pubkeys;
1168  for (int i = 0; i < 3; i++)
1169  {
1170  CKey key = GenerateRandomKey(/*compressed=*/i%2 == 1);
1171  keys.push_back(key);
1172  pubkeys.push_back(key.GetPubKey());
1173  BOOST_CHECK(keystore.AddKey(key));
1174  }
1175 
1178  CScript& scriptPubKey = txFrom.vout[0].scriptPubKey;
1179  SignatureData scriptSig;
1180 
1181  SignatureData empty;
1182  SignatureData combined = CombineSignatures(txFrom.vout[0], txTo, empty, empty);
1183  BOOST_CHECK(combined.scriptSig.empty());
1184 
1185  // Single signature case:
1186  SignatureData dummy;
1187  BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy)); // changes scriptSig
1188  scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1189  combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
1190  BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1191  combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
1192  BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1193  SignatureData scriptSigCopy = scriptSig;
1194  // Signing again will give a different, valid signature:
1195  SignatureData dummy_b;
1196  BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_b));
1197  scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1198  combined = CombineSignatures(txFrom.vout[0], txTo, scriptSigCopy, scriptSig);
1199  BOOST_CHECK(combined.scriptSig == scriptSigCopy.scriptSig || combined.scriptSig == scriptSig.scriptSig);
1200 
1201  // P2SH, single-signature case:
1202  CScript pkSingle; pkSingle << ToByteVector(keys[0].GetPubKey()) << OP_CHECKSIG;
1203  BOOST_CHECK(keystore.AddCScript(pkSingle));
1204  scriptPubKey = GetScriptForDestination(ScriptHash(pkSingle));
1205  SignatureData dummy_c;
1206  BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_c));
1207  scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1208  combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
1209  BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1210  combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
1211  BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1212  scriptSigCopy = scriptSig;
1213  SignatureData dummy_d;
1214  BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_d));
1215  scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1216  combined = CombineSignatures(txFrom.vout[0], txTo, scriptSigCopy, scriptSig);
1217  BOOST_CHECK(combined.scriptSig == scriptSigCopy.scriptSig || combined.scriptSig == scriptSig.scriptSig);
1218 
1219  // Hardest case: Multisig 2-of-3
1220  scriptPubKey = GetScriptForMultisig(2, pubkeys);
1221  BOOST_CHECK(keystore.AddCScript(scriptPubKey));
1222  SignatureData dummy_e;
1223  BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL, dummy_e));
1224  scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
1225  combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
1226  BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1227  combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
1228  BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
1229 
1230  // A couple of partially-signed versions:
1231  std::vector<unsigned char> sig1;
1232  uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL, 0, SigVersion::BASE);
1233  BOOST_CHECK(keys[0].Sign(hash1, sig1));
1234  sig1.push_back(SIGHASH_ALL);
1235  std::vector<unsigned char> sig2;
1236  uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE, 0, SigVersion::BASE);
1237  BOOST_CHECK(keys[1].Sign(hash2, sig2));
1238  sig2.push_back(SIGHASH_NONE);
1239  std::vector<unsigned char> sig3;
1240  uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE, 0, SigVersion::BASE);
1241  BOOST_CHECK(keys[2].Sign(hash3, sig3));
1242  sig3.push_back(SIGHASH_SINGLE);
1243 
1244  // Not fussy about order (or even existence) of placeholders or signatures:
1245  CScript partial1a = CScript() << OP_0 << sig1 << OP_0;
1246  CScript partial1b = CScript() << OP_0 << OP_0 << sig1;
1247  CScript partial2a = CScript() << OP_0 << sig2;
1248  CScript partial2b = CScript() << sig2 << OP_0;
1249  CScript partial3a = CScript() << sig3;
1250  CScript partial3b = CScript() << OP_0 << OP_0 << sig3;
1251  CScript partial3c = CScript() << OP_0 << sig3 << OP_0;
1252  CScript complete12 = CScript() << OP_0 << sig1 << sig2;
1253  CScript complete13 = CScript() << OP_0 << sig1 << sig3;
1254  CScript complete23 = CScript() << OP_0 << sig2 << sig3;
1255  SignatureData partial1_sigs;
1256  partial1_sigs.signatures.emplace(keys[0].GetPubKey().GetID(), SigPair(keys[0].GetPubKey(), sig1));
1257  SignatureData partial2_sigs;
1258  partial2_sigs.signatures.emplace(keys[1].GetPubKey().GetID(), SigPair(keys[1].GetPubKey(), sig2));
1259  SignatureData partial3_sigs;
1260  partial3_sigs.signatures.emplace(keys[2].GetPubKey().GetID(), SigPair(keys[2].GetPubKey(), sig3));
1261 
1262  combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial1_sigs);
1263  BOOST_CHECK(combined.scriptSig == partial1a);
1264  combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial2_sigs);
1265  BOOST_CHECK(combined.scriptSig == complete12);
1266  combined = CombineSignatures(txFrom.vout[0], txTo, partial2_sigs, partial1_sigs);
1267  BOOST_CHECK(combined.scriptSig == complete12);
1268  combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial2_sigs);
1269  BOOST_CHECK(combined.scriptSig == complete12);
1270  combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial1_sigs);
1271  BOOST_CHECK(combined.scriptSig == complete13);
1272  combined = CombineSignatures(txFrom.vout[0], txTo, partial2_sigs, partial3_sigs);
1273  BOOST_CHECK(combined.scriptSig == complete23);
1274  combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial2_sigs);
1275  BOOST_CHECK(combined.scriptSig == complete23);
1276  combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial3_sigs);
1277  BOOST_CHECK(combined.scriptSig == partial3c);
1278 }
1279 
1283 BOOST_AUTO_TEST_CASE(sign_invalid_miniscript)
1284 {
1285  FillableSigningProvider keystore;
1286  SignatureData sig_data;
1287  CMutableTransaction prev, curr;
1288 
1289  // Create a Taproot output which contains a leaf in which a non-32 bytes push is used where a public key is expected
1290  // by the Miniscript parser. This offending Script was found by the RPC fuzzer.
1291  const auto invalid_pubkey{ParseHex("173d36c8c9c9c9ffffffffffff0200000000021e1e37373721361818181818181e1e1e1e19000000000000000000b19292929292926b006c9b9b9292")};
1292  TaprootBuilder builder;
1293  builder.Add(0, {invalid_pubkey}, 0xc0);
1294  XOnlyPubKey nums{ParseHex("50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0")};
1295  builder.Finalize(nums);
1296  prev.vout.emplace_back(0, GetScriptForDestination(builder.GetOutput()));
1297  curr.vin.emplace_back(COutPoint{prev.GetHash(), 0});
1298  sig_data.tr_spenddata = builder.GetSpendData();
1299 
1300  // SignSignature can fail but it shouldn't raise an exception (nor crash).
1301  BOOST_CHECK(!SignSignature(keystore, CTransaction(prev), curr, 0, SIGHASH_ALL, sig_data));
1302 }
1303 
1304 BOOST_AUTO_TEST_CASE(script_standard_push)
1305 {
1306  ScriptError err;
1307  for (int i=0; i<67000; i++) {
1308  CScript script;
1309  script << i;
1310  BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Number " << i << " is not pure push.");
1311  BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Number " << i << " push is not minimal data.");
1312  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1313  }
1314 
1315  for (unsigned int i=0; i<=MAX_SCRIPT_ELEMENT_SIZE; i++) {
1316  std::vector<unsigned char> data(i, '\111');
1317  CScript script;
1318  script << data;
1319  BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Length " << i << " is not pure push.");
1320  BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Length " << i << " push is not minimal data.");
1321  BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
1322  }
1323 }
1324 
1325 BOOST_AUTO_TEST_CASE(script_IsPushOnly_on_invalid_scripts)
1326 {
1327  // IsPushOnly returns false when given a script containing only pushes that
1328  // are invalid due to truncation. IsPushOnly() is consensus critical
1329  // because P2SH evaluation uses it, although this specific behavior should
1330  // not be consensus critical as the P2SH evaluation would fail first due to
1331  // the invalid push. Still, it doesn't hurt to test it explicitly.
1332  static const unsigned char direct[] = { 1 };
1333  BOOST_CHECK(!CScript(direct, direct+sizeof(direct)).IsPushOnly());
1334 }
1335 
1336 BOOST_AUTO_TEST_CASE(script_GetScriptAsm)
1337 {
1338  BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2, true));
1339  BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY, true));
1340  BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2));
1341  BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY));
1342 
1343  std::string derSig("304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c5090");
1344  std::string pubKey("03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2");
1345  std::vector<unsigned char> vchPubKey = ToByteVector(ParseHex(pubKey));
1346 
1347  BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey, true));
1348  BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey, true));
1349  BOOST_CHECK_EQUAL(derSig + "[ALL] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey, true));
1350  BOOST_CHECK_EQUAL(derSig + "[NONE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey, true));
1351  BOOST_CHECK_EQUAL(derSig + "[SINGLE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey, true));
1352  BOOST_CHECK_EQUAL(derSig + "[ALL|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey, true));
1353  BOOST_CHECK_EQUAL(derSig + "[NONE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey, true));
1354  BOOST_CHECK_EQUAL(derSig + "[SINGLE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey, true));
1355 
1356  BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey));
1357  BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey));
1358  BOOST_CHECK_EQUAL(derSig + "01 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey));
1359  BOOST_CHECK_EQUAL(derSig + "02 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey));
1360  BOOST_CHECK_EQUAL(derSig + "03 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey));
1361  BOOST_CHECK_EQUAL(derSig + "81 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey));
1362  BOOST_CHECK_EQUAL(derSig + "82 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey));
1363  BOOST_CHECK_EQUAL(derSig + "83 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey));
1364 }
1365 
1366 static CScript ScriptFromHex(const std::string& str)
1367 {
1368  std::vector<unsigned char> data = ParseHex(str);
1369  return CScript(data.begin(), data.end());
1370 }
1371 
1372 BOOST_AUTO_TEST_CASE(script_FindAndDelete)
1373 {
1374  // Exercise the FindAndDelete functionality
1375  CScript s;
1376  CScript d;
1377  CScript expect;
1378 
1379  s = CScript() << OP_1 << OP_2;
1380  d = CScript(); // delete nothing should be a no-op
1381  expect = s;
1382  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
1383  BOOST_CHECK(s == expect);
1384 
1385  s = CScript() << OP_1 << OP_2 << OP_3;
1386  d = CScript() << OP_2;
1387  expect = CScript() << OP_1 << OP_3;
1388  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1389  BOOST_CHECK(s == expect);
1390 
1391  s = CScript() << OP_3 << OP_1 << OP_3 << OP_3 << OP_4 << OP_3;
1392  d = CScript() << OP_3;
1393  expect = CScript() << OP_1 << OP_4;
1394  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 4);
1395  BOOST_CHECK(s == expect);
1396 
1397  s = ScriptFromHex("0302ff03"); // PUSH 0x02ff03 onto stack
1398  d = ScriptFromHex("0302ff03");
1399  expect = CScript();
1400  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1401  BOOST_CHECK(s == expect);
1402 
1403  s = ScriptFromHex("0302ff030302ff03"); // PUSH 0x2ff03 PUSH 0x2ff03
1404  d = ScriptFromHex("0302ff03");
1405  expect = CScript();
1406  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 2);
1407  BOOST_CHECK(s == expect);
1408 
1409  s = ScriptFromHex("0302ff030302ff03");
1410  d = ScriptFromHex("02");
1411  expect = s; // FindAndDelete matches entire opcodes
1412  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
1413  BOOST_CHECK(s == expect);
1414 
1415  s = ScriptFromHex("0302ff030302ff03");
1416  d = ScriptFromHex("ff");
1417  expect = s;
1418  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
1419  BOOST_CHECK(s == expect);
1420 
1421  // This is an odd edge case: strip of the push-three-bytes
1422  // prefix, leaving 02ff03 which is push-two-bytes:
1423  s = ScriptFromHex("0302ff030302ff03");
1424  d = ScriptFromHex("03");
1425  expect = CScript() << ParseHex("ff03") << ParseHex("ff03");
1426  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 2);
1427  BOOST_CHECK(s == expect);
1428 
1429  // Byte sequence that spans multiple opcodes:
1430  s = ScriptFromHex("02feed5169"); // PUSH(0xfeed) OP_1 OP_VERIFY
1431  d = ScriptFromHex("feed51");
1432  expect = s;
1433  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0); // doesn't match 'inside' opcodes
1434  BOOST_CHECK(s == expect);
1435 
1436  s = ScriptFromHex("02feed5169"); // PUSH(0xfeed) OP_1 OP_VERIFY
1437  d = ScriptFromHex("02feed51");
1438  expect = ScriptFromHex("69");
1439  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1440  BOOST_CHECK(s == expect);
1441 
1442  s = ScriptFromHex("516902feed5169");
1443  d = ScriptFromHex("feed51");
1444  expect = s;
1445  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
1446  BOOST_CHECK(s == expect);
1447 
1448  s = ScriptFromHex("516902feed5169");
1449  d = ScriptFromHex("02feed51");
1450  expect = ScriptFromHex("516969");
1451  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1452  BOOST_CHECK(s == expect);
1453 
1454  s = CScript() << OP_0 << OP_0 << OP_1 << OP_1;
1455  d = CScript() << OP_0 << OP_1;
1456  expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass
1457  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1458  BOOST_CHECK(s == expect);
1459 
1460  s = CScript() << OP_0 << OP_0 << OP_1 << OP_0 << OP_1 << OP_1;
1461  d = CScript() << OP_0 << OP_1;
1462  expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass
1463  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 2);
1464  BOOST_CHECK(s == expect);
1465 
1466  // Another weird edge case:
1467  // End with invalid push (not enough data)...
1468  s = ScriptFromHex("0003feed");
1469  d = ScriptFromHex("03feed"); // ... can remove the invalid push
1470  expect = ScriptFromHex("00");
1471  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1472  BOOST_CHECK(s == expect);
1473 
1474  s = ScriptFromHex("0003feed");
1475  d = ScriptFromHex("00");
1476  expect = ScriptFromHex("03feed");
1477  BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
1478  BOOST_CHECK(s == expect);
1479 }
1480 
1481 BOOST_AUTO_TEST_CASE(script_HasValidOps)
1482 {
1483  // Exercise the HasValidOps functionality
1484  CScript script;
1485  script = ScriptFromHex("76a9141234567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac"); // Normal script
1486  BOOST_CHECK(script.HasValidOps());
1487  script = ScriptFromHex("76a914ff34567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac");
1488  BOOST_CHECK(script.HasValidOps());
1489  script = ScriptFromHex("ff88ac"); // Script with OP_INVALIDOPCODE explicit
1490  BOOST_CHECK(!script.HasValidOps());
1491  script = ScriptFromHex("88acc0"); // Script with undefined opcode
1492  BOOST_CHECK(!script.HasValidOps());
1493 }
1494 
1495 static CMutableTransaction TxFromHex(const std::string& str)
1496 {
1498  SpanReader{ParseHex(str)} >> TX_NO_WITNESS(tx);
1499  return tx;
1500 }
1501 
1502 static std::vector<CTxOut> TxOutsFromJSON(const UniValue& univalue)
1503 {
1504  assert(univalue.isArray());
1505  std::vector<CTxOut> prevouts;
1506  for (size_t i = 0; i < univalue.size(); ++i) {
1507  CTxOut txout;
1508  SpanReader{ParseHex(univalue[i].get_str())} >> txout;
1509  prevouts.push_back(std::move(txout));
1510  }
1511  return prevouts;
1512 }
1513 
1515 {
1516  assert(univalue.isArray());
1517  CScriptWitness scriptwitness;
1518  for (size_t i = 0; i < univalue.size(); ++i) {
1519  auto bytes = ParseHex(univalue[i].get_str());
1520  scriptwitness.stack.push_back(std::move(bytes));
1521  }
1522  return scriptwitness;
1523 }
1524 
1525 #if defined(HAVE_CONSENSUS_LIB)
1526 
1527 /* Test simple (successful) usage of bitcoinconsensus_verify_script */
1528 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_returns_true)
1529 {
1530  unsigned int libconsensus_flags = 0;
1531  int nIn = 0;
1532 
1533  CScript scriptPubKey;
1534  CScript scriptSig;
1535  CScriptWitness wit;
1536 
1537  scriptPubKey << OP_1;
1538  CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
1539  CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
1540 
1541  DataStream stream;
1542  stream << TX_WITH_WITNESS(spendTx);
1543 
1545  int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
1546  BOOST_CHECK_EQUAL(result, 1);
1548 }
1549 
1550 /* Test bitcoinconsensus_verify_script returns invalid tx index err*/
1551 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_index_err)
1552 {
1553  unsigned int libconsensus_flags = 0;
1554  int nIn = 3;
1555 
1556  CScript scriptPubKey;
1557  CScript scriptSig;
1558  CScriptWitness wit;
1559 
1560  scriptPubKey << OP_EQUAL;
1561  CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
1562  CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
1563 
1564  DataStream stream;
1565  stream << TX_WITH_WITNESS(spendTx);
1566 
1568  int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
1569  BOOST_CHECK_EQUAL(result, 0);
1571 }
1572 
1573 /* Test bitcoinconsensus_verify_script returns tx size mismatch err*/
1574 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_size)
1575 {
1576  unsigned int libconsensus_flags = 0;
1577  int nIn = 0;
1578 
1579  CScript scriptPubKey;
1580  CScript scriptSig;
1581  CScriptWitness wit;
1582 
1583  scriptPubKey << OP_EQUAL;
1584  CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
1585  CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
1586 
1587  DataStream stream;
1588  stream << TX_WITH_WITNESS(spendTx);
1589 
1591  int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size() * 2, nIn, libconsensus_flags, &err);
1592  BOOST_CHECK_EQUAL(result, 0);
1594 }
1595 
1596 /* Test bitcoinconsensus_verify_script returns invalid tx serialization error */
1597 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_serialization)
1598 {
1599  unsigned int libconsensus_flags = 0;
1600  int nIn = 0;
1601 
1602  CScript scriptPubKey;
1603  CScript scriptSig;
1604  CScriptWitness wit;
1605 
1606  scriptPubKey << OP_EQUAL;
1607  CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
1608  CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
1609 
1610  DataStream stream;
1611  stream << 0xffffffff;
1612 
1614  int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
1615  BOOST_CHECK_EQUAL(result, 0);
1617 }
1618 
1619 /* Test bitcoinconsensus_verify_script returns amount required error */
1620 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_amount_required_err)
1621 {
1622  unsigned int libconsensus_flags = bitcoinconsensus_SCRIPT_FLAGS_VERIFY_WITNESS;
1623  int nIn = 0;
1624 
1625  CScript scriptPubKey;
1626  CScript scriptSig;
1627  CScriptWitness wit;
1628 
1629  scriptPubKey << OP_EQUAL;
1630  CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
1631  CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
1632 
1633  DataStream stream;
1634  stream << TX_WITH_WITNESS(spendTx);
1635 
1637  int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
1638  BOOST_CHECK_EQUAL(result, 0);
1640 }
1641 
1642 /* Test bitcoinconsensus_verify_script returns invalid flags err */
1643 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_invalid_flags)
1644 {
1645  unsigned int libconsensus_flags = 1 << 3;
1646  int nIn = 0;
1647 
1648  CScript scriptPubKey;
1649  CScript scriptSig;
1650  CScriptWitness wit;
1651 
1652  scriptPubKey << OP_EQUAL;
1653  CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
1654  CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
1655 
1656  DataStream stream;
1657  stream << TX_WITH_WITNESS(spendTx);
1658 
1660  int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
1661  BOOST_CHECK_EQUAL(result, 0);
1663 }
1664 
1665 /* Test bitcoinconsensus_verify_script returns spent outputs required err */
1666 BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_spent_outputs_required_err)
1667 {
1668  unsigned int libconsensus_flags{bitcoinconsensus_SCRIPT_FLAGS_VERIFY_TAPROOT};
1669  const int nIn{0};
1670 
1671  CScript scriptPubKey;
1672  CScript scriptSig;
1673  CScriptWitness wit;
1674 
1675  scriptPubKey << OP_EQUAL;
1676  CTransaction creditTx{BuildCreditingTransaction(scriptPubKey, 1)};
1677  CTransaction spendTx{BuildSpendingTransaction(scriptSig, wit, creditTx)};
1678 
1679  DataStream stream;
1680  stream << TX_WITH_WITNESS(spendTx);
1681 
1683  int result{bitcoinconsensus_verify_script_with_spent_outputs(scriptPubKey.data(), scriptPubKey.size(), creditTx.vout[0].nValue, UCharCast(stream.data()), stream.size(), nullptr, 0, nIn, libconsensus_flags, &err)};
1684  BOOST_CHECK_EQUAL(result, 0);
1686 
1687  result = bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), creditTx.vout[0].nValue, UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
1688  BOOST_CHECK_EQUAL(result, 0);
1690 
1691  result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), UCharCast(stream.data()), stream.size(), nIn, libconsensus_flags, &err);
1692  BOOST_CHECK_EQUAL(result, 0);
1694 }
1695 
1696 #endif // defined(HAVE_CONSENSUS_LIB)
1697 
1698 static std::vector<unsigned int> AllConsensusFlags()
1699 {
1700  std::vector<unsigned int> ret;
1701 
1702  for (unsigned int i = 0; i < 128; ++i) {
1703  unsigned int flag = 0;
1704  if (i & 1) flag |= SCRIPT_VERIFY_P2SH;
1705  if (i & 2) flag |= SCRIPT_VERIFY_DERSIG;
1706  if (i & 4) flag |= SCRIPT_VERIFY_NULLDUMMY;
1707  if (i & 8) flag |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1708  if (i & 16) flag |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1709  if (i & 32) flag |= SCRIPT_VERIFY_WITNESS;
1710  if (i & 64) flag |= SCRIPT_VERIFY_TAPROOT;
1711 
1712  // SCRIPT_VERIFY_WITNESS requires SCRIPT_VERIFY_P2SH
1713  if (flag & SCRIPT_VERIFY_WITNESS && !(flag & SCRIPT_VERIFY_P2SH)) continue;
1714  // SCRIPT_VERIFY_TAPROOT requires SCRIPT_VERIFY_WITNESS
1715  if (flag & SCRIPT_VERIFY_TAPROOT && !(flag & SCRIPT_VERIFY_WITNESS)) continue;
1716 
1717  ret.push_back(flag);
1718  }
1719 
1720  return ret;
1721 }
1722 
1724 static const std::vector<unsigned int> ALL_CONSENSUS_FLAGS = AllConsensusFlags();
1725 
1726 static void AssetTest(const UniValue& test)
1727 {
1728  BOOST_CHECK(test.isObject());
1729 
1730  CMutableTransaction mtx = TxFromHex(test["tx"].get_str());
1731  const std::vector<CTxOut> prevouts = TxOutsFromJSON(test["prevouts"]);
1732  BOOST_CHECK(prevouts.size() == mtx.vin.size());
1733  size_t idx = test["index"].getInt<int64_t>();
1734  uint32_t test_flags{ParseScriptFlags(test["flags"].get_str())};
1735  bool fin = test.exists("final") && test["final"].get_bool();
1736 
1737  if (test.exists("success")) {
1738  mtx.vin[idx].scriptSig = ScriptFromHex(test["success"]["scriptSig"].get_str());
1739  mtx.vin[idx].scriptWitness = ScriptWitnessFromJSON(test["success"]["witness"]);
1740  CTransaction tx(mtx);
1742  txdata.Init(tx, std::vector<CTxOut>(prevouts));
1743  CachingTransactionSignatureChecker txcheck(&tx, idx, prevouts[idx].nValue, true, txdata);
1744 
1745 #if defined(HAVE_CONSENSUS_LIB)
1746  DataStream stream;
1747  stream << TX_WITH_WITNESS(tx);
1748  std::vector<UTXO> utxos;
1749  utxos.resize(prevouts.size());
1750  for (size_t i = 0; i < prevouts.size(); i++) {
1751  utxos[i].scriptPubKey = prevouts[i].scriptPubKey.data();
1752  utxos[i].scriptPubKeySize = prevouts[i].scriptPubKey.size();
1753  utxos[i].value = prevouts[i].nValue;
1754  }
1755 #endif
1756 
1757  for (const auto flags : ALL_CONSENSUS_FLAGS) {
1758  // "final": true tests are valid for all flags. Others are only valid with flags that are
1759  // a subset of test_flags.
1760  if (fin || ((flags & test_flags) == flags)) {
1761  bool ret = VerifyScript(tx.vin[idx].scriptSig, prevouts[idx].scriptPubKey, &tx.vin[idx].scriptWitness, flags, txcheck, nullptr);
1762  BOOST_CHECK(ret);
1763 #if defined(HAVE_CONSENSUS_LIB)
1764  int lib_ret = bitcoinconsensus_verify_script_with_spent_outputs(prevouts[idx].scriptPubKey.data(), prevouts[idx].scriptPubKey.size(), prevouts[idx].nValue, UCharCast(stream.data()), stream.size(), utxos.data(), utxos.size(), idx, flags, nullptr);
1765  BOOST_CHECK(lib_ret == 1);
1766 #endif
1767  }
1768  }
1769  }
1770 
1771  if (test.exists("failure")) {
1772  mtx.vin[idx].scriptSig = ScriptFromHex(test["failure"]["scriptSig"].get_str());
1773  mtx.vin[idx].scriptWitness = ScriptWitnessFromJSON(test["failure"]["witness"]);
1774  CTransaction tx(mtx);
1776  txdata.Init(tx, std::vector<CTxOut>(prevouts));
1777  CachingTransactionSignatureChecker txcheck(&tx, idx, prevouts[idx].nValue, true, txdata);
1778 
1779 #if defined(HAVE_CONSENSUS_LIB)
1780  DataStream stream;
1781  stream << TX_WITH_WITNESS(tx);
1782  std::vector<UTXO> utxos;
1783  utxos.resize(prevouts.size());
1784  for (size_t i = 0; i < prevouts.size(); i++) {
1785  utxos[i].scriptPubKey = prevouts[i].scriptPubKey.data();
1786  utxos[i].scriptPubKeySize = prevouts[i].scriptPubKey.size();
1787  utxos[i].value = prevouts[i].nValue;
1788  }
1789 #endif
1790 
1791  for (const auto flags : ALL_CONSENSUS_FLAGS) {
1792  // If a test is supposed to fail with test_flags, it should also fail with any superset thereof.
1793  if ((flags & test_flags) == test_flags) {
1794  bool ret = VerifyScript(tx.vin[idx].scriptSig, prevouts[idx].scriptPubKey, &tx.vin[idx].scriptWitness, flags, txcheck, nullptr);
1795  BOOST_CHECK(!ret);
1796 #if defined(HAVE_CONSENSUS_LIB)
1797  int lib_ret = bitcoinconsensus_verify_script_with_spent_outputs(prevouts[idx].scriptPubKey.data(), prevouts[idx].scriptPubKey.size(), prevouts[idx].nValue, UCharCast(stream.data()), stream.size(), utxos.data(), utxos.size(), idx, flags, nullptr);
1798  BOOST_CHECK(lib_ret == 0);
1799 #endif
1800  }
1801  }
1802  }
1803 }
1804 
1805 BOOST_AUTO_TEST_CASE(script_assets_test)
1806 {
1807  // See src/test/fuzz/script_assets_test_minimizer.cpp for information on how to generate
1808  // the script_assets_test.json file used by this test.
1809 
1810  const char* dir = std::getenv("DIR_UNIT_TEST_DATA");
1811  BOOST_WARN_MESSAGE(dir != nullptr, "Variable DIR_UNIT_TEST_DATA unset, skipping script_assets_test");
1812  if (dir == nullptr) return;
1813  auto path = fs::path(dir) / "script_assets_test.json";
1814  bool exists = fs::exists(path);
1815  BOOST_WARN_MESSAGE(exists, "File $DIR_UNIT_TEST_DATA/script_assets_test.json not found, skipping script_assets_test");
1816  if (!exists) return;
1817  std::ifstream file{path};
1818  BOOST_CHECK(file.is_open());
1819  file.seekg(0, std::ios::end);
1820  size_t length = file.tellg();
1821  file.seekg(0, std::ios::beg);
1822  std::string data(length, '\0');
1823  file.read(data.data(), data.size());
1824  UniValue tests = read_json(data);
1825  BOOST_CHECK(tests.isArray());
1826  BOOST_CHECK(tests.size() > 0);
1827 
1828  for (size_t i = 0; i < tests.size(); i++) {
1829  AssetTest(tests[i]);
1830  }
1831  file.close();
1832 }
1833 
1834 BOOST_AUTO_TEST_CASE(bip341_keypath_test_vectors)
1835 {
1836  UniValue tests;
1838 
1839  const auto& vectors = tests["keyPathSpending"];
1840 
1841  for (const auto& vec : vectors.getValues()) {
1842  auto txhex = ParseHex(vec["given"]["rawUnsignedTx"].get_str());
1844  SpanReader{txhex} >> TX_WITH_WITNESS(tx);
1845  std::vector<CTxOut> utxos;
1846  for (const auto& utxo_spent : vec["given"]["utxosSpent"].getValues()) {
1847  auto script_bytes = ParseHex(utxo_spent["scriptPubKey"].get_str());
1848  CScript script{script_bytes.begin(), script_bytes.end()};
1849  CAmount amount{utxo_spent["amountSats"].getInt<int>()};
1850  utxos.emplace_back(amount, script);
1851  }
1852 
1854  txdata.Init(tx, std::vector<CTxOut>{utxos}, true);
1855 
1857  BOOST_CHECK_EQUAL(HexStr(txdata.m_spent_amounts_single_hash), vec["intermediary"]["hashAmounts"].get_str());
1858  BOOST_CHECK_EQUAL(HexStr(txdata.m_outputs_single_hash), vec["intermediary"]["hashOutputs"].get_str());
1859  BOOST_CHECK_EQUAL(HexStr(txdata.m_prevouts_single_hash), vec["intermediary"]["hashPrevouts"].get_str());
1860  BOOST_CHECK_EQUAL(HexStr(txdata.m_spent_scripts_single_hash), vec["intermediary"]["hashScriptPubkeys"].get_str());
1861  BOOST_CHECK_EQUAL(HexStr(txdata.m_sequences_single_hash), vec["intermediary"]["hashSequences"].get_str());
1862 
1863  for (const auto& input : vec["inputSpending"].getValues()) {
1864  int txinpos = input["given"]["txinIndex"].getInt<int>();
1865  int hashtype = input["given"]["hashType"].getInt<int>();
1866 
1867  // Load key.
1868  auto privkey = ParseHex(input["given"]["internalPrivkey"].get_str());
1869  CKey key;
1870  key.Set(privkey.begin(), privkey.end(), true);
1871 
1872  // Load Merkle root.
1873  uint256 merkle_root;
1874  if (!input["given"]["merkleRoot"].isNull()) {
1875  merkle_root = uint256{ParseHex(input["given"]["merkleRoot"].get_str())};
1876  }
1877 
1878  // Compute and verify (internal) public key.
1879  XOnlyPubKey pubkey{key.GetPubKey()};
1880  BOOST_CHECK_EQUAL(HexStr(pubkey), input["intermediary"]["internalPubkey"].get_str());
1881 
1882  // Sign and verify signature.
1883  FlatSigningProvider provider;
1884  provider.keys[key.GetPubKey().GetID()] = key;
1885  MutableTransactionSignatureCreator creator(tx, txinpos, utxos[txinpos].nValue, &txdata, hashtype);
1886  std::vector<unsigned char> signature;
1887  BOOST_CHECK(creator.CreateSchnorrSig(provider, signature, pubkey, nullptr, &merkle_root, SigVersion::TAPROOT));
1888  BOOST_CHECK_EQUAL(HexStr(signature), input["expected"]["witness"][0].get_str());
1889 
1890  // We can't observe the tweak used inside the signing logic, so verify by recomputing it.
1891  BOOST_CHECK_EQUAL(HexStr(pubkey.ComputeTapTweakHash(merkle_root.IsNull() ? nullptr : &merkle_root)), input["intermediary"]["tweak"].get_str());
1892 
1893  // We can't observe the sighash used inside the signing logic, so verify by recomputing it.
1894  ScriptExecutionData sed;
1895  sed.m_annex_init = true;
1896  sed.m_annex_present = false;
1897  uint256 sighash;
1899  BOOST_CHECK_EQUAL(HexStr(sighash), input["intermediary"]["sigHash"].get_str());
1900 
1901  // To verify the sigmsg, hash the expected sigmsg, and compare it with the (expected) sighash.
1902  BOOST_CHECK_EQUAL(HexStr((HashWriter{HASHER_TAPSIGHASH} << Span{ParseHex(input["intermediary"]["sigMsg"].get_str())}).GetSHA256()), input["intermediary"]["sigHash"].get_str());
1903  }
1904 
1905  }
1906 }
1907 
1908 BOOST_AUTO_TEST_CASE(compute_tapbranch)
1909 {
1910  uint256 hash1 = uint256S("8ad69ec7cf41c2a4001fd1f738bf1e505ce2277acdcaa63fe4765192497f47a7");
1911  uint256 hash2 = uint256S("f224a923cd0021ab202ab139cc56802ddb92dcfc172b9212261a539df79a112a");
1912  uint256 result = uint256S("a64c5b7b943315f9b805d7a7296bedfcfd08919270a1f7a1466e98f8693d8cd9");
1913  BOOST_CHECK_EQUAL(ComputeTapbranchHash(hash1, hash2), result);
1914 }
1915 
1916 BOOST_AUTO_TEST_CASE(compute_tapleaf)
1917 {
1918  const uint8_t script[6] = {'f','o','o','b','a','r'};
1919  uint256 tlc0 = uint256S("edbc10c272a1215dcdcc11d605b9027b5ad6ed97cd45521203f136767b5b9c06");
1920  uint256 tlc2 = uint256S("8b5c4f90ae6bf76e259dbef5d8a59df06359c391b59263741b25eca76451b27a");
1921 
1922  BOOST_CHECK_EQUAL(ComputeTapleafHash(0xc0, Span(script)), tlc0);
1923  BOOST_CHECK_EQUAL(ComputeTapleafHash(0xc2, Span(script)), tlc2);
1924 }
1925 
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
CAmount nValue
Definition: transaction.h:152
CMutableTransaction BuildCreditingTransaction(const CScript &scriptPubKey, int nValue)
static const std::string sighash
Definition: sighash.json.h:3
Witness v0 (P2WPKH and P2WSH); see BIP 141.
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:702
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition: solver.cpp:214
static const std::string bip341_wallet_vectors
bool isObject() const
Definition: univalue.h:85
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).
Definition: sign.cpp:694
int ret
Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, key path spending; see BIP 341...
std::string FormatScript(const CScript &script)
Definition: core_write.cpp:39
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)
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:65
assert(!tx.IsCoinBase())
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:26
enum ScriptError_t ScriptError
CScript scriptPubKey
Definition: transaction.h:153
bool get_bool() const
Definition: script.h:124
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:188
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
CScript scriptSig
The scriptSig of an input. Contains complete signatures or the traditional partial signatures format...
Definition: sign.h:71
static const std::string script_tests
std::vector< CTxIn > vin
Definition: transaction.h:379
std::map< CKeyID, CKey > keys
bool read(std::string_view raw)
virtual bool AddCScript(const CScript &redeemScript)
#define expect(bit)
static CMutableTransaction TxFromHex(const std::string &str)
std::vector< std::vector< unsigned char > > stack
Definition: script.h:569
ScriptError_t err
CMutableTransaction BuildSpendingTransaction(const CScript &scriptSig, const CScriptWitness &scriptWitness, const CTransaction &txCredit)
const std::string & get_str() const
const UniValue & get_array() const
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
bool HasValidOps() const
Check if the script contains valid OP_CODES.
Definition: script.cpp:276
unsigned int ParseScriptFlags(std::string strFlags)
Definition: script.h:75
A signature creator for transactions.
Definition: sign.h:39
Int getInt() const
Definition: univalue.h:137
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:35
int bitcoinconsensus_verify_script(const unsigned char *scriptPubKey, unsigned int scriptPubKeyLen, const unsigned char *txTo, unsigned int txToLen, unsigned int nIn, unsigned int flags, bitcoinconsensus_error *err)
Returns 1 if the input nIn of the serialized transaction pointed to by txTo correctly spends the scri...
const HashWriter HASHER_TAPSIGHASH
Hasher with tag "TapSighash" pre-fed to it.
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:164
std::pair< opcodetype, std::vector< unsigned char > > Opcode
Definition: miniscript.h:184
const unsigned char * begin() const
Definition: pubkey.h:114
value_type * data()
Definition: streams.h:188
const std::vector< CTxIn > vin
Definition: transaction.h:306
value_type * data()
Definition: prevector.h:532
Basic testing setup.
Definition: setup_common.h:49
constexpr unsigned char * begin()
Definition: uint256.h:68
static const unsigned int gFlags
Minimal stream for reading from an existing byte array by Span.
Definition: streams.h:100
Definition: script.h:82
CKey GenerateRandomKey(bool compressed) noexcept
Definition: key.cpp:372
int bitcoinconsensus_verify_script_with_spent_outputs(const unsigned char *scriptPubKey, unsigned int scriptPubKeyLen, int64_t amount, const unsigned char *txTo, unsigned int txToLen, const UTXO *spentOutputs, unsigned int spentOutputsLen, unsigned int nIn, unsigned int flags, bitcoinconsensus_error *err)
SignatureData CombineSignatures(const CTxOut &txout, const CMutableTransaction &tx, const SignatureData &scriptSig1, const SignatureData &scriptSig2)
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static void NegateSignatureS(std::vector< unsigned char > &vchSig)
static CScript ScriptFromHex(const std::string &str)
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:214
bool m_annex_init
Whether m_annex_present and (when needed) m_annex_hash are initialized.
Definition: interpreter.h:211
iterator end()
Definition: prevector.h:306
static CScriptWitness ScriptWitnessFromJSON(const UniValue &univalue)
void push_back(const T &value)
Definition: prevector.h:443
enum bitcoinconsensus_error_t bitcoinconsensus_error
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.
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:98
static CAmount AmountFromValue(const UniValue &value)
Definition: bitcoin-tx.cpp:555
UniValue read_json(const std::string &jsondata)
Definition: json.cpp:12
const unsigned char * end() const
Definition: pubkey.h:115
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
bool IsPushOnly(const_iterator pc) const
Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical).
Definition: script.cpp:242
static ScriptError_t ParseScriptError(const std::string &name)
const char * name
Definition: rest.cpp:49
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:146
bool exists(const std::string &key) const
Definition: univalue.h:76
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.
uint256 uint256S(const char *str)
Definition: uint256.h:119
An encapsulated public key.
Definition: pubkey.h:33
Fillable signing provider that keeps keys in an address->secret map.
std::string ScriptErrorString(const ScriptError serror)
ScriptError_t
Definition: script_error.h:11
std::pair< CPubKey, std::vector< unsigned char > > SigPair
Definition: sign.h:63
opcodetype
Script opcodes.
Definition: script.h:72
WitnessV1Taproot GetOutput()
Compute scriptPubKey (after Finalize()).
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
Just act as if the signature was invalid.
An output of a transaction.
Definition: transaction.h:149
GenericTransactionSignatureChecker< CMutableTransaction > MutableTransactionSignatureChecker
Definition: interpreter.h:307
void MergeSignatureData(SignatureData sigdata)
Definition: sign.cpp:678
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:69
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:163
std::vector< CTxOut > vout
Definition: transaction.h:380
constexpr bool IsNull() const
Definition: uint256.h:42
static void AssetTest(const UniValue &test)
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:99
A type to represent integers in the type system.
Definition: lintrans.h:13
uint256 ComputeTapleafHash(uint8_t leaf_version, Span< const unsigned char > script)
Compute the BIP341 tapleaf hash from leaf version & script.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
TaprootSpendData GetSpendData() const
Compute spending data (after Finalize()).
Utility class to construct Taproot outputs from internal key and script tree.
size_type size() const
Definition: streams.h:181
int flags
Definition: bitcoin-tx.cpp:530
static ScriptErrorDesc script_errors[]
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:66
BOOST_AUTO_TEST_CASE(script_build)
256-bit opaque blob.
Definition: uint256.h:106
WitnessMode
int bitcoinconsensus_verify_script_with_amount(const unsigned char *scriptPubKey, unsigned int scriptPubKeyLen, int64_t amount, const unsigned char *txTo, unsigned int txToLen, unsigned int nIn, unsigned int flags, bitcoinconsensus_error *err)
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition: sign.cpp:607
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:413
void DoTest(const CScript &scriptPubKey, const CScript &scriptSig, const CScriptWitness &scriptWitness, uint32_t flags, const std::string &message, int scriptError, CAmount nValue=0)
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
Definition: sign.cpp:109
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:62
bool empty() const
Definition: prevector.h:300
TaprootBuilder & Add(int depth, Span< const unsigned char > script, int leaf_version, bool track=true)
Add a new script at a certain depth in the tree.
Definition: script.h:85
static std::vector< CTxOut > TxOutsFromJSON(const UniValue &univalue)
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:27
const char * name
uint256 SignatureHash(const CScript &scriptCode, const T &txTo, unsigned int nIn, int nHashType, const CAmount &amount, SigVersion sigversion, const PrecomputedTransactionData *cache)
UniValue ValueFromAmount(const CAmount amount)
Definition: core_write.cpp:26
uint256 ComputeTapbranchHash(Span< const unsigned char > a, Span< const unsigned char > b)
Compute the BIP341 tapbranch hash from two branches.
static std::vector< unsigned int > AllConsensusFlags()
160-bit opaque blob.
Definition: uint256.h:95
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:499
iterator begin()
Definition: prevector.h:304
std::string FormatScriptFlags(unsigned int flags)
static const std::vector< unsigned int > ALL_CONSENSUS_FLAGS
Precomputed list of all valid combinations of consensus-relevant script validation flags...
static uint64_t InsecureRandBits(int bits)
Definition: random.h:55
A reference to a CScript: the Hash160 of its serialization.
Definition: script.h:582
A mutable version of CTransaction.
Definition: transaction.h:377
size_type size() const
Definition: prevector.h:296
unsigned char * UCharCast(char *c)
Definition: span.h:288
Definition: script.h:84
static std::string FormatScriptError(ScriptError_t err)
size_t size() const
Definition: univalue.h:70
const unsigned char * data() const
Definition: pubkey.h:113
An encapsulated private key.
Definition: key.h:32
A Span is an object that can refer to a contiguous sequence of objects.
Definition: solver.h:20
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:295
A hasher class for Bitcoin&#39;s 160-bit hash (SHA-256 + RIPEMD-160).
Definition: hash.h:49
static bool exists(const path &p)
Definition: fs.h:89
A hasher class for SHA-256.
Definition: sha256.h:13
CScript ParseScript(const std::string &s)
Definition: core_read.cpp:61
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror)
int FindAndDelete(CScript &script, const CScript &b)
Span(T *, EndOrSize) -> Span< T >
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:32
CHash160 & Write(Span< const unsigned char > input)
Definition: hash.h:62
Definition: script.h:157
bool isArray() const
Definition: univalue.h:84
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:77
Definition: script.h:86
static constexpr TransactionSerParams TX_NO_WITNESS
Definition: transaction.h:196
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:195
#define BOOST_CHECK(expr)
Definition: object.cpp:17
static CScript sign_multisig(const CScript &scriptPubKey, const std::vector< CKey > &keys, const CTransaction &transaction)
SigVersion
Definition: interpreter.h:190
TaprootSpendData tr_spenddata
Taproot spending data.
Definition: sign.h:75