Get rid of nType and nVersion
[bitcoinplatinum.git] / src / script / interpreter.cpp
bloba6403f9363745e6479ab85061617a73fe07baf33
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 bool static IsCompressedPubKey(const valtype &vchPubKey) {
89 if (vchPubKey.size() != 33) {
90 // Non-canonical public key: invalid length for compressed key
91 return false;
93 if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
94 // Non-canonical public key: invalid prefix for compressed key
95 return false;
97 return true;
101 * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
102 * Where R and S are not negative (their first byte has its highest bit not set), and not
103 * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
104 * in which case a single 0 byte is necessary and even required).
106 * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
108 * This function is consensus-critical since BIP66.
110 bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
111 // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
112 // * total-length: 1-byte length descriptor of everything that follows,
113 // excluding the sighash byte.
114 // * R-length: 1-byte length descriptor of the R value that follows.
115 // * R: arbitrary-length big-endian encoded R value. It must use the shortest
116 // possible encoding for a positive integers (which means no null bytes at
117 // the start, except a single one when the next byte has its highest bit set).
118 // * S-length: 1-byte length descriptor of the S value that follows.
119 // * S: arbitrary-length big-endian encoded S value. The same rules apply.
120 // * sighash: 1-byte value indicating what data is hashed (not part of the DER
121 // signature)
123 // Minimum and maximum size constraints.
124 if (sig.size() < 9) return false;
125 if (sig.size() > 73) return false;
127 // A signature is of type 0x30 (compound).
128 if (sig[0] != 0x30) return false;
130 // Make sure the length covers the entire signature.
131 if (sig[1] != sig.size() - 3) return false;
133 // Extract the length of the R element.
134 unsigned int lenR = sig[3];
136 // Make sure the length of the S element is still inside the signature.
137 if (5 + lenR >= sig.size()) return false;
139 // Extract the length of the S element.
140 unsigned int lenS = sig[5 + lenR];
142 // Verify that the length of the signature matches the sum of the length
143 // of the elements.
144 if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
146 // Check whether the R element is an integer.
147 if (sig[2] != 0x02) return false;
149 // Zero-length integers are not allowed for R.
150 if (lenR == 0) return false;
152 // Negative numbers are not allowed for R.
153 if (sig[4] & 0x80) return false;
155 // Null bytes at the start of R are not allowed, unless R would
156 // otherwise be interpreted as a negative number.
157 if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
159 // Check whether the S element is an integer.
160 if (sig[lenR + 4] != 0x02) return false;
162 // Zero-length integers are not allowed for S.
163 if (lenS == 0) return false;
165 // Negative numbers are not allowed for S.
166 if (sig[lenR + 6] & 0x80) return false;
168 // Null bytes at the start of S are not allowed, unless S would otherwise be
169 // interpreted as a negative number.
170 if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
172 return true;
175 bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
176 if (!IsValidSignatureEncoding(vchSig)) {
177 return set_error(serror, SCRIPT_ERR_SIG_DER);
179 std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
180 if (!CPubKey::CheckLowS(vchSigCopy)) {
181 return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
183 return true;
186 bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
187 if (vchSig.size() == 0) {
188 return false;
190 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
191 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
192 return false;
194 return true;
197 bool CheckSignatureEncoding(const vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
198 // Empty signature. Not strictly DER encoded, but allowed to provide a
199 // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
200 if (vchSig.size() == 0) {
201 return true;
203 if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
204 return set_error(serror, SCRIPT_ERR_SIG_DER);
205 } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
206 // serror is set
207 return false;
208 } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
209 return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
211 return true;
214 bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
215 if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
216 return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
218 // Only compressed keys are accepted in segwit
219 if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SIGVERSION_WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
220 return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
222 return true;
225 bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
226 if (data.size() == 0) {
227 // Could have used OP_0.
228 return opcode == OP_0;
229 } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
230 // Could have used OP_1 .. OP_16.
231 return opcode == OP_1 + (data[0] - 1);
232 } else if (data.size() == 1 && data[0] == 0x81) {
233 // Could have used OP_1NEGATE.
234 return opcode == OP_1NEGATE;
235 } else if (data.size() <= 75) {
236 // Could have used a direct push (opcode indicating number of bytes pushed + those bytes).
237 return opcode == data.size();
238 } else if (data.size() <= 255) {
239 // Could have used OP_PUSHDATA.
240 return opcode == OP_PUSHDATA1;
241 } else if (data.size() <= 65535) {
242 // Could have used OP_PUSHDATA2.
243 return opcode == OP_PUSHDATA2;
245 return true;
248 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
250 static const CScriptNum bnZero(0);
251 static const CScriptNum bnOne(1);
252 static const CScriptNum bnFalse(0);
253 static const CScriptNum bnTrue(1);
254 static const valtype vchFalse(0);
255 static const valtype vchZero(0);
256 static const valtype vchTrue(1, 1);
258 CScript::const_iterator pc = script.begin();
259 CScript::const_iterator pend = script.end();
260 CScript::const_iterator pbegincodehash = script.begin();
261 opcodetype opcode;
262 valtype vchPushValue;
263 vector<bool> vfExec;
264 vector<valtype> altstack;
265 set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
266 if (script.size() > MAX_SCRIPT_SIZE)
267 return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
268 int nOpCount = 0;
269 bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
273 while (pc < pend)
275 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
278 // Read instruction
280 if (!script.GetOp(pc, opcode, vchPushValue))
281 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
282 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
283 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
285 // Note how OP_RESERVED does not count towards the opcode limit.
286 if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
287 return set_error(serror, SCRIPT_ERR_OP_COUNT);
289 if (opcode == OP_CAT ||
290 opcode == OP_SUBSTR ||
291 opcode == OP_LEFT ||
292 opcode == OP_RIGHT ||
293 opcode == OP_INVERT ||
294 opcode == OP_AND ||
295 opcode == OP_OR ||
296 opcode == OP_XOR ||
297 opcode == OP_2MUL ||
298 opcode == OP_2DIV ||
299 opcode == OP_MUL ||
300 opcode == OP_DIV ||
301 opcode == OP_MOD ||
302 opcode == OP_LSHIFT ||
303 opcode == OP_RSHIFT)
304 return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes.
306 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
307 if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
308 return set_error(serror, SCRIPT_ERR_MINIMALDATA);
310 stack.push_back(vchPushValue);
311 } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
312 switch (opcode)
315 // Push value
317 case OP_1NEGATE:
318 case OP_1:
319 case OP_2:
320 case OP_3:
321 case OP_4:
322 case OP_5:
323 case OP_6:
324 case OP_7:
325 case OP_8:
326 case OP_9:
327 case OP_10:
328 case OP_11:
329 case OP_12:
330 case OP_13:
331 case OP_14:
332 case OP_15:
333 case OP_16:
335 // ( -- value)
336 CScriptNum bn((int)opcode - (int)(OP_1 - 1));
337 stack.push_back(bn.getvch());
338 // The result of these opcodes should always be the minimal way to push the data
339 // they push, so no need for a CheckMinimalPush here.
341 break;
345 // Control
347 case OP_NOP:
348 break;
350 case OP_CHECKLOCKTIMEVERIFY:
352 if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
353 // not enabled; treat as a NOP2
354 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
355 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
357 break;
360 if (stack.size() < 1)
361 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
363 // Note that elsewhere numeric opcodes are limited to
364 // operands in the range -2**31+1 to 2**31-1, however it is
365 // legal for opcodes to produce results exceeding that
366 // range. This limitation is implemented by CScriptNum's
367 // default 4-byte limit.
369 // If we kept to that limit we'd have a year 2038 problem,
370 // even though the nLockTime field in transactions
371 // themselves is uint32 which only becomes meaningless
372 // after the year 2106.
374 // Thus as a special case we tell CScriptNum to accept up
375 // to 5-byte bignums, which are good until 2**39-1, well
376 // beyond the 2**32-1 limit of the nLockTime field itself.
377 const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
379 // In the rare event that the argument may be < 0 due to
380 // some arithmetic being done first, you can always use
381 // 0 MAX CHECKLOCKTIMEVERIFY.
382 if (nLockTime < 0)
383 return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
385 // Actually compare the specified lock time with the transaction.
386 if (!checker.CheckLockTime(nLockTime))
387 return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
389 break;
392 case OP_CHECKSEQUENCEVERIFY:
394 if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
395 // not enabled; treat as a NOP3
396 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
397 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
399 break;
402 if (stack.size() < 1)
403 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
405 // nSequence, like nLockTime, is a 32-bit unsigned integer
406 // field. See the comment in CHECKLOCKTIMEVERIFY regarding
407 // 5-byte numeric operands.
408 const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
410 // In the rare event that the argument may be < 0 due to
411 // some arithmetic being done first, you can always use
412 // 0 MAX CHECKSEQUENCEVERIFY.
413 if (nSequence < 0)
414 return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
416 // To provide for future soft-fork extensibility, if the
417 // operand has the disabled lock-time flag set,
418 // CHECKSEQUENCEVERIFY behaves as a NOP.
419 if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
420 break;
422 // Compare the specified sequence number with the input.
423 if (!checker.CheckSequence(nSequence))
424 return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
426 break;
429 case OP_NOP1: case OP_NOP4: case OP_NOP5:
430 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
432 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
433 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
435 break;
437 case OP_IF:
438 case OP_NOTIF:
440 // <expression> if [statements] [else [statements]] endif
441 bool fValue = false;
442 if (fExec)
444 if (stack.size() < 1)
445 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
446 valtype& vch = stacktop(-1);
447 if (sigversion == SIGVERSION_WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
448 if (vch.size() > 1)
449 return set_error(serror, SCRIPT_ERR_MINIMALIF);
450 if (vch.size() == 1 && vch[0] != 1)
451 return set_error(serror, SCRIPT_ERR_MINIMALIF);
453 fValue = CastToBool(vch);
454 if (opcode == OP_NOTIF)
455 fValue = !fValue;
456 popstack(stack);
458 vfExec.push_back(fValue);
460 break;
462 case OP_ELSE:
464 if (vfExec.empty())
465 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
466 vfExec.back() = !vfExec.back();
468 break;
470 case OP_ENDIF:
472 if (vfExec.empty())
473 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
474 vfExec.pop_back();
476 break;
478 case OP_VERIFY:
480 // (true -- ) or
481 // (false -- false) and return
482 if (stack.size() < 1)
483 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
484 bool fValue = CastToBool(stacktop(-1));
485 if (fValue)
486 popstack(stack);
487 else
488 return set_error(serror, SCRIPT_ERR_VERIFY);
490 break;
492 case OP_RETURN:
494 return set_error(serror, SCRIPT_ERR_OP_RETURN);
496 break;
500 // Stack ops
502 case OP_TOALTSTACK:
504 if (stack.size() < 1)
505 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
506 altstack.push_back(stacktop(-1));
507 popstack(stack);
509 break;
511 case OP_FROMALTSTACK:
513 if (altstack.size() < 1)
514 return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
515 stack.push_back(altstacktop(-1));
516 popstack(altstack);
518 break;
520 case OP_2DROP:
522 // (x1 x2 -- )
523 if (stack.size() < 2)
524 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
525 popstack(stack);
526 popstack(stack);
528 break;
530 case OP_2DUP:
532 // (x1 x2 -- x1 x2 x1 x2)
533 if (stack.size() < 2)
534 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
535 valtype vch1 = stacktop(-2);
536 valtype vch2 = stacktop(-1);
537 stack.push_back(vch1);
538 stack.push_back(vch2);
540 break;
542 case OP_3DUP:
544 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
545 if (stack.size() < 3)
546 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
547 valtype vch1 = stacktop(-3);
548 valtype vch2 = stacktop(-2);
549 valtype vch3 = stacktop(-1);
550 stack.push_back(vch1);
551 stack.push_back(vch2);
552 stack.push_back(vch3);
554 break;
556 case OP_2OVER:
558 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
559 if (stack.size() < 4)
560 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
561 valtype vch1 = stacktop(-4);
562 valtype vch2 = stacktop(-3);
563 stack.push_back(vch1);
564 stack.push_back(vch2);
566 break;
568 case OP_2ROT:
570 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
571 if (stack.size() < 6)
572 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
573 valtype vch1 = stacktop(-6);
574 valtype vch2 = stacktop(-5);
575 stack.erase(stack.end()-6, stack.end()-4);
576 stack.push_back(vch1);
577 stack.push_back(vch2);
579 break;
581 case OP_2SWAP:
583 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
584 if (stack.size() < 4)
585 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
586 swap(stacktop(-4), stacktop(-2));
587 swap(stacktop(-3), stacktop(-1));
589 break;
591 case OP_IFDUP:
593 // (x - 0 | x x)
594 if (stack.size() < 1)
595 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
596 valtype vch = stacktop(-1);
597 if (CastToBool(vch))
598 stack.push_back(vch);
600 break;
602 case OP_DEPTH:
604 // -- stacksize
605 CScriptNum bn(stack.size());
606 stack.push_back(bn.getvch());
608 break;
610 case OP_DROP:
612 // (x -- )
613 if (stack.size() < 1)
614 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
615 popstack(stack);
617 break;
619 case OP_DUP:
621 // (x -- x x)
622 if (stack.size() < 1)
623 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
624 valtype vch = stacktop(-1);
625 stack.push_back(vch);
627 break;
629 case OP_NIP:
631 // (x1 x2 -- x2)
632 if (stack.size() < 2)
633 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
634 stack.erase(stack.end() - 2);
636 break;
638 case OP_OVER:
640 // (x1 x2 -- x1 x2 x1)
641 if (stack.size() < 2)
642 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
643 valtype vch = stacktop(-2);
644 stack.push_back(vch);
646 break;
648 case OP_PICK:
649 case OP_ROLL:
651 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
652 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
653 if (stack.size() < 2)
654 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
655 int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
656 popstack(stack);
657 if (n < 0 || n >= (int)stack.size())
658 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
659 valtype vch = stacktop(-n-1);
660 if (opcode == OP_ROLL)
661 stack.erase(stack.end()-n-1);
662 stack.push_back(vch);
664 break;
666 case OP_ROT:
668 // (x1 x2 x3 -- x2 x3 x1)
669 // x2 x1 x3 after first swap
670 // x2 x3 x1 after second swap
671 if (stack.size() < 3)
672 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
673 swap(stacktop(-3), stacktop(-2));
674 swap(stacktop(-2), stacktop(-1));
676 break;
678 case OP_SWAP:
680 // (x1 x2 -- x2 x1)
681 if (stack.size() < 2)
682 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
683 swap(stacktop(-2), stacktop(-1));
685 break;
687 case OP_TUCK:
689 // (x1 x2 -- x2 x1 x2)
690 if (stack.size() < 2)
691 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
692 valtype vch = stacktop(-1);
693 stack.insert(stack.end()-2, vch);
695 break;
698 case OP_SIZE:
700 // (in -- in size)
701 if (stack.size() < 1)
702 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
703 CScriptNum bn(stacktop(-1).size());
704 stack.push_back(bn.getvch());
706 break;
710 // Bitwise logic
712 case OP_EQUAL:
713 case OP_EQUALVERIFY:
714 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
716 // (x1 x2 - bool)
717 if (stack.size() < 2)
718 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
719 valtype& vch1 = stacktop(-2);
720 valtype& vch2 = stacktop(-1);
721 bool fEqual = (vch1 == vch2);
722 // OP_NOTEQUAL is disabled because it would be too easy to say
723 // something like n != 1 and have some wiseguy pass in 1 with extra
724 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
725 //if (opcode == OP_NOTEQUAL)
726 // fEqual = !fEqual;
727 popstack(stack);
728 popstack(stack);
729 stack.push_back(fEqual ? vchTrue : vchFalse);
730 if (opcode == OP_EQUALVERIFY)
732 if (fEqual)
733 popstack(stack);
734 else
735 return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
738 break;
742 // Numeric
744 case OP_1ADD:
745 case OP_1SUB:
746 case OP_NEGATE:
747 case OP_ABS:
748 case OP_NOT:
749 case OP_0NOTEQUAL:
751 // (in -- out)
752 if (stack.size() < 1)
753 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
754 CScriptNum bn(stacktop(-1), fRequireMinimal);
755 switch (opcode)
757 case OP_1ADD: bn += bnOne; break;
758 case OP_1SUB: bn -= bnOne; break;
759 case OP_NEGATE: bn = -bn; break;
760 case OP_ABS: if (bn < bnZero) bn = -bn; break;
761 case OP_NOT: bn = (bn == bnZero); break;
762 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
763 default: assert(!"invalid opcode"); break;
765 popstack(stack);
766 stack.push_back(bn.getvch());
768 break;
770 case OP_ADD:
771 case OP_SUB:
772 case OP_BOOLAND:
773 case OP_BOOLOR:
774 case OP_NUMEQUAL:
775 case OP_NUMEQUALVERIFY:
776 case OP_NUMNOTEQUAL:
777 case OP_LESSTHAN:
778 case OP_GREATERTHAN:
779 case OP_LESSTHANOREQUAL:
780 case OP_GREATERTHANOREQUAL:
781 case OP_MIN:
782 case OP_MAX:
784 // (x1 x2 -- out)
785 if (stack.size() < 2)
786 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
787 CScriptNum bn1(stacktop(-2), fRequireMinimal);
788 CScriptNum bn2(stacktop(-1), fRequireMinimal);
789 CScriptNum bn(0);
790 switch (opcode)
792 case OP_ADD:
793 bn = bn1 + bn2;
794 break;
796 case OP_SUB:
797 bn = bn1 - bn2;
798 break;
800 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
801 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
802 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
803 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
804 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
805 case OP_LESSTHAN: bn = (bn1 < bn2); break;
806 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
807 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
808 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
809 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
810 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
811 default: assert(!"invalid opcode"); break;
813 popstack(stack);
814 popstack(stack);
815 stack.push_back(bn.getvch());
817 if (opcode == OP_NUMEQUALVERIFY)
819 if (CastToBool(stacktop(-1)))
820 popstack(stack);
821 else
822 return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
825 break;
827 case OP_WITHIN:
829 // (x min max -- out)
830 if (stack.size() < 3)
831 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
832 CScriptNum bn1(stacktop(-3), fRequireMinimal);
833 CScriptNum bn2(stacktop(-2), fRequireMinimal);
834 CScriptNum bn3(stacktop(-1), fRequireMinimal);
835 bool fValue = (bn2 <= bn1 && bn1 < bn3);
836 popstack(stack);
837 popstack(stack);
838 popstack(stack);
839 stack.push_back(fValue ? vchTrue : vchFalse);
841 break;
845 // Crypto
847 case OP_RIPEMD160:
848 case OP_SHA1:
849 case OP_SHA256:
850 case OP_HASH160:
851 case OP_HASH256:
853 // (in -- hash)
854 if (stack.size() < 1)
855 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
856 valtype& vch = stacktop(-1);
857 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
858 if (opcode == OP_RIPEMD160)
859 CRIPEMD160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
860 else if (opcode == OP_SHA1)
861 CSHA1().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
862 else if (opcode == OP_SHA256)
863 CSHA256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
864 else if (opcode == OP_HASH160)
865 CHash160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
866 else if (opcode == OP_HASH256)
867 CHash256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
868 popstack(stack);
869 stack.push_back(vchHash);
871 break;
873 case OP_CODESEPARATOR:
875 // Hash starts after the code separator
876 pbegincodehash = pc;
878 break;
880 case OP_CHECKSIG:
881 case OP_CHECKSIGVERIFY:
883 // (sig pubkey -- bool)
884 if (stack.size() < 2)
885 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
887 valtype& vchSig = stacktop(-2);
888 valtype& vchPubKey = stacktop(-1);
890 // Subset of script starting at the most recent codeseparator
891 CScript scriptCode(pbegincodehash, pend);
893 // Drop the signature in pre-segwit scripts but not segwit scripts
894 if (sigversion == SIGVERSION_BASE) {
895 scriptCode.FindAndDelete(CScript(vchSig));
898 if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
899 //serror is set
900 return false;
902 bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
904 if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
905 return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
907 popstack(stack);
908 popstack(stack);
909 stack.push_back(fSuccess ? vchTrue : vchFalse);
910 if (opcode == OP_CHECKSIGVERIFY)
912 if (fSuccess)
913 popstack(stack);
914 else
915 return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
918 break;
920 case OP_CHECKMULTISIG:
921 case OP_CHECKMULTISIGVERIFY:
923 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
925 int i = 1;
926 if ((int)stack.size() < i)
927 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
929 int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
930 if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
931 return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
932 nOpCount += nKeysCount;
933 if (nOpCount > MAX_OPS_PER_SCRIPT)
934 return set_error(serror, SCRIPT_ERR_OP_COUNT);
935 int ikey = ++i;
936 // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
937 // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
938 int ikey2 = nKeysCount + 2;
939 i += nKeysCount;
940 if ((int)stack.size() < i)
941 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
943 int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
944 if (nSigsCount < 0 || nSigsCount > nKeysCount)
945 return set_error(serror, SCRIPT_ERR_SIG_COUNT);
946 int isig = ++i;
947 i += nSigsCount;
948 if ((int)stack.size() < i)
949 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
951 // Subset of script starting at the most recent codeseparator
952 CScript scriptCode(pbegincodehash, pend);
954 // Drop the signature in pre-segwit scripts but not segwit scripts
955 for (int k = 0; k < nSigsCount; k++)
957 valtype& vchSig = stacktop(-isig-k);
958 if (sigversion == SIGVERSION_BASE) {
959 scriptCode.FindAndDelete(CScript(vchSig));
963 bool fSuccess = true;
964 while (fSuccess && nSigsCount > 0)
966 valtype& vchSig = stacktop(-isig);
967 valtype& vchPubKey = stacktop(-ikey);
969 // Note how this makes the exact order of pubkey/signature evaluation
970 // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
971 // See the script_(in)valid tests for details.
972 if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
973 // serror is set
974 return false;
977 // Check signature
978 bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
980 if (fOk) {
981 isig++;
982 nSigsCount--;
984 ikey++;
985 nKeysCount--;
987 // If there are more signatures left than keys left,
988 // then too many signatures have failed. Exit early,
989 // without checking any further signatures.
990 if (nSigsCount > nKeysCount)
991 fSuccess = false;
994 // Clean up stack of actual arguments
995 while (i-- > 1) {
996 // If the operation failed, we require that all signatures must be empty vector
997 if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
998 return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
999 if (ikey2 > 0)
1000 ikey2--;
1001 popstack(stack);
1004 // A bug causes CHECKMULTISIG to consume one extra argument
1005 // whose contents were not checked in any way.
1007 // Unfortunately this is a potential source of mutability,
1008 // so optionally verify it is exactly equal to zero prior
1009 // to removing it from the stack.
1010 if (stack.size() < 1)
1011 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1012 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1013 return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1014 popstack(stack);
1016 stack.push_back(fSuccess ? vchTrue : vchFalse);
1018 if (opcode == OP_CHECKMULTISIGVERIFY)
1020 if (fSuccess)
1021 popstack(stack);
1022 else
1023 return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1026 break;
1028 default:
1029 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1032 // Size limits
1033 if (stack.size() + altstack.size() > 1000)
1034 return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1037 catch (...)
1039 return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1042 if (!vfExec.empty())
1043 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1045 return set_success(serror);
1048 namespace {
1051 * Wrapper that serializes like CTransaction, but with the modifications
1052 * required for the signature hash done in-place
1054 class CTransactionSignatureSerializer {
1055 private:
1056 const CTransaction& txTo; //!< reference to the spending transaction (the one being serialized)
1057 const CScript& scriptCode; //!< output script being consumed
1058 const unsigned int nIn; //!< input index of txTo being signed
1059 const bool fAnyoneCanPay; //!< whether the hashtype has the SIGHASH_ANYONECANPAY flag set
1060 const bool fHashSingle; //!< whether the hashtype is SIGHASH_SINGLE
1061 const bool fHashNone; //!< whether the hashtype is SIGHASH_NONE
1063 public:
1064 CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1065 txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1066 fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1067 fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1068 fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1070 /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1071 template<typename S>
1072 void SerializeScriptCode(S &s) const {
1073 CScript::const_iterator it = scriptCode.begin();
1074 CScript::const_iterator itBegin = it;
1075 opcodetype opcode;
1076 unsigned int nCodeSeparators = 0;
1077 while (scriptCode.GetOp(it, opcode)) {
1078 if (opcode == OP_CODESEPARATOR)
1079 nCodeSeparators++;
1081 ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1082 it = itBegin;
1083 while (scriptCode.GetOp(it, opcode)) {
1084 if (opcode == OP_CODESEPARATOR) {
1085 s.write((char*)&itBegin[0], it-itBegin-1);
1086 itBegin = it;
1089 if (itBegin != scriptCode.end())
1090 s.write((char*)&itBegin[0], it-itBegin);
1093 /** Serialize an input of txTo */
1094 template<typename S>
1095 void SerializeInput(S &s, unsigned int nInput) const {
1096 // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1097 if (fAnyoneCanPay)
1098 nInput = nIn;
1099 // Serialize the prevout
1100 ::Serialize(s, txTo.vin[nInput].prevout);
1101 // Serialize the script
1102 if (nInput != nIn)
1103 // Blank out other inputs' signatures
1104 ::Serialize(s, CScriptBase());
1105 else
1106 SerializeScriptCode(s);
1107 // Serialize the nSequence
1108 if (nInput != nIn && (fHashSingle || fHashNone))
1109 // let the others update at will
1110 ::Serialize(s, (int)0);
1111 else
1112 ::Serialize(s, txTo.vin[nInput].nSequence);
1115 /** Serialize an output of txTo */
1116 template<typename S>
1117 void SerializeOutput(S &s, unsigned int nOutput) const {
1118 if (fHashSingle && nOutput != nIn)
1119 // Do not lock-in the txout payee at other indices as txin
1120 ::Serialize(s, CTxOut());
1121 else
1122 ::Serialize(s, txTo.vout[nOutput]);
1125 /** Serialize txTo */
1126 template<typename S>
1127 void Serialize(S &s) const {
1128 // Serialize nVersion
1129 ::Serialize(s, txTo.nVersion);
1130 // Serialize vin
1131 unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1132 ::WriteCompactSize(s, nInputs);
1133 for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1134 SerializeInput(s, nInput);
1135 // Serialize vout
1136 unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1137 ::WriteCompactSize(s, nOutputs);
1138 for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1139 SerializeOutput(s, nOutput);
1140 // Serialize nLockTime
1141 ::Serialize(s, txTo.nLockTime);
1145 uint256 GetPrevoutHash(const CTransaction& txTo) {
1146 CHashWriter ss(SER_GETHASH, 0);
1147 for (unsigned int n = 0; n < txTo.vin.size(); n++) {
1148 ss << txTo.vin[n].prevout;
1150 return ss.GetHash();
1153 uint256 GetSequenceHash(const CTransaction& txTo) {
1154 CHashWriter ss(SER_GETHASH, 0);
1155 for (unsigned int n = 0; n < txTo.vin.size(); n++) {
1156 ss << txTo.vin[n].nSequence;
1158 return ss.GetHash();
1161 uint256 GetOutputsHash(const CTransaction& txTo) {
1162 CHashWriter ss(SER_GETHASH, 0);
1163 for (unsigned int n = 0; n < txTo.vout.size(); n++) {
1164 ss << txTo.vout[n];
1166 return ss.GetHash();
1169 } // anon namespace
1171 PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo)
1173 hashPrevouts = GetPrevoutHash(txTo);
1174 hashSequence = GetSequenceHash(txTo);
1175 hashOutputs = GetOutputsHash(txTo);
1178 uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1180 if (sigversion == SIGVERSION_WITNESS_V0) {
1181 uint256 hashPrevouts;
1182 uint256 hashSequence;
1183 uint256 hashOutputs;
1185 if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1186 hashPrevouts = cache ? cache->hashPrevouts : GetPrevoutHash(txTo);
1189 if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1190 hashSequence = cache ? cache->hashSequence : GetSequenceHash(txTo);
1194 if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1195 hashOutputs = cache ? cache->hashOutputs : GetOutputsHash(txTo);
1196 } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
1197 CHashWriter ss(SER_GETHASH, 0);
1198 ss << txTo.vout[nIn];
1199 hashOutputs = ss.GetHash();
1202 CHashWriter ss(SER_GETHASH, 0);
1203 // Version
1204 ss << txTo.nVersion;
1205 // Input prevouts/nSequence (none/all, depending on flags)
1206 ss << hashPrevouts;
1207 ss << hashSequence;
1208 // The input being signed (replacing the scriptSig with scriptCode + amount)
1209 // The prevout may already be contained in hashPrevout, and the nSequence
1210 // may already be contain in hashSequence.
1211 ss << txTo.vin[nIn].prevout;
1212 ss << static_cast<const CScriptBase&>(scriptCode);
1213 ss << amount;
1214 ss << txTo.vin[nIn].nSequence;
1215 // Outputs (none/one/all, depending on flags)
1216 ss << hashOutputs;
1217 // Locktime
1218 ss << txTo.nLockTime;
1219 // Sighash type
1220 ss << nHashType;
1222 return ss.GetHash();
1225 static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
1226 if (nIn >= txTo.vin.size()) {
1227 // nIn out of range
1228 return one;
1231 // Check for invalid use of SIGHASH_SINGLE
1232 if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1233 if (nIn >= txTo.vout.size()) {
1234 // nOut out of range
1235 return one;
1239 // Wrapper to serialize only the necessary parts of the transaction being signed
1240 CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
1242 // Serialize and hash
1243 CHashWriter ss(SER_GETHASH, 0);
1244 ss << txTmp << nHashType;
1245 return ss.GetHash();
1248 bool TransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1250 return pubkey.Verify(sighash, vchSig);
1253 bool TransactionSignatureChecker::CheckSig(const vector<unsigned char>& vchSigIn, const vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1255 CPubKey pubkey(vchPubKey);
1256 if (!pubkey.IsValid())
1257 return false;
1259 // Hash type is one byte tacked on to the end of the signature
1260 vector<unsigned char> vchSig(vchSigIn);
1261 if (vchSig.empty())
1262 return false;
1263 int nHashType = vchSig.back();
1264 vchSig.pop_back();
1266 uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
1268 if (!VerifySignature(vchSig, pubkey, sighash))
1269 return false;
1271 return true;
1274 bool TransactionSignatureChecker::CheckLockTime(const CScriptNum& nLockTime) const
1276 // There are two kinds of nLockTime: lock-by-blockheight
1277 // and lock-by-blocktime, distinguished by whether
1278 // nLockTime < LOCKTIME_THRESHOLD.
1280 // We want to compare apples to apples, so fail the script
1281 // unless the type of nLockTime being tested is the same as
1282 // the nLockTime in the transaction.
1283 if (!(
1284 (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
1285 (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1287 return false;
1289 // Now that we know we're comparing apples-to-apples, the
1290 // comparison is a simple numeric one.
1291 if (nLockTime > (int64_t)txTo->nLockTime)
1292 return false;
1294 // Finally the nLockTime feature can be disabled and thus
1295 // CHECKLOCKTIMEVERIFY bypassed if every txin has been
1296 // finalized by setting nSequence to maxint. The
1297 // transaction would be allowed into the blockchain, making
1298 // the opcode ineffective.
1300 // Testing if this vin is not final is sufficient to
1301 // prevent this condition. Alternatively we could test all
1302 // inputs, but testing just this input minimizes the data
1303 // required to prove correct CHECKLOCKTIMEVERIFY execution.
1304 if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1305 return false;
1307 return true;
1310 bool TransactionSignatureChecker::CheckSequence(const CScriptNum& nSequence) const
1312 // Relative lock times are supported by comparing the passed
1313 // in operand to the sequence number of the input.
1314 const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1316 // Fail if the transaction's version number is not set high
1317 // enough to trigger BIP 68 rules.
1318 if (static_cast<uint32_t>(txTo->nVersion) < 2)
1319 return false;
1321 // Sequence numbers with their most significant bit set are not
1322 // consensus constrained. Testing that the transaction's sequence
1323 // number do not have this bit set prevents using this property
1324 // to get around a CHECKSEQUENCEVERIFY check.
1325 if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1326 return false;
1328 // Mask off any bits that do not have consensus-enforced meaning
1329 // before doing the integer comparisons
1330 const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1331 const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1332 const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1334 // There are two kinds of nSequence: lock-by-blockheight
1335 // and lock-by-blocktime, distinguished by whether
1336 // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1338 // We want to compare apples to apples, so fail the script
1339 // unless the type of nSequenceMasked being tested is the same as
1340 // the nSequenceMasked in the transaction.
1341 if (!(
1342 (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1343 (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1344 )) {
1345 return false;
1348 // Now that we know we're comparing apples-to-apples, the
1349 // comparison is a simple numeric one.
1350 if (nSequenceMasked > txToSequenceMasked)
1351 return false;
1353 return true;
1356 static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1358 vector<vector<unsigned char> > stack;
1359 CScript scriptPubKey;
1361 if (witversion == 0) {
1362 if (program.size() == 32) {
1363 // Version 0 segregated witness program: SHA256(CScript) inside the program, CScript + inputs in witness
1364 if (witness.stack.size() == 0) {
1365 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1367 scriptPubKey = CScript(witness.stack.back().begin(), witness.stack.back().end());
1368 stack = std::vector<std::vector<unsigned char> >(witness.stack.begin(), witness.stack.end() - 1);
1369 uint256 hashScriptPubKey;
1370 CSHA256().Write(&scriptPubKey[0], scriptPubKey.size()).Finalize(hashScriptPubKey.begin());
1371 if (memcmp(hashScriptPubKey.begin(), &program[0], 32)) {
1372 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1374 } else if (program.size() == 20) {
1375 // Special case for pay-to-pubkeyhash; signature + pubkey in witness
1376 if (witness.stack.size() != 2) {
1377 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1379 scriptPubKey << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
1380 stack = witness.stack;
1381 } else {
1382 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
1384 } else if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
1385 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
1386 } else {
1387 // Higher version witness scripts return true for future softfork compatibility
1388 return set_success(serror);
1391 // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
1392 for (unsigned int i = 0; i < stack.size(); i++) {
1393 if (stack.at(i).size() > MAX_SCRIPT_ELEMENT_SIZE)
1394 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
1397 if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_WITNESS_V0, serror)) {
1398 return false;
1401 // Scripts inside witness implicitly require cleanstack behaviour
1402 if (stack.size() != 1)
1403 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1404 if (!CastToBool(stack.back()))
1405 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1406 return true;
1409 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1411 static const CScriptWitness emptyWitness;
1412 if (witness == NULL) {
1413 witness = &emptyWitness;
1415 bool hadWitness = false;
1417 set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1419 if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1420 return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1423 vector<vector<unsigned char> > stack, stackCopy;
1424 if (!EvalScript(stack, scriptSig, flags, checker, SIGVERSION_BASE, serror))
1425 // serror is set
1426 return false;
1427 if (flags & SCRIPT_VERIFY_P2SH)
1428 stackCopy = stack;
1429 if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_BASE, serror))
1430 // serror is set
1431 return false;
1432 if (stack.empty())
1433 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1434 if (CastToBool(stack.back()) == false)
1435 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1437 // Bare witness programs
1438 int witnessversion;
1439 std::vector<unsigned char> witnessprogram;
1440 if (flags & SCRIPT_VERIFY_WITNESS) {
1441 if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1442 hadWitness = true;
1443 if (scriptSig.size() != 0) {
1444 // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
1445 return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
1447 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
1448 return false;
1450 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1451 // for witness programs.
1452 stack.resize(1);
1456 // Additional validation for spend-to-script-hash transactions:
1457 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1459 // scriptSig must be literals-only or validation fails
1460 if (!scriptSig.IsPushOnly())
1461 return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1463 // Restore stack.
1464 swap(stack, stackCopy);
1466 // stack cannot be empty here, because if it was the
1467 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1468 // an empty stack and the EvalScript above would return false.
1469 assert(!stack.empty());
1471 const valtype& pubKeySerialized = stack.back();
1472 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1473 popstack(stack);
1475 if (!EvalScript(stack, pubKey2, flags, checker, SIGVERSION_BASE, serror))
1476 // serror is set
1477 return false;
1478 if (stack.empty())
1479 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1480 if (!CastToBool(stack.back()))
1481 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1483 // P2SH witness program
1484 if (flags & SCRIPT_VERIFY_WITNESS) {
1485 if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
1486 hadWitness = true;
1487 if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
1488 // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
1489 // reintroduce malleability.
1490 return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
1492 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
1493 return false;
1495 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1496 // for witness programs.
1497 stack.resize(1);
1502 // The CLEANSTACK check is only performed after potential P2SH evaluation,
1503 // as the non-P2SH evaluation of a P2SH script will obviously not result in
1504 // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
1505 if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
1506 // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
1507 // would be possible, which is not a softfork (and P2SH should be one).
1508 assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1509 assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
1510 if (stack.size() != 1) {
1511 return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1515 if (flags & SCRIPT_VERIFY_WITNESS) {
1516 // We can't check for correct unexpected witness data if P2SH was off, so require
1517 // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
1518 // possible, which is not a softfork.
1519 assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1520 if (!hadWitness && !witness->IsNull()) {
1521 return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
1525 return set_success(serror);
1528 size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness, int flags)
1530 if (witversion == 0) {
1531 if (witprogram.size() == 20)
1532 return 1;
1534 if (witprogram.size() == 32 && witness.stack.size() > 0) {
1535 CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
1536 return subscript.GetSigOpCount(true);
1540 // Future flags may be implemented here.
1541 return 0;
1544 size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags)
1546 static const CScriptWitness witnessEmpty;
1548 if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
1549 return 0;
1551 assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1553 int witnessversion;
1554 std::vector<unsigned char> witnessprogram;
1555 if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1556 return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty, flags);
1559 if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
1560 CScript::const_iterator pc = scriptSig.begin();
1561 vector<unsigned char> data;
1562 while (pc < scriptSig.end()) {
1563 opcodetype opcode;
1564 scriptSig.GetOp(pc, opcode, data);
1566 CScript subscript(data.begin(), data.end());
1567 if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
1568 return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty, flags);
1572 return 0;