Bitcoin ABC  0.22.12
P2P Digital Currency
interpreter.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2017-2020 The Bitcoin developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include <script/interpreter.h>
8 
9 #include <crypto/ripemd160.h>
10 #include <crypto/sha1.h>
11 #include <crypto/sha256.h>
12 #include <pubkey.h>
13 #include <script/bitfield.h>
14 #include <script/script.h>
15 #include <script/sigencoding.h>
16 #include <uint256.h>
17 #include <util/bitmanip.h>
18 
19 bool CastToBool(const valtype &vch) {
20  for (size_t i = 0; i < vch.size(); i++) {
21  if (vch[i] != 0) {
22  // Can be negative zero
23  if (i == vch.size() - 1 && vch[i] == 0x80) {
24  return false;
25  }
26  return true;
27  }
28  }
29  return false;
30 }
31 
36 #define stacktop(i) (stack.at(stack.size() + (i)))
37 #define altstacktop(i) (altstack.at(altstack.size() + (i)))
38 static inline void popstack(std::vector<valtype> &stack) {
39  if (stack.empty()) {
40  throw std::runtime_error("popstack(): stack empty");
41  }
42  stack.pop_back();
43 }
44 
45 int FindAndDelete(CScript &script, const CScript &b) {
46  int nFound = 0;
47  if (b.empty()) {
48  return nFound;
49  }
50 
51  CScript result;
52  CScript::const_iterator pc = script.begin(), pc2 = script.begin(),
53  end = script.end();
54  opcodetype opcode;
55  do {
56  result.insert(result.end(), pc2, pc);
57  while (static_cast<size_t>(end - pc) >= b.size() &&
58  std::equal(b.begin(), b.end(), pc)) {
59  pc = pc + b.size();
60  ++nFound;
61  }
62  pc2 = pc;
63  } while (script.GetOp(pc, opcode));
64 
65  if (nFound > 0) {
66  result.insert(result.end(), pc2, end);
67  script = std::move(result);
68  }
69 
70  return nFound;
71 }
72 
73 static void CleanupScriptCode(CScript &scriptCode,
74  const std::vector<uint8_t> &vchSig,
75  uint32_t flags) {
76  // Drop the signature in scripts when SIGHASH_FORKID is not used.
77  SigHashType sigHashType = GetHashType(vchSig);
78  if (!(flags & SCRIPT_ENABLE_SIGHASH_FORKID) || !sigHashType.hasForkId()) {
79  FindAndDelete(scriptCode, CScript() << vchSig);
80  }
81 }
82 
83 static bool IsOpcodeDisabled(opcodetype opcode, uint32_t flags) {
84  switch (opcode) {
85  case OP_INVERT:
86  case OP_2MUL:
87  case OP_2DIV:
88  case OP_MUL:
89  case OP_LSHIFT:
90  case OP_RSHIFT:
91  // Disabled opcodes.
92  return true;
93 
94  default:
95  break;
96  }
97 
98  return false;
99 }
100 
101 namespace {
118 class ConditionStack {
119 private:
121  static constexpr uint32_t NO_FALSE = std::numeric_limits<uint32_t>::max();
122 
124  uint32_t m_stack_size = 0;
127  uint32_t m_first_false_pos = NO_FALSE;
128 
129 public:
130  bool empty() { return m_stack_size == 0; }
131  bool all_true() { return m_first_false_pos == NO_FALSE; }
132  void push_back(bool f) {
133  if (m_first_false_pos == NO_FALSE && !f) {
134  // The stack consists of all true values, and a false is added.
135  // The first false value will appear at the current size.
136  m_first_false_pos = m_stack_size;
137  }
138  ++m_stack_size;
139  }
140  void pop_back() {
141  assert(m_stack_size > 0);
142  --m_stack_size;
143  if (m_first_false_pos == m_stack_size) {
144  // When popping off the first false value, everything becomes true.
145  m_first_false_pos = NO_FALSE;
146  }
147  }
148  void toggle_top() {
149  assert(m_stack_size > 0);
150  if (m_first_false_pos == NO_FALSE) {
151  // The current stack is all true values; the first false will be the
152  // top.
153  m_first_false_pos = m_stack_size - 1;
154  } else if (m_first_false_pos == m_stack_size - 1) {
155  // The top is the first false value; toggling it will make
156  // everything true.
157  m_first_false_pos = NO_FALSE;
158  } else {
159  // There is a false value, but not on top. No action is needed as
160  // toggling anything but the first false value is unobservable.
161  }
162  }
163 };
164 } // namespace
165 
173 static bool EvalChecksig(const valtype &vchSig, const valtype &vchPubKey,
174  CScript::const_iterator pbegincodehash,
175  CScript::const_iterator pend, uint32_t flags,
176  const BaseSignatureChecker &checker,
177  ScriptExecutionMetrics &metrics, ScriptError *serror,
178  bool &fSuccess) {
179  if (!CheckTransactionSignatureEncoding(vchSig, flags, serror) ||
180  !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
181  // serror is set
182  return false;
183  }
184 
185  if (vchSig.size()) {
186  // Subset of script starting at the most recent
187  // codeseparator
188  CScript scriptCode(pbegincodehash, pend);
189 
190  // Remove signature for pre-fork scripts
191  CleanupScriptCode(scriptCode, vchSig, flags);
192 
193  fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, flags);
194  metrics.nSigChecks += 1;
195 
196  if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL)) {
197  return set_error(serror, ScriptError::SIG_NULLFAIL);
198  }
199  }
200  return true;
201 }
202 
203 bool EvalScript(std::vector<valtype> &stack, const CScript &script,
204  uint32_t flags, const BaseSignatureChecker &checker,
205  ScriptExecutionMetrics &metrics, ScriptError *serror) {
206  static const CScriptNum bnZero(0);
207  static const CScriptNum bnOne(1);
208  static const valtype vchFalse(0);
209  static const valtype vchTrue(1, 1);
210 
211  CScript::const_iterator pc = script.begin();
212  CScript::const_iterator pend = script.end();
213  CScript::const_iterator pbegincodehash = script.begin();
214  opcodetype opcode;
215  valtype vchPushValue;
216  ConditionStack vfExec;
217  std::vector<valtype> altstack;
218  set_error(serror, ScriptError::UNKNOWN);
219  if (script.size() > MAX_SCRIPT_SIZE) {
220  return set_error(serror, ScriptError::SCRIPT_SIZE);
221  }
222  int nOpCount = 0;
223  bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
224 
225  try {
226  while (pc < pend) {
227  bool fExec = vfExec.all_true();
228 
229  //
230  // Read instruction
231  //
232  if (!script.GetOp(pc, opcode, vchPushValue)) {
233  return set_error(serror, ScriptError::BAD_OPCODE);
234  }
235  if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE) {
236  return set_error(serror, ScriptError::PUSH_SIZE);
237  }
238 
239  // Note how OP_RESERVED does not count towards the opcode limit.
240  if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT) {
241  return set_error(serror, ScriptError::OP_COUNT);
242  }
243 
244  // Some opcodes are disabled (CVE-2010-5137).
245  if (IsOpcodeDisabled(opcode, flags)) {
246  return set_error(serror, ScriptError::DISABLED_OPCODE);
247  }
248 
249  if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
250  if (fRequireMinimal &&
251  !CheckMinimalPush(vchPushValue, opcode)) {
252  return set_error(serror, ScriptError::MINIMALDATA);
253  }
254  stack.push_back(vchPushValue);
255  } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF)) {
256  switch (opcode) {
257  //
258  // Push value
259  //
260  case OP_1NEGATE:
261  case OP_1:
262  case OP_2:
263  case OP_3:
264  case OP_4:
265  case OP_5:
266  case OP_6:
267  case OP_7:
268  case OP_8:
269  case OP_9:
270  case OP_10:
271  case OP_11:
272  case OP_12:
273  case OP_13:
274  case OP_14:
275  case OP_15:
276  case OP_16: {
277  // ( -- value)
278  CScriptNum bn((int)opcode - (int)(OP_1 - 1));
279  stack.push_back(bn.getvch());
280  // The result of these opcodes should always be the
281  // minimal way to push the data they push, so no need
282  // for a CheckMinimalPush here.
283  } break;
284 
285  //
286  // Control
287  //
288  case OP_NOP:
289  break;
290 
291  case OP_CHECKLOCKTIMEVERIFY: {
292  if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
293  break;
294  }
295 
296  if (stack.size() < 1) {
297  return set_error(
299  }
300 
301  // Note that elsewhere numeric opcodes are limited to
302  // operands in the range -2**31+1 to 2**31-1, however it
303  // is legal for opcodes to produce results exceeding
304  // that range. This limitation is implemented by
305  // CScriptNum's default 4-byte limit.
306  //
307  // If we kept to that limit we'd have a year 2038
308  // problem, even though the nLockTime field in
309  // transactions themselves is uint32 which only becomes
310  // meaningless after the year 2106.
311  //
312  // Thus as a special case we tell CScriptNum to accept
313  // up to 5-byte bignums, which are good until 2**39-1,
314  // well beyond the 2**32-1 limit of the nLockTime field
315  // itself.
316  const CScriptNum nLockTime(stacktop(-1),
317  fRequireMinimal, 5);
318 
319  // In the rare event that the argument may be < 0 due to
320  // some arithmetic being done first, you can always use
321  // 0 MAX CHECKLOCKTIMEVERIFY.
322  if (nLockTime < 0) {
323  return set_error(serror,
325  }
326 
327  // Actually compare the specified lock time with the
328  // transaction.
329  if (!checker.CheckLockTime(nLockTime)) {
330  return set_error(serror,
332  }
333 
334  break;
335  }
336 
337  case OP_CHECKSEQUENCEVERIFY: {
338  if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
339  break;
340  }
341 
342  if (stack.size() < 1) {
343  return set_error(
345  }
346 
347  // nSequence, like nLockTime, is a 32-bit unsigned
348  // integer field. See the comment in CHECKLOCKTIMEVERIFY
349  // regarding 5-byte numeric operands.
350  const CScriptNum nSequence(stacktop(-1),
351  fRequireMinimal, 5);
352 
353  // In the rare event that the argument may be < 0 due to
354  // some arithmetic being done first, you can always use
355  // 0 MAX CHECKSEQUENCEVERIFY.
356  if (nSequence < 0) {
357  return set_error(serror,
359  }
360 
361  // To provide for future soft-fork extensibility, if the
362  // operand has the disabled lock-time flag set,
363  // CHECKSEQUENCEVERIFY behaves as a NOP.
364  if ((nSequence &
366  break;
367  }
368 
369  // Compare the specified sequence number with the input.
370  if (!checker.CheckSequence(nSequence)) {
371  return set_error(serror,
373  }
374 
375  break;
376  }
377 
378  case OP_NOP1:
379  case OP_NOP4:
380  case OP_NOP5:
381  case OP_NOP6:
382  case OP_NOP7:
383  case OP_NOP8:
384  case OP_NOP9:
385  case OP_NOP10: {
387  return set_error(
388  serror,
390  }
391  } break;
392 
393  case OP_IF:
394  case OP_NOTIF: {
395  // <expression> if [statements] [else [statements]]
396  // endif
397  bool fValue = false;
398  if (fExec) {
399  if (stack.size() < 1) {
400  return set_error(
401  serror,
403  }
404  valtype &vch = stacktop(-1);
405  if (flags & SCRIPT_VERIFY_MINIMALIF) {
406  if (vch.size() > 1) {
407  return set_error(serror,
409  }
410  if (vch.size() == 1 && vch[0] != 1) {
411  return set_error(serror,
413  }
414  }
415  fValue = CastToBool(vch);
416  if (opcode == OP_NOTIF) {
417  fValue = !fValue;
418  }
419  popstack(stack);
420  }
421  vfExec.push_back(fValue);
422  } break;
423 
424  case OP_ELSE: {
425  if (vfExec.empty()) {
426  return set_error(
428  }
429  vfExec.toggle_top();
430  } break;
431 
432  case OP_ENDIF: {
433  if (vfExec.empty()) {
434  return set_error(
436  }
437  vfExec.pop_back();
438  } break;
439 
440  case OP_VERIFY: {
441  // (true -- ) or
442  // (false -- false) and return
443  if (stack.size() < 1) {
444  return set_error(
446  }
447  bool fValue = CastToBool(stacktop(-1));
448  if (fValue) {
449  popstack(stack);
450  } else {
451  return set_error(serror, ScriptError::VERIFY);
452  }
453  } break;
454 
455  case OP_RETURN: {
456  return set_error(serror, ScriptError::OP_RETURN);
457  } break;
458 
459  //
460  // Stack ops
461  //
462  case OP_TOALTSTACK: {
463  if (stack.size() < 1) {
464  return set_error(
466  }
467  altstack.push_back(stacktop(-1));
468  popstack(stack);
469  } break;
470 
471  case OP_FROMALTSTACK: {
472  if (altstack.size() < 1) {
473  return set_error(
474  serror,
476  }
477  stack.push_back(altstacktop(-1));
478  popstack(altstack);
479  } break;
480 
481  case OP_2DROP: {
482  // (x1 x2 -- )
483  if (stack.size() < 2) {
484  return set_error(
486  }
487  popstack(stack);
488  popstack(stack);
489  } break;
490 
491  case OP_2DUP: {
492  // (x1 x2 -- x1 x2 x1 x2)
493  if (stack.size() < 2) {
494  return set_error(
496  }
497  valtype vch1 = stacktop(-2);
498  valtype vch2 = stacktop(-1);
499  stack.push_back(vch1);
500  stack.push_back(vch2);
501  } break;
502 
503  case OP_3DUP: {
504  // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
505  if (stack.size() < 3) {
506  return set_error(
508  }
509  valtype vch1 = stacktop(-3);
510  valtype vch2 = stacktop(-2);
511  valtype vch3 = stacktop(-1);
512  stack.push_back(vch1);
513  stack.push_back(vch2);
514  stack.push_back(vch3);
515  } break;
516 
517  case OP_2OVER: {
518  // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
519  if (stack.size() < 4) {
520  return set_error(
522  }
523  valtype vch1 = stacktop(-4);
524  valtype vch2 = stacktop(-3);
525  stack.push_back(vch1);
526  stack.push_back(vch2);
527  } break;
528 
529  case OP_2ROT: {
530  // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
531  if (stack.size() < 6) {
532  return set_error(
534  }
535  valtype vch1 = stacktop(-6);
536  valtype vch2 = stacktop(-5);
537  stack.erase(stack.end() - 6, stack.end() - 4);
538  stack.push_back(vch1);
539  stack.push_back(vch2);
540  } break;
541 
542  case OP_2SWAP: {
543  // (x1 x2 x3 x4 -- x3 x4 x1 x2)
544  if (stack.size() < 4) {
545  return set_error(
547  }
548  swap(stacktop(-4), stacktop(-2));
549  swap(stacktop(-3), stacktop(-1));
550  } break;
551 
552  case OP_IFDUP: {
553  // (x - 0 | x x)
554  if (stack.size() < 1) {
555  return set_error(
557  }
558  valtype vch = stacktop(-1);
559  if (CastToBool(vch)) {
560  stack.push_back(vch);
561  }
562  } break;
563 
564  case OP_DEPTH: {
565  // -- stacksize
566  CScriptNum bn(stack.size());
567  stack.push_back(bn.getvch());
568  } break;
569 
570  case OP_DROP: {
571  // (x -- )
572  if (stack.size() < 1) {
573  return set_error(
575  }
576  popstack(stack);
577  } break;
578 
579  case OP_DUP: {
580  // (x -- x x)
581  if (stack.size() < 1) {
582  return set_error(
584  }
585  valtype vch = stacktop(-1);
586  stack.push_back(vch);
587  } break;
588 
589  case OP_NIP: {
590  // (x1 x2 -- x2)
591  if (stack.size() < 2) {
592  return set_error(
594  }
595  stack.erase(stack.end() - 2);
596  } break;
597 
598  case OP_OVER: {
599  // (x1 x2 -- x1 x2 x1)
600  if (stack.size() < 2) {
601  return set_error(
603  }
604  valtype vch = stacktop(-2);
605  stack.push_back(vch);
606  } break;
607 
608  case OP_PICK:
609  case OP_ROLL: {
610  // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
611  // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
612  if (stack.size() < 2) {
613  return set_error(
615  }
616  int n =
617  CScriptNum(stacktop(-1), fRequireMinimal).getint();
618  popstack(stack);
619  if (n < 0 || n >= (int)stack.size()) {
620  return set_error(
622  }
623  valtype vch = stacktop(-n - 1);
624  if (opcode == OP_ROLL) {
625  stack.erase(stack.end() - n - 1);
626  }
627  stack.push_back(vch);
628  } break;
629 
630  case OP_ROT: {
631  // (x1 x2 x3 -- x2 x3 x1)
632  // x2 x1 x3 after first swap
633  // x2 x3 x1 after second swap
634  if (stack.size() < 3) {
635  return set_error(
637  }
638  swap(stacktop(-3), stacktop(-2));
639  swap(stacktop(-2), stacktop(-1));
640  } break;
641 
642  case OP_SWAP: {
643  // (x1 x2 -- x2 x1)
644  if (stack.size() < 2) {
645  return set_error(
647  }
648  swap(stacktop(-2), stacktop(-1));
649  } break;
650 
651  case OP_TUCK: {
652  // (x1 x2 -- x2 x1 x2)
653  if (stack.size() < 2) {
654  return set_error(
656  }
657  valtype vch = stacktop(-1);
658  stack.insert(stack.end() - 2, vch);
659  } break;
660 
661  case OP_SIZE: {
662  // (in -- in size)
663  if (stack.size() < 1) {
664  return set_error(
666  }
667  CScriptNum bn(stacktop(-1).size());
668  stack.push_back(bn.getvch());
669  } break;
670 
671  //
672  // Bitwise logic
673  //
674  case OP_AND:
675  case OP_OR:
676  case OP_XOR: {
677  // (x1 x2 - out)
678  if (stack.size() < 2) {
679  return set_error(
681  }
682  valtype &vch1 = stacktop(-2);
683  valtype &vch2 = stacktop(-1);
684 
685  // Inputs must be the same size
686  if (vch1.size() != vch2.size()) {
687  return set_error(serror,
689  }
690 
691  // To avoid allocating, we modify vch1 in place.
692  switch (opcode) {
693  case OP_AND:
694  for (size_t i = 0; i < vch1.size(); ++i) {
695  vch1[i] &= vch2[i];
696  }
697  break;
698  case OP_OR:
699  for (size_t i = 0; i < vch1.size(); ++i) {
700  vch1[i] |= vch2[i];
701  }
702  break;
703  case OP_XOR:
704  for (size_t i = 0; i < vch1.size(); ++i) {
705  vch1[i] ^= vch2[i];
706  }
707  break;
708  default:
709  break;
710  }
711 
712  // And pop vch2.
713  popstack(stack);
714  } break;
715 
716  case OP_EQUAL:
717  case OP_EQUALVERIFY:
718  // case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
719  {
720  // (x1 x2 - bool)
721  if (stack.size() < 2) {
722  return set_error(
723  serror,
725  }
726  valtype &vch1 = stacktop(-2);
727  valtype &vch2 = stacktop(-1);
728 
729  bool fEqual = (vch1 == vch2);
730  // OP_NOTEQUAL is disabled because it would be too
731  // easy to say something like n != 1 and have some
732  // wiseguy pass in 1 with extra zero bytes after it
733  // (numerically, 0x01 == 0x0001 == 0x000001)
734  // if (opcode == OP_NOTEQUAL)
735  // fEqual = !fEqual;
736  popstack(stack);
737  popstack(stack);
738  stack.push_back(fEqual ? vchTrue : vchFalse);
739  if (opcode == OP_EQUALVERIFY) {
740  if (fEqual) {
741  popstack(stack);
742  } else {
743  return set_error(serror,
745  }
746  }
747  }
748  break;
749 
750  //
751  // Numeric
752  //
753  case OP_1ADD:
754  case OP_1SUB:
755  case OP_NEGATE:
756  case OP_ABS:
757  case OP_NOT:
758  case OP_0NOTEQUAL: {
759  // (in -- out)
760  if (stack.size() < 1) {
761  return set_error(
763  }
764  CScriptNum bn(stacktop(-1), fRequireMinimal);
765  switch (opcode) {
766  case OP_1ADD:
767  bn += bnOne;
768  break;
769  case OP_1SUB:
770  bn -= bnOne;
771  break;
772  case OP_NEGATE:
773  bn = -bn;
774  break;
775  case OP_ABS:
776  if (bn < bnZero) {
777  bn = -bn;
778  }
779  break;
780  case OP_NOT:
781  bn = (bn == bnZero);
782  break;
783  case OP_0NOTEQUAL:
784  bn = (bn != bnZero);
785  break;
786  default:
787  assert(!"invalid opcode");
788  break;
789  }
790  popstack(stack);
791  stack.push_back(bn.getvch());
792  } break;
793 
794  case OP_ADD:
795  case OP_SUB:
796  case OP_DIV:
797  case OP_MOD:
798  case OP_BOOLAND:
799  case OP_BOOLOR:
800  case OP_NUMEQUAL:
801  case OP_NUMEQUALVERIFY:
802  case OP_NUMNOTEQUAL:
803  case OP_LESSTHAN:
804  case OP_GREATERTHAN:
805  case OP_LESSTHANOREQUAL:
807  case OP_MIN:
808  case OP_MAX: {
809  // (x1 x2 -- out)
810  if (stack.size() < 2) {
811  return set_error(
813  }
814  CScriptNum bn1(stacktop(-2), fRequireMinimal);
815  CScriptNum bn2(stacktop(-1), fRequireMinimal);
816  CScriptNum bn(0);
817  switch (opcode) {
818  case OP_ADD:
819  bn = bn1 + bn2;
820  break;
821 
822  case OP_SUB:
823  bn = bn1 - bn2;
824  break;
825 
826  case OP_DIV:
827  // denominator must not be 0
828  if (bn2 == 0) {
829  return set_error(serror,
831  }
832  bn = bn1 / bn2;
833  break;
834 
835  case OP_MOD:
836  // divisor must not be 0
837  if (bn2 == 0) {
838  return set_error(serror,
840  }
841  bn = bn1 % bn2;
842  break;
843 
844  case OP_BOOLAND:
845  bn = (bn1 != bnZero && bn2 != bnZero);
846  break;
847  case OP_BOOLOR:
848  bn = (bn1 != bnZero || bn2 != bnZero);
849  break;
850  case OP_NUMEQUAL:
851  bn = (bn1 == bn2);
852  break;
853  case OP_NUMEQUALVERIFY:
854  bn = (bn1 == bn2);
855  break;
856  case OP_NUMNOTEQUAL:
857  bn = (bn1 != bn2);
858  break;
859  case OP_LESSTHAN:
860  bn = (bn1 < bn2);
861  break;
862  case OP_GREATERTHAN:
863  bn = (bn1 > bn2);
864  break;
865  case OP_LESSTHANOREQUAL:
866  bn = (bn1 <= bn2);
867  break;
869  bn = (bn1 >= bn2);
870  break;
871  case OP_MIN:
872  bn = (bn1 < bn2 ? bn1 : bn2);
873  break;
874  case OP_MAX:
875  bn = (bn1 > bn2 ? bn1 : bn2);
876  break;
877  default:
878  assert(!"invalid opcode");
879  break;
880  }
881  popstack(stack);
882  popstack(stack);
883  stack.push_back(bn.getvch());
884 
885  if (opcode == OP_NUMEQUALVERIFY) {
886  if (CastToBool(stacktop(-1))) {
887  popstack(stack);
888  } else {
889  return set_error(serror,
891  }
892  }
893  } break;
894 
895  case OP_WITHIN: {
896  // (x min max -- out)
897  if (stack.size() < 3) {
898  return set_error(
900  }
901  CScriptNum bn1(stacktop(-3), fRequireMinimal);
902  CScriptNum bn2(stacktop(-2), fRequireMinimal);
903  CScriptNum bn3(stacktop(-1), fRequireMinimal);
904  bool fValue = (bn2 <= bn1 && bn1 < bn3);
905  popstack(stack);
906  popstack(stack);
907  popstack(stack);
908  stack.push_back(fValue ? vchTrue : vchFalse);
909  } break;
910 
911  //
912  // Crypto
913  //
914  case OP_RIPEMD160:
915  case OP_SHA1:
916  case OP_SHA256:
917  case OP_HASH160:
918  case OP_HASH256: {
919  // (in -- hash)
920  if (stack.size() < 1) {
921  return set_error(
923  }
924  valtype &vch = stacktop(-1);
925  valtype vchHash((opcode == OP_RIPEMD160 ||
926  opcode == OP_SHA1 ||
927  opcode == OP_HASH160)
928  ? 20
929  : 32);
930  if (opcode == OP_RIPEMD160) {
931  CRIPEMD160()
932  .Write(vch.data(), vch.size())
933  .Finalize(vchHash.data());
934  } else if (opcode == OP_SHA1) {
935  CSHA1()
936  .Write(vch.data(), vch.size())
937  .Finalize(vchHash.data());
938  } else if (opcode == OP_SHA256) {
939  CSHA256()
940  .Write(vch.data(), vch.size())
941  .Finalize(vchHash.data());
942  } else if (opcode == OP_HASH160) {
943  CHash160()
944  .Write(vch.data(), vch.size())
945  .Finalize(vchHash.data());
946  } else if (opcode == OP_HASH256) {
947  CHash256()
948  .Write(vch.data(), vch.size())
949  .Finalize(vchHash.data());
950  }
951  popstack(stack);
952  stack.push_back(vchHash);
953  } break;
954 
955  case OP_CODESEPARATOR: {
956  // Hash starts after the code separator
957  pbegincodehash = pc;
958  } break;
959 
960  case OP_CHECKSIG:
961  case OP_CHECKSIGVERIFY: {
962  // (sig pubkey -- bool)
963  if (stack.size() < 2) {
964  return set_error(
966  }
967  valtype &vchSig = stacktop(-2);
968  valtype &vchPubKey = stacktop(-1);
969 
970  bool fSuccess = false;
971  if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash,
972  pend, flags, checker, metrics, serror,
973  fSuccess)) {
974  return false;
975  }
976  popstack(stack);
977  popstack(stack);
978  stack.push_back(fSuccess ? vchTrue : vchFalse);
979  if (opcode == OP_CHECKSIGVERIFY) {
980  if (fSuccess) {
981  popstack(stack);
982  } else {
983  return set_error(serror,
985  }
986  }
987  } break;
988 
989  case OP_CHECKDATASIG:
990  case OP_CHECKDATASIGVERIFY: {
991  // (sig message pubkey -- bool)
992  if (stack.size() < 3) {
993  return set_error(
995  }
996 
997  valtype &vchSig = stacktop(-3);
998  valtype &vchMessage = stacktop(-2);
999  valtype &vchPubKey = stacktop(-1);
1000 
1001  if (!CheckDataSignatureEncoding(vchSig, flags,
1002  serror) ||
1003  !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
1004  // serror is set
1005  return false;
1006  }
1007 
1008  bool fSuccess = false;
1009  if (vchSig.size()) {
1010  valtype vchHash(32);
1011  CSHA256()
1012  .Write(vchMessage.data(), vchMessage.size())
1013  .Finalize(vchHash.data());
1014  fSuccess = checker.VerifySignature(
1015  vchSig, CPubKey(vchPubKey), uint256(vchHash));
1016  metrics.nSigChecks += 1;
1017 
1018  if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL)) {
1019  return set_error(serror,
1021  }
1022  }
1023 
1024  popstack(stack);
1025  popstack(stack);
1026  popstack(stack);
1027  stack.push_back(fSuccess ? vchTrue : vchFalse);
1028  if (opcode == OP_CHECKDATASIGVERIFY) {
1029  if (fSuccess) {
1030  popstack(stack);
1031  } else {
1032  return set_error(
1034  }
1035  }
1036  } break;
1037 
1038  case OP_CHECKMULTISIG:
1039  case OP_CHECKMULTISIGVERIFY: {
1040  // ([dummy] [sig ...] num_of_signatures [pubkey ...]
1041  // num_of_pubkeys -- bool)
1042  const size_t idxKeyCount = 1;
1043  if (stack.size() < idxKeyCount) {
1044  return set_error(
1046  }
1047  const int nKeysCount =
1048  CScriptNum(stacktop(-idxKeyCount), fRequireMinimal)
1049  .getint();
1050  if (nKeysCount < 0 ||
1051  nKeysCount > MAX_PUBKEYS_PER_MULTISIG) {
1052  return set_error(serror, ScriptError::PUBKEY_COUNT);
1053  }
1054  nOpCount += nKeysCount;
1055  if (nOpCount > MAX_OPS_PER_SCRIPT) {
1056  return set_error(serror, ScriptError::OP_COUNT);
1057  }
1058 
1059  // stack depth of the top pubkey
1060  const size_t idxTopKey = idxKeyCount + 1;
1061 
1062  // stack depth of nSigsCount
1063  const size_t idxSigCount = idxTopKey + nKeysCount;
1064  if (stack.size() < idxSigCount) {
1065  return set_error(
1067  }
1068  const int nSigsCount =
1069  CScriptNum(stacktop(-idxSigCount), fRequireMinimal)
1070  .getint();
1071  if (nSigsCount < 0 || nSigsCount > nKeysCount) {
1072  return set_error(serror, ScriptError::SIG_COUNT);
1073  }
1074 
1075  // stack depth of the top signature
1076  const size_t idxTopSig = idxSigCount + 1;
1077 
1078  // stack depth of the dummy element
1079  const size_t idxDummy = idxTopSig + nSigsCount;
1080  if (stack.size() < idxDummy) {
1081  return set_error(
1083  }
1084 
1085  // Subset of script starting at the most recent
1086  // codeseparator
1087  CScript scriptCode(pbegincodehash, pend);
1088 
1089  // Assuming success is usually a bad idea, but the
1090  // schnorr path can only succeed.
1091  bool fSuccess = true;
1092 
1093  if ((flags & SCRIPT_ENABLE_SCHNORR_MULTISIG) &&
1094  stacktop(-idxDummy).size() != 0) {
1095  // SCHNORR MULTISIG
1096  static_assert(
1098  "Schnorr multisig checkbits implementation "
1099  "assumes < 32 pubkeys.");
1100  uint32_t checkBits = 0;
1101 
1102  // Dummy element is to be interpreted as a bitfield
1103  // that represent which pubkeys should be checked.
1104  valtype &vchDummy = stacktop(-idxDummy);
1105  if (!DecodeBitfield(vchDummy, nKeysCount, checkBits,
1106  serror)) {
1107  // serror is set
1108  return false;
1109  }
1110 
1111  // The bitfield doesn't set the right number of
1112  // signatures.
1113  if (countBits(checkBits) != uint32_t(nSigsCount)) {
1114  return set_error(
1116  }
1117 
1118  const size_t idxBottomKey =
1119  idxTopKey + nKeysCount - 1;
1120  const size_t idxBottomSig =
1121  idxTopSig + nSigsCount - 1;
1122 
1123  int iKey = 0;
1124  for (int iSig = 0; iSig < nSigsCount;
1125  iSig++, iKey++) {
1126  if ((checkBits >> iKey) == 0) {
1127  // This is a sanity check and should be
1128  // unrecheable.
1129  return set_error(
1131  }
1132 
1133  // Find the next suitable key.
1134  while (((checkBits >> iKey) & 0x01) == 0) {
1135  iKey++;
1136  }
1137 
1138  if (iKey >= nKeysCount) {
1139  // This is a sanity check and should be
1140  // unrecheable.
1141  return set_error(serror,
1143  }
1144 
1145  // Check the signature.
1146  valtype &vchSig =
1147  stacktop(-idxBottomSig + iSig);
1148  valtype &vchPubKey =
1149  stacktop(-idxBottomKey + iKey);
1150 
1151  // Note that only pubkeys associated with a
1152  // signature are checked for validity.
1154  vchSig, flags, serror) ||
1155  !CheckPubKeyEncoding(vchPubKey, flags,
1156  serror)) {
1157  // serror is set
1158  return false;
1159  }
1160 
1161  // Check signature
1162  if (!checker.CheckSig(vchSig, vchPubKey,
1163  scriptCode, flags)) {
1164  // This can fail if the signature is empty,
1165  // which also is a NULLFAIL error as the
1166  // bitfield should have been null in this
1167  // situation.
1168  return set_error(serror,
1170  }
1171 
1172  // this is guaranteed to execute exactly
1173  // nSigsCount times (if not script error)
1174  metrics.nSigChecks += 1;
1175  }
1176 
1177  if ((checkBits >> iKey) != 0) {
1178  // This is a sanity check and should be
1179  // unrecheable.
1180  return set_error(
1182  }
1183  } else {
1184  // LEGACY MULTISIG (ECDSA / NULL)
1185 
1186  // Remove signature for pre-fork scripts
1187  for (int k = 0; k < nSigsCount; k++) {
1188  valtype &vchSig = stacktop(-idxTopSig - k);
1189  CleanupScriptCode(scriptCode, vchSig, flags);
1190  }
1191 
1192  int nSigsRemaining = nSigsCount;
1193  int nKeysRemaining = nKeysCount;
1194  while (fSuccess && nSigsRemaining > 0) {
1195  valtype &vchSig = stacktop(
1196  -idxTopSig - (nSigsCount - nSigsRemaining));
1197  valtype &vchPubKey = stacktop(
1198  -idxTopKey - (nKeysCount - nKeysRemaining));
1199 
1200  // Note how this makes the exact order of
1201  // pubkey/signature evaluation distinguishable
1202  // by CHECKMULTISIG NOT if the STRICTENC flag is
1203  // set. See the script_(in)valid tests for
1204  // details.
1206  vchSig, flags, serror) ||
1207  !CheckPubKeyEncoding(vchPubKey, flags,
1208  serror)) {
1209  // serror is set
1210  return false;
1211  }
1212 
1213  // Check signature
1214  bool fOk = checker.CheckSig(vchSig, vchPubKey,
1215  scriptCode, flags);
1216 
1217  if (fOk) {
1218  nSigsRemaining--;
1219  }
1220  nKeysRemaining--;
1221 
1222  // If there are more signatures left than keys
1223  // left, then too many signatures have failed.
1224  // Exit early, without checking any further
1225  // signatures.
1226  if (nSigsRemaining > nKeysRemaining) {
1227  fSuccess = false;
1228  }
1229  }
1230 
1231  bool areAllSignaturesNull = true;
1232  for (int i = 0; i < nSigsCount; i++) {
1233  if (stacktop(-idxTopSig - i).size()) {
1234  areAllSignaturesNull = false;
1235  break;
1236  }
1237  }
1238 
1239  // If the operation failed, we may require that all
1240  // signatures must be empty vector
1241  if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) &&
1242  !areAllSignaturesNull) {
1243  return set_error(serror,
1245  }
1246 
1247  if (!areAllSignaturesNull) {
1248  // This is not identical to the number of actual
1249  // ECDSA verifies, but, it is an upper bound
1250  // that can be easily determined without doing
1251  // CPU-intensive checks.
1252  metrics.nSigChecks += nKeysCount;
1253  }
1254  }
1255 
1256  // Clean up stack of all arguments
1257  for (size_t i = 0; i < idxDummy; i++) {
1258  popstack(stack);
1259  }
1260 
1261  stack.push_back(fSuccess ? vchTrue : vchFalse);
1262  if (opcode == OP_CHECKMULTISIGVERIFY) {
1263  if (fSuccess) {
1264  popstack(stack);
1265  } else {
1266  return set_error(
1268  }
1269  }
1270  } break;
1271 
1272  //
1273  // Byte string operations
1274  //
1275  case OP_CAT: {
1276  // (x1 x2 -- out)
1277  if (stack.size() < 2) {
1278  return set_error(
1280  }
1281  valtype &vch1 = stacktop(-2);
1282  valtype &vch2 = stacktop(-1);
1283  if (vch1.size() + vch2.size() >
1285  return set_error(serror, ScriptError::PUSH_SIZE);
1286  }
1287  vch1.insert(vch1.end(), vch2.begin(), vch2.end());
1288  popstack(stack);
1289  } break;
1290 
1291  case OP_SPLIT: {
1292  // (in position -- x1 x2)
1293  if (stack.size() < 2) {
1294  return set_error(
1296  }
1297 
1298  const valtype &data = stacktop(-2);
1299 
1300  // Make sure the split point is appropriate.
1301  uint64_t position =
1302  CScriptNum(stacktop(-1), fRequireMinimal).getint();
1303  if (position > data.size()) {
1304  return set_error(serror,
1306  }
1307 
1308  // Prepare the results in their own buffer as `data`
1309  // will be invalidated.
1310  valtype n1(data.begin(), data.begin() + position);
1311  valtype n2(data.begin() + position, data.end());
1312 
1313  // Replace existing stack values by the new values.
1314  stacktop(-2) = std::move(n1);
1315  stacktop(-1) = std::move(n2);
1316  } break;
1317 
1318  case OP_REVERSEBYTES: {
1319  // (in -- out)
1320  if (stack.size() < 1) {
1321  return set_error(
1323  }
1324 
1325  valtype &data = stacktop(-1);
1326  std::reverse(data.begin(), data.end());
1327  } break;
1328 
1329  //
1330  // Conversion operations
1331  //
1332  case OP_NUM2BIN: {
1333  // (in size -- out)
1334  if (stack.size() < 2) {
1335  return set_error(
1337  }
1338 
1339  uint64_t size =
1340  CScriptNum(stacktop(-1), fRequireMinimal).getint();
1341  if (size > MAX_SCRIPT_ELEMENT_SIZE) {
1342  return set_error(serror, ScriptError::PUSH_SIZE);
1343  }
1344 
1345  popstack(stack);
1346  valtype &rawnum = stacktop(-1);
1347 
1348  // Try to see if we can fit that number in the number of
1349  // byte requested.
1351  if (rawnum.size() > size) {
1352  // We definitively cannot.
1353  return set_error(serror,
1355  }
1356 
1357  // We already have an element of the right size, we
1358  // don't need to do anything.
1359  if (rawnum.size() == size) {
1360  break;
1361  }
1362 
1363  uint8_t signbit = 0x00;
1364  if (rawnum.size() > 0) {
1365  signbit = rawnum.back() & 0x80;
1366  rawnum[rawnum.size() - 1] &= 0x7f;
1367  }
1368 
1369  rawnum.reserve(size);
1370  while (rawnum.size() < size - 1) {
1371  rawnum.push_back(0x00);
1372  }
1373 
1374  rawnum.push_back(signbit);
1375  } break;
1376 
1377  case OP_BIN2NUM: {
1378  // (in -- out)
1379  if (stack.size() < 1) {
1380  return set_error(
1382  }
1383 
1384  valtype &n = stacktop(-1);
1386 
1387  // The resulting number must be a valid number.
1389  return set_error(serror,
1391  }
1392  } break;
1393 
1394  default:
1395  return set_error(serror, ScriptError::BAD_OPCODE);
1396  }
1397  }
1398 
1399  // Size limits
1400  if (stack.size() + altstack.size() > MAX_STACK_SIZE) {
1401  return set_error(serror, ScriptError::STACK_SIZE);
1402  }
1403  }
1404  } catch (...) {
1405  return set_error(serror, ScriptError::UNKNOWN);
1406  }
1407 
1408  if (!vfExec.empty()) {
1409  return set_error(serror, ScriptError::UNBALANCED_CONDITIONAL);
1410  }
1411 
1412  return set_success(serror);
1413 }
1414 
1415 namespace {
1416 
1421 template <class T> class CTransactionSignatureSerializer {
1422 private:
1424  const T &txTo;
1426  const CScript &scriptCode;
1428  const unsigned int nIn;
1430  const SigHashType sigHashType;
1431 
1432 public:
1433  CTransactionSignatureSerializer(const T &txToIn,
1434  const CScript &scriptCodeIn,
1435  unsigned int nInIn,
1436  SigHashType sigHashTypeIn)
1437  : txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1438  sigHashType(sigHashTypeIn) {}
1439 
1441  template <typename S> void SerializeScriptCode(S &s) const {
1442  CScript::const_iterator it = scriptCode.begin();
1443  CScript::const_iterator itBegin = it;
1444  opcodetype opcode;
1445  unsigned int nCodeSeparators = 0;
1446  while (scriptCode.GetOp(it, opcode)) {
1447  if (opcode == OP_CODESEPARATOR) {
1448  nCodeSeparators++;
1449  }
1450  }
1451  ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1452  it = itBegin;
1453  while (scriptCode.GetOp(it, opcode)) {
1454  if (opcode == OP_CODESEPARATOR) {
1455  s.write((char *)&itBegin[0], it - itBegin - 1);
1456  itBegin = it;
1457  }
1458  }
1459  if (itBegin != scriptCode.end()) {
1460  s.write((char *)&itBegin[0], it - itBegin);
1461  }
1462  }
1463 
1465  template <typename S> void SerializeInput(S &s, unsigned int nInput) const {
1466  // In case of SIGHASH_ANYONECANPAY, only the input being signed is
1467  // serialized
1468  if (sigHashType.hasAnyoneCanPay()) {
1469  nInput = nIn;
1470  }
1471  // Serialize the prevout
1472  ::Serialize(s, txTo.vin[nInput].prevout);
1473  // Serialize the script
1474  if (nInput != nIn) {
1475  // Blank out other inputs' signatures
1476  ::Serialize(s, CScript());
1477  } else {
1478  SerializeScriptCode(s);
1479  }
1480  // Serialize the nSequence
1481  if (nInput != nIn &&
1482  (sigHashType.getBaseType() == BaseSigHashType::SINGLE ||
1483  sigHashType.getBaseType() == BaseSigHashType::NONE)) {
1484  // let the others update at will
1485  ::Serialize(s, (int)0);
1486  } else {
1487  ::Serialize(s, txTo.vin[nInput].nSequence);
1488  }
1489  }
1490 
1492  template <typename S>
1493  void SerializeOutput(S &s, unsigned int nOutput) const {
1494  if (sigHashType.getBaseType() == BaseSigHashType::SINGLE &&
1495  nOutput != nIn) {
1496  // Do not lock-in the txout payee at other indices as txin
1497  ::Serialize(s, CTxOut());
1498  } else {
1499  ::Serialize(s, txTo.vout[nOutput]);
1500  }
1501  }
1502 
1504  template <typename S> void Serialize(S &s) const {
1505  // Serialize nVersion
1506  ::Serialize(s, txTo.nVersion);
1507  // Serialize vin
1508  unsigned int nInputs =
1509  sigHashType.hasAnyoneCanPay() ? 1 : txTo.vin.size();
1510  ::WriteCompactSize(s, nInputs);
1511  for (unsigned int nInput = 0; nInput < nInputs; nInput++) {
1512  SerializeInput(s, nInput);
1513  }
1514  // Serialize vout
1515  unsigned int nOutputs =
1516  (sigHashType.getBaseType() == BaseSigHashType::NONE)
1517  ? 0
1518  : ((sigHashType.getBaseType() == BaseSigHashType::SINGLE)
1519  ? nIn + 1
1520  : txTo.vout.size());
1521  ::WriteCompactSize(s, nOutputs);
1522  for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++) {
1523  SerializeOutput(s, nOutput);
1524  }
1525  // Serialize nLockTime
1526  ::Serialize(s, txTo.nLockTime);
1527  }
1528 };
1529 
1530 template <class T> uint256 GetPrevoutHash(const T &txTo) {
1531  CHashWriter ss(SER_GETHASH, 0);
1532  for (const auto &txin : txTo.vin) {
1533  ss << txin.prevout;
1534  }
1535  return ss.GetHash();
1536 }
1537 
1538 template <class T> uint256 GetSequenceHash(const T &txTo) {
1539  CHashWriter ss(SER_GETHASH, 0);
1540  for (const auto &txin : txTo.vin) {
1541  ss << txin.nSequence;
1542  }
1543  return ss.GetHash();
1544 }
1545 
1546 template <class T> uint256 GetOutputsHash(const T &txTo) {
1547  CHashWriter ss(SER_GETHASH, 0);
1548  for (const auto &txout : txTo.vout) {
1549  ss << txout;
1550  }
1551  return ss.GetHash();
1552 }
1553 
1554 } // namespace
1555 
1556 template <class T>
1558  hashPrevouts = GetPrevoutHash(txTo);
1559  hashSequence = GetSequenceHash(txTo);
1560  hashOutputs = GetOutputsHash(txTo);
1561 }
1562 
1563 // explicit instantiation
1565  const CTransaction &txTo);
1567  const CMutableTransaction &txTo);
1568 
1569 template <class T>
1570 uint256 SignatureHash(const CScript &scriptCode, const T &txTo,
1571  unsigned int nIn, SigHashType sigHashType,
1572  const Amount amount,
1573  const PrecomputedTransactionData *cache, uint32_t flags) {
1574  assert(nIn < txTo.vin.size());
1575 
1576  if (flags & SCRIPT_ENABLE_REPLAY_PROTECTION) {
1577  // Legacy chain's value for fork id must be of the form 0xffxxxx.
1578  // By xoring with 0xdead, we ensure that the value will be different
1579  // from the original one, even if it already starts with 0xff.
1580  uint32_t newForkValue = sigHashType.getForkValue() ^ 0xdead;
1581  sigHashType = sigHashType.withForkValue(0xff0000 | newForkValue);
1582  }
1583 
1584  if (sigHashType.hasForkId() && (flags & SCRIPT_ENABLE_SIGHASH_FORKID)) {
1585  uint256 hashPrevouts;
1586  uint256 hashSequence;
1587  uint256 hashOutputs;
1588 
1589  if (!sigHashType.hasAnyoneCanPay()) {
1590  hashPrevouts = cache ? cache->hashPrevouts : GetPrevoutHash(txTo);
1591  }
1592 
1593  if (!sigHashType.hasAnyoneCanPay() &&
1594  (sigHashType.getBaseType() != BaseSigHashType::SINGLE) &&
1595  (sigHashType.getBaseType() != BaseSigHashType::NONE)) {
1596  hashSequence = cache ? cache->hashSequence : GetSequenceHash(txTo);
1597  }
1598 
1599  if ((sigHashType.getBaseType() != BaseSigHashType::SINGLE) &&
1600  (sigHashType.getBaseType() != BaseSigHashType::NONE)) {
1601  hashOutputs = cache ? cache->hashOutputs : GetOutputsHash(txTo);
1602  } else if ((sigHashType.getBaseType() == BaseSigHashType::SINGLE) &&
1603  (nIn < txTo.vout.size())) {
1604  CHashWriter ss(SER_GETHASH, 0);
1605  ss << txTo.vout[nIn];
1606  hashOutputs = ss.GetHash();
1607  }
1608 
1609  CHashWriter ss(SER_GETHASH, 0);
1610  // Version
1611  ss << txTo.nVersion;
1612  // Input prevouts/nSequence (none/all, depending on flags)
1613  ss << hashPrevouts;
1614  ss << hashSequence;
1615  // The input being signed (replacing the scriptSig with scriptCode +
1616  // amount). The prevout may already be contained in hashPrevout, and the
1617  // nSequence may already be contain in hashSequence.
1618  ss << txTo.vin[nIn].prevout;
1619  ss << scriptCode;
1620  ss << amount;
1621  ss << txTo.vin[nIn].nSequence;
1622  // Outputs (none/one/all, depending on flags)
1623  ss << hashOutputs;
1624  // Locktime
1625  ss << txTo.nLockTime;
1626  // Sighash type
1627  ss << sigHashType;
1628 
1629  return ss.GetHash();
1630  }
1631 
1632  // Check for invalid use of SIGHASH_SINGLE
1633  if ((sigHashType.getBaseType() == BaseSigHashType::SINGLE) &&
1634  (nIn >= txTo.vout.size())) {
1635  // nOut out of range
1636  return UINT256_ONE();
1637  }
1638 
1639  // Wrapper to serialize only the necessary parts of the transaction being
1640  // signed
1641  CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn,
1642  sigHashType);
1643 
1644  // Serialize and hash
1645  CHashWriter ss(SER_GETHASH, 0);
1646  ss << txTmp << sigHashType;
1647  return ss.GetHash();
1648 }
1649 
1650 bool BaseSignatureChecker::VerifySignature(const std::vector<uint8_t> &vchSig,
1651  const CPubKey &pubkey,
1652  const uint256 &sighash) const {
1653  if (vchSig.size() == 64) {
1654  return pubkey.VerifySchnorr(sighash, vchSig);
1655  } else {
1656  return pubkey.VerifyECDSA(sighash, vchSig);
1657  }
1658 }
1659 
1660 template <class T>
1662  const std::vector<uint8_t> &vchSigIn, const std::vector<uint8_t> &vchPubKey,
1663  const CScript &scriptCode, uint32_t flags) const {
1664  CPubKey pubkey(vchPubKey);
1665  if (!pubkey.IsValid()) {
1666  return false;
1667  }
1668 
1669  // Hash type is one byte tacked on to the end of the signature
1670  std::vector<uint8_t> vchSig(vchSigIn);
1671  if (vchSig.empty()) {
1672  return false;
1673  }
1674  SigHashType sigHashType = GetHashType(vchSig);
1675  vchSig.pop_back();
1676 
1677  uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, sigHashType, amount,
1678  this->txdata, flags);
1679 
1680  if (!VerifySignature(vchSig, pubkey, sighash)) {
1681  return false;
1682  }
1683 
1684  return true;
1685 }
1686 
1687 template <class T>
1689  const CScriptNum &nLockTime) const {
1690  // There are two kinds of nLockTime: lock-by-blockheight and
1691  // lock-by-blocktime, distinguished by whether nLockTime <
1692  // LOCKTIME_THRESHOLD.
1693  //
1694  // We want to compare apples to apples, so fail the script unless the type
1695  // of nLockTime being tested is the same as the nLockTime in the
1696  // transaction.
1697  if (!((txTo->nLockTime < LOCKTIME_THRESHOLD &&
1698  nLockTime < LOCKTIME_THRESHOLD) ||
1699  (txTo->nLockTime >= LOCKTIME_THRESHOLD &&
1700  nLockTime >= LOCKTIME_THRESHOLD))) {
1701  return false;
1702  }
1703 
1704  // Now that we know we're comparing apples-to-apples, the comparison is a
1705  // simple numeric one.
1706  if (nLockTime > int64_t(txTo->nLockTime)) {
1707  return false;
1708  }
1709 
1710  // Finally the nLockTime feature can be disabled and thus
1711  // CHECKLOCKTIMEVERIFY bypassed if every txin has been finalized by setting
1712  // nSequence to maxint. The transaction would be allowed into the
1713  // blockchain, making the opcode ineffective.
1714  //
1715  // Testing if this vin is not final is sufficient to prevent this condition.
1716  // Alternatively we could test all inputs, but testing just this input
1717  // minimizes the data required to prove correct CHECKLOCKTIMEVERIFY
1718  // execution.
1719  if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence) {
1720  return false;
1721  }
1722 
1723  return true;
1724 }
1725 
1726 template <class T>
1728  const CScriptNum &nSequence) const {
1729  // Relative lock times are supported by comparing the passed in operand to
1730  // the sequence number of the input.
1731  const int64_t txToSequence = int64_t(txTo->vin[nIn].nSequence);
1732 
1733  // Fail if the transaction's version number is not set high enough to
1734  // trigger BIP 68 rules.
1735  if (static_cast<uint32_t>(txTo->nVersion) < 2) {
1736  return false;
1737  }
1738 
1739  // Sequence numbers with their most significant bit set are not consensus
1740  // constrained. Testing that the transaction's sequence number do not have
1741  // this bit set prevents using this property to get around a
1742  // CHECKSEQUENCEVERIFY check.
1743  if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
1744  return false;
1745  }
1746 
1747  // Mask off any bits that do not have consensus-enforced meaning before
1748  // doing the integer comparisons
1749  const uint32_t nLockTimeMask =
1751  const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1752  const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1753 
1754  // There are two kinds of nSequence: lock-by-blockheight and
1755  // lock-by-blocktime, distinguished by whether nSequenceMasked <
1756  // CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1757  //
1758  // We want to compare apples to apples, so fail the script unless the type
1759  // of nSequenceMasked being tested is the same as the nSequenceMasked in the
1760  // transaction.
1761  if (!((txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG &&
1762  nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1763  (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG &&
1764  nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG))) {
1765  return false;
1766  }
1767 
1768  // Now that we know we're comparing apples-to-apples, the comparison is a
1769  // simple numeric one.
1770  if (nSequenceMasked > txToSequenceMasked) {
1771  return false;
1772  }
1773 
1774  return true;
1775 }
1776 
1777 // explicit instantiation
1780 
1781 bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey,
1782  uint32_t flags, const BaseSignatureChecker &checker,
1783  ScriptExecutionMetrics &metricsOut, ScriptError *serror) {
1784  set_error(serror, ScriptError::UNKNOWN);
1785 
1786  // If FORKID is enabled, we also ensure strict encoding.
1787  if (flags & SCRIPT_ENABLE_SIGHASH_FORKID) {
1788  flags |= SCRIPT_VERIFY_STRICTENC;
1789  }
1790 
1791  if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1792  return set_error(serror, ScriptError::SIG_PUSHONLY);
1793  }
1794 
1795  ScriptExecutionMetrics metrics = {};
1796 
1797  // scriptSig and scriptPubKey must be evaluated sequentially on the same
1798  // stack rather than being simply concatenated (see CVE-2010-5141)
1799  std::vector<valtype> stack, stackCopy;
1800  if (!EvalScript(stack, scriptSig, flags, checker, metrics, serror)) {
1801  // serror is set
1802  return false;
1803  }
1804  if (flags & SCRIPT_VERIFY_P2SH) {
1805  stackCopy = stack;
1806  }
1807  if (!EvalScript(stack, scriptPubKey, flags, checker, metrics, serror)) {
1808  // serror is set
1809  return false;
1810  }
1811  if (stack.empty()) {
1812  return set_error(serror, ScriptError::EVAL_FALSE);
1813  }
1814  if (CastToBool(stack.back()) == false) {
1815  return set_error(serror, ScriptError::EVAL_FALSE);
1816  }
1817 
1818  // Additional validation for spend-to-script-hash transactions:
1819  if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash()) {
1820  // scriptSig must be literals-only or validation fails
1821  if (!scriptSig.IsPushOnly()) {
1822  return set_error(serror, ScriptError::SIG_PUSHONLY);
1823  }
1824 
1825  // Restore stack.
1826  swap(stack, stackCopy);
1827 
1828  // stack cannot be empty here, because if it was the P2SH HASH <> EQUAL
1829  // scriptPubKey would be evaluated with an empty stack and the
1830  // EvalScript above would return false.
1831  assert(!stack.empty());
1832 
1833  const valtype &pubKeySerialized = stack.back();
1834  CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1835  popstack(stack);
1836 
1837  // Bail out early if SCRIPT_DISALLOW_SEGWIT_RECOVERY is not set, the
1838  // redeem script is a p2sh segwit program, and it was the only item
1839  // pushed onto the stack.
1840  if ((flags & SCRIPT_DISALLOW_SEGWIT_RECOVERY) == 0 && stack.empty() &&
1841  pubKey2.IsWitnessProgram()) {
1842  // must set metricsOut for all successful returns
1843  metricsOut = metrics;
1844  return set_success(serror);
1845  }
1846 
1847  if (!EvalScript(stack, pubKey2, flags, checker, metrics, serror)) {
1848  // serror is set
1849  return false;
1850  }
1851  if (stack.empty()) {
1852  return set_error(serror, ScriptError::EVAL_FALSE);
1853  }
1854  if (!CastToBool(stack.back())) {
1855  return set_error(serror, ScriptError::EVAL_FALSE);
1856  }
1857  }
1858 
1859  // The CLEANSTACK check is only performed after potential P2SH evaluation,
1860  // as the non-P2SH evaluation of a P2SH script will obviously not result in
1861  // a clean stack (the P2SH inputs remain). The same holds for witness
1862  // evaluation.
1863  if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
1864  // Disallow CLEANSTACK without P2SH, as otherwise a switch
1865  // CLEANSTACK->P2SH+CLEANSTACK would be possible, which is not a
1866  // softfork (and P2SH should be one).
1867  assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1868  if (stack.size() != 1) {
1869  return set_error(serror, ScriptError::CLEANSTACK);
1870  }
1871  }
1872 
1873  if (flags & SCRIPT_VERIFY_INPUT_SIGCHECKS) {
1874  // This limit is intended for standard use, and is based on an
1875  // examination of typical and historical standard uses.
1876  // - allowing P2SH ECDSA multisig with compressed keys, which at an
1877  // extreme (1-of-15) may have 15 SigChecks in ~590 bytes of scriptSig.
1878  // - allowing Bare ECDSA multisig, which at an extreme (1-of-3) may have
1879  // 3 sigchecks in ~72 bytes of scriptSig.
1880  // - Since the size of an input is 41 bytes + length of scriptSig, then
1881  // the most dense possible inputs satisfying this rule would be:
1882  // 2 sigchecks and 26 bytes: 1/33.50 sigchecks/byte.
1883  // 3 sigchecks and 69 bytes: 1/36.66 sigchecks/byte.
1884  // The latter can be readily done with 1-of-3 bare multisignatures,
1885  // however the former is not practically doable with standard scripts,
1886  // so the practical density limit is 1/36.66.
1887  static_assert(INT_MAX > MAX_SCRIPT_SIZE,
1888  "overflow sanity check on max script size");
1889  static_assert(INT_MAX / 43 / 3 > MAX_OPS_PER_SCRIPT,
1890  "overflow sanity check on maximum possible sigchecks "
1891  "from sig+redeem+pub scripts");
1892  if (int(scriptSig.size()) < metrics.nSigChecks * 43 - 60) {
1893  return set_error(serror, ScriptError::INPUT_SIGCHECKS);
1894  }
1895  }
1896 
1897  metricsOut = metrics;
1898  return set_success(serror);
1899 }
Definition: script.h:130
Definition: script.h:59
Definition: script.h:115
bool CheckSequence(const CScriptNum &nSequence) const final override
virtual bool CheckLockTime(const CScriptNum &nLockTime) const
Definition: interpreter.h:43
static const int MAX_PUBKEYS_PER_MULTISIG
Definition: script.h:29
Definition: script.h:98
const int nVersion
Definition: hash.h:125
bool hasForkId() const
Definition: sighashtype.h:77
bool EvalScript(std::vector< valtype > &stack, const CScript &script, uint32_t flags, const BaseSignatureChecker &checker, ScriptExecutionMetrics &metrics, ScriptError *serror)
int getint() const
Definition: script.h:351
Definition: script.h:151
Definition: script.h:90
bool hasAnyoneCanPay() const
Definition: sighashtype.h:79
iterator insert(iterator pos, const T &value)
Definition: prevector.h:441
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:1189
bool IsPayToScriptHash() const
Definition: script.cpp:372
Definition: script.h:76
Definition: script.h:69
Definition: script.h:65
virtual bool VerifySignature(const std::vector< uint8_t > &vchSig, const CPubKey &vchPubKey, const uint256 &sighash) const
Definition: script.h:92
Precompute sighash midstate to avoid quadratic hashing.
Definition: transaction.h:348
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime.
Definition: transaction.h:77
CHash160 & Write(const uint8_t *data, size_t len)
Definition: hash.h:60
BaseSigHashType getBaseType() const
Definition: sighashtype.h:64
Definition: script.h:129
static void popstack(std::vector< valtype > &stack)
Definition: interpreter.cpp:38
Definition: script.h:57
Definition: script.h:136
Definition: script.h:63
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
If this flag set, CTxIn::nSequence is NOT interpreted as a relative lock-time.
Definition: transaction.h:84
virtual bool CheckSig(const std::vector< uint8_t > &vchSigIn, const std::vector< uint8_t > &vchPubKey, const CScript &scriptCode, uint32_t flags) const
Definition: interpreter.h:37
bool VerifyECDSA(const uint256 &hash, const std::vector< uint8_t > &vchSig) const
Verify a DER-serialized ECDSA signature (~72 bytes).
Definition: pubkey.cpp:173
Definition: amount.h:17
Definition: script.h:58
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, uint32_t flags, const BaseSignatureChecker &checker, ScriptExecutionMetrics &metricsOut, ScriptError *serror)
Execute an unlocking and locking script together.
uint256 SignatureHash(const CScript &scriptCode, const T &txTo, unsigned int nIn, SigHashType sigHashType, const Amount amount, const PrecomputedTransactionData *cache, uint32_t flags)
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:22
ScriptError
Definition: script_error.h:9
bool VerifySchnorr(const uint256 &hash, const std::array< uint8_t, SCHNORR_SIZE > &sig) const
Verify a Schnorr signature (=64 bytes).
Definition: pubkey.cpp:200
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:23
Definition: script.h:150
uint256 & UINT256_ONE()
Definition: uint256.cpp:70
Definition: script.h:71
Definition: script.h:67
static const int MAX_OPS_PER_SCRIPT
Definition: script.h:26
void Serialize(Stream &s, char a)
Definition: serialize.h:261
Definition: script.h:116
static bool IsMinimallyEncoded(const std::vector< uint8_t > &vch, const size_t nMaxNumSize=CScriptNum::MAXIMUM_ELEMENT_SIZE)
Definition: script.cpp:298
bool CheckMinimalPush(const std::vector< uint8_t > &data, opcodetype opcode)
Check whether the given stack element data would be minimally pushed using the given opcode...
Definition: script.cpp:267
std::vector< CTxIn > vin
Definition: transaction.h:299
CRIPEMD160 & Write(const uint8_t *data, size_t len)
Definition: ripemd160.cpp:286
bool CheckLockTime(const CScriptNum &nLockTime) const final override
Definition: script.h:60
iterator end()
Definition: prevector.h:390
static bool IsOpcodeDisabled(opcodetype opcode, uint32_t flags)
Definition: interpreter.cpp:83
bool CheckTransactionECDSASignatureEncoding(const valtype &vchSig, uint32_t flags, ScriptError *serror)
Check that the signature provided to authentify a transaction is properly encoded ECDSA signature...
Definition: script.h:137
Struct for holding cumulative results from executing a script or a sequence of scripts.
opcodetype
Script opcodes.
Definition: script.h:46
bool CheckDataSignatureEncoding(const valtype &vchSig, uint32_t flags, ScriptError *serror)
Check that the signature provided on some data is properly encoded.
Definition: script.h:107
bool IsPushOnly(const_iterator pc) const
Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical).
Definition: script.cpp:424
bool IsValid() const
Definition: pubkey.h:147
An encapsulated public key.
Definition: pubkey.h:31
Definition: script.h:62
static bool EvalChecksig(const valtype &vchSig, const valtype &vchPubKey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, uint32_t flags, const BaseSignatureChecker &checker, ScriptExecutionMetrics &metrics, ScriptError *serror, bool &fSuccess)
Helper for OP_CHECKSIG and OP_CHECKSIGVERIFY.
Definition: script.h:55
SigHashType withForkValue(uint32_t forkId) const
Definition: sighashtype.h:50
Definition: script.h:74
Definition: script.h:99
#define stacktop(i)
Script is a stack machine (like Forth) that evaluates a predicate returning a bool indicating valid o...
Definition: interpreter.cpp:36
uint32_t getForkValue() const
Definition: sighashtype.h:68
Definition: script.h:134
An output of a transaction.
Definition: transaction.h:141
static const int MAX_SCRIPT_SIZE
Definition: script.h:32
Definition: script.h:102
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG
If CTxIn::nSequence encodes a relative lock-time and this flag is set, the relative lock-time has uni...
Definition: transaction.h:91
static const int MAX_STACK_SIZE
Definition: script.h:35
Definition: script.h:135
#define altstacktop(i)
Definition: interpreter.cpp:37
Definition: script.h:80
CHash256 & Write(const uint8_t *data, size_t len)
Definition: hash.h:35
int flags
Definition: bitcoin-tx.cpp:529
uint256 GetHash()
Definition: hash.h:139
Definition: script.h:64
256-bit opaque blob.
Definition: uint256.h:120
Definition: script.h:96
Definition: script.h:89
bool CheckSig(const std::vector< uint8_t > &vchSigIn, const std::vector< uint8_t > &vchPubKey, const CScript &scriptCode, uint32_t flags) const final override
std::vector< uint8_t > getvch() const
Definition: script.h:360
static const uint32_t SEQUENCE_LOCKTIME_MASK
If CTxIn::nSequence encodes a relative lock-time, this mask is applied to extract that lock-time from...
Definition: transaction.h:97
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:429
bool CheckTransactionSignatureEncoding(const valtype &vchSig, uint32_t flags, ScriptError *serror)
Check that the signature provided to authentify a transaction is properly encoded.
bool empty() const
Definition: prevector.h:386
static void CleanupScriptCode(CScript &scriptCode, const std::vector< uint8_t > &vchSig, uint32_t flags)
Definition: interpreter.cpp:73
A mutable version of CTransaction.
Definition: transaction.h:297
bool DecodeBitfield(const std::vector< uint8_t > &vch, unsigned size, uint32_t &bitfield, ScriptError *serror)
Definition: bitfield.cpp:12
CSHA256 & Write(const uint8_t *data, size_t len)
Definition: sha256.cpp:819
Definition: script.h:61
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< uint8_t > &vchRet) const
Definition: script.h:524
A hasher class for SHA1.
Definition: sha1.h:12
virtual bool CheckSequence(const CScriptNum &nSequence) const
Definition: interpreter.h:47
iterator begin()
Definition: prevector.h:388
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:120
size_type size() const
Definition: prevector.h:384
CSHA1 & Write(const uint8_t *data, size_t len)
Definition: sha1.cpp:154
Definition: script.h:68
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:211
A hasher class for Bitcoin&#39;s 160-bit hash (SHA-256 + RIPEMD-160).
Definition: hash.h:47
Definition: script.h:117
Definition: script.h:66
A hasher class for SHA-256.
Definition: sha256.h:13
int FindAndDelete(CScript &script, const CScript &b)
Definition: interpreter.cpp:45
bool CastToBool(const valtype &vch)
Definition: interpreter.cpp:19
uint32_t countBits(uint32_t v)
Definition: bitmanip.h:12
Definition: script.h:133
Definition: script.h:70
static bool MinimallyEncode(std::vector< uint8_t > &data)
Definition: script.cpp:326
A hasher class for RIPEMD-160.
Definition: ripemd160.h:12
Signature hash type wrapper class.
Definition: sighashtype.h:37
Definition: script.h:97
bool CheckTransactionSchnorrSignatureEncoding(const valtype &vchSig, uint32_t flags, ScriptError *serror)
Check that the signature provided to authentify a transaction is properly encoded Schnorr signature (...
std::vector< uint8_t > valtype
Definition: sigencoding.h:16
bool CheckPubKeyEncoding(const valtype &vchPubKey, uint32_t flags, ScriptError *serror)
Check that a public key is encoded properly.