Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2021 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.
5 :
6 : #include <script/interpreter.h>
7 :
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>
14 :
15 : typedef std::vector<unsigned char> valtype;
16 :
17 : namespace {
18 :
19 529388 : inline bool set_success(ScriptError* ret)
20 : {
21 529388 : if (ret)
22 511257 : *ret = SCRIPT_ERR_OK;
23 529388 : return true;
24 : }
25 :
26 755296 : inline bool set_error(ScriptError* ret, const ScriptError serror)
27 : {
28 755296 : if (ret)
29 734847 : *ret = serror;
30 755296 : return false;
31 : }
32 :
33 : } // namespace
34 :
35 156179 : bool CastToBool(const valtype& vch)
36 : {
37 157341 : for (unsigned int i = 0; i < vch.size(); i++)
38 : {
39 154005 : if (vch[i] != 0)
40 : {
41 : // Can be negative zero
42 152843 : if (i == vch.size()-1 && vch[i] == 0x80)
43 17 : return false;
44 152826 : return true;
45 : }
46 1162 : }
47 3336 : return false;
48 156179 : }
49 :
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.
53 : */
54 : #define stacktop(i) (stack.at(stack.size()+(i)))
55 : #define altstacktop(i) (altstack.at(altstack.size()+(i)))
56 485013 : static inline void popstack(std::vector<valtype>& stack)
57 : {
58 485013 : if (stack.empty())
59 0 : throw std::runtime_error("popstack(): stack empty");
60 485013 : stack.pop_back();
61 485013 : }
62 :
63 31280 : bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
64 31280 : if (vchPubKey.size() < CPubKey::COMPRESSED_SIZE) {
65 : // Non-canonical public key: too short
66 60 : return false;
67 : }
68 31220 : if (vchPubKey[0] == 0x04) {
69 8873 : if (vchPubKey.size() != CPubKey::SIZE) {
70 : // Non-canonical public key: invalid length for uncompressed key
71 0 : return false;
72 : }
73 31220 : } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
74 18028 : if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
75 : // Non-canonical public key: invalid length for compressed key
76 0 : return false;
77 : }
78 18028 : } else {
79 : // Non-canonical public key: neither compressed nor uncompressed
80 4319 : return false;
81 : }
82 26901 : return true;
83 31280 : }
84 :
85 : [[maybe_unused]] bool static IsCompressedPubKey(const valtype &vchPubKey) {
86 : if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
87 : // Non-canonical public key: invalid length for compressed key
88 : return false;
89 : }
90 : if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
91 : // Non-canonical public key: invalid prefix for compressed key
92 : return false;
93 : }
94 : return true;
95 : }
96 :
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).
102 : *
103 : * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
104 : *
105 : * This function is consensus-critical since BIP66.
106 : */
107 79251 : 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 integer (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)
119 :
120 : // Minimum and maximum size constraints.
121 79251 : if (sig.size() < 9) return false;
122 79145 : if (sig.size() > 73) return false;
123 :
124 : // A signature is of type 0x30 (compound).
125 79130 : if (sig[0] != 0x30) return false;
126 :
127 : // Make sure the length covers the entire signature.
128 79046 : if (sig[1] != sig.size() - 3) return false;
129 :
130 : // Extract the length of the R element.
131 62957 : unsigned int lenR = sig[3];
132 :
133 : // Make sure the length of the S element is still inside the signature.
134 62957 : if (5 + lenR >= sig.size()) return false;
135 :
136 : // Extract the length of the S element.
137 62943 : unsigned int lenS = sig[5 + lenR];
138 :
139 : // Verify that the length of the signature matches the sum of the length
140 : // of the elements.
141 62943 : if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
142 :
143 : // Check whether the R element is an integer.
144 62932 : if (sig[2] != 0x02) return false;
145 :
146 : // Zero-length integers are not allowed for R.
147 62919 : if (lenR == 0) return false;
148 :
149 : // Negative numbers are not allowed for R.
150 62904 : if (sig[4] & 0x80) return false;
151 :
152 : // Null bytes at the start of R are not allowed, unless R would
153 : // otherwise be interpreted as a negative number.
154 62585 : if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
155 :
156 : // Check whether the S element is an integer.
157 62486 : if (sig[lenR + 4] != 0x02) return false;
158 :
159 : // Zero-length integers are not allowed for S.
160 62471 : if (lenS == 0) return false;
161 :
162 : // Negative numbers are not allowed for S.
163 62460 : if (sig[lenR + 6] & 0x80) return false;
164 :
165 : // Null bytes at the start of S are not allowed, unless S would otherwise be
166 : // interpreted as a negative number.
167 62401 : if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
168 :
169 62371 : return true;
170 79251 : }
171 :
172 23828 : bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
173 23828 : if (!IsValidSignatureEncoding(vchSig)) {
174 0 : return set_error(serror, SCRIPT_ERR_SIG_DER);
175 : }
176 : // https://bitcoin.stackexchange.com/a/12556:
177 : // Also note that inside transaction signatures, an extra hashtype byte
178 : // follows the actual signature data.
179 23828 : std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
180 : // If the S value is above the order of the curve divided by two, its
181 : // complement modulo the order could have been used instead, which is
182 : // one byte shorter when encoded correctly.
183 23828 : if (!CPubKey::CheckLowS(vchSigCopy)) {
184 4121 : return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
185 : }
186 19707 : return true;
187 23828 : }
188 :
189 22883 : bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
190 22883 : if (vchSig.size() == 0) {
191 0 : return false;
192 : }
193 22883 : unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
194 22883 : if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
195 56 : return false;
196 :
197 22827 : return true;
198 22883 : }
199 :
200 100181 : bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
201 : // Empty signature. Not strictly DER encoded, but allowed to provide a
202 : // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
203 100181 : if (vchSig.size() == 0) {
204 17175 : return true;
205 : }
206 83006 : if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
207 16880 : return set_error(serror, SCRIPT_ERR_SIG_DER);
208 66126 : } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
209 : // serror is set
210 4121 : return false;
211 62005 : } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
212 56 : return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
213 : }
214 61949 : return true;
215 100181 : }
216 :
217 79061 : bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
218 79061 : if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
219 4379 : return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
220 : }
221 74682 : return true;
222 79061 : }
223 :
224 102844 : int FindAndDelete(CScript& script, const CScript& b)
225 : {
226 102844 : int nFound = 0;
227 102844 : if (b.empty())
228 1 : return nFound;
229 102843 : CScript result;
230 102843 : CScript::const_iterator pc = script.begin(), pc2 = script.begin(), end = script.end();
231 : opcodetype opcode;
232 102794 : do
233 : {
234 536212 : result.insert(result.end(), pc2, pc);
235 856894 : while (static_cast<size_t>(end - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
236 : {
237 25364 : pc = pc + b.size();
238 25364 : ++nFound;
239 : }
240 536214 : pc2 = pc;
241 1072431 : }
242 536214 : while (script.GetOp(pc, opcode));
243 :
244 102799 : if (nFound > 0) {
245 19105 : result.insert(result.end(), pc2, end);
246 19105 : script = std::move(result);
247 19105 : }
248 :
249 102799 : return nFound;
250 102898 : }
251 :
252 : namespace {
253 : /** A data type to abstract out the condition stack during script execution.
254 : *
255 : * Conceptually it acts like a vector of booleans, one for each level of nested
256 : * IF/THEN/ELSE, indicating whether we're in the active or inactive branch of
257 : * each.
258 : *
259 : * The elements on the stack cannot be observed individually; we only need to
260 : * expose whether the stack is empty and whether or not any false values are
261 : * present at all. To implement OP_ELSE, a toggle_top modifier is added, which
262 : * flips the last value without returning it.
263 : *
264 : * This uses an optimized implementation that does not materialize the
265 : * actual stack. Instead, it just stores the size of the would-be stack,
266 : * and the position of the first false value in it.
267 : */
268 495863 : class ConditionStack {
269 : private:
270 : //! A constant for m_first_false_pos to indicate there are no falses.
271 : static constexpr uint32_t NO_FALSE = std::numeric_limits<uint32_t>::max();
272 :
273 : //! The size of the implied stack.
274 495863 : uint32_t m_stack_size = 0;
275 : //! The position of the first false value on the implied stack, or NO_FALSE if all true.
276 495863 : uint32_t m_first_false_pos = NO_FALSE;
277 :
278 : public:
279 413981 : bool empty() const { return m_stack_size == 0; }
280 929926 : bool all_true() const { return m_first_false_pos == NO_FALSE; }
281 4586 : void push_back(bool f)
282 : {
283 4586 : if (m_first_false_pos == NO_FALSE && !f) {
284 : // The stack consists of all true values, and a false is added.
285 : // The first false value will appear at the current size.
286 2336 : m_first_false_pos = m_stack_size;
287 2336 : }
288 4586 : ++m_stack_size;
289 4586 : }
290 3070 : void pop_back()
291 : {
292 3070 : assert(m_stack_size > 0);
293 3070 : --m_stack_size;
294 3070 : if (m_first_false_pos == m_stack_size) {
295 : // When popping off the first false value, everything becomes true.
296 933 : m_first_false_pos = NO_FALSE;
297 933 : }
298 3070 : }
299 3894 : void toggle_top()
300 : {
301 3894 : assert(m_stack_size > 0);
302 3894 : if (m_first_false_pos == NO_FALSE) {
303 : // The current stack is all true values; the first false will be the top.
304 1208 : m_first_false_pos = m_stack_size - 1;
305 3894 : } else if (m_first_false_pos == m_stack_size - 1) {
306 : // The top is the first false value; toggling it will make everything true.
307 2414 : m_first_false_pos = NO_FALSE;
308 2414 : } else {
309 : // There is a false value, but not on top. No action is needed as toggling
310 : // anything but the first false value is unobservable.
311 : }
312 3894 : }
313 : };
314 : }
315 :
316 : /** Helper for OP_CHECKSIG and OP_CHECKSIGVERIFY
317 : *
318 : * A return value of false means the script fails entirely. When true is returned, the
319 : * fSuccess variable indicates whether the signature check itself succeeded.
320 : */
321 47251 : static bool EvalChecksig(const valtype& vchSig, const valtype& vchPubKey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& fSuccess)
322 : {
323 : // Subset of script starting at the most recent codeseparator
324 47251 : CScript scriptCode(pbegincodehash, pend);
325 :
326 : // Drop the signature, since there's no way for a signature to sign itself
327 47251 : if (sigversion == SigVersion::BASE) {
328 47232 : int found = FindAndDelete(scriptCode, CScript() << vchSig);
329 47225 : if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
330 58 : return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
331 47167 : }
332 :
333 47186 : if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
334 : //serror is set
335 9481 : return false;
336 : }
337 37690 : fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
338 :
339 37694 : if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
340 51 : return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
341 :
342 37643 : return true;
343 47273 : }
344 :
345 :
346 496355 : bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
347 : {
348 496355 : static const CScriptNum bnZero(0);
349 496355 : static const CScriptNum bnOne(1);
350 : // static const CScriptNum bnFalse(0);
351 : // static const CScriptNum bnTrue(1);
352 : static const valtype vchFalse(0);
353 : // static const valtype vchZero(0);
354 496355 : static const valtype vchTrue(1, 1);
355 :
356 496355 : CScript::const_iterator pc = script.begin();
357 496355 : CScript::const_iterator pend = script.end();
358 496355 : CScript::const_iterator pbegincodehash = script.begin();
359 : opcodetype opcode;
360 496355 : valtype vchPushValue;
361 496355 : ConditionStack vfExec;
362 496355 : std::vector<valtype> altstack;
363 496355 : set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
364 495864 : if (script.size() > MAX_SCRIPT_SIZE)
365 9 : return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
366 496340 : int nOpCount = 0;
367 496340 : bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
368 :
369 : try
370 : {
371 1337255 : while (pc < pend)
372 : {
373 929927 : bool fExec = vfExec.all_true();
374 :
375 : //
376 : // Read instruction
377 : //
378 929924 : if (!script.GetOp(pc, opcode, vchPushValue))
379 30 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
380 929895 : if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
381 43 : return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
382 :
383 : // Note how OP_RESERVED does not count towards the opcode limit.
384 929852 : if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
385 45 : return set_error(serror, SCRIPT_ERR_OP_COUNT);
386 :
387 1859525 : if (opcode == OP_INVERT ||
388 929791 : opcode == OP_2MUL ||
389 929772 : opcode == OP_2DIV ||
390 929757 : opcode == OP_MUL ||
391 929741 : opcode == OP_LSHIFT ||
392 929718 : opcode == OP_RSHIFT)
393 110 : return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes (CVE-2010-5137).
394 :
395 : // With SCRIPT_VERIFY_CONST_SCRIPTCODE, OP_CODESEPARATOR is rejected even in an unexecuted branch
396 929697 : if (opcode == OP_CODESEPARATOR && sigversion == SigVersion::BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
397 175 : return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
398 :
399 929522 : if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
400 380966 : if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
401 285 : return set_error(serror, SCRIPT_ERR_MINIMALDATA);
402 : }
403 380681 : stack.push_back(vchPushValue);
404 929249 : } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
405 538878 : switch (opcode)
406 : {
407 : //
408 : // Push value
409 : //
410 : case OP_1NEGATE:
411 : case OP_1:
412 : case OP_2:
413 : case OP_3:
414 : case OP_4:
415 : case OP_5:
416 : case OP_6:
417 : case OP_7:
418 : case OP_8:
419 : case OP_9:
420 : case OP_10:
421 : case OP_11:
422 : case OP_12:
423 : case OP_13:
424 : case OP_14:
425 : case OP_15:
426 : case OP_16:
427 : {
428 : // ( -- value)
429 97212 : CScriptNum bn((int)opcode - (int)(OP_1 - 1));
430 96975 : stack.push_back(bn.getvch());
431 : // The result of these opcodes should always be the minimal way to push the data
432 : // they push, so no need for a CheckMinimalPush here.
433 : }
434 96976 : break;
435 :
436 :
437 : //
438 : // Control
439 : //
440 : case OP_NOP:
441 11186 : break;
442 :
443 : case OP_CHECKLOCKTIMEVERIFY:
444 : {
445 15565 : if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
446 : // not enabled; treat as a NOP2
447 9850 : break;
448 : }
449 :
450 5715 : if (stack.size() < 1)
451 50 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
452 :
453 : // Note that elsewhere numeric opcodes are limited to
454 : // operands in the range -2**31+1 to 2**31-1, however it is
455 : // legal for opcodes to produce results exceeding that
456 : // range. This limitation is implemented by CScriptNum's
457 : // default 4-byte limit.
458 : //
459 : // If we kept to that limit we'd have a year 2038 problem,
460 : // even though the nLockTime field in transactions
461 : // themselves is uint32 which only becomes meaningless
462 : // after the year 2106.
463 : //
464 : // Thus as a special case we tell CScriptNum to accept up
465 : // to 5-byte bignums, which are good until 2**39-1, well
466 : // beyond the 2**32-1 limit of the nLockTime field itself.
467 5665 : const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
468 :
469 : // In the rare event that the argument may be < 0 due to
470 : // some arithmetic being done first, you can always use
471 : // 0 MAX CHECKLOCKTIMEVERIFY.
472 5638 : if (nLockTime < 0)
473 71 : return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
474 :
475 : // Actually compare the specified lock time with the transaction.
476 5567 : if (!checker.CheckLockTime(nLockTime))
477 5334 : return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
478 :
479 233 : break;
480 : }
481 :
482 : case OP_CHECKSEQUENCEVERIFY:
483 : {
484 16069 : if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
485 : // not enabled; treat as a NOP3
486 10031 : break;
487 : }
488 :
489 6038 : if (stack.size() < 1)
490 42 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
491 :
492 : // nSequence, like nLockTime, is a 32-bit unsigned integer
493 : // field. See the comment in CHECKLOCKTIMEVERIFY regarding
494 : // 5-byte numeric operands.
495 5996 : const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
496 :
497 : // In the rare event that the argument may be < 0 due to
498 : // some arithmetic being done first, you can always use
499 : // 0 MAX CHECKSEQUENCEVERIFY.
500 5955 : if (nSequence < 0)
501 67 : return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
502 :
503 : // To provide for future soft-fork extensibility, if the
504 : // operand has the disabled lock-time flag set,
505 : // CHECKSEQUENCEVERIFY behaves as a NOP.
506 5888 : if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
507 329 : break;
508 :
509 : // Compare the specified sequence number with the input.
510 5559 : if (!checker.CheckSequence(nSequence))
511 5326 : return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
512 :
513 233 : break;
514 : }
515 :
516 : case OP_NOP1: case OP_NOP4: case OP_NOP5:
517 : case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
518 : {
519 763 : if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
520 190 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
521 : }
522 573 : break;
523 :
524 : case OP_IF:
525 : case OP_NOTIF:
526 : {
527 : // <expression> if [statements] [else [statements]] endif
528 4365 : bool fValue = false;
529 4365 : if (fExec)
530 : {
531 4365 : if (stack.size() < 1)
532 17 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
533 4348 : valtype& vch = stacktop(-1);
534 4348 : fValue = CastToBool(vch);
535 4348 : if (opcode == OP_NOTIF)
536 297 : fValue = !fValue;
537 4348 : popstack(stack);
538 4348 : }
539 4348 : vfExec.push_back(fValue);
540 : }
541 4586 : break;
542 :
543 : case OP_ELSE:
544 : {
545 3952 : if (vfExec.empty())
546 58 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
547 3894 : vfExec.toggle_top();
548 : }
549 3894 : break;
550 :
551 : case OP_ENDIF:
552 : {
553 3208 : if (vfExec.empty())
554 138 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
555 3070 : vfExec.pop_back();
556 : }
557 3070 : break;
558 :
559 : case OP_VERIFY:
560 : {
561 : // (true -- ) or
562 : // (false -- false) and return
563 12077 : if (stack.size() < 1)
564 9 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
565 12068 : bool fValue = CastToBool(stacktop(-1));
566 12068 : if (fValue)
567 12033 : popstack(stack);
568 : else
569 35 : return set_error(serror, SCRIPT_ERR_VERIFY);
570 : }
571 12033 : break;
572 :
573 : case OP_RETURN:
574 : {
575 85 : return set_error(serror, SCRIPT_ERR_OP_RETURN);
576 : }
577 : break;
578 :
579 :
580 : //
581 : // Stack ops
582 : //
583 : case OP_TOALTSTACK:
584 : {
585 143 : if (stack.size() < 1)
586 14 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
587 129 : altstack.push_back(stacktop(-1));
588 129 : popstack(stack);
589 : }
590 129 : break;
591 :
592 : case OP_FROMALTSTACK:
593 : {
594 75 : if (altstack.size() < 1)
595 24 : return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
596 51 : stack.push_back(altstacktop(-1));
597 51 : popstack(altstack);
598 : }
599 51 : break;
600 :
601 : case OP_2DROP:
602 : {
603 : // (x1 x2 -- )
604 187 : if (stack.size() < 2)
605 17 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
606 170 : popstack(stack);
607 170 : popstack(stack);
608 : }
609 170 : break;
610 :
611 : case OP_2DUP:
612 : {
613 : // (x1 x2 -- x1 x2 x1 x2)
614 95 : if (stack.size() < 2)
615 44 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
616 51 : valtype vch1 = stacktop(-2);
617 51 : valtype vch2 = stacktop(-1);
618 51 : stack.push_back(vch1);
619 51 : stack.push_back(vch2);
620 51 : }
621 51 : break;
622 :
623 : case OP_3DUP:
624 : {
625 : // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
626 23026 : if (stack.size() < 3)
627 62 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
628 22964 : valtype vch1 = stacktop(-3);
629 22964 : valtype vch2 = stacktop(-2);
630 22964 : valtype vch3 = stacktop(-1);
631 22964 : stack.push_back(vch1);
632 22964 : stack.push_back(vch2);
633 22964 : stack.push_back(vch3);
634 22964 : }
635 22964 : break;
636 :
637 : case OP_2OVER:
638 : {
639 : // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
640 76 : if (stack.size() < 4)
641 42 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
642 34 : valtype vch1 = stacktop(-4);
643 34 : valtype vch2 = stacktop(-3);
644 34 : stack.push_back(vch1);
645 34 : stack.push_back(vch2);
646 34 : }
647 34 : break;
648 :
649 : case OP_2ROT:
650 : {
651 : // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
652 221 : if (stack.size() < 6)
653 17 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
654 204 : valtype vch1 = stacktop(-6);
655 204 : valtype vch2 = stacktop(-5);
656 204 : stack.erase(stack.end()-6, stack.end()-4);
657 204 : stack.push_back(vch1);
658 204 : stack.push_back(vch2);
659 204 : }
660 204 : break;
661 :
662 : case OP_2SWAP:
663 : {
664 : // (x1 x2 x3 x4 -- x3 x4 x1 x2)
665 76 : if (stack.size() < 4)
666 42 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
667 34 : swap(stacktop(-4), stacktop(-2));
668 34 : swap(stacktop(-3), stacktop(-1));
669 : }
670 34 : break;
671 :
672 : case OP_IFDUP:
673 : {
674 : // (x - 0 | x x)
675 87 : if (stack.size() < 1)
676 19 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
677 68 : valtype vch = stacktop(-1);
678 68 : if (CastToBool(vch))
679 51 : stack.push_back(vch);
680 68 : }
681 68 : break;
682 :
683 : case OP_DEPTH:
684 : {
685 : // -- stacksize
686 1322 : CScriptNum bn(stack.size());
687 1322 : stack.push_back(bn.getvch());
688 : }
689 1322 : break;
690 :
691 : case OP_DROP:
692 : {
693 : // (x -- )
694 20553 : if (stack.size() < 1)
695 15 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
696 20538 : popstack(stack);
697 : }
698 20538 : break;
699 :
700 : case OP_DUP:
701 : {
702 : // (x -- x x)
703 6722 : if (stack.size() < 1)
704 597 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
705 6125 : valtype vch = stacktop(-1);
706 6125 : stack.push_back(vch);
707 6125 : }
708 6125 : break;
709 :
710 : case OP_NIP:
711 : {
712 : // (x1 x2 -- x2)
713 189 : if (stack.size() < 2)
714 37 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
715 152 : stack.erase(stack.end() - 2);
716 : }
717 152 : break;
718 :
719 : case OP_OVER:
720 : {
721 : // (x1 x2 -- x1 x2 x1)
722 93 : if (stack.size() < 2)
723 42 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
724 51 : valtype vch = stacktop(-2);
725 51 : stack.push_back(vch);
726 51 : }
727 51 : break;
728 :
729 : case OP_PICK:
730 : case OP_ROLL:
731 : {
732 : // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
733 : // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
734 658 : if (stack.size() < 2)
735 55 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
736 603 : int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
737 582 : popstack(stack);
738 582 : if (n < 0 || n >= (int)stack.size())
739 85 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
740 497 : valtype vch = stacktop(-n-1);
741 497 : if (opcode == OP_ROLL)
742 154 : stack.erase(stack.end()-n-1);
743 497 : stack.push_back(vch);
744 497 : }
745 497 : break;
746 :
747 : case OP_ROT:
748 : {
749 : // (x1 x2 x3 -- x2 x3 x1)
750 : // x2 x1 x3 after first swap
751 : // x2 x3 x1 after second swap
752 224 : if (stack.size() < 3)
753 43 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
754 181 : swap(stacktop(-3), stacktop(-2));
755 181 : swap(stacktop(-2), stacktop(-1));
756 : }
757 181 : break;
758 :
759 : case OP_SWAP:
760 : {
761 : // (x1 x2 -- x2 x1)
762 316 : if (stack.size() < 2)
763 41 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
764 275 : swap(stacktop(-2), stacktop(-1));
765 : }
766 275 : break;
767 :
768 : case OP_TUCK:
769 : {
770 : // (x1 x2 -- x2 x1 x2)
771 97 : if (stack.size() < 2)
772 46 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
773 51 : valtype vch = stacktop(-1);
774 51 : stack.insert(stack.end()-2, vch);
775 51 : }
776 51 : break;
777 :
778 :
779 : case OP_SIZE:
780 : {
781 : // (in -- in size)
782 616 : if (stack.size() < 1)
783 15 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
784 601 : CScriptNum bn(stacktop(-1).size());
785 601 : stack.push_back(bn.getvch());
786 : }
787 601 : break;
788 :
789 :
790 : //
791 : // Bitwise logic
792 : //
793 : case OP_EQUAL:
794 : case OP_EQUALVERIFY:
795 : //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
796 : {
797 : // (x1 x2 - bool)
798 30985 : if (stack.size() < 2)
799 68 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
800 30917 : valtype& vch1 = stacktop(-2);
801 30917 : valtype& vch2 = stacktop(-1);
802 30917 : bool fEqual = (vch1 == vch2);
803 : // OP_NOTEQUAL is disabled because it would be too easy to say
804 : // something like n != 1 and have some wiseguy pass in 1 with extra
805 : // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
806 : //if (opcode == OP_NOTEQUAL)
807 : // fEqual = !fEqual;
808 30917 : popstack(stack);
809 30917 : popstack(stack);
810 30917 : stack.push_back(fEqual ? vchTrue : vchFalse);
811 30917 : if (opcode == OP_EQUALVERIFY)
812 : {
813 6401 : if (fEqual)
814 6205 : popstack(stack);
815 : else
816 196 : return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
817 6205 : }
818 : }
819 30721 : break;
820 :
821 : case OP_AND:
822 : case OP_OR:
823 : case OP_XOR: {
824 : // (x1 x2 - out)
825 51228 : if (stack.size() < 2) {
826 342 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
827 : }
828 50886 : valtype &vch1 = stacktop(-2);
829 50886 : valtype &vch2 = stacktop(-1);
830 :
831 : // Inputs must be the same size
832 50886 : if (vch1.size() != vch2.size()) {
833 393 : return set_error(serror, SCRIPT_ERR_INVALID_OPERAND_SIZE);
834 : }
835 :
836 : // To avoid allocating, we modify vch1 in place.
837 50493 : switch (opcode) {
838 : case OP_AND:
839 4395836 : for (size_t i = 0; i < vch1.size(); ++i) {
840 4379005 : vch1[i] &= vch2[i];
841 4379005 : }
842 16831 : break;
843 : case OP_OR:
844 4395836 : for (size_t i = 0; i < vch1.size(); ++i) {
845 4379005 : vch1[i] |= vch2[i];
846 4379005 : }
847 16831 : break;
848 : case OP_XOR:
849 4395836 : for (size_t i = 0; i < vch1.size(); ++i) {
850 4379005 : vch1[i] ^= vch2[i];
851 4379005 : }
852 16831 : break;
853 : default:
854 0 : break;
855 : }
856 :
857 : // And pop vch2.
858 50493 : popstack(stack);
859 : }
860 50493 : break;
861 :
862 :
863 : //
864 : // Numeric
865 : //
866 : case OP_1ADD:
867 : case OP_1SUB:
868 : case OP_NEGATE:
869 : case OP_ABS:
870 : case OP_NOT:
871 : case OP_0NOTEQUAL:
872 : {
873 : // (in -- out)
874 13856 : if (stack.size() < 1)
875 56 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
876 13800 : CScriptNum bn(stacktop(-1), fRequireMinimal);
877 13481 : switch (opcode)
878 : {
879 174 : case OP_1ADD: bn += bnOne; break;
880 79 : case OP_1SUB: bn -= bnOne; break;
881 69 : case OP_NEGATE: bn = -bn; break;
882 86 : case OP_ABS: if (bn < bnZero) bn = -bn; break;
883 12970 : case OP_NOT: bn = (bn == bnZero); break;
884 103 : case OP_0NOTEQUAL: bn = (bn != bnZero); break;
885 0 : default: assert(!"invalid opcode"); break;
886 : }
887 13481 : popstack(stack);
888 13481 : stack.push_back(bn.getvch());
889 : }
890 13481 : break;
891 :
892 : case OP_ADD:
893 : case OP_SUB:
894 : case OP_DIV:
895 : case OP_MOD:
896 : case OP_BOOLAND:
897 : case OP_BOOLOR:
898 : case OP_NUMEQUAL:
899 : case OP_NUMEQUALVERIFY:
900 : case OP_NUMNOTEQUAL:
901 : case OP_LESSTHAN:
902 : case OP_GREATERTHAN:
903 : case OP_LESSTHANOREQUAL:
904 : case OP_GREATERTHANOREQUAL:
905 : case OP_MIN:
906 : case OP_MAX:
907 : {
908 : // (x1 x2 -- out)
909 4471 : if (stack.size() < 2)
910 297 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
911 4174 : CScriptNum bn1(stacktop(-2), fRequireMinimal);
912 3875 : CScriptNum bn2(stacktop(-1), fRequireMinimal);
913 3591 : CScriptNum bn(0);
914 3591 : switch (opcode)
915 : {
916 : case OP_ADD:
917 650 : bn = bn1 + bn2;
918 650 : break;
919 :
920 : case OP_SUB:
921 111 : bn = bn1 - bn2;
922 111 : break;
923 :
924 : case OP_DIV:
925 : // denominator must not be 0
926 655 : if (bn2 == 0) {
927 137 : return set_error(serror, SCRIPT_ERR_DIV_BY_ZERO);
928 : }
929 518 : bn = bn1 / bn2;
930 518 : break;
931 :
932 : case OP_MOD:
933 : // divisor must not be 0
934 256 : if (bn2 == 0) {
935 17 : return set_error(serror, SCRIPT_ERR_MOD_BY_ZERO);
936 : }
937 239 : bn = bn1 % bn2;
938 239 : break;
939 :
940 417 : case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
941 176 : case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
942 541 : case OP_NUMEQUAL: bn = (bn1 == bn2); break;
943 70 : case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
944 87 : case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
945 138 : case OP_LESSTHAN: bn = (bn1 < bn2); break;
946 138 : case OP_GREATERTHAN: bn = (bn1 > bn2); break;
947 138 : case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
948 138 : case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
949 121 : case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
950 121 : case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
951 0 : default: assert(!"invalid opcode"); break;
952 : }
953 3437 : popstack(stack);
954 3437 : popstack(stack);
955 3437 : stack.push_back(bn.getvch());
956 :
957 3437 : if (opcode == OP_NUMEQUALVERIFY)
958 : {
959 70 : if (CastToBool(stacktop(-1)))
960 70 : popstack(stack);
961 : else
962 0 : return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
963 70 : }
964 : }
965 3437 : break;
966 :
967 : case OP_WITHIN:
968 : {
969 : // (x min max -- out)
970 303 : if (stack.size() < 3)
971 17 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
972 286 : CScriptNum bn1(stacktop(-3), fRequireMinimal);
973 270 : CScriptNum bn2(stacktop(-2), fRequireMinimal);
974 257 : CScriptNum bn3(stacktop(-1), fRequireMinimal);
975 471 : bool fValue = (bn2 <= bn1 && bn1 < bn3);
976 244 : popstack(stack);
977 244 : popstack(stack);
978 244 : popstack(stack);
979 244 : stack.push_back(fValue ? vchTrue : vchFalse);
980 : }
981 244 : break;
982 :
983 :
984 : //
985 : // Crypto
986 : //
987 : case OP_RIPEMD160:
988 : case OP_SHA1:
989 : case OP_SHA256:
990 : case OP_HASH160:
991 : case OP_HASH256:
992 : {
993 : // (in -- hash)
994 25752 : if (stack.size() < 1)
995 92 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
996 25660 : valtype& vch = stacktop(-1);
997 25660 : valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
998 25660 : if (opcode == OP_RIPEMD160)
999 85 : CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1000 25575 : else if (opcode == OP_SHA1)
1001 748 : CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1002 24827 : else if (opcode == OP_SHA256)
1003 173 : CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1004 24654 : else if (opcode == OP_HASH160)
1005 24569 : CHash160().Write(vch).Finalize(vchHash);
1006 85 : else if (opcode == OP_HASH256)
1007 85 : CHash256().Write(vch).Finalize(vchHash);
1008 25660 : popstack(stack);
1009 25660 : stack.push_back(vchHash);
1010 25660 : }
1011 25660 : break;
1012 :
1013 : case OP_CODESEPARATOR:
1014 : {
1015 : // If SCRIPT_VERIFY_CONST_SCRIPTCODE flag is set, use of OP_CODESEPARATOR is rejected,
1016 : // even in an unexecuted branch (this is checked above the opcode case statement).
1017 :
1018 : // Hash starts after the code separator
1019 341 : pbegincodehash = pc;
1020 : }
1021 341 : break;
1022 :
1023 : case OP_CHECKSIG:
1024 : case OP_CHECKSIGVERIFY:
1025 : {
1026 : // (sig pubkey -- bool)
1027 62431 : if (stack.size() < 2)
1028 15205 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1029 :
1030 47226 : valtype& vchSig = stacktop(-2);
1031 47222 : valtype& vchPubKey = stacktop(-1);
1032 :
1033 47228 : bool fSuccess = true;
1034 47228 : if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, flags, checker, sigversion, serror, fSuccess)) return false;
1035 37643 : popstack(stack);
1036 37641 : popstack(stack);
1037 37643 : stack.push_back(fSuccess ? vchTrue : vchFalse);
1038 37643 : if (opcode == OP_CHECKSIGVERIFY)
1039 : {
1040 302 : if (fSuccess)
1041 182 : popstack(stack);
1042 : else
1043 120 : return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
1044 182 : }
1045 : }
1046 37523 : break;
1047 :
1048 : case OP_CHECKDATASIG:
1049 : case OP_CHECKDATASIGVERIFY: {
1050 : // (sig message pubkey -- bool)
1051 50176 : if (stack.size() < 3) {
1052 114 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1053 : }
1054 :
1055 50062 : valtype &vchSig = stacktop(-3);
1056 50062 : valtype &vchMessage = stacktop(-2);
1057 50062 : valtype &vchPubKey = stacktop(-1);
1058 :
1059 50062 : if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
1060 : // serror is set
1061 15590 : return false;
1062 : }
1063 :
1064 34472 : bool fSuccess = false;
1065 34472 : if (vchSig.size()) {
1066 22076 : valtype vchHash(32);
1067 22076 : CSHA256()
1068 22076 : .Write(vchMessage.data(), vchMessage.size())
1069 22076 : .Finalize(vchHash.data());
1070 22076 : fSuccess = CPubKey(vchPubKey).Verify(uint256(vchHash), vchSig);
1071 22076 : }
1072 :
1073 34472 : if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size()) {
1074 10861 : return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
1075 : }
1076 :
1077 23611 : popstack(stack);
1078 23611 : popstack(stack);
1079 23611 : popstack(stack);
1080 23611 : stack.push_back(fSuccess ? vchTrue : vchFalse);
1081 23611 : if (opcode == OP_CHECKDATASIGVERIFY) {
1082 11780 : if (fSuccess) {
1083 138 : popstack(stack);
1084 138 : } else {
1085 11642 : return set_error(serror, SCRIPT_ERR_CHECKDATASIGVERIFY);
1086 : }
1087 138 : }
1088 : }
1089 11969 : break;
1090 :
1091 : case OP_CHECKMULTISIG:
1092 : case OP_CHECKMULTISIGVERIFY:
1093 : {
1094 : // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1095 :
1096 13614 : int i = 1;
1097 13614 : if ((int)stack.size() < i)
1098 14 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1099 :
1100 13600 : int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1101 13574 : if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
1102 32 : return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
1103 13542 : nOpCount += nKeysCount;
1104 13542 : if (nOpCount > MAX_OPS_PER_SCRIPT)
1105 34 : return set_error(serror, SCRIPT_ERR_OP_COUNT);
1106 13508 : int ikey = ++i;
1107 : // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
1108 : // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
1109 13508 : int ikey2 = nKeysCount + 2;
1110 13508 : i += nKeysCount;
1111 13508 : if ((int)stack.size() < i)
1112 13 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1113 :
1114 13495 : int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1115 13460 : if (nSigsCount < 0 || nSigsCount > nKeysCount)
1116 30 : return set_error(serror, SCRIPT_ERR_SIG_COUNT);
1117 13430 : int isig = ++i;
1118 13430 : i += nSigsCount;
1119 13430 : if ((int)stack.size() < i)
1120 80 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1121 :
1122 : // Subset of script starting at the most recent codeseparator
1123 13350 : CScript scriptCode(pbegincodehash, pend);
1124 :
1125 : // Drop the signatures, since there's no way for a signature to sign itself
1126 18849 : for (int k = 0; k < nSigsCount; k++)
1127 : {
1128 5553 : valtype& vchSig = stacktop(-isig-k);
1129 5552 : if (sigversion == SigVersion::BASE) {
1130 5552 : int found = FindAndDelete(scriptCode, CScript() << vchSig);
1131 5552 : if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
1132 54 : return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
1133 5498 : }
1134 5498 : }
1135 :
1136 13296 : bool fSuccess = true;
1137 15812 : while (fSuccess && nSigsCount > 0)
1138 : {
1139 2807 : valtype& vchSig = stacktop(-isig);
1140 2807 : valtype& vchPubKey = stacktop(-ikey);
1141 :
1142 : // Note how this makes the exact order of pubkey/signature evaluation
1143 : // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
1144 : // See the script_(in)valid tests for details.
1145 2807 : if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
1146 : // serror is set
1147 291 : return false;
1148 : }
1149 :
1150 : // Check signature
1151 2516 : bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
1152 :
1153 2516 : if (fOk) {
1154 1622 : isig++;
1155 1622 : nSigsCount--;
1156 1622 : }
1157 2516 : ikey++;
1158 2516 : nKeysCount--;
1159 :
1160 : // If there are more signatures left than keys left,
1161 : // then too many signatures have failed. Exit early,
1162 : // without checking any further signatures.
1163 2516 : if (nSigsCount > nKeysCount)
1164 573 : fSuccess = false;
1165 : }
1166 :
1167 : // Clean up stack of actual arguments
1168 67464 : while (i-- > 1) {
1169 : // If the operation failed, we require that all signatures must be empty vector
1170 54554 : if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
1171 95 : return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
1172 54459 : if (ikey2 > 0)
1173 50075 : ikey2--;
1174 54459 : popstack(stack);
1175 : }
1176 :
1177 : // A bug causes CHECKMULTISIG to consume one extra argument
1178 : // whose contents were not checked in any way.
1179 : //
1180 : // Unfortunately this is a potential source of mutability,
1181 : // so optionally verify it is exactly equal to zero prior
1182 : // to removing it from the stack.
1183 12910 : if (stack.size() < 1)
1184 0 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1185 12910 : if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1186 97 : return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1187 12813 : popstack(stack);
1188 :
1189 12813 : stack.push_back(fSuccess ? vchTrue : vchFalse);
1190 :
1191 12812 : if (opcode == OP_CHECKMULTISIGVERIFY)
1192 : {
1193 4175 : if (fSuccess)
1194 4175 : popstack(stack);
1195 : else
1196 0 : return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1197 4175 : }
1198 13349 : }
1199 12813 : break;
1200 :
1201 : //
1202 : // Splice operations
1203 : //
1204 : case OP_CAT:
1205 : {
1206 : // (x1 x2 -- out)
1207 10688 : if (stack.size() < 2) {
1208 42 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1209 : }
1210 :
1211 10646 : valtype &vch1 = stacktop(-2);
1212 10646 : valtype &vch2 = stacktop(-1);
1213 10646 : if (vch1.size() + vch2.size() > MAX_SCRIPT_ELEMENT_SIZE) {
1214 3160 : return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
1215 : }
1216 :
1217 7486 : vch1.insert(vch1.end(), vch2.begin(), vch2.end());
1218 7486 : popstack(stack);
1219 : }
1220 7486 : break;
1221 :
1222 : case OP_SPLIT:
1223 : {
1224 : // (in position -- x1 x2)
1225 11830 : if (stack.size() < 2) {
1226 42 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1227 : }
1228 :
1229 11788 : valtype vch = stacktop(-2);
1230 11788 : int64_t nPosition = CScriptNum(stacktop(-1), fRequireMinimal).getint();
1231 :
1232 : // if nPosition is less than 0 or is larger than the input then throw error
1233 11754 : if (nPosition < 0 || static_cast<size_t>(nPosition) > vch.size()) {
1234 4251 : return set_error(serror, SCRIPT_ERR_INVALID_SPLIT_RANGE);
1235 : }
1236 :
1237 7503 : popstack(stack);
1238 7503 : popstack(stack);
1239 :
1240 : // initialize outputs
1241 7503 : if (nPosition == 0) {
1242 2188 : stack.push_back(valtype());
1243 2188 : stack.push_back(vch);
1244 7503 : } else if (static_cast<size_t>(nPosition) == vch.size()) {
1245 2132 : stack.push_back(vch);
1246 2132 : stack.push_back(valtype());
1247 2132 : } else {
1248 3183 : valtype vchOut1, vchOut2;
1249 3183 : vchOut1.insert(vchOut1.end(), vch.begin(), vch.begin() + nPosition);
1250 3183 : vchOut2.insert(vchOut2.end(), vch.begin() + nPosition, vch.end());
1251 3183 : stack.emplace_back(std::move(vchOut1));
1252 3183 : stack.emplace_back(std::move(vchOut2));
1253 3183 : }
1254 11788 : }
1255 7503 : break;
1256 :
1257 :
1258 : //
1259 : // Conversion operations
1260 : //
1261 : case OP_NUM2BIN: {
1262 : // (in size -- out)
1263 25312 : if (stack.size() < 2) {
1264 38 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1265 : }
1266 :
1267 25274 : uint64_t size = CScriptNum(stacktop(-1), fRequireMinimal).getint();
1268 25274 : if (size > MAX_SCRIPT_ELEMENT_SIZE) {
1269 36 : return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
1270 : }
1271 :
1272 25238 : popstack(stack);
1273 25238 : valtype &rawnum = stacktop(-1);
1274 :
1275 : // Try to see if we can fit that number in the number of
1276 : // bytes requested.
1277 25238 : CScriptNum::MinimallyEncode(rawnum);
1278 25238 : if (rawnum.size() > size) {
1279 : // We definitively cannot.
1280 2 : return set_error(serror, SCRIPT_ERR_IMPOSSIBLE_ENCODING);
1281 : }
1282 :
1283 : // We already have an element of the right size, we
1284 : // don't need to do anything.
1285 25236 : if (rawnum.size() == size) {
1286 142 : break;
1287 : }
1288 :
1289 25094 : uint8_t signbit = 0x00;
1290 25094 : if (rawnum.size() > 0) {
1291 12555 : signbit = rawnum.back() & 0x80;
1292 12555 : rawnum[rawnum.size() - 1] &= 0x7f;
1293 12555 : }
1294 :
1295 25094 : rawnum.reserve(size);
1296 8670264 : while (rawnum.size() < size - 1) {
1297 8645170 : rawnum.push_back(0x00);
1298 : }
1299 :
1300 25094 : rawnum.push_back(signbit);
1301 : }
1302 25094 : break;
1303 :
1304 : case OP_BIN2NUM: {
1305 : // (in -- out)
1306 17204 : if (stack.size() < 1) {
1307 19 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1308 : }
1309 :
1310 17185 : valtype &n = stacktop(-1);
1311 17185 : CScriptNum::MinimallyEncode(n);
1312 :
1313 : // The resulting number must be a valid number.
1314 17185 : if (!CScriptNum::IsMinimallyEncoded(n)) {
1315 21 : return set_error(serror, SCRIPT_ERR_INVALID_NUMBER_RANGE);
1316 : }
1317 : }
1318 17164 : break;
1319 :
1320 : default:
1321 1429 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1322 450563 : }
1323 :
1324 : // Size limits
1325 840934 : if (stack.size() + altstack.size() > MAX_STACK_SIZE)
1326 19 : return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1327 : }
1328 407950 : }
1329 : catch (...)
1330 : {
1331 1129 : return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1332 1129 : }
1333 :
1334 406821 : if (!vfExec.empty())
1335 51 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1336 :
1337 406764 : return set_success(serror);
1338 498980 : }
1339 :
1340 : namespace {
1341 :
1342 : /**
1343 : * Wrapper that serializes like CTransaction, but with the modifications
1344 : * required for the signature hash done in-place
1345 : */
1346 : template <class T>
1347 : class CTransactionSignatureSerializer
1348 : {
1349 : private:
1350 : const T& txTo; //!< reference to the spending transaction (the one being serialized)
1351 : const CScript& scriptCode; //!< output script being consumed
1352 : const unsigned int nIn; //!< input index of txTo being signed
1353 : const bool fAnyoneCanPay; //!< whether the hashtype has the SIGHASH_ANYONECANPAY flag set
1354 : const bool fHashSingle; //!< whether the hashtype is SIGHASH_SINGLE
1355 : const bool fHashNone; //!< whether the hashtype is SIGHASH_NONE
1356 :
1357 : public:
1358 172851 : CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1359 86432 : txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1360 86432 : fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1361 86432 : fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1362 172851 : fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1363 :
1364 : /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1365 : template<typename S>
1366 86432 : void SerializeScriptCode(S &s) const {
1367 86432 : CScript::const_iterator it = scriptCode.begin();
1368 86432 : CScript::const_iterator itBegin = it;
1369 : opcodetype opcode;
1370 86432 : unsigned int nCodeSeparators = 0;
1371 441070 : while (scriptCode.GetOp(it, opcode)) {
1372 354638 : if (opcode == OP_CODESEPARATOR)
1373 25379 : nCodeSeparators++;
1374 : }
1375 86432 : ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1376 86432 : it = itBegin;
1377 441070 : while (scriptCode.GetOp(it, opcode)) {
1378 354638 : if (opcode == OP_CODESEPARATOR) {
1379 25379 : s.write(AsBytes(Span{&itBegin[0], size_t(it - itBegin - 1)}));
1380 25379 : itBegin = it;
1381 25379 : }
1382 : }
1383 86432 : if (itBegin != scriptCode.end())
1384 76271 : s.write(AsBytes(Span{&itBegin[0], size_t(it - itBegin)}));
1385 86432 : }
1386 :
1387 : /** Serialize an input of txTo */
1388 : template<typename S>
1389 191868 : void SerializeInput(S &s, unsigned int nInput) const {
1390 : // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1391 191868 : if (fAnyoneCanPay)
1392 25436 : nInput = nIn;
1393 : // Serialize the prevout
1394 191868 : ::Serialize(s, txTo.vin[nInput].prevout);
1395 : // Serialize the script
1396 191868 : if (nInput != nIn)
1397 : // Blank out other inputs' signatures
1398 105436 : ::Serialize(s, CScript());
1399 : else
1400 86432 : SerializeScriptCode(s);
1401 : // Serialize the nSequence
1402 191868 : if (nInput != nIn && (fHashSingle || fHashNone))
1403 : // let the others update at will
1404 2558 : ::Serialize(s, int{0});
1405 : else
1406 189310 : ::Serialize(s, txTo.vin[nInput].nSequence);
1407 191868 : }
1408 :
1409 : /** Serialize an output of txTo */
1410 : template<typename S>
1411 220022 : void SerializeOutput(S &s, unsigned int nOutput) const {
1412 220022 : if (fHashSingle && nOutput != nIn)
1413 : // Do not lock-in the txout payee at other indices as txin
1414 1238 : ::Serialize(s, CTxOut());
1415 : else
1416 218784 : ::Serialize(s, txTo.vout[nOutput]);
1417 220022 : }
1418 :
1419 : /** Serialize txTo */
1420 : template<typename S>
1421 86432 : void Serialize(S &s) const {
1422 : // Serialize nVersion
1423 86432 : int32_t n32bitVersion = txTo.nVersion | (txTo.nType << 16);
1424 86432 : ::Serialize(s, n32bitVersion);
1425 : // Serialize vin
1426 86432 : unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1427 86432 : ::WriteCompactSize(s, nInputs);
1428 278299 : for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1429 191867 : SerializeInput(s, nInput);
1430 : // Serialize vout
1431 86432 : unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1432 86432 : ::WriteCompactSize(s, nOutputs);
1433 306455 : for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1434 220023 : SerializeOutput(s, nOutput);
1435 : // Serialize nLockTime
1436 86432 : ::Serialize(s, txTo.nLockTime);
1437 86432 : if (txTo.nVersion >= CTransaction::SPECIAL_VERSION && txTo.nType != TRANSACTION_NORMAL)
1438 392 : ::Serialize(s, txTo.vExtraPayload);
1439 86432 : }
1440 : };
1441 :
1442 : /** Compute the (single) SHA256 of the concatenation of all prevouts of a tx. */
1443 : template <class T>
1444 : uint256 GetPrevoutsSHA256(const T& txTo)
1445 : {
1446 : HashWriter ss{};
1447 : for (const auto& txin : txTo.vin) {
1448 : ss << txin.prevout;
1449 : }
1450 : return ss.GetSHA256();
1451 : }
1452 :
1453 : /** Compute the (single) SHA256 of the concatenation of all nSequences of a tx. */
1454 : template <class T>
1455 : uint256 GetSequencesSHA256(const T& txTo)
1456 : {
1457 : HashWriter ss{};
1458 : for (const auto& txin : txTo.vin) {
1459 : ss << txin.nSequence;
1460 : }
1461 : return ss.GetSHA256();
1462 : }
1463 :
1464 : /** Compute the (single) SHA256 of the concatenation of all txouts of a tx. */
1465 : template <class T>
1466 : uint256 GetOutputsSHA256(const T& txTo)
1467 : {
1468 : HashWriter ss{};
1469 : for (const auto& txout : txTo.vout) {
1470 : ss << txout;
1471 : }
1472 : return ss.GetSHA256();
1473 : }
1474 :
1475 : } // namespace
1476 :
1477 : template <class T>
1478 97799 : void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent_outputs, bool force)
1479 : {
1480 97799 : assert(!m_ready);
1481 :
1482 97799 : m_spent_outputs = std::move(spent_outputs);
1483 :
1484 97799 : m_ready = true;
1485 97799 : }
1486 :
1487 : template <class T>
1488 134649 : PrecomputedTransactionData::PrecomputedTransactionData(const T& txTo)
1489 67325 : {
1490 : Init(txTo, {});
1491 67325 : }
1492 :
1493 : // explicit instantiation
1494 : template void PrecomputedTransactionData::Init(const CTransaction& txTo, std::vector<CTxOut>&& spent_outputs, bool force);
1495 : template void PrecomputedTransactionData::Init(const CMutableTransaction& txTo, std::vector<CTxOut>&& spent_outputs, bool force);
1496 : template PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo);
1497 : template PrecomputedTransactionData::PrecomputedTransactionData(const CMutableTransaction& txTo);
1498 :
1499 : [[maybe_unused]] static bool HandleMissingData(MissingDataBehavior mdb)
1500 : {
1501 : switch (mdb) {
1502 : case MissingDataBehavior::ASSERT_FAIL:
1503 : assert(!"Missing data");
1504 : break;
1505 : case MissingDataBehavior::FAIL:
1506 : return false;
1507 : }
1508 : assert(!"Unknown MissingDataBehavior value");
1509 : }
1510 :
1511 : template <class T>
1512 86519 : uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1513 : {
1514 86519 : assert(nIn < txTo.vin.size());
1515 :
1516 : // Check for invalid use of SIGHASH_SINGLE
1517 86519 : if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1518 1758 : if (nIn >= txTo.vout.size()) {
1519 : // nOut out of range
1520 100 : return uint256::ONE;
1521 : }
1522 1658 : }
1523 :
1524 : // Wrapper to serialize only the necessary parts of the transaction being signed
1525 86419 : CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
1526 :
1527 : // Serialize and hash
1528 86419 : HashWriter ss{};
1529 86419 : ss << txTmp << nHashType;
1530 86419 : return ss.GetHash();
1531 86519 : }
1532 :
1533 : template uint256 SignatureHash<CMutableTransaction>(const CScript& scriptCode, const CMutableTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache);
1534 : template uint256 SignatureHash<CTransaction>(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache);
1535 :
1536 : template <class T>
1537 5470 : bool GenericTransactionSignatureChecker<T>::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1538 : {
1539 5470 : return pubkey.Verify(sighash, vchSig);
1540 : }
1541 :
1542 : template <class T>
1543 35770 : bool GenericTransactionSignatureChecker<T>::CheckSig(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1544 : {
1545 35770 : CPubKey pubkey(vchPubKey);
1546 35770 : if (!pubkey.IsValid())
1547 313 : return false;
1548 :
1549 : // Hash type is one byte tacked on to the end of the signature
1550 35457 : std::vector<unsigned char> vchSig(vchSigIn);
1551 35457 : if (vchSig.empty())
1552 556 : return false;
1553 34901 : int nHashType = vchSig.back();
1554 34901 : vchSig.pop_back();
1555 :
1556 34896 : uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
1557 :
1558 34899 : if (!VerifySignature(vchSig, pubkey, sighash))
1559 817 : return false;
1560 :
1561 34084 : return true;
1562 35780 : }
1563 :
1564 : template <class T>
1565 5567 : bool GenericTransactionSignatureChecker<T>::CheckLockTime(const CScriptNum& nLockTime) const
1566 : {
1567 : // There are two kinds of nLockTime: lock-by-blockheight
1568 : // and lock-by-blocktime, distinguished by whether
1569 : // nLockTime < LOCKTIME_THRESHOLD.
1570 : //
1571 : // We want to compare apples to apples, so fail the script
1572 : // unless the type of nLockTime being tested is the same as
1573 : // the nLockTime in the transaction.
1574 5567 : if (!(
1575 5898 : (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
1576 331 : (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1577 : ))
1578 127 : return false;
1579 :
1580 : // Now that we know we're comparing apples-to-apples, the
1581 : // comparison is a simple numeric one.
1582 5440 : if (nLockTime > (int64_t)txTo->nLockTime)
1583 5131 : return false;
1584 :
1585 : // Finally the nLockTime feature can be disabled in IsFinalTx()
1586 : // and thus CHECKLOCKTIMEVERIFY bypassed if every txin has
1587 : // been finalized by setting nSequence to maxint. The
1588 : // transaction would be allowed into the blockchain, making
1589 : // the opcode ineffective.
1590 : //
1591 : // Testing if this vin is not final is sufficient to
1592 : // prevent this condition. Alternatively we could test all
1593 : // inputs, but testing just this input minimizes the data
1594 : // required to prove correct CHECKLOCKTIMEVERIFY execution.
1595 309 : if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1596 76 : return false;
1597 :
1598 233 : return true;
1599 5567 : }
1600 :
1601 : template <class T>
1602 5559 : bool GenericTransactionSignatureChecker<T>::CheckSequence(const CScriptNum& nSequence) const
1603 : {
1604 : // Relative lock times are supported by comparing the passed
1605 : // in operand to the sequence number of the input.
1606 5559 : const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1607 :
1608 : // Fail if the transaction's version number is not set high
1609 : // enough to trigger BIP 68 rules.
1610 5559 : if (static_cast<uint32_t>(txTo->nVersion) < 2)
1611 82 : return false;
1612 :
1613 : // Sequence numbers with their most significant bit set are not
1614 : // consensus constrained. Testing that the transaction's sequence
1615 : // number do not have this bit set prevents using this property
1616 : // to get around a CHECKSEQUENCEVERIFY check.
1617 5477 : if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1618 0 : return false;
1619 :
1620 : // Mask off any bits that do not have consensus-enforced meaning
1621 : // before doing the integer comparisons
1622 5477 : const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1623 5477 : const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1624 5477 : const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1625 :
1626 : // There are two kinds of nSequence: lock-by-blockheight
1627 : // and lock-by-blocktime, distinguished by whether
1628 : // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1629 : //
1630 : // We want to compare apples to apples, so fail the script
1631 : // unless the type of nSequenceMasked being tested is the same as
1632 : // the nSequenceMasked in the transaction.
1633 5477 : if (!(
1634 5756 : (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1635 279 : (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1636 : )) {
1637 108 : return false;
1638 : }
1639 :
1640 : // Now that we know we're comparing apples-to-apples, the
1641 : // comparison is a simple numeric one.
1642 5369 : if (nSequenceMasked > txToSequenceMasked)
1643 5136 : return false;
1644 :
1645 233 : return true;
1646 5559 : }
1647 :
1648 : // explicit instantiation
1649 : template class GenericTransactionSignatureChecker<CTransaction>;
1650 : template class GenericTransactionSignatureChecker<CMutableTransaction>;
1651 :
1652 168364 : bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1653 : {
1654 168364 : set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1655 :
1656 168364 : if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1657 816 : return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1658 : }
1659 :
1660 : // scriptSig and scriptPubKey must be evaluated sequentially on the same stack
1661 : // rather than being simply concatenated (see CVE-2010-5141)
1662 167548 : std::vector<std::vector<unsigned char> > stack, stackCopy;
1663 167548 : if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
1664 : // serror is set
1665 774 : return false;
1666 166767 : if (flags & SCRIPT_VERIFY_P2SH)
1667 74941 : stackCopy = stack;
1668 166771 : if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
1669 : // serror is set
1670 27784 : return false;
1671 138986 : if (stack.empty())
1672 126 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1673 138860 : if (CastToBool(stack.back()) == false)
1674 828 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1675 :
1676 : // Additional validation for spend-to-script-hash transactions:
1677 138032 : if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1678 : {
1679 : // scriptSig must be literals-only or validation fails
1680 16058 : if (!scriptSig.IsPushOnly())
1681 23 : return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1682 :
1683 : // Restore stack.
1684 16035 : swap(stack, stackCopy);
1685 :
1686 : // stack cannot be empty here, because if it was the
1687 : // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1688 : // an empty stack and the EvalScript above would return false.
1689 16035 : assert(!stack.empty());
1690 :
1691 16035 : const valtype& pubKeySerialized = stack.back();
1692 16035 : CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1693 16035 : popstack(stack);
1694 :
1695 16035 : if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
1696 : // serror is set
1697 15269 : return false;
1698 766 : if (stack.empty())
1699 0 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1700 766 : if (!CastToBool(stack.back()))
1701 44 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1702 16035 : }
1703 :
1704 : // The CLEANSTACK check is only performed after potential P2SH evaluation,
1705 : // as the non-P2SH evaluation of a P2SH script will obviously not result in
1706 : // a clean stack (the P2SH inputs remain).
1707 122695 : if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
1708 : // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
1709 : // would be possible, which is not a softfork (and P2SH should be one).
1710 12520 : assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1711 12520 : if (stack.size() != 1) {
1712 68 : return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1713 : }
1714 12452 : }
1715 :
1716 122627 : return set_success(serror);
1717 168372 : }
|