1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 
set_success(ScriptError * ret)19 inline bool set_success(ScriptError* ret)
20 {
21     if (ret)
22         *ret = SCRIPT_ERR_OK;
23     return true;
24 }
25 
set_error(ScriptError * ret,const ScriptError serror)26 inline bool set_error(ScriptError* ret, const ScriptError serror)
27 {
28     if (ret)
29         *ret = serror;
30     return false;
31 }
32 
33 } // namespace
34 
CastToBool(const valtype & vch)35 bool CastToBool(const valtype& vch)
36 {
37     for (unsigned int i = 0; i < vch.size(); i++)
38     {
39         if (vch[i] != 0)
40         {
41             // Can be negative zero
42             if (i == vch.size()-1 && vch[i] == 0x80)
43                 return false;
44             return true;
45         }
46     }
47     return false;
48 }
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)))
popstack(std::vector<valtype> & stack)56 static inline void popstack(std::vector<valtype>& stack)
57 {
58     if (stack.empty())
59         throw std::runtime_error("popstack(): stack empty");
60     stack.pop_back();
61 }
62 
IsCompressedOrUncompressedPubKey(const valtype & vchPubKey)63 bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
64     if (vchPubKey.size() < CPubKey::COMPRESSED_SIZE) {
65         //  Non-canonical public key: too short
66         return false;
67     }
68     if (vchPubKey[0] == 0x04) {
69         if (vchPubKey.size() != CPubKey::SIZE) {
70             //  Non-canonical public key: invalid length for uncompressed key
71             return false;
72         }
73     } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
74         if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
75             //  Non-canonical public key: invalid length for compressed key
76             return false;
77         }
78     } else {
79         //  Non-canonical public key: neither compressed nor uncompressed
80         return false;
81     }
82     return true;
83 }
84 
IsCompressedPubKey(const valtype & vchPubKey)85 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  */
IsValidSignatureEncoding(const std::vector<unsigned char> & sig)107 bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
108     // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
109     // * total-length: 1-byte length descriptor of everything that follows,
110     //   excluding the sighash byte.
111     // * R-length: 1-byte length descriptor of the R value that follows.
112     // * R: arbitrary-length big-endian encoded R value. It must use the shortest
113     //   possible encoding for a positive 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     if (sig.size() < 9) return false;
122     if (sig.size() > 73) return false;
123 
124     // A signature is of type 0x30 (compound).
125     if (sig[0] != 0x30) return false;
126 
127     // Make sure the length covers the entire signature.
128     if (sig[1] != sig.size() - 3) return false;
129 
130     // Extract the length of the R element.
131     unsigned int lenR = sig[3];
132 
133     // Make sure the length of the S element is still inside the signature.
134     if (5 + lenR >= sig.size()) return false;
135 
136     // Extract the length of the S element.
137     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     if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
142 
143     // Check whether the R element is an integer.
144     if (sig[2] != 0x02) return false;
145 
146     // Zero-length integers are not allowed for R.
147     if (lenR == 0) return false;
148 
149     // Negative numbers are not allowed for R.
150     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     if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
155 
156     // Check whether the S element is an integer.
157     if (sig[lenR + 4] != 0x02) return false;
158 
159     // Zero-length integers are not allowed for S.
160     if (lenS == 0) return false;
161 
162     // Negative numbers are not allowed for S.
163     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     if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
168 
169     return true;
170 }
171 
IsLowDERSignature(const valtype & vchSig,ScriptError * serror)172 bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
173     if (!IsValidSignatureEncoding(vchSig)) {
174         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     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     if (!CPubKey::CheckLowS(vchSigCopy)) {
184         return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
185     }
186     return true;
187 }
188 
IsDefinedHashtypeSignature(const valtype & vchSig)189 bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
190     if (vchSig.size() == 0) {
191         return false;
192     }
193     unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
194     if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
195         return false;
196 
197     return true;
198 }
199 
CheckSignatureEncoding(const std::vector<unsigned char> & vchSig,unsigned int flags,ScriptError * serror)200 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     if (vchSig.size() == 0) {
204         return true;
205     }
206     if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
207         return set_error(serror, SCRIPT_ERR_SIG_DER);
208     } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
209         // serror is set
210         return false;
211     } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
212         return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
213     }
214     return true;
215 }
216 
CheckPubKeyEncoding(const valtype & vchPubKey,unsigned int flags,const SigVersion & sigversion,ScriptError * serror)217 bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
218     if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
219         return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
220     }
221     // Only compressed keys are accepted in segwit
222     if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SigVersion::WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
223         return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
224     }
225     return true;
226 }
227 
CheckMinimalPush(const valtype & data,opcodetype opcode)228 bool CheckMinimalPush(const valtype& data, opcodetype opcode) {
229     // Excludes OP_1NEGATE, OP_1-16 since they are by definition minimal
230     assert(0 <= opcode && opcode <= OP_PUSHDATA4);
231     if (data.size() == 0) {
232         // Should have used OP_0.
233         return opcode == OP_0;
234     } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
235         // Should have used OP_1 .. OP_16.
236         return false;
237     } else if (data.size() == 1 && data[0] == 0x81) {
238         // Should have used OP_1NEGATE.
239         return false;
240     } else if (data.size() <= 75) {
241         // Must have used a direct push (opcode indicating number of bytes pushed + those bytes).
242         return opcode == data.size();
243     } else if (data.size() <= 255) {
244         // Must have used OP_PUSHDATA.
245         return opcode == OP_PUSHDATA1;
246     } else if (data.size() <= 65535) {
247         // Must have used OP_PUSHDATA2.
248         return opcode == OP_PUSHDATA2;
249     }
250     return true;
251 }
252 
FindAndDelete(CScript & script,const CScript & b)253 int FindAndDelete(CScript& script, const CScript& b)
254 {
255     int nFound = 0;
256     if (b.empty())
257         return nFound;
258     CScript result;
259     CScript::const_iterator pc = script.begin(), pc2 = script.begin(), end = script.end();
260     opcodetype opcode;
261     do
262     {
263         result.insert(result.end(), pc2, pc);
264         while (static_cast<size_t>(end - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
265         {
266             pc = pc + b.size();
267             ++nFound;
268         }
269         pc2 = pc;
270     }
271     while (script.GetOp(pc, opcode));
272 
273     if (nFound > 0) {
274         result.insert(result.end(), pc2, end);
275         script = std::move(result);
276     }
277 
278     return nFound;
279 }
280 
281 namespace {
282 /** A data type to abstract out the condition stack during script execution.
283  *
284  * Conceptually it acts like a vector of booleans, one for each level of nested
285  * IF/THEN/ELSE, indicating whether we're in the active or inactive branch of
286  * each.
287  *
288  * The elements on the stack cannot be observed individually; we only need to
289  * expose whether the stack is empty and whether or not any false values are
290  * present at all. To implement OP_ELSE, a toggle_top modifier is added, which
291  * flips the last value without returning it.
292  *
293  * This uses an optimized implementation that does not materialize the
294  * actual stack. Instead, it just stores the size of the would-be stack,
295  * and the position of the first false value in it.
296  */
297 class ConditionStack {
298 private:
299     //! A constant for m_first_false_pos to indicate there are no falses.
300     static constexpr uint32_t NO_FALSE = std::numeric_limits<uint32_t>::max();
301 
302     //! The size of the implied stack.
303     uint32_t m_stack_size = 0;
304     //! The position of the first false value on the implied stack, or NO_FALSE if all true.
305     uint32_t m_first_false_pos = NO_FALSE;
306 
307 public:
empty() const308     bool empty() const { return m_stack_size == 0; }
all_true() const309     bool all_true() const { return m_first_false_pos == NO_FALSE; }
push_back(bool f)310     void push_back(bool f)
311     {
312         if (m_first_false_pos == NO_FALSE && !f) {
313             // The stack consists of all true values, and a false is added.
314             // The first false value will appear at the current size.
315             m_first_false_pos = m_stack_size;
316         }
317         ++m_stack_size;
318     }
pop_back()319     void pop_back()
320     {
321         assert(m_stack_size > 0);
322         --m_stack_size;
323         if (m_first_false_pos == m_stack_size) {
324             // When popping off the first false value, everything becomes true.
325             m_first_false_pos = NO_FALSE;
326         }
327     }
toggle_top()328     void toggle_top()
329     {
330         assert(m_stack_size > 0);
331         if (m_first_false_pos == NO_FALSE) {
332             // The current stack is all true values; the first false will be the top.
333             m_first_false_pos = m_stack_size - 1;
334         } else if (m_first_false_pos == m_stack_size - 1) {
335             // The top is the first false value; toggling it will make everything true.
336             m_first_false_pos = NO_FALSE;
337         } else {
338             // There is a false value, but not on top. No action is needed as toggling
339             // anything but the first false value is unobservable.
340         }
341     }
342 };
343 }
344 
EvalChecksigPreTapscript(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)345 static bool EvalChecksigPreTapscript(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)
346 {
347     assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
348 
349     // Subset of script starting at the most recent codeseparator
350     CScript scriptCode(pbegincodehash, pend);
351 
352     // Drop the signature in pre-segwit scripts but not segwit scripts
353     if (sigversion == SigVersion::BASE) {
354         int found = FindAndDelete(scriptCode, CScript() << vchSig);
355         if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
356             return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
357     }
358 
359     if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
360         //serror is set
361         return false;
362     }
363     fSuccess = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
364 
365     if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
366         return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
367 
368     return true;
369 }
370 
EvalChecksigTapscript(const valtype & sig,const valtype & pubkey,ScriptExecutionData & execdata,unsigned int flags,const BaseSignatureChecker & checker,SigVersion sigversion,ScriptError * serror,bool & success)371 static bool EvalChecksigTapscript(const valtype& sig, const valtype& pubkey, ScriptExecutionData& execdata, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& success)
372 {
373     assert(sigversion == SigVersion::TAPSCRIPT);
374 
375     /*
376      *  The following validation sequence is consensus critical. Please note how --
377      *    upgradable public key versions precede other rules;
378      *    the script execution fails when using empty signature with invalid public key;
379      *    the script execution fails when using non-empty invalid signature.
380      */
381     success = !sig.empty();
382     if (success) {
383         // Implement the sigops/witnesssize ratio test.
384         // Passing with an upgradable public key version is also counted.
385         assert(execdata.m_validation_weight_left_init);
386         execdata.m_validation_weight_left -= VALIDATION_WEIGHT_PER_SIGOP_PASSED;
387         if (execdata.m_validation_weight_left < 0) {
388             return set_error(serror, SCRIPT_ERR_TAPSCRIPT_VALIDATION_WEIGHT);
389         }
390     }
391     if (pubkey.size() == 0) {
392         return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
393     } else if (pubkey.size() == 32) {
394         if (success && !checker.CheckSchnorrSignature(sig, pubkey, sigversion, execdata, serror)) {
395             return false; // serror is set
396         }
397     } else {
398         /*
399          *  New public key version softforks should be defined before this `else` block.
400          *  Generally, the new code should not do anything but failing the script execution. To avoid
401          *  consensus bugs, it should not modify any existing values (including `success`).
402          */
403         if ((flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_PUBKEYTYPE) != 0) {
404             return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_PUBKEYTYPE);
405         }
406     }
407 
408     return true;
409 }
410 
411 /** Helper for OP_CHECKSIG, OP_CHECKSIGVERIFY, and (in Tapscript) OP_CHECKSIGADD.
412  *
413  * A return value of false means the script fails entirely. When true is returned, the
414  * success variable indicates whether the signature check itself succeeded.
415  */
EvalChecksig(const valtype & sig,const valtype & pubkey,CScript::const_iterator pbegincodehash,CScript::const_iterator pend,ScriptExecutionData & execdata,unsigned int flags,const BaseSignatureChecker & checker,SigVersion sigversion,ScriptError * serror,bool & success)416 static bool EvalChecksig(const valtype& sig, const valtype& pubkey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, ScriptExecutionData& execdata, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& success)
417 {
418     switch (sigversion) {
419     case SigVersion::BASE:
420     case SigVersion::WITNESS_V0:
421         return EvalChecksigPreTapscript(sig, pubkey, pbegincodehash, pend, flags, checker, sigversion, serror, success);
422     case SigVersion::TAPSCRIPT:
423         return EvalChecksigTapscript(sig, pubkey, execdata, flags, checker, sigversion, serror, success);
424     case SigVersion::TAPROOT:
425         // Key path spending in Taproot has no script, so this is unreachable.
426         break;
427     }
428     assert(false);
429 }
430 
EvalScript(std::vector<std::vector<unsigned char>> & stack,const CScript & script,unsigned int flags,const BaseSignatureChecker & checker,SigVersion sigversion,ScriptExecutionData & execdata,ScriptError * serror)431 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror)
432 {
433     static const CScriptNum bnZero(0);
434     static const CScriptNum bnOne(1);
435     // static const CScriptNum bnFalse(0);
436     // static const CScriptNum bnTrue(1);
437     static const valtype vchFalse(0);
438     // static const valtype vchZero(0);
439     static const valtype vchTrue(1, 1);
440 
441     // sigversion cannot be TAPROOT here, as it admits no script execution.
442     assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0 || sigversion == SigVersion::TAPSCRIPT);
443 
444     CScript::const_iterator pc = script.begin();
445     CScript::const_iterator pend = script.end();
446     CScript::const_iterator pbegincodehash = script.begin();
447     opcodetype opcode;
448     valtype vchPushValue;
449     ConditionStack vfExec;
450     std::vector<valtype> altstack;
451     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
452     if ((sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) && script.size() > MAX_SCRIPT_SIZE) {
453         return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
454     }
455     int nOpCount = 0;
456     bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
457     uint32_t opcode_pos = 0;
458     execdata.m_codeseparator_pos = 0xFFFFFFFFUL;
459     execdata.m_codeseparator_pos_init = true;
460 
461     try
462     {
463         for (; pc < pend; ++opcode_pos) {
464             bool fExec = vfExec.all_true();
465 
466             //
467             // Read instruction
468             //
469             if (!script.GetOp(pc, opcode, vchPushValue))
470                 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
471             if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
472                 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
473 
474             if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) {
475                 // Note how OP_RESERVED does not count towards the opcode limit.
476                 if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT) {
477                     return set_error(serror, SCRIPT_ERR_OP_COUNT);
478                 }
479             }
480 
481             if (opcode == OP_CAT ||
482                 opcode == OP_SUBSTR ||
483                 opcode == OP_LEFT ||
484                 opcode == OP_RIGHT ||
485                 opcode == OP_INVERT ||
486                 opcode == OP_AND ||
487                 opcode == OP_OR ||
488                 opcode == OP_XOR ||
489                 opcode == OP_2MUL ||
490                 opcode == OP_2DIV ||
491                 opcode == OP_MUL ||
492                 opcode == OP_DIV ||
493                 opcode == OP_MOD ||
494                 opcode == OP_LSHIFT ||
495                 opcode == OP_RSHIFT)
496                 return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes (CVE-2010-5137).
497 
498             // With SCRIPT_VERIFY_CONST_SCRIPTCODE, OP_CODESEPARATOR in non-segwit script is rejected even in an unexecuted branch
499             if (opcode == OP_CODESEPARATOR && sigversion == SigVersion::BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
500                 return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
501 
502             if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
503                 if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
504                     return set_error(serror, SCRIPT_ERR_MINIMALDATA);
505                 }
506                 stack.push_back(vchPushValue);
507             } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
508             switch (opcode)
509             {
510                 //
511                 // Push value
512                 //
513                 case OP_1NEGATE:
514                 case OP_1:
515                 case OP_2:
516                 case OP_3:
517                 case OP_4:
518                 case OP_5:
519                 case OP_6:
520                 case OP_7:
521                 case OP_8:
522                 case OP_9:
523                 case OP_10:
524                 case OP_11:
525                 case OP_12:
526                 case OP_13:
527                 case OP_14:
528                 case OP_15:
529                 case OP_16:
530                 {
531                     // ( -- value)
532                     CScriptNum bn((int)opcode - (int)(OP_1 - 1));
533                     stack.push_back(bn.getvch());
534                     // The result of these opcodes should always be the minimal way to push the data
535                     // they push, so no need for a CheckMinimalPush here.
536                 }
537                 break;
538 
539 
540                 //
541                 // Control
542                 //
543                 case OP_NOP:
544                     break;
545 
546                 case OP_CHECKLOCKTIMEVERIFY:
547                 {
548                     if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
549                         // not enabled; treat as a NOP2
550                         break;
551                     }
552 
553                     if (stack.size() < 1)
554                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
555 
556                     // Note that elsewhere numeric opcodes are limited to
557                     // operands in the range -2**31+1 to 2**31-1, however it is
558                     // legal for opcodes to produce results exceeding that
559                     // range. This limitation is implemented by CScriptNum's
560                     // default 4-byte limit.
561                     //
562                     // If we kept to that limit we'd have a year 2038 problem,
563                     // even though the nLockTime field in transactions
564                     // themselves is uint32 which only becomes meaningless
565                     // after the year 2106.
566                     //
567                     // Thus as a special case we tell CScriptNum to accept up
568                     // to 5-byte bignums, which are good until 2**39-1, well
569                     // beyond the 2**32-1 limit of the nLockTime field itself.
570                     const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
571 
572                     // In the rare event that the argument may be < 0 due to
573                     // some arithmetic being done first, you can always use
574                     // 0 MAX CHECKLOCKTIMEVERIFY.
575                     if (nLockTime < 0)
576                         return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
577 
578                     // Actually compare the specified lock time with the transaction.
579                     if (!checker.CheckLockTime(nLockTime))
580                         return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
581 
582                     break;
583                 }
584 
585                 case OP_CHECKSEQUENCEVERIFY:
586                 {
587                     if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
588                         // not enabled; treat as a NOP3
589                         break;
590                     }
591 
592                     if (stack.size() < 1)
593                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
594 
595                     // nSequence, like nLockTime, is a 32-bit unsigned integer
596                     // field. See the comment in CHECKLOCKTIMEVERIFY regarding
597                     // 5-byte numeric operands.
598                     const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
599 
600                     // In the rare event that the argument may be < 0 due to
601                     // some arithmetic being done first, you can always use
602                     // 0 MAX CHECKSEQUENCEVERIFY.
603                     if (nSequence < 0)
604                         return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
605 
606                     // To provide for future soft-fork extensibility, if the
607                     // operand has the disabled lock-time flag set,
608                     // CHECKSEQUENCEVERIFY behaves as a NOP.
609                     if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
610                         break;
611 
612                     // Compare the specified sequence number with the input.
613                     if (!checker.CheckSequence(nSequence))
614                         return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
615 
616                     break;
617                 }
618 
619                 case OP_NOP1: case OP_NOP4: case OP_NOP5:
620                 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
621                 {
622                     if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
623                         return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
624                 }
625                 break;
626 
627                 case OP_IF:
628                 case OP_NOTIF:
629                 {
630                     // <expression> if [statements] [else [statements]] endif
631                     bool fValue = false;
632                     if (fExec)
633                     {
634                         if (stack.size() < 1)
635                             return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
636                         valtype& vch = stacktop(-1);
637                         // Tapscript requires minimal IF/NOTIF inputs as a consensus rule.
638                         if (sigversion == SigVersion::TAPSCRIPT) {
639                             // The input argument to the OP_IF and OP_NOTIF opcodes must be either
640                             // exactly 0 (the empty vector) or exactly 1 (the one-byte vector with value 1).
641                             if (vch.size() > 1 || (vch.size() == 1 && vch[0] != 1)) {
642                                 return set_error(serror, SCRIPT_ERR_TAPSCRIPT_MINIMALIF);
643                             }
644                         }
645                         // Under witness v0 rules it is only a policy rule, enabled through SCRIPT_VERIFY_MINIMALIF.
646                         if (sigversion == SigVersion::WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
647                             if (vch.size() > 1)
648                                 return set_error(serror, SCRIPT_ERR_MINIMALIF);
649                             if (vch.size() == 1 && vch[0] != 1)
650                                 return set_error(serror, SCRIPT_ERR_MINIMALIF);
651                         }
652                         fValue = CastToBool(vch);
653                         if (opcode == OP_NOTIF)
654                             fValue = !fValue;
655                         popstack(stack);
656                     }
657                     vfExec.push_back(fValue);
658                 }
659                 break;
660 
661                 case OP_ELSE:
662                 {
663                     if (vfExec.empty())
664                         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
665                     vfExec.toggle_top();
666                 }
667                 break;
668 
669                 case OP_ENDIF:
670                 {
671                     if (vfExec.empty())
672                         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
673                     vfExec.pop_back();
674                 }
675                 break;
676 
677                 case OP_VERIFY:
678                 {
679                     // (true -- ) or
680                     // (false -- false) and return
681                     if (stack.size() < 1)
682                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
683                     bool fValue = CastToBool(stacktop(-1));
684                     if (fValue)
685                         popstack(stack);
686                     else
687                         return set_error(serror, SCRIPT_ERR_VERIFY);
688                 }
689                 break;
690 
691                 case OP_RETURN:
692                 {
693                     return set_error(serror, SCRIPT_ERR_OP_RETURN);
694                 }
695                 break;
696 
697 
698                 //
699                 // Stack ops
700                 //
701                 case OP_TOALTSTACK:
702                 {
703                     if (stack.size() < 1)
704                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
705                     altstack.push_back(stacktop(-1));
706                     popstack(stack);
707                 }
708                 break;
709 
710                 case OP_FROMALTSTACK:
711                 {
712                     if (altstack.size() < 1)
713                         return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
714                     stack.push_back(altstacktop(-1));
715                     popstack(altstack);
716                 }
717                 break;
718 
719                 case OP_2DROP:
720                 {
721                     // (x1 x2 -- )
722                     if (stack.size() < 2)
723                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
724                     popstack(stack);
725                     popstack(stack);
726                 }
727                 break;
728 
729                 case OP_2DUP:
730                 {
731                     // (x1 x2 -- x1 x2 x1 x2)
732                     if (stack.size() < 2)
733                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
734                     valtype vch1 = stacktop(-2);
735                     valtype vch2 = stacktop(-1);
736                     stack.push_back(vch1);
737                     stack.push_back(vch2);
738                 }
739                 break;
740 
741                 case OP_3DUP:
742                 {
743                     // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
744                     if (stack.size() < 3)
745                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
746                     valtype vch1 = stacktop(-3);
747                     valtype vch2 = stacktop(-2);
748                     valtype vch3 = stacktop(-1);
749                     stack.push_back(vch1);
750                     stack.push_back(vch2);
751                     stack.push_back(vch3);
752                 }
753                 break;
754 
755                 case OP_2OVER:
756                 {
757                     // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
758                     if (stack.size() < 4)
759                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
760                     valtype vch1 = stacktop(-4);
761                     valtype vch2 = stacktop(-3);
762                     stack.push_back(vch1);
763                     stack.push_back(vch2);
764                 }
765                 break;
766 
767                 case OP_2ROT:
768                 {
769                     // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
770                     if (stack.size() < 6)
771                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
772                     valtype vch1 = stacktop(-6);
773                     valtype vch2 = stacktop(-5);
774                     stack.erase(stack.end()-6, stack.end()-4);
775                     stack.push_back(vch1);
776                     stack.push_back(vch2);
777                 }
778                 break;
779 
780                 case OP_2SWAP:
781                 {
782                     // (x1 x2 x3 x4 -- x3 x4 x1 x2)
783                     if (stack.size() < 4)
784                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
785                     swap(stacktop(-4), stacktop(-2));
786                     swap(stacktop(-3), stacktop(-1));
787                 }
788                 break;
789 
790                 case OP_IFDUP:
791                 {
792                     // (x - 0 | x x)
793                     if (stack.size() < 1)
794                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
795                     valtype vch = stacktop(-1);
796                     if (CastToBool(vch))
797                         stack.push_back(vch);
798                 }
799                 break;
800 
801                 case OP_DEPTH:
802                 {
803                     // -- stacksize
804                     CScriptNum bn(stack.size());
805                     stack.push_back(bn.getvch());
806                 }
807                 break;
808 
809                 case OP_DROP:
810                 {
811                     // (x -- )
812                     if (stack.size() < 1)
813                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
814                     popstack(stack);
815                 }
816                 break;
817 
818                 case OP_DUP:
819                 {
820                     // (x -- x x)
821                     if (stack.size() < 1)
822                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
823                     valtype vch = stacktop(-1);
824                     stack.push_back(vch);
825                 }
826                 break;
827 
828                 case OP_NIP:
829                 {
830                     // (x1 x2 -- x2)
831                     if (stack.size() < 2)
832                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
833                     stack.erase(stack.end() - 2);
834                 }
835                 break;
836 
837                 case OP_OVER:
838                 {
839                     // (x1 x2 -- x1 x2 x1)
840                     if (stack.size() < 2)
841                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
842                     valtype vch = stacktop(-2);
843                     stack.push_back(vch);
844                 }
845                 break;
846 
847                 case OP_PICK:
848                 case OP_ROLL:
849                 {
850                     // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
851                     // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
852                     if (stack.size() < 2)
853                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
854                     int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
855                     popstack(stack);
856                     if (n < 0 || n >= (int)stack.size())
857                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
858                     valtype vch = stacktop(-n-1);
859                     if (opcode == OP_ROLL)
860                         stack.erase(stack.end()-n-1);
861                     stack.push_back(vch);
862                 }
863                 break;
864 
865                 case OP_ROT:
866                 {
867                     // (x1 x2 x3 -- x2 x3 x1)
868                     //  x2 x1 x3  after first swap
869                     //  x2 x3 x1  after second swap
870                     if (stack.size() < 3)
871                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
872                     swap(stacktop(-3), stacktop(-2));
873                     swap(stacktop(-2), stacktop(-1));
874                 }
875                 break;
876 
877                 case OP_SWAP:
878                 {
879                     // (x1 x2 -- x2 x1)
880                     if (stack.size() < 2)
881                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
882                     swap(stacktop(-2), stacktop(-1));
883                 }
884                 break;
885 
886                 case OP_TUCK:
887                 {
888                     // (x1 x2 -- x2 x1 x2)
889                     if (stack.size() < 2)
890                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
891                     valtype vch = stacktop(-1);
892                     stack.insert(stack.end()-2, vch);
893                 }
894                 break;
895 
896 
897                 case OP_SIZE:
898                 {
899                     // (in -- in size)
900                     if (stack.size() < 1)
901                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
902                     CScriptNum bn(stacktop(-1).size());
903                     stack.push_back(bn.getvch());
904                 }
905                 break;
906 
907 
908                 //
909                 // Bitwise logic
910                 //
911                 case OP_EQUAL:
912                 case OP_EQUALVERIFY:
913                 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
914                 {
915                     // (x1 x2 - bool)
916                     if (stack.size() < 2)
917                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
918                     valtype& vch1 = stacktop(-2);
919                     valtype& vch2 = stacktop(-1);
920                     bool fEqual = (vch1 == vch2);
921                     // OP_NOTEQUAL is disabled because it would be too easy to say
922                     // something like n != 1 and have some wiseguy pass in 1 with extra
923                     // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
924                     //if (opcode == OP_NOTEQUAL)
925                     //    fEqual = !fEqual;
926                     popstack(stack);
927                     popstack(stack);
928                     stack.push_back(fEqual ? vchTrue : vchFalse);
929                     if (opcode == OP_EQUALVERIFY)
930                     {
931                         if (fEqual)
932                             popstack(stack);
933                         else
934                             return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
935                     }
936                 }
937                 break;
938 
939 
940                 //
941                 // Numeric
942                 //
943                 case OP_1ADD:
944                 case OP_1SUB:
945                 case OP_NEGATE:
946                 case OP_ABS:
947                 case OP_NOT:
948                 case OP_0NOTEQUAL:
949                 {
950                     // (in -- out)
951                     if (stack.size() < 1)
952                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
953                     CScriptNum bn(stacktop(-1), fRequireMinimal);
954                     switch (opcode)
955                     {
956                     case OP_1ADD:       bn += bnOne; break;
957                     case OP_1SUB:       bn -= bnOne; break;
958                     case OP_NEGATE:     bn = -bn; break;
959                     case OP_ABS:        if (bn < bnZero) bn = -bn; break;
960                     case OP_NOT:        bn = (bn == bnZero); break;
961                     case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
962                     default:            assert(!"invalid opcode"); break;
963                     }
964                     popstack(stack);
965                     stack.push_back(bn.getvch());
966                 }
967                 break;
968 
969                 case OP_ADD:
970                 case OP_SUB:
971                 case OP_BOOLAND:
972                 case OP_BOOLOR:
973                 case OP_NUMEQUAL:
974                 case OP_NUMEQUALVERIFY:
975                 case OP_NUMNOTEQUAL:
976                 case OP_LESSTHAN:
977                 case OP_GREATERTHAN:
978                 case OP_LESSTHANOREQUAL:
979                 case OP_GREATERTHANOREQUAL:
980                 case OP_MIN:
981                 case OP_MAX:
982                 {
983                     // (x1 x2 -- out)
984                     if (stack.size() < 2)
985                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
986                     CScriptNum bn1(stacktop(-2), fRequireMinimal);
987                     CScriptNum bn2(stacktop(-1), fRequireMinimal);
988                     CScriptNum bn(0);
989                     switch (opcode)
990                     {
991                     case OP_ADD:
992                         bn = bn1 + bn2;
993                         break;
994 
995                     case OP_SUB:
996                         bn = bn1 - bn2;
997                         break;
998 
999                     case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
1000                     case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
1001                     case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
1002                     case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
1003                     case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
1004                     case OP_LESSTHAN:            bn = (bn1 < bn2); break;
1005                     case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
1006                     case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
1007                     case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
1008                     case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
1009                     case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
1010                     default:                     assert(!"invalid opcode"); break;
1011                     }
1012                     popstack(stack);
1013                     popstack(stack);
1014                     stack.push_back(bn.getvch());
1015 
1016                     if (opcode == OP_NUMEQUALVERIFY)
1017                     {
1018                         if (CastToBool(stacktop(-1)))
1019                             popstack(stack);
1020                         else
1021                             return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
1022                     }
1023                 }
1024                 break;
1025 
1026                 case OP_WITHIN:
1027                 {
1028                     // (x min max -- out)
1029                     if (stack.size() < 3)
1030                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1031                     CScriptNum bn1(stacktop(-3), fRequireMinimal);
1032                     CScriptNum bn2(stacktop(-2), fRequireMinimal);
1033                     CScriptNum bn3(stacktop(-1), fRequireMinimal);
1034                     bool fValue = (bn2 <= bn1 && bn1 < bn3);
1035                     popstack(stack);
1036                     popstack(stack);
1037                     popstack(stack);
1038                     stack.push_back(fValue ? vchTrue : vchFalse);
1039                 }
1040                 break;
1041 
1042 
1043                 //
1044                 // Crypto
1045                 //
1046                 case OP_RIPEMD160:
1047                 case OP_SHA1:
1048                 case OP_SHA256:
1049                 case OP_HASH160:
1050                 case OP_HASH256:
1051                 {
1052                     // (in -- hash)
1053                     if (stack.size() < 1)
1054                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1055                     valtype& vch = stacktop(-1);
1056                     valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
1057                     if (opcode == OP_RIPEMD160)
1058                         CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1059                     else if (opcode == OP_SHA1)
1060                         CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1061                     else if (opcode == OP_SHA256)
1062                         CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1063                     else if (opcode == OP_HASH160)
1064                         CHash160().Write(vch).Finalize(vchHash);
1065                     else if (opcode == OP_HASH256)
1066                         CHash256().Write(vch).Finalize(vchHash);
1067                     popstack(stack);
1068                     stack.push_back(vchHash);
1069                 }
1070                 break;
1071 
1072                 case OP_CODESEPARATOR:
1073                 {
1074                     // If SCRIPT_VERIFY_CONST_SCRIPTCODE flag is set, use of OP_CODESEPARATOR is rejected in pre-segwit
1075                     // script, even in an unexecuted branch (this is checked above the opcode case statement).
1076 
1077                     // Hash starts after the code separator
1078                     pbegincodehash = pc;
1079                     execdata.m_codeseparator_pos = opcode_pos;
1080                 }
1081                 break;
1082 
1083                 case OP_CHECKSIG:
1084                 case OP_CHECKSIGVERIFY:
1085                 {
1086                     // (sig pubkey -- bool)
1087                     if (stack.size() < 2)
1088                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1089 
1090                     valtype& vchSig    = stacktop(-2);
1091                     valtype& vchPubKey = stacktop(-1);
1092 
1093                     bool fSuccess = true;
1094                     if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, fSuccess)) return false;
1095                     popstack(stack);
1096                     popstack(stack);
1097                     stack.push_back(fSuccess ? vchTrue : vchFalse);
1098                     if (opcode == OP_CHECKSIGVERIFY)
1099                     {
1100                         if (fSuccess)
1101                             popstack(stack);
1102                         else
1103                             return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
1104                     }
1105                 }
1106                 break;
1107 
1108                 case OP_CHECKSIGADD:
1109                 {
1110                     // OP_CHECKSIGADD is only available in Tapscript
1111                     if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1112 
1113                     // (sig num pubkey -- num)
1114                     if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1115 
1116                     const valtype& sig = stacktop(-3);
1117                     const CScriptNum num(stacktop(-2), fRequireMinimal);
1118                     const valtype& pubkey = stacktop(-1);
1119 
1120                     bool success = true;
1121                     if (!EvalChecksig(sig, pubkey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, success)) return false;
1122                     popstack(stack);
1123                     popstack(stack);
1124                     popstack(stack);
1125                     stack.push_back((num + (success ? 1 : 0)).getvch());
1126                 }
1127                 break;
1128 
1129                 case OP_CHECKMULTISIG:
1130                 case OP_CHECKMULTISIGVERIFY:
1131                 {
1132                     if (sigversion == SigVersion::TAPSCRIPT) return set_error(serror, SCRIPT_ERR_TAPSCRIPT_CHECKMULTISIG);
1133 
1134                     // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1135 
1136                     int i = 1;
1137                     if ((int)stack.size() < i)
1138                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1139 
1140                     int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1141                     if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
1142                         return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
1143                     nOpCount += nKeysCount;
1144                     if (nOpCount > MAX_OPS_PER_SCRIPT)
1145                         return set_error(serror, SCRIPT_ERR_OP_COUNT);
1146                     int ikey = ++i;
1147                     // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
1148                     // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
1149                     int ikey2 = nKeysCount + 2;
1150                     i += nKeysCount;
1151                     if ((int)stack.size() < i)
1152                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1153 
1154                     int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1155                     if (nSigsCount < 0 || nSigsCount > nKeysCount)
1156                         return set_error(serror, SCRIPT_ERR_SIG_COUNT);
1157                     int isig = ++i;
1158                     i += nSigsCount;
1159                     if ((int)stack.size() < i)
1160                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1161 
1162                     // Subset of script starting at the most recent codeseparator
1163                     CScript scriptCode(pbegincodehash, pend);
1164 
1165                     // Drop the signature in pre-segwit scripts but not segwit scripts
1166                     for (int k = 0; k < nSigsCount; k++)
1167                     {
1168                         valtype& vchSig = stacktop(-isig-k);
1169                         if (sigversion == SigVersion::BASE) {
1170                             int found = FindAndDelete(scriptCode, CScript() << vchSig);
1171                             if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
1172                                 return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
1173                         }
1174                     }
1175 
1176                     bool fSuccess = true;
1177                     while (fSuccess && nSigsCount > 0)
1178                     {
1179                         valtype& vchSig    = stacktop(-isig);
1180                         valtype& vchPubKey = stacktop(-ikey);
1181 
1182                         // Note how this makes the exact order of pubkey/signature evaluation
1183                         // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
1184                         // See the script_(in)valid tests for details.
1185                         if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
1186                             // serror is set
1187                             return false;
1188                         }
1189 
1190                         // Check signature
1191                         bool fOk = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
1192 
1193                         if (fOk) {
1194                             isig++;
1195                             nSigsCount--;
1196                         }
1197                         ikey++;
1198                         nKeysCount--;
1199 
1200                         // If there are more signatures left than keys left,
1201                         // then too many signatures have failed. Exit early,
1202                         // without checking any further signatures.
1203                         if (nSigsCount > nKeysCount)
1204                             fSuccess = false;
1205                     }
1206 
1207                     // Clean up stack of actual arguments
1208                     while (i-- > 1) {
1209                         // If the operation failed, we require that all signatures must be empty vector
1210                         if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
1211                             return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
1212                         if (ikey2 > 0)
1213                             ikey2--;
1214                         popstack(stack);
1215                     }
1216 
1217                     // A bug causes CHECKMULTISIG to consume one extra argument
1218                     // whose contents were not checked in any way.
1219                     //
1220                     // Unfortunately this is a potential source of mutability,
1221                     // so optionally verify it is exactly equal to zero prior
1222                     // to removing it from the stack.
1223                     if (stack.size() < 1)
1224                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1225                     if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1226                         return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1227                     popstack(stack);
1228 
1229                     stack.push_back(fSuccess ? vchTrue : vchFalse);
1230 
1231                     if (opcode == OP_CHECKMULTISIGVERIFY)
1232                     {
1233                         if (fSuccess)
1234                             popstack(stack);
1235                         else
1236                             return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1237                     }
1238                 }
1239                 break;
1240 
1241                 default:
1242                     return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1243             }
1244 
1245             // Size limits
1246             if (stack.size() + altstack.size() > MAX_STACK_SIZE)
1247                 return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1248         }
1249     }
1250     catch (...)
1251     {
1252         return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1253     }
1254 
1255     if (!vfExec.empty())
1256         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1257 
1258     return set_success(serror);
1259 }
1260 
EvalScript(std::vector<std::vector<unsigned char>> & stack,const CScript & script,unsigned int flags,const BaseSignatureChecker & checker,SigVersion sigversion,ScriptError * serror)1261 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
1262 {
1263     ScriptExecutionData execdata;
1264     return EvalScript(stack, script, flags, checker, sigversion, execdata, serror);
1265 }
1266 
1267 namespace {
1268 
1269 /**
1270  * Wrapper that serializes like CTransaction, but with the modifications
1271  *  required for the signature hash done in-place
1272  */
1273 template <class T>
1274 class CTransactionSignatureSerializer
1275 {
1276 private:
1277     const T& txTo;             //!< reference to the spending transaction (the one being serialized)
1278     const CScript& scriptCode; //!< output script being consumed
1279     const unsigned int nIn;    //!< input index of txTo being signed
1280     const bool fAnyoneCanPay;  //!< whether the hashtype has the SIGHASH_ANYONECANPAY flag set
1281     const bool fHashSingle;    //!< whether the hashtype is SIGHASH_SINGLE
1282     const bool fHashNone;      //!< whether the hashtype is SIGHASH_NONE
1283 
1284 public:
CTransactionSignatureSerializer(const T & txToIn,const CScript & scriptCodeIn,unsigned int nInIn,int nHashTypeIn)1285     CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1286         txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1287         fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1288         fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1289         fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1290 
1291     /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1292     template<typename S>
SerializeScriptCode(S & s) const1293     void SerializeScriptCode(S &s) const {
1294         CScript::const_iterator it = scriptCode.begin();
1295         CScript::const_iterator itBegin = it;
1296         opcodetype opcode;
1297         unsigned int nCodeSeparators = 0;
1298         while (scriptCode.GetOp(it, opcode)) {
1299             if (opcode == OP_CODESEPARATOR)
1300                 nCodeSeparators++;
1301         }
1302         ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1303         it = itBegin;
1304         while (scriptCode.GetOp(it, opcode)) {
1305             if (opcode == OP_CODESEPARATOR) {
1306                 s.write((char*)&itBegin[0], it-itBegin-1);
1307                 itBegin = it;
1308             }
1309         }
1310         if (itBegin != scriptCode.end())
1311             s.write((char*)&itBegin[0], it-itBegin);
1312     }
1313 
1314     /** Serialize an input of txTo */
1315     template<typename S>
SerializeInput(S & s,unsigned int nInput) const1316     void SerializeInput(S &s, unsigned int nInput) const {
1317         // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1318         if (fAnyoneCanPay)
1319             nInput = nIn;
1320         // Serialize the prevout
1321         ::Serialize(s, txTo.vin[nInput].prevout);
1322         // Serialize the script
1323         if (nInput != nIn)
1324             // Blank out other inputs' signatures
1325             ::Serialize(s, CScript());
1326         else
1327             SerializeScriptCode(s);
1328         // Serialize the nSequence
1329         if (nInput != nIn && (fHashSingle || fHashNone))
1330             // let the others update at will
1331             ::Serialize(s, (int)0);
1332         else
1333             ::Serialize(s, txTo.vin[nInput].nSequence);
1334     }
1335 
1336     /** Serialize an output of txTo */
1337     template<typename S>
SerializeOutput(S & s,unsigned int nOutput) const1338     void SerializeOutput(S &s, unsigned int nOutput) const {
1339         if (fHashSingle && nOutput != nIn)
1340             // Do not lock-in the txout payee at other indices as txin
1341             ::Serialize(s, CTxOut());
1342         else
1343             ::Serialize(s, txTo.vout[nOutput]);
1344     }
1345 
1346     /** Serialize txTo */
1347     template<typename S>
Serialize(S & s) const1348     void Serialize(S &s) const {
1349         // Serialize nVersion
1350         ::Serialize(s, txTo.nVersion);
1351         // Serialize vin
1352         unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1353         ::WriteCompactSize(s, nInputs);
1354         for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1355              SerializeInput(s, nInput);
1356         // Serialize vout
1357         unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1358         ::WriteCompactSize(s, nOutputs);
1359         for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1360              SerializeOutput(s, nOutput);
1361         // Serialize nLockTime
1362         ::Serialize(s, txTo.nLockTime);
1363     }
1364 };
1365 
1366 /** Compute the (single) SHA256 of the concatenation of all prevouts of a tx. */
1367 template <class T>
GetPrevoutsSHA256(const T & txTo)1368 uint256 GetPrevoutsSHA256(const T& txTo)
1369 {
1370     CHashWriter ss(SER_GETHASH, 0);
1371     for (const auto& txin : txTo.vin) {
1372         ss << txin.prevout;
1373     }
1374     return ss.GetSHA256();
1375 }
1376 
1377 /** Compute the (single) SHA256 of the concatenation of all nSequences of a tx. */
1378 template <class T>
GetSequencesSHA256(const T & txTo)1379 uint256 GetSequencesSHA256(const T& txTo)
1380 {
1381     CHashWriter ss(SER_GETHASH, 0);
1382     for (const auto& txin : txTo.vin) {
1383         ss << txin.nSequence;
1384     }
1385     return ss.GetSHA256();
1386 }
1387 
1388 /** Compute the (single) SHA256 of the concatenation of all txouts of a tx. */
1389 template <class T>
GetOutputsSHA256(const T & txTo)1390 uint256 GetOutputsSHA256(const T& txTo)
1391 {
1392     CHashWriter ss(SER_GETHASH, 0);
1393     for (const auto& txout : txTo.vout) {
1394         ss << txout;
1395     }
1396     return ss.GetSHA256();
1397 }
1398 
1399 /** Compute the (single) SHA256 of the concatenation of all amounts spent by a tx. */
GetSpentAmountsSHA256(const std::vector<CTxOut> & outputs_spent)1400 uint256 GetSpentAmountsSHA256(const std::vector<CTxOut>& outputs_spent)
1401 {
1402     CHashWriter ss(SER_GETHASH, 0);
1403     for (const auto& txout : outputs_spent) {
1404         ss << txout.nValue;
1405     }
1406     return ss.GetSHA256();
1407 }
1408 
1409 /** Compute the (single) SHA256 of the concatenation of all scriptPubKeys spent by a tx. */
GetSpentScriptsSHA256(const std::vector<CTxOut> & outputs_spent)1410 uint256 GetSpentScriptsSHA256(const std::vector<CTxOut>& outputs_spent)
1411 {
1412     CHashWriter ss(SER_GETHASH, 0);
1413     for (const auto& txout : outputs_spent) {
1414         ss << txout.scriptPubKey;
1415     }
1416     return ss.GetSHA256();
1417 }
1418 
1419 
1420 } // namespace
1421 
1422 template <class T>
Init(const T & txTo,std::vector<CTxOut> && spent_outputs,bool force)1423 void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent_outputs, bool force)
1424 {
1425     assert(!m_spent_outputs_ready);
1426 
1427     m_spent_outputs = std::move(spent_outputs);
1428     if (!m_spent_outputs.empty()) {
1429         assert(m_spent_outputs.size() == txTo.vin.size());
1430         m_spent_outputs_ready = true;
1431     }
1432 
1433     // Determine which precomputation-impacting features this transaction uses.
1434     bool uses_bip143_segwit = force;
1435     bool uses_bip341_taproot = force;
1436     for (size_t inpos = 0; inpos < txTo.vin.size() && !(uses_bip143_segwit && uses_bip341_taproot); ++inpos) {
1437         if (!txTo.vin[inpos].scriptWitness.IsNull()) {
1438             if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.size() == 2 + WITNESS_V1_TAPROOT_SIZE &&
1439                 m_spent_outputs[inpos].scriptPubKey[0] == OP_1) {
1440                 // Treat every witness-bearing spend with 34-byte scriptPubKey that starts with OP_1 as a Taproot
1441                 // spend. This only works if spent_outputs was provided as well, but if it wasn't, actual validation
1442                 // will fail anyway. Note that this branch may trigger for scriptPubKeys that aren't actually segwit
1443                 // but in that case validation will fail as SCRIPT_ERR_WITNESS_UNEXPECTED anyway.
1444                 uses_bip341_taproot = true;
1445             } else {
1446                 // Treat every spend that's not known to native witness v1 as a Witness v0 spend. This branch may
1447                 // also be taken for unknown witness versions, but it is harmless, and being precise would require
1448                 // P2SH evaluation to find the redeemScript.
1449                 uses_bip143_segwit = true;
1450             }
1451         }
1452         if (uses_bip341_taproot && uses_bip143_segwit) break; // No need to scan further if we already need all.
1453     }
1454 
1455     if (uses_bip143_segwit || uses_bip341_taproot) {
1456         // Computations shared between both sighash schemes.
1457         m_prevouts_single_hash = GetPrevoutsSHA256(txTo);
1458         m_sequences_single_hash = GetSequencesSHA256(txTo);
1459         m_outputs_single_hash = GetOutputsSHA256(txTo);
1460     }
1461     if (uses_bip143_segwit) {
1462         hashPrevouts = SHA256Uint256(m_prevouts_single_hash);
1463         hashSequence = SHA256Uint256(m_sequences_single_hash);
1464         hashOutputs = SHA256Uint256(m_outputs_single_hash);
1465         m_bip143_segwit_ready = true;
1466     }
1467     if (uses_bip341_taproot) {
1468         m_spent_amounts_single_hash = GetSpentAmountsSHA256(m_spent_outputs);
1469         m_spent_scripts_single_hash = GetSpentScriptsSHA256(m_spent_outputs);
1470         m_bip341_taproot_ready = true;
1471     }
1472 }
1473 
1474 template <class T>
PrecomputedTransactionData(const T & txTo)1475 PrecomputedTransactionData::PrecomputedTransactionData(const T& txTo)
1476 {
1477     Init(txTo, {});
1478 }
1479 
1480 // explicit instantiation
1481 template void PrecomputedTransactionData::Init(const CTransaction& txTo, std::vector<CTxOut>&& spent_outputs, bool force);
1482 template void PrecomputedTransactionData::Init(const CMutableTransaction& txTo, std::vector<CTxOut>&& spent_outputs, bool force);
1483 template PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo);
1484 template PrecomputedTransactionData::PrecomputedTransactionData(const CMutableTransaction& txTo);
1485 
1486 static const CHashWriter HASHER_TAPSIGHASH = TaggedHash("TapSighash");
1487 const CHashWriter HASHER_TAPLEAF = TaggedHash("TapLeaf");
1488 const CHashWriter HASHER_TAPBRANCH = TaggedHash("TapBranch");
1489 
HandleMissingData(MissingDataBehavior mdb)1490 static bool HandleMissingData(MissingDataBehavior mdb)
1491 {
1492     switch (mdb) {
1493     case MissingDataBehavior::ASSERT_FAIL:
1494         assert(!"Missing data");
1495         break;
1496     case MissingDataBehavior::FAIL:
1497         return false;
1498     }
1499     assert(!"Unknown MissingDataBehavior value");
1500 }
1501 
1502 template<typename T>
SignatureHashSchnorr(uint256 & hash_out,const ScriptExecutionData & execdata,const T & tx_to,uint32_t in_pos,uint8_t hash_type,SigVersion sigversion,const PrecomputedTransactionData & cache,MissingDataBehavior mdb)1503 bool SignatureHashSchnorr(uint256& hash_out, const ScriptExecutionData& execdata, const T& tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData& cache, MissingDataBehavior mdb)
1504 {
1505     uint8_t ext_flag, key_version;
1506     switch (sigversion) {
1507     case SigVersion::TAPROOT:
1508         ext_flag = 0;
1509         // key_version is not used and left uninitialized.
1510         break;
1511     case SigVersion::TAPSCRIPT:
1512         ext_flag = 1;
1513         // key_version must be 0 for now, representing the current version of
1514         // 32-byte public keys in the tapscript signature opcode execution.
1515         // An upgradable public key version (with a size not 32-byte) may
1516         // request a different key_version with a new sigversion.
1517         key_version = 0;
1518         break;
1519     default:
1520         assert(false);
1521     }
1522     assert(in_pos < tx_to.vin.size());
1523     if (!(cache.m_bip341_taproot_ready && cache.m_spent_outputs_ready)) {
1524         return HandleMissingData(mdb);
1525     }
1526 
1527     CHashWriter ss = HASHER_TAPSIGHASH;
1528 
1529     // Epoch
1530     static constexpr uint8_t EPOCH = 0;
1531     ss << EPOCH;
1532 
1533     // Hash type
1534     const uint8_t output_type = (hash_type == SIGHASH_DEFAULT) ? SIGHASH_ALL : (hash_type & SIGHASH_OUTPUT_MASK); // Default (no sighash byte) is equivalent to SIGHASH_ALL
1535     const uint8_t input_type = hash_type & SIGHASH_INPUT_MASK;
1536     if (!(hash_type <= 0x03 || (hash_type >= 0x81 && hash_type <= 0x83))) return false;
1537     ss << hash_type;
1538 
1539     // Transaction level data
1540     ss << tx_to.nVersion;
1541     ss << tx_to.nLockTime;
1542     if (input_type != SIGHASH_ANYONECANPAY) {
1543         ss << cache.m_prevouts_single_hash;
1544         ss << cache.m_spent_amounts_single_hash;
1545         ss << cache.m_spent_scripts_single_hash;
1546         ss << cache.m_sequences_single_hash;
1547     }
1548     if (output_type == SIGHASH_ALL) {
1549         ss << cache.m_outputs_single_hash;
1550     }
1551 
1552     // Data about the input/prevout being spent
1553     assert(execdata.m_annex_init);
1554     const bool have_annex = execdata.m_annex_present;
1555     const uint8_t spend_type = (ext_flag << 1) + (have_annex ? 1 : 0); // The low bit indicates whether an annex is present.
1556     ss << spend_type;
1557     if (input_type == SIGHASH_ANYONECANPAY) {
1558         ss << tx_to.vin[in_pos].prevout;
1559         ss << cache.m_spent_outputs[in_pos];
1560         ss << tx_to.vin[in_pos].nSequence;
1561     } else {
1562         ss << in_pos;
1563     }
1564     if (have_annex) {
1565         ss << execdata.m_annex_hash;
1566     }
1567 
1568     // Data about the output (if only one).
1569     if (output_type == SIGHASH_SINGLE) {
1570         if (in_pos >= tx_to.vout.size()) return false;
1571         CHashWriter sha_single_output(SER_GETHASH, 0);
1572         sha_single_output << tx_to.vout[in_pos];
1573         ss << sha_single_output.GetSHA256();
1574     }
1575 
1576     // Additional data for BIP 342 signatures
1577     if (sigversion == SigVersion::TAPSCRIPT) {
1578         assert(execdata.m_tapleaf_hash_init);
1579         ss << execdata.m_tapleaf_hash;
1580         ss << key_version;
1581         assert(execdata.m_codeseparator_pos_init);
1582         ss << execdata.m_codeseparator_pos;
1583     }
1584 
1585     hash_out = ss.GetSHA256();
1586     return true;
1587 }
1588 
1589 template <class T>
SignatureHash(const CScript & scriptCode,const T & txTo,unsigned int nIn,int nHashType,const CAmount & amount,SigVersion sigversion,const PrecomputedTransactionData * cache)1590 uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1591 {
1592     assert(nIn < txTo.vin.size());
1593 
1594     if (sigversion == SigVersion::WITNESS_V0) {
1595         uint256 hashPrevouts;
1596         uint256 hashSequence;
1597         uint256 hashOutputs;
1598         const bool cacheready = cache && cache->m_bip143_segwit_ready;
1599 
1600         if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1601             hashPrevouts = cacheready ? cache->hashPrevouts : SHA256Uint256(GetPrevoutsSHA256(txTo));
1602         }
1603 
1604         if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1605             hashSequence = cacheready ? cache->hashSequence : SHA256Uint256(GetSequencesSHA256(txTo));
1606         }
1607 
1608 
1609         if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1610             hashOutputs = cacheready ? cache->hashOutputs : SHA256Uint256(GetOutputsSHA256(txTo));
1611         } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
1612             CHashWriter ss(SER_GETHASH, 0);
1613             ss << txTo.vout[nIn];
1614             hashOutputs = ss.GetHash();
1615         }
1616 
1617         CHashWriter ss(SER_GETHASH, 0);
1618         // Version
1619         ss << txTo.nVersion;
1620         // Input prevouts/nSequence (none/all, depending on flags)
1621         ss << hashPrevouts;
1622         ss << hashSequence;
1623         // The input being signed (replacing the scriptSig with scriptCode + amount)
1624         // The prevout may already be contained in hashPrevout, and the nSequence
1625         // may already be contain in hashSequence.
1626         ss << txTo.vin[nIn].prevout;
1627         ss << scriptCode;
1628         ss << amount;
1629         ss << txTo.vin[nIn].nSequence;
1630         // Outputs (none/one/all, depending on flags)
1631         ss << hashOutputs;
1632         // Locktime
1633         ss << txTo.nLockTime;
1634         // Sighash type
1635         ss << nHashType;
1636 
1637         return ss.GetHash();
1638     }
1639 
1640     // Check for invalid use of SIGHASH_SINGLE
1641     if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1642         if (nIn >= txTo.vout.size()) {
1643             //  nOut out of range
1644             return uint256::ONE;
1645         }
1646     }
1647 
1648     // Wrapper to serialize only the necessary parts of the transaction being signed
1649     CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
1650 
1651     // Serialize and hash
1652     CHashWriter ss(SER_GETHASH, 0);
1653     ss << txTmp << nHashType;
1654     return ss.GetHash();
1655 }
1656 
1657 template <class T>
VerifyECDSASignature(const std::vector<unsigned char> & vchSig,const CPubKey & pubkey,const uint256 & sighash) const1658 bool GenericTransactionSignatureChecker<T>::VerifyECDSASignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1659 {
1660     return pubkey.Verify(sighash, vchSig);
1661 }
1662 
1663 template <class T>
VerifySchnorrSignature(Span<const unsigned char> sig,const XOnlyPubKey & pubkey,const uint256 & sighash) const1664 bool GenericTransactionSignatureChecker<T>::VerifySchnorrSignature(Span<const unsigned char> sig, const XOnlyPubKey& pubkey, const uint256& sighash) const
1665 {
1666     return pubkey.VerifySchnorr(sighash, sig);
1667 }
1668 
1669 template <class T>
CheckECDSASignature(const std::vector<unsigned char> & vchSigIn,const std::vector<unsigned char> & vchPubKey,const CScript & scriptCode,SigVersion sigversion) const1670 bool GenericTransactionSignatureChecker<T>::CheckECDSASignature(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1671 {
1672     CPubKey pubkey(vchPubKey);
1673     if (!pubkey.IsValid())
1674         return false;
1675 
1676     // Hash type is one byte tacked on to the end of the signature
1677     std::vector<unsigned char> vchSig(vchSigIn);
1678     if (vchSig.empty())
1679         return false;
1680     int nHashType = vchSig.back();
1681     vchSig.pop_back();
1682 
1683     // Witness sighashes need the amount.
1684     if (sigversion == SigVersion::WITNESS_V0 && amount < 0) return HandleMissingData(m_mdb);
1685 
1686     uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
1687 
1688     if (!VerifyECDSASignature(vchSig, pubkey, sighash))
1689         return false;
1690 
1691     return true;
1692 }
1693 
1694 template <class T>
CheckSchnorrSignature(Span<const unsigned char> sig,Span<const unsigned char> pubkey_in,SigVersion sigversion,const ScriptExecutionData & execdata,ScriptError * serror) const1695 bool GenericTransactionSignatureChecker<T>::CheckSchnorrSignature(Span<const unsigned char> sig, Span<const unsigned char> pubkey_in, SigVersion sigversion, const ScriptExecutionData& execdata, ScriptError* serror) const
1696 {
1697     assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
1698     // Schnorr signatures have 32-byte public keys. The caller is responsible for enforcing this.
1699     assert(pubkey_in.size() == 32);
1700     // Note that in Tapscript evaluation, empty signatures are treated specially (invalid signature that does not
1701     // abort script execution). This is implemented in EvalChecksigTapscript, which won't invoke
1702     // CheckSchnorrSignature in that case. In other contexts, they are invalid like every other signature with
1703     // size different from 64 or 65.
1704     if (sig.size() != 64 && sig.size() != 65) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_SIZE);
1705 
1706     XOnlyPubKey pubkey{pubkey_in};
1707 
1708     uint8_t hashtype = SIGHASH_DEFAULT;
1709     if (sig.size() == 65) {
1710         hashtype = SpanPopBack(sig);
1711         if (hashtype == SIGHASH_DEFAULT) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
1712     }
1713     uint256 sighash;
1714     if (!this->txdata) return HandleMissingData(m_mdb);
1715     if (!SignatureHashSchnorr(sighash, execdata, *txTo, nIn, hashtype, sigversion, *this->txdata, m_mdb)) {
1716         return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
1717     }
1718     if (!VerifySchnorrSignature(sig, pubkey, sighash)) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG);
1719     return true;
1720 }
1721 
1722 template <class T>
CheckLockTime(const CScriptNum & nLockTime) const1723 bool GenericTransactionSignatureChecker<T>::CheckLockTime(const CScriptNum& nLockTime) const
1724 {
1725     // There are two kinds of nLockTime: lock-by-blockheight
1726     // and lock-by-blocktime, distinguished by whether
1727     // nLockTime < LOCKTIME_THRESHOLD.
1728     //
1729     // We want to compare apples to apples, so fail the script
1730     // unless the type of nLockTime being tested is the same as
1731     // the nLockTime in the transaction.
1732     if (!(
1733         (txTo->nLockTime <  LOCKTIME_THRESHOLD && nLockTime <  LOCKTIME_THRESHOLD) ||
1734         (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1735     ))
1736         return false;
1737 
1738     // Now that we know we're comparing apples-to-apples, the
1739     // comparison is a simple numeric one.
1740     if (nLockTime > (int64_t)txTo->nLockTime)
1741         return false;
1742 
1743     // Finally the nLockTime feature can be disabled in IsFinalTx()
1744     // and thus CHECKLOCKTIMEVERIFY bypassed if every txin has
1745     // been finalized by setting nSequence to maxint. The
1746     // transaction would be allowed into the blockchain, making
1747     // the opcode ineffective.
1748     //
1749     // Testing if this vin is not final is sufficient to
1750     // prevent this condition. Alternatively we could test all
1751     // inputs, but testing just this input minimizes the data
1752     // required to prove correct CHECKLOCKTIMEVERIFY execution.
1753     if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1754         return false;
1755 
1756     return true;
1757 }
1758 
1759 template <class T>
CheckSequence(const CScriptNum & nSequence) const1760 bool GenericTransactionSignatureChecker<T>::CheckSequence(const CScriptNum& nSequence) const
1761 {
1762     // Relative lock times are supported by comparing the passed
1763     // in operand to the sequence number of the input.
1764     const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1765 
1766     // Fail if the transaction's version number is not set high
1767     // enough to trigger BIP 68 rules.
1768     if (static_cast<uint32_t>(txTo->nVersion) < 2)
1769         return false;
1770 
1771     // Sequence numbers with their most significant bit set are not
1772     // consensus constrained. Testing that the transaction's sequence
1773     // number do not have this bit set prevents using this property
1774     // to get around a CHECKSEQUENCEVERIFY check.
1775     if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1776         return false;
1777 
1778     // Mask off any bits that do not have consensus-enforced meaning
1779     // before doing the integer comparisons
1780     const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1781     const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1782     const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1783 
1784     // There are two kinds of nSequence: lock-by-blockheight
1785     // and lock-by-blocktime, distinguished by whether
1786     // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1787     //
1788     // We want to compare apples to apples, so fail the script
1789     // unless the type of nSequenceMasked being tested is the same as
1790     // the nSequenceMasked in the transaction.
1791     if (!(
1792         (txToSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1793         (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1794     )) {
1795         return false;
1796     }
1797 
1798     // Now that we know we're comparing apples-to-apples, the
1799     // comparison is a simple numeric one.
1800     if (nSequenceMasked > txToSequenceMasked)
1801         return false;
1802 
1803     return true;
1804 }
1805 
1806 // explicit instantiation
1807 template class GenericTransactionSignatureChecker<CTransaction>;
1808 template class GenericTransactionSignatureChecker<CMutableTransaction>;
1809 
ExecuteWitnessScript(const Span<const valtype> & stack_span,const CScript & scriptPubKey,unsigned int flags,SigVersion sigversion,const BaseSignatureChecker & checker,ScriptExecutionData & execdata,ScriptError * serror)1810 static bool ExecuteWitnessScript(const Span<const valtype>& stack_span, const CScript& scriptPubKey, unsigned int flags, SigVersion sigversion, const BaseSignatureChecker& checker, ScriptExecutionData& execdata, ScriptError* serror)
1811 {
1812     std::vector<valtype> stack{stack_span.begin(), stack_span.end()};
1813 
1814     if (sigversion == SigVersion::TAPSCRIPT) {
1815         // OP_SUCCESSx processing overrides everything, including stack element size limits
1816         CScript::const_iterator pc = scriptPubKey.begin();
1817         while (pc < scriptPubKey.end()) {
1818             opcodetype opcode;
1819             if (!scriptPubKey.GetOp(pc, opcode)) {
1820                 // Note how this condition would not be reached if an unknown OP_SUCCESSx was found
1821                 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1822             }
1823             // New opcodes will be listed here. May use a different sigversion to modify existing opcodes.
1824             if (IsOpSuccess(opcode)) {
1825                 if (flags & SCRIPT_VERIFY_DISCOURAGE_OP_SUCCESS) {
1826                     return set_error(serror, SCRIPT_ERR_DISCOURAGE_OP_SUCCESS);
1827                 }
1828                 return set_success(serror);
1829             }
1830         }
1831 
1832         // Tapscript enforces initial stack size limits (altstack is empty here)
1833         if (stack.size() > MAX_STACK_SIZE) return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1834     }
1835 
1836     // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
1837     for (const valtype& elem : stack) {
1838         if (elem.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
1839     }
1840 
1841     // Run the script interpreter.
1842     if (!EvalScript(stack, scriptPubKey, flags, checker, sigversion, execdata, serror)) return false;
1843 
1844     // Scripts inside witness implicitly require cleanstack behaviour
1845     if (stack.size() != 1) return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1846     if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1847     return true;
1848 }
1849 
ComputeTapleafHash(uint8_t leaf_version,const CScript & script)1850 uint256 ComputeTapleafHash(uint8_t leaf_version, const CScript& script)
1851 {
1852     return (CHashWriter(HASHER_TAPLEAF) << leaf_version << script).GetSHA256();
1853 }
1854 
ComputeTaprootMerkleRoot(Span<const unsigned char> control,const uint256 & tapleaf_hash)1855 uint256 ComputeTaprootMerkleRoot(Span<const unsigned char> control, const uint256& tapleaf_hash)
1856 {
1857     const int path_len = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
1858     uint256 k = tapleaf_hash;
1859     for (int i = 0; i < path_len; ++i) {
1860         CHashWriter ss_branch{HASHER_TAPBRANCH};
1861         Span<const unsigned char> node(control.data() + TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * i, TAPROOT_CONTROL_NODE_SIZE);
1862         if (std::lexicographical_compare(k.begin(), k.end(), node.begin(), node.end())) {
1863             ss_branch << k << node;
1864         } else {
1865             ss_branch << node << k;
1866         }
1867         k = ss_branch.GetSHA256();
1868     }
1869     return k;
1870 }
1871 
VerifyTaprootCommitment(const std::vector<unsigned char> & control,const std::vector<unsigned char> & program,const uint256 & tapleaf_hash)1872 static bool VerifyTaprootCommitment(const std::vector<unsigned char>& control, const std::vector<unsigned char>& program, const uint256& tapleaf_hash)
1873 {
1874     assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE);
1875     assert(program.size() >= uint256::size());
1876     //! The internal pubkey (x-only, so no Y coordinate parity).
1877     const XOnlyPubKey p{uint256(std::vector<unsigned char>(control.begin() + 1, control.begin() + TAPROOT_CONTROL_BASE_SIZE))};
1878     //! The output pubkey (taken from the scriptPubKey).
1879     const XOnlyPubKey q{uint256(program)};
1880     // Compute the Merkle root from the leaf and the provided path.
1881     const uint256 merkle_root = ComputeTaprootMerkleRoot(control, tapleaf_hash);
1882     // Verify that the output pubkey matches the tweaked internal pubkey, after correcting for parity.
1883     return q.CheckTapTweak(p, merkle_root, control[0] & 1);
1884 }
1885 
VerifyWitnessProgram(const CScriptWitness & witness,int witversion,const std::vector<unsigned char> & program,unsigned int flags,const BaseSignatureChecker & checker,ScriptError * serror,bool is_p2sh)1886 static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror, bool is_p2sh)
1887 {
1888     CScript exec_script; //!< Actually executed script (last stack item in P2WSH; implied P2PKH script in P2WPKH; leaf script in P2TR)
1889     Span<const valtype> stack{witness.stack};
1890     ScriptExecutionData execdata;
1891 
1892     if (witversion == 0) {
1893         if (program.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
1894             // BIP141 P2WSH: 32-byte witness v0 program (which encodes SHA256(script))
1895             if (stack.size() == 0) {
1896                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1897             }
1898             const valtype& script_bytes = SpanPopBack(stack);
1899             exec_script = CScript(script_bytes.begin(), script_bytes.end());
1900             uint256 hash_exec_script;
1901             CSHA256().Write(exec_script.data(), exec_script.size()).Finalize(hash_exec_script.begin());
1902             if (memcmp(hash_exec_script.begin(), program.data(), 32)) {
1903                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1904             }
1905             return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
1906         } else if (program.size() == WITNESS_V0_KEYHASH_SIZE) {
1907             // BIP141 P2WPKH: 20-byte witness v0 program (which encodes Hash160(pubkey))
1908             if (stack.size() != 2) {
1909                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1910             }
1911             exec_script << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
1912             return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
1913         } else {
1914             return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
1915         }
1916     } else if (witversion == 1 && program.size() == WITNESS_V1_TAPROOT_SIZE && !is_p2sh) {
1917         // BIP341 Taproot: 32-byte non-P2SH witness v1 program (which encodes a P2C-tweaked pubkey)
1918         if (!(flags & SCRIPT_VERIFY_TAPROOT)) return set_success(serror);
1919         if (stack.size() == 0) return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1920         if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
1921             // Drop annex (this is non-standard; see IsWitnessStandard)
1922             const valtype& annex = SpanPopBack(stack);
1923             execdata.m_annex_hash = (CHashWriter(SER_GETHASH, 0) << annex).GetSHA256();
1924             execdata.m_annex_present = true;
1925         } else {
1926             execdata.m_annex_present = false;
1927         }
1928         execdata.m_annex_init = true;
1929         if (stack.size() == 1) {
1930             // Key path spending (stack size is 1 after removing optional annex)
1931             if (!checker.CheckSchnorrSignature(stack.front(), program, SigVersion::TAPROOT, execdata, serror)) {
1932                 return false; // serror is set
1933             }
1934             return set_success(serror);
1935         } else {
1936             // Script path spending (stack size is >1 after removing optional annex)
1937             const valtype& control = SpanPopBack(stack);
1938             const valtype& script_bytes = SpanPopBack(stack);
1939             exec_script = CScript(script_bytes.begin(), script_bytes.end());
1940             if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE || ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) {
1941                 return set_error(serror, SCRIPT_ERR_TAPROOT_WRONG_CONTROL_SIZE);
1942             }
1943             execdata.m_tapleaf_hash = ComputeTapleafHash(control[0] & TAPROOT_LEAF_MASK, exec_script);
1944             if (!VerifyTaprootCommitment(control, program, execdata.m_tapleaf_hash)) {
1945                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1946             }
1947             execdata.m_tapleaf_hash_init = true;
1948             if ((control[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
1949                 // Tapscript (leaf version 0xc0)
1950                 execdata.m_validation_weight_left = ::GetSerializeSize(witness.stack, PROTOCOL_VERSION) + VALIDATION_WEIGHT_OFFSET;
1951                 execdata.m_validation_weight_left_init = true;
1952                 return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::TAPSCRIPT, checker, execdata, serror);
1953             }
1954             if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION) {
1955                 return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION);
1956             }
1957             return set_success(serror);
1958         }
1959     } else {
1960         if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
1961             return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
1962         }
1963         // Other version/size/p2sh combinations return true for future softfork compatibility
1964         return true;
1965     }
1966     // 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.
1967 }
1968 
VerifyScript(const CScript & scriptSig,const CScript & scriptPubKey,const CScriptWitness * witness,unsigned int flags,const BaseSignatureChecker & checker,ScriptError * serror)1969 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1970 {
1971     static const CScriptWitness emptyWitness;
1972     if (witness == nullptr) {
1973         witness = &emptyWitness;
1974     }
1975     bool hadWitness = false;
1976 
1977     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1978 
1979     if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1980         return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1981     }
1982 
1983     // scriptSig and scriptPubKey must be evaluated sequentially on the same stack
1984     // rather than being simply concatenated (see CVE-2010-5141)
1985     std::vector<std::vector<unsigned char> > stack, stackCopy;
1986     if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
1987         // serror is set
1988         return false;
1989     if (flags & SCRIPT_VERIFY_P2SH)
1990         stackCopy = stack;
1991     if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
1992         // serror is set
1993         return false;
1994     if (stack.empty())
1995         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1996     if (CastToBool(stack.back()) == false)
1997         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1998 
1999     // Bare witness programs
2000     int witnessversion;
2001     std::vector<unsigned char> witnessprogram;
2002     if (flags & SCRIPT_VERIFY_WITNESS) {
2003         if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2004             hadWitness = true;
2005             if (scriptSig.size() != 0) {
2006                 // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
2007                 return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
2008             }
2009             if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /* is_p2sh */ false)) {
2010                 return false;
2011             }
2012             // Bypass the cleanstack check at the end. The actual stack is obviously not clean
2013             // for witness programs.
2014             stack.resize(1);
2015         }
2016     }
2017 
2018     // Additional validation for spend-to-script-hash transactions:
2019     if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
2020     {
2021         // scriptSig must be literals-only or validation fails
2022         if (!scriptSig.IsPushOnly())
2023             return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
2024 
2025         // Restore stack.
2026         swap(stack, stackCopy);
2027 
2028         // stack cannot be empty here, because if it was the
2029         // P2SH  HASH <> EQUAL  scriptPubKey would be evaluated with
2030         // an empty stack and the EvalScript above would return false.
2031         assert(!stack.empty());
2032 
2033         const valtype& pubKeySerialized = stack.back();
2034         CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
2035         popstack(stack);
2036 
2037         if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
2038             // serror is set
2039             return false;
2040         if (stack.empty())
2041             return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2042         if (!CastToBool(stack.back()))
2043             return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2044 
2045         // P2SH witness program
2046         if (flags & SCRIPT_VERIFY_WITNESS) {
2047             if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
2048                 hadWitness = true;
2049                 if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
2050                     // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
2051                     // reintroduce malleability.
2052                     return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
2053                 }
2054                 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /* is_p2sh */ true)) {
2055                     return false;
2056                 }
2057                 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
2058                 // for witness programs.
2059                 stack.resize(1);
2060             }
2061         }
2062     }
2063 
2064     // The CLEANSTACK check is only performed after potential P2SH evaluation,
2065     // as the non-P2SH evaluation of a P2SH script will obviously not result in
2066     // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
2067     if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
2068         // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
2069         // would be possible, which is not a softfork (and P2SH should be one).
2070         assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2071         assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
2072         if (stack.size() != 1) {
2073             return set_error(serror, SCRIPT_ERR_CLEANSTACK);
2074         }
2075     }
2076 
2077     if (flags & SCRIPT_VERIFY_WITNESS) {
2078         // We can't check for correct unexpected witness data if P2SH was off, so require
2079         // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
2080         // possible, which is not a softfork.
2081         assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2082         if (!hadWitness && !witness->IsNull()) {
2083             return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
2084         }
2085     }
2086 
2087     return set_success(serror);
2088 }
2089 
WitnessSigOps(int witversion,const std::vector<unsigned char> & witprogram,const CScriptWitness & witness)2090 size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness)
2091 {
2092     if (witversion == 0) {
2093         if (witprogram.size() == WITNESS_V0_KEYHASH_SIZE)
2094             return 1;
2095 
2096         if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.stack.size() > 0) {
2097             CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
2098             return subscript.GetSigOpCount(true);
2099         }
2100     }
2101 
2102     // Future flags may be implemented here.
2103     return 0;
2104 }
2105 
CountWitnessSigOps(const CScript & scriptSig,const CScript & scriptPubKey,const CScriptWitness * witness,unsigned int flags)2106 size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags)
2107 {
2108     static const CScriptWitness witnessEmpty;
2109 
2110     if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
2111         return 0;
2112     }
2113     assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2114 
2115     int witnessversion;
2116     std::vector<unsigned char> witnessprogram;
2117     if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2118         return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
2119     }
2120 
2121     if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
2122         CScript::const_iterator pc = scriptSig.begin();
2123         std::vector<unsigned char> data;
2124         while (pc < scriptSig.end()) {
2125             opcodetype opcode;
2126             scriptSig.GetOp(pc, opcode, data);
2127         }
2128         CScript subscript(data.begin(), data.end());
2129         if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
2130             return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
2131         }
2132     }
2133 
2134     return 0;
2135 }
2136