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