Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

interpreter.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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() < 33) {
65  // Non-canonical public key: too short
66  return false;
67  }
68  if (vchPubKey[0] == 0x04) {
69  if (vchPubKey.size() != 65) {
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() != 33) {
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 
95 bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
96  // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
97  // * total-length: 1-byte length descriptor of everything that follows,
98  // excluding the sighash byte.
99  // * R-length: 1-byte length descriptor of the R value that follows.
100  // * R: arbitrary-length big-endian encoded R value. It must use the shortest
101  // possible encoding for a positive integers (which means no null bytes at
102  // the start, except a single one when the next byte has its highest bit set).
103  // * S-length: 1-byte length descriptor of the S value that follows.
104  // * S: arbitrary-length big-endian encoded S value. The same rules apply.
105  // * sighash: 1-byte value indicating what data is hashed (not part of the DER
106  // signature)
107 
108  // Minimum and maximum size constraints.
109  if (sig.size() < 9) return false;
110  if (sig.size() > 73) return false;
111 
112  // A signature is of type 0x30 (compound).
113  if (sig[0] != 0x30) return false;
114 
115  // Make sure the length covers the entire signature.
116  if (sig[1] != sig.size() - 3) return false;
117 
118  // Extract the length of the R element.
119  unsigned int lenR = sig[3];
120 
121  // Make sure the length of the S element is still inside the signature.
122  if (5 + lenR >= sig.size()) return false;
123 
124  // Extract the length of the S element.
125  unsigned int lenS = sig[5 + lenR];
126 
127  // Verify that the length of the signature matches the sum of the length
128  // of the elements.
129  if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
130 
131  // Check whether the R element is an integer.
132  if (sig[2] != 0x02) return false;
133 
134  // Zero-length integers are not allowed for R.
135  if (lenR == 0) return false;
136 
137  // Negative numbers are not allowed for R.
138  if (sig[4] & 0x80) return false;
139 
140  // Null bytes at the start of R are not allowed, unless R would
141  // otherwise be interpreted as a negative number.
142  if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
143 
144  // Check whether the S element is an integer.
145  if (sig[lenR + 4] != 0x02) return false;
146 
147  // Zero-length integers are not allowed for S.
148  if (lenS == 0) return false;
149 
150  // Negative numbers are not allowed for S.
151  if (sig[lenR + 6] & 0x80) return false;
152 
153  // Null bytes at the start of S are not allowed, unless S would otherwise be
154  // interpreted as a negative number.
155  if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
156 
157  return true;
158 }
159 
160 bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
161  if (!IsValidSignatureEncoding(vchSig)) {
162  return set_error(serror, SCRIPT_ERR_SIG_DER);
163  }
164  // https://bitcoin.stackexchange.com/a/12556:
165  // Also note that inside transaction signatures, an extra hashtype byte
166  // follows the actual signature data.
167  std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
168  // If the S value is above the order of the curve divided by two, its
169  // complement modulo the order could have been used instead, which is
170  // one byte shorter when encoded correctly.
171  if (!CPubKey::CheckLowS(vchSigCopy)) {
172  return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
173  }
174  return true;
175 }
176 
177 bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
178  if (vchSig.size() == 0) {
179  return false;
180  }
181  unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
182  if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
183  return false;
184 
185  return true;
186 }
187 
188 bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
189  // Empty signature. Not strictly DER encoded, but allowed to provide a
190  // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
191  if (vchSig.size() == 0) {
192  return true;
193  }
195  return set_error(serror, SCRIPT_ERR_SIG_DER);
196  } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
197  // serror is set
198  return false;
199  } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
200  return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
201  }
202  return true;
203 }
204 
205 bool static CheckPubKeyEncoding(const valtype &vchSig, unsigned int flags, ScriptError* serror) {
207  return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
208  }
209  return true;
210 }
211 
212 bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
213  if (data.size() == 0) {
214  // Could have used OP_0.
215  return opcode == OP_0;
216  } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
217  // Could have used OP_1 .. OP_16.
218  return opcode == OP_1 + (data[0] - 1);
219  } else if (data.size() == 1 && data[0] == 0x81) {
220  // Could have used OP_1NEGATE.
221  return opcode == OP_1NEGATE;
222  } else if (data.size() <= 75) {
223  // Could have used a direct push (opcode indicating number of bytes pushed + those bytes).
224  return opcode == data.size();
225  } else if (data.size() <= 255) {
226  // Could have used OP_PUSHDATA.
227  return opcode == OP_PUSHDATA1;
228  } else if (data.size() <= 65535) {
229  // Could have used OP_PUSHDATA2.
230  return opcode == OP_PUSHDATA2;
231  }
232  return true;
233 }
234 
235 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
236 {
237  static const CScriptNum bnZero(0);
238  static const CScriptNum bnOne(1);
239  // static const CScriptNum bnFalse(0);
240  // static const CScriptNum bnTrue(1);
241  static const valtype vchFalse(0);
242  // static const valtype vchZero(0);
243  static const valtype vchTrue(1, 1);
244 
245  CScript::const_iterator pc = script.begin();
246  CScript::const_iterator pend = script.end();
247  CScript::const_iterator pbegincodehash = script.begin();
248  opcodetype opcode;
249  valtype vchPushValue;
250  std::vector<bool> vfExec;
251  std::vector<valtype> altstack;
252  set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
253  if (script.size() > MAX_SCRIPT_SIZE)
254  return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
255  int nOpCount = 0;
256  bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
257 
258  try
259  {
260  while (pc < pend)
261  {
262  bool fExec = !count(vfExec.begin(), vfExec.end(), false);
263 
264  //
265  // Read instruction
266  //
267  if (!script.GetOp(pc, opcode, vchPushValue))
268  return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
269  if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
270  return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
271 
272  // Note how OP_RESERVED does not count towards the opcode limit.
273  if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
274  return set_error(serror, SCRIPT_ERR_OP_COUNT);
275 
276  if (opcode == OP_CAT ||
277  opcode == OP_SUBSTR ||
278  opcode == OP_LEFT ||
279  opcode == OP_RIGHT ||
280  opcode == OP_INVERT ||
281  opcode == OP_AND ||
282  opcode == OP_OR ||
283  opcode == OP_XOR ||
284  opcode == OP_2MUL ||
285  opcode == OP_2DIV ||
286  opcode == OP_MUL ||
287  opcode == OP_DIV ||
288  opcode == OP_MOD ||
289  opcode == OP_LSHIFT ||
290  opcode == OP_RSHIFT)
291  return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes.
292 
293  if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
294  if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
295  return set_error(serror, SCRIPT_ERR_MINIMALDATA);
296  }
297  stack.push_back(vchPushValue);
298  } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
299  switch (opcode)
300  {
301  //
302  // Push value
303  //
304  case OP_1NEGATE:
305  case OP_1:
306  case OP_2:
307  case OP_3:
308  case OP_4:
309  case OP_5:
310  case OP_6:
311  case OP_7:
312  case OP_8:
313  case OP_9:
314  case OP_10:
315  case OP_11:
316  case OP_12:
317  case OP_13:
318  case OP_14:
319  case OP_15:
320  case OP_16:
321  {
322  // ( -- value)
323  CScriptNum bn((int)opcode - (int)(OP_1 - 1));
324  stack.push_back(bn.getvch());
325  // The result of these opcodes should always be the minimal way to push the data
326  // they push, so no need for a CheckMinimalPush here.
327  }
328  break;
329 
330 
331  //
332  // Control
333  //
334  case OP_NOP:
335  break;
336 
338  {
340  // not enabled; treat as a NOP2
341  break;
342  }
343 
344  if (stack.size() < 1)
345  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
346 
347  // Note that elsewhere numeric opcodes are limited to
348  // operands in the range -2**31+1 to 2**31-1, however it is
349  // legal for opcodes to produce results exceeding that
350  // range. This limitation is implemented by CScriptNum's
351  // default 4-byte limit.
352  //
353  // If we kept to that limit we'd have a year 2038 problem,
354  // even though the nLockTime field in transactions
355  // themselves is uint32 which only becomes meaningless
356  // after the year 2106.
357  //
358  // Thus as a special case we tell CScriptNum to accept up
359  // to 5-byte bignums, which are good until 2**39-1, well
360  // beyond the 2**32-1 limit of the nLockTime field itself.
361  const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
362 
363  // In the rare event that the argument may be < 0 due to
364  // some arithmetic being done first, you can always use
365  // 0 MAX CHECKLOCKTIMEVERIFY.
366  if (nLockTime < 0)
367  return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
368 
369  // Actually compare the specified lock time with the transaction.
370  if (!checker.CheckLockTime(nLockTime))
371  return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
372 
373  break;
374  }
375 
377  {
379  // not enabled; treat as a NOP3
380  break;
381  }
382 
383  if (stack.size() < 1)
384  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
385 
386  // nSequence, like nLockTime, is a 32-bit unsigned integer
387  // field. See the comment in CHECKLOCKTIMEVERIFY regarding
388  // 5-byte numeric operands.
389  const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
390 
391  // In the rare event that the argument may be < 0 due to
392  // some arithmetic being done first, you can always use
393  // 0 MAX CHECKSEQUENCEVERIFY.
394  if (nSequence < 0)
395  return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
396 
397  // To provide for future soft-fork extensibility, if the
398  // operand has the disabled lock-time flag set,
399  // CHECKSEQUENCEVERIFY behaves as a NOP.
400  if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
401  break;
402 
403  // Compare the specified sequence number with the input.
404  if (!checker.CheckSequence(nSequence))
405  return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
406 
407  break;
408  }
409 
410  case OP_NOP1: case OP_NOP4: case OP_NOP5:
411  case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
412  {
414  return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
415  }
416  break;
417 
418  case OP_IF:
419  case OP_NOTIF:
420  {
421  // <expression> if [statements] [else [statements]] endif
422  bool fValue = false;
423  if (fExec)
424  {
425  if (stack.size() < 1)
426  return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
427  valtype& vch = stacktop(-1);
428  fValue = CastToBool(vch);
429  if (opcode == OP_NOTIF)
430  fValue = !fValue;
431  popstack(stack);
432  }
433  vfExec.push_back(fValue);
434  }
435  break;
436 
437  case OP_ELSE:
438  {
439  if (vfExec.empty())
440  return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
441  vfExec.back() = !vfExec.back();
442  }
443  break;
444 
445  case OP_ENDIF:
446  {
447  if (vfExec.empty())
448  return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
449  vfExec.pop_back();
450  }
451  break;
452 
453  case OP_VERIFY:
454  {
455  // (true -- ) or
456  // (false -- false) and return
457  if (stack.size() < 1)
458  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
459  bool fValue = CastToBool(stacktop(-1));
460  if (fValue)
461  popstack(stack);
462  else
463  return set_error(serror, SCRIPT_ERR_VERIFY);
464  }
465  break;
466 
467  case OP_RETURN:
468  {
469  return set_error(serror, SCRIPT_ERR_OP_RETURN);
470  }
471  break;
472 
473 
474  //
475  // Stack ops
476  //
477  case OP_TOALTSTACK:
478  {
479  if (stack.size() < 1)
480  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
481  altstack.push_back(stacktop(-1));
482  popstack(stack);
483  }
484  break;
485 
486  case OP_FROMALTSTACK:
487  {
488  if (altstack.size() < 1)
489  return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
490  stack.push_back(altstacktop(-1));
491  popstack(altstack);
492  }
493  break;
494 
495  case OP_2DROP:
496  {
497  // (x1 x2 -- )
498  if (stack.size() < 2)
499  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
500  popstack(stack);
501  popstack(stack);
502  }
503  break;
504 
505  case OP_2DUP:
506  {
507  // (x1 x2 -- x1 x2 x1 x2)
508  if (stack.size() < 2)
509  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
510  valtype vch1 = stacktop(-2);
511  valtype vch2 = stacktop(-1);
512  stack.push_back(vch1);
513  stack.push_back(vch2);
514  }
515  break;
516 
517  case OP_3DUP:
518  {
519  // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
520  if (stack.size() < 3)
521  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
522  valtype vch1 = stacktop(-3);
523  valtype vch2 = stacktop(-2);
524  valtype vch3 = stacktop(-1);
525  stack.push_back(vch1);
526  stack.push_back(vch2);
527  stack.push_back(vch3);
528  }
529  break;
530 
531  case OP_2OVER:
532  {
533  // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
534  if (stack.size() < 4)
535  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
536  valtype vch1 = stacktop(-4);
537  valtype vch2 = stacktop(-3);
538  stack.push_back(vch1);
539  stack.push_back(vch2);
540  }
541  break;
542 
543  case OP_2ROT:
544  {
545  // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
546  if (stack.size() < 6)
547  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
548  valtype vch1 = stacktop(-6);
549  valtype vch2 = stacktop(-5);
550  stack.erase(stack.end()-6, stack.end()-4);
551  stack.push_back(vch1);
552  stack.push_back(vch2);
553  }
554  break;
555 
556  case OP_2SWAP:
557  {
558  // (x1 x2 x3 x4 -- x3 x4 x1 x2)
559  if (stack.size() < 4)
560  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
561  swap(stacktop(-4), stacktop(-2));
562  swap(stacktop(-3), stacktop(-1));
563  }
564  break;
565 
566  case OP_IFDUP:
567  {
568  // (x - 0 | x x)
569  if (stack.size() < 1)
570  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
571  valtype vch = stacktop(-1);
572  if (CastToBool(vch))
573  stack.push_back(vch);
574  }
575  break;
576 
577  case OP_DEPTH:
578  {
579  // -- stacksize
580  CScriptNum bn(stack.size());
581  stack.push_back(bn.getvch());
582  }
583  break;
584 
585  case OP_DROP:
586  {
587  // (x -- )
588  if (stack.size() < 1)
589  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
590  popstack(stack);
591  }
592  break;
593 
594  case OP_DUP:
595  {
596  // (x -- x x)
597  if (stack.size() < 1)
598  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
599  valtype vch = stacktop(-1);
600  stack.push_back(vch);
601  }
602  break;
603 
604  case OP_NIP:
605  {
606  // (x1 x2 -- x2)
607  if (stack.size() < 2)
608  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
609  stack.erase(stack.end() - 2);
610  }
611  break;
612 
613  case OP_OVER:
614  {
615  // (x1 x2 -- x1 x2 x1)
616  if (stack.size() < 2)
617  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
618  valtype vch = stacktop(-2);
619  stack.push_back(vch);
620  }
621  break;
622 
623  case OP_PICK:
624  case OP_ROLL:
625  {
626  // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
627  // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
628  if (stack.size() < 2)
629  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
630  int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
631  popstack(stack);
632  if (n < 0 || n >= (int)stack.size())
633  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
634  valtype vch = stacktop(-n-1);
635  if (opcode == OP_ROLL)
636  stack.erase(stack.end()-n-1);
637  stack.push_back(vch);
638  }
639  break;
640 
641  case OP_ROT:
642  {
643  // (x1 x2 x3 -- x2 x3 x1)
644  // x2 x1 x3 after first swap
645  // x2 x3 x1 after second swap
646  if (stack.size() < 3)
647  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
648  swap(stacktop(-3), stacktop(-2));
649  swap(stacktop(-2), stacktop(-1));
650  }
651  break;
652 
653  case OP_SWAP:
654  {
655  // (x1 x2 -- x2 x1)
656  if (stack.size() < 2)
657  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
658  swap(stacktop(-2), stacktop(-1));
659  }
660  break;
661 
662  case OP_TUCK:
663  {
664  // (x1 x2 -- x2 x1 x2)
665  if (stack.size() < 2)
666  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
667  valtype vch = stacktop(-1);
668  stack.insert(stack.end()-2, vch);
669  }
670  break;
671 
672 
673  case OP_SIZE:
674  {
675  // (in -- in size)
676  if (stack.size() < 1)
677  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
678  CScriptNum bn(stacktop(-1).size());
679  stack.push_back(bn.getvch());
680  }
681  break;
682 
683 
684  //
685  // Bitwise logic
686  //
687  case OP_EQUAL:
688  case OP_EQUALVERIFY:
689  //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
690  {
691  // (x1 x2 - bool)
692  if (stack.size() < 2)
693  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
694  valtype& vch1 = stacktop(-2);
695  valtype& vch2 = stacktop(-1);
696  bool fEqual = (vch1 == vch2);
697  // OP_NOTEQUAL is disabled because it would be too easy to say
698  // something like n != 1 and have some wiseguy pass in 1 with extra
699  // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
700  //if (opcode == OP_NOTEQUAL)
701  // fEqual = !fEqual;
702  popstack(stack);
703  popstack(stack);
704  stack.push_back(fEqual ? vchTrue : vchFalse);
705  if (opcode == OP_EQUALVERIFY)
706  {
707  if (fEqual)
708  popstack(stack);
709  else
710  return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
711  }
712  }
713  break;
714 
715 
716  //
717  // Numeric
718  //
719  case OP_1ADD:
720  case OP_1SUB:
721  case OP_NEGATE:
722  case OP_ABS:
723  case OP_NOT:
724  case OP_0NOTEQUAL:
725  {
726  // (in -- out)
727  if (stack.size() < 1)
728  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
729  CScriptNum bn(stacktop(-1), fRequireMinimal);
730  switch (opcode)
731  {
732  case OP_1ADD: bn += bnOne; break;
733  case OP_1SUB: bn -= bnOne; break;
734  case OP_NEGATE: bn = -bn; break;
735  case OP_ABS: if (bn < bnZero) bn = -bn; break;
736  case OP_NOT: bn = (bn == bnZero); break;
737  case OP_0NOTEQUAL: bn = (bn != bnZero); break;
738  default: assert(!"invalid opcode"); break;
739  }
740  popstack(stack);
741  stack.push_back(bn.getvch());
742  }
743  break;
744 
745  case OP_ADD:
746  case OP_SUB:
747  case OP_BOOLAND:
748  case OP_BOOLOR:
749  case OP_NUMEQUAL:
750  case OP_NUMEQUALVERIFY:
751  case OP_NUMNOTEQUAL:
752  case OP_LESSTHAN:
753  case OP_GREATERTHAN:
754  case OP_LESSTHANOREQUAL:
756  case OP_MIN:
757  case OP_MAX:
758  {
759  // (x1 x2 -- out)
760  if (stack.size() < 2)
761  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
762  CScriptNum bn1(stacktop(-2), fRequireMinimal);
763  CScriptNum bn2(stacktop(-1), fRequireMinimal);
764  CScriptNum bn(0);
765  switch (opcode)
766  {
767  case OP_ADD:
768  bn = bn1 + bn2;
769  break;
770 
771  case OP_SUB:
772  bn = bn1 - bn2;
773  break;
774 
775  case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
776  case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
777  case OP_NUMEQUAL: bn = (bn1 == bn2); break;
778  case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
779  case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
780  case OP_LESSTHAN: bn = (bn1 < bn2); break;
781  case OP_GREATERTHAN: bn = (bn1 > bn2); break;
782  case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
783  case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
784  case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
785  case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
786  default: assert(!"invalid opcode"); break;
787  }
788  popstack(stack);
789  popstack(stack);
790  stack.push_back(bn.getvch());
791 
792  if (opcode == OP_NUMEQUALVERIFY)
793  {
794  if (CastToBool(stacktop(-1)))
795  popstack(stack);
796  else
797  return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
798  }
799  }
800  break;
801 
802  case OP_WITHIN:
803  {
804  // (x min max -- out)
805  if (stack.size() < 3)
806  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
807  CScriptNum bn1(stacktop(-3), fRequireMinimal);
808  CScriptNum bn2(stacktop(-2), fRequireMinimal);
809  CScriptNum bn3(stacktop(-1), fRequireMinimal);
810  bool fValue = (bn2 <= bn1 && bn1 < bn3);
811  popstack(stack);
812  popstack(stack);
813  popstack(stack);
814  stack.push_back(fValue ? vchTrue : vchFalse);
815  }
816  break;
817 
818 
819  //
820  // Crypto
821  //
822  case OP_RIPEMD160:
823  case OP_SHA1:
824  case OP_SHA256:
825  case OP_HASH160:
826  case OP_HASH256:
827  {
828  // (in -- hash)
829  if (stack.size() < 1)
830  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
831  valtype& vch = stacktop(-1);
832  valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
833  if (opcode == OP_RIPEMD160)
834  CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
835  else if (opcode == OP_SHA1)
836  CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
837  else if (opcode == OP_SHA256)
838  CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
839  else if (opcode == OP_HASH160)
840  CHash160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
841  else if (opcode == OP_HASH256)
842  CHash256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
843  popstack(stack);
844  stack.push_back(vchHash);
845  }
846  break;
847 
848  case OP_CODESEPARATOR:
849  {
850  // Hash starts after the code separator
851  pbegincodehash = pc;
852  }
853  break;
854 
855  case OP_CHECKSIG:
856  case OP_CHECKSIGVERIFY:
857  {
858  // (sig pubkey -- bool)
859  if (stack.size() < 2)
860  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
861 
862  valtype& vchSig = stacktop(-2);
863  valtype& vchPubKey = stacktop(-1);
864 
865  // Subset of script starting at the most recent codeseparator
866  CScript scriptCode(pbegincodehash, pend);
867 
868  // Drop the signature, since there's no way for a signature to sign itself
869  if (sigversion == SIGVERSION_BASE) {
870  scriptCode.FindAndDelete(CScript(vchSig));
871  }
872 
873  if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
874  //serror is set
875  return false;
876  }
877  bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
878 
879  if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
880  return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
881 
882  popstack(stack);
883  popstack(stack);
884  stack.push_back(fSuccess ? vchTrue : vchFalse);
885  if (opcode == OP_CHECKSIGVERIFY)
886  {
887  if (fSuccess)
888  popstack(stack);
889  else
890  return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
891  }
892  }
893  break;
894 
895  case OP_CHECKMULTISIG:
897  {
898  // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
899 
900  int i = 1;
901  if ((int)stack.size() < i)
902  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
903 
904  int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
905  if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
906  return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
907  nOpCount += nKeysCount;
908  if (nOpCount > MAX_OPS_PER_SCRIPT)
909  return set_error(serror, SCRIPT_ERR_OP_COUNT);
910  int ikey = ++i;
911  // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
912  // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
913  int ikey2 = nKeysCount + 2;
914  i += nKeysCount;
915  if ((int)stack.size() < i)
916  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
917 
918  int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
919  if (nSigsCount < 0 || nSigsCount > nKeysCount)
920  return set_error(serror, SCRIPT_ERR_SIG_COUNT);
921  int isig = ++i;
922  i += nSigsCount;
923  if ((int)stack.size() < i)
924  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
925 
926  // Subset of script starting at the most recent codeseparator
927  CScript scriptCode(pbegincodehash, pend);
928 
929  // Drop the signatures, since there's no way for a signature to sign itself
930  for (int k = 0; k < nSigsCount; k++)
931  {
932  valtype& vchSig = stacktop(-isig-k);
933  if (sigversion == SIGVERSION_BASE) {
934  scriptCode.FindAndDelete(CScript(vchSig));
935  }
936  }
937 
938  bool fSuccess = true;
939  while (fSuccess && nSigsCount > 0)
940  {
941  valtype& vchSig = stacktop(-isig);
942  valtype& vchPubKey = stacktop(-ikey);
943 
944  // Note how this makes the exact order of pubkey/signature evaluation
945  // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
946  // See the script_(in)valid tests for details.
947  if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
948  // serror is set
949  return false;
950  }
951 
952  // Check signature
953  bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
954 
955  if (fOk) {
956  isig++;
957  nSigsCount--;
958  }
959  ikey++;
960  nKeysCount--;
961 
962  // If there are more signatures left than keys left,
963  // then too many signatures have failed. Exit early,
964  // without checking any further signatures.
965  if (nSigsCount > nKeysCount)
966  fSuccess = false;
967  }
968 
969  // Clean up stack of actual arguments
970  while (i-- > 1) {
971  // If the operation failed, we require that all signatures must be empty vector
972  if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
973  return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
974  if (ikey2 > 0)
975  ikey2--;
976  popstack(stack);
977  }
978 
979  // A bug causes CHECKMULTISIG to consume one extra argument
980  // whose contents were not checked in any way.
981  //
982  // Unfortunately this is a potential source of mutability,
983  // so optionally verify it is exactly equal to zero prior
984  // to removing it from the stack.
985  if (stack.size() < 1)
986  return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
987  if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
988  return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
989  popstack(stack);
990 
991  stack.push_back(fSuccess ? vchTrue : vchFalse);
992 
993  if (opcode == OP_CHECKMULTISIGVERIFY)
994  {
995  if (fSuccess)
996  popstack(stack);
997  else
998  return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
999  }
1000  }
1001  break;
1002 
1003  default:
1004  return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1005  }
1006 
1007  // Size limits
1008  if (stack.size() + altstack.size() > MAX_STACK_SIZE)
1009  return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1010  }
1011  }
1012  catch (...)
1013  {
1014  return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1015  }
1016 
1017  if (!vfExec.empty())
1018  return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1019 
1020  return set_success(serror);
1021 }
1022 
1023 namespace {
1024 
1029 class CTransactionSignatureSerializer {
1030 private:
1031  const CTransaction& txTo;
1032  const CScript& scriptCode;
1033  const unsigned int nIn;
1034  const bool fAnyoneCanPay;
1035  const bool fHashSingle;
1036  const bool fHashNone;
1037 
1038 public:
1039  CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1040  txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1041  fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1042  fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1043  fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1044 
1046  template<typename S>
1047  void SerializeScriptCode(S &s) const {
1048  CScript::const_iterator it = scriptCode.begin();
1049  CScript::const_iterator itBegin = it;
1050  opcodetype opcode;
1051  unsigned int nCodeSeparators = 0;
1052  while (scriptCode.GetOp(it, opcode)) {
1053  if (opcode == OP_CODESEPARATOR)
1054  nCodeSeparators++;
1055  }
1056  ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1057  it = itBegin;
1058  while (scriptCode.GetOp(it, opcode)) {
1059  if (opcode == OP_CODESEPARATOR) {
1060  s.write((char*)&itBegin[0], it-itBegin-1);
1061  itBegin = it;
1062  }
1063  }
1064  if (itBegin != scriptCode.end())
1065  s.write((char*)&itBegin[0], it-itBegin);
1066  }
1067 
1069  template<typename S>
1070  void SerializeInput(S &s, unsigned int nInput) const {
1071  // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1072  if (fAnyoneCanPay)
1073  nInput = nIn;
1074  // Serialize the prevout
1075  ::Serialize(s, txTo.vin[nInput].prevout);
1076  // Serialize the script
1077  if (nInput != nIn)
1078  // Blank out other inputs' signatures
1079  ::Serialize(s, CScript());
1080  else
1081  SerializeScriptCode(s);
1082  // Serialize the nSequence
1083  if (nInput != nIn && (fHashSingle || fHashNone))
1084  // let the others update at will
1085  ::Serialize(s, (int)0);
1086  else
1087  ::Serialize(s, txTo.vin[nInput].nSequence);
1088  }
1089 
1091  template<typename S>
1092  void SerializeOutput(S &s, unsigned int nOutput) const {
1093  if (fHashSingle && nOutput != nIn)
1094  // Do not lock-in the txout payee at other indices as txin
1095  ::Serialize(s, CTxOut());
1096  else
1097  ::Serialize(s, txTo.vout[nOutput]);
1098  }
1099 
1101  template<typename S>
1102  void Serialize(S &s) const {
1103  // Serialize nVersion
1104  int32_t n32bitVersion = txTo.nVersion | (txTo.nType << 16);
1105  ::Serialize(s, n32bitVersion);
1106  // Serialize vin
1107  unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1108  ::WriteCompactSize(s, nInputs);
1109  for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1110  SerializeInput(s, nInput);
1111  // Serialize vout
1112  unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1113  ::WriteCompactSize(s, nOutputs);
1114  for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1115  SerializeOutput(s, nOutput);
1116  // Serialize nLockTime
1117  ::Serialize(s, txTo.nLockTime);
1118  if (txTo.nVersion == 3 && txTo.nType != TRANSACTION_NORMAL)
1119  ::Serialize(s, txTo.vExtraPayload);
1120  }
1121 };
1122 
1123 uint256 GetPrevoutHash(const CTransaction& txTo) {
1124  CHashWriter ss(SER_GETHASH, 0);
1125  for (const auto& txin : txTo.vin) {
1126  ss << txin.prevout;
1127  }
1128  return ss.GetHash();
1129 }
1130 
1131 uint256 GetSequenceHash(const CTransaction& txTo) {
1132  CHashWriter ss(SER_GETHASH, 0);
1133  for (const auto& txin : txTo.vin) {
1134  ss << txin.nSequence;
1135  }
1136  return ss.GetHash();
1137 }
1138 
1139 uint256 GetOutputsHash(const CTransaction& txTo) {
1140  CHashWriter ss(SER_GETHASH, 0);
1141  for (const auto& txout : txTo.vout) {
1142  ss << txout;
1143  }
1144  return ss.GetHash();
1145 }
1146 
1147 } // namespace
1148 
1150 {
1151  hashPrevouts = GetPrevoutHash(txTo);
1152  hashSequence = GetSequenceHash(txTo);
1153  hashOutputs = GetOutputsHash(txTo);
1154 }
1155 
1156 uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1157 {
1158  assert(nIn < txTo.vin.size());
1159 
1160  static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
1161 
1162  // Check for invalid use of SIGHASH_SINGLE
1163  if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1164  if (nIn >= txTo.vout.size()) {
1165  // nOut out of range
1166  return one;
1167  }
1168  }
1169 
1170  // Wrapper to serialize only the necessary parts of the transaction being signed
1171  CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
1172 
1173  // Serialize and hash
1174  CHashWriter ss(SER_GETHASH, 0);
1175  ss << txTmp << nHashType;
1176  return ss.GetHash();
1177 }
1178 
1179 bool TransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1180 {
1181  return pubkey.Verify(sighash, vchSig);
1182 }
1183 
1184 bool TransactionSignatureChecker::CheckSig(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1185 {
1186  CPubKey pubkey(vchPubKey);
1187  if (!pubkey.IsValid())
1188  return false;
1189 
1190  // Hash type is one byte tacked on to the end of the signature
1191  std::vector<unsigned char> vchSig(vchSigIn);
1192  if (vchSig.empty())
1193  return false;
1194  int nHashType = vchSig.back();
1195  vchSig.pop_back();
1196 
1197  uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
1198 
1199  if (!VerifySignature(vchSig, pubkey, sighash))
1200  return false;
1201 
1202  return true;
1203 }
1204 
1206 {
1207  // There are two kinds of nLockTime: lock-by-blockheight
1208  // and lock-by-blocktime, distinguished by whether
1209  // nLockTime < LOCKTIME_THRESHOLD.
1210  //
1211  // We want to compare apples to apples, so fail the script
1212  // unless the type of nLockTime being tested is the same as
1213  // the nLockTime in the transaction.
1214  if (!(
1215  (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
1216  (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1217  ))
1218  return false;
1219 
1220  // Now that we know we're comparing apples-to-apples, the
1221  // comparison is a simple numeric one.
1222  if (nLockTime > (int64_t)txTo->nLockTime)
1223  return false;
1224 
1225  // Finally the nLockTime feature can be disabled and thus
1226  // CHECKLOCKTIMEVERIFY bypassed if every txin has been
1227  // finalized by setting nSequence to maxint. The
1228  // transaction would be allowed into the blockchain, making
1229  // the opcode ineffective.
1230  //
1231  // Testing if this vin is not final is sufficient to
1232  // prevent this condition. Alternatively we could test all
1233  // inputs, but testing just this input minimizes the data
1234  // required to prove correct CHECKLOCKTIMEVERIFY execution.
1235  if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1236  return false;
1237 
1238  return true;
1239 }
1240 
1242 {
1243  // Relative lock times are supported by comparing the passed
1244  // in operand to the sequence number of the input.
1245  const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1246 
1247  // Fail if the transaction's version number is not set high
1248  // enough to trigger BIP 68 rules.
1249  if (static_cast<uint32_t>(txTo->nVersion) < 2)
1250  return false;
1251 
1252  // Sequence numbers with their most significant bit set are not
1253  // consensus constrained. Testing that the transaction's sequence
1254  // number do not have this bit set prevents using this property
1255  // to get around a CHECKSEQUENCEVERIFY check.
1256  if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1257  return false;
1258 
1259  // Mask off any bits that do not have consensus-enforced meaning
1260  // before doing the integer comparisons
1261  const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1262  const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1263  const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1264 
1265  // There are two kinds of nSequence: lock-by-blockheight
1266  // and lock-by-blocktime, distinguished by whether
1267  // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1268  //
1269  // We want to compare apples to apples, so fail the script
1270  // unless the type of nSequenceMasked being tested is the same as
1271  // the nSequenceMasked in the transaction.
1272  if (!(
1273  (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1274  (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1275  )) {
1276  return false;
1277  }
1278 
1279  // Now that we know we're comparing apples-to-apples, the
1280  // comparison is a simple numeric one.
1281  if (nSequenceMasked > txToSequenceMasked)
1282  return false;
1283 
1284  return true;
1285 }
1286 
1287 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1288 {
1289  set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1290 
1291  if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1292  return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1293  }
1294 
1295  std::vector<std::vector<unsigned char> > stack, stackCopy;
1296  if (!EvalScript(stack, scriptSig, flags, checker, SIGVERSION_BASE, serror))
1297  // serror is set
1298  return false;
1299  if (flags & SCRIPT_VERIFY_P2SH)
1300  stackCopy = stack;
1301  if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_BASE, serror))
1302  // serror is set
1303  return false;
1304  if (stack.empty())
1305  return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1306  if (CastToBool(stack.back()) == false)
1307  return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1308 
1309  // Additional validation for spend-to-script-hash transactions:
1310  if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1311  {
1312  // scriptSig must be literals-only or validation fails
1313  if (!scriptSig.IsPushOnly())
1314  return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1315 
1316  // Restore stack.
1317  swap(stack, stackCopy);
1318 
1319  // stack cannot be empty here, because if it was the
1320  // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1321  // an empty stack and the EvalScript above would return false.
1322  assert(!stack.empty());
1323 
1324  const valtype& pubKeySerialized = stack.back();
1325  CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1326  popstack(stack);
1327 
1328  if (!EvalScript(stack, pubKey2, flags, checker, SIGVERSION_BASE, serror))
1329  // serror is set
1330  return false;
1331  if (stack.empty())
1332  return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1333  if (!CastToBool(stack.back()))
1334  return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1335  }
1336 
1337  // The CLEANSTACK check is only performed after potential P2SH evaluation,
1338  // as the non-P2SH evaluation of a P2SH script will obviously not result in
1339  // a clean stack (the P2SH inputs remain).
1340  if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
1341  // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
1342  // would be possible, which is not a softfork (and P2SH should be one).
1343  assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1344  if (stack.size() != 1) {
1345  return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1346  }
1347  }
1348 
1349  return set_success(serror);
1350 }
Definition: script.h:133
Definition: script.h:62
Definition: script.h:118
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:648
virtual bool CheckLockTime(const CScriptNum &nLockTime) const
Definition: interpreter.h:124
static const int MAX_PUBKEYS_PER_MULTISIG
Definition: script.h:29
const PrecomputedTransactionData * txdata
Definition: interpreter.h:143
Definition: script.h:101
CSHA1 & Write(const unsigned char *data, size_t len)
Definition: sha1.cpp:154
int getint() const
Definition: script.h:312
Definition: script.h:154
enum ScriptError_t ScriptError
Definition: script.h:93
virtual bool VerifySignature(const std::vector< unsigned char > &vchSig, const CPubKey &vchPubKey, const uint256 &sighash) const
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:1289
bool IsPayToScriptHash() const
Definition: script.cpp:212
Definition: script.h:79
Definition: script.h:72
Definition: script.h:68
Definition: script.h:95
CHash256 & Write(const unsigned char *data, size_t len)
Definition: hash.h:47
static const uint32_t SEQUENCE_FINAL
Definition: transaction.h:79
Definition: script.h:132
static void popstack(std::vector< valtype > &stack)
Definition: interpreter.cpp:56
Definition: script.h:60
Definition: script.h:139
Definition: script.h:66
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
Definition: transaction.h:84
Definition: script.h:61
bool CheckSequence(const CScriptNum &nSequence) const override
int flags
Definition: dash-tx.cpp:462
static bool CheckLowS(const std::vector< unsigned char > &vchSig)
Check whether a signature is normalized (lower-S).
Definition: pubkey.cpp:274
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:35
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:23
Definition: script.h:153
bool CheckSig(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const override
static bool CheckMinimalPush(const valtype &data, opcodetype opcode)
Definition: script.h:74
const std::vector< CTxIn > vin
Definition: transaction.h:215
Definition: script.h:70
static const int MAX_OPS_PER_SCRIPT
Definition: script.h:26
void Serialize(Stream &s, char a)
Definition: serialize.h:184
Definition: script.h:119
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
Definition: script.h:63
iterator end()
Definition: prevector.h:320
uint256 SignatureHash(const CScript &scriptCode, const CTransaction &txTo, unsigned int nIn, int nHashType, const CAmount &amount, SigVersion sigversion, const PrecomputedTransactionData *cache)
Definition: script.h:140
opcodetype
Script opcodes.
Definition: script.h:48
Definition: script.h:110
bool CheckSignatureEncoding(const std::vector< unsigned char > &vchSig, unsigned int flags, ScriptError *serror)
bool IsPushOnly(const_iterator pc) const
Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical).
Definition: script.cpp:236
PrecomputedTransactionData(const CTransaction &tx)
bool IsValid() const
Definition: pubkey.h:165
uint256 uint256S(const char *str)
Definition: uint256.h:143
An encapsulated public key.
Definition: pubkey.h:30
Definition: script.h:65
Definition: script.h:58
Definition: script.h:77
const std::vector< CTxOut > vout
Definition: transaction.h:216
#define S(x0, x1, x2, x3, cb, r)
Definition: jh.c:494
std::vector< unsigned char > getvch() const
Definition: script.h:321
#define stacktop(i)
Script is a stack machine (like Forth) that evaluates a predicate returning a bool indicating valid o...
Definition: interpreter.cpp:54
CHash160 & Write(const unsigned char *data, size_t len)
Definition: hash.h:71
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: interpreter.cpp:95
Definition: script.h:137
An output of a transaction.
Definition: transaction.h:144
static const int MAX_SCRIPT_SIZE
Definition: script.h:32
Definition: script.h:105
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG
Definition: transaction.h:89
static const int MAX_STACK_SIZE
Definition: script.h:35
Definition: script.h:138
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptError *serror)
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
#define altstacktop(i)
Definition: interpreter.cpp:55
Definition: script.h:83
const int16_t nVersion
Definition: transaction.h:217
CRIPEMD160 & Write(const unsigned char *data, size_t len)
Definition: ripemd160.cpp:247
uint256 GetHash()
Definition: hash.h:203
Definition: script.h:67
256-bit opaque blob.
Definition: uint256.h:123
Definition: script.h:99
Definition: script.h:92
static const uint32_t SEQUENCE_LOCKTIME_MASK
Definition: transaction.h:93
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:389
static bool IsCompressedOrUncompressedPubKey(const valtype &vchPubKey)
Definition: interpreter.cpp:63
const std::vector< uint8_t > vExtraPayload
Definition: transaction.h:220
int FindAndDelete(const CScript &b)
Definition: script.h:591
Definition: script.h:64
virtual bool CheckSig(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const
Definition: interpreter.h:119
std::vector< unsigned char > valtype
Definition: interpreter.cpp:15
A hasher class for SHA1.
Definition: sha1.h:12
static int count
Definition: tests.c:45
virtual bool CheckSequence(const CScriptNum &nSequence) const
Definition: interpreter.h:129
iterator begin()
Definition: prevector.h:318
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:184
size_type size() const
Definition: prevector.h:310
static bool CheckPubKeyEncoding(const valtype &vchSig, unsigned int flags, ScriptError *serror)
bool GetOp(iterator &pc, opcodetype &opcodeRet, std::vector< unsigned char > &vchRet)
Definition: script.h:496
static bool IsLowDERSignature(const valtype &vchSig, ScriptError *serror)
Definition: script.h:71
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:198
A hasher class for Bitcoin&#39;s 160-bit hash (SHA-256 + RIPEMD-160).
Definition: hash.h:59
Definition: script.h:120
Definition: script.h:69
A hasher class for SHA-256.
Definition: sha256.h:13
const CTransaction * txTo
Definition: interpreter.h:140
Definition: script.h:51
bool CastToBool(const valtype &vch)
Definition: interpreter.cpp:35
const int16_t nType
Definition: transaction.h:218
static bool IsDefinedHashtypeSignature(const valtype &vchSig)
Definition: script.h:136
Definition: script.h:73
const uint32_t nLockTime
Definition: transaction.h:219
A hasher class for RIPEMD-160.
Definition: ripemd160.h:12
Definition: script.h:100
SigVersion
Definition: interpreter.h:109
Released under the MIT license