Merge #11221: Refactor: simpler read
[bitcoinplatinum.git] / src / script / interpreter.cpp
blob2f7b8e3a035ba881d45964fbcf383995995138ac
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
6 #include "interpreter.h"
8 #include "primitives/transaction.h"
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"
16 typedef std::vector<unsigned char> valtype;
18 namespace {
20 inline bool set_success(ScriptError* ret)
22 if (ret)
23 *ret = SCRIPT_ERR_OK;
24 return true;
27 inline bool set_error(ScriptError* ret, const ScriptError serror)
29 if (ret)
30 *ret = serror;
31 return false;
34 } // namespace
36 bool CastToBool(const valtype& vch)
38 for (unsigned int i = 0; i < vch.size(); i++)
40 if (vch[i] != 0)
42 // Can be negative zero
43 if (i == vch.size()-1 && vch[i] == 0x80)
44 return false;
45 return true;
48 return false;
51 /**
52 * Script is a stack machine (like Forth) that evaluates a predicate
53 * returning a bool indicating valid or not. There are no loops.
55 #define stacktop(i) (stack.at(stack.size()+(i)))
56 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
57 static inline void popstack(std::vector<valtype>& stack)
59 if (stack.empty())
60 throw std::runtime_error("popstack(): stack empty");
61 stack.pop_back();
64 bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
65 if (vchPubKey.size() < 33) {
66 // Non-canonical public key: too short
67 return false;
69 if (vchPubKey[0] == 0x04) {
70 if (vchPubKey.size() != 65) {
71 // Non-canonical public key: invalid length for uncompressed key
72 return false;
74 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
75 if (vchPubKey.size() != 33) {
76 // Non-canonical public key: invalid length for compressed key
77 return false;
79 } else {
80 // Non-canonical public key: neither compressed nor uncompressed
81 return false;
83 return true;
86 bool static IsCompressedPubKey(const valtype &vchPubKey) {
87 if (vchPubKey.size() != 33) {
88 // Non-canonical public key: invalid length for compressed key
89 return false;
91 if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
92 // Non-canonical public key: invalid prefix for compressed key
93 return false;
95 return true;
98 /**
99 * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
100 * Where R and S are not negative (their first byte has its highest bit not set), and not
101 * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
102 * in which case a single 0 byte is necessary and even required).
104 * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
106 * This function is consensus-critical since BIP66.
108 bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
109 // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
110 // * total-length: 1-byte length descriptor of everything that follows,
111 // excluding the sighash byte.
112 // * R-length: 1-byte length descriptor of the R value that follows.
113 // * R: arbitrary-length big-endian encoded R value. It must use the shortest
114 // possible encoding for a positive integers (which means no null bytes at
115 // the start, except a single one when the next byte has its highest bit set).
116 // * S-length: 1-byte length descriptor of the S value that follows.
117 // * S: arbitrary-length big-endian encoded S value. The same rules apply.
118 // * sighash: 1-byte value indicating what data is hashed (not part of the DER
119 // signature)
121 // Minimum and maximum size constraints.
122 if (sig.size() < 9) return false;
123 if (sig.size() > 73) return false;
125 // A signature is of type 0x30 (compound).
126 if (sig[0] != 0x30) return false;
128 // Make sure the length covers the entire signature.
129 if (sig[1] != sig.size() - 3) return false;
131 // Extract the length of the R element.
132 unsigned int lenR = sig[3];
134 // Make sure the length of the S element is still inside the signature.
135 if (5 + lenR >= sig.size()) return false;
137 // Extract the length of the S element.
138 unsigned int lenS = sig[5 + lenR];
140 // Verify that the length of the signature matches the sum of the length
141 // of the elements.
142 if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
144 // Check whether the R element is an integer.
145 if (sig[2] != 0x02) return false;
147 // Zero-length integers are not allowed for R.
148 if (lenR == 0) return false;
150 // Negative numbers are not allowed for R.
151 if (sig[4] & 0x80) return false;
153 // Null bytes at the start of R are not allowed, unless R would
154 // otherwise be interpreted as a negative number.
155 if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
157 // Check whether the S element is an integer.
158 if (sig[lenR + 4] != 0x02) return false;
160 // Zero-length integers are not allowed for S.
161 if (lenS == 0) return false;
163 // Negative numbers are not allowed for S.
164 if (sig[lenR + 6] & 0x80) return false;
166 // Null bytes at the start of S are not allowed, unless S would otherwise be
167 // interpreted as a negative number.
168 if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
170 return true;
173 bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
174 if (!IsValidSignatureEncoding(vchSig)) {
175 return set_error(serror, SCRIPT_ERR_SIG_DER);
177 std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
178 if (!CPubKey::CheckLowS(vchSigCopy)) {
179 return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
181 return true;
184 bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
185 if (vchSig.size() == 0) {
186 return false;
188 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
189 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
190 return false;
192 return true;
195 bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
196 // Empty signature. Not strictly DER encoded, but allowed to provide a
197 // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
198 if (vchSig.size() == 0) {
199 return true;
201 if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
202 return set_error(serror, SCRIPT_ERR_SIG_DER);
203 } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
204 // serror is set
205 return false;
206 } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
207 return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
209 return true;
212 bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
213 if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
214 return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
216 // Only compressed keys are accepted in segwit
217 if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SIGVERSION_WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
218 return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
220 return true;
223 bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
224 if (data.size() == 0) {
225 // Could have used OP_0.
226 return opcode == OP_0;
227 } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
228 // Could have used OP_1 .. OP_16.
229 return opcode == OP_1 + (data[0] - 1);
230 } else if (data.size() == 1 && data[0] == 0x81) {
231 // Could have used OP_1NEGATE.
232 return opcode == OP_1NEGATE;
233 } else if (data.size() <= 75) {
234 // Could have used a direct push (opcode indicating number of bytes pushed + those bytes).
235 return opcode == data.size();
236 } else if (data.size() <= 255) {
237 // Could have used OP_PUSHDATA.
238 return opcode == OP_PUSHDATA1;
239 } else if (data.size() <= 65535) {
240 // Could have used OP_PUSHDATA2.
241 return opcode == OP_PUSHDATA2;
243 return true;
246 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
248 static const CScriptNum bnZero(0);
249 static const CScriptNum bnOne(1);
250 // static const CScriptNum bnFalse(0);
251 // static const CScriptNum bnTrue(1);
252 static const valtype vchFalse(0);
253 // static const valtype vchZero(0);
254 static const valtype vchTrue(1, 1);
256 CScript::const_iterator pc = script.begin();
257 CScript::const_iterator pend = script.end();
258 CScript::const_iterator pbegincodehash = script.begin();
259 opcodetype opcode;
260 valtype vchPushValue;
261 std::vector<bool> vfExec;
262 std::vector<valtype> altstack;
263 set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
264 if (script.size() > MAX_SCRIPT_SIZE)
265 return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
266 int nOpCount = 0;
267 bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
271 while (pc < pend)
273 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
276 // Read instruction
278 if (!script.GetOp(pc, opcode, vchPushValue))
279 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
280 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
281 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
283 // Note how OP_RESERVED does not count towards the opcode limit.
284 if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
285 return set_error(serror, SCRIPT_ERR_OP_COUNT);
287 if (opcode == OP_CAT ||
288 opcode == OP_SUBSTR ||
289 opcode == OP_LEFT ||
290 opcode == OP_RIGHT ||
291 opcode == OP_INVERT ||
292 opcode == OP_AND ||
293 opcode == OP_OR ||
294 opcode == OP_XOR ||
295 opcode == OP_2MUL ||
296 opcode == OP_2DIV ||
297 opcode == OP_MUL ||
298 opcode == OP_DIV ||
299 opcode == OP_MOD ||
300 opcode == OP_LSHIFT ||
301 opcode == OP_RSHIFT)
302 return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes.
304 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
305 if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
306 return set_error(serror, SCRIPT_ERR_MINIMALDATA);
308 stack.push_back(vchPushValue);
309 } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
310 switch (opcode)
313 // Push value
315 case OP_1NEGATE:
316 case OP_1:
317 case OP_2:
318 case OP_3:
319 case OP_4:
320 case OP_5:
321 case OP_6:
322 case OP_7:
323 case OP_8:
324 case OP_9:
325 case OP_10:
326 case OP_11:
327 case OP_12:
328 case OP_13:
329 case OP_14:
330 case OP_15:
331 case OP_16:
333 // ( -- value)
334 CScriptNum bn((int)opcode - (int)(OP_1 - 1));
335 stack.push_back(bn.getvch());
336 // The result of these opcodes should always be the minimal way to push the data
337 // they push, so no need for a CheckMinimalPush here.
339 break;
343 // Control
345 case OP_NOP:
346 break;
348 case OP_CHECKLOCKTIMEVERIFY:
350 if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
351 // not enabled; treat as a NOP2
352 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
353 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
355 break;
358 if (stack.size() < 1)
359 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
361 // Note that elsewhere numeric opcodes are limited to
362 // operands in the range -2**31+1 to 2**31-1, however it is
363 // legal for opcodes to produce results exceeding that
364 // range. This limitation is implemented by CScriptNum's
365 // default 4-byte limit.
367 // If we kept to that limit we'd have a year 2038 problem,
368 // even though the nLockTime field in transactions
369 // themselves is uint32 which only becomes meaningless
370 // after the year 2106.
372 // Thus as a special case we tell CScriptNum to accept up
373 // to 5-byte bignums, which are good until 2**39-1, well
374 // beyond the 2**32-1 limit of the nLockTime field itself.
375 const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
377 // In the rare event that the argument may be < 0 due to
378 // some arithmetic being done first, you can always use
379 // 0 MAX CHECKLOCKTIMEVERIFY.
380 if (nLockTime < 0)
381 return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
383 // Actually compare the specified lock time with the transaction.
384 if (!checker.CheckLockTime(nLockTime))
385 return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
387 break;
390 case OP_CHECKSEQUENCEVERIFY:
392 if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
393 // not enabled; treat as a NOP3
394 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
395 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
397 break;
400 if (stack.size() < 1)
401 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
403 // nSequence, like nLockTime, is a 32-bit unsigned integer
404 // field. See the comment in CHECKLOCKTIMEVERIFY regarding
405 // 5-byte numeric operands.
406 const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
408 // In the rare event that the argument may be < 0 due to
409 // some arithmetic being done first, you can always use
410 // 0 MAX CHECKSEQUENCEVERIFY.
411 if (nSequence < 0)
412 return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
414 // To provide for future soft-fork extensibility, if the
415 // operand has the disabled lock-time flag set,
416 // CHECKSEQUENCEVERIFY behaves as a NOP.
417 if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
418 break;
420 // Compare the specified sequence number with the input.
421 if (!checker.CheckSequence(nSequence))
422 return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
424 break;
427 case OP_NOP1: case OP_NOP4: case OP_NOP5:
428 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
430 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
431 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
433 break;
435 case OP_IF:
436 case OP_NOTIF:
438 // <expression> if [statements] [else [statements]] endif
439 bool fValue = false;
440 if (fExec)
442 if (stack.size() < 1)
443 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
444 valtype& vch = stacktop(-1);
445 if (sigversion == SIGVERSION_WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
446 if (vch.size() > 1)
447 return set_error(serror, SCRIPT_ERR_MINIMALIF);
448 if (vch.size() == 1 && vch[0] != 1)
449 return set_error(serror, SCRIPT_ERR_MINIMALIF);
451 fValue = CastToBool(vch);
452 if (opcode == OP_NOTIF)
453 fValue = !fValue;
454 popstack(stack);
456 vfExec.push_back(fValue);
458 break;
460 case OP_ELSE:
462 if (vfExec.empty())
463 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
464 vfExec.back() = !vfExec.back();
466 break;
468 case OP_ENDIF:
470 if (vfExec.empty())
471 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
472 vfExec.pop_back();
474 break;
476 case OP_VERIFY:
478 // (true -- ) or
479 // (false -- false) and return
480 if (stack.size() < 1)
481 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
482 bool fValue = CastToBool(stacktop(-1));
483 if (fValue)
484 popstack(stack);
485 else
486 return set_error(serror, SCRIPT_ERR_VERIFY);
488 break;
490 case OP_RETURN:
492 return set_error(serror, SCRIPT_ERR_OP_RETURN);
494 break;
498 // Stack ops
500 case OP_TOALTSTACK:
502 if (stack.size() < 1)
503 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
504 altstack.push_back(stacktop(-1));
505 popstack(stack);
507 break;
509 case OP_FROMALTSTACK:
511 if (altstack.size() < 1)
512 return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
513 stack.push_back(altstacktop(-1));
514 popstack(altstack);
516 break;
518 case OP_2DROP:
520 // (x1 x2 -- )
521 if (stack.size() < 2)
522 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
523 popstack(stack);
524 popstack(stack);
526 break;
528 case OP_2DUP:
530 // (x1 x2 -- x1 x2 x1 x2)
531 if (stack.size() < 2)
532 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
533 valtype vch1 = stacktop(-2);
534 valtype vch2 = stacktop(-1);
535 stack.push_back(vch1);
536 stack.push_back(vch2);
538 break;
540 case OP_3DUP:
542 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
543 if (stack.size() < 3)
544 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
545 valtype vch1 = stacktop(-3);
546 valtype vch2 = stacktop(-2);
547 valtype vch3 = stacktop(-1);
548 stack.push_back(vch1);
549 stack.push_back(vch2);
550 stack.push_back(vch3);
552 break;
554 case OP_2OVER:
556 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
557 if (stack.size() < 4)
558 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
559 valtype vch1 = stacktop(-4);
560 valtype vch2 = stacktop(-3);
561 stack.push_back(vch1);
562 stack.push_back(vch2);
564 break;
566 case OP_2ROT:
568 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
569 if (stack.size() < 6)
570 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
571 valtype vch1 = stacktop(-6);
572 valtype vch2 = stacktop(-5);
573 stack.erase(stack.end()-6, stack.end()-4);
574 stack.push_back(vch1);
575 stack.push_back(vch2);
577 break;
579 case OP_2SWAP:
581 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
582 if (stack.size() < 4)
583 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
584 swap(stacktop(-4), stacktop(-2));
585 swap(stacktop(-3), stacktop(-1));
587 break;
589 case OP_IFDUP:
591 // (x - 0 | x x)
592 if (stack.size() < 1)
593 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
594 valtype vch = stacktop(-1);
595 if (CastToBool(vch))
596 stack.push_back(vch);
598 break;
600 case OP_DEPTH:
602 // -- stacksize
603 CScriptNum bn(stack.size());
604 stack.push_back(bn.getvch());
606 break;
608 case OP_DROP:
610 // (x -- )
611 if (stack.size() < 1)
612 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
613 popstack(stack);
615 break;
617 case OP_DUP:
619 // (x -- x x)
620 if (stack.size() < 1)
621 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
622 valtype vch = stacktop(-1);
623 stack.push_back(vch);
625 break;
627 case OP_NIP:
629 // (x1 x2 -- x2)
630 if (stack.size() < 2)
631 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
632 stack.erase(stack.end() - 2);
634 break;
636 case OP_OVER:
638 // (x1 x2 -- x1 x2 x1)
639 if (stack.size() < 2)
640 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
641 valtype vch = stacktop(-2);
642 stack.push_back(vch);
644 break;
646 case OP_PICK:
647 case OP_ROLL:
649 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
650 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
651 if (stack.size() < 2)
652 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
653 int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
654 popstack(stack);
655 if (n < 0 || n >= (int)stack.size())
656 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
657 valtype vch = stacktop(-n-1);
658 if (opcode == OP_ROLL)
659 stack.erase(stack.end()-n-1);
660 stack.push_back(vch);
662 break;
664 case OP_ROT:
666 // (x1 x2 x3 -- x2 x3 x1)
667 // x2 x1 x3 after first swap
668 // x2 x3 x1 after second swap
669 if (stack.size() < 3)
670 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
671 swap(stacktop(-3), stacktop(-2));
672 swap(stacktop(-2), stacktop(-1));
674 break;
676 case OP_SWAP:
678 // (x1 x2 -- x2 x1)
679 if (stack.size() < 2)
680 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
681 swap(stacktop(-2), stacktop(-1));
683 break;
685 case OP_TUCK:
687 // (x1 x2 -- x2 x1 x2)
688 if (stack.size() < 2)
689 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
690 valtype vch = stacktop(-1);
691 stack.insert(stack.end()-2, vch);
693 break;
696 case OP_SIZE:
698 // (in -- in size)
699 if (stack.size() < 1)
700 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
701 CScriptNum bn(stacktop(-1).size());
702 stack.push_back(bn.getvch());
704 break;
708 // Bitwise logic
710 case OP_EQUAL:
711 case OP_EQUALVERIFY:
712 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
714 // (x1 x2 - bool)
715 if (stack.size() < 2)
716 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
717 valtype& vch1 = stacktop(-2);
718 valtype& vch2 = stacktop(-1);
719 bool fEqual = (vch1 == vch2);
720 // OP_NOTEQUAL is disabled because it would be too easy to say
721 // something like n != 1 and have some wiseguy pass in 1 with extra
722 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
723 //if (opcode == OP_NOTEQUAL)
724 // fEqual = !fEqual;
725 popstack(stack);
726 popstack(stack);
727 stack.push_back(fEqual ? vchTrue : vchFalse);
728 if (opcode == OP_EQUALVERIFY)
730 if (fEqual)
731 popstack(stack);
732 else
733 return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
736 break;
740 // Numeric
742 case OP_1ADD:
743 case OP_1SUB:
744 case OP_NEGATE:
745 case OP_ABS:
746 case OP_NOT:
747 case OP_0NOTEQUAL:
749 // (in -- out)
750 if (stack.size() < 1)
751 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
752 CScriptNum bn(stacktop(-1), fRequireMinimal);
753 switch (opcode)
755 case OP_1ADD: bn += bnOne; break;
756 case OP_1SUB: bn -= bnOne; break;
757 case OP_NEGATE: bn = -bn; break;
758 case OP_ABS: if (bn < bnZero) bn = -bn; break;
759 case OP_NOT: bn = (bn == bnZero); break;
760 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
761 default: assert(!"invalid opcode"); break;
763 popstack(stack);
764 stack.push_back(bn.getvch());
766 break;
768 case OP_ADD:
769 case OP_SUB:
770 case OP_BOOLAND:
771 case OP_BOOLOR:
772 case OP_NUMEQUAL:
773 case OP_NUMEQUALVERIFY:
774 case OP_NUMNOTEQUAL:
775 case OP_LESSTHAN:
776 case OP_GREATERTHAN:
777 case OP_LESSTHANOREQUAL:
778 case OP_GREATERTHANOREQUAL:
779 case OP_MIN:
780 case OP_MAX:
782 // (x1 x2 -- out)
783 if (stack.size() < 2)
784 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
785 CScriptNum bn1(stacktop(-2), fRequireMinimal);
786 CScriptNum bn2(stacktop(-1), fRequireMinimal);
787 CScriptNum bn(0);
788 switch (opcode)
790 case OP_ADD:
791 bn = bn1 + bn2;
792 break;
794 case OP_SUB:
795 bn = bn1 - bn2;
796 break;
798 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
799 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
800 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
801 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
802 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
803 case OP_LESSTHAN: bn = (bn1 < bn2); break;
804 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
805 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
806 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
807 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
808 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
809 default: assert(!"invalid opcode"); break;
811 popstack(stack);
812 popstack(stack);
813 stack.push_back(bn.getvch());
815 if (opcode == OP_NUMEQUALVERIFY)
817 if (CastToBool(stacktop(-1)))
818 popstack(stack);
819 else
820 return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
823 break;
825 case OP_WITHIN:
827 // (x min max -- out)
828 if (stack.size() < 3)
829 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
830 CScriptNum bn1(stacktop(-3), fRequireMinimal);
831 CScriptNum bn2(stacktop(-2), fRequireMinimal);
832 CScriptNum bn3(stacktop(-1), fRequireMinimal);
833 bool fValue = (bn2 <= bn1 && bn1 < bn3);
834 popstack(stack);
835 popstack(stack);
836 popstack(stack);
837 stack.push_back(fValue ? vchTrue : vchFalse);
839 break;
843 // Crypto
845 case OP_RIPEMD160:
846 case OP_SHA1:
847 case OP_SHA256:
848 case OP_HASH160:
849 case OP_HASH256:
851 // (in -- hash)
852 if (stack.size() < 1)
853 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
854 valtype& vch = stacktop(-1);
855 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
856 if (opcode == OP_RIPEMD160)
857 CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
858 else if (opcode == OP_SHA1)
859 CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
860 else if (opcode == OP_SHA256)
861 CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
862 else if (opcode == OP_HASH160)
863 CHash160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
864 else if (opcode == OP_HASH256)
865 CHash256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
866 popstack(stack);
867 stack.push_back(vchHash);
869 break;
871 case OP_CODESEPARATOR:
873 // Hash starts after the code separator
874 pbegincodehash = pc;
876 break;
878 case OP_CHECKSIG:
879 case OP_CHECKSIGVERIFY:
881 // (sig pubkey -- bool)
882 if (stack.size() < 2)
883 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
885 valtype& vchSig = stacktop(-2);
886 valtype& vchPubKey = stacktop(-1);
888 // Subset of script starting at the most recent codeseparator
889 CScript scriptCode(pbegincodehash, pend);
891 // Drop the signature in pre-segwit scripts but not segwit scripts
892 if (sigversion == SIGVERSION_BASE) {
893 scriptCode.FindAndDelete(CScript(vchSig));
896 if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
897 //serror is set
898 return false;
900 bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
902 if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
903 return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
905 popstack(stack);
906 popstack(stack);
907 stack.push_back(fSuccess ? vchTrue : vchFalse);
908 if (opcode == OP_CHECKSIGVERIFY)
910 if (fSuccess)
911 popstack(stack);
912 else
913 return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
916 break;
918 case OP_CHECKMULTISIG:
919 case OP_CHECKMULTISIGVERIFY:
921 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
923 int i = 1;
924 if ((int)stack.size() < i)
925 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
927 int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
928 if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
929 return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
930 nOpCount += nKeysCount;
931 if (nOpCount > MAX_OPS_PER_SCRIPT)
932 return set_error(serror, SCRIPT_ERR_OP_COUNT);
933 int ikey = ++i;
934 // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
935 // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
936 int ikey2 = nKeysCount + 2;
937 i += nKeysCount;
938 if ((int)stack.size() < i)
939 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
941 int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
942 if (nSigsCount < 0 || nSigsCount > nKeysCount)
943 return set_error(serror, SCRIPT_ERR_SIG_COUNT);
944 int isig = ++i;
945 i += nSigsCount;
946 if ((int)stack.size() < i)
947 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
949 // Subset of script starting at the most recent codeseparator
950 CScript scriptCode(pbegincodehash, pend);
952 // Drop the signature in pre-segwit scripts but not segwit scripts
953 for (int k = 0; k < nSigsCount; k++)
955 valtype& vchSig = stacktop(-isig-k);
956 if (sigversion == SIGVERSION_BASE) {
957 scriptCode.FindAndDelete(CScript(vchSig));
961 bool fSuccess = true;
962 while (fSuccess && nSigsCount > 0)
964 valtype& vchSig = stacktop(-isig);
965 valtype& vchPubKey = stacktop(-ikey);
967 // Note how this makes the exact order of pubkey/signature evaluation
968 // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
969 // See the script_(in)valid tests for details.
970 if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
971 // serror is set
972 return false;
975 // Check signature
976 bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
978 if (fOk) {
979 isig++;
980 nSigsCount--;
982 ikey++;
983 nKeysCount--;
985 // If there are more signatures left than keys left,
986 // then too many signatures have failed. Exit early,
987 // without checking any further signatures.
988 if (nSigsCount > nKeysCount)
989 fSuccess = false;
992 // Clean up stack of actual arguments
993 while (i-- > 1) {
994 // If the operation failed, we require that all signatures must be empty vector
995 if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
996 return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
997 if (ikey2 > 0)
998 ikey2--;
999 popstack(stack);
1002 // A bug causes CHECKMULTISIG to consume one extra argument
1003 // whose contents were not checked in any way.
1005 // Unfortunately this is a potential source of mutability,
1006 // so optionally verify it is exactly equal to zero prior
1007 // to removing it from the stack.
1008 if (stack.size() < 1)
1009 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1010 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1011 return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1012 popstack(stack);
1014 stack.push_back(fSuccess ? vchTrue : vchFalse);
1016 if (opcode == OP_CHECKMULTISIGVERIFY)
1018 if (fSuccess)
1019 popstack(stack);
1020 else
1021 return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1024 break;
1026 default:
1027 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1030 // Size limits
1031 if (stack.size() + altstack.size() > MAX_STACK_SIZE)
1032 return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1035 catch (...)
1037 return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1040 if (!vfExec.empty())
1041 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1043 return set_success(serror);
1046 namespace {
1049 * Wrapper that serializes like CTransaction, but with the modifications
1050 * required for the signature hash done in-place
1052 class CTransactionSignatureSerializer {
1053 private:
1054 const CTransaction& txTo; //!< reference to the spending transaction (the one being serialized)
1055 const CScript& scriptCode; //!< output script being consumed
1056 const unsigned int nIn; //!< input index of txTo being signed
1057 const bool fAnyoneCanPay; //!< whether the hashtype has the SIGHASH_ANYONECANPAY flag set
1058 const bool fHashSingle; //!< whether the hashtype is SIGHASH_SINGLE
1059 const bool fHashNone; //!< whether the hashtype is SIGHASH_NONE
1061 public:
1062 CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1063 txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1064 fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1065 fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1066 fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1068 /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1069 template<typename S>
1070 void SerializeScriptCode(S &s) const {
1071 CScript::const_iterator it = scriptCode.begin();
1072 CScript::const_iterator itBegin = it;
1073 opcodetype opcode;
1074 unsigned int nCodeSeparators = 0;
1075 while (scriptCode.GetOp(it, opcode)) {
1076 if (opcode == OP_CODESEPARATOR)
1077 nCodeSeparators++;
1079 ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1080 it = itBegin;
1081 while (scriptCode.GetOp(it, opcode)) {
1082 if (opcode == OP_CODESEPARATOR) {
1083 s.write((char*)&itBegin[0], it-itBegin-1);
1084 itBegin = it;
1087 if (itBegin != scriptCode.end())
1088 s.write((char*)&itBegin[0], it-itBegin);
1091 /** Serialize an input of txTo */
1092 template<typename S>
1093 void SerializeInput(S &s, unsigned int nInput) const {
1094 // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1095 if (fAnyoneCanPay)
1096 nInput = nIn;
1097 // Serialize the prevout
1098 ::Serialize(s, txTo.vin[nInput].prevout);
1099 // Serialize the script
1100 if (nInput != nIn)
1101 // Blank out other inputs' signatures
1102 ::Serialize(s, CScript());
1103 else
1104 SerializeScriptCode(s);
1105 // Serialize the nSequence
1106 if (nInput != nIn && (fHashSingle || fHashNone))
1107 // let the others update at will
1108 ::Serialize(s, (int)0);
1109 else
1110 ::Serialize(s, txTo.vin[nInput].nSequence);
1113 /** Serialize an output of txTo */
1114 template<typename S>
1115 void SerializeOutput(S &s, unsigned int nOutput) const {
1116 if (fHashSingle && nOutput != nIn)
1117 // Do not lock-in the txout payee at other indices as txin
1118 ::Serialize(s, CTxOut());
1119 else
1120 ::Serialize(s, txTo.vout[nOutput]);
1123 /** Serialize txTo */
1124 template<typename S>
1125 void Serialize(S &s) const {
1126 // Serialize nVersion
1127 ::Serialize(s, txTo.nVersion);
1128 // Serialize vin
1129 unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1130 ::WriteCompactSize(s, nInputs);
1131 for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1132 SerializeInput(s, nInput);
1133 // Serialize vout
1134 unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1135 ::WriteCompactSize(s, nOutputs);
1136 for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1137 SerializeOutput(s, nOutput);
1138 // Serialize nLockTime
1139 ::Serialize(s, txTo.nLockTime);
1143 uint256 GetPrevoutHash(const CTransaction& txTo) {
1144 CHashWriter ss(SER_GETHASH, 0);
1145 for (const auto& txin : txTo.vin) {
1146 ss << txin.prevout;
1148 return ss.GetHash();
1151 uint256 GetSequenceHash(const CTransaction& txTo) {
1152 CHashWriter ss(SER_GETHASH, 0);
1153 for (const auto& txin : txTo.vin) {
1154 ss << txin.nSequence;
1156 return ss.GetHash();
1159 uint256 GetOutputsHash(const CTransaction& txTo) {
1160 CHashWriter ss(SER_GETHASH, 0);
1161 for (const auto& txout : txTo.vout) {
1162 ss << txout;
1164 return ss.GetHash();
1167 } // namespace
1169 PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo)
1171 // Cache is calculated only for transactions with witness
1172 if (txTo.HasWitness()) {
1173 hashPrevouts = GetPrevoutHash(txTo);
1174 hashSequence = GetSequenceHash(txTo);
1175 hashOutputs = GetOutputsHash(txTo);
1176 ready = true;
1180 uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1182 assert(nIn < txTo.vin.size());
1184 if (sigversion == SIGVERSION_WITNESS_V0) {
1185 uint256 hashPrevouts;
1186 uint256 hashSequence;
1187 uint256 hashOutputs;
1188 const bool cacheready = cache && cache->ready;
1190 if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1191 hashPrevouts = cacheready ? cache->hashPrevouts : GetPrevoutHash(txTo);
1194 if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1195 hashSequence = cacheready ? cache->hashSequence : GetSequenceHash(txTo);
1199 if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1200 hashOutputs = cacheready ? cache->hashOutputs : GetOutputsHash(txTo);
1201 } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
1202 CHashWriter ss(SER_GETHASH, 0);
1203 ss << txTo.vout[nIn];
1204 hashOutputs = ss.GetHash();
1207 CHashWriter ss(SER_GETHASH, 0);
1208 // Version
1209 ss << txTo.nVersion;
1210 // Input prevouts/nSequence (none/all, depending on flags)
1211 ss << hashPrevouts;
1212 ss << hashSequence;
1213 // The input being signed (replacing the scriptSig with scriptCode + amount)
1214 // The prevout may already be contained in hashPrevout, and the nSequence
1215 // may already be contain in hashSequence.
1216 ss << txTo.vin[nIn].prevout;
1217 ss << scriptCode;
1218 ss << amount;
1219 ss << txTo.vin[nIn].nSequence;
1220 // Outputs (none/one/all, depending on flags)
1221 ss << hashOutputs;
1222 // Locktime
1223 ss << txTo.nLockTime;
1224 // Sighash type
1225 ss << nHashType;
1227 return ss.GetHash();
1230 static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
1232 // Check for invalid use of SIGHASH_SINGLE
1233 if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1234 if (nIn >= txTo.vout.size()) {
1235 // nOut out of range
1236 return one;
1240 // Wrapper to serialize only the necessary parts of the transaction being signed
1241 CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
1243 // Serialize and hash
1244 CHashWriter ss(SER_GETHASH, 0);
1245 ss << txTmp << nHashType;
1246 return ss.GetHash();
1249 bool TransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1251 return pubkey.Verify(sighash, vchSig);
1254 bool TransactionSignatureChecker::CheckSig(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1256 CPubKey pubkey(vchPubKey);
1257 if (!pubkey.IsValid())
1258 return false;
1260 // Hash type is one byte tacked on to the end of the signature
1261 std::vector<unsigned char> vchSig(vchSigIn);
1262 if (vchSig.empty())
1263 return false;
1264 int nHashType = vchSig.back();
1265 vchSig.pop_back();
1267 uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
1269 if (!VerifySignature(vchSig, pubkey, sighash))
1270 return false;
1272 return true;
1275 bool TransactionSignatureChecker::CheckLockTime(const CScriptNum& nLockTime) const
1277 // There are two kinds of nLockTime: lock-by-blockheight
1278 // and lock-by-blocktime, distinguished by whether
1279 // nLockTime < LOCKTIME_THRESHOLD.
1281 // We want to compare apples to apples, so fail the script
1282 // unless the type of nLockTime being tested is the same as
1283 // the nLockTime in the transaction.
1284 if (!(
1285 (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
1286 (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1288 return false;
1290 // Now that we know we're comparing apples-to-apples, the
1291 // comparison is a simple numeric one.
1292 if (nLockTime > (int64_t)txTo->nLockTime)
1293 return false;
1295 // Finally the nLockTime feature can be disabled and thus
1296 // CHECKLOCKTIMEVERIFY bypassed if every txin has been
1297 // finalized by setting nSequence to maxint. The
1298 // transaction would be allowed into the blockchain, making
1299 // the opcode ineffective.
1301 // Testing if this vin is not final is sufficient to
1302 // prevent this condition. Alternatively we could test all
1303 // inputs, but testing just this input minimizes the data
1304 // required to prove correct CHECKLOCKTIMEVERIFY execution.
1305 if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1306 return false;
1308 return true;
1311 bool TransactionSignatureChecker::CheckSequence(const CScriptNum& nSequence) const
1313 // Relative lock times are supported by comparing the passed
1314 // in operand to the sequence number of the input.
1315 const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1317 // Fail if the transaction's version number is not set high
1318 // enough to trigger BIP 68 rules.
1319 if (static_cast<uint32_t>(txTo->nVersion) < 2)
1320 return false;
1322 // Sequence numbers with their most significant bit set are not
1323 // consensus constrained. Testing that the transaction's sequence
1324 // number do not have this bit set prevents using this property
1325 // to get around a CHECKSEQUENCEVERIFY check.
1326 if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1327 return false;
1329 // Mask off any bits that do not have consensus-enforced meaning
1330 // before doing the integer comparisons
1331 const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1332 const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1333 const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1335 // There are two kinds of nSequence: lock-by-blockheight
1336 // and lock-by-blocktime, distinguished by whether
1337 // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1339 // We want to compare apples to apples, so fail the script
1340 // unless the type of nSequenceMasked being tested is the same as
1341 // the nSequenceMasked in the transaction.
1342 if (!(
1343 (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1344 (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1345 )) {
1346 return false;
1349 // Now that we know we're comparing apples-to-apples, the
1350 // comparison is a simple numeric one.
1351 if (nSequenceMasked > txToSequenceMasked)
1352 return false;
1354 return true;
1357 static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1359 std::vector<std::vector<unsigned char> > stack;
1360 CScript scriptPubKey;
1362 if (witversion == 0) {
1363 if (program.size() == 32) {
1364 // Version 0 segregated witness program: SHA256(CScript) inside the program, CScript + inputs in witness
1365 if (witness.stack.size() == 0) {
1366 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1368 scriptPubKey = CScript(witness.stack.back().begin(), witness.stack.back().end());
1369 stack = std::vector<std::vector<unsigned char> >(witness.stack.begin(), witness.stack.end() - 1);
1370 uint256 hashScriptPubKey;
1371 CSHA256().Write(&scriptPubKey[0], scriptPubKey.size()).Finalize(hashScriptPubKey.begin());
1372 if (memcmp(hashScriptPubKey.begin(), program.data(), 32)) {
1373 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1375 } else if (program.size() == 20) {
1376 // Special case for pay-to-pubkeyhash; signature + pubkey in witness
1377 if (witness.stack.size() != 2) {
1378 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1380 scriptPubKey << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
1381 stack = witness.stack;
1382 } else {
1383 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
1385 } else if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
1386 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
1387 } else {
1388 // Higher version witness scripts return true for future softfork compatibility
1389 return set_success(serror);
1392 // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
1393 for (unsigned int i = 0; i < stack.size(); i++) {
1394 if (stack.at(i).size() > MAX_SCRIPT_ELEMENT_SIZE)
1395 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
1398 if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_WITNESS_V0, serror)) {
1399 return false;
1402 // Scripts inside witness implicitly require cleanstack behaviour
1403 if (stack.size() != 1)
1404 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1405 if (!CastToBool(stack.back()))
1406 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1407 return true;
1410 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1412 static const CScriptWitness emptyWitness;
1413 if (witness == nullptr) {
1414 witness = &emptyWitness;
1416 bool hadWitness = false;
1418 set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1420 if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1421 return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1424 std::vector<std::vector<unsigned char> > stack, stackCopy;
1425 if (!EvalScript(stack, scriptSig, flags, checker, SIGVERSION_BASE, serror))
1426 // serror is set
1427 return false;
1428 if (flags & SCRIPT_VERIFY_P2SH)
1429 stackCopy = stack;
1430 if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_BASE, serror))
1431 // serror is set
1432 return false;
1433 if (stack.empty())
1434 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1435 if (CastToBool(stack.back()) == false)
1436 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1438 // Bare witness programs
1439 int witnessversion;
1440 std::vector<unsigned char> witnessprogram;
1441 if (flags & SCRIPT_VERIFY_WITNESS) {
1442 if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1443 hadWitness = true;
1444 if (scriptSig.size() != 0) {
1445 // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
1446 return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
1448 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
1449 return false;
1451 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1452 // for witness programs.
1453 stack.resize(1);
1457 // Additional validation for spend-to-script-hash transactions:
1458 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1460 // scriptSig must be literals-only or validation fails
1461 if (!scriptSig.IsPushOnly())
1462 return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1464 // Restore stack.
1465 swap(stack, stackCopy);
1467 // stack cannot be empty here, because if it was the
1468 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1469 // an empty stack and the EvalScript above would return false.
1470 assert(!stack.empty());
1472 const valtype& pubKeySerialized = stack.back();
1473 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1474 popstack(stack);
1476 if (!EvalScript(stack, pubKey2, flags, checker, SIGVERSION_BASE, serror))
1477 // serror is set
1478 return false;
1479 if (stack.empty())
1480 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1481 if (!CastToBool(stack.back()))
1482 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1484 // P2SH witness program
1485 if (flags & SCRIPT_VERIFY_WITNESS) {
1486 if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
1487 hadWitness = true;
1488 if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
1489 // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
1490 // reintroduce malleability.
1491 return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
1493 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
1494 return false;
1496 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1497 // for witness programs.
1498 stack.resize(1);
1503 // The CLEANSTACK check is only performed after potential P2SH evaluation,
1504 // as the non-P2SH evaluation of a P2SH script will obviously not result in
1505 // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
1506 if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
1507 // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
1508 // would be possible, which is not a softfork (and P2SH should be one).
1509 assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1510 assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
1511 if (stack.size() != 1) {
1512 return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1516 if (flags & SCRIPT_VERIFY_WITNESS) {
1517 // We can't check for correct unexpected witness data if P2SH was off, so require
1518 // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
1519 // possible, which is not a softfork.
1520 assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1521 if (!hadWitness && !witness->IsNull()) {
1522 return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
1526 return set_success(serror);
1529 size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness, int flags)
1531 if (witversion == 0) {
1532 if (witprogram.size() == 20)
1533 return 1;
1535 if (witprogram.size() == 32 && witness.stack.size() > 0) {
1536 CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
1537 return subscript.GetSigOpCount(true);
1541 // Future flags may be implemented here.
1542 return 0;
1545 size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags)
1547 static const CScriptWitness witnessEmpty;
1549 if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
1550 return 0;
1552 assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1554 int witnessversion;
1555 std::vector<unsigned char> witnessprogram;
1556 if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1557 return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty, flags);
1560 if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
1561 CScript::const_iterator pc = scriptSig.begin();
1562 std::vector<unsigned char> data;
1563 while (pc < scriptSig.end()) {
1564 opcodetype opcode;
1565 scriptSig.GetOp(pc, opcode, data);
1567 CScript subscript(data.begin(), data.end());
1568 if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
1569 return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty, flags);
1573 return 0;