1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 #include <script/standard.h>
15 
16 namespace {
17 
set_success(ScriptError * ret)18 inline bool set_success(ScriptError* ret)
19 {
20     if (ret)
21         *ret = SCRIPT_ERR_OK;
22     return true;
23 }
24 
set_error(ScriptError * ret,const ScriptError serror)25 inline bool set_error(ScriptError* ret, const ScriptError serror)
26 {
27     if (ret)
28         *ret = serror;
29     return false;
30 }
31 
32 } // namespace
33 
CastToBool(const valtype & vch)34 bool CastToBool(const valtype& vch)
35 {
36     for (unsigned int i = 0; i < vch.size(); i++)
37     {
38         if (vch[i] != 0)
39         {
40             // Can be negative zero
41             if (i == vch.size()-1 && vch[i] == 0x80)
42                 return false;
43             return true;
44         }
45     }
46     return false;
47 }
48 
49 /**
50  * Script is a stack machine (like Forth) that evaluates a predicate
51  * returning a bool indicating valid or not.  There are no loops.
52  */
53 #define stacktop(i)  (stack.at(stack.size()+(i)))
54 #define altstacktop(i)  (altstack.at(altstack.size()+(i)))
popstack(std::vector<valtype> & stack)55 static inline void popstack(std::vector<valtype>& stack)
56 {
57     if (stack.empty())
58         throw std::runtime_error("popstack(): stack empty");
59     stack.pop_back();
60 }
61 
IsCompressedOrUncompressedPubKey(const valtype & vchPubKey)62 bool IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
63     if (vchPubKey.size() < CPubKey::COMPRESSED_SIZE) {
64         //  Non-canonical public key: too short
65         return false;
66     }
67     if (vchPubKey[0] == 0x04) {
68         if (vchPubKey.size() != CPubKey::SIZE) {
69             //  Non-canonical public key: invalid length for uncompressed key
70             return false;
71         }
72     } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
73         if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
74             //  Non-canonical public key: invalid length for compressed key
75             return false;
76         }
77     } else {
78         //  Non-canonical public key: neither compressed nor uncompressed
79         return false;
80     }
81     return true;
82 }
83 
IsCompressedPubKey(const valtype & vchPubKey)84 bool static IsCompressedPubKey(const valtype &vchPubKey) {
85     if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
86         //  Non-canonical public key: invalid length for compressed key
87         return false;
88     }
89     if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
90         //  Non-canonical public key: invalid prefix for compressed key
91         return false;
92     }
93     return true;
94 }
95 
96 /**
97  * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
98  * Where R and S are not negative (their first byte has its highest bit not set), and not
99  * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
100  * in which case a single 0 byte is necessary and even required).
101  *
102  * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
103  *
104  * This function is consensus-critical since BIP66.
105  */
IsValidSignatureEncoding(const std::vector<unsigned char> & sig,bool haveHashType=true)106 bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig, bool haveHashType = true) {
107     // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
108     // * total-length: 1-byte length descriptor of everything that follows,
109     //   excluding the sighash byte.
110     // * R-length: 1-byte length descriptor of the R value that follows.
111     // * R: arbitrary-length big-endian encoded R value. It must use the shortest
112     //   possible encoding for a positive integer (which means no null bytes at
113     //   the start, except a single one when the next byte has its highest bit set).
114     // * S-length: 1-byte length descriptor of the S value that follows.
115     // * S: arbitrary-length big-endian encoded S value. The same rules apply.
116     // * sighash: 1-byte value indicating what data is hashed (not part of the DER
117     //   signature)
118 
119     // Minimum and maximum size constraints.
120     if (sig.size() < 9) return false;
121     if (sig.size() > 73) return false;
122 
123     // A signature is of type 0x30 (compound).
124     if (sig[0] != 0x30) return false;
125 
126     // Make sure the length covers the entire signature.
127     if (sig[1] != sig.size() - (haveHashType ? 3 : 2)) return false;
128 
129     // Extract the length of the R element.
130     unsigned int lenR = sig[3];
131 
132     // Make sure the length of the S element is still inside the signature.
133     if (5 + lenR >= sig.size()) return false;
134 
135     // Extract the length of the S element.
136     unsigned int lenS = sig[5 + lenR];
137 
138     // Verify that the length of the signature matches the sum of the length
139     // of the elements.
140     if ((size_t)(lenR + lenS + (haveHashType ? 7 : 6)) != sig.size()) return false;
141 
142     // Check whether the R element is an integer.
143     if (sig[2] != 0x02) return false;
144 
145     // Zero-length integers are not allowed for R.
146     if (lenR == 0) return false;
147 
148     // Negative numbers are not allowed for R.
149     if (sig[4] & 0x80) return false;
150 
151     // Null bytes at the start of R are not allowed, unless R would
152     // otherwise be interpreted as a negative number.
153     if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
154 
155     // Check whether the S element is an integer.
156     if (sig[lenR + 4] != 0x02) return false;
157 
158     // Zero-length integers are not allowed for S.
159     if (lenS == 0) return false;
160 
161     // Negative numbers are not allowed for S.
162     if (sig[lenR + 6] & 0x80) return false;
163 
164     // Null bytes at the start of S are not allowed, unless S would otherwise be
165     // interpreted as a negative number.
166     if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
167 
168     return true;
169 }
170 
IsLowDERSignature(const valtype & vchSig,ScriptError * serror,bool haveHashType)171 bool IsLowDERSignature(const valtype &vchSig, ScriptError* serror, bool haveHashType) {
172     if (!IsValidSignatureEncoding(vchSig, haveHashType)) {
173         return set_error(serror, SCRIPT_ERR_SIG_DER);
174     }
175     // https://bitcoin.stackexchange.com/a/12556:
176     //     Also note that inside transaction signatures, an extra hashtype byte
177     //     follows the actual signature data.
178     std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - (haveHashType ? 1 : 0));
179     // If the S value is above the order of the curve divided by two, its
180     // complement modulo the order could have been used instead, which is
181     // one byte shorter when encoded correctly.
182     if (!CPubKey::CheckLowS(vchSigCopy)) {
183         return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
184     }
185     return true;
186 }
187 
IsDERSignature(const valtype & vchSig,ScriptError * serror,bool haveHashType)188 bool IsDERSignature(const valtype &vchSig, ScriptError* serror, bool haveHashType) {
189     if (!IsValidSignatureEncoding(vchSig, haveHashType)) {
190         return set_error(serror, SCRIPT_ERR_SIG_DER);
191     }
192     return true;
193 }
194 
IsDefinedHashtypeSignature(const valtype & vchSig)195 bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
196     if (vchSig.size() == 0) {
197         return false;
198     }
199     unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
200     if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
201         return false;
202 
203     return true;
204 }
205 
CheckSignatureEncoding(const std::vector<unsigned char> & vchSig,unsigned int flags,ScriptError * serror)206 bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
207     // Empty signature. Not strictly DER encoded, but allowed to provide a
208     // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
209     if (vchSig.size() == 0) {
210         return true;
211     }
212     if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
213         return set_error(serror, SCRIPT_ERR_SIG_DER);
214     } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
215         // serror is set
216         return false;
217     } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
218         return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
219     }
220     return true;
221 }
222 
CheckPubKeyEncoding(const valtype & vchPubKey,unsigned int flags,const SigVersion & sigversion,ScriptError * serror)223 bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
224     if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
225         return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
226     }
227     // Only compressed keys are accepted in segwit
228     if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SigVersion::WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
229         return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
230     }
231     return true;
232 }
233 
CheckMinimalPush(const valtype & data,opcodetype opcode)234 bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
235     // Excludes OP_1NEGATE, OP_1-16 since they are by definition minimal
236     assert(0 <= opcode && opcode <= OP_PUSHDATA4);
237     if (data.size() == 0) {
238         // Should have used OP_0.
239         return opcode == OP_0;
240     } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
241         // Should have used OP_1 .. OP_16.
242         return false;
243     } else if (data.size() == 1 && data[0] == 0x81) {
244         // Should have used OP_1NEGATE.
245         return false;
246     } else if (data.size() <= 75) {
247         // Must have used a direct push (opcode indicating number of bytes pushed + those bytes).
248         return opcode == data.size();
249     } else if (data.size() <= 255) {
250         // Must have used OP_PUSHDATA.
251         return opcode == OP_PUSHDATA1;
252     } else if (data.size() <= 65535) {
253         // Must have used OP_PUSHDATA2.
254         return opcode == OP_PUSHDATA2;
255     }
256     return true;
257 }
258 
FindAndDelete(CScript & script,const CScript & b)259 int FindAndDelete(CScript& script, const CScript& b)
260 {
261     int nFound = 0;
262     if (b.empty())
263         return nFound;
264     CScript result;
265     CScript::const_iterator pc = script.begin(), pc2 = script.begin(), end = script.end();
266     opcodetype opcode;
267     do
268     {
269         result.insert(result.end(), pc2, pc);
270         while (static_cast<size_t>(end - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
271         {
272             pc = pc + b.size();
273             ++nFound;
274         }
275         pc2 = pc;
276     }
277     while (script.GetOp(pc, opcode));
278 
279     if (nFound > 0) {
280         result.insert(result.end(), pc2, end);
281         script = std::move(result);
282     }
283 
284     return nFound;
285 }
286 
287 namespace {
288 /** A data type to abstract out the condition stack during script execution.
289  *
290  * Conceptually it acts like a vector of booleans, one for each level of nested
291  * IF/THEN/ELSE, indicating whether we're in the active or inactive branch of
292  * each.
293  *
294  * The elements on the stack cannot be observed individually; we only need to
295  * expose whether the stack is empty and whether or not any false values are
296  * present at all. To implement OP_ELSE, a toggle_top modifier is added, which
297  * flips the last value without returning it.
298  *
299  * This uses an optimized implementation that does not materialize the
300  * actual stack. Instead, it just stores the size of the would-be stack,
301  * and the position of the first false value in it.
302  */
303 class ConditionStack {
304 private:
305     //! A constant for m_first_false_pos to indicate there are no falses.
306     static constexpr uint32_t NO_FALSE = std::numeric_limits<uint32_t>::max();
307 
308     //! The size of the implied stack.
309     uint32_t m_stack_size = 0;
310     //! The position of the first false value on the implied stack, or NO_FALSE if all true.
311     uint32_t m_first_false_pos = NO_FALSE;
312 
313 public:
empty()314     bool empty() { return m_stack_size == 0; }
all_true()315     bool all_true() { return m_first_false_pos == NO_FALSE; }
push_back(bool f)316     void push_back(bool f)
317     {
318         if (m_first_false_pos == NO_FALSE && !f) {
319             // The stack consists of all true values, and a false is added.
320             // The first false value will appear at the current size.
321             m_first_false_pos = m_stack_size;
322         }
323         ++m_stack_size;
324     }
pop_back()325     void pop_back()
326     {
327         assert(m_stack_size > 0);
328         --m_stack_size;
329         if (m_first_false_pos == m_stack_size) {
330             // When popping off the first false value, everything becomes true.
331             m_first_false_pos = NO_FALSE;
332         }
333     }
toggle_top()334     void toggle_top()
335     {
336         assert(m_stack_size > 0);
337         if (m_first_false_pos == NO_FALSE) {
338             // The current stack is all true values; the first false will be the top.
339             m_first_false_pos = m_stack_size - 1;
340         } else if (m_first_false_pos == m_stack_size - 1) {
341             // The top is the first false value; toggling it will make everything true.
342             m_first_false_pos = NO_FALSE;
343         } else {
344             // There is a false value, but not on top. No action is needed as toggling
345             // anything but the first false value is unobservable.
346         }
347     }
348 };
349 }
350 
EvalScript(std::vector<std::vector<unsigned char>> & stack,const CScript & script,unsigned int flags,const BaseSignatureChecker & checker,SigVersion sigversion,ScriptError * serror)351 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
352 {
353     static const CScriptNum bnZero(0);
354     static const CScriptNum bnOne(1);
355     // static const CScriptNum bnFalse(0);
356     // static const CScriptNum bnTrue(1);
357     static const valtype vchFalse(0);
358     // static const valtype vchZero(0);
359     static const valtype vchTrue(1, 1);
360 
361     CScript::const_iterator pc = script.begin();
362     CScript::const_iterator pend = script.end();
363     CScript::const_iterator pbegincodehash = script.begin();
364     opcodetype opcode;
365     valtype vchPushValue;
366     ConditionStack vfExec;
367     std::vector<valtype> altstack;
368     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
369     if (script.size() > MAX_SCRIPT_SIZE)
370         return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
371     int nOpCount = 0;
372     bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
373 
374     try
375     {
376         while (pc < pend)
377         {
378             bool fExec = vfExec.all_true();
379 
380             //
381             // Read instruction
382             //
383             if (!script.GetOp(pc, opcode, vchPushValue))
384                 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
385             if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
386                 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
387 
388             // Note how OP_RESERVED does not count towards the opcode limit.
389             if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
390                 return set_error(serror, SCRIPT_ERR_OP_COUNT);
391 
392             if (opcode == OP_CAT ||
393                 opcode == OP_SUBSTR ||
394                 opcode == OP_LEFT ||
395                 opcode == OP_RIGHT ||
396                 opcode == OP_INVERT ||
397                 opcode == OP_AND ||
398                 opcode == OP_OR ||
399                 opcode == OP_XOR ||
400                 opcode == OP_2MUL ||
401                 opcode == OP_2DIV ||
402                 opcode == OP_MUL ||
403                 opcode == OP_DIV ||
404                 opcode == OP_MOD ||
405                 opcode == OP_LSHIFT ||
406                 opcode == OP_RSHIFT)
407                 return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes (CVE-2010-5137).
408 
409             // With SCRIPT_VERIFY_CONST_SCRIPTCODE, OP_CODESEPARATOR in non-segwit script is rejected even in an unexecuted branch
410             if (opcode == OP_CODESEPARATOR && sigversion == SigVersion::BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
411                 return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
412 
413             if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
414                 if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
415                     return set_error(serror, SCRIPT_ERR_MINIMALDATA);
416                 }
417                 stack.push_back(vchPushValue);
418             } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
419             switch (opcode)
420             {
421                 //
422                 // Push value
423                 //
424                 case OP_1NEGATE:
425                 case OP_1:
426                 case OP_2:
427                 case OP_3:
428                 case OP_4:
429                 case OP_5:
430                 case OP_6:
431                 case OP_7:
432                 case OP_8:
433                 case OP_9:
434                 case OP_10:
435                 case OP_11:
436                 case OP_12:
437                 case OP_13:
438                 case OP_14:
439                 case OP_15:
440                 case OP_16:
441                 {
442                     // ( -- value)
443                     CScriptNum bn((int)opcode - (int)(OP_1 - 1));
444                     stack.push_back(bn.getvch());
445                     // The result of these opcodes should always be the minimal way to push the data
446                     // they push, so no need for a CheckMinimalPush here.
447                 }
448                 break;
449 
450 
451                 //
452                 // Control
453                 //
454                 case OP_NOP:
455                     break;
456 
457                 case OP_CHECKLOCKTIMEVERIFY:
458                 {
459                     if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
460                         // not enabled; treat as a NOP2
461                         break;
462                     }
463 
464                     if (stack.size() < 1)
465                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
466 
467                     // Note that elsewhere numeric opcodes are limited to
468                     // operands in the range -2**31+1 to 2**31-1, however it is
469                     // legal for opcodes to produce results exceeding that
470                     // range. This limitation is implemented by CScriptNum's
471                     // default 4-byte limit.
472                     //
473                     // If we kept to that limit we'd have a year 2038 problem,
474                     // even though the nLockTime field in transactions
475                     // themselves is uint32 which only becomes meaningless
476                     // after the year 2106.
477                     //
478                     // Thus as a special case we tell CScriptNum to accept up
479                     // to 5-byte bignums, which are good until 2**39-1, well
480                     // beyond the 2**32-1 limit of the nLockTime field itself.
481                     const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
482 
483                     // In the rare event that the argument may be < 0 due to
484                     // some arithmetic being done first, you can always use
485                     // 0 MAX CHECKLOCKTIMEVERIFY.
486                     if (nLockTime < 0)
487                         return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
488 
489                     // Actually compare the specified lock time with the transaction.
490                     if (!checker.CheckLockTime(nLockTime))
491                         return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
492 
493                     break;
494                 }
495 
496                 case OP_CHECKSEQUENCEVERIFY:
497                 {
498                     if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
499                         // not enabled; treat as a NOP3
500                         break;
501                     }
502 
503                     if (stack.size() < 1)
504                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
505 
506                     // nSequence, like nLockTime, is a 32-bit unsigned integer
507                     // field. See the comment in CHECKLOCKTIMEVERIFY regarding
508                     // 5-byte numeric operands.
509                     const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
510 
511                     // In the rare event that the argument may be < 0 due to
512                     // some arithmetic being done first, you can always use
513                     // 0 MAX CHECKSEQUENCEVERIFY.
514                     if (nSequence < 0)
515                         return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
516 
517                     // To provide for future soft-fork extensibility, if the
518                     // operand has the disabled lock-time flag set,
519                     // CHECKSEQUENCEVERIFY behaves as a NOP.
520                     if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
521                         break;
522 
523                     // Compare the specified sequence number with the input.
524                     if (!checker.CheckSequence(nSequence))
525                         return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
526 
527                     break;
528                 }
529 
530                 case OP_NOP1: case OP_NOP4: case OP_NOP5:
531                 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
532                 {
533                     if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
534                         return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
535                 }
536                 break;
537 
538                 case OP_IF:
539                 case OP_NOTIF:
540                 {
541                     // <expression> if [statements] [else [statements]] endif
542                     bool fValue = false;
543                     if (fExec)
544                     {
545                         if (stack.size() < 1)
546                             return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
547                         valtype& vch = stacktop(-1);
548                         if (sigversion == SigVersion::WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
549                             if (vch.size() > 1)
550                                 return set_error(serror, SCRIPT_ERR_MINIMALIF);
551                             if (vch.size() == 1 && vch[0] != 1)
552                                 return set_error(serror, SCRIPT_ERR_MINIMALIF);
553                         }
554                         fValue = CastToBool(vch);
555                         if (opcode == OP_NOTIF)
556                             fValue = !fValue;
557                         popstack(stack);
558                     }
559                     vfExec.push_back(fValue);
560                 }
561                 break;
562 
563                 case OP_ELSE:
564                 {
565                     if (vfExec.empty())
566                         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
567                     vfExec.toggle_top();
568                 }
569                 break;
570 
571                 case OP_ENDIF:
572                 {
573                     if (vfExec.empty())
574                         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
575                     vfExec.pop_back();
576                 }
577                 break;
578 
579                 case OP_VERIFY:
580                 {
581                     // (true -- ) or
582                     // (false -- false) and return
583                     if (stack.size() < 1)
584                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
585                     bool fValue = CastToBool(stacktop(-1));
586                     if (fValue)
587                         popstack(stack);
588                     else
589                         return set_error(serror, SCRIPT_ERR_VERIFY);
590                 }
591                 break;
592 
593                 case OP_RETURN:
594                 {
595                     return set_error(serror, SCRIPT_ERR_OP_RETURN);
596                 }
597                 break;
598 
599 
600                 //
601                 // Stack ops
602                 //
603                 case OP_TOALTSTACK:
604                 {
605                     if (stack.size() < 1)
606                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
607                     altstack.push_back(stacktop(-1));
608                     popstack(stack);
609                 }
610                 break;
611 
612                 case OP_FROMALTSTACK:
613                 {
614                     if (altstack.size() < 1)
615                         return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
616                     stack.push_back(altstacktop(-1));
617                     popstack(altstack);
618                 }
619                 break;
620 
621                 case OP_2DROP:
622                 {
623                     // (x1 x2 -- )
624                     if (stack.size() < 2)
625                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
626                     popstack(stack);
627                     popstack(stack);
628                 }
629                 break;
630 
631                 case OP_2DUP:
632                 {
633                     // (x1 x2 -- x1 x2 x1 x2)
634                     if (stack.size() < 2)
635                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
636                     valtype vch1 = stacktop(-2);
637                     valtype vch2 = stacktop(-1);
638                     stack.push_back(vch1);
639                     stack.push_back(vch2);
640                 }
641                 break;
642 
643                 case OP_3DUP:
644                 {
645                     // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
646                     if (stack.size() < 3)
647                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
648                     valtype vch1 = stacktop(-3);
649                     valtype vch2 = stacktop(-2);
650                     valtype vch3 = stacktop(-1);
651                     stack.push_back(vch1);
652                     stack.push_back(vch2);
653                     stack.push_back(vch3);
654                 }
655                 break;
656 
657                 case OP_2OVER:
658                 {
659                     // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
660                     if (stack.size() < 4)
661                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
662                     valtype vch1 = stacktop(-4);
663                     valtype vch2 = stacktop(-3);
664                     stack.push_back(vch1);
665                     stack.push_back(vch2);
666                 }
667                 break;
668 
669                 case OP_2ROT:
670                 {
671                     // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
672                     if (stack.size() < 6)
673                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
674                     valtype vch1 = stacktop(-6);
675                     valtype vch2 = stacktop(-5);
676                     stack.erase(stack.end()-6, stack.end()-4);
677                     stack.push_back(vch1);
678                     stack.push_back(vch2);
679                 }
680                 break;
681 
682                 case OP_2SWAP:
683                 {
684                     // (x1 x2 x3 x4 -- x3 x4 x1 x2)
685                     if (stack.size() < 4)
686                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
687                     swap(stacktop(-4), stacktop(-2));
688                     swap(stacktop(-3), stacktop(-1));
689                 }
690                 break;
691 
692                 case OP_IFDUP:
693                 {
694                     // (x - 0 | x x)
695                     if (stack.size() < 1)
696                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
697                     valtype vch = stacktop(-1);
698                     if (CastToBool(vch))
699                         stack.push_back(vch);
700                 }
701                 break;
702 
703                 case OP_DEPTH:
704                 {
705                     // -- stacksize
706                     CScriptNum bn(stack.size());
707                     stack.push_back(bn.getvch());
708                 }
709                 break;
710 
711                 case OP_DROP:
712                 {
713                     // (x -- )
714                     if (stack.size() < 1)
715                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
716                     popstack(stack);
717                 }
718                 break;
719 
720                 case OP_DUP:
721                 {
722                     // (x -- x x)
723                     if (stack.size() < 1)
724                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
725                     valtype vch = stacktop(-1);
726                     stack.push_back(vch);
727                 }
728                 break;
729 
730                 case OP_NIP:
731                 {
732                     // (x1 x2 -- x2)
733                     if (stack.size() < 2)
734                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
735                     stack.erase(stack.end() - 2);
736                 }
737                 break;
738 
739                 case OP_OVER:
740                 {
741                     // (x1 x2 -- x1 x2 x1)
742                     if (stack.size() < 2)
743                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
744                     valtype vch = stacktop(-2);
745                     stack.push_back(vch);
746                 }
747                 break;
748 
749                 case OP_PICK:
750                 case OP_ROLL:
751                 {
752                     // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
753                     // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
754                     if (stack.size() < 2)
755                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
756                     int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
757                     popstack(stack);
758                     if (n < 0 || n >= (int)stack.size())
759                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
760                     valtype vch = stacktop(-n-1);
761                     if (opcode == OP_ROLL)
762                         stack.erase(stack.end()-n-1);
763                     stack.push_back(vch);
764                 }
765                 break;
766 
767                 case OP_ROT:
768                 {
769                     // (x1 x2 x3 -- x2 x3 x1)
770                     //  x2 x1 x3  after first swap
771                     //  x2 x3 x1  after second swap
772                     if (stack.size() < 3)
773                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
774                     swap(stacktop(-3), stacktop(-2));
775                     swap(stacktop(-2), stacktop(-1));
776                 }
777                 break;
778 
779                 case OP_SWAP:
780                 {
781                     // (x1 x2 -- x2 x1)
782                     if (stack.size() < 2)
783                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
784                     swap(stacktop(-2), stacktop(-1));
785                 }
786                 break;
787 
788                 case OP_TUCK:
789                 {
790                     // (x1 x2 -- x2 x1 x2)
791                     if (stack.size() < 2)
792                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
793                     valtype vch = stacktop(-1);
794                     stack.insert(stack.end()-2, vch);
795                 }
796                 break;
797 
798 
799                 case OP_SIZE:
800                 {
801                     // (in -- in size)
802                     if (stack.size() < 1)
803                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
804                     CScriptNum bn(stacktop(-1).size());
805                     stack.push_back(bn.getvch());
806                 }
807                 break;
808 
809 
810                 //
811                 // Bitwise logic
812                 //
813                 case OP_EQUAL:
814                 case OP_EQUALVERIFY:
815                 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
816                 {
817                     // (x1 x2 - bool)
818                     if (stack.size() < 2)
819                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
820                     valtype& vch1 = stacktop(-2);
821                     valtype& vch2 = stacktop(-1);
822                     bool fEqual = (vch1 == vch2);
823                     // OP_NOTEQUAL is disabled because it would be too easy to say
824                     // something like n != 1 and have some wiseguy pass in 1 with extra
825                     // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
826                     //if (opcode == OP_NOTEQUAL)
827                     //    fEqual = !fEqual;
828                     popstack(stack);
829                     popstack(stack);
830                     stack.push_back(fEqual ? vchTrue : vchFalse);
831                     if (opcode == OP_EQUALVERIFY)
832                     {
833                         if (fEqual)
834                             popstack(stack);
835                         else
836                             return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
837                     }
838                 }
839                 break;
840 
841 
842                 //
843                 // Numeric
844                 //
845                 case OP_1ADD:
846                 case OP_1SUB:
847                 case OP_NEGATE:
848                 case OP_ABS:
849                 case OP_NOT:
850                 case OP_0NOTEQUAL:
851                 {
852                     // (in -- out)
853                     if (stack.size() < 1)
854                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
855                     CScriptNum bn(stacktop(-1), fRequireMinimal);
856                     switch (opcode)
857                     {
858                     case OP_1ADD:       bn += bnOne; break;
859                     case OP_1SUB:       bn -= bnOne; break;
860                     case OP_NEGATE:     bn = -bn; break;
861                     case OP_ABS:        if (bn < bnZero) bn = -bn; break;
862                     case OP_NOT:        bn = (bn == bnZero); break;
863                     case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
864                     default:            assert(!"invalid opcode"); break;
865                     }
866                     popstack(stack);
867                     stack.push_back(bn.getvch());
868                 }
869                 break;
870 
871                 case OP_ADD:
872                 case OP_SUB:
873                 case OP_BOOLAND:
874                 case OP_BOOLOR:
875                 case OP_NUMEQUAL:
876                 case OP_NUMEQUALVERIFY:
877                 case OP_NUMNOTEQUAL:
878                 case OP_LESSTHAN:
879                 case OP_GREATERTHAN:
880                 case OP_LESSTHANOREQUAL:
881                 case OP_GREATERTHANOREQUAL:
882                 case OP_MIN:
883                 case OP_MAX:
884                 {
885                     // (x1 x2 -- out)
886                     if (stack.size() < 2)
887                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
888                     CScriptNum bn1(stacktop(-2), fRequireMinimal);
889                     CScriptNum bn2(stacktop(-1), fRequireMinimal);
890                     CScriptNum bn(0);
891                     switch (opcode)
892                     {
893                     case OP_ADD:
894                         bn = bn1 + bn2;
895                         break;
896 
897                     case OP_SUB:
898                         bn = bn1 - bn2;
899                         break;
900 
901                     case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
902                     case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
903                     case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
904                     case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
905                     case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
906                     case OP_LESSTHAN:            bn = (bn1 < bn2); break;
907                     case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
908                     case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
909                     case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
910                     case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
911                     case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
912                     default:                     assert(!"invalid opcode"); break;
913                     }
914                     popstack(stack);
915                     popstack(stack);
916                     stack.push_back(bn.getvch());
917 
918                     if (opcode == OP_NUMEQUALVERIFY)
919                     {
920                         if (CastToBool(stacktop(-1)))
921                             popstack(stack);
922                         else
923                             return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
924                     }
925                 }
926                 break;
927 
928                 case OP_WITHIN:
929                 {
930                     // (x min max -- out)
931                     if (stack.size() < 3)
932                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
933                     CScriptNum bn1(stacktop(-3), fRequireMinimal);
934                     CScriptNum bn2(stacktop(-2), fRequireMinimal);
935                     CScriptNum bn3(stacktop(-1), fRequireMinimal);
936                     bool fValue = (bn2 <= bn1 && bn1 < bn3);
937                     popstack(stack);
938                     popstack(stack);
939                     popstack(stack);
940                     stack.push_back(fValue ? vchTrue : vchFalse);
941                 }
942                 break;
943 
944 
945                 //
946                 // Crypto
947                 //
948                 case OP_RIPEMD160:
949                 case OP_SHA1:
950                 case OP_SHA256:
951                 case OP_HASH160:
952                 case OP_HASH256:
953                 {
954                     // (in -- hash)
955                     if (stack.size() < 1)
956                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
957                     valtype& vch = stacktop(-1);
958                     valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
959                     if (opcode == OP_RIPEMD160)
960                         CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
961                     else if (opcode == OP_SHA1)
962                         CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
963                     else if (opcode == OP_SHA256)
964                         CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
965                     else if (opcode == OP_HASH160)
966                         CHash160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
967                     else if (opcode == OP_HASH256)
968                         CHash256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
969                     popstack(stack);
970                     stack.push_back(vchHash);
971                 }
972                 break;
973 
974                 case OP_CODESEPARATOR:
975                 {
976                     // If SCRIPT_VERIFY_CONST_SCRIPTCODE flag is set, use of OP_CODESEPARATOR is rejected in pre-segwit
977                     // script, even in an unexecuted branch (this is checked above the opcode case statement).
978 
979                     // Hash starts after the code separator
980                     pbegincodehash = pc;
981                 }
982                 break;
983 
984                 case OP_CHECKSIG:
985                 case OP_CHECKSIGVERIFY:
986                 {
987                     // (sig pubkey -- bool)
988                     if (stack.size() < 2)
989                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
990 
991                     valtype& vchSig    = stacktop(-2);
992                     valtype& vchPubKey = stacktop(-1);
993 
994                     // Subset of script starting at the most recent codeseparator
995                     CScript scriptCode(pbegincodehash, pend);
996 
997                     // Drop the signature in pre-segwit scripts but not segwit scripts
998                     if (sigversion == SigVersion::BASE) {
999                         int found = FindAndDelete(scriptCode, CScript() << vchSig);
1000                         if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
1001                             return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
1002                     }
1003 
1004                     if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
1005                         //serror is set
1006                         return false;
1007                     }
1008                     bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
1009 
1010                     if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
1011                         return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
1012 
1013                     popstack(stack);
1014                     popstack(stack);
1015                     stack.push_back(fSuccess ? vchTrue : vchFalse);
1016                     if (opcode == OP_CHECKSIGVERIFY)
1017                     {
1018                         if (fSuccess)
1019                             popstack(stack);
1020                         else
1021                             return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
1022                     }
1023                 }
1024                 break;
1025 
1026                 case OP_CHECKMULTISIG:
1027                 case OP_CHECKMULTISIGVERIFY:
1028                 {
1029                     // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1030 
1031                     int i = 1;
1032                     if ((int)stack.size() < i)
1033                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1034 
1035                     int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1036                     if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
1037                         return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
1038                     nOpCount += nKeysCount;
1039                     if (nOpCount > MAX_OPS_PER_SCRIPT)
1040                         return set_error(serror, SCRIPT_ERR_OP_COUNT);
1041                     int ikey = ++i;
1042                     // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
1043                     // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
1044                     int ikey2 = nKeysCount + 2;
1045                     i += nKeysCount;
1046                     if ((int)stack.size() < i)
1047                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1048 
1049                     int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1050                     if (nSigsCount < 0 || nSigsCount > nKeysCount)
1051                         return set_error(serror, SCRIPT_ERR_SIG_COUNT);
1052                     int isig = ++i;
1053                     i += nSigsCount;
1054                     if ((int)stack.size() < i)
1055                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1056 
1057                     // Subset of script starting at the most recent codeseparator
1058                     CScript scriptCode(pbegincodehash, pend);
1059 
1060                     // Drop the signature in pre-segwit scripts but not segwit scripts
1061                     for (int k = 0; k < nSigsCount; k++)
1062                     {
1063                         valtype& vchSig = stacktop(-isig-k);
1064                         if (sigversion == SigVersion::BASE) {
1065                             int found = FindAndDelete(scriptCode, CScript() << vchSig);
1066                             if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
1067                                 return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
1068                         }
1069                     }
1070 
1071                     bool fSuccess = true;
1072                     while (fSuccess && nSigsCount > 0)
1073                     {
1074                         valtype& vchSig    = stacktop(-isig);
1075                         valtype& vchPubKey = stacktop(-ikey);
1076 
1077                         // Note how this makes the exact order of pubkey/signature evaluation
1078                         // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
1079                         // See the script_(in)valid tests for details.
1080                         if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
1081                             // serror is set
1082                             return false;
1083                         }
1084 
1085                         // Check signature
1086                         bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
1087 
1088                         if (fOk) {
1089                             isig++;
1090                             nSigsCount--;
1091                         }
1092                         ikey++;
1093                         nKeysCount--;
1094 
1095                         // If there are more signatures left than keys left,
1096                         // then too many signatures have failed. Exit early,
1097                         // without checking any further signatures.
1098                         if (nSigsCount > nKeysCount)
1099                             fSuccess = false;
1100                     }
1101 
1102                     // Clean up stack of actual arguments
1103                     while (i-- > 1) {
1104                         // If the operation failed, we require that all signatures must be empty vector
1105                         if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
1106                             return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
1107                         if (ikey2 > 0)
1108                             ikey2--;
1109                         popstack(stack);
1110                     }
1111 
1112                     // A bug causes CHECKMULTISIG to consume one extra argument
1113                     // whose contents were not checked in any way.
1114                     //
1115                     // Unfortunately this is a potential source of mutability,
1116                     // so optionally verify it is exactly equal to zero prior
1117                     // to removing it from the stack.
1118                     if (stack.size() < 1)
1119                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1120                     if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1121                         return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1122                     popstack(stack);
1123 
1124                     stack.push_back(fSuccess ? vchTrue : vchFalse);
1125 
1126                     if (opcode == OP_CHECKMULTISIGVERIFY)
1127                     {
1128                         if (fSuccess)
1129                             popstack(stack);
1130                         else
1131                             return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1132                     }
1133                 }
1134                 break;
1135 
1136                 //////////////////////////////////////////////////////// qtum
1137                 case OP_SENDER:
1138                 {
1139                     if(!(flags & SCRIPT_OUTPUT_SENDER))
1140                         return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1141                 }
1142                 break;
1143                 case OP_SPEND:
1144                 {
1145                     return true; // temp
1146                 }
1147                 break;
1148                 case OP_CREATE:
1149                 case OP_CALL:
1150                 {
1151                     valtype scriptRest(pc - 1, pend);
1152                     stack.push_back(scriptRest);
1153                     return true; // temp
1154                 }
1155                 break;
1156                 ////////////////////////////////////////////////////////
1157 
1158                 default:
1159                     return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1160             }
1161 
1162             // Size limits
1163             if (stack.size() + altstack.size() > MAX_STACK_SIZE)
1164                 return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1165         }
1166     }
1167     catch (...)
1168     {
1169         return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1170     }
1171 
1172     if (!vfExec.empty())
1173         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1174 
1175     return set_success(serror);
1176 }
1177 
1178 namespace {
1179 
1180 /**
1181  * Wrapper that serializes like CTransaction, but with the modifications
1182  *  required for the signature hash done in-place
1183  */
1184 template <class T>
1185 class CTransactionSignatureSerializer
1186 {
1187 private:
1188     const T& txTo;             //!< reference to the spending transaction (the one being serialized)
1189     const CScript& scriptCode; //!< output script being consumed
1190     const unsigned int nIn;    //!< input index of txTo being signed
1191     const bool fAnyoneCanPay;  //!< whether the hashtype has the SIGHASH_ANYONECANPAY flag set
1192     const bool fHashSingle;    //!< whether the hashtype is SIGHASH_SINGLE
1193     const bool fHashNone;      //!< whether the hashtype is SIGHASH_NONE
1194 
1195 public:
CTransactionSignatureSerializer(const T & txToIn,const CScript & scriptCodeIn,unsigned int nInIn,int nHashTypeIn)1196     CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1197         txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1198         fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1199         fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1200         fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1201 
1202     /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1203     template<typename S>
SerializeScriptCode(S & s) const1204     void SerializeScriptCode(S &s) const {
1205         CScript::const_iterator it = scriptCode.begin();
1206         CScript::const_iterator itBegin = it;
1207         opcodetype opcode;
1208         unsigned int nCodeSeparators = 0;
1209         while (scriptCode.GetOp(it, opcode)) {
1210             if (opcode == OP_CODESEPARATOR)
1211                 nCodeSeparators++;
1212         }
1213         ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1214         it = itBegin;
1215         while (scriptCode.GetOp(it, opcode)) {
1216             if (opcode == OP_CODESEPARATOR) {
1217                 s.write((char*)&itBegin[0], it-itBegin-1);
1218                 itBegin = it;
1219             }
1220         }
1221         if (itBegin != scriptCode.end())
1222             s.write((char*)&itBegin[0], it-itBegin);
1223     }
1224 
1225     /** Serialize an input of txTo */
1226     template<typename S>
SerializeInput(S & s,unsigned int nInput) const1227     void SerializeInput(S &s, unsigned int nInput) const {
1228         // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1229         if (fAnyoneCanPay)
1230             nInput = nIn;
1231         // Serialize the prevout
1232         ::Serialize(s, txTo.vin[nInput].prevout);
1233         // Serialize the script
1234         if (nInput != nIn)
1235             // Blank out other inputs' signatures
1236             ::Serialize(s, CScript());
1237         else
1238             SerializeScriptCode(s);
1239         // Serialize the nSequence
1240         if (nInput != nIn && (fHashSingle || fHashNone))
1241             // let the others update at will
1242             ::Serialize(s, (int)0);
1243         else
1244             ::Serialize(s, txTo.vin[nInput].nSequence);
1245     }
1246 
1247     /** Serialize an output of txTo */
1248     template<typename S>
SerializeOutput(S & s,unsigned int nOutput) const1249     void SerializeOutput(S &s, unsigned int nOutput) const {
1250         if (fHashSingle && nOutput != nIn)
1251             // Do not lock-in the txout payee at other indices as txin
1252             ::Serialize(s, CTxOut());
1253         else
1254             ::Serialize(s, txTo.vout[nOutput]);
1255     }
1256 
1257     /** Serialize txTo */
1258     template<typename S>
Serialize(S & s) const1259     void Serialize(S &s) const {
1260         // Serialize nVersion
1261         ::Serialize(s, txTo.nVersion);
1262         // Serialize vin
1263         unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1264         ::WriteCompactSize(s, nInputs);
1265         for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1266              SerializeInput(s, nInput);
1267         // Serialize vout
1268         unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1269         ::WriteCompactSize(s, nOutputs);
1270         for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1271              SerializeOutput(s, nOutput);
1272         // Serialize nLockTime
1273         ::Serialize(s, txTo.nLockTime);
1274     }
1275 };
1276 
1277 template <class T>
GetPrevoutHash(const T & txTo)1278 uint256 GetPrevoutHash(const T& txTo)
1279 {
1280     CHashWriter ss(SER_GETHASH, 0);
1281     for (const auto& txin : txTo.vin) {
1282         ss << txin.prevout;
1283     }
1284     return ss.GetHash();
1285 }
1286 
1287 template <class T>
GetSequenceHash(const T & txTo)1288 uint256 GetSequenceHash(const T& txTo)
1289 {
1290     CHashWriter ss(SER_GETHASH, 0);
1291     for (const auto& txin : txTo.vin) {
1292         ss << txin.nSequence;
1293     }
1294     return ss.GetHash();
1295 }
1296 
1297 template <class T>
GetFirstPrevoutHash(const T & txTo)1298 uint256 GetFirstPrevoutHash(const T& txTo)
1299 {
1300     CHashWriter ss(SER_GETHASH, 0);
1301     ss << txTo.vin[0].prevout;
1302     return ss.GetHash();
1303 }
1304 
1305 template <class T>
GetFirstSequenceHash(const T & txTo)1306 uint256 GetFirstSequenceHash(const T& txTo)
1307 {
1308     CHashWriter ss(SER_GETHASH, 0);
1309     ss << txTo.vin[0].nSequence;
1310     return ss.GetHash();
1311 }
1312 
1313 template <class T>
GetOutputsHash(const T & txTo)1314 uint256 GetOutputsHash(const T& txTo)
1315 {
1316     CHashWriter ss(SER_GETHASH, 0);
1317     for (const auto& txout : txTo.vout) {
1318         ss << txout;
1319     }
1320     return ss.GetHash();
1321 }
1322 
GetOutputWithoutSenderSig(const CTxOut & output)1323 CTxOut GetOutputWithoutSenderSig(const CTxOut& output)
1324 {
1325     return CTxOut(output.nValue, output.scriptPubKey.WithoutSenderSig());
1326 }
1327 
1328 template <class T>
GetOutputsOpSenderHash(const T & txTo)1329 uint256 GetOutputsOpSenderHash(const T& txTo)
1330 {
1331     CHashWriter ss(SER_GETHASH, 0);
1332     for (const auto& txout : txTo.vout) {
1333         if(txout.scriptPubKey.HasOpSender())
1334         {
1335             ss << GetOutputWithoutSenderSig(txout);
1336         }
1337         else
1338         {
1339             ss << txout;
1340         }
1341     }
1342     return ss.GetHash();
1343 }
1344 
1345 } // namespace
1346 
1347 template <class T>
PrecomputedTransactionData(const T & txTo)1348 PrecomputedTransactionData::PrecomputedTransactionData(const T& txTo)
1349 {
1350     // Cache is calculated only for transactions with witness or those that have op sender output signature
1351     if (txTo.HasWitness() || txTo.HasOpSender()) {
1352         hashPrevouts = GetPrevoutHash(txTo);
1353         hashSequence = GetSequenceHash(txTo);
1354         hashOutputs = GetOutputsHash(txTo);
1355         if(txTo.HasOpSender())
1356         {
1357             hashOutputsOpSender = GetOutputsOpSenderHash(txTo);
1358         }
1359         ready = true;
1360     }
1361 }
1362 
1363 // explicit instantiation
1364 template PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo);
1365 template PrecomputedTransactionData::PrecomputedTransactionData(const CMutableTransaction& txTo);
1366 
1367 template <class T>
SignatureHashOutput(const CScript & scriptCode,const T & txTo,unsigned int nOut,int nHashType,const CAmount & amount,SigVersion sigversion,const PrecomputedTransactionData * cache)1368 uint256 SignatureHashOutput(const CScript& scriptCode, const T& txTo, unsigned int nOut, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1369 {
1370     assert(nOut < txTo.vout.size());
1371 
1372     uint256 hashPrevouts;
1373     uint256 hashSequence;
1374     uint256 hashOutputs;
1375     const bool cacheready = cache && cache->ready;
1376 
1377     if (nHashType & SIGHASH_ANYONECANPAY) {
1378         assert(0 < txTo.vin.size());
1379         hashPrevouts = GetFirstPrevoutHash(txTo);
1380         hashSequence = GetFirstSequenceHash(txTo);
1381     }
1382 
1383     if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1384         hashPrevouts = cacheready ? cache->hashPrevouts : GetPrevoutHash(txTo);
1385     }
1386 
1387     if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1388         hashSequence = cacheready ? cache->hashSequence : GetSequenceHash(txTo);
1389     }
1390 
1391 
1392     if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1393         hashOutputs = cacheready ? cache->hashOutputsOpSender : GetOutputsOpSenderHash(txTo);
1394     } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nOut < txTo.vout.size()) {
1395         CHashWriter ss(SER_GETHASH, 0);
1396         ss << GetOutputWithoutSenderSig(txTo.vout[nOut]);
1397         hashOutputs = ss.GetHash();
1398     }
1399 
1400     CHashWriter ss(SER_GETHASH, 0);
1401 
1402     // Version
1403     ss << txTo.nVersion;
1404     // Input prevouts/nSequence (none/first/all, depending on flags)
1405     ss << hashPrevouts;
1406     ss << hashSequence;
1407     // The output being signed
1408     ss << GetOutputWithoutSenderSig(txTo.vout[nOut]);
1409     ss << scriptCode;
1410     ss << amount;
1411     // Outputs (none/one/all, depending on flags)
1412     ss << hashOutputs;
1413     // Locktime
1414     ss << txTo.nLockTime;
1415     // Sighash type
1416     ss << nHashType;
1417 
1418     return ss.GetHash();
1419 }
1420 
1421 template <class T>
SignatureHash(const CScript & scriptCode,const T & txTo,unsigned int nIn,int nHashType,const CAmount & amount,SigVersion sigversion,const PrecomputedTransactionData * cache)1422 uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1423 {
1424     assert(nIn < txTo.vin.size());
1425 
1426     if (sigversion == SigVersion::WITNESS_V0) {
1427         uint256 hashPrevouts;
1428         uint256 hashSequence;
1429         uint256 hashOutputs;
1430         const bool cacheready = cache && cache->ready;
1431 
1432         if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1433             hashPrevouts = cacheready ? cache->hashPrevouts : GetPrevoutHash(txTo);
1434         }
1435 
1436         if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1437             hashSequence = cacheready ? cache->hashSequence : GetSequenceHash(txTo);
1438         }
1439 
1440 
1441         if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1442             hashOutputs = cacheready ? cache->hashOutputs : GetOutputsHash(txTo);
1443         } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
1444             CHashWriter ss(SER_GETHASH, 0);
1445             ss << txTo.vout[nIn];
1446             hashOutputs = ss.GetHash();
1447         }
1448 
1449         CHashWriter ss(SER_GETHASH, 0);
1450         // Version
1451         ss << txTo.nVersion;
1452         // Input prevouts/nSequence (none/all, depending on flags)
1453         ss << hashPrevouts;
1454         ss << hashSequence;
1455         // The input being signed (replacing the scriptSig with scriptCode + amount)
1456         // The prevout may already be contained in hashPrevout, and the nSequence
1457         // may already be contain in hashSequence.
1458         ss << txTo.vin[nIn].prevout;
1459         ss << scriptCode;
1460         ss << amount;
1461         ss << txTo.vin[nIn].nSequence;
1462         // Outputs (none/one/all, depending on flags)
1463         ss << hashOutputs;
1464         // Locktime
1465         ss << txTo.nLockTime;
1466         // Sighash type
1467         ss << nHashType;
1468 
1469         return ss.GetHash();
1470     }
1471 
1472     // Check for invalid use of SIGHASH_SINGLE
1473     if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1474         if (nIn >= txTo.vout.size()) {
1475             //  nOut out of range
1476             return UINT256_ONE();
1477         }
1478     }
1479 
1480     // Wrapper to serialize only the necessary parts of the transaction being signed
1481     CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
1482 
1483     // Serialize and hash
1484     CHashWriter ss(SER_GETHASH, 0);
1485     ss << txTmp << nHashType;
1486     return ss.GetHash();
1487 }
1488 
1489 template <class T>
VerifySignature(const std::vector<unsigned char> & vchSig,const CPubKey & pubkey,const uint256 & sighash) const1490 bool GenericTransactionSignatureChecker<T>::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1491 {
1492     return pubkey.Verify(sighash, vchSig);
1493 }
1494 
1495 template <class T>
CheckSig(const std::vector<unsigned char> & vchSigIn,const std::vector<unsigned char> & vchPubKey,const CScript & scriptCode,SigVersion sigversion) const1496 bool GenericTransactionSignatureChecker<T>::CheckSig(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1497 {
1498     CPubKey pubkey(vchPubKey);
1499     if (!pubkey.IsValid())
1500         return false;
1501 
1502     // Hash type is one byte tacked on to the end of the signature
1503     std::vector<unsigned char> vchSig(vchSigIn);
1504     if (vchSig.empty())
1505         return false;
1506     int nHashType = vchSig.back();
1507     vchSig.pop_back();
1508 
1509     uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
1510 
1511     if (!VerifySignature(vchSig, pubkey, sighash))
1512         return false;
1513 
1514     return true;
1515 }
1516 
1517 template <class T>
CheckLockTime(const CScriptNum & nLockTime) const1518 bool GenericTransactionSignatureChecker<T>::CheckLockTime(const CScriptNum& nLockTime) const
1519 {
1520     // There are two kinds of nLockTime: lock-by-blockheight
1521     // and lock-by-blocktime, distinguished by whether
1522     // nLockTime < LOCKTIME_THRESHOLD.
1523     //
1524     // We want to compare apples to apples, so fail the script
1525     // unless the type of nLockTime being tested is the same as
1526     // the nLockTime in the transaction.
1527     if (!(
1528         (txTo->nLockTime <  LOCKTIME_THRESHOLD && nLockTime <  LOCKTIME_THRESHOLD) ||
1529         (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1530     ))
1531         return false;
1532 
1533     // Now that we know we're comparing apples-to-apples, the
1534     // comparison is a simple numeric one.
1535     if (nLockTime > (int64_t)txTo->nLockTime)
1536         return false;
1537 
1538     // Finally the nLockTime feature can be disabled and thus
1539     // CHECKLOCKTIMEVERIFY bypassed if every txin has been
1540     // finalized by setting nSequence to maxint. The
1541     // transaction would be allowed into the blockchain, making
1542     // the opcode ineffective.
1543     //
1544     // Testing if this vin is not final is sufficient to
1545     // prevent this condition. Alternatively we could test all
1546     // inputs, but testing just this input minimizes the data
1547     // required to prove correct CHECKLOCKTIMEVERIFY execution.
1548     if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1549         return false;
1550 
1551     return true;
1552 }
1553 
1554 template <class T>
CheckSequence(const CScriptNum & nSequence) const1555 bool GenericTransactionSignatureChecker<T>::CheckSequence(const CScriptNum& nSequence) const
1556 {
1557     // Relative lock times are supported by comparing the passed
1558     // in operand to the sequence number of the input.
1559     const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1560 
1561     // Fail if the transaction's version number is not set high
1562     // enough to trigger BIP 68 rules.
1563     if (static_cast<uint32_t>(txTo->nVersion) < 2)
1564         return false;
1565 
1566     // Sequence numbers with their most significant bit set are not
1567     // consensus constrained. Testing that the transaction's sequence
1568     // number do not have this bit set prevents using this property
1569     // to get around a CHECKSEQUENCEVERIFY check.
1570     if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1571         return false;
1572 
1573     // Mask off any bits that do not have consensus-enforced meaning
1574     // before doing the integer comparisons
1575     const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1576     const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1577     const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1578 
1579     // There are two kinds of nSequence: lock-by-blockheight
1580     // and lock-by-blocktime, distinguished by whether
1581     // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1582     //
1583     // We want to compare apples to apples, so fail the script
1584     // unless the type of nSequenceMasked being tested is the same as
1585     // the nSequenceMasked in the transaction.
1586     if (!(
1587         (txToSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1588         (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1589     )) {
1590         return false;
1591     }
1592 
1593     // Now that we know we're comparing apples-to-apples, the
1594     // comparison is a simple numeric one.
1595     if (nSequenceMasked > txToSequenceMasked)
1596         return false;
1597 
1598     return true;
1599 }
1600 
1601 // explicit instantiation
1602 template class GenericTransactionSignatureChecker<CTransaction>;
1603 template class GenericTransactionSignatureChecker<CMutableTransaction>;
1604 
1605 template <class T>
VerifySignature(const std::vector<unsigned char> & vchSig,const CPubKey & pubkey,const uint256 & sighash) const1606 bool GenericTransactionSignatureOutputChecker<T>::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1607 {
1608     return pubkey.Verify(sighash, vchSig);
1609 }
1610 
1611 template <class T>
CheckSig(const std::vector<unsigned char> & vchSigIn,const std::vector<unsigned char> & vchPubKey,const CScript & scriptCode,SigVersion sigversion) const1612 bool GenericTransactionSignatureOutputChecker<T>::CheckSig(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1613 {
1614     CPubKey pubkey(vchPubKey);
1615     if (!pubkey.IsValid())
1616         return false;
1617 
1618     // Hash type is one byte tacked on to the end of the signature
1619     std::vector<unsigned char> vchSig(vchSigIn);
1620     if (vchSig.empty())
1621         return false;
1622     int nHashType = vchSig.back();
1623     vchSig.pop_back();
1624 
1625     uint256 sighash = SignatureHashOutput(scriptCode, *txTo, nOut, nHashType, amount, sigversion, this->txdata);
1626 
1627     if (!VerifySignature(vchSig, pubkey, sighash))
1628         return false;
1629 
1630     return true;
1631 }
1632 
1633 // explicit instantiation
1634 template class GenericTransactionSignatureOutputChecker<CTransaction>;
1635 template class GenericTransactionSignatureOutputChecker<CMutableTransaction>;
1636 
ExecuteWitnessScript(const Span<const valtype> & stack_span,const CScript & scriptPubKey,unsigned int flags,SigVersion sigversion,const BaseSignatureChecker & checker,ScriptError * serror)1637 static bool ExecuteWitnessScript(const Span<const valtype>& stack_span, const CScript& scriptPubKey, unsigned int flags, SigVersion sigversion, const BaseSignatureChecker& checker, ScriptError* serror)
1638 {
1639     std::vector<valtype> stack{stack_span.begin(), stack_span.end()};
1640 
1641     // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
1642     for (const valtype& elem : stack) {
1643         if (elem.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
1644     }
1645 
1646     // Run the script interpreter.
1647     if (!EvalScript(stack, scriptPubKey, flags, checker, sigversion, serror)) return false;
1648 
1649     // Scripts inside witness implicitly require cleanstack behaviour
1650     if (stack.size() != 1) return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1651     if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1652     return true;
1653 }
1654 
VerifyWitnessProgram(const CScriptWitness & witness,int witversion,const std::vector<unsigned char> & program,unsigned int flags,const BaseSignatureChecker & checker,ScriptError * serror)1655 static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1656 {
1657     CScript scriptPubKey;
1658     Span<const valtype> stack = MakeSpan(witness.stack);
1659 
1660     if (witversion == 0) {
1661         if (program.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
1662             // Version 0 segregated witness program: SHA256(CScript) inside the program, CScript + inputs in witness
1663             if (stack.size() == 0) {
1664                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1665             }
1666             const valtype& script_bytes = SpanPopBack(stack);
1667             scriptPubKey = CScript(script_bytes.begin(), script_bytes.end());
1668             uint256 hashScriptPubKey;
1669             CSHA256().Write(&scriptPubKey[0], scriptPubKey.size()).Finalize(hashScriptPubKey.begin());
1670             if (memcmp(hashScriptPubKey.begin(), program.data(), 32)) {
1671                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1672             }
1673             return ExecuteWitnessScript(stack, scriptPubKey, flags, SigVersion::WITNESS_V0, checker, serror);
1674         } else if (program.size() == WITNESS_V0_KEYHASH_SIZE) {
1675             // Special case for pay-to-pubkeyhash; signature + pubkey in witness
1676             if (stack.size() != 2) {
1677                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1678             }
1679             scriptPubKey << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
1680             return ExecuteWitnessScript(stack, scriptPubKey, flags, SigVersion::WITNESS_V0, checker, serror);
1681         } else {
1682             return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
1683         }
1684     } else {
1685         if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
1686             return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
1687         }
1688         // Higher version witness scripts return true for future softfork compatibility
1689         return true;
1690     }
1691     // There is intentionally no return statement here, to be able to use "control reaches end of non-void function" warnings to detect gaps in the logic above.
1692 }
1693 
VerifyScript(const CScript & scriptSig,const CScript & scriptPubKey,const CScriptWitness * witness,unsigned int flags,const BaseSignatureChecker & checker,ScriptError * serror)1694 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1695 {
1696     static const CScriptWitness emptyWitness;
1697     if (witness == nullptr) {
1698         witness = &emptyWitness;
1699     }
1700     bool hadWitness = false;
1701 
1702     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1703 
1704     if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1705         return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1706     }
1707 
1708     // scriptSig and scriptPubKey must be evaluated sequentially on the same stack
1709     // rather than being simply concatenated (see CVE-2010-5141)
1710     std::vector<std::vector<unsigned char> > stack, stackCopy;
1711     if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
1712         // serror is set
1713         return false;
1714     if (flags & SCRIPT_VERIFY_P2SH)
1715         stackCopy = stack;
1716     if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
1717         // serror is set
1718         return false;
1719     if (stack.empty())
1720         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1721     if (CastToBool(stack.back()) == false)
1722         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1723 
1724     // Bare witness programs
1725     int witnessversion;
1726     std::vector<unsigned char> witnessprogram;
1727     if (flags & SCRIPT_VERIFY_WITNESS) {
1728         if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1729             hadWitness = true;
1730             if (scriptSig.size() != 0) {
1731                 // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
1732                 return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
1733             }
1734             if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
1735                 return false;
1736             }
1737             // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1738             // for witness programs.
1739             stack.resize(1);
1740         }
1741     }
1742 
1743     // Additional validation for spend-to-script-hash transactions:
1744     if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1745     {
1746         // scriptSig must be literals-only or validation fails
1747         if (!scriptSig.IsPushOnly())
1748             return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1749 
1750         // Restore stack.
1751         swap(stack, stackCopy);
1752 
1753         // stack cannot be empty here, because if it was the
1754         // P2SH  HASH <> EQUAL  scriptPubKey would be evaluated with
1755         // an empty stack and the EvalScript above would return false.
1756         assert(!stack.empty());
1757 
1758         const valtype& pubKeySerialized = stack.back();
1759         CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1760         popstack(stack);
1761 
1762         if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
1763             // serror is set
1764             return false;
1765         if (stack.empty())
1766             return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1767         if (!CastToBool(stack.back()))
1768             return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1769 
1770         // P2SH witness program
1771         if (flags & SCRIPT_VERIFY_WITNESS) {
1772             if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
1773                 hadWitness = true;
1774                 if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
1775                     // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
1776                     // reintroduce malleability.
1777                     return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
1778                 }
1779                 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
1780                     return false;
1781                 }
1782                 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1783                 // for witness programs.
1784                 stack.resize(1);
1785             }
1786         }
1787     }
1788 
1789     // The CLEANSTACK check is only performed after potential P2SH evaluation,
1790     // as the non-P2SH evaluation of a P2SH script will obviously not result in
1791     // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
1792     if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
1793         // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
1794         // would be possible, which is not a softfork (and P2SH should be one).
1795         assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1796         assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
1797         if (stack.size() != 1) {
1798             return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1799         }
1800     }
1801 
1802     if (flags & SCRIPT_VERIFY_WITNESS) {
1803         // We can't check for correct unexpected witness data if P2SH was off, so require
1804         // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
1805         // possible, which is not a softfork.
1806         assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1807         if (!hadWitness && !witness->IsNull()) {
1808             return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
1809         }
1810     }
1811 
1812     return set_success(serror);
1813 }
1814 
WitnessSigOps(int witversion,const std::vector<unsigned char> & witprogram,const CScriptWitness & witness)1815 size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness)
1816 {
1817     if (witversion == 0) {
1818         if (witprogram.size() == WITNESS_V0_KEYHASH_SIZE)
1819             return 1;
1820 
1821         if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.stack.size() > 0) {
1822             CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
1823             return subscript.GetSigOpCount(true);
1824         }
1825     }
1826 
1827     // Future flags may be implemented here.
1828     return 0;
1829 }
1830 
CountWitnessSigOps(const CScript & scriptSig,const CScript & scriptPubKey,const CScriptWitness * witness,unsigned int flags)1831 size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags)
1832 {
1833     static const CScriptWitness witnessEmpty;
1834 
1835     if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
1836         return 0;
1837     }
1838     assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1839 
1840     int witnessversion;
1841     std::vector<unsigned char> witnessprogram;
1842     if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1843         return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
1844     }
1845 
1846     if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
1847         CScript::const_iterator pc = scriptSig.begin();
1848         std::vector<unsigned char> data;
1849         while (pc < scriptSig.end()) {
1850             opcodetype opcode;
1851             scriptSig.GetOp(pc, opcode, data);
1852         }
1853         CScript subscript(data.begin(), data.end());
1854         if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
1855             return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
1856         }
1857     }
1858 
1859     return 0;
1860 }
1861