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