Separate CheckLockTime() and CheckSequence() logic
[bitcoinplatinum.git] / src / script / interpreter.cpp
blobd4fe001d7a8fb3eea4330ae3e8940c2d48fda1ab
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
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 using namespace std;
18 typedef vector<unsigned char> valtype;
20 namespace {
22 inline bool set_success(ScriptError* ret)
24 if (ret)
25 *ret = SCRIPT_ERR_OK;
26 return true;
29 inline bool set_error(ScriptError* ret, const ScriptError serror)
31 if (ret)
32 *ret = serror;
33 return false;
36 } // anon namespace
38 bool CastToBool(const valtype& vch)
40 for (unsigned int i = 0; i < vch.size(); i++)
42 if (vch[i] != 0)
44 // Can be negative zero
45 if (i == vch.size()-1 && vch[i] == 0x80)
46 return false;
47 return true;
50 return false;
53 /**
54 * Script is a stack machine (like Forth) that evaluates a predicate
55 * returning a bool indicating valid or not. There are no loops.
57 #define stacktop(i) (stack.at(stack.size()+(i)))
58 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
59 static inline void popstack(vector<valtype>& stack)
61 if (stack.empty())
62 throw runtime_error("popstack(): stack empty");
63 stack.pop_back();
66 bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
67 if (vchPubKey.size() < 33) {
68 // Non-canonical public key: too short
69 return false;
71 if (vchPubKey[0] == 0x04) {
72 if (vchPubKey.size() != 65) {
73 // Non-canonical public key: invalid length for uncompressed key
74 return false;
76 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
77 if (vchPubKey.size() != 33) {
78 // Non-canonical public key: invalid length for compressed key
79 return false;
81 } else {
82 // Non-canonical public key: neither compressed nor uncompressed
83 return false;
85 return true;
88 /**
89 * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
90 * Where R and S are not negative (their first byte has its highest bit not set), and not
91 * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
92 * in which case a single 0 byte is necessary and even required).
94 * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
96 * This function is consensus-critical since BIP66.
98 bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
99 // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
100 // * total-length: 1-byte length descriptor of everything that follows,
101 // excluding the sighash byte.
102 // * R-length: 1-byte length descriptor of the R value that follows.
103 // * R: arbitrary-length big-endian encoded R value. It must use the shortest
104 // possible encoding for a positive integers (which means no null bytes at
105 // the start, except a single one when the next byte has its highest bit set).
106 // * S-length: 1-byte length descriptor of the S value that follows.
107 // * S: arbitrary-length big-endian encoded S value. The same rules apply.
108 // * sighash: 1-byte value indicating what data is hashed (not part of the DER
109 // signature)
111 // Minimum and maximum size constraints.
112 if (sig.size() < 9) return false;
113 if (sig.size() > 73) return false;
115 // A signature is of type 0x30 (compound).
116 if (sig[0] != 0x30) return false;
118 // Make sure the length covers the entire signature.
119 if (sig[1] != sig.size() - 3) return false;
121 // Extract the length of the R element.
122 unsigned int lenR = sig[3];
124 // Make sure the length of the S element is still inside the signature.
125 if (5 + lenR >= sig.size()) return false;
127 // Extract the length of the S element.
128 unsigned int lenS = sig[5 + lenR];
130 // Verify that the length of the signature matches the sum of the length
131 // of the elements.
132 if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
134 // Check whether the R element is an integer.
135 if (sig[2] != 0x02) return false;
137 // Zero-length integers are not allowed for R.
138 if (lenR == 0) return false;
140 // Negative numbers are not allowed for R.
141 if (sig[4] & 0x80) return false;
143 // Null bytes at the start of R are not allowed, unless R would
144 // otherwise be interpreted as a negative number.
145 if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
147 // Check whether the S element is an integer.
148 if (sig[lenR + 4] != 0x02) return false;
150 // Zero-length integers are not allowed for S.
151 if (lenS == 0) return false;
153 // Negative numbers are not allowed for S.
154 if (sig[lenR + 6] & 0x80) return false;
156 // Null bytes at the start of S are not allowed, unless S would otherwise be
157 // interpreted as a negative number.
158 if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
160 return true;
163 bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
164 if (!IsValidSignatureEncoding(vchSig)) {
165 return set_error(serror, SCRIPT_ERR_SIG_DER);
167 std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
168 if (!CPubKey::CheckLowS(vchSigCopy)) {
169 return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
171 return true;
174 bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
175 if (vchSig.size() == 0) {
176 return false;
178 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
179 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
180 return false;
182 return true;
185 bool CheckSignatureEncoding(const vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
186 // Empty signature. Not strictly DER encoded, but allowed to provide a
187 // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
188 if (vchSig.size() == 0) {
189 return true;
191 if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
192 return set_error(serror, SCRIPT_ERR_SIG_DER);
193 } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
194 // serror is set
195 return false;
196 } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
197 return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
199 return true;
202 bool static CheckPubKeyEncoding(const valtype &vchSig, unsigned int flags, ScriptError* serror) {
203 if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchSig)) {
204 return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
206 return true;
209 bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
210 if (data.size() == 0) {
211 // Could have used OP_0.
212 return opcode == OP_0;
213 } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
214 // Could have used OP_1 .. OP_16.
215 return opcode == OP_1 + (data[0] - 1);
216 } else if (data.size() == 1 && data[0] == 0x81) {
217 // Could have used OP_1NEGATE.
218 return opcode == OP_1NEGATE;
219 } else if (data.size() <= 75) {
220 // Could have used a direct push (opcode indicating number of bytes pushed + those bytes).
221 return opcode == data.size();
222 } else if (data.size() <= 255) {
223 // Could have used OP_PUSHDATA.
224 return opcode == OP_PUSHDATA1;
225 } else if (data.size() <= 65535) {
226 // Could have used OP_PUSHDATA2.
227 return opcode == OP_PUSHDATA2;
229 return true;
232 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
234 static const CScriptNum bnZero(0);
235 static const CScriptNum bnOne(1);
236 static const CScriptNum bnFalse(0);
237 static const CScriptNum bnTrue(1);
238 static const valtype vchFalse(0);
239 static const valtype vchZero(0);
240 static const valtype vchTrue(1, 1);
242 CScript::const_iterator pc = script.begin();
243 CScript::const_iterator pend = script.end();
244 CScript::const_iterator pbegincodehash = script.begin();
245 opcodetype opcode;
246 valtype vchPushValue;
247 vector<bool> vfExec;
248 vector<valtype> altstack;
249 set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
250 if (script.size() > 10000)
251 return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
252 int nOpCount = 0;
253 bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
257 while (pc < pend)
259 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
262 // Read instruction
264 if (!script.GetOp(pc, opcode, vchPushValue))
265 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
266 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
267 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
269 // Note how OP_RESERVED does not count towards the opcode limit.
270 if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
271 return set_error(serror, SCRIPT_ERR_OP_COUNT);
273 if (opcode == OP_CAT ||
274 opcode == OP_SUBSTR ||
275 opcode == OP_LEFT ||
276 opcode == OP_RIGHT ||
277 opcode == OP_INVERT ||
278 opcode == OP_AND ||
279 opcode == OP_OR ||
280 opcode == OP_XOR ||
281 opcode == OP_2MUL ||
282 opcode == OP_2DIV ||
283 opcode == OP_MUL ||
284 opcode == OP_DIV ||
285 opcode == OP_MOD ||
286 opcode == OP_LSHIFT ||
287 opcode == OP_RSHIFT)
288 return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes.
290 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
291 if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
292 return set_error(serror, SCRIPT_ERR_MINIMALDATA);
294 stack.push_back(vchPushValue);
295 } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
296 switch (opcode)
299 // Push value
301 case OP_1NEGATE:
302 case OP_1:
303 case OP_2:
304 case OP_3:
305 case OP_4:
306 case OP_5:
307 case OP_6:
308 case OP_7:
309 case OP_8:
310 case OP_9:
311 case OP_10:
312 case OP_11:
313 case OP_12:
314 case OP_13:
315 case OP_14:
316 case OP_15:
317 case OP_16:
319 // ( -- value)
320 CScriptNum bn((int)opcode - (int)(OP_1 - 1));
321 stack.push_back(bn.getvch());
322 // The result of these opcodes should always be the minimal way to push the data
323 // they push, so no need for a CheckMinimalPush here.
325 break;
329 // Control
331 case OP_NOP:
332 break;
334 case OP_CHECKLOCKTIMEVERIFY:
336 if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
337 // not enabled; treat as a NOP2
338 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
339 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
341 break;
344 if (stack.size() < 1)
345 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
347 // Note that elsewhere numeric opcodes are limited to
348 // operands in the range -2**31+1 to 2**31-1, however it is
349 // legal for opcodes to produce results exceeding that
350 // range. This limitation is implemented by CScriptNum's
351 // default 4-byte limit.
353 // If we kept to that limit we'd have a year 2038 problem,
354 // even though the nLockTime field in transactions
355 // themselves is uint32 which only becomes meaningless
356 // after the year 2106.
358 // Thus as a special case we tell CScriptNum to accept up
359 // to 5-byte bignums, which are good until 2**39-1, well
360 // beyond the 2**32-1 limit of the nLockTime field itself.
361 const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
363 // In the rare event that the argument may be < 0 due to
364 // some arithmetic being done first, you can always use
365 // 0 MAX CHECKLOCKTIMEVERIFY.
366 if (nLockTime < 0)
367 return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
369 // Actually compare the specified lock time with the transaction.
370 if (!checker.CheckLockTime(nLockTime))
371 return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
373 break;
376 case OP_CHECKSEQUENCEVERIFY:
378 if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
379 // not enabled; treat as a NOP3
380 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
381 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
383 break;
386 if (stack.size() < 1)
387 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
389 // nSequence, like nLockTime, is a 32-bit unsigned integer
390 // field. See the comment in CHECKLOCKTIMEVERIFY regarding
391 // 5-byte numeric operands.
392 const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
394 // In the rare event that the argument may be < 0 due to
395 // some arithmetic being done first, you can always use
396 // 0 MAX CHECKSEQUENCEVERIFY.
397 if (nSequence < 0)
398 return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
400 // To provide for future soft-fork extensibility, if the
401 // operand has the disabled lock-time flag set,
402 // CHECKSEQUENCEVERIFY behaves as a NOP.
403 if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
404 break;
406 // Compare the specified sequence number with the input.
407 if (!checker.CheckSequence(nSequence))
408 return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
410 break;
413 case OP_NOP1: case OP_NOP4: case OP_NOP5:
414 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
416 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
417 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
419 break;
421 case OP_IF:
422 case OP_NOTIF:
424 // <expression> if [statements] [else [statements]] endif
425 bool fValue = false;
426 if (fExec)
428 if (stack.size() < 1)
429 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
430 valtype& vch = stacktop(-1);
431 fValue = CastToBool(vch);
432 if (opcode == OP_NOTIF)
433 fValue = !fValue;
434 popstack(stack);
436 vfExec.push_back(fValue);
438 break;
440 case OP_ELSE:
442 if (vfExec.empty())
443 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
444 vfExec.back() = !vfExec.back();
446 break;
448 case OP_ENDIF:
450 if (vfExec.empty())
451 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
452 vfExec.pop_back();
454 break;
456 case OP_VERIFY:
458 // (true -- ) or
459 // (false -- false) and return
460 if (stack.size() < 1)
461 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
462 bool fValue = CastToBool(stacktop(-1));
463 if (fValue)
464 popstack(stack);
465 else
466 return set_error(serror, SCRIPT_ERR_VERIFY);
468 break;
470 case OP_RETURN:
472 return set_error(serror, SCRIPT_ERR_OP_RETURN);
474 break;
478 // Stack ops
480 case OP_TOALTSTACK:
482 if (stack.size() < 1)
483 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
484 altstack.push_back(stacktop(-1));
485 popstack(stack);
487 break;
489 case OP_FROMALTSTACK:
491 if (altstack.size() < 1)
492 return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
493 stack.push_back(altstacktop(-1));
494 popstack(altstack);
496 break;
498 case OP_2DROP:
500 // (x1 x2 -- )
501 if (stack.size() < 2)
502 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
503 popstack(stack);
504 popstack(stack);
506 break;
508 case OP_2DUP:
510 // (x1 x2 -- x1 x2 x1 x2)
511 if (stack.size() < 2)
512 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
513 valtype vch1 = stacktop(-2);
514 valtype vch2 = stacktop(-1);
515 stack.push_back(vch1);
516 stack.push_back(vch2);
518 break;
520 case OP_3DUP:
522 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
523 if (stack.size() < 3)
524 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
525 valtype vch1 = stacktop(-3);
526 valtype vch2 = stacktop(-2);
527 valtype vch3 = stacktop(-1);
528 stack.push_back(vch1);
529 stack.push_back(vch2);
530 stack.push_back(vch3);
532 break;
534 case OP_2OVER:
536 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
537 if (stack.size() < 4)
538 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
539 valtype vch1 = stacktop(-4);
540 valtype vch2 = stacktop(-3);
541 stack.push_back(vch1);
542 stack.push_back(vch2);
544 break;
546 case OP_2ROT:
548 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
549 if (stack.size() < 6)
550 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
551 valtype vch1 = stacktop(-6);
552 valtype vch2 = stacktop(-5);
553 stack.erase(stack.end()-6, stack.end()-4);
554 stack.push_back(vch1);
555 stack.push_back(vch2);
557 break;
559 case OP_2SWAP:
561 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
562 if (stack.size() < 4)
563 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
564 swap(stacktop(-4), stacktop(-2));
565 swap(stacktop(-3), stacktop(-1));
567 break;
569 case OP_IFDUP:
571 // (x - 0 | x x)
572 if (stack.size() < 1)
573 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
574 valtype vch = stacktop(-1);
575 if (CastToBool(vch))
576 stack.push_back(vch);
578 break;
580 case OP_DEPTH:
582 // -- stacksize
583 CScriptNum bn(stack.size());
584 stack.push_back(bn.getvch());
586 break;
588 case OP_DROP:
590 // (x -- )
591 if (stack.size() < 1)
592 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
593 popstack(stack);
595 break;
597 case OP_DUP:
599 // (x -- x x)
600 if (stack.size() < 1)
601 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
602 valtype vch = stacktop(-1);
603 stack.push_back(vch);
605 break;
607 case OP_NIP:
609 // (x1 x2 -- x2)
610 if (stack.size() < 2)
611 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
612 stack.erase(stack.end() - 2);
614 break;
616 case OP_OVER:
618 // (x1 x2 -- x1 x2 x1)
619 if (stack.size() < 2)
620 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
621 valtype vch = stacktop(-2);
622 stack.push_back(vch);
624 break;
626 case OP_PICK:
627 case OP_ROLL:
629 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
630 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
631 if (stack.size() < 2)
632 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
633 int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
634 popstack(stack);
635 if (n < 0 || n >= (int)stack.size())
636 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
637 valtype vch = stacktop(-n-1);
638 if (opcode == OP_ROLL)
639 stack.erase(stack.end()-n-1);
640 stack.push_back(vch);
642 break;
644 case OP_ROT:
646 // (x1 x2 x3 -- x2 x3 x1)
647 // x2 x1 x3 after first swap
648 // x2 x3 x1 after second swap
649 if (stack.size() < 3)
650 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
651 swap(stacktop(-3), stacktop(-2));
652 swap(stacktop(-2), stacktop(-1));
654 break;
656 case OP_SWAP:
658 // (x1 x2 -- x2 x1)
659 if (stack.size() < 2)
660 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
661 swap(stacktop(-2), stacktop(-1));
663 break;
665 case OP_TUCK:
667 // (x1 x2 -- x2 x1 x2)
668 if (stack.size() < 2)
669 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
670 valtype vch = stacktop(-1);
671 stack.insert(stack.end()-2, vch);
673 break;
676 case OP_SIZE:
678 // (in -- in size)
679 if (stack.size() < 1)
680 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
681 CScriptNum bn(stacktop(-1).size());
682 stack.push_back(bn.getvch());
684 break;
688 // Bitwise logic
690 case OP_EQUAL:
691 case OP_EQUALVERIFY:
692 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
694 // (x1 x2 - bool)
695 if (stack.size() < 2)
696 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
697 valtype& vch1 = stacktop(-2);
698 valtype& vch2 = stacktop(-1);
699 bool fEqual = (vch1 == vch2);
700 // OP_NOTEQUAL is disabled because it would be too easy to say
701 // something like n != 1 and have some wiseguy pass in 1 with extra
702 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
703 //if (opcode == OP_NOTEQUAL)
704 // fEqual = !fEqual;
705 popstack(stack);
706 popstack(stack);
707 stack.push_back(fEqual ? vchTrue : vchFalse);
708 if (opcode == OP_EQUALVERIFY)
710 if (fEqual)
711 popstack(stack);
712 else
713 return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
716 break;
720 // Numeric
722 case OP_1ADD:
723 case OP_1SUB:
724 case OP_NEGATE:
725 case OP_ABS:
726 case OP_NOT:
727 case OP_0NOTEQUAL:
729 // (in -- out)
730 if (stack.size() < 1)
731 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
732 CScriptNum bn(stacktop(-1), fRequireMinimal);
733 switch (opcode)
735 case OP_1ADD: bn += bnOne; break;
736 case OP_1SUB: bn -= bnOne; break;
737 case OP_NEGATE: bn = -bn; break;
738 case OP_ABS: if (bn < bnZero) bn = -bn; break;
739 case OP_NOT: bn = (bn == bnZero); break;
740 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
741 default: assert(!"invalid opcode"); break;
743 popstack(stack);
744 stack.push_back(bn.getvch());
746 break;
748 case OP_ADD:
749 case OP_SUB:
750 case OP_BOOLAND:
751 case OP_BOOLOR:
752 case OP_NUMEQUAL:
753 case OP_NUMEQUALVERIFY:
754 case OP_NUMNOTEQUAL:
755 case OP_LESSTHAN:
756 case OP_GREATERTHAN:
757 case OP_LESSTHANOREQUAL:
758 case OP_GREATERTHANOREQUAL:
759 case OP_MIN:
760 case OP_MAX:
762 // (x1 x2 -- out)
763 if (stack.size() < 2)
764 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
765 CScriptNum bn1(stacktop(-2), fRequireMinimal);
766 CScriptNum bn2(stacktop(-1), fRequireMinimal);
767 CScriptNum bn(0);
768 switch (opcode)
770 case OP_ADD:
771 bn = bn1 + bn2;
772 break;
774 case OP_SUB:
775 bn = bn1 - bn2;
776 break;
778 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
779 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
780 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
781 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
782 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
783 case OP_LESSTHAN: bn = (bn1 < bn2); break;
784 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
785 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
786 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
787 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
788 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
789 default: assert(!"invalid opcode"); break;
791 popstack(stack);
792 popstack(stack);
793 stack.push_back(bn.getvch());
795 if (opcode == OP_NUMEQUALVERIFY)
797 if (CastToBool(stacktop(-1)))
798 popstack(stack);
799 else
800 return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
803 break;
805 case OP_WITHIN:
807 // (x min max -- out)
808 if (stack.size() < 3)
809 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
810 CScriptNum bn1(stacktop(-3), fRequireMinimal);
811 CScriptNum bn2(stacktop(-2), fRequireMinimal);
812 CScriptNum bn3(stacktop(-1), fRequireMinimal);
813 bool fValue = (bn2 <= bn1 && bn1 < bn3);
814 popstack(stack);
815 popstack(stack);
816 popstack(stack);
817 stack.push_back(fValue ? vchTrue : vchFalse);
819 break;
823 // Crypto
825 case OP_RIPEMD160:
826 case OP_SHA1:
827 case OP_SHA256:
828 case OP_HASH160:
829 case OP_HASH256:
831 // (in -- hash)
832 if (stack.size() < 1)
833 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
834 valtype& vch = stacktop(-1);
835 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
836 if (opcode == OP_RIPEMD160)
837 CRIPEMD160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
838 else if (opcode == OP_SHA1)
839 CSHA1().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
840 else if (opcode == OP_SHA256)
841 CSHA256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
842 else if (opcode == OP_HASH160)
843 CHash160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
844 else if (opcode == OP_HASH256)
845 CHash256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
846 popstack(stack);
847 stack.push_back(vchHash);
849 break;
851 case OP_CODESEPARATOR:
853 // Hash starts after the code separator
854 pbegincodehash = pc;
856 break;
858 case OP_CHECKSIG:
859 case OP_CHECKSIGVERIFY:
861 // (sig pubkey -- bool)
862 if (stack.size() < 2)
863 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
865 valtype& vchSig = stacktop(-2);
866 valtype& vchPubKey = stacktop(-1);
868 // Subset of script starting at the most recent codeseparator
869 CScript scriptCode(pbegincodehash, pend);
871 // Drop the signature, since there's no way for a signature to sign itself
872 scriptCode.FindAndDelete(CScript(vchSig));
874 if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
875 //serror is set
876 return false;
878 bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode);
880 popstack(stack);
881 popstack(stack);
882 stack.push_back(fSuccess ? vchTrue : vchFalse);
883 if (opcode == OP_CHECKSIGVERIFY)
885 if (fSuccess)
886 popstack(stack);
887 else
888 return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
891 break;
893 case OP_CHECKMULTISIG:
894 case OP_CHECKMULTISIGVERIFY:
896 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
898 int i = 1;
899 if ((int)stack.size() < i)
900 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
902 int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
903 if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
904 return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
905 nOpCount += nKeysCount;
906 if (nOpCount > MAX_OPS_PER_SCRIPT)
907 return set_error(serror, SCRIPT_ERR_OP_COUNT);
908 int ikey = ++i;
909 i += nKeysCount;
910 if ((int)stack.size() < i)
911 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
913 int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
914 if (nSigsCount < 0 || nSigsCount > nKeysCount)
915 return set_error(serror, SCRIPT_ERR_SIG_COUNT);
916 int isig = ++i;
917 i += nSigsCount;
918 if ((int)stack.size() < i)
919 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
921 // Subset of script starting at the most recent codeseparator
922 CScript scriptCode(pbegincodehash, pend);
924 // Drop the signatures, since there's no way for a signature to sign itself
925 for (int k = 0; k < nSigsCount; k++)
927 valtype& vchSig = stacktop(-isig-k);
928 scriptCode.FindAndDelete(CScript(vchSig));
931 bool fSuccess = true;
932 while (fSuccess && nSigsCount > 0)
934 valtype& vchSig = stacktop(-isig);
935 valtype& vchPubKey = stacktop(-ikey);
937 // Note how this makes the exact order of pubkey/signature evaluation
938 // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
939 // See the script_(in)valid tests for details.
940 if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
941 // serror is set
942 return false;
945 // Check signature
946 bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode);
948 if (fOk) {
949 isig++;
950 nSigsCount--;
952 ikey++;
953 nKeysCount--;
955 // If there are more signatures left than keys left,
956 // then too many signatures have failed. Exit early,
957 // without checking any further signatures.
958 if (nSigsCount > nKeysCount)
959 fSuccess = false;
962 // Clean up stack of actual arguments
963 while (i-- > 1)
964 popstack(stack);
966 // A bug causes CHECKMULTISIG to consume one extra argument
967 // whose contents were not checked in any way.
969 // Unfortunately this is a potential source of mutability,
970 // so optionally verify it is exactly equal to zero prior
971 // to removing it from the stack.
972 if (stack.size() < 1)
973 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
974 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
975 return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
976 popstack(stack);
978 stack.push_back(fSuccess ? vchTrue : vchFalse);
980 if (opcode == OP_CHECKMULTISIGVERIFY)
982 if (fSuccess)
983 popstack(stack);
984 else
985 return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
988 break;
990 default:
991 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
994 // Size limits
995 if (stack.size() + altstack.size() > 1000)
996 return set_error(serror, SCRIPT_ERR_STACK_SIZE);
999 catch (...)
1001 return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1004 if (!vfExec.empty())
1005 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1007 return set_success(serror);
1010 namespace {
1013 * Wrapper that serializes like CTransaction, but with the modifications
1014 * required for the signature hash done in-place
1016 class CTransactionSignatureSerializer {
1017 private:
1018 const CTransaction &txTo; //! reference to the spending transaction (the one being serialized)
1019 const CScript &scriptCode; //! output script being consumed
1020 const unsigned int nIn; //! input index of txTo being signed
1021 const bool fAnyoneCanPay; //! whether the hashtype has the SIGHASH_ANYONECANPAY flag set
1022 const bool fHashSingle; //! whether the hashtype is SIGHASH_SINGLE
1023 const bool fHashNone; //! whether the hashtype is SIGHASH_NONE
1025 public:
1026 CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1027 txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1028 fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1029 fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1030 fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1032 /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1033 template<typename S>
1034 void SerializeScriptCode(S &s, int nType, int nVersion) const {
1035 CScript::const_iterator it = scriptCode.begin();
1036 CScript::const_iterator itBegin = it;
1037 opcodetype opcode;
1038 unsigned int nCodeSeparators = 0;
1039 while (scriptCode.GetOp(it, opcode)) {
1040 if (opcode == OP_CODESEPARATOR)
1041 nCodeSeparators++;
1043 ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1044 it = itBegin;
1045 while (scriptCode.GetOp(it, opcode)) {
1046 if (opcode == OP_CODESEPARATOR) {
1047 s.write((char*)&itBegin[0], it-itBegin-1);
1048 itBegin = it;
1051 if (itBegin != scriptCode.end())
1052 s.write((char*)&itBegin[0], it-itBegin);
1055 /** Serialize an input of txTo */
1056 template<typename S>
1057 void SerializeInput(S &s, unsigned int nInput, int nType, int nVersion) const {
1058 // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1059 if (fAnyoneCanPay)
1060 nInput = nIn;
1061 // Serialize the prevout
1062 ::Serialize(s, txTo.vin[nInput].prevout, nType, nVersion);
1063 // Serialize the script
1064 if (nInput != nIn)
1065 // Blank out other inputs' signatures
1066 ::Serialize(s, CScriptBase(), nType, nVersion);
1067 else
1068 SerializeScriptCode(s, nType, nVersion);
1069 // Serialize the nSequence
1070 if (nInput != nIn && (fHashSingle || fHashNone))
1071 // let the others update at will
1072 ::Serialize(s, (int)0, nType, nVersion);
1073 else
1074 ::Serialize(s, txTo.vin[nInput].nSequence, nType, nVersion);
1077 /** Serialize an output of txTo */
1078 template<typename S>
1079 void SerializeOutput(S &s, unsigned int nOutput, int nType, int nVersion) const {
1080 if (fHashSingle && nOutput != nIn)
1081 // Do not lock-in the txout payee at other indices as txin
1082 ::Serialize(s, CTxOut(), nType, nVersion);
1083 else
1084 ::Serialize(s, txTo.vout[nOutput], nType, nVersion);
1087 /** Serialize txTo */
1088 template<typename S>
1089 void Serialize(S &s, int nType, int nVersion) const {
1090 // Serialize nVersion
1091 ::Serialize(s, txTo.nVersion, nType, nVersion);
1092 // Serialize vin
1093 unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1094 ::WriteCompactSize(s, nInputs);
1095 for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1096 SerializeInput(s, nInput, nType, nVersion);
1097 // Serialize vout
1098 unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1099 ::WriteCompactSize(s, nOutputs);
1100 for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1101 SerializeOutput(s, nOutput, nType, nVersion);
1102 // Serialize nLockTime
1103 ::Serialize(s, txTo.nLockTime, nType, nVersion);
1107 } // anon namespace
1109 uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1111 static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
1112 if (nIn >= txTo.vin.size()) {
1113 // nIn out of range
1114 return one;
1117 // Check for invalid use of SIGHASH_SINGLE
1118 if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1119 if (nIn >= txTo.vout.size()) {
1120 // nOut out of range
1121 return one;
1125 // Wrapper to serialize only the necessary parts of the transaction being signed
1126 CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
1128 // Serialize and hash
1129 CHashWriter ss(SER_GETHASH, 0);
1130 ss << txTmp << nHashType;
1131 return ss.GetHash();
1134 bool TransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1136 return pubkey.Verify(sighash, vchSig);
1139 bool TransactionSignatureChecker::CheckSig(const vector<unsigned char>& vchSigIn, const vector<unsigned char>& vchPubKey, const CScript& scriptCode) const
1141 CPubKey pubkey(vchPubKey);
1142 if (!pubkey.IsValid())
1143 return false;
1145 // Hash type is one byte tacked on to the end of the signature
1146 vector<unsigned char> vchSig(vchSigIn);
1147 if (vchSig.empty())
1148 return false;
1149 int nHashType = vchSig.back();
1150 vchSig.pop_back();
1152 uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType);
1154 if (!VerifySignature(vchSig, pubkey, sighash))
1155 return false;
1157 return true;
1160 bool TransactionSignatureChecker::CheckLockTime(const CScriptNum& nLockTime) const
1162 // There are two kinds of nLockTime: lock-by-blockheight
1163 // and lock-by-blocktime, distinguished by whether
1164 // nLockTime < LOCKTIME_THRESHOLD.
1166 // We want to compare apples to apples, so fail the script
1167 // unless the type of nLockTime being tested is the same as
1168 // the nLockTime in the transaction.
1169 if (!(
1170 (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
1171 (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1173 return false;
1175 // Now that we know we're comparing apples-to-apples, the
1176 // comparison is a simple numeric one.
1177 if (nLockTime > (int64_t)txTo->nLockTime)
1178 return false;
1180 // Finally the nLockTime feature can be disabled and thus
1181 // CHECKLOCKTIMEVERIFY bypassed if every txin has been
1182 // finalized by setting nSequence to maxint. The
1183 // transaction would be allowed into the blockchain, making
1184 // the opcode ineffective.
1186 // Testing if this vin is not final is sufficient to
1187 // prevent this condition. Alternatively we could test all
1188 // inputs, but testing just this input minimizes the data
1189 // required to prove correct CHECKLOCKTIMEVERIFY execution.
1190 if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1191 return false;
1193 return true;
1196 bool TransactionSignatureChecker::CheckSequence(const CScriptNum& nSequence) const
1198 // Relative lock times are supported by comparing the passed
1199 // in operand to the sequence number of the input.
1200 const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1202 // Fail if the transaction's version number is not set high
1203 // enough to trigger BIP 68 rules.
1204 if (static_cast<uint32_t>(txTo->nVersion) < 2)
1205 return false;
1207 // Sequence numbers with their most significant bit set are not
1208 // consensus constrained. Testing that the transaction's sequence
1209 // number do not have this bit set prevents using this property
1210 // to get around a CHECKSEQUENCEVERIFY check.
1211 if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1212 return false;
1214 // Mask off any bits that do not have consensus-enforced meaning
1215 // before doing the integer comparisons
1216 const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1217 const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1218 const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1220 // There are two kinds of nSequence: lock-by-blockheight
1221 // and lock-by-blocktime, distinguished by whether
1222 // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1224 // We want to compare apples to apples, so fail the script
1225 // unless the type of nSequenceMasked being tested is the same as
1226 // the nSequenceMasked in the transaction.
1227 if (!(
1228 (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1229 (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1231 return false;
1233 // Now that we know we're comparing apples-to-apples, the
1234 // comparison is a simple numeric one.
1235 if (nSequenceMasked > txToSequenceMasked)
1236 return false;
1238 return true;
1241 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1243 set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1245 if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1246 return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1249 vector<vector<unsigned char> > stack, stackCopy;
1250 if (!EvalScript(stack, scriptSig, flags, checker, serror))
1251 // serror is set
1252 return false;
1253 if (flags & SCRIPT_VERIFY_P2SH)
1254 stackCopy = stack;
1255 if (!EvalScript(stack, scriptPubKey, flags, checker, serror))
1256 // serror is set
1257 return false;
1258 if (stack.empty())
1259 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1260 if (CastToBool(stack.back()) == false)
1261 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1263 // Additional validation for spend-to-script-hash transactions:
1264 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1266 // scriptSig must be literals-only or validation fails
1267 if (!scriptSig.IsPushOnly())
1268 return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1270 // Restore stack.
1271 swap(stack, stackCopy);
1273 // stack cannot be empty here, because if it was the
1274 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1275 // an empty stack and the EvalScript above would return false.
1276 assert(!stack.empty());
1278 const valtype& pubKeySerialized = stack.back();
1279 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1280 popstack(stack);
1282 if (!EvalScript(stack, pubKey2, flags, checker, serror))
1283 // serror is set
1284 return false;
1285 if (stack.empty())
1286 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1287 if (!CastToBool(stack.back()))
1288 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1291 // The CLEANSTACK check is only performed after potential P2SH evaluation,
1292 // as the non-P2SH evaluation of a P2SH script will obviously not result in
1293 // a clean stack (the P2SH inputs remain).
1294 if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
1295 // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
1296 // would be possible, which is not a softfork (and P2SH should be one).
1297 assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1298 if (stack.size() != 1) {
1299 return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1303 return set_success(serror);