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 
350 static bool EvalChecksig(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)
351 {
352  // Subset of script starting at the most recent codeseparator
353  CScript scriptCode(pbegincodehash, pend);
354 
355  // Drop the signature in pre-segwit scripts but not segwit scripts
356  if (sigversion == SigVersion::BASE) {
357  int found = FindAndDelete(scriptCode, CScript() << vchSig);
358  if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
359  return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
360  }
361 
362  if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
363  //serror is set
364  return false;
365  }
366  fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
367 
368  if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
369  return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
370 
371  return true;
372 }
373 
374 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
375 {
376  static const CScriptNum bnZero(0);
377  static const CScriptNum bnOne(1);
378  // static const CScriptNum bnFalse(0);
379  // static const CScriptNum bnTrue(1);
380  static const valtype vchFalse(0);
381  // static const valtype vchZero(0);
382  static const valtype vchTrue(1, 1);
383 
384  CScript::const_iterator pc = script.begin();
385  CScript::const_iterator pend = script.end();
386  CScript::const_iterator pbegincodehash = script.begin();
387  opcodetype opcode;
388  valtype vchPushValue;
389  ConditionStack vfExec;
390  std::vector<valtype> altstack;
391  set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
392  if (script.size() > MAX_SCRIPT_SIZE)
393  return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
394  int nOpCount = 0;
395  bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
396 
397  try
398  {
399  while (pc < pend)
400  {
401  bool fExec = vfExec.all_true();
402 
403  //
404  // Read instruction
405  //
406  if (!script.GetOp(pc, opcode, vchPushValue))
407  return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
408  if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
409  return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
410 
411  // Note how OP_RESERVED does not count towards the opcode limit.
412  if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
413  return set_error(serror, SCRIPT_ERR_OP_COUNT);
414 
415  if (opcode == OP_CAT ||
416  opcode == OP_SUBSTR ||
417  opcode == OP_LEFT ||
418  opcode == OP_RIGHT ||
419  opcode == OP_INVERT ||
420  opcode == OP_AND ||
421  opcode == OP_OR ||
422  opcode == OP_XOR ||
423  opcode == OP_2MUL ||
424  opcode == OP_2DIV ||
425  opcode == OP_MUL ||
426  opcode == OP_DIV ||
427  opcode == OP_MOD ||
428  opcode == OP_LSHIFT ||
429  opcode == OP_RSHIFT)
430  return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes (CVE-2010-5137).
431 
432  // With SCRIPT_VERIFY_CONST_SCRIPTCODE, OP_CODESEPARATOR in non-segwit script is rejected even in an unexecuted branch
433  if (opcode == OP_CODESEPARATOR && sigversion == SigVersion::BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
434  return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
435 
436  if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
437  if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
438  return set_error(serror, SCRIPT_ERR_MINIMALDATA);
439  }
440  stack.push_back(vchPushValue);
441  } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
442  switch (opcode)
443  {
444  //
445  // Push value
446  //
447  case OP_1NEGATE:
448  case OP_1:
449  case OP_2:
450  case OP_3:
451  case OP_4:
452  case OP_5:
453  case OP_6:
454  case OP_7:
455  case OP_8:
456  case OP_9:
457  case OP_10:
458  case OP_11:
459  case OP_12:
460  case OP_13:
461  case OP_14:
462  case OP_15:
463  case OP_16:
464  {
465  // ( -- value)
466  CScriptNum bn((int)opcode - (int)(OP_1 - 1));
467  stack.push_back(bn.getvch());
468  // The result of these opcodes should always be the minimal way to push the data
469  // they push, so no need for a CheckMinimalPush here.
470  }
471  break;
472 
473 
474  //
475  // Control
476  //
477  case OP_NOP:
478  break;
479 
481  {
482  if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
483  // not enabled; treat as a NOP2
484  break;
485  }
486 
487  if (stack.size() < 1)
488  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
489 
490  // Note that elsewhere numeric opcodes are limited to
491  // operands in the range -2**31+1 to 2**31-1, however it is
492  // legal for opcodes to produce results exceeding that
493  // range. This limitation is implemented by CScriptNum's
494  // default 4-byte limit.
495  //
496  // If we kept to that limit we'd have a year 2038 problem,
497  // even though the nLockTime field in transactions
498  // themselves is uint32 which only becomes meaningless
499  // after the year 2106.
500  //
501  // Thus as a special case we tell CScriptNum to accept up
502  // to 5-byte bignums, which are good until 2**39-1, well
503  // beyond the 2**32-1 limit of the nLockTime field itself.
504  const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
505 
506  // In the rare event that the argument may be < 0 due to
507  // some arithmetic being done first, you can always use
508  // 0 MAX CHECKLOCKTIMEVERIFY.
509  if (nLockTime < 0)
510  return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
511 
512  // Actually compare the specified lock time with the transaction.
513  if (!checker.CheckLockTime(nLockTime))
514  return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
515 
516  break;
517  }
518 
520  {
521  if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
522  // not enabled; treat as a NOP3
523  break;
524  }
525 
526  if (stack.size() < 1)
527  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
528 
529  // nSequence, like nLockTime, is a 32-bit unsigned integer
530  // field. See the comment in CHECKLOCKTIMEVERIFY regarding
531  // 5-byte numeric operands.
532  const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
533 
534  // In the rare event that the argument may be < 0 due to
535  // some arithmetic being done first, you can always use
536  // 0 MAX CHECKSEQUENCEVERIFY.
537  if (nSequence < 0)
538  return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
539 
540  // To provide for future soft-fork extensibility, if the
541  // operand has the disabled lock-time flag set,
542  // CHECKSEQUENCEVERIFY behaves as a NOP.
543  if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
544  break;
545 
546  // Compare the specified sequence number with the input.
547  if (!checker.CheckSequence(nSequence))
548  return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
549 
550  break;
551  }
552 
553  case OP_NOP1: case OP_NOP4: case OP_NOP5:
554  case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
555  {
557  return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
558  }
559  break;
560 
561  case OP_IF:
562  case OP_NOTIF:
563  {
564  // <expression> if [statements] [else [statements]] endif
565  bool fValue = false;
566  if (fExec)
567  {
568  if (stack.size() < 1)
569  return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
570  valtype& vch = stacktop(-1);
571  if (sigversion == SigVersion::WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
572  if (vch.size() > 1)
573  return set_error(serror, SCRIPT_ERR_MINIMALIF);
574  if (vch.size() == 1 && vch[0] != 1)
575  return set_error(serror, SCRIPT_ERR_MINIMALIF);
576  }
577  fValue = CastToBool(vch);
578  if (opcode == OP_NOTIF)
579  fValue = !fValue;
580  popstack(stack);
581  }
582  vfExec.push_back(fValue);
583  }
584  break;
585 
586  case OP_ELSE:
587  {
588  if (vfExec.empty())
589  return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
590  vfExec.toggle_top();
591  }
592  break;
593 
594  case OP_ENDIF:
595  {
596  if (vfExec.empty())
597  return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
598  vfExec.pop_back();
599  }
600  break;
601 
602  case OP_VERIFY:
603  {
604  // (true -- ) or
605  // (false -- false) and return
606  if (stack.size() < 1)
607  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
608  bool fValue = CastToBool(stacktop(-1));
609  if (fValue)
610  popstack(stack);
611  else
612  return set_error(serror, SCRIPT_ERR_VERIFY);
613  }
614  break;
615 
616  case OP_RETURN:
617  {
618  return set_error(serror, SCRIPT_ERR_OP_RETURN);
619  }
620  break;
621 
622 
623  //
624  // Stack ops
625  //
626  case OP_TOALTSTACK:
627  {
628  if (stack.size() < 1)
629  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
630  altstack.push_back(stacktop(-1));
631  popstack(stack);
632  }
633  break;
634 
635  case OP_FROMALTSTACK:
636  {
637  if (altstack.size() < 1)
638  return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
639  stack.push_back(altstacktop(-1));
640  popstack(altstack);
641  }
642  break;
643 
644  case OP_2DROP:
645  {
646  // (x1 x2 -- )
647  if (stack.size() < 2)
648  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
649  popstack(stack);
650  popstack(stack);
651  }
652  break;
653 
654  case OP_2DUP:
655  {
656  // (x1 x2 -- x1 x2 x1 x2)
657  if (stack.size() < 2)
658  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
659  valtype vch1 = stacktop(-2);
660  valtype vch2 = stacktop(-1);
661  stack.push_back(vch1);
662  stack.push_back(vch2);
663  }
664  break;
665 
666  case OP_3DUP:
667  {
668  // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
669  if (stack.size() < 3)
670  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
671  valtype vch1 = stacktop(-3);
672  valtype vch2 = stacktop(-2);
673  valtype vch3 = stacktop(-1);
674  stack.push_back(vch1);
675  stack.push_back(vch2);
676  stack.push_back(vch3);
677  }
678  break;
679 
680  case OP_2OVER:
681  {
682  // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
683  if (stack.size() < 4)
684  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
685  valtype vch1 = stacktop(-4);
686  valtype vch2 = stacktop(-3);
687  stack.push_back(vch1);
688  stack.push_back(vch2);
689  }
690  break;
691 
692  case OP_2ROT:
693  {
694  // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
695  if (stack.size() < 6)
696  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
697  valtype vch1 = stacktop(-6);
698  valtype vch2 = stacktop(-5);
699  stack.erase(stack.end()-6, stack.end()-4);
700  stack.push_back(vch1);
701  stack.push_back(vch2);
702  }
703  break;
704 
705  case OP_2SWAP:
706  {
707  // (x1 x2 x3 x4 -- x3 x4 x1 x2)
708  if (stack.size() < 4)
709  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
710  swap(stacktop(-4), stacktop(-2));
711  swap(stacktop(-3), stacktop(-1));
712  }
713  break;
714 
715  case OP_IFDUP:
716  {
717  // (x - 0 | x x)
718  if (stack.size() < 1)
719  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
720  valtype vch = stacktop(-1);
721  if (CastToBool(vch))
722  stack.push_back(vch);
723  }
724  break;
725 
726  case OP_DEPTH:
727  {
728  // -- stacksize
729  CScriptNum bn(stack.size());
730  stack.push_back(bn.getvch());
731  }
732  break;
733 
734  case OP_DROP:
735  {
736  // (x -- )
737  if (stack.size() < 1)
738  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
739  popstack(stack);
740  }
741  break;
742 
743  case OP_DUP:
744  {
745  // (x -- x x)
746  if (stack.size() < 1)
747  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
748  valtype vch = stacktop(-1);
749  stack.push_back(vch);
750  }
751  break;
752 
753  case OP_NIP:
754  {
755  // (x1 x2 -- x2)
756  if (stack.size() < 2)
757  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
758  stack.erase(stack.end() - 2);
759  }
760  break;
761 
762  case OP_OVER:
763  {
764  // (x1 x2 -- x1 x2 x1)
765  if (stack.size() < 2)
766  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
767  valtype vch = stacktop(-2);
768  stack.push_back(vch);
769  }
770  break;
771 
772  case OP_PICK:
773  case OP_ROLL:
774  {
775  // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
776  // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
777  if (stack.size() < 2)
778  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
779  int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
780  popstack(stack);
781  if (n < 0 || n >= (int)stack.size())
782  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
783  valtype vch = stacktop(-n-1);
784  if (opcode == OP_ROLL)
785  stack.erase(stack.end()-n-1);
786  stack.push_back(vch);
787  }
788  break;
789 
790  case OP_ROT:
791  {
792  // (x1 x2 x3 -- x2 x3 x1)
793  // x2 x1 x3 after first swap
794  // x2 x3 x1 after second swap
795  if (stack.size() < 3)
796  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
797  swap(stacktop(-3), stacktop(-2));
798  swap(stacktop(-2), stacktop(-1));
799  }
800  break;
801 
802  case OP_SWAP:
803  {
804  // (x1 x2 -- x2 x1)
805  if (stack.size() < 2)
806  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
807  swap(stacktop(-2), stacktop(-1));
808  }
809  break;
810 
811  case OP_TUCK:
812  {
813  // (x1 x2 -- x2 x1 x2)
814  if (stack.size() < 2)
815  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
816  valtype vch = stacktop(-1);
817  stack.insert(stack.end()-2, vch);
818  }
819  break;
820 
821 
822  case OP_SIZE:
823  {
824  // (in -- in size)
825  if (stack.size() < 1)
826  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
827  CScriptNum bn(stacktop(-1).size());
828  stack.push_back(bn.getvch());
829  }
830  break;
831 
832 
833  //
834  // Bitwise logic
835  //
836  case OP_EQUAL:
837  case OP_EQUALVERIFY:
838  //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
839  {
840  // (x1 x2 - bool)
841  if (stack.size() < 2)
842  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
843  valtype& vch1 = stacktop(-2);
844  valtype& vch2 = stacktop(-1);
845  bool fEqual = (vch1 == vch2);
846  // OP_NOTEQUAL is disabled because it would be too easy to say
847  // something like n != 1 and have some wiseguy pass in 1 with extra
848  // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
849  //if (opcode == OP_NOTEQUAL)
850  // fEqual = !fEqual;
851  popstack(stack);
852  popstack(stack);
853  stack.push_back(fEqual ? vchTrue : vchFalse);
854  if (opcode == OP_EQUALVERIFY)
855  {
856  if (fEqual)
857  popstack(stack);
858  else
859  return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
860  }
861  }
862  break;
863 
864 
865  //
866  // Numeric
867  //
868  case OP_1ADD:
869  case OP_1SUB:
870  case OP_NEGATE:
871  case OP_ABS:
872  case OP_NOT:
873  case OP_0NOTEQUAL:
874  {
875  // (in -- out)
876  if (stack.size() < 1)
877  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
878  CScriptNum bn(stacktop(-1), fRequireMinimal);
879  switch (opcode)
880  {
881  case OP_1ADD: bn += bnOne; break;
882  case OP_1SUB: bn -= bnOne; break;
883  case OP_NEGATE: bn = -bn; break;
884  case OP_ABS: if (bn < bnZero) bn = -bn; break;
885  case OP_NOT: bn = (bn == bnZero); break;
886  case OP_0NOTEQUAL: bn = (bn != bnZero); break;
887  default: assert(!"invalid opcode"); break;
888  }
889  popstack(stack);
890  stack.push_back(bn.getvch());
891  }
892  break;
893 
894  case OP_ADD:
895  case OP_SUB:
896  case OP_BOOLAND:
897  case OP_BOOLOR:
898  case OP_NUMEQUAL:
899  case OP_NUMEQUALVERIFY:
900  case OP_NUMNOTEQUAL:
901  case OP_LESSTHAN:
902  case OP_GREATERTHAN:
903  case OP_LESSTHANOREQUAL:
905  case OP_MIN:
906  case OP_MAX:
907  {
908  // (x1 x2 -- out)
909  if (stack.size() < 2)
910  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
911  CScriptNum bn1(stacktop(-2), fRequireMinimal);
912  CScriptNum bn2(stacktop(-1), fRequireMinimal);
913  CScriptNum bn(0);
914  switch (opcode)
915  {
916  case OP_ADD:
917  bn = bn1 + bn2;
918  break;
919 
920  case OP_SUB:
921  bn = bn1 - bn2;
922  break;
923 
924  case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
925  case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
926  case OP_NUMEQUAL: bn = (bn1 == bn2); break;
927  case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
928  case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
929  case OP_LESSTHAN: bn = (bn1 < bn2); break;
930  case OP_GREATERTHAN: bn = (bn1 > bn2); break;
931  case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
932  case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
933  case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
934  case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
935  default: assert(!"invalid opcode"); break;
936  }
937  popstack(stack);
938  popstack(stack);
939  stack.push_back(bn.getvch());
940 
941  if (opcode == OP_NUMEQUALVERIFY)
942  {
943  if (CastToBool(stacktop(-1)))
944  popstack(stack);
945  else
946  return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
947  }
948  }
949  break;
950 
951  case OP_WITHIN:
952  {
953  // (x min max -- out)
954  if (stack.size() < 3)
955  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
956  CScriptNum bn1(stacktop(-3), fRequireMinimal);
957  CScriptNum bn2(stacktop(-2), fRequireMinimal);
958  CScriptNum bn3(stacktop(-1), fRequireMinimal);
959  bool fValue = (bn2 <= bn1 && bn1 < bn3);
960  popstack(stack);
961  popstack(stack);
962  popstack(stack);
963  stack.push_back(fValue ? vchTrue : vchFalse);
964  }
965  break;
966 
967 
968  //
969  // Crypto
970  //
971  case OP_RIPEMD160:
972  case OP_SHA1:
973  case OP_SHA256:
974  case OP_HASH160:
975  case OP_HASH256:
976  {
977  // (in -- hash)
978  if (stack.size() < 1)
979  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
980  valtype& vch = stacktop(-1);
981  valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
982  if (opcode == OP_RIPEMD160)
983  CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
984  else if (opcode == OP_SHA1)
985  CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
986  else if (opcode == OP_SHA256)
987  CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
988  else if (opcode == OP_HASH160)
989  CHash160().Write(vch).Finalize(vchHash);
990  else if (opcode == OP_HASH256)
991  CHash256().Write(vch).Finalize(vchHash);
992  popstack(stack);
993  stack.push_back(vchHash);
994  }
995  break;
996 
997  case OP_CODESEPARATOR:
998  {
999  // If SCRIPT_VERIFY_CONST_SCRIPTCODE flag is set, use of OP_CODESEPARATOR is rejected in pre-segwit
1000  // script, even in an unexecuted branch (this is checked above the opcode case statement).
1001 
1002  // Hash starts after the code separator
1003  pbegincodehash = pc;
1004  }
1005  break;
1006 
1007  case OP_CHECKSIG:
1008  case OP_CHECKSIGVERIFY:
1009  {
1010  // (sig pubkey -- bool)
1011  if (stack.size() < 2)
1012  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1013 
1014  valtype& vchSig = stacktop(-2);
1015  valtype& vchPubKey = stacktop(-1);
1016 
1017  bool fSuccess = true;
1018  if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, flags, checker, sigversion, serror, fSuccess)) return false;
1019  popstack(stack);
1020  popstack(stack);
1021  stack.push_back(fSuccess ? vchTrue : vchFalse);
1022  if (opcode == OP_CHECKSIGVERIFY)
1023  {
1024  if (fSuccess)
1025  popstack(stack);
1026  else
1027  return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
1028  }
1029  }
1030  break;
1031 
1032  case OP_CHECKMULTISIG:
1034  {
1035  // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1036 
1037  int i = 1;
1038  if ((int)stack.size() < i)
1039  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1040 
1041  int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1042  if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
1043  return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
1044  nOpCount += nKeysCount;
1045  if (nOpCount > MAX_OPS_PER_SCRIPT)
1046  return set_error(serror, SCRIPT_ERR_OP_COUNT);
1047  int ikey = ++i;
1048  // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
1049  // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
1050  int ikey2 = nKeysCount + 2;
1051  i += nKeysCount;
1052  if ((int)stack.size() < i)
1053  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1054 
1055  int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1056  if (nSigsCount < 0 || nSigsCount > nKeysCount)
1057  return set_error(serror, SCRIPT_ERR_SIG_COUNT);
1058  int isig = ++i;
1059  i += nSigsCount;
1060  if ((int)stack.size() < i)
1061  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1062 
1063  // Subset of script starting at the most recent codeseparator
1064  CScript scriptCode(pbegincodehash, pend);
1065 
1066  // Drop the signature in pre-segwit scripts but not segwit scripts
1067  for (int k = 0; k < nSigsCount; k++)
1068  {
1069  valtype& vchSig = stacktop(-isig-k);
1070  if (sigversion == SigVersion::BASE) {
1071  int found = FindAndDelete(scriptCode, CScript() << vchSig);
1072  if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
1073  return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
1074  }
1075  }
1076 
1077  bool fSuccess = true;
1078  while (fSuccess && nSigsCount > 0)
1079  {
1080  valtype& vchSig = stacktop(-isig);
1081  valtype& vchPubKey = stacktop(-ikey);
1082 
1083  // Note how this makes the exact order of pubkey/signature evaluation
1084  // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
1085  // See the script_(in)valid tests for details.
1086  if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
1087  // serror is set
1088  return false;
1089  }
1090 
1091  // Check signature
1092  bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
1093 
1094  if (fOk) {
1095  isig++;
1096  nSigsCount--;
1097  }
1098  ikey++;
1099  nKeysCount--;
1100 
1101  // If there are more signatures left than keys left,
1102  // then too many signatures have failed. Exit early,
1103  // without checking any further signatures.
1104  if (nSigsCount > nKeysCount)
1105  fSuccess = false;
1106  }
1107 
1108  // Clean up stack of actual arguments
1109  while (i-- > 1) {
1110  // If the operation failed, we require that all signatures must be empty vector
1111  if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
1112  return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
1113  if (ikey2 > 0)
1114  ikey2--;
1115  popstack(stack);
1116  }
1117 
1118  // A bug causes CHECKMULTISIG to consume one extra argument
1119  // whose contents were not checked in any way.
1120  //
1121  // Unfortunately this is a potential source of mutability,
1122  // so optionally verify it is exactly equal to zero prior
1123  // to removing it from the stack.
1124  if (stack.size() < 1)
1125  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1126  if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1127  return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1128  popstack(stack);
1129 
1130  stack.push_back(fSuccess ? vchTrue : vchFalse);
1131 
1132  if (opcode == OP_CHECKMULTISIGVERIFY)
1133  {
1134  if (fSuccess)
1135  popstack(stack);
1136  else
1137  return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1138  }
1139  }
1140  break;
1141 
1142  default:
1143  return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1144  }
1145 
1146  // Size limits
1147  if (stack.size() + altstack.size() > MAX_STACK_SIZE)
1148  return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1149  }
1150  }
1151  catch (...)
1152  {
1153  return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1154  }
1155 
1156  if (!vfExec.empty())
1157  return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1158 
1159  return set_success(serror);
1160 }
1161 
1162 namespace {
1163 
1168 template <class T>
1169 class CTransactionSignatureSerializer
1170 {
1171 private:
1172  const T& txTo;
1173  const CScript& scriptCode;
1174  const unsigned int nIn;
1175  const bool fAnyoneCanPay;
1176  const bool fHashSingle;
1177  const bool fHashNone;
1178 
1179 public:
1180  CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1181  txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1182  fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1183  fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1184  fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1185 
1187  template<typename S>
1188  void SerializeScriptCode(S &s) const {
1189  CScript::const_iterator it = scriptCode.begin();
1190  CScript::const_iterator itBegin = it;
1191  opcodetype opcode;
1192  unsigned int nCodeSeparators = 0;
1193  while (scriptCode.GetOp(it, opcode)) {
1194  if (opcode == OP_CODESEPARATOR)
1195  nCodeSeparators++;
1196  }
1197  ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1198  it = itBegin;
1199  while (scriptCode.GetOp(it, opcode)) {
1200  if (opcode == OP_CODESEPARATOR) {
1201  s.write((char*)&itBegin[0], it-itBegin-1);
1202  itBegin = it;
1203  }
1204  }
1205  if (itBegin != scriptCode.end())
1206  s.write((char*)&itBegin[0], it-itBegin);
1207  }
1208 
1210  template<typename S>
1211  void SerializeInput(S &s, unsigned int nInput) const {
1212  // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1213  if (fAnyoneCanPay)
1214  nInput = nIn;
1215  // Serialize the prevout
1216  ::Serialize(s, txTo.vin[nInput].prevout);
1217  // Serialize the script
1218  if (nInput != nIn)
1219  // Blank out other inputs' signatures
1220  ::Serialize(s, CScript());
1221  else
1222  SerializeScriptCode(s);
1223  // Serialize the nSequence
1224  if (nInput != nIn && (fHashSingle || fHashNone))
1225  // let the others update at will
1226  ::Serialize(s, (int)0);
1227  else
1228  ::Serialize(s, txTo.vin[nInput].nSequence);
1229  }
1230 
1232  template<typename S>
1233  void SerializeOutput(S &s, unsigned int nOutput) const {
1234  if (fHashSingle && nOutput != nIn)
1235  // Do not lock-in the txout payee at other indices as txin
1236  ::Serialize(s, CTxOut());
1237  else
1238  ::Serialize(s, txTo.vout[nOutput]);
1239  }
1240 
1242  template<typename S>
1243  void Serialize(S &s) const {
1244  // Serialize nVersion
1245  ::Serialize(s, txTo.nVersion);
1246  // Serialize vin
1247  unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1248  ::WriteCompactSize(s, nInputs);
1249  for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1250  SerializeInput(s, nInput);
1251  // Serialize vout
1252  unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1253  ::WriteCompactSize(s, nOutputs);
1254  for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1255  SerializeOutput(s, nOutput);
1256  // Serialize nLockTime
1257  ::Serialize(s, txTo.nLockTime);
1258  }
1259 };
1260 
1261 template <class T>
1262 uint256 GetPrevoutHash(const T& txTo)
1263 {
1264  CHashWriter ss(SER_GETHASH, 0);
1265  for (const auto& txin : txTo.vin) {
1266  ss << txin.prevout;
1267  }
1268  return ss.GetHash();
1269 }
1270 
1271 template <class T>
1272 uint256 GetSequenceHash(const T& txTo)
1273 {
1274  CHashWriter ss(SER_GETHASH, 0);
1275  for (const auto& txin : txTo.vin) {
1276  ss << txin.nSequence;
1277  }
1278  return ss.GetHash();
1279 }
1280 
1281 template <class T>
1282 uint256 GetOutputsHash(const T& txTo)
1283 {
1284  CHashWriter ss(SER_GETHASH, 0);
1285  for (const auto& txout : txTo.vout) {
1286  ss << txout;
1287  }
1288  return ss.GetHash();
1289 }
1290 
1291 } // namespace
1292 
1293 template <class T>
1295 {
1296  assert(!m_ready);
1297 
1298  // Cache is calculated only for transactions with witness
1299  if (txTo.HasWitness()) {
1300  hashPrevouts = GetPrevoutHash(txTo);
1301  hashSequence = GetSequenceHash(txTo);
1302  hashOutputs = GetOutputsHash(txTo);
1303  }
1304 
1305  m_ready = true;
1306 }
1307 
1308 template <class T>
1310 {
1311  Init(txTo);
1312 }
1313 
1314 // explicit instantiation
1315 template void PrecomputedTransactionData::Init(const CTransaction& txTo);
1316 template void PrecomputedTransactionData::Init(const CMutableTransaction& txTo);
1319 
1320 template <class T>
1321 uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1322 {
1323  assert(nIn < txTo.vin.size());
1324 
1325  if (sigversion == SigVersion::WITNESS_V0) {
1326  uint256 hashPrevouts;
1327  uint256 hashSequence;
1328  uint256 hashOutputs;
1329  const bool cacheready = cache && cache->m_ready;
1330 
1331  if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1332  hashPrevouts = cacheready ? cache->hashPrevouts : GetPrevoutHash(txTo);
1333  }
1334 
1335  if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1336  hashSequence = cacheready ? cache->hashSequence : GetSequenceHash(txTo);
1337  }
1338 
1339 
1340  if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1341  hashOutputs = cacheready ? cache->hashOutputs : GetOutputsHash(txTo);
1342  } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
1343  CHashWriter ss(SER_GETHASH, 0);
1344  ss << txTo.vout[nIn];
1345  hashOutputs = ss.GetHash();
1346  }
1347 
1348  CHashWriter ss(SER_GETHASH, 0);
1349  // Version
1350  ss << txTo.nVersion;
1351  // Input prevouts/nSequence (none/all, depending on flags)
1352  ss << hashPrevouts;
1353  ss << hashSequence;
1354  // The input being signed (replacing the scriptSig with scriptCode + amount)
1355  // The prevout may already be contained in hashPrevout, and the nSequence
1356  // may already be contain in hashSequence.
1357  ss << txTo.vin[nIn].prevout;
1358  ss << scriptCode;
1359  ss << amount;
1360  ss << txTo.vin[nIn].nSequence;
1361  // Outputs (none/one/all, depending on flags)
1362  ss << hashOutputs;
1363  // Locktime
1364  ss << txTo.nLockTime;
1365  // Sighash type
1366  ss << nHashType;
1367 
1368  return ss.GetHash();
1369  }
1370 
1371  // Check for invalid use of SIGHASH_SINGLE
1372  if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1373  if (nIn >= txTo.vout.size()) {
1374  // nOut out of range
1375  return UINT256_ONE();
1376  }
1377  }
1378 
1379  // Wrapper to serialize only the necessary parts of the transaction being signed
1380  CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
1381 
1382  // Serialize and hash
1383  CHashWriter ss(SER_GETHASH, 0);
1384  ss << txTmp << nHashType;
1385  return ss.GetHash();
1386 }
1387 
1388 template <class T>
1389 bool GenericTransactionSignatureChecker<T>::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1390 {
1391  return pubkey.Verify(sighash, vchSig);
1392 }
1393 
1394 template <class T>
1395 bool GenericTransactionSignatureChecker<T>::CheckSig(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1396 {
1397  CPubKey pubkey(vchPubKey);
1398  if (!pubkey.IsValid())
1399  return false;
1400 
1401  // Hash type is one byte tacked on to the end of the signature
1402  std::vector<unsigned char> vchSig(vchSigIn);
1403  if (vchSig.empty())
1404  return false;
1405  int nHashType = vchSig.back();
1406  vchSig.pop_back();
1407 
1408  uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
1409 
1410  if (!VerifySignature(vchSig, pubkey, sighash))
1411  return false;
1412 
1413  return true;
1414 }
1415 
1416 template <class T>
1418 {
1419  // There are two kinds of nLockTime: lock-by-blockheight
1420  // and lock-by-blocktime, distinguished by whether
1421  // nLockTime < LOCKTIME_THRESHOLD.
1422  //
1423  // We want to compare apples to apples, so fail the script
1424  // unless the type of nLockTime being tested is the same as
1425  // the nLockTime in the transaction.
1426  if (!(
1427  (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
1428  (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1429  ))
1430  return false;
1431 
1432  // Now that we know we're comparing apples-to-apples, the
1433  // comparison is a simple numeric one.
1434  if (nLockTime > (int64_t)txTo->nLockTime)
1435  return false;
1436 
1437  // Finally the nLockTime feature can be disabled and thus
1438  // CHECKLOCKTIMEVERIFY bypassed if every txin has been
1439  // finalized by setting nSequence to maxint. The
1440  // transaction would be allowed into the blockchain, making
1441  // the opcode ineffective.
1442  //
1443  // Testing if this vin is not final is sufficient to
1444  // prevent this condition. Alternatively we could test all
1445  // inputs, but testing just this input minimizes the data
1446  // required to prove correct CHECKLOCKTIMEVERIFY execution.
1447  if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1448  return false;
1449 
1450  return true;
1451 }
1452 
1453 template <class T>
1455 {
1456  // Relative lock times are supported by comparing the passed
1457  // in operand to the sequence number of the input.
1458  const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1459 
1460  // Fail if the transaction's version number is not set high
1461  // enough to trigger BIP 68 rules.
1462  if (static_cast<uint32_t>(txTo->nVersion) < 2)
1463  return false;
1464 
1465  // Sequence numbers with their most significant bit set are not
1466  // consensus constrained. Testing that the transaction's sequence
1467  // number do not have this bit set prevents using this property
1468  // to get around a CHECKSEQUENCEVERIFY check.
1469  if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1470  return false;
1471 
1472  // Mask off any bits that do not have consensus-enforced meaning
1473  // before doing the integer comparisons
1474  const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1475  const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1476  const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1477 
1478  // There are two kinds of nSequence: lock-by-blockheight
1479  // and lock-by-blocktime, distinguished by whether
1480  // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1481  //
1482  // We want to compare apples to apples, so fail the script
1483  // unless the type of nSequenceMasked being tested is the same as
1484  // the nSequenceMasked in the transaction.
1485  if (!(
1486  (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1487  (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1488  )) {
1489  return false;
1490  }
1491 
1492  // Now that we know we're comparing apples-to-apples, the
1493  // comparison is a simple numeric one.
1494  if (nSequenceMasked > txToSequenceMasked)
1495  return false;
1496 
1497  return true;
1498 }
1499 
1500 // explicit instantiation
1503 
1504 static bool ExecuteWitnessScript(const Span<const valtype>& stack_span, const CScript& scriptPubKey, unsigned int flags, SigVersion sigversion, const BaseSignatureChecker& checker, ScriptError* serror)
1505 {
1506  std::vector<valtype> stack{stack_span.begin(), stack_span.end()};
1507 
1508  // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
1509  for (const valtype& elem : stack) {
1510  if (elem.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
1511  }
1512 
1513  // Run the script interpreter.
1514  if (!EvalScript(stack, scriptPubKey, flags, checker, sigversion, serror)) return false;
1515 
1516  // Scripts inside witness implicitly require cleanstack behaviour
1517  if (stack.size() != 1) return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1518  if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1519  return true;
1520 }
1521 
1522 static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1523 {
1524  CScript scriptPubKey;
1525  Span<const valtype> stack{witness.stack};
1526 
1527  if (witversion == 0) {
1528  if (program.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
1529  // Version 0 segregated witness program: SHA256(CScript) inside the program, CScript + inputs in witness
1530  if (stack.size() == 0) {
1531  return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1532  }
1533  const valtype& script_bytes = SpanPopBack(stack);
1534  scriptPubKey = CScript(script_bytes.begin(), script_bytes.end());
1535  uint256 hashScriptPubKey;
1536  CSHA256().Write(&scriptPubKey[0], scriptPubKey.size()).Finalize(hashScriptPubKey.begin());
1537  if (memcmp(hashScriptPubKey.begin(), program.data(), 32)) {
1538  return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1539  }
1540  return ExecuteWitnessScript(stack, scriptPubKey, flags, SigVersion::WITNESS_V0, checker, serror);
1541  } else if (program.size() == WITNESS_V0_KEYHASH_SIZE) {
1542  // Special case for pay-to-pubkeyhash; signature + pubkey in witness
1543  if (stack.size() != 2) {
1544  return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1545  }
1546  scriptPubKey << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
1547  return ExecuteWitnessScript(stack, scriptPubKey, flags, SigVersion::WITNESS_V0, checker, serror);
1548  } else {
1549  return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
1550  }
1551  } else {
1553  return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
1554  }
1555  // Higher version witness scripts return true for future softfork compatibility
1556  return true;
1557  }
1558  // 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.
1559 }
1560 
1561 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1562 {
1563  static const CScriptWitness emptyWitness;
1564  if (witness == nullptr) {
1565  witness = &emptyWitness;
1566  }
1567  bool hadWitness = false;
1568 
1569  set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1570 
1571  if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1572  return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1573  }
1574 
1575  // scriptSig and scriptPubKey must be evaluated sequentially on the same stack
1576  // rather than being simply concatenated (see CVE-2010-5141)
1577  std::vector<std::vector<unsigned char> > stack, stackCopy;
1578  if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
1579  // serror is set
1580  return false;
1581  if (flags & SCRIPT_VERIFY_P2SH)
1582  stackCopy = stack;
1583  if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
1584  // serror is set
1585  return false;
1586  if (stack.empty())
1587  return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1588  if (CastToBool(stack.back()) == false)
1589  return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1590 
1591  // Bare witness programs
1592  int witnessversion;
1593  std::vector<unsigned char> witnessprogram;
1594  if (flags & SCRIPT_VERIFY_WITNESS) {
1595  if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1596  hadWitness = true;
1597  if (scriptSig.size() != 0) {
1598  // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
1599  return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
1600  }
1601  if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
1602  return false;
1603  }
1604  // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1605  // for witness programs.
1606  stack.resize(1);
1607  }
1608  }
1609 
1610  // Additional validation for spend-to-script-hash transactions:
1611  if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1612  {
1613  // scriptSig must be literals-only or validation fails
1614  if (!scriptSig.IsPushOnly())
1615  return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1616 
1617  // Restore stack.
1618  swap(stack, stackCopy);
1619 
1620  // stack cannot be empty here, because if it was the
1621  // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1622  // an empty stack and the EvalScript above would return false.
1623  assert(!stack.empty());
1624 
1625  const valtype& pubKeySerialized = stack.back();
1626  CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1627  popstack(stack);
1628 
1629  if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
1630  // serror is set
1631  return false;
1632  if (stack.empty())
1633  return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1634  if (!CastToBool(stack.back()))
1635  return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1636 
1637  // P2SH witness program
1638  if (flags & SCRIPT_VERIFY_WITNESS) {
1639  if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
1640  hadWitness = true;
1641  if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
1642  // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
1643  // reintroduce malleability.
1644  return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
1645  }
1646  if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
1647  return false;
1648  }
1649  // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1650  // for witness programs.
1651  stack.resize(1);
1652  }
1653  }
1654  }
1655 
1656  // The CLEANSTACK check is only performed after potential P2SH evaluation,
1657  // as the non-P2SH evaluation of a P2SH script will obviously not result in
1658  // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
1659  if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
1660  // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
1661  // would be possible, which is not a softfork (and P2SH should be one).
1662  assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1663  assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
1664  if (stack.size() != 1) {
1665  return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1666  }
1667  }
1668 
1669  if (flags & SCRIPT_VERIFY_WITNESS) {
1670  // We can't check for correct unexpected witness data if P2SH was off, so require
1671  // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
1672  // possible, which is not a softfork.
1673  assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1674  if (!hadWitness && !witness->IsNull()) {
1675  return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
1676  }
1677  }
1678 
1679  return set_success(serror);
1680 }
1681 
1682 size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness)
1683 {
1684  if (witversion == 0) {
1685  if (witprogram.size() == WITNESS_V0_KEYHASH_SIZE)
1686  return 1;
1687 
1688  if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.stack.size() > 0) {
1689  CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
1690  return subscript.GetSigOpCount(true);
1691  }
1692  }
1693 
1694  // Future flags may be implemented here.
1695  return 0;
1696 }
1697 
1698 size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags)
1699 {
1700  static const CScriptWitness witnessEmpty;
1701 
1702  if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
1703  return 0;
1704  }
1705  assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1706 
1707  int witnessversion;
1708  std::vector<unsigned char> witnessprogram;
1709  if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1710  return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
1711  }
1712 
1713  if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
1714  CScript::const_iterator pc = scriptSig.begin();
1715  std::vector<unsigned char> data;
1716  while (pc < scriptSig.end()) {
1717  opcodetype opcode;
1718  scriptSig.GetOp(pc, opcode, data);
1719  }
1720  CScript subscript(data.begin(), data.end());
1721  if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
1722  return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
1723  }
1724  }
1725 
1726  return 0;
1727 }
Definition: script.h:139
Definition: script.h:68
Definition: script.h:124
unsigned int GetSigOpCount(bool fAccurate) const
Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs as 20 sigops.
Definition: script.cpp:150
static size_t WitnessSigOps(int witversion, const std::vector< unsigned char > &witprogram, const CScriptWitness &witness)
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:637
virtual bool CheckLockTime(const CScriptNum &nLockTime) const
Definition: interpreter.h:156
static const int MAX_PUBKEYS_PER_MULTISIG
Definition: script.h:29
if(expired !=0)
Definition: validation.cpp:338
static constexpr unsigned int SIZE
secp256k1:
Definition: pubkey.h:36
Definition: script.h:107
const int nVersion
Definition: hash.h:104
void Finalize(Span< unsigned char > output)
Definition: hash.h:28
CSHA1 & Write(const unsigned char *data, size_t len)
Definition: sha1.cpp:154
int getint() const
Definition: script.h:311
Definition: script.h:160
enum ScriptError_t ScriptError
Definition: script.h:99
constexpr C * end() const noexcept
Definition: span.h:142
iterator insert(iterator pos, const T &value)
Definition: prevector.h:347
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< unsigned char > &vchRet) const
Definition: script.h:472
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:1098
bool IsPayToScriptHash() const
Definition: script.cpp:198
void Finalize(Span< unsigned char > output)
Definition: hash.h:53
Definition: script.h:85
Definition: script.h:78
Definition: script.h:74
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:349
static const uint32_t SEQUENCE_FINAL
Definition: transaction.h:69
Definition: script.h:138
static void popstack(std::vector< valtype > &stack)
Definition: interpreter.cpp:56
Definition: script.h:66
Definition: script.h:145
Definition: script.h:72
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
Definition: transaction.h:74
static bool IsCompressedPubKey(const valtype &vchPubKey)
Definition: interpreter.cpp:85
static bool VerifyWitnessProgram(const CScriptWitness &witness, int witversion, const std::vector< unsigned char > &program, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
Definition: script.h:67
std::vector< std::vector< unsigned char > > stack
Definition: script.h:546
static bool CheckLowS(const std::vector< unsigned char > &vchSig)
Check whether a signature is normalized (lower-S).
Definition: pubkey.cpp:279
static bool ExecuteWitnessScript(const Span< const valtype > &stack_span, const CScript &scriptPubKey, unsigned int flags, SigVersion sigversion, const BaseSignatureChecker &checker, ScriptError *serror)
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
Definition: script.cpp:217
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:22
bool IsNull() const
Definition: script.h:551
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:23
Definition: script.h:159
uint256 & UINT256_ONE()
Definition: uint256.cpp:79
static bool CheckMinimalPush(const valtype &data, opcodetype opcode)
Definition: script.h:80
Definition: script.h:76
static const int MAX_OPS_PER_SCRIPT
Definition: script.h:26
void Serialize(Stream &s, char a)
Definition: serialize.h:223
Definition: script.h:125
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
Definition: script.h:69
iterator end()
Definition: prevector.h:292
Definition: script.h:146
opcodetype
Script opcodes.
Definition: script.h:54
static constexpr unsigned int COMPRESSED_SIZE
Definition: pubkey.h:37
Definition: script.h:116
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:233
static bool EvalChecksig(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)
Helper for OP_CHECKSIG and OP_CHECKSIGVERIFY.
virtual bool VerifySignature(const std::vector< unsigned char > &vchSig, const CPubKey &vchPubKey, const uint256 &sighash) const
bool IsValid() const
Definition: pubkey.h:174
An encapsulated public key.
Definition: pubkey.h:30
Definition: script.h:71
Definition: script.h:64
Definition: script.h:83
std::vector< unsigned char > getvch() const
Definition: script.h:320
#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 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:143
bool CheckSig(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const override
An output of a transaction.
Definition: transaction.h:122
static constexpr size_t WITNESS_V0_SCRIPTHASH_SIZE
Signature hash sizes.
Definition: interpreter.h:142
static const int MAX_SCRIPT_SIZE
Definition: script.h:32
Definition: script.h:111
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG
Definition: transaction.h:79
static const int MAX_STACK_SIZE
Definition: script.h:35
Definition: script.h:144
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptError *serror)
#define altstacktop(i)
Definition: interpreter.cpp:55
Definition: script.h:89
CRIPEMD160 & Write(const unsigned char *data, size_t len)
Definition: ripemd160.cpp:247
int flags
Definition: bitcoin-tx.cpp:509
constexpr C * begin() const noexcept
Definition: span.h:141
uint256 GetHash()
Definition: hash.h:117
Definition: script.h:73
256-bit opaque blob.
Definition: uint256.h:123
Definition: script.h:98
static const uint32_t SEQUENCE_LOCKTIME_MASK
Definition: transaction.h:83
bool Verify(const uint256 &hash, const std::vector< unsigned char > &vchSig) const
Verify a DER signature (~72 bytes).
Definition: pubkey.cpp:169
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:390
static constexpr size_t WITNESS_V0_KEYHASH_SIZE
Definition: interpreter.h:143
static bool IsCompressedOrUncompressedPubKey(const valtype &vchPubKey)
Definition: interpreter.cpp:63
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:70
virtual bool CheckSig(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const
Definition: interpreter.h:151
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:161
iterator begin()
Definition: prevector.h:290
A mutable version of CTransaction.
Definition: transaction.h:347
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:98
size_type size() const
Definition: prevector.h:282
PrecomputedTransactionData()=default
static bool IsLowDERSignature(const valtype &vchSig, ScriptError *serror)
Definition: script.h:77
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:253
bool CheckSequence(const CScriptNum &nSequence) const override
A hasher class for Bitcoin&#39;s 160-bit hash (SHA-256 + RIPEMD-160).
Definition: hash.h:47
Definition: script.h:126
Definition: script.h:75
A hasher class for SHA-256.
Definition: sha256.h:13
auto it
Definition: validation.cpp:383
int FindAndDelete(CScript &script, const CScript &b)
Definition: script.h:57
bool CastToBool(const valtype &vch)
Definition: interpreter.cpp:35
CHash160 & Write(Span< const unsigned char > input)
Definition: hash.h:60
CHash256 & Write(Span< const unsigned char > input)
Definition: hash.h:35
static bool IsDefinedHashtypeSignature(const valtype &vchSig)
Definition: script.h:142
Definition: script.h:79
A hasher class for RIPEMD-160.
Definition: ripemd160.h:12
Definition: script.h:106
SigVersion
Definition: interpreter.h:135