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