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"
13 #include "script/script.h"
18 typedef vector
<unsigned char> valtype
;
22 inline bool set_success(ScriptError
* ret
)
29 inline bool set_error(ScriptError
* ret
, const ScriptError serror
)
38 bool CastToBool(const valtype
& vch
)
40 for (unsigned int i
= 0; i
< vch
.size(); i
++)
44 // Can be negative zero
45 if (i
== vch
.size()-1 && vch
[i
] == 0x80)
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
)
62 throw runtime_error("popstack(): stack empty");
66 bool static IsCompressedOrUncompressedPubKey(const valtype
&vchPubKey
) {
67 if (vchPubKey
.size() < 33) {
68 // Non-canonical public key: too short
71 if (vchPubKey
[0] == 0x04) {
72 if (vchPubKey
.size() != 65) {
73 // Non-canonical public key: invalid length for uncompressed key
76 } else if (vchPubKey
[0] == 0x02 || vchPubKey
[0] == 0x03) {
77 if (vchPubKey
.size() != 33) {
78 // Non-canonical public key: invalid length for compressed key
82 // Non-canonical public key: neither compressed nor uncompressed
88 bool static IsCompressedPubKey(const valtype
&vchPubKey
) {
89 if (vchPubKey
.size() != 33) {
90 // Non-canonical public key: invalid length for compressed key
93 if (vchPubKey
[0] != 0x02 && vchPubKey
[0] != 0x03) {
94 // Non-canonical public key: invalid prefix for compressed key
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
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
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;
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
);
186 bool static IsDefinedHashtypeSignature(const valtype
&vchSig
) {
187 if (vchSig
.size() == 0) {
190 unsigned char nHashType
= vchSig
[vchSig
.size() - 1] & (~(SIGHASH_ANYONECANPAY
));
191 if (nHashType
< SIGHASH_ALL
|| nHashType
> SIGHASH_SINGLE
)
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) {
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
)) {
208 } else if ((flags
& SCRIPT_VERIFY_STRICTENC
) != 0 && !IsDefinedHashtypeSignature(vchSig
)) {
209 return set_error(serror
, SCRIPT_ERR_SIG_HASHTYPE
);
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
);
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
;
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();
262 valtype vchPushValue
;
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
);
269 bool fRequireMinimal
= (flags
& SCRIPT_VERIFY_MINIMALDATA
) != 0;
275 bool fExec
= !count(vfExec
.begin(), vfExec
.end(), false);
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
||
292 opcode
== OP_RIGHT
||
293 opcode
== OP_INVERT
||
302 opcode
== OP_LSHIFT
||
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
))
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.
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
);
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.
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
);
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
);
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.
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)
422 // Compare the specified sequence number with the input.
423 if (!checker
.CheckSequence(nSequence
))
424 return set_error(serror
, SCRIPT_ERR_UNSATISFIED_LOCKTIME
);
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
);
440 // <expression> if [statements] [else [statements]] endif
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
)) {
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
)
458 vfExec
.push_back(fValue
);
465 return set_error(serror
, SCRIPT_ERR_UNBALANCED_CONDITIONAL
);
466 vfExec
.back() = !vfExec
.back();
473 return set_error(serror
, SCRIPT_ERR_UNBALANCED_CONDITIONAL
);
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));
488 return set_error(serror
, SCRIPT_ERR_VERIFY
);
494 return set_error(serror
, SCRIPT_ERR_OP_RETURN
);
504 if (stack
.size() < 1)
505 return set_error(serror
, SCRIPT_ERR_INVALID_STACK_OPERATION
);
506 altstack
.push_back(stacktop(-1));
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));
523 if (stack
.size() < 2)
524 return set_error(serror
, SCRIPT_ERR_INVALID_STACK_OPERATION
);
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
);
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
);
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
);
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
);
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));
594 if (stack
.size() < 1)
595 return set_error(serror
, SCRIPT_ERR_INVALID_STACK_OPERATION
);
596 valtype vch
= stacktop(-1);
598 stack
.push_back(vch
);
605 CScriptNum
bn(stack
.size());
606 stack
.push_back(bn
.getvch());
613 if (stack
.size() < 1)
614 return set_error(serror
, SCRIPT_ERR_INVALID_STACK_OPERATION
);
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
);
632 if (stack
.size() < 2)
633 return set_error(serror
, SCRIPT_ERR_INVALID_STACK_OPERATION
);
634 stack
.erase(stack
.end() - 2);
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
);
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();
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
);
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));
681 if (stack
.size() < 2)
682 return set_error(serror
, SCRIPT_ERR_INVALID_STACK_OPERATION
);
683 swap(stacktop(-2), stacktop(-1));
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
);
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());
714 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
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)
729 stack
.push_back(fEqual
? vchTrue
: vchFalse
);
730 if (opcode
== OP_EQUALVERIFY
)
735 return set_error(serror
, SCRIPT_ERR_EQUALVERIFY
);
752 if (stack
.size() < 1)
753 return set_error(serror
, SCRIPT_ERR_INVALID_STACK_OPERATION
);
754 CScriptNum
bn(stacktop(-1), fRequireMinimal
);
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;
766 stack
.push_back(bn
.getvch());
775 case OP_NUMEQUALVERIFY
:
779 case OP_LESSTHANOREQUAL
:
780 case OP_GREATERTHANOREQUAL
:
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
);
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;
815 stack
.push_back(bn
.getvch());
817 if (opcode
== OP_NUMEQUALVERIFY
)
819 if (CastToBool(stacktop(-1)))
822 return set_error(serror
, SCRIPT_ERR_NUMEQUALVERIFY
);
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
);
839 stack
.push_back(fValue
? vchTrue
: vchFalse
);
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
));
869 stack
.push_back(vchHash
);
873 case OP_CODESEPARATOR
:
875 // Hash starts after the code separator
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
)) {
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
);
909 stack
.push_back(fSuccess
? vchTrue
: vchFalse
);
910 if (opcode
== OP_CHECKSIGVERIFY
)
915 return set_error(serror
, SCRIPT_ERR_CHECKSIGVERIFY
);
920 case OP_CHECKMULTISIG
:
921 case OP_CHECKMULTISIGVERIFY
:
923 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
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
);
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;
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
);
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
)) {
978 bool fOk
= checker
.CheckSig(vchSig
, vchPubKey
, scriptCode
, sigversion
);
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
)
994 // Clean up stack of actual arguments
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
);
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
);
1016 stack
.push_back(fSuccess
? vchTrue
: vchFalse
);
1018 if (opcode
== OP_CHECKMULTISIGVERIFY
)
1023 return set_error(serror
, SCRIPT_ERR_CHECKMULTISIGVERIFY
);
1029 return set_error(serror
, SCRIPT_ERR_BAD_OPCODE
);
1033 if (stack
.size() + altstack
.size() > 1000)
1034 return set_error(serror
, SCRIPT_ERR_STACK_SIZE
);
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
);
1051 * Wrapper that serializes like CTransaction, but with the modifications
1052 * required for the signature hash done in-place
1054 class CTransactionSignatureSerializer
{
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
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
;
1076 unsigned int nCodeSeparators
= 0;
1077 while (scriptCode
.GetOp(it
, opcode
)) {
1078 if (opcode
== OP_CODESEPARATOR
)
1081 ::WriteCompactSize(s
, scriptCode
.size() - nCodeSeparators
);
1083 while (scriptCode
.GetOp(it
, opcode
)) {
1084 if (opcode
== OP_CODESEPARATOR
) {
1085 s
.write((char*)&itBegin
[0], it
-itBegin
-1);
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
1099 // Serialize the prevout
1100 ::Serialize(s
, txTo
.vin
[nInput
].prevout
);
1101 // Serialize the script
1103 // Blank out other inputs' signatures
1104 ::Serialize(s
, CScriptBase());
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);
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());
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
);
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
);
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
++) {
1166 return ss
.GetHash();
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);
1204 ss
<< txTo
.nVersion
;
1205 // Input prevouts/nSequence (none/all, depending on flags)
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
);
1214 ss
<< txTo
.vin
[nIn
].nSequence
;
1215 // Outputs (none/one/all, depending on flags)
1218 ss
<< txTo
.nLockTime
;
1222 return ss
.GetHash();
1225 static const uint256
one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
1226 if (nIn
>= txTo
.vin
.size()) {
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
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())
1259 // Hash type is one byte tacked on to the end of the signature
1260 vector
<unsigned char> vchSig(vchSigIn
);
1263 int nHashType
= vchSig
.back();
1266 uint256 sighash
= SignatureHash(scriptCode
, *txTo
, nIn
, nHashType
, amount
, sigversion
, this->txdata
);
1268 if (!VerifySignature(vchSig
, pubkey
, sighash
))
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.
1284 (txTo
->nLockTime
< LOCKTIME_THRESHOLD
&& nLockTime
< LOCKTIME_THRESHOLD
) ||
1285 (txTo
->nLockTime
>= LOCKTIME_THRESHOLD
&& nLockTime
>= LOCKTIME_THRESHOLD
)
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
)
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
)
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)
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
)
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.
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
)
1348 // Now that we know we're comparing apples-to-apples, the
1349 // comparison is a simple numeric one.
1350 if (nSequenceMasked
> txToSequenceMasked
)
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
;
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
);
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
)) {
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
);
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
))
1427 if (flags
& SCRIPT_VERIFY_P2SH
)
1429 if (!EvalScript(stack
, scriptPubKey
, flags
, checker
, SIGVERSION_BASE
, serror
))
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
1439 std::vector
<unsigned char> witnessprogram
;
1440 if (flags
& SCRIPT_VERIFY_WITNESS
) {
1441 if (scriptPubKey
.IsWitnessProgram(witnessversion
, witnessprogram
)) {
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
)) {
1450 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1451 // for witness programs.
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
);
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());
1475 if (!EvalScript(stack
, pubKey2
, flags
, checker
, SIGVERSION_BASE
, serror
))
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
)) {
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
)) {
1495 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1496 // for witness programs.
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)
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.
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) {
1551 assert((flags
& SCRIPT_VERIFY_P2SH
) != 0);
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()) {
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
);