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