Merge #10574: Remove includes in .cpp files for things the corresponding .h file...
[bitcoinplatinum.git] / src / script / interpreter.cpp
blob3c3f92fe46b36f78b5adfb2689615f117675b6a3
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 <script/interpreter.h>
8 #include <crypto/ripemd160.h>
9 #include <crypto/sha1.h>
10 #include <crypto/sha256.h>
11 #include <pubkey.h>
12 #include <script/script.h>
13 #include <uint256.h>
15 typedef std::vector<unsigned char> valtype;
17 namespace {
19 inline bool set_success(ScriptError* ret)
21 if (ret)
22 *ret = SCRIPT_ERR_OK;
23 return true;
26 inline bool set_error(ScriptError* ret, const ScriptError serror)
28 if (ret)
29 *ret = serror;
30 return false;
33 } // namespace
35 bool CastToBool(const valtype& vch)
37 for (unsigned int i = 0; i < vch.size(); i++)
39 if (vch[i] != 0)
41 // Can be negative zero
42 if (i == vch.size()-1 && vch[i] == 0x80)
43 return false;
44 return true;
47 return false;
50 /**
51 * Script is a stack machine (like Forth) that evaluates a predicate
52 * returning a bool indicating valid or not. There are no loops.
54 #define stacktop(i) (stack.at(stack.size()+(i)))
55 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
56 static inline void popstack(std::vector<valtype>& stack)
58 if (stack.empty())
59 throw std::runtime_error("popstack(): stack empty");
60 stack.pop_back();
63 bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
64 if (vchPubKey.size() < 33) {
65 // Non-canonical public key: too short
66 return false;
68 if (vchPubKey[0] == 0x04) {
69 if (vchPubKey.size() != 65) {
70 // Non-canonical public key: invalid length for uncompressed key
71 return false;
73 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
74 if (vchPubKey.size() != 33) {
75 // Non-canonical public key: invalid length for compressed key
76 return false;
78 } else {
79 // Non-canonical public key: neither compressed nor uncompressed
80 return false;
82 return true;
85 bool static IsCompressedPubKey(const valtype &vchPubKey) {
86 if (vchPubKey.size() != 33) {
87 // Non-canonical public key: invalid length for compressed key
88 return false;
90 if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
91 // Non-canonical public key: invalid prefix for compressed key
92 return false;
94 return true;
97 /**
98 * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
99 * Where R and S are not negative (their first byte has its highest bit not set), and not
100 * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
101 * in which case a single 0 byte is necessary and even required).
103 * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
105 * This function is consensus-critical since BIP66.
107 bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
108 // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
109 // * total-length: 1-byte length descriptor of everything that follows,
110 // excluding the sighash byte.
111 // * R-length: 1-byte length descriptor of the R value that follows.
112 // * R: arbitrary-length big-endian encoded R value. It must use the shortest
113 // possible encoding for a positive integers (which means no null bytes at
114 // the start, except a single one when the next byte has its highest bit set).
115 // * S-length: 1-byte length descriptor of the S value that follows.
116 // * S: arbitrary-length big-endian encoded S value. The same rules apply.
117 // * sighash: 1-byte value indicating what data is hashed (not part of the DER
118 // signature)
120 // Minimum and maximum size constraints.
121 if (sig.size() < 9) return false;
122 if (sig.size() > 73) return false;
124 // A signature is of type 0x30 (compound).
125 if (sig[0] != 0x30) return false;
127 // Make sure the length covers the entire signature.
128 if (sig[1] != sig.size() - 3) return false;
130 // Extract the length of the R element.
131 unsigned int lenR = sig[3];
133 // Make sure the length of the S element is still inside the signature.
134 if (5 + lenR >= sig.size()) return false;
136 // Extract the length of the S element.
137 unsigned int lenS = sig[5 + lenR];
139 // Verify that the length of the signature matches the sum of the length
140 // of the elements.
141 if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
143 // Check whether the R element is an integer.
144 if (sig[2] != 0x02) return false;
146 // Zero-length integers are not allowed for R.
147 if (lenR == 0) return false;
149 // Negative numbers are not allowed for R.
150 if (sig[4] & 0x80) return false;
152 // Null bytes at the start of R are not allowed, unless R would
153 // otherwise be interpreted as a negative number.
154 if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
156 // Check whether the S element is an integer.
157 if (sig[lenR + 4] != 0x02) return false;
159 // Zero-length integers are not allowed for S.
160 if (lenS == 0) return false;
162 // Negative numbers are not allowed for S.
163 if (sig[lenR + 6] & 0x80) return false;
165 // Null bytes at the start of S are not allowed, unless S would otherwise be
166 // interpreted as a negative number.
167 if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
169 return true;
172 bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
173 if (!IsValidSignatureEncoding(vchSig)) {
174 return set_error(serror, SCRIPT_ERR_SIG_DER);
176 std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
177 if (!CPubKey::CheckLowS(vchSigCopy)) {
178 return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
180 return true;
183 bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
184 if (vchSig.size() == 0) {
185 return false;
187 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
188 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
189 return false;
191 return true;
194 bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
195 // Empty signature. Not strictly DER encoded, but allowed to provide a
196 // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
197 if (vchSig.size() == 0) {
198 return true;
200 if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
201 return set_error(serror, SCRIPT_ERR_SIG_DER);
202 } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
203 // serror is set
204 return false;
205 } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
206 return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
208 return true;
211 bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
212 if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
213 return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
215 // Only compressed keys are accepted in segwit
216 if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SIGVERSION_WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
217 return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
219 return true;
222 bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
223 if (data.size() == 0) {
224 // Could have used OP_0.
225 return opcode == OP_0;
226 } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
227 // Could have used OP_1 .. OP_16.
228 return opcode == OP_1 + (data[0] - 1);
229 } else if (data.size() == 1 && data[0] == 0x81) {
230 // Could have used OP_1NEGATE.
231 return opcode == OP_1NEGATE;
232 } else if (data.size() <= 75) {
233 // Could have used a direct push (opcode indicating number of bytes pushed + those bytes).
234 return opcode == data.size();
235 } else if (data.size() <= 255) {
236 // Could have used OP_PUSHDATA.
237 return opcode == OP_PUSHDATA1;
238 } else if (data.size() <= 65535) {
239 // Could have used OP_PUSHDATA2.
240 return opcode == OP_PUSHDATA2;
242 return true;
245 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
247 static const CScriptNum bnZero(0);
248 static const CScriptNum bnOne(1);
249 // static const CScriptNum bnFalse(0);
250 // static const CScriptNum bnTrue(1);
251 static const valtype vchFalse(0);
252 // static const valtype vchZero(0);
253 static const valtype vchTrue(1, 1);
255 CScript::const_iterator pc = script.begin();
256 CScript::const_iterator pend = script.end();
257 CScript::const_iterator pbegincodehash = script.begin();
258 opcodetype opcode;
259 valtype vchPushValue;
260 std::vector<bool> vfExec;
261 std::vector<valtype> altstack;
262 set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
263 if (script.size() > MAX_SCRIPT_SIZE)
264 return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
265 int nOpCount = 0;
266 bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
270 while (pc < pend)
272 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
275 // Read instruction
277 if (!script.GetOp(pc, opcode, vchPushValue))
278 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
279 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
280 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
282 // Note how OP_RESERVED does not count towards the opcode limit.
283 if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
284 return set_error(serror, SCRIPT_ERR_OP_COUNT);
286 if (opcode == OP_CAT ||
287 opcode == OP_SUBSTR ||
288 opcode == OP_LEFT ||
289 opcode == OP_RIGHT ||
290 opcode == OP_INVERT ||
291 opcode == OP_AND ||
292 opcode == OP_OR ||
293 opcode == OP_XOR ||
294 opcode == OP_2MUL ||
295 opcode == OP_2DIV ||
296 opcode == OP_MUL ||
297 opcode == OP_DIV ||
298 opcode == OP_MOD ||
299 opcode == OP_LSHIFT ||
300 opcode == OP_RSHIFT)
301 return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes.
303 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
304 if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
305 return set_error(serror, SCRIPT_ERR_MINIMALDATA);
307 stack.push_back(vchPushValue);
308 } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
309 switch (opcode)
312 // Push value
314 case OP_1NEGATE:
315 case OP_1:
316 case OP_2:
317 case OP_3:
318 case OP_4:
319 case OP_5:
320 case OP_6:
321 case OP_7:
322 case OP_8:
323 case OP_9:
324 case OP_10:
325 case OP_11:
326 case OP_12:
327 case OP_13:
328 case OP_14:
329 case OP_15:
330 case OP_16:
332 // ( -- value)
333 CScriptNum bn((int)opcode - (int)(OP_1 - 1));
334 stack.push_back(bn.getvch());
335 // The result of these opcodes should always be the minimal way to push the data
336 // they push, so no need for a CheckMinimalPush here.
338 break;
342 // Control
344 case OP_NOP:
345 break;
347 case OP_CHECKLOCKTIMEVERIFY:
349 if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
350 // not enabled; treat as a NOP2
351 break;
354 if (stack.size() < 1)
355 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
357 // Note that elsewhere numeric opcodes are limited to
358 // operands in the range -2**31+1 to 2**31-1, however it is
359 // legal for opcodes to produce results exceeding that
360 // range. This limitation is implemented by CScriptNum's
361 // default 4-byte limit.
363 // If we kept to that limit we'd have a year 2038 problem,
364 // even though the nLockTime field in transactions
365 // themselves is uint32 which only becomes meaningless
366 // after the year 2106.
368 // Thus as a special case we tell CScriptNum to accept up
369 // to 5-byte bignums, which are good until 2**39-1, well
370 // beyond the 2**32-1 limit of the nLockTime field itself.
371 const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
373 // In the rare event that the argument may be < 0 due to
374 // some arithmetic being done first, you can always use
375 // 0 MAX CHECKLOCKTIMEVERIFY.
376 if (nLockTime < 0)
377 return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
379 // Actually compare the specified lock time with the transaction.
380 if (!checker.CheckLockTime(nLockTime))
381 return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
383 break;
386 case OP_CHECKSEQUENCEVERIFY:
388 if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
389 // not enabled; treat as a NOP3
390 break;
393 if (stack.size() < 1)
394 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
396 // nSequence, like nLockTime, is a 32-bit unsigned integer
397 // field. See the comment in CHECKLOCKTIMEVERIFY regarding
398 // 5-byte numeric operands.
399 const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
401 // In the rare event that the argument may be < 0 due to
402 // some arithmetic being done first, you can always use
403 // 0 MAX CHECKSEQUENCEVERIFY.
404 if (nSequence < 0)
405 return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
407 // To provide for future soft-fork extensibility, if the
408 // operand has the disabled lock-time flag set,
409 // CHECKSEQUENCEVERIFY behaves as a NOP.
410 if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
411 break;
413 // Compare the specified sequence number with the input.
414 if (!checker.CheckSequence(nSequence))
415 return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
417 break;
420 case OP_NOP1: case OP_NOP4: case OP_NOP5:
421 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
423 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
424 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
426 break;
428 case OP_IF:
429 case OP_NOTIF:
431 // <expression> if [statements] [else [statements]] endif
432 bool fValue = false;
433 if (fExec)
435 if (stack.size() < 1)
436 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
437 valtype& vch = stacktop(-1);
438 if (sigversion == SIGVERSION_WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
439 if (vch.size() > 1)
440 return set_error(serror, SCRIPT_ERR_MINIMALIF);
441 if (vch.size() == 1 && vch[0] != 1)
442 return set_error(serror, SCRIPT_ERR_MINIMALIF);
444 fValue = CastToBool(vch);
445 if (opcode == OP_NOTIF)
446 fValue = !fValue;
447 popstack(stack);
449 vfExec.push_back(fValue);
451 break;
453 case OP_ELSE:
455 if (vfExec.empty())
456 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
457 vfExec.back() = !vfExec.back();
459 break;
461 case OP_ENDIF:
463 if (vfExec.empty())
464 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
465 vfExec.pop_back();
467 break;
469 case OP_VERIFY:
471 // (true -- ) or
472 // (false -- false) and return
473 if (stack.size() < 1)
474 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
475 bool fValue = CastToBool(stacktop(-1));
476 if (fValue)
477 popstack(stack);
478 else
479 return set_error(serror, SCRIPT_ERR_VERIFY);
481 break;
483 case OP_RETURN:
485 return set_error(serror, SCRIPT_ERR_OP_RETURN);
487 break;
491 // Stack ops
493 case OP_TOALTSTACK:
495 if (stack.size() < 1)
496 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
497 altstack.push_back(stacktop(-1));
498 popstack(stack);
500 break;
502 case OP_FROMALTSTACK:
504 if (altstack.size() < 1)
505 return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
506 stack.push_back(altstacktop(-1));
507 popstack(altstack);
509 break;
511 case OP_2DROP:
513 // (x1 x2 -- )
514 if (stack.size() < 2)
515 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
516 popstack(stack);
517 popstack(stack);
519 break;
521 case OP_2DUP:
523 // (x1 x2 -- x1 x2 x1 x2)
524 if (stack.size() < 2)
525 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
526 valtype vch1 = stacktop(-2);
527 valtype vch2 = stacktop(-1);
528 stack.push_back(vch1);
529 stack.push_back(vch2);
531 break;
533 case OP_3DUP:
535 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
536 if (stack.size() < 3)
537 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
538 valtype vch1 = stacktop(-3);
539 valtype vch2 = stacktop(-2);
540 valtype vch3 = stacktop(-1);
541 stack.push_back(vch1);
542 stack.push_back(vch2);
543 stack.push_back(vch3);
545 break;
547 case OP_2OVER:
549 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
550 if (stack.size() < 4)
551 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
552 valtype vch1 = stacktop(-4);
553 valtype vch2 = stacktop(-3);
554 stack.push_back(vch1);
555 stack.push_back(vch2);
557 break;
559 case OP_2ROT:
561 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
562 if (stack.size() < 6)
563 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
564 valtype vch1 = stacktop(-6);
565 valtype vch2 = stacktop(-5);
566 stack.erase(stack.end()-6, stack.end()-4);
567 stack.push_back(vch1);
568 stack.push_back(vch2);
570 break;
572 case OP_2SWAP:
574 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
575 if (stack.size() < 4)
576 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
577 swap(stacktop(-4), stacktop(-2));
578 swap(stacktop(-3), stacktop(-1));
580 break;
582 case OP_IFDUP:
584 // (x - 0 | x x)
585 if (stack.size() < 1)
586 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
587 valtype vch = stacktop(-1);
588 if (CastToBool(vch))
589 stack.push_back(vch);
591 break;
593 case OP_DEPTH:
595 // -- stacksize
596 CScriptNum bn(stack.size());
597 stack.push_back(bn.getvch());
599 break;
601 case OP_DROP:
603 // (x -- )
604 if (stack.size() < 1)
605 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
606 popstack(stack);
608 break;
610 case OP_DUP:
612 // (x -- x x)
613 if (stack.size() < 1)
614 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
615 valtype vch = stacktop(-1);
616 stack.push_back(vch);
618 break;
620 case OP_NIP:
622 // (x1 x2 -- x2)
623 if (stack.size() < 2)
624 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
625 stack.erase(stack.end() - 2);
627 break;
629 case OP_OVER:
631 // (x1 x2 -- x1 x2 x1)
632 if (stack.size() < 2)
633 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
634 valtype vch = stacktop(-2);
635 stack.push_back(vch);
637 break;
639 case OP_PICK:
640 case OP_ROLL:
642 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
643 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
644 if (stack.size() < 2)
645 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
646 int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
647 popstack(stack);
648 if (n < 0 || n >= (int)stack.size())
649 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
650 valtype vch = stacktop(-n-1);
651 if (opcode == OP_ROLL)
652 stack.erase(stack.end()-n-1);
653 stack.push_back(vch);
655 break;
657 case OP_ROT:
659 // (x1 x2 x3 -- x2 x3 x1)
660 // x2 x1 x3 after first swap
661 // x2 x3 x1 after second swap
662 if (stack.size() < 3)
663 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
664 swap(stacktop(-3), stacktop(-2));
665 swap(stacktop(-2), stacktop(-1));
667 break;
669 case OP_SWAP:
671 // (x1 x2 -- x2 x1)
672 if (stack.size() < 2)
673 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
674 swap(stacktop(-2), stacktop(-1));
676 break;
678 case OP_TUCK:
680 // (x1 x2 -- x2 x1 x2)
681 if (stack.size() < 2)
682 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
683 valtype vch = stacktop(-1);
684 stack.insert(stack.end()-2, vch);
686 break;
689 case OP_SIZE:
691 // (in -- in size)
692 if (stack.size() < 1)
693 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
694 CScriptNum bn(stacktop(-1).size());
695 stack.push_back(bn.getvch());
697 break;
701 // Bitwise logic
703 case OP_EQUAL:
704 case OP_EQUALVERIFY:
705 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
707 // (x1 x2 - bool)
708 if (stack.size() < 2)
709 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
710 valtype& vch1 = stacktop(-2);
711 valtype& vch2 = stacktop(-1);
712 bool fEqual = (vch1 == vch2);
713 // OP_NOTEQUAL is disabled because it would be too easy to say
714 // something like n != 1 and have some wiseguy pass in 1 with extra
715 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
716 //if (opcode == OP_NOTEQUAL)
717 // fEqual = !fEqual;
718 popstack(stack);
719 popstack(stack);
720 stack.push_back(fEqual ? vchTrue : vchFalse);
721 if (opcode == OP_EQUALVERIFY)
723 if (fEqual)
724 popstack(stack);
725 else
726 return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
729 break;
733 // Numeric
735 case OP_1ADD:
736 case OP_1SUB:
737 case OP_NEGATE:
738 case OP_ABS:
739 case OP_NOT:
740 case OP_0NOTEQUAL:
742 // (in -- out)
743 if (stack.size() < 1)
744 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
745 CScriptNum bn(stacktop(-1), fRequireMinimal);
746 switch (opcode)
748 case OP_1ADD: bn += bnOne; break;
749 case OP_1SUB: bn -= bnOne; break;
750 case OP_NEGATE: bn = -bn; break;
751 case OP_ABS: if (bn < bnZero) bn = -bn; break;
752 case OP_NOT: bn = (bn == bnZero); break;
753 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
754 default: assert(!"invalid opcode"); break;
756 popstack(stack);
757 stack.push_back(bn.getvch());
759 break;
761 case OP_ADD:
762 case OP_SUB:
763 case OP_BOOLAND:
764 case OP_BOOLOR:
765 case OP_NUMEQUAL:
766 case OP_NUMEQUALVERIFY:
767 case OP_NUMNOTEQUAL:
768 case OP_LESSTHAN:
769 case OP_GREATERTHAN:
770 case OP_LESSTHANOREQUAL:
771 case OP_GREATERTHANOREQUAL:
772 case OP_MIN:
773 case OP_MAX:
775 // (x1 x2 -- out)
776 if (stack.size() < 2)
777 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
778 CScriptNum bn1(stacktop(-2), fRequireMinimal);
779 CScriptNum bn2(stacktop(-1), fRequireMinimal);
780 CScriptNum bn(0);
781 switch (opcode)
783 case OP_ADD:
784 bn = bn1 + bn2;
785 break;
787 case OP_SUB:
788 bn = bn1 - bn2;
789 break;
791 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
792 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
793 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
794 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
795 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
796 case OP_LESSTHAN: bn = (bn1 < bn2); break;
797 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
798 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
799 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
800 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
801 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
802 default: assert(!"invalid opcode"); break;
804 popstack(stack);
805 popstack(stack);
806 stack.push_back(bn.getvch());
808 if (opcode == OP_NUMEQUALVERIFY)
810 if (CastToBool(stacktop(-1)))
811 popstack(stack);
812 else
813 return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
816 break;
818 case OP_WITHIN:
820 // (x min max -- out)
821 if (stack.size() < 3)
822 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
823 CScriptNum bn1(stacktop(-3), fRequireMinimal);
824 CScriptNum bn2(stacktop(-2), fRequireMinimal);
825 CScriptNum bn3(stacktop(-1), fRequireMinimal);
826 bool fValue = (bn2 <= bn1 && bn1 < bn3);
827 popstack(stack);
828 popstack(stack);
829 popstack(stack);
830 stack.push_back(fValue ? vchTrue : vchFalse);
832 break;
836 // Crypto
838 case OP_RIPEMD160:
839 case OP_SHA1:
840 case OP_SHA256:
841 case OP_HASH160:
842 case OP_HASH256:
844 // (in -- hash)
845 if (stack.size() < 1)
846 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
847 valtype& vch = stacktop(-1);
848 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
849 if (opcode == OP_RIPEMD160)
850 CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
851 else if (opcode == OP_SHA1)
852 CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
853 else if (opcode == OP_SHA256)
854 CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
855 else if (opcode == OP_HASH160)
856 CHash160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
857 else if (opcode == OP_HASH256)
858 CHash256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
859 popstack(stack);
860 stack.push_back(vchHash);
862 break;
864 case OP_CODESEPARATOR:
866 // Hash starts after the code separator
867 pbegincodehash = pc;
869 break;
871 case OP_CHECKSIG:
872 case OP_CHECKSIGVERIFY:
874 // (sig pubkey -- bool)
875 if (stack.size() < 2)
876 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
878 valtype& vchSig = stacktop(-2);
879 valtype& vchPubKey = stacktop(-1);
881 // Subset of script starting at the most recent codeseparator
882 CScript scriptCode(pbegincodehash, pend);
884 // Drop the signature in pre-segwit scripts but not segwit scripts
885 if (sigversion == SIGVERSION_BASE) {
886 scriptCode.FindAndDelete(CScript(vchSig));
889 if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
890 //serror is set
891 return false;
893 bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
895 if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
896 return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
898 popstack(stack);
899 popstack(stack);
900 stack.push_back(fSuccess ? vchTrue : vchFalse);
901 if (opcode == OP_CHECKSIGVERIFY)
903 if (fSuccess)
904 popstack(stack);
905 else
906 return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
909 break;
911 case OP_CHECKMULTISIG:
912 case OP_CHECKMULTISIGVERIFY:
914 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
916 int i = 1;
917 if ((int)stack.size() < i)
918 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
920 int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
921 if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
922 return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
923 nOpCount += nKeysCount;
924 if (nOpCount > MAX_OPS_PER_SCRIPT)
925 return set_error(serror, SCRIPT_ERR_OP_COUNT);
926 int ikey = ++i;
927 // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
928 // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
929 int ikey2 = nKeysCount + 2;
930 i += nKeysCount;
931 if ((int)stack.size() < i)
932 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
934 int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
935 if (nSigsCount < 0 || nSigsCount > nKeysCount)
936 return set_error(serror, SCRIPT_ERR_SIG_COUNT);
937 int isig = ++i;
938 i += nSigsCount;
939 if ((int)stack.size() < i)
940 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
942 // Subset of script starting at the most recent codeseparator
943 CScript scriptCode(pbegincodehash, pend);
945 // Drop the signature in pre-segwit scripts but not segwit scripts
946 for (int k = 0; k < nSigsCount; k++)
948 valtype& vchSig = stacktop(-isig-k);
949 if (sigversion == SIGVERSION_BASE) {
950 scriptCode.FindAndDelete(CScript(vchSig));
954 bool fSuccess = true;
955 while (fSuccess && nSigsCount > 0)
957 valtype& vchSig = stacktop(-isig);
958 valtype& vchPubKey = stacktop(-ikey);
960 // Note how this makes the exact order of pubkey/signature evaluation
961 // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
962 // See the script_(in)valid tests for details.
963 if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
964 // serror is set
965 return false;
968 // Check signature
969 bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
971 if (fOk) {
972 isig++;
973 nSigsCount--;
975 ikey++;
976 nKeysCount--;
978 // If there are more signatures left than keys left,
979 // then too many signatures have failed. Exit early,
980 // without checking any further signatures.
981 if (nSigsCount > nKeysCount)
982 fSuccess = false;
985 // Clean up stack of actual arguments
986 while (i-- > 1) {
987 // If the operation failed, we require that all signatures must be empty vector
988 if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
989 return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
990 if (ikey2 > 0)
991 ikey2--;
992 popstack(stack);
995 // A bug causes CHECKMULTISIG to consume one extra argument
996 // whose contents were not checked in any way.
998 // Unfortunately this is a potential source of mutability,
999 // so optionally verify it is exactly equal to zero prior
1000 // to removing it from the stack.
1001 if (stack.size() < 1)
1002 return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1003 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1004 return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1005 popstack(stack);
1007 stack.push_back(fSuccess ? vchTrue : vchFalse);
1009 if (opcode == OP_CHECKMULTISIGVERIFY)
1011 if (fSuccess)
1012 popstack(stack);
1013 else
1014 return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1017 break;
1019 default:
1020 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1023 // Size limits
1024 if (stack.size() + altstack.size() > MAX_STACK_SIZE)
1025 return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1028 catch (...)
1030 return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1033 if (!vfExec.empty())
1034 return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1036 return set_success(serror);
1039 namespace {
1042 * Wrapper that serializes like CTransaction, but with the modifications
1043 * required for the signature hash done in-place
1045 class CTransactionSignatureSerializer {
1046 private:
1047 const CTransaction& txTo; //!< reference to the spending transaction (the one being serialized)
1048 const CScript& scriptCode; //!< output script being consumed
1049 const unsigned int nIn; //!< input index of txTo being signed
1050 const bool fAnyoneCanPay; //!< whether the hashtype has the SIGHASH_ANYONECANPAY flag set
1051 const bool fHashSingle; //!< whether the hashtype is SIGHASH_SINGLE
1052 const bool fHashNone; //!< whether the hashtype is SIGHASH_NONE
1054 public:
1055 CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1056 txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1057 fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1058 fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1059 fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1061 /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1062 template<typename S>
1063 void SerializeScriptCode(S &s) const {
1064 CScript::const_iterator it = scriptCode.begin();
1065 CScript::const_iterator itBegin = it;
1066 opcodetype opcode;
1067 unsigned int nCodeSeparators = 0;
1068 while (scriptCode.GetOp(it, opcode)) {
1069 if (opcode == OP_CODESEPARATOR)
1070 nCodeSeparators++;
1072 ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1073 it = itBegin;
1074 while (scriptCode.GetOp(it, opcode)) {
1075 if (opcode == OP_CODESEPARATOR) {
1076 s.write((char*)&itBegin[0], it-itBegin-1);
1077 itBegin = it;
1080 if (itBegin != scriptCode.end())
1081 s.write((char*)&itBegin[0], it-itBegin);
1084 /** Serialize an input of txTo */
1085 template<typename S>
1086 void SerializeInput(S &s, unsigned int nInput) const {
1087 // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1088 if (fAnyoneCanPay)
1089 nInput = nIn;
1090 // Serialize the prevout
1091 ::Serialize(s, txTo.vin[nInput].prevout);
1092 // Serialize the script
1093 if (nInput != nIn)
1094 // Blank out other inputs' signatures
1095 ::Serialize(s, CScript());
1096 else
1097 SerializeScriptCode(s);
1098 // Serialize the nSequence
1099 if (nInput != nIn && (fHashSingle || fHashNone))
1100 // let the others update at will
1101 ::Serialize(s, (int)0);
1102 else
1103 ::Serialize(s, txTo.vin[nInput].nSequence);
1106 /** Serialize an output of txTo */
1107 template<typename S>
1108 void SerializeOutput(S &s, unsigned int nOutput) const {
1109 if (fHashSingle && nOutput != nIn)
1110 // Do not lock-in the txout payee at other indices as txin
1111 ::Serialize(s, CTxOut());
1112 else
1113 ::Serialize(s, txTo.vout[nOutput]);
1116 /** Serialize txTo */
1117 template<typename S>
1118 void Serialize(S &s) const {
1119 // Serialize nVersion
1120 ::Serialize(s, txTo.nVersion);
1121 // Serialize vin
1122 unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1123 ::WriteCompactSize(s, nInputs);
1124 for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1125 SerializeInput(s, nInput);
1126 // Serialize vout
1127 unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1128 ::WriteCompactSize(s, nOutputs);
1129 for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1130 SerializeOutput(s, nOutput);
1131 // Serialize nLockTime
1132 ::Serialize(s, txTo.nLockTime);
1136 uint256 GetPrevoutHash(const CTransaction& txTo) {
1137 CHashWriter ss(SER_GETHASH, 0);
1138 for (const auto& txin : txTo.vin) {
1139 ss << txin.prevout;
1141 return ss.GetHash();
1144 uint256 GetSequenceHash(const CTransaction& txTo) {
1145 CHashWriter ss(SER_GETHASH, 0);
1146 for (const auto& txin : txTo.vin) {
1147 ss << txin.nSequence;
1149 return ss.GetHash();
1152 uint256 GetOutputsHash(const CTransaction& txTo) {
1153 CHashWriter ss(SER_GETHASH, 0);
1154 for (const auto& txout : txTo.vout) {
1155 ss << txout;
1157 return ss.GetHash();
1160 } // namespace
1162 PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo)
1164 // Cache is calculated only for transactions with witness
1165 if (txTo.HasWitness()) {
1166 hashPrevouts = GetPrevoutHash(txTo);
1167 hashSequence = GetSequenceHash(txTo);
1168 hashOutputs = GetOutputsHash(txTo);
1169 ready = true;
1173 uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1175 assert(nIn < txTo.vin.size());
1177 if (sigversion == SIGVERSION_WITNESS_V0) {
1178 uint256 hashPrevouts;
1179 uint256 hashSequence;
1180 uint256 hashOutputs;
1181 const bool cacheready = cache && cache->ready;
1183 if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1184 hashPrevouts = cacheready ? cache->hashPrevouts : GetPrevoutHash(txTo);
1187 if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1188 hashSequence = cacheready ? cache->hashSequence : GetSequenceHash(txTo);
1192 if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1193 hashOutputs = cacheready ? cache->hashOutputs : GetOutputsHash(txTo);
1194 } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
1195 CHashWriter ss(SER_GETHASH, 0);
1196 ss << txTo.vout[nIn];
1197 hashOutputs = ss.GetHash();
1200 CHashWriter ss(SER_GETHASH, 0);
1201 // Version
1202 ss << txTo.nVersion;
1203 // Input prevouts/nSequence (none/all, depending on flags)
1204 ss << hashPrevouts;
1205 ss << hashSequence;
1206 // The input being signed (replacing the scriptSig with scriptCode + amount)
1207 // The prevout may already be contained in hashPrevout, and the nSequence
1208 // may already be contain in hashSequence.
1209 ss << txTo.vin[nIn].prevout;
1210 ss << scriptCode;
1211 ss << amount;
1212 ss << txTo.vin[nIn].nSequence;
1213 // Outputs (none/one/all, depending on flags)
1214 ss << hashOutputs;
1215 // Locktime
1216 ss << txTo.nLockTime;
1217 // Sighash type
1218 ss << nHashType;
1220 return ss.GetHash();
1223 static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
1225 // Check for invalid use of SIGHASH_SINGLE
1226 if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1227 if (nIn >= txTo.vout.size()) {
1228 // nOut out of range
1229 return one;
1233 // Wrapper to serialize only the necessary parts of the transaction being signed
1234 CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
1236 // Serialize and hash
1237 CHashWriter ss(SER_GETHASH, 0);
1238 ss << txTmp << nHashType;
1239 return ss.GetHash();
1242 bool TransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1244 return pubkey.Verify(sighash, vchSig);
1247 bool TransactionSignatureChecker::CheckSig(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1249 CPubKey pubkey(vchPubKey);
1250 if (!pubkey.IsValid())
1251 return false;
1253 // Hash type is one byte tacked on to the end of the signature
1254 std::vector<unsigned char> vchSig(vchSigIn);
1255 if (vchSig.empty())
1256 return false;
1257 int nHashType = vchSig.back();
1258 vchSig.pop_back();
1260 uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
1262 if (!VerifySignature(vchSig, pubkey, sighash))
1263 return false;
1265 return true;
1268 bool TransactionSignatureChecker::CheckLockTime(const CScriptNum& nLockTime) const
1270 // There are two kinds of nLockTime: lock-by-blockheight
1271 // and lock-by-blocktime, distinguished by whether
1272 // nLockTime < LOCKTIME_THRESHOLD.
1274 // We want to compare apples to apples, so fail the script
1275 // unless the type of nLockTime being tested is the same as
1276 // the nLockTime in the transaction.
1277 if (!(
1278 (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
1279 (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1281 return false;
1283 // Now that we know we're comparing apples-to-apples, the
1284 // comparison is a simple numeric one.
1285 if (nLockTime > (int64_t)txTo->nLockTime)
1286 return false;
1288 // Finally the nLockTime feature can be disabled and thus
1289 // CHECKLOCKTIMEVERIFY bypassed if every txin has been
1290 // finalized by setting nSequence to maxint. The
1291 // transaction would be allowed into the blockchain, making
1292 // the opcode ineffective.
1294 // Testing if this vin is not final is sufficient to
1295 // prevent this condition. Alternatively we could test all
1296 // inputs, but testing just this input minimizes the data
1297 // required to prove correct CHECKLOCKTIMEVERIFY execution.
1298 if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1299 return false;
1301 return true;
1304 bool TransactionSignatureChecker::CheckSequence(const CScriptNum& nSequence) const
1306 // Relative lock times are supported by comparing the passed
1307 // in operand to the sequence number of the input.
1308 const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1310 // Fail if the transaction's version number is not set high
1311 // enough to trigger BIP 68 rules.
1312 if (static_cast<uint32_t>(txTo->nVersion) < 2)
1313 return false;
1315 // Sequence numbers with their most significant bit set are not
1316 // consensus constrained. Testing that the transaction's sequence
1317 // number do not have this bit set prevents using this property
1318 // to get around a CHECKSEQUENCEVERIFY check.
1319 if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1320 return false;
1322 // Mask off any bits that do not have consensus-enforced meaning
1323 // before doing the integer comparisons
1324 const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1325 const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1326 const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1328 // There are two kinds of nSequence: lock-by-blockheight
1329 // and lock-by-blocktime, distinguished by whether
1330 // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1332 // We want to compare apples to apples, so fail the script
1333 // unless the type of nSequenceMasked being tested is the same as
1334 // the nSequenceMasked in the transaction.
1335 if (!(
1336 (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1337 (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1338 )) {
1339 return false;
1342 // Now that we know we're comparing apples-to-apples, the
1343 // comparison is a simple numeric one.
1344 if (nSequenceMasked > txToSequenceMasked)
1345 return false;
1347 return true;
1350 static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1352 std::vector<std::vector<unsigned char> > stack;
1353 CScript scriptPubKey;
1355 if (witversion == 0) {
1356 if (program.size() == 32) {
1357 // Version 0 segregated witness program: SHA256(CScript) inside the program, CScript + inputs in witness
1358 if (witness.stack.size() == 0) {
1359 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1361 scriptPubKey = CScript(witness.stack.back().begin(), witness.stack.back().end());
1362 stack = std::vector<std::vector<unsigned char> >(witness.stack.begin(), witness.stack.end() - 1);
1363 uint256 hashScriptPubKey;
1364 CSHA256().Write(&scriptPubKey[0], scriptPubKey.size()).Finalize(hashScriptPubKey.begin());
1365 if (memcmp(hashScriptPubKey.begin(), program.data(), 32)) {
1366 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1368 } else if (program.size() == 20) {
1369 // Special case for pay-to-pubkeyhash; signature + pubkey in witness
1370 if (witness.stack.size() != 2) {
1371 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1373 scriptPubKey << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
1374 stack = witness.stack;
1375 } else {
1376 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
1378 } else if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
1379 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
1380 } else {
1381 // Higher version witness scripts return true for future softfork compatibility
1382 return set_success(serror);
1385 // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
1386 for (unsigned int i = 0; i < stack.size(); i++) {
1387 if (stack.at(i).size() > MAX_SCRIPT_ELEMENT_SIZE)
1388 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
1391 if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_WITNESS_V0, serror)) {
1392 return false;
1395 // Scripts inside witness implicitly require cleanstack behaviour
1396 if (stack.size() != 1)
1397 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1398 if (!CastToBool(stack.back()))
1399 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1400 return true;
1403 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1405 static const CScriptWitness emptyWitness;
1406 if (witness == nullptr) {
1407 witness = &emptyWitness;
1409 bool hadWitness = false;
1411 set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1413 if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1414 return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1417 std::vector<std::vector<unsigned char> > stack, stackCopy;
1418 if (!EvalScript(stack, scriptSig, flags, checker, SIGVERSION_BASE, serror))
1419 // serror is set
1420 return false;
1421 if (flags & SCRIPT_VERIFY_P2SH)
1422 stackCopy = stack;
1423 if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_BASE, serror))
1424 // serror is set
1425 return false;
1426 if (stack.empty())
1427 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1428 if (CastToBool(stack.back()) == false)
1429 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1431 // Bare witness programs
1432 int witnessversion;
1433 std::vector<unsigned char> witnessprogram;
1434 if (flags & SCRIPT_VERIFY_WITNESS) {
1435 if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1436 hadWitness = true;
1437 if (scriptSig.size() != 0) {
1438 // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
1439 return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
1441 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
1442 return false;
1444 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1445 // for witness programs.
1446 stack.resize(1);
1450 // Additional validation for spend-to-script-hash transactions:
1451 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1453 // scriptSig must be literals-only or validation fails
1454 if (!scriptSig.IsPushOnly())
1455 return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1457 // Restore stack.
1458 swap(stack, stackCopy);
1460 // stack cannot be empty here, because if it was the
1461 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1462 // an empty stack and the EvalScript above would return false.
1463 assert(!stack.empty());
1465 const valtype& pubKeySerialized = stack.back();
1466 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1467 popstack(stack);
1469 if (!EvalScript(stack, pubKey2, flags, checker, SIGVERSION_BASE, serror))
1470 // serror is set
1471 return false;
1472 if (stack.empty())
1473 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1474 if (!CastToBool(stack.back()))
1475 return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1477 // P2SH witness program
1478 if (flags & SCRIPT_VERIFY_WITNESS) {
1479 if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
1480 hadWitness = true;
1481 if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
1482 // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
1483 // reintroduce malleability.
1484 return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
1486 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
1487 return false;
1489 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1490 // for witness programs.
1491 stack.resize(1);
1496 // The CLEANSTACK check is only performed after potential P2SH evaluation,
1497 // as the non-P2SH evaluation of a P2SH script will obviously not result in
1498 // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
1499 if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
1500 // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
1501 // would be possible, which is not a softfork (and P2SH should be one).
1502 assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1503 assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
1504 if (stack.size() != 1) {
1505 return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1509 if (flags & SCRIPT_VERIFY_WITNESS) {
1510 // We can't check for correct unexpected witness data if P2SH was off, so require
1511 // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
1512 // possible, which is not a softfork.
1513 assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1514 if (!hadWitness && !witness->IsNull()) {
1515 return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
1519 return set_success(serror);
1522 size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness, int flags)
1524 if (witversion == 0) {
1525 if (witprogram.size() == 20)
1526 return 1;
1528 if (witprogram.size() == 32 && witness.stack.size() > 0) {
1529 CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
1530 return subscript.GetSigOpCount(true);
1534 // Future flags may be implemented here.
1535 return 0;
1538 size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags)
1540 static const CScriptWitness witnessEmpty;
1542 if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
1543 return 0;
1545 assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1547 int witnessversion;
1548 std::vector<unsigned char> witnessprogram;
1549 if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1550 return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty, flags);
1553 if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
1554 CScript::const_iterator pc = scriptSig.begin();
1555 std::vector<unsigned char> data;
1556 while (pc < scriptSig.end()) {
1557 opcodetype opcode;
1558 scriptSig.GetOp(pc, opcode, data);
1560 CScript subscript(data.begin(), data.end());
1561 if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
1562 return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty, flags);
1566 return 0;