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