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