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