Bitcoin Core  0.20.99
P2P Digital Currency
interpreter.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <script/interpreter.h>
7 
8 #include <crypto/ripemd160.h>
9 #include <crypto/sha1.h>
10 #include <crypto/sha256.h>
11 #include <pubkey.h>
12 #include <script/script.h>
13 #include <uint256.h>
14 
15 typedef std::vector<unsigned char> valtype;
16 
17 namespace {
18 
19 inline bool set_success(ScriptError* ret)
20 {
21  if (ret)
22  *ret = SCRIPT_ERR_OK;
23  return true;
24 }
25 
26 inline bool set_error(ScriptError* ret, const ScriptError serror)
27 {
28  if (ret)
29  *ret = serror;
30  return false;
31 }
32 
33 } // namespace
34 
35 bool CastToBool(const valtype& vch)
36 {
37  for (unsigned int i = 0; i < vch.size(); i++)
38  {
39  if (vch[i] != 0)
40  {
41  // Can be negative zero
42  if (i == vch.size()-1 && vch[i] == 0x80)
43  return false;
44  return true;
45  }
46  }
47  return false;
48 }
49 
54 #define stacktop(i) (stack.at(stack.size()+(i)))
55 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
56 static inline void popstack(std::vector<valtype>& stack)
57 {
58  if (stack.empty())
59  throw std::runtime_error("popstack(): stack empty");
60  stack.pop_back();
61 }
62 
63 bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
64  if (vchPubKey.size() < CPubKey::COMPRESSED_SIZE) {
65  // Non-canonical public key: too short
66  return false;
67  }
68  if (vchPubKey[0] == 0x04) {
69  if (vchPubKey.size() != CPubKey::SIZE) {
70  // Non-canonical public key: invalid length for uncompressed key
71  return false;
72  }
73  } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
74  if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
75  // Non-canonical public key: invalid length for compressed key
76  return false;
77  }
78  } else {
79  // Non-canonical public key: neither compressed nor uncompressed
80  return false;
81  }
82  return true;
83 }
84 
85 bool static IsCompressedPubKey(const valtype &vchPubKey) {
86  if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
87  // Non-canonical public key: invalid length for compressed key
88  return false;
89  }
90  if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
91  // Non-canonical public key: invalid prefix for compressed key
92  return false;
93  }
94  return true;
95 }
96 
107 bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
108  // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
109  // * total-length: 1-byte length descriptor of everything that follows,
110  // excluding the sighash byte.
111  // * R-length: 1-byte length descriptor of the R value that follows.
112  // * R: arbitrary-length big-endian encoded R value. It must use the shortest
113  // possible encoding for a positive integer (which means no null bytes at
114  // the start, except a single one when the next byte has its highest bit set).
115  // * S-length: 1-byte length descriptor of the S value that follows.
116  // * S: arbitrary-length big-endian encoded S value. The same rules apply.
117  // * sighash: 1-byte value indicating what data is hashed (not part of the DER
118  // signature)
119 
120  // Minimum and maximum size constraints.
121  if (sig.size() < 9) return false;
122  if (sig.size() > 73) return false;
123 
124  // A signature is of type 0x30 (compound).
125  if (sig[0] != 0x30) return false;
126 
127  // Make sure the length covers the entire signature.
128  if (sig[1] != sig.size() - 3) return false;
129 
130  // Extract the length of the R element.
131  unsigned int lenR = sig[3];
132 
133  // Make sure the length of the S element is still inside the signature.
134  if (5 + lenR >= sig.size()) return false;
135 
136  // Extract the length of the S element.
137  unsigned int lenS = sig[5 + lenR];
138 
139  // Verify that the length of the signature matches the sum of the length
140  // of the elements.
141  if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
142 
143  // Check whether the R element is an integer.
144  if (sig[2] != 0x02) return false;
145 
146  // Zero-length integers are not allowed for R.
147  if (lenR == 0) return false;
148 
149  // Negative numbers are not allowed for R.
150  if (sig[4] & 0x80) return false;
151 
152  // Null bytes at the start of R are not allowed, unless R would
153  // otherwise be interpreted as a negative number.
154  if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
155 
156  // Check whether the S element is an integer.
157  if (sig[lenR + 4] != 0x02) return false;
158 
159  // Zero-length integers are not allowed for S.
160  if (lenS == 0) return false;
161 
162  // Negative numbers are not allowed for S.
163  if (sig[lenR + 6] & 0x80) return false;
164 
165  // Null bytes at the start of S are not allowed, unless S would otherwise be
166  // interpreted as a negative number.
167  if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
168 
169  return true;
170 }
171 
172 bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
173  if (!IsValidSignatureEncoding(vchSig)) {
174  return set_error(serror, SCRIPT_ERR_SIG_DER);
175  }
176  // https://bitcoin.stackexchange.com/a/12556:
177  // Also note that inside transaction signatures, an extra hashtype byte
178  // follows the actual signature data.
179  std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
180  // If the S value is above the order of the curve divided by two, its
181  // complement modulo the order could have been used instead, which is
182  // one byte shorter when encoded correctly.
183  if (!CPubKey::CheckLowS(vchSigCopy)) {
184  return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
185  }
186  return true;
187 }
188 
189 bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
190  if (vchSig.size() == 0) {
191  return false;
192  }
193  unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
194  if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
195  return false;
196 
197  return true;
198 }
199 
200 bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
201  // Empty signature. Not strictly DER encoded, but allowed to provide a
202  // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
203  if (vchSig.size() == 0) {
204  return true;
205  }
207  return set_error(serror, SCRIPT_ERR_SIG_DER);
208  } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
209  // serror is set
210  return false;
211  } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
212  return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
213  }
214  return true;
215 }
216 
217 bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
218  if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
219  return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
220  }
221  // Only compressed keys are accepted in segwit
222  if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SigVersion::WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
223  return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
224  }
225  return true;
226 }
227 
228 bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
229  // Excludes OP_1NEGATE, OP_1-16 since they are by definition minimal
230  assert(0 <= opcode && opcode <= OP_PUSHDATA4);
231  if (data.size() == 0) {
232  // Should have used OP_0.
233  return opcode == OP_0;
234  } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
235  // Should have used OP_1 .. OP_16.
236  return false;
237  } else if (data.size() == 1 && data[0] == 0x81) {
238  // Should have used OP_1NEGATE.
239  return false;
240  } else if (data.size() <= 75) {
241  // Must have used a direct push (opcode indicating number of bytes pushed + those bytes).
242  return opcode == data.size();
243  } else if (data.size() <= 255) {
244  // Must have used OP_PUSHDATA.
245  return opcode == OP_PUSHDATA1;
246  } else if (data.size() <= 65535) {
247  // Must have used OP_PUSHDATA2.
248  return opcode == OP_PUSHDATA2;
249  }
250  return true;
251 }
252 
253 int FindAndDelete(CScript& script, const CScript& b)
254 {
255  int nFound = 0;
256  if (b.empty())
257  return nFound;
258  CScript result;
259  CScript::const_iterator pc = script.begin(), pc2 = script.begin(), end = script.end();
260  opcodetype opcode;
261  do
262  {
263  result.insert(result.end(), pc2, pc);
264  while (static_cast<size_t>(end - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
265  {
266  pc = pc + b.size();
267  ++nFound;
268  }
269  pc2 = pc;
270  }
271  while (script.GetOp(pc, opcode));
272 
273  if (nFound > 0) {
274  result.insert(result.end(), pc2, end);
275  script = std::move(result);
276  }
277 
278  return nFound;
279 }
280 
281 namespace {
297 class ConditionStack {
298 private:
300  static constexpr uint32_t NO_FALSE = std::numeric_limits<uint32_t>::max();
301 
303  uint32_t m_stack_size = 0;
305  uint32_t m_first_false_pos = NO_FALSE;
306 
307 public:
308  bool empty() { return m_stack_size == 0; }
309  bool all_true() { return m_first_false_pos == NO_FALSE; }
310  void push_back(bool f)
311  {
312  if (m_first_false_pos == NO_FALSE && !f) {
313  // The stack consists of all true values, and a false is added.
314  // The first false value will appear at the current size.
315  m_first_false_pos = m_stack_size;
316  }
317  ++m_stack_size;
318  }
319  void pop_back()
320  {
321  assert(m_stack_size > 0);
322  --m_stack_size;
323  if (m_first_false_pos == m_stack_size) {
324  // When popping off the first false value, everything becomes true.
325  m_first_false_pos = NO_FALSE;
326  }
327  }
328  void toggle_top()
329  {
330  assert(m_stack_size > 0);
331  if (m_first_false_pos == NO_FALSE) {
332  // The current stack is all true values; the first false will be the top.
333  m_first_false_pos = m_stack_size - 1;
334  } else if (m_first_false_pos == m_stack_size - 1) {
335  // The top is the first false value; toggling it will make everything true.
336  m_first_false_pos = NO_FALSE;
337  } else {
338  // There is a false value, but not on top. No action is needed as toggling
339  // anything but the first false value is unobservable.
340  }
341  }
342 };
343 }
344 
345 static bool EvalChecksigPreTapscript(const valtype& vchSig, const valtype& vchPubKey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& fSuccess)
346 {
347  assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
348 
349  // Subset of script starting at the most recent codeseparator
350  CScript scriptCode(pbegincodehash, pend);
351 
352  // Drop the signature in pre-segwit scripts but not segwit scripts
353  if (sigversion == SigVersion::BASE) {
354  int found = FindAndDelete(scriptCode, CScript() << vchSig);
355  if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
356  return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
357  }
358 
359  if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
360  //serror is set
361  return false;
362  }
363  fSuccess = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
364 
365  if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
366  return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
367 
368  return true;
369 }
370 
371 static bool EvalChecksigTapscript(const valtype& sig, const valtype& pubkey, ScriptExecutionData& execdata, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& success)
372 {
373  assert(sigversion == SigVersion::TAPSCRIPT);
374 
375  /*
376  * The following validation sequence is consensus critical. Please note how --
377  * upgradable public key versions precede other rules;
378  * the script execution fails when using empty signature with invalid public key;
379  * the script execution fails when using non-empty invalid signature.
380  */
381  success = !sig.empty();
382  if (success) {
383  // Implement the sigops/witnesssize ratio test.
384  // Passing with an upgradable public key version is also counted.
385  assert(execdata.m_validation_weight_left_init);
387  if (execdata.m_validation_weight_left < 0) {
388  return set_error(serror, SCRIPT_ERR_TAPSCRIPT_VALIDATION_WEIGHT);
389  }
390  }
391  if (pubkey.size() == 0) {
392  return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
393  } else if (pubkey.size() == 32) {
394  if (success && !checker.CheckSchnorrSignature(sig, pubkey, sigversion, execdata, serror)) {
395  return false; // serror is set
396  }
397  } else {
398  /*
399  * New public key version softforks should be defined before this `else` block.
400  * Generally, the new code should not do anything but failing the script execution. To avoid
401  * consensus bugs, it should not modify any existing values (including `success`).
402  */
404  return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_PUBKEYTYPE);
405  }
406  }
407 
408  return true;
409 }
410 
416 static bool EvalChecksig(const valtype& sig, const valtype& pubkey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, ScriptExecutionData& execdata, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& success)
417 {
418  switch (sigversion) {
419  case SigVersion::BASE:
421  return EvalChecksigPreTapscript(sig, pubkey, pbegincodehash, pend, flags, checker, sigversion, serror, success);
423  return EvalChecksigTapscript(sig, pubkey, execdata, flags, checker, sigversion, serror, success);
424  case SigVersion::TAPROOT:
425  // Key path spending in Taproot has no script, so this is unreachable.
426  break;
427  }
428  assert(false);
429 }
430 
431 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror)
432 {
433  static const CScriptNum bnZero(0);
434  static const CScriptNum bnOne(1);
435  // static const CScriptNum bnFalse(0);
436  // static const CScriptNum bnTrue(1);
437  static const valtype vchFalse(0);
438  // static const valtype vchZero(0);
439  static const valtype vchTrue(1, 1);
440 
441  // sigversion cannot be TAPROOT here, as it admits no script execution.
442  assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0 || sigversion == SigVersion::TAPSCRIPT);
443 
444  CScript::const_iterator pc = script.begin();
445  CScript::const_iterator pend = script.end();
446  CScript::const_iterator pbegincodehash = script.begin();
447  opcodetype opcode;
448  valtype vchPushValue;
449  ConditionStack vfExec;
450  std::vector<valtype> altstack;
451  set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
452  if ((sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) && script.size() > MAX_SCRIPT_SIZE) {
453  return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
454  }
455  int nOpCount = 0;
456  bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
457  uint32_t opcode_pos = 0;
458  execdata.m_codeseparator_pos = 0xFFFFFFFFUL;
459  execdata.m_codeseparator_pos_init = true;
460 
461  try
462  {
463  for (; pc < pend; ++opcode_pos) {
464  bool fExec = vfExec.all_true();
465 
466  //
467  // Read instruction
468  //
469  if (!script.GetOp(pc, opcode, vchPushValue))
470  return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
471  if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
472  return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
473 
474  if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) {
475  // Note how OP_RESERVED does not count towards the opcode limit.
476  if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT) {
477  return set_error(serror, SCRIPT_ERR_OP_COUNT);
478  }
479  }
480 
481  if (opcode == OP_CAT ||
482  opcode == OP_SUBSTR ||
483  opcode == OP_LEFT ||
484  opcode == OP_RIGHT ||
485  opcode == OP_INVERT ||
486  opcode == OP_AND ||
487  opcode == OP_OR ||
488  opcode == OP_XOR ||
489  opcode == OP_2MUL ||
490  opcode == OP_2DIV ||
491  opcode == OP_MUL ||
492  opcode == OP_DIV ||
493  opcode == OP_MOD ||
494  opcode == OP_LSHIFT ||
495  opcode == OP_RSHIFT)
496  return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes (CVE-2010-5137).
497 
498  // With SCRIPT_VERIFY_CONST_SCRIPTCODE, OP_CODESEPARATOR in non-segwit script is rejected even in an unexecuted branch
499  if (opcode == OP_CODESEPARATOR && sigversion == SigVersion::BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
500  return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
501 
502  if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
503  if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
504  return set_error(serror, SCRIPT_ERR_MINIMALDATA);
505  }
506  stack.push_back(vchPushValue);
507  } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
508  switch (opcode)
509  {
510  //
511  // Push value
512  //
513  case OP_1NEGATE:
514  case OP_1:
515  case OP_2:
516  case OP_3:
517  case OP_4:
518  case OP_5:
519  case OP_6:
520  case OP_7:
521  case OP_8:
522  case OP_9:
523  case OP_10:
524  case OP_11:
525  case OP_12:
526  case OP_13:
527  case OP_14:
528  case OP_15:
529  case OP_16:
530  {
531  // ( -- value)
532  CScriptNum bn((int)opcode - (int)(OP_1 - 1));
533  stack.push_back(bn.getvch());
534  // The result of these opcodes should always be the minimal way to push the data
535  // they push, so no need for a CheckMinimalPush here.
536  }
537  break;
538 
539 
540  //
541  // Control
542  //
543  case OP_NOP:
544  break;
545 
547  {
548  if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
549  // not enabled; treat as a NOP2
550  break;
551  }
552 
553  if (stack.size() < 1)
554  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
555 
556  // Note that elsewhere numeric opcodes are limited to
557  // operands in the range -2**31+1 to 2**31-1, however it is
558  // legal for opcodes to produce results exceeding that
559  // range. This limitation is implemented by CScriptNum's
560  // default 4-byte limit.
561  //
562  // If we kept to that limit we'd have a year 2038 problem,
563  // even though the nLockTime field in transactions
564  // themselves is uint32 which only becomes meaningless
565  // after the year 2106.
566  //
567  // Thus as a special case we tell CScriptNum to accept up
568  // to 5-byte bignums, which are good until 2**39-1, well
569  // beyond the 2**32-1 limit of the nLockTime field itself.
570  const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
571 
572  // In the rare event that the argument may be < 0 due to
573  // some arithmetic being done first, you can always use
574  // 0 MAX CHECKLOCKTIMEVERIFY.
575  if (nLockTime < 0)
576  return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
577 
578  // Actually compare the specified lock time with the transaction.
579  if (!checker.CheckLockTime(nLockTime))
580  return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
581 
582  break;
583  }
584 
586  {
587  if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
588  // not enabled; treat as a NOP3
589  break;
590  }
591 
592  if (stack.size() < 1)
593  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
594 
595  // nSequence, like nLockTime, is a 32-bit unsigned integer
596  // field. See the comment in CHECKLOCKTIMEVERIFY regarding
597  // 5-byte numeric operands.
598  const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
599 
600  // In the rare event that the argument may be < 0 due to
601  // some arithmetic being done first, you can always use
602  // 0 MAX CHECKSEQUENCEVERIFY.
603  if (nSequence < 0)
604  return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
605 
606  // To provide for future soft-fork extensibility, if the
607  // operand has the disabled lock-time flag set,
608  // CHECKSEQUENCEVERIFY behaves as a NOP.
609  if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
610  break;
611 
612  // Compare the specified sequence number with the input.
613  if (!checker.CheckSequence(nSequence))
614  return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
615 
616  break;
617  }
618 
619  case OP_NOP1: case OP_NOP4: case OP_NOP5:
620  case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
621  {
623  return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
624  }
625  break;
626 
627  case OP_IF:
628  case OP_NOTIF:
629  {
630  // <expression> if [statements] [else [statements]] endif
631  bool fValue = false;
632  if (fExec)
633  {
634  if (stack.size() < 1)
635  return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
636  valtype& vch = stacktop(-1);
637  // Tapscript requires minimal IF/NOTIF inputs as a consensus rule.
638  if (sigversion == SigVersion::TAPSCRIPT) {
639  // The input argument to the OP_IF and OP_NOTIF opcodes must be either
640  // exactly 0 (the empty vector) or exactly 1 (the one-byte vector with value 1).
641  if (vch.size() > 1 || (vch.size() == 1 && vch[0] != 1)) {
642  return set_error(serror, SCRIPT_ERR_TAPSCRIPT_MINIMALIF);
643  }
644  }
645  // Under witness v0 rules it is only a policy rule, enabled through SCRIPT_VERIFY_MINIMALIF.
646  if (sigversion == SigVersion::WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
647  if (vch.size() > 1)
648  return set_error(serror, SCRIPT_ERR_MINIMALIF);
649  if (vch.size() == 1 && vch[0] != 1)
650  return set_error(serror, SCRIPT_ERR_MINIMALIF);
651  }
652  fValue = CastToBool(vch);
653  if (opcode == OP_NOTIF)
654  fValue = !fValue;
655  popstack(stack);
656  }
657  vfExec.push_back(fValue);
658  }
659  break;
660 
661  case OP_ELSE:
662  {
663  if (vfExec.empty())
664  return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
665  vfExec.toggle_top();
666  }
667  break;
668 
669  case OP_ENDIF:
670  {
671  if (vfExec.empty())
672  return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
673  vfExec.pop_back();
674  }
675  break;
676 
677  case OP_VERIFY:
678  {
679  // (true -- ) or
680  // (false -- false) and return
681  if (stack.size() < 1)
682  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
683  bool fValue = CastToBool(stacktop(-1));
684  if (fValue)
685  popstack(stack);
686  else
687  return set_error(serror, SCRIPT_ERR_VERIFY);
688  }
689  break;
690 
691  case OP_RETURN:
692  {
693  return set_error(serror, SCRIPT_ERR_OP_RETURN);
694  }
695  break;
696 
697 
698  //
699  // Stack ops
700  //
701  case OP_TOALTSTACK:
702  {
703  if (stack.size() < 1)
704  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
705  altstack.push_back(stacktop(-1));
706  popstack(stack);
707  }
708  break;
709 
710  case OP_FROMALTSTACK:
711  {
712  if (altstack.size() < 1)
713  return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
714  stack.push_back(altstacktop(-1));
715  popstack(altstack);
716  }
717  break;
718 
719  case OP_2DROP:
720  {
721  // (x1 x2 -- )
722  if (stack.size() < 2)
723  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
724  popstack(stack);
725  popstack(stack);
726  }
727  break;
728 
729  case OP_2DUP:
730  {
731  // (x1 x2 -- x1 x2 x1 x2)
732  if (stack.size() < 2)
733  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
734  valtype vch1 = stacktop(-2);
735  valtype vch2 = stacktop(-1);
736  stack.push_back(vch1);
737  stack.push_back(vch2);
738  }
739  break;
740 
741  case OP_3DUP:
742  {
743  // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
744  if (stack.size() < 3)
745  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
746  valtype vch1 = stacktop(-3);
747  valtype vch2 = stacktop(-2);
748  valtype vch3 = stacktop(-1);
749  stack.push_back(vch1);
750  stack.push_back(vch2);
751  stack.push_back(vch3);
752  }
753  break;
754 
755  case OP_2OVER:
756  {
757  // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
758  if (stack.size() < 4)
759  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
760  valtype vch1 = stacktop(-4);
761  valtype vch2 = stacktop(-3);
762  stack.push_back(vch1);
763  stack.push_back(vch2);
764  }
765  break;
766 
767  case OP_2ROT:
768  {
769  // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
770  if (stack.size() < 6)
771  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
772  valtype vch1 = stacktop(-6);
773  valtype vch2 = stacktop(-5);
774  stack.erase(stack.end()-6, stack.end()-4);
775  stack.push_back(vch1);
776  stack.push_back(vch2);
777  }
778  break;
779 
780  case OP_2SWAP:
781  {
782  // (x1 x2 x3 x4 -- x3 x4 x1 x2)
783  if (stack.size() < 4)
784  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
785  swap(stacktop(-4), stacktop(-2));
786  swap(stacktop(-3), stacktop(-1));
787  }
788  break;
789 
790  case OP_IFDUP:
791  {
792  // (x - 0 | x x)
793  if (stack.size() < 1)
794  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
795  valtype vch = stacktop(-1);
796  if (CastToBool(vch))
797  stack.push_back(vch);
798  }
799  break;
800 
801  case OP_DEPTH:
802  {
803  // -- stacksize
804  CScriptNum bn(stack.size());
805  stack.push_back(bn.getvch());
806  }
807  break;
808 
809  case OP_DROP:
810  {
811  // (x -- )
812  if (stack.size() < 1)
813  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
814  popstack(stack);
815  }
816  break;
817 
818  case OP_DUP:
819  {
820  // (x -- x x)
821  if (stack.size() < 1)
822  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
823  valtype vch = stacktop(-1);
824  stack.push_back(vch);
825  }
826  break;
827 
828  case OP_NIP:
829  {
830  // (x1 x2 -- x2)
831  if (stack.size() < 2)
832  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
833  stack.erase(stack.end() - 2);
834  }
835  break;
836 
837  case OP_OVER:
838  {
839  // (x1 x2 -- x1 x2 x1)
840  if (stack.size() < 2)
841  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
842  valtype vch = stacktop(-2);
843  stack.push_back(vch);
844  }
845  break;
846 
847  case OP_PICK:
848  case OP_ROLL:
849  {
850  // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
851  // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
852  if (stack.size() < 2)
853  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
854  int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
855  popstack(stack);
856  if (n < 0 || n >= (int)stack.size())
857  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
858  valtype vch = stacktop(-n-1);
859  if (opcode == OP_ROLL)
860  stack.erase(stack.end()-n-1);
861  stack.push_back(vch);
862  }
863  break;
864 
865  case OP_ROT:
866  {
867  // (x1 x2 x3 -- x2 x3 x1)
868  // x2 x1 x3 after first swap
869  // x2 x3 x1 after second swap
870  if (stack.size() < 3)
871  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
872  swap(stacktop(-3), stacktop(-2));
873  swap(stacktop(-2), stacktop(-1));
874  }
875  break;
876 
877  case OP_SWAP:
878  {
879  // (x1 x2 -- x2 x1)
880  if (stack.size() < 2)
881  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
882  swap(stacktop(-2), stacktop(-1));
883  }
884  break;
885 
886  case OP_TUCK:
887  {
888  // (x1 x2 -- x2 x1 x2)
889  if (stack.size() < 2)
890  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
891  valtype vch = stacktop(-1);
892  stack.insert(stack.end()-2, vch);
893  }
894  break;
895 
896 
897  case OP_SIZE:
898  {
899  // (in -- in size)
900  if (stack.size() < 1)
901  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
902  CScriptNum bn(stacktop(-1).size());
903  stack.push_back(bn.getvch());
904  }
905  break;
906 
907 
908  //
909  // Bitwise logic
910  //
911  case OP_EQUAL:
912  case OP_EQUALVERIFY:
913  //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
914  {
915  // (x1 x2 - bool)
916  if (stack.size() < 2)
917  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
918  valtype& vch1 = stacktop(-2);
919  valtype& vch2 = stacktop(-1);
920  bool fEqual = (vch1 == vch2);
921  // OP_NOTEQUAL is disabled because it would be too easy to say
922  // something like n != 1 and have some wiseguy pass in 1 with extra
923  // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
924  //if (opcode == OP_NOTEQUAL)
925  // fEqual = !fEqual;
926  popstack(stack);
927  popstack(stack);
928  stack.push_back(fEqual ? vchTrue : vchFalse);
929  if (opcode == OP_EQUALVERIFY)
930  {
931  if (fEqual)
932  popstack(stack);
933  else
934  return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
935  }
936  }
937  break;
938 
939 
940  //
941  // Numeric
942  //
943  case OP_1ADD:
944  case OP_1SUB:
945  case OP_NEGATE:
946  case OP_ABS:
947  case OP_NOT:
948  case OP_0NOTEQUAL:
949  {
950  // (in -- out)
951  if (stack.size() < 1)
952  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
953  CScriptNum bn(stacktop(-1), fRequireMinimal);
954  switch (opcode)
955  {
956  case OP_1ADD: bn += bnOne; break;
957  case OP_1SUB: bn -= bnOne; break;
958  case OP_NEGATE: bn = -bn; break;
959  case OP_ABS: if (bn < bnZero) bn = -bn; break;
960  case OP_NOT: bn = (bn == bnZero); break;
961  case OP_0NOTEQUAL: bn = (bn != bnZero); break;
962  default: assert(!"invalid opcode"); break;
963  }
964  popstack(stack);
965  stack.push_back(bn.getvch());
966  }
967  break;
968 
969  case OP_ADD:
970  case OP_SUB:
971  case OP_BOOLAND:
972  case OP_BOOLOR:
973  case OP_NUMEQUAL:
974  case OP_NUMEQUALVERIFY:
975  case OP_NUMNOTEQUAL:
976  case OP_LESSTHAN:
977  case OP_GREATERTHAN:
978  case OP_LESSTHANOREQUAL:
980  case OP_MIN:
981  case OP_MAX:
982  {
983  // (x1 x2 -- out)
984  if (stack.size() < 2)
985  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
986  CScriptNum bn1(stacktop(-2), fRequireMinimal);
987  CScriptNum bn2(stacktop(-1), fRequireMinimal);
988  CScriptNum bn(0);
989  switch (opcode)
990  {
991  case OP_ADD:
992  bn = bn1 + bn2;
993  break;
994 
995  case OP_SUB:
996  bn = bn1 - bn2;
997  break;
998 
999  case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
1000  case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
1001  case OP_NUMEQUAL: bn = (bn1 == bn2); break;
1002  case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
1003  case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
1004  case OP_LESSTHAN: bn = (bn1 < bn2); break;
1005  case OP_GREATERTHAN: bn = (bn1 > bn2); break;
1006  case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
1007  case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
1008  case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
1009  case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
1010  default: assert(!"invalid opcode"); break;
1011  }
1012  popstack(stack);
1013  popstack(stack);
1014  stack.push_back(bn.getvch());
1015 
1016  if (opcode == OP_NUMEQUALVERIFY)
1017  {
1018  if (CastToBool(stacktop(-1)))
1019  popstack(stack);
1020  else
1021  return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
1022  }
1023  }
1024  break;
1025 
1026  case OP_WITHIN:
1027  {
1028  // (x min max -- out)
1029  if (stack.size() < 3)
1030  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1031  CScriptNum bn1(stacktop(-3), fRequireMinimal);
1032  CScriptNum bn2(stacktop(-2), fRequireMinimal);
1033  CScriptNum bn3(stacktop(-1), fRequireMinimal);
1034  bool fValue = (bn2 <= bn1 && bn1 < bn3);
1035  popstack(stack);
1036  popstack(stack);
1037  popstack(stack);
1038  stack.push_back(fValue ? vchTrue : vchFalse);
1039  }
1040  break;
1041 
1042 
1043  //
1044  // Crypto
1045  //
1046  case OP_RIPEMD160:
1047  case OP_SHA1:
1048  case OP_SHA256:
1049  case OP_HASH160:
1050  case OP_HASH256:
1051  {
1052  // (in -- hash)
1053  if (stack.size() < 1)
1054  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1055  valtype& vch = stacktop(-1);
1056  valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
1057  if (opcode == OP_RIPEMD160)
1058  CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1059  else if (opcode == OP_SHA1)
1060  CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1061  else if (opcode == OP_SHA256)
1062  CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1063  else if (opcode == OP_HASH160)
1064  CHash160().Write(vch).Finalize(vchHash);
1065  else if (opcode == OP_HASH256)
1066  CHash256().Write(vch).Finalize(vchHash);
1067  popstack(stack);
1068  stack.push_back(vchHash);
1069  }
1070  break;
1071 
1072  case OP_CODESEPARATOR:
1073  {
1074  // If SCRIPT_VERIFY_CONST_SCRIPTCODE flag is set, use of OP_CODESEPARATOR is rejected in pre-segwit
1075  // script, even in an unexecuted branch (this is checked above the opcode case statement).
1076 
1077  // Hash starts after the code separator
1078  pbegincodehash = pc;
1079  execdata.m_codeseparator_pos = opcode_pos;
1080  }
1081  break;
1082 
1083  case OP_CHECKSIG:
1084  case OP_CHECKSIGVERIFY:
1085  {
1086  // (sig pubkey -- bool)
1087  if (stack.size() < 2)
1088  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1089 
1090  valtype& vchSig = stacktop(-2);
1091  valtype& vchPubKey = stacktop(-1);
1092 
1093  bool fSuccess = true;
1094  if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, fSuccess)) return false;
1095  popstack(stack);
1096  popstack(stack);
1097  stack.push_back(fSuccess ? vchTrue : vchFalse);
1098  if (opcode == OP_CHECKSIGVERIFY)
1099  {
1100  if (fSuccess)
1101  popstack(stack);
1102  else
1103  return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
1104  }
1105  }
1106  break;
1107 
1108  case OP_CHECKSIGADD:
1109  {
1110  // OP_CHECKSIGADD is only available in Tapscript
1111  if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1112 
1113  // (sig num pubkey -- num)
1114  if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1115 
1116  const valtype& sig = stacktop(-3);
1117  const CScriptNum num(stacktop(-2), fRequireMinimal);
1118  const valtype& pubkey = stacktop(-1);
1119 
1120  bool success = true;
1121  if (!EvalChecksig(sig, pubkey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, success)) return false;
1122  popstack(stack);
1123  popstack(stack);
1124  popstack(stack);
1125  stack.push_back((num + (success ? 1 : 0)).getvch());
1126  }
1127  break;
1128 
1129  case OP_CHECKMULTISIG:
1131  {
1132  if (sigversion == SigVersion::TAPSCRIPT) return set_error(serror, SCRIPT_ERR_TAPSCRIPT_CHECKMULTISIG);
1133 
1134  // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1135 
1136  int i = 1;
1137  if ((int)stack.size() < i)
1138  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1139 
1140  int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1141  if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
1142  return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
1143  nOpCount += nKeysCount;
1144  if (nOpCount > MAX_OPS_PER_SCRIPT)
1145  return set_error(serror, SCRIPT_ERR_OP_COUNT);
1146  int ikey = ++i;
1147  // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
1148  // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
1149  int ikey2 = nKeysCount + 2;
1150  i += nKeysCount;
1151  if ((int)stack.size() < i)
1152  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1153 
1154  int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1155  if (nSigsCount < 0 || nSigsCount > nKeysCount)
1156  return set_error(serror, SCRIPT_ERR_SIG_COUNT);
1157  int isig = ++i;
1158  i += nSigsCount;
1159  if ((int)stack.size() < i)
1160  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1161 
1162  // Subset of script starting at the most recent codeseparator
1163  CScript scriptCode(pbegincodehash, pend);
1164 
1165  // Drop the signature in pre-segwit scripts but not segwit scripts
1166  for (int k = 0; k < nSigsCount; k++)
1167  {
1168  valtype& vchSig = stacktop(-isig-k);
1169  if (sigversion == SigVersion::BASE) {
1170  int found = FindAndDelete(scriptCode, CScript() << vchSig);
1171  if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
1172  return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
1173  }
1174  }
1175 
1176  bool fSuccess = true;
1177  while (fSuccess && nSigsCount > 0)
1178  {
1179  valtype& vchSig = stacktop(-isig);
1180  valtype& vchPubKey = stacktop(-ikey);
1181 
1182  // Note how this makes the exact order of pubkey/signature evaluation
1183  // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
1184  // See the script_(in)valid tests for details.
1185  if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
1186  // serror is set
1187  return false;
1188  }
1189 
1190  // Check signature
1191  bool fOk = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
1192 
1193  if (fOk) {
1194  isig++;
1195  nSigsCount--;
1196  }
1197  ikey++;
1198  nKeysCount--;
1199 
1200  // If there are more signatures left than keys left,
1201  // then too many signatures have failed. Exit early,
1202  // without checking any further signatures.
1203  if (nSigsCount > nKeysCount)
1204  fSuccess = false;
1205  }
1206 
1207  // Clean up stack of actual arguments
1208  while (i-- > 1) {
1209  // If the operation failed, we require that all signatures must be empty vector
1210  if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
1211  return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
1212  if (ikey2 > 0)
1213  ikey2--;
1214  popstack(stack);
1215  }
1216 
1217  // A bug causes CHECKMULTISIG to consume one extra argument
1218  // whose contents were not checked in any way.
1219  //
1220  // Unfortunately this is a potential source of mutability,
1221  // so optionally verify it is exactly equal to zero prior
1222  // to removing it from the stack.
1223  if (stack.size() < 1)
1224  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1225  if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1226  return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1227  popstack(stack);
1228 
1229  stack.push_back(fSuccess ? vchTrue : vchFalse);
1230 
1231  if (opcode == OP_CHECKMULTISIGVERIFY)
1232  {
1233  if (fSuccess)
1234  popstack(stack);
1235  else
1236  return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1237  }
1238  }
1239  break;
1240 
1241  default:
1242  return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1243  }
1244 
1245  // Size limits
1246  if (stack.size() + altstack.size() > MAX_STACK_SIZE)
1247  return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1248  }
1249  }
1250  catch (...)
1251  {
1252  return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1253  }
1254 
1255  if (!vfExec.empty())
1256  return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1257 
1258  return set_success(serror);
1259 }
1260 
1261 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
1262 {
1263  ScriptExecutionData execdata;
1264  return EvalScript(stack, script, flags, checker, sigversion, execdata, serror);
1265 }
1266 
1267 namespace {
1268 
1273 template <class T>
1274 class CTransactionSignatureSerializer
1275 {
1276 private:
1277  const T& txTo;
1278  const CScript& scriptCode;
1279  const unsigned int nIn;
1280  const bool fAnyoneCanPay;
1281  const bool fHashSingle;
1282  const bool fHashNone;
1283 
1284 public:
1285  CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1286  txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1287  fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1288  fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1289  fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1290 
1292  template<typename S>
1293  void SerializeScriptCode(S &s) const {
1294  CScript::const_iterator it = scriptCode.begin();
1295  CScript::const_iterator itBegin = it;
1296  opcodetype opcode;
1297  unsigned int nCodeSeparators = 0;
1298  while (scriptCode.GetOp(it, opcode)) {
1299  if (opcode == OP_CODESEPARATOR)
1300  nCodeSeparators++;
1301  }
1302  ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1303  it = itBegin;
1304  while (scriptCode.GetOp(it, opcode)) {
1305  if (opcode == OP_CODESEPARATOR) {
1306  s.write((char*)&itBegin[0], it-itBegin-1);
1307  itBegin = it;
1308  }
1309  }
1310  if (itBegin != scriptCode.end())
1311  s.write((char*)&itBegin[0], it-itBegin);
1312  }
1313 
1315  template<typename S>
1316  void SerializeInput(S &s, unsigned int nInput) const {
1317  // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1318  if (fAnyoneCanPay)
1319  nInput = nIn;
1320  // Serialize the prevout
1321  ::Serialize(s, txTo.vin[nInput].prevout);
1322  // Serialize the script
1323  if (nInput != nIn)
1324  // Blank out other inputs' signatures
1325  ::Serialize(s, CScript());
1326  else
1327  SerializeScriptCode(s);
1328  // Serialize the nSequence
1329  if (nInput != nIn && (fHashSingle || fHashNone))
1330  // let the others update at will
1331  ::Serialize(s, (int)0);
1332  else
1333  ::Serialize(s, txTo.vin[nInput].nSequence);
1334  }
1335 
1337  template<typename S>
1338  void SerializeOutput(S &s, unsigned int nOutput) const {
1339  if (fHashSingle && nOutput != nIn)
1340  // Do not lock-in the txout payee at other indices as txin
1341  ::Serialize(s, CTxOut());
1342  else
1343  ::Serialize(s, txTo.vout[nOutput]);
1344  }
1345 
1347  template<typename S>
1348  void Serialize(S &s) const {
1349  // Serialize nVersion
1350  ::Serialize(s, txTo.nVersion);
1351  // Serialize vin
1352  unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1353  ::WriteCompactSize(s, nInputs);
1354  for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1355  SerializeInput(s, nInput);
1356  // Serialize vout
1357  unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1358  ::WriteCompactSize(s, nOutputs);
1359  for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1360  SerializeOutput(s, nOutput);
1361  // Serialize nLockTime
1362  ::Serialize(s, txTo.nLockTime);
1363  }
1364 };
1365 
1367 template <class T>
1368 uint256 GetPrevoutsSHA256(const T& txTo)
1369 {
1370  CHashWriter ss(SER_GETHASH, 0);
1371  for (const auto& txin : txTo.vin) {
1372  ss << txin.prevout;
1373  }
1374  return ss.GetSHA256();
1375 }
1376 
1378 template <class T>
1379 uint256 GetSequencesSHA256(const T& txTo)
1380 {
1381  CHashWriter ss(SER_GETHASH, 0);
1382  for (const auto& txin : txTo.vin) {
1383  ss << txin.nSequence;
1384  }
1385  return ss.GetSHA256();
1386 }
1387 
1389 template <class T>
1390 uint256 GetOutputsSHA256(const T& txTo)
1391 {
1392  CHashWriter ss(SER_GETHASH, 0);
1393  for (const auto& txout : txTo.vout) {
1394  ss << txout;
1395  }
1396  return ss.GetSHA256();
1397 }
1398 
1400 uint256 GetSpentAmountsSHA256(const std::vector<CTxOut>& outputs_spent)
1401 {
1402  CHashWriter ss(SER_GETHASH, 0);
1403  for (const auto& txout : outputs_spent) {
1404  ss << txout.nValue;
1405  }
1406  return ss.GetSHA256();
1407 }
1408 
1410 uint256 GetSpentScriptsSHA256(const std::vector<CTxOut>& outputs_spent)
1411 {
1412  CHashWriter ss(SER_GETHASH, 0);
1413  for (const auto& txout : outputs_spent) {
1414  ss << txout.scriptPubKey;
1415  }
1416  return ss.GetSHA256();
1417 }
1418 
1419 
1420 } // namespace
1421 
1422 template <class T>
1423 void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent_outputs)
1424 {
1425  assert(!m_spent_outputs_ready);
1426 
1427  m_spent_outputs = std::move(spent_outputs);
1428  if (!m_spent_outputs.empty()) {
1429  assert(m_spent_outputs.size() == txTo.vin.size());
1430  m_spent_outputs_ready = true;
1431  }
1432 
1433  // Determine which precomputation-impacting features this transaction uses.
1434  bool uses_bip143_segwit = false;
1435  bool uses_bip341_taproot = false;
1436  for (size_t inpos = 0; inpos < txTo.vin.size(); ++inpos) {
1437  if (!txTo.vin[inpos].scriptWitness.IsNull()) {
1438  if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.size() == 2 + WITNESS_V1_TAPROOT_SIZE &&
1439  m_spent_outputs[inpos].scriptPubKey[0] == OP_1) {
1440  // Treat every witness-bearing spend with 34-byte scriptPubKey that starts with OP_1 as a Taproot
1441  // spend. This only works if spent_outputs was provided as well, but if it wasn't, actual validation
1442  // will fail anyway. Note that this branch may trigger for scriptPubKeys that aren't actually segwit
1443  // but in that case validation will fail as SCRIPT_ERR_WITNESS_UNEXPECTED anyway.
1444  uses_bip341_taproot = true;
1445  } else {
1446  // Treat every spend that's not known to native witness v1 as a Witness v0 spend. This branch may
1447  // also be taken for unknown witness versions, but it is harmless, and being precise would require
1448  // P2SH evaluation to find the redeemScript.
1449  uses_bip143_segwit = true;
1450  }
1451  }
1452  if (uses_bip341_taproot && uses_bip143_segwit) break; // No need to scan further if we already need all.
1453  }
1454 
1455  if (uses_bip143_segwit || uses_bip341_taproot) {
1456  // Computations shared between both sighash schemes.
1457  m_prevouts_single_hash = GetPrevoutsSHA256(txTo);
1458  m_sequences_single_hash = GetSequencesSHA256(txTo);
1459  m_outputs_single_hash = GetOutputsSHA256(txTo);
1460  }
1461  if (uses_bip143_segwit) {
1462  hashPrevouts = SHA256Uint256(m_prevouts_single_hash);
1463  hashSequence = SHA256Uint256(m_sequences_single_hash);
1464  hashOutputs = SHA256Uint256(m_outputs_single_hash);
1465  m_bip143_segwit_ready = true;
1466  }
1467  if (uses_bip341_taproot) {
1468  m_spent_amounts_single_hash = GetSpentAmountsSHA256(m_spent_outputs);
1469  m_spent_scripts_single_hash = GetSpentScriptsSHA256(m_spent_outputs);
1470  m_bip341_taproot_ready = true;
1471  }
1472 }
1473 
1474 template <class T>
1476 {
1477  Init(txTo, {});
1478 }
1479 
1480 // explicit instantiation
1481 template void PrecomputedTransactionData::Init(const CTransaction& txTo, std::vector<CTxOut>&& spent_outputs);
1482 template void PrecomputedTransactionData::Init(const CMutableTransaction& txTo, std::vector<CTxOut>&& spent_outputs);
1485 
1486 static const CHashWriter HASHER_TAPSIGHASH = TaggedHash("TapSighash");
1487 static const CHashWriter HASHER_TAPLEAF = TaggedHash("TapLeaf");
1488 static const CHashWriter HASHER_TAPBRANCH = TaggedHash("TapBranch");
1489 static const CHashWriter HASHER_TAPTWEAK = TaggedHash("TapTweak");
1490 
1491 template<typename T>
1492 bool SignatureHashSchnorr(uint256& hash_out, const ScriptExecutionData& execdata, const T& tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData& cache)
1493 {
1494  uint8_t ext_flag, key_version;
1495  switch (sigversion) {
1496  case SigVersion::TAPROOT:
1497  ext_flag = 0;
1498  // key_version is not used and left uninitialized.
1499  break;
1500  case SigVersion::TAPSCRIPT:
1501  ext_flag = 1;
1502  // key_version must be 0 for now, representing the current version of
1503  // 32-byte public keys in the tapscript signature opcode execution.
1504  // An upgradable public key version (with a size not 32-byte) may
1505  // request a different key_version with a new sigversion.
1506  key_version = 0;
1507  break;
1508  default:
1509  assert(false);
1510  }
1511  assert(in_pos < tx_to.vin.size());
1512  assert(cache.m_bip341_taproot_ready && cache.m_spent_outputs_ready);
1513 
1515 
1516  // Epoch
1517  static constexpr uint8_t EPOCH = 0;
1518  ss << EPOCH;
1519 
1520  // Hash type
1521  const uint8_t output_type = (hash_type == SIGHASH_DEFAULT) ? SIGHASH_ALL : (hash_type & SIGHASH_OUTPUT_MASK); // Default (no sighash byte) is equivalent to SIGHASH_ALL
1522  const uint8_t input_type = hash_type & SIGHASH_INPUT_MASK;
1523  if (!(hash_type <= 0x03 || (hash_type >= 0x81 && hash_type <= 0x83))) return false;
1524  ss << hash_type;
1525 
1526  // Transaction level data
1527  ss << tx_to.nVersion;
1528  ss << tx_to.nLockTime;
1529  if (input_type != SIGHASH_ANYONECANPAY) {
1530  ss << cache.m_prevouts_single_hash;
1531  ss << cache.m_spent_amounts_single_hash;
1532  ss << cache.m_spent_scripts_single_hash;
1533  ss << cache.m_sequences_single_hash;
1534  }
1535  if (output_type == SIGHASH_ALL) {
1536  ss << cache.m_outputs_single_hash;
1537  }
1538 
1539  // Data about the input/prevout being spent
1540  assert(execdata.m_annex_init);
1541  const bool have_annex = execdata.m_annex_present;
1542  const uint8_t spend_type = (ext_flag << 1) + (have_annex ? 1 : 0); // The low bit indicates whether an annex is present.
1543  ss << spend_type;
1544  if (input_type == SIGHASH_ANYONECANPAY) {
1545  ss << tx_to.vin[in_pos].prevout;
1546  ss << cache.m_spent_outputs[in_pos];
1547  ss << tx_to.vin[in_pos].nSequence;
1548  } else {
1549  ss << in_pos;
1550  }
1551  if (have_annex) {
1552  ss << execdata.m_annex_hash;
1553  }
1554 
1555  // Data about the output (if only one).
1556  if (output_type == SIGHASH_SINGLE) {
1557  if (in_pos >= tx_to.vout.size()) return false;
1558  CHashWriter sha_single_output(SER_GETHASH, 0);
1559  sha_single_output << tx_to.vout[in_pos];
1560  ss << sha_single_output.GetSHA256();
1561  }
1562 
1563  // Additional data for BIP 342 signatures
1564  if (sigversion == SigVersion::TAPSCRIPT) {
1565  assert(execdata.m_tapleaf_hash_init);
1566  ss << execdata.m_tapleaf_hash;
1567  ss << key_version;
1568  assert(execdata.m_codeseparator_pos_init);
1569  ss << execdata.m_codeseparator_pos;
1570  }
1571 
1572  hash_out = ss.GetSHA256();
1573  return true;
1574 }
1575 
1576 template <class T>
1577 uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1578 {
1579  assert(nIn < txTo.vin.size());
1580 
1581  if (sigversion == SigVersion::WITNESS_V0) {
1582  uint256 hashPrevouts;
1583  uint256 hashSequence;
1584  uint256 hashOutputs;
1585  const bool cacheready = cache && cache->m_bip143_segwit_ready;
1586 
1587  if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1588  hashPrevouts = cacheready ? cache->hashPrevouts : SHA256Uint256(GetPrevoutsSHA256(txTo));
1589  }
1590 
1591  if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1592  hashSequence = cacheready ? cache->hashSequence : SHA256Uint256(GetSequencesSHA256(txTo));
1593  }
1594 
1595 
1596  if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1597  hashOutputs = cacheready ? cache->hashOutputs : SHA256Uint256(GetOutputsSHA256(txTo));
1598  } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
1599  CHashWriter ss(SER_GETHASH, 0);
1600  ss << txTo.vout[nIn];
1601  hashOutputs = ss.GetHash();
1602  }
1603 
1604  CHashWriter ss(SER_GETHASH, 0);
1605  // Version
1606  ss << txTo.nVersion;
1607  // Input prevouts/nSequence (none/all, depending on flags)
1608  ss << hashPrevouts;
1609  ss << hashSequence;
1610  // The input being signed (replacing the scriptSig with scriptCode + amount)
1611  // The prevout may already be contained in hashPrevout, and the nSequence
1612  // may already be contain in hashSequence.
1613  ss << txTo.vin[nIn].prevout;
1614  ss << scriptCode;
1615  ss << amount;
1616  ss << txTo.vin[nIn].nSequence;
1617  // Outputs (none/one/all, depending on flags)
1618  ss << hashOutputs;
1619  // Locktime
1620  ss << txTo.nLockTime;
1621  // Sighash type
1622  ss << nHashType;
1623 
1624  return ss.GetHash();
1625  }
1626 
1627  // Check for invalid use of SIGHASH_SINGLE
1628  if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1629  if (nIn >= txTo.vout.size()) {
1630  // nOut out of range
1631  return uint256::ONE;
1632  }
1633  }
1634 
1635  // Wrapper to serialize only the necessary parts of the transaction being signed
1636  CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
1637 
1638  // Serialize and hash
1639  CHashWriter ss(SER_GETHASH, 0);
1640  ss << txTmp << nHashType;
1641  return ss.GetHash();
1642 }
1643 
1644 template <class T>
1645 bool GenericTransactionSignatureChecker<T>::VerifyECDSASignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1646 {
1647  return pubkey.Verify(sighash, vchSig);
1648 }
1649 
1650 template <class T>
1652 {
1653  return pubkey.VerifySchnorr(sighash, sig);
1654 }
1655 
1656 template <class T>
1657 bool GenericTransactionSignatureChecker<T>::CheckECDSASignature(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1658 {
1659  CPubKey pubkey(vchPubKey);
1660  if (!pubkey.IsValid())
1661  return false;
1662 
1663  // Hash type is one byte tacked on to the end of the signature
1664  std::vector<unsigned char> vchSig(vchSigIn);
1665  if (vchSig.empty())
1666  return false;
1667  int nHashType = vchSig.back();
1668  vchSig.pop_back();
1669 
1670  uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
1671 
1672  if (!VerifyECDSASignature(vchSig, pubkey, sighash))
1673  return false;
1674 
1675  return true;
1676 }
1677 
1678 template <class T>
1680 {
1681  assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
1682  // Schnorr signatures have 32-byte public keys. The caller is responsible for enforcing this.
1683  assert(pubkey_in.size() == 32);
1684  // Note that in Tapscript evaluation, empty signatures are treated specially (invalid signature that does not
1685  // abort script execution). This is implemented in EvalChecksigTapscript, which won't invoke
1686  // CheckSchnorrSignature in that case. In other contexts, they are invalid like every other signature with
1687  // size different from 64 or 65.
1688  if (sig.size() != 64 && sig.size() != 65) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_SIZE);
1689 
1690  XOnlyPubKey pubkey{pubkey_in};
1691 
1692  uint8_t hashtype = SIGHASH_DEFAULT;
1693  if (sig.size() == 65) {
1694  hashtype = SpanPopBack(sig);
1695  if (hashtype == SIGHASH_DEFAULT) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
1696  }
1697  uint256 sighash;
1698  assert(this->txdata);
1699  if (!SignatureHashSchnorr(sighash, execdata, *txTo, nIn, hashtype, sigversion, *this->txdata)) {
1700  return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
1701  }
1702  if (!VerifySchnorrSignature(sig, pubkey, sighash)) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG);
1703  return true;
1704 }
1705 
1706 template <class T>
1708 {
1709  // There are two kinds of nLockTime: lock-by-blockheight
1710  // and lock-by-blocktime, distinguished by whether
1711  // nLockTime < LOCKTIME_THRESHOLD.
1712  //
1713  // We want to compare apples to apples, so fail the script
1714  // unless the type of nLockTime being tested is the same as
1715  // the nLockTime in the transaction.
1716  if (!(
1717  (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
1718  (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1719  ))
1720  return false;
1721 
1722  // Now that we know we're comparing apples-to-apples, the
1723  // comparison is a simple numeric one.
1724  if (nLockTime > (int64_t)txTo->nLockTime)
1725  return false;
1726 
1727  // Finally the nLockTime feature can be disabled and thus
1728  // CHECKLOCKTIMEVERIFY bypassed if every txin has been
1729  // finalized by setting nSequence to maxint. The
1730  // transaction would be allowed into the blockchain, making
1731  // the opcode ineffective.
1732  //
1733  // Testing if this vin is not final is sufficient to
1734  // prevent this condition. Alternatively we could test all
1735  // inputs, but testing just this input minimizes the data
1736  // required to prove correct CHECKLOCKTIMEVERIFY execution.
1737  if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1738  return false;
1739 
1740  return true;
1741 }
1742 
1743 template <class T>
1745 {
1746  // Relative lock times are supported by comparing the passed
1747  // in operand to the sequence number of the input.
1748  const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1749 
1750  // Fail if the transaction's version number is not set high
1751  // enough to trigger BIP 68 rules.
1752  if (static_cast<uint32_t>(txTo->nVersion) < 2)
1753  return false;
1754 
1755  // Sequence numbers with their most significant bit set are not
1756  // consensus constrained. Testing that the transaction's sequence
1757  // number do not have this bit set prevents using this property
1758  // to get around a CHECKSEQUENCEVERIFY check.
1759  if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1760  return false;
1761 
1762  // Mask off any bits that do not have consensus-enforced meaning
1763  // before doing the integer comparisons
1764  const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1765  const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1766  const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1767 
1768  // There are two kinds of nSequence: lock-by-blockheight
1769  // and lock-by-blocktime, distinguished by whether
1770  // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1771  //
1772  // We want to compare apples to apples, so fail the script
1773  // unless the type of nSequenceMasked being tested is the same as
1774  // the nSequenceMasked in the transaction.
1775  if (!(
1776  (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1777  (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1778  )) {
1779  return false;
1780  }
1781 
1782  // Now that we know we're comparing apples-to-apples, the
1783  // comparison is a simple numeric one.
1784  if (nSequenceMasked > txToSequenceMasked)
1785  return false;
1786 
1787  return true;
1788 }
1789 
1790 // explicit instantiation
1793 
1794 static bool ExecuteWitnessScript(const Span<const valtype>& stack_span, const CScript& scriptPubKey, unsigned int flags, SigVersion sigversion, const BaseSignatureChecker& checker, ScriptExecutionData& execdata, ScriptError* serror)
1795 {
1796  std::vector<valtype> stack{stack_span.begin(), stack_span.end()};
1797 
1798  if (sigversion == SigVersion::TAPSCRIPT) {
1799  // OP_SUCCESSx processing overrides everything, including stack element size limits
1800  CScript::const_iterator pc = scriptPubKey.begin();
1801  while (pc < scriptPubKey.end()) {
1802  opcodetype opcode;
1803  if (!scriptPubKey.GetOp(pc, opcode)) {
1804  // Note how this condition would not be reached if an unknown OP_SUCCESSx was found
1805  return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1806  }
1807  // New opcodes will be listed here. May use a different sigversion to modify existing opcodes.
1808  if (IsOpSuccess(opcode)) {
1810  return set_error(serror, SCRIPT_ERR_DISCOURAGE_OP_SUCCESS);
1811  }
1812  return set_success(serror);
1813  }
1814  }
1815 
1816  // Tapscript enforces initial stack size limits (altstack is empty here)
1817  if (stack.size() > MAX_STACK_SIZE) return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1818  }
1819 
1820  // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
1821  for (const valtype& elem : stack) {
1822  if (elem.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
1823  }
1824 
1825  // Run the script interpreter.
1826  if (!EvalScript(stack, scriptPubKey, flags, checker, sigversion, execdata, serror)) return false;
1827 
1828  // Scripts inside witness implicitly require cleanstack behaviour
1829  if (stack.size() != 1) return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1830  if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1831  return true;
1832 }
1833 
1834 static bool VerifyTaprootCommitment(const std::vector<unsigned char>& control, const std::vector<unsigned char>& program, const CScript& script, uint256& tapleaf_hash)
1835 {
1836  const int path_len = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
1837  const XOnlyPubKey p{uint256(std::vector<unsigned char>(control.begin() + 1, control.begin() + TAPROOT_CONTROL_BASE_SIZE))};
1838  const XOnlyPubKey q{uint256(program)};
1839  tapleaf_hash = (CHashWriter(HASHER_TAPLEAF) << uint8_t(control[0] & TAPROOT_LEAF_MASK) << script).GetSHA256();
1840  uint256 k = tapleaf_hash;
1841  for (int i = 0; i < path_len; ++i) {
1842  CHashWriter ss_branch{HASHER_TAPBRANCH};
1844  if (std::lexicographical_compare(k.begin(), k.end(), node.begin(), node.end())) {
1845  ss_branch << k << node;
1846  } else {
1847  ss_branch << node << k;
1848  }
1849  k = ss_branch.GetSHA256();
1850  }
1851  k = (CHashWriter(HASHER_TAPTWEAK) << MakeSpan(p) << k).GetSHA256();
1852  return q.CheckPayToContract(p, k, control[0] & 1);
1853 }
1854 
1855 static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror, bool is_p2sh)
1856 {
1857  CScript exec_script;
1858  Span<const valtype> stack{witness.stack};
1859  ScriptExecutionData execdata;
1860 
1861  if (witversion == 0) {
1862  if (program.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
1863  // BIP141 P2WSH: 32-byte witness v0 program (which encodes SHA256(script))
1864  if (stack.size() == 0) {
1865  return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1866  }
1867  const valtype& script_bytes = SpanPopBack(stack);
1868  exec_script = CScript(script_bytes.begin(), script_bytes.end());
1869  uint256 hash_exec_script;
1870  CSHA256().Write(&exec_script[0], exec_script.size()).Finalize(hash_exec_script.begin());
1871  if (memcmp(hash_exec_script.begin(), program.data(), 32)) {
1872  return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1873  }
1874  return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
1875  } else if (program.size() == WITNESS_V0_KEYHASH_SIZE) {
1876  // BIP141 P2WPKH: 20-byte witness v0 program (which encodes Hash160(pubkey))
1877  if (stack.size() != 2) {
1878  return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1879  }
1880  exec_script << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
1881  return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
1882  } else {
1883  return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
1884  }
1885  } else if (witversion == 1 && program.size() == WITNESS_V1_TAPROOT_SIZE && !is_p2sh) {
1886  // BIP341 Taproot: 32-byte non-P2SH witness v1 program (which encodes a P2C-tweaked pubkey)
1887  if (!(flags & SCRIPT_VERIFY_TAPROOT)) return set_success(serror);
1888  if (stack.size() == 0) return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1889  if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
1890  // Drop annex (this is non-standard; see IsWitnessStandard)
1891  const valtype& annex = SpanPopBack(stack);
1892  execdata.m_annex_hash = (CHashWriter(SER_GETHASH, 0) << annex).GetSHA256();
1893  execdata.m_annex_present = true;
1894  } else {
1895  execdata.m_annex_present = false;
1896  }
1897  execdata.m_annex_init = true;
1898  if (stack.size() == 1) {
1899  // Key path spending (stack size is 1 after removing optional annex)
1900  if (!checker.CheckSchnorrSignature(stack.front(), program, SigVersion::TAPROOT, execdata, serror)) {
1901  return false; // serror is set
1902  }
1903  return set_success(serror);
1904  } else {
1905  // Script path spending (stack size is >1 after removing optional annex)
1906  const valtype& control = SpanPopBack(stack);
1907  const valtype& script_bytes = SpanPopBack(stack);
1908  exec_script = CScript(script_bytes.begin(), script_bytes.end());
1909  if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE || ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) {
1910  return set_error(serror, SCRIPT_ERR_TAPROOT_WRONG_CONTROL_SIZE);
1911  }
1912  if (!VerifyTaprootCommitment(control, program, exec_script, execdata.m_tapleaf_hash)) {
1913  return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1914  }
1915  execdata.m_tapleaf_hash_init = true;
1916  if ((control[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
1917  // Tapscript (leaf version 0xc0)
1919  execdata.m_validation_weight_left_init = true;
1920  return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::TAPSCRIPT, checker, execdata, serror);
1921  }
1923  return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION);
1924  }
1925  return set_success(serror);
1926  }
1927  } else {
1929  return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
1930  }
1931  // Other version/size/p2sh combinations return true for future softfork compatibility
1932  return true;
1933  }
1934  // There is intentionally no return statement here, to be able to use "control reaches end of non-void function" warnings to detect gaps in the logic above.
1935 }
1936 
1937 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1938 {
1939  static const CScriptWitness emptyWitness;
1940  if (witness == nullptr) {
1941  witness = &emptyWitness;
1942  }
1943  bool hadWitness = false;
1944 
1945  set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1946 
1947  if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1948  return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1949  }
1950 
1951  // scriptSig and scriptPubKey must be evaluated sequentially on the same stack
1952  // rather than being simply concatenated (see CVE-2010-5141)
1953  std::vector<std::vector<unsigned char> > stack, stackCopy;
1954  if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
1955  // serror is set
1956  return false;
1957  if (flags & SCRIPT_VERIFY_P2SH)
1958  stackCopy = stack;
1959  if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
1960  // serror is set
1961  return false;
1962  if (stack.empty())
1963  return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1964  if (CastToBool(stack.back()) == false)
1965  return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1966 
1967  // Bare witness programs
1968  int witnessversion;
1969  std::vector<unsigned char> witnessprogram;
1970  if (flags & SCRIPT_VERIFY_WITNESS) {
1971  if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1972  hadWitness = true;
1973  if (scriptSig.size() != 0) {
1974  // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
1975  return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
1976  }
1977  if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /* is_p2sh */ false)) {
1978  return false;
1979  }
1980  // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1981  // for witness programs.
1982  stack.resize(1);
1983  }
1984  }
1985 
1986  // Additional validation for spend-to-script-hash transactions:
1987  if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1988  {
1989  // scriptSig must be literals-only or validation fails
1990  if (!scriptSig.IsPushOnly())
1991  return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1992 
1993  // Restore stack.
1994  swap(stack, stackCopy);
1995 
1996  // stack cannot be empty here, because if it was the
1997  // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1998  // an empty stack and the EvalScript above would return false.
1999  assert(!stack.empty());
2000 
2001  const valtype& pubKeySerialized = stack.back();
2002  CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
2003  popstack(stack);
2004 
2005  if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
2006  // serror is set
2007  return false;
2008  if (stack.empty())
2009  return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2010  if (!CastToBool(stack.back()))
2011  return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2012 
2013  // P2SH witness program
2014  if (flags & SCRIPT_VERIFY_WITNESS) {
2015  if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
2016  hadWitness = true;
2017  if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
2018  // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
2019  // reintroduce malleability.
2020  return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
2021  }
2022  if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /* is_p2sh */ true)) {
2023  return false;
2024  }
2025  // Bypass the cleanstack check at the end. The actual stack is obviously not clean
2026  // for witness programs.
2027  stack.resize(1);
2028  }
2029  }
2030  }
2031 
2032  // The CLEANSTACK check is only performed after potential P2SH evaluation,
2033  // as the non-P2SH evaluation of a P2SH script will obviously not result in
2034  // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
2035  if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
2036  // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
2037  // would be possible, which is not a softfork (and P2SH should be one).
2038  assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2039  assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
2040  if (stack.size() != 1) {
2041  return set_error(serror, SCRIPT_ERR_CLEANSTACK);
2042  }
2043  }
2044 
2045  if (flags & SCRIPT_VERIFY_WITNESS) {
2046  // We can't check for correct unexpected witness data if P2SH was off, so require
2047  // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
2048  // possible, which is not a softfork.
2049  assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2050  if (!hadWitness && !witness->IsNull()) {
2051  return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
2052  }
2053  }
2054 
2055  return set_success(serror);
2056 }
2057 
2058 size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness)
2059 {
2060  if (witversion == 0) {
2061  if (witprogram.size() == WITNESS_V0_KEYHASH_SIZE)
2062  return 1;
2063 
2064  if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.stack.size() > 0) {
2065  CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
2066  return subscript.GetSigOpCount(true);
2067  }
2068  }
2069 
2070  // Future flags may be implemented here.
2071  return 0;
2072 }
2073 
2074 size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags)
2075 {
2076  static const CScriptWitness witnessEmpty;
2077 
2078  if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
2079  return 0;
2080  }
2081  assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2082 
2083  int witnessversion;
2084  std::vector<unsigned char> witnessprogram;
2085  if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2086  return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
2087  }
2088 
2089  if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
2090  CScript::const_iterator pc = scriptSig.begin();
2091  std::vector<unsigned char> data;
2092  while (pc < scriptSig.end()) {
2093  opcodetype opcode;
2094  scriptSig.GetOp(pc, opcode, data);
2095  }
2096  CScript subscript(data.begin(), data.end());
2097  if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
2098  return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
2099  }
2100  }
2101 
2102  return 0;
2103 }
virtual bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const
Definition: interpreter.h:227
Definition: script.h:150
Definition: script.h:79
Definition: script.h:135
unsigned int GetSigOpCount(bool fAccurate) const
Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs as 20 sigops.
Definition: script.cpp:153
CHashWriter TaggedHash(const std::string &tag)
Return a CHashWriter primed for tagged hashes (as specified in BIP 340).
Definition: hash.cpp:89
static size_t WitnessSigOps(int witversion, const std::vector< unsigned char > &witprogram, const CScriptWitness &witness)
Witness v0 (P2WPKH and P2WSH); see BIP 141.
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:637
virtual bool CheckLockTime(const CScriptNum &nLockTime) const
Definition: interpreter.h:237
static const int MAX_PUBKEYS_PER_MULTISIG
Definition: script.h:29
static const uint256 ONE
Definition: uint256.h:130
Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, key path spending; see BIP 341...
static constexpr unsigned int SIZE
secp256k1:
Definition: pubkey.h:37
std::deque< CInv >::iterator it
Definition: script.h:118
const int nVersion
Definition: hash.h:106
void Finalize(Span< unsigned char > output)
Definition: hash.h:30
CSHA1 & Write(const unsigned char *data, size_t len)
Definition: sha1.cpp:154
int getint() const
Definition: script.h:325
Definition: script.h:171
enum ScriptError_t ScriptError
virtual bool VerifySchnorrSignature(Span< const unsigned char > sig, const XOnlyPubKey &pubkey, const uint256 &sighash) const
constexpr C * end() const noexcept
Definition: span.h:142
iterator insert(iterator pos, const T &value)
Definition: prevector.h:347
static constexpr size_t WITNESS_V1_TAPROOT_SIZE
Definition: interpreter.h:212
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< unsigned char > &vchRet) const
Definition: script.h:486
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:1110
bool IsPayToScriptHash() const
Definition: script.cpp:201
bool SignatureHashSchnorr(uint256 &hash_out, const ScriptExecutionData &execdata, const T &tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData &cache)
void Finalize(Span< unsigned char > output)
Definition: hash.h:55
Definition: script.h:96
Definition: script.h:89
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:31
bool CheckSchnorrSignature(Span< const unsigned char > sig, Span< const unsigned char > pubkey, SigVersion sigversion, const ScriptExecutionData &execdata, ScriptError *serror=nullptr) const override
Definition: script.h:85
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
size_t CountWitnessSigOps(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags)
std::vector< CTxIn > vin
Definition: transaction.h:355
static const uint32_t SEQUENCE_FINAL
Definition: transaction.h:75
Definition: script.h:149
bool m_annex_present
Whether an annex is present.
Definition: interpreter.h:199
uint256 GetSHA256()
Compute the SHA256 hash of all data written to this object.
Definition: hash.h:133
static void popstack(std::vector< valtype > &stack)
Definition: interpreter.cpp:56
Definition: script.h:77
Definition: script.h:156
Definition: script.h:83
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
Definition: transaction.h:80
static bool IsCompressedPubKey(const valtype &vchPubKey)
Definition: interpreter.cpp:85
constexpr std::size_t size() const noexcept
Definition: span.h:153
Definition: script.h:78
std::vector< std::vector< unsigned char > > stack
Definition: script.h:560
int64_t m_validation_weight_left
How much validation weight is left (decremented for every successful non-empty signature check)...
Definition: interpreter.h:206
std::vector< CTxOut > m_spent_outputs
Definition: interpreter.h:163
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Definition: interpreter.h:215
static bool CheckLowS(const std::vector< unsigned char > &vchSig)
Check whether a signature is normalized (lower-S).
Definition: pubkey.cpp:301
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, script path spending, leaf version 0xc0; see...
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
Definition: script.cpp:220
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:24
static constexpr size_t TAPROOT_CONTROL_BASE_SIZE
Definition: interpreter.h:216
bool IsNull() const
Definition: script.h:565
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:23
bool IsOpSuccess(const opcodetype &opcode)
Test for OP_SUCCESSx opcodes as defined by BIP342.
Definition: script.cpp:335
Definition: script.h:170
bool VerifySchnorr(const uint256 &msg, Span< const unsigned char > sigbytes) const
Verify a Schnorr signature against this public key.
Definition: pubkey.cpp:176
unsigned char * begin()
Definition: uint256.h:58
static bool CheckMinimalPush(const valtype &data, opcodetype opcode)
uint32_t m_codeseparator_pos
Opcode position of the last executed OP_CODESEPARATOR (or 0xFFFFFFFF if none executed).
Definition: interpreter.h:194
Definition: script.h:91
unsigned char * end()
Definition: uint256.h:63
Definition: script.h:87
static const int MAX_OPS_PER_SCRIPT
Definition: script.h:26
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1116
void Serialize(Stream &s, char a)
Definition: serialize.h:227
Definition: script.h:136
bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const override
static constexpr size_t TAPROOT_CONTROL_NODE_SIZE
Definition: interpreter.h:217
static bool EvalChecksig(const valtype &sig, const valtype &pubkey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, ScriptExecutionData &execdata, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptError *serror, bool &success)
Helper for OP_CHECKSIG, OP_CHECKSIGVERIFY, and (in Tapscript) OP_CHECKSIGADD.
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
Definition: script.h:80
bool m_annex_init
Whether m_annex_present and (when needed) m_annex_hash are initialized.
Definition: interpreter.h:197
iterator end()
Definition: prevector.h:292
uint256 m_tapleaf_hash
The tapleaf hash.
Definition: interpreter.h:189
Definition: script.h:157
opcodetype
Script opcodes.
Definition: script.h:65
virtual bool VerifyECDSASignature(const std::vector< unsigned char > &vchSig, const CPubKey &vchPubKey, const uint256 &sighash) const
static constexpr unsigned int COMPRESSED_SIZE
Definition: pubkey.h:38
static bool VerifyTaprootCommitment(const std::vector< unsigned char > &control, const std::vector< unsigned char > &program, const CScript &script, uint256 &tapleaf_hash)
Definition: script.h:127
bool CheckSignatureEncoding(const std::vector< unsigned char > &vchSig, unsigned int flags, ScriptError *serror)
bool IsPushOnly(const_iterator pc) const
Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical).
Definition: script.cpp:236
static constexpr uint8_t TAPROOT_LEAF_MASK
Definition: interpreter.h:214
bool IsValid() const
Definition: pubkey.h:175
An encapsulated public key.
Definition: pubkey.h:31
Definition: script.h:82
bool m_bip143_segwit_ready
Whether the 3 fields above are initialized.
Definition: interpreter.h:161
Definition: script.h:75
virtual bool CheckSchnorrSignature(Span< const unsigned char > sig, Span< const unsigned char > pubkey, SigVersion sigversion, const ScriptExecutionData &execdata, ScriptError *serror=nullptr) const
Definition: interpreter.h:232
Definition: script.h:94
std::vector< unsigned char > getvch() const
Definition: script.h:334
#define stacktop(i)
Script is a stack machine (like Forth) that evaluates a predicate returning a bool indicating valid o...
Definition: interpreter.cpp:54
bool CheckLockTime(const CScriptNum &nLockTime) const override
static bool EvalChecksigPreTapscript(const valtype &vchSig, const valtype &vchPubKey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptError *serror, bool &fSuccess)
static const CHashWriter HASHER_TAPLEAF
static bool IsValidSignatureEncoding(const std::vector< unsigned char > &sig)
A canonical signature exists of: <30> <total len>=""> <02> <len r>=""> <R> <02> <len s>=""> <S> <hash...
Definition: script.h:154
An output of a transaction.
Definition: transaction.h:128
static constexpr size_t WITNESS_V0_SCRIPTHASH_SIZE
Signature hash sizes.
Definition: interpreter.h:210
static const int MAX_SCRIPT_SIZE
Definition: script.h:32
Definition: script.h:122
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG
Definition: transaction.h:85
static const int MAX_STACK_SIZE
Definition: script.h:35
static constexpr uint64_t VALIDATION_WEIGHT_PER_SIGOP_PASSED
Definition: script.h:53
bool m_bip341_taproot_ready
Whether the 5 fields above are initialized.
Definition: interpreter.h:156
Definition: script.h:155
static constexpr size_t TAPROOT_CONTROL_MAX_SIZE
Definition: interpreter.h:219
#define altstacktop(i)
Definition: interpreter.cpp:55
static bool ExecuteWitnessScript(const Span< const valtype > &stack_span, const CScript &scriptPubKey, unsigned int flags, SigVersion sigversion, const BaseSignatureChecker &checker, ScriptExecutionData &execdata, ScriptError *serror)
bool m_codeseparator_pos_init
Whether m_codeseparator_pos is initialized.
Definition: interpreter.h:192
CRIPEMD160 & Write(const unsigned char *data, size_t len)
Definition: ripemd160.cpp:247
static const CHashWriter HASHER_TAPTWEAK
int flags
Definition: bitcoin-tx.cpp:506
constexpr C * begin() const noexcept
Definition: span.h:141
uint256 GetHash()
Compute the double-SHA256 hash of all data written to this object.
Definition: hash.h:122
Definition: script.h:84
256-bit opaque blob.
Definition: uint256.h:124
static bool VerifyWitnessProgram(const CScriptWitness &witness, int witversion, const std::vector< unsigned char > &program, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror, bool is_p2sh)
uint256 SHA256Uint256(const uint256 &input)
Single-SHA256 a 32-byte input (represented as uint256).
Definition: hash.cpp:82
static const uint32_t SEQUENCE_LOCKTIME_MASK
Definition: transaction.h:89
bool Verify(const uint256 &hash, const std::vector< unsigned char > &vchSig) const
Verify a DER signature (~72 bytes).
Definition: pubkey.cpp:191
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
static constexpr size_t WITNESS_V0_KEYHASH_SIZE
Definition: interpreter.h:211
static constexpr unsigned int ANNEX_TAG
Definition: script.h:50
static bool IsCompressedOrUncompressedPubKey(const valtype &vchPubKey)
Definition: interpreter.cpp:63
static bool EvalChecksigTapscript(const valtype &sig, const valtype &pubkey, ScriptExecutionData &execdata, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptError *serror, bool &success)
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
bool m_spent_outputs_ready
Whether m_spent_outputs is initialized.
Definition: interpreter.h:165
bool empty() const
Definition: prevector.h:286
T & SpanPopBack(Span< T > &span)
Pop the last element off a span, and return a reference to that element.
Definition: span.h:201
static bool CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError *serror)
uint256 SignatureHash(const CScript &scriptCode, const T &txTo, unsigned int nIn, int nHashType, const CAmount &amount, SigVersion sigversion, const PrecomputedTransactionData *cache)
Definition: script.h:81
static const CHashWriter HASHER_TAPSIGHASH
std::vector< unsigned char > valtype
Definition: interpreter.cpp:15
A hasher class for SHA1.
Definition: sha1.h:12
virtual bool CheckSequence(const CScriptNum &nSequence) const
Definition: interpreter.h:242
iterator begin()
Definition: prevector.h:290
bool m_tapleaf_hash_init
Whether m_tapleaf_hash is initialized.
Definition: interpreter.h:187
A mutable version of CTransaction.
Definition: transaction.h:353
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:100
size_type size() const
Definition: prevector.h:282
static constexpr uint64_t VALIDATION_WEIGHT_OFFSET
Definition: script.h:56
PrecomputedTransactionData()=default
static bool IsLowDERSignature(const valtype &vchSig, ScriptError *serror)
Definition: script.h:88
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:82
static const unsigned int LOCKTIME_THRESHOLD
Definition: script.h:39
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:259
bool CheckSequence(const CScriptNum &nSequence) const override
A hasher class for Bitcoin&#39;s 160-bit hash (SHA-256 + RIPEMD-160).
Definition: hash.h:49
Definition: script.h:137
Definition: script.h:86
void Init(const T &tx, std::vector< CTxOut > &&spent_outputs)
if(it !=peer.m_getdata_requests.end() &&!pfrom.fPauseSend)
static const CHashWriter HASHER_TAPBRANCH
A hasher class for SHA-256.
Definition: sha256.h:13
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror)
int FindAndDelete(CScript &script, const CScript &b)
Definition: script.h:68
bool CastToBool(const valtype &vch)
Definition: interpreter.cpp:35
CHash160 & Write(Span< const unsigned char > input)
Definition: hash.h:62
CHash256 & Write(Span< const unsigned char > input)
Definition: hash.h:37
uint256 m_annex_hash
Hash of the annex data.
Definition: interpreter.h:201
static bool IsDefinedHashtypeSignature(const valtype &vchSig)
Definition: script.h:153
Definition: script.h:90
A hasher class for RIPEMD-160.
Definition: ripemd160.h:12
bool m_validation_weight_left_init
Whether m_validation_weight_left is initialized.
Definition: interpreter.h:204
Definition: script.h:117
SigVersion
Definition: interpreter.h:176
Span< A > constexpr MakeSpan(A(&a)[N])
MakeSpan for arrays:
Definition: span.h:193