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 : 2237012 : inline bool set_success(ScriptError* ret)
31 : : {
32 : 2237012 : if (ret)
33 : 1943952 : *ret = SCRIPT_ERR_OK;
34 : : return true;
35 : : }
36 : :
37 : 3066888 : inline bool set_error(ScriptError* ret, const ScriptError serror)
38 : : {
39 [ - - - - : 5803 : if (ret)
- - - + +
- + - + -
+ - ]
40 : 2535348 : *ret = serror;
41 : 2758563 : return false;
42 : : }
43 : :
44 : : } // namespace
45 : :
46 : 903595 : bool CastToBool(const valtype& vch)
47 : : {
48 [ - + + + ]: 910295 : for (unsigned int i = 0; i < vch.size(); i++)
49 : : {
50 [ + + ]: 860353 : if (vch[i] != 0)
51 : : {
52 : : // Can be negative zero
53 [ + + + + ]: 853653 : if (i == vch.size()-1 && vch[i] == 0x80)
54 : : return false;
55 : 853139 : 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 : 10291425 : static inline void popstack(std::vector<valtype>& stack)
68 : : {
69 [ - + ]: 10291425 : if (stack.empty())
70 [ # # ]: 0 : throw std::runtime_error("popstack(): stack empty");
71 : 10291425 : stack.pop_back();
72 : 10291425 : }
73 : :
74 : 74557 : bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
75 [ - + + + ]: 74557 : if (vchPubKey.size() < CPubKey::COMPRESSED_SIZE) {
76 : : // Non-canonical public key: too short
77 : : return false;
78 : : }
79 [ + + ]: 74207 : if (vchPubKey[0] == 0x04) {
80 [ + + ]: 6102 : if (vchPubKey.size() != CPubKey::SIZE) {
81 : : // Non-canonical public key: invalid length for uncompressed key
82 : 273 : return false;
83 : : }
84 [ + + + + ]: 68105 : } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
85 [ + + ]: 66848 : if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
86 : : // Non-canonical public key: invalid length for compressed key
87 : 126 : return false;
88 : : }
89 : : } else {
90 : : // Non-canonical public key: neither compressed nor uncompressed
91 : : return false;
92 : : }
93 : : return true;
94 : : }
95 : :
96 : 43410 : bool static IsCompressedPubKey(const valtype &vchPubKey) {
97 [ - + + + ]: 43410 : if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
98 : : // Non-canonical public key: invalid length for compressed key
99 : : return false;
100 : : }
101 [ + + + + ]: 36211 : if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
102 : : // Non-canonical public key: invalid prefix for compressed key
103 : 124 : 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 : 234958 : 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 [ - + + + ]: 234958 : if (sig.size() < 9) return false;
133 [ + + ]: 233762 : if (sig.size() > 73) return false;
134 : :
135 : : // A signature is of type 0x30 (compound).
136 [ + + ]: 233466 : if (sig[0] != 0x30) return false;
137 : :
138 : : // Make sure the length covers the entire signature.
139 [ + + ]: 231801 : if (sig[1] != sig.size() - 3) return false;
140 : :
141 : : // Extract the length of the R element.
142 : 222164 : unsigned int lenR = sig[3];
143 : :
144 : : // Make sure the length of the S element is still inside the signature.
145 [ + + ]: 222164 : if (5 + lenR >= sig.size()) return false;
146 : :
147 : : // Extract the length of the S element.
148 [ + + ]: 222033 : 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 [ + + ]: 222033 : if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
153 : :
154 : : // Check whether the R element is an integer.
155 [ + + ]: 221914 : if (sig[2] != 0x02) return false;
156 : :
157 : : // Zero-length integers are not allowed for R.
158 [ + + ]: 221768 : if (lenR == 0) return false;
159 : :
160 : : // Negative numbers are not allowed for R.
161 [ + + ]: 221642 : 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 [ + + + + : 219192 : if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
+ + ]
166 : :
167 : : // Check whether the S element is an integer.
168 [ + + ]: 218067 : if (sig[lenR + 4] != 0x02) return false;
169 : :
170 : : // Zero-length integers are not allowed for S.
171 [ + + ]: 217936 : if (lenS == 0) return false;
172 : :
173 : : // Negative numbers are not allowed for S.
174 [ + + ]: 217804 : 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 [ + + + + : 217595 : if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
+ + ]
179 : :
180 : : return true;
181 : : }
182 : :
183 : 65601 : bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
184 [ - + ]: 65601 : if (!IsValidSignatureEncoding(vchSig)) {
185 [ - - ]: 65601 : 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 [ - + ]: 65601 : 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 [ + - + + ]: 65601 : if (!CPubKey::CheckLowS(vchSigCopy)) {
195 [ + - ]: 65968 : return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
196 : : }
197 : : return true;
198 : 65601 : }
199 : :
200 : 68729 : bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
201 [ - + + - ]: 68729 : if (vchSig.size() == 0) {
202 : : return false;
203 : : }
204 [ + + ]: 68729 : unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
205 [ + + ]: 68729 : if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
206 : 804 : return false;
207 : :
208 : : return true;
209 : : }
210 : :
211 : 231287 : 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 [ - + + + ]: 231287 : if (vchSig.size() == 0) {
215 : : return true;
216 : : }
217 [ + + + + ]: 209072 : if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
218 [ + + ]: 17623 : return set_error(serror, SCRIPT_ERR_SIG_DER);
219 [ + + + + ]: 191449 : } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
220 : : // serror is set
221 : : return false;
222 [ + + + + ]: 191082 : } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
223 [ + + ]: 804 : return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
224 : : }
225 : : return true;
226 : : }
227 : :
228 : 211209 : bool static CheckPubKeyEncoding(const valtype &vchPubKey, script_verify_flags flags, const SigVersion &sigversion, ScriptError* serror) {
229 [ + + + + ]: 211209 : if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
230 [ + - ]: 2006 : return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
231 : : }
232 : : // Only compressed keys are accepted in segwit
233 [ + + + + : 209203 : if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SigVersion::WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
+ + ]
234 [ + - ]: 7323 : return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
235 : : }
236 : : return true;
237 : : }
238 : :
239 : 240057 : int FindAndDelete(CScript& script, const CScript& b)
240 : : {
241 : 240057 : int nFound = 0;
242 [ + + + + ]: 370628 : if (b.empty())
243 : : return nFound;
244 : 240056 : CScript result;
245 [ + + + + ]: 720168 : CScript::const_iterator pc = script.begin(), pc2 = script.begin(), end = script.end();
246 : 2704726 : opcodetype opcode;
247 : 2704726 : do
248 : : {
249 : 2704726 : result.insert(result.end(), pc2, pc);
250 [ + + + + : 5370862 : while (static_cast<size_t>(end - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
+ + + + ]
251 : : {
252 : 26776 : pc = pc + b.size();
253 : 26776 : ++nFound;
254 : : }
255 : 2704726 : pc2 = pc;
256 : : }
257 [ + - + + ]: 2704726 : while (script.GetOp(pc, opcode));
258 : :
259 [ + + ]: 240056 : if (nFound > 0) {
260 : 20312 : result.insert(result.end(), pc2, end);
261 : 20312 : script = std::move(result);
262 : : }
263 : :
264 : 240056 : return nFound;
265 : 240056 : }
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 : 1824998 : bool empty() const { return m_stack_size == 0; }
295 : 14105564 : bool all_true() const { return m_first_false_pos == NO_FALSE; }
296 : 71491 : void push_back(bool f)
297 : : {
298 [ + + ]: 68231 : 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 : 40289 : m_first_false_pos = m_stack_size;
302 : : }
303 : 71491 : ++m_stack_size;
304 : 71491 : }
305 : 52960 : void pop_back()
306 : : {
307 [ - + ]: 52960 : assert(m_stack_size > 0);
308 : 52960 : --m_stack_size;
309 [ + + ]: 52960 : if (m_first_false_pos == m_stack_size) {
310 : : // When popping off the first false value, everything becomes true.
311 : 20222 : m_first_false_pos = NO_FALSE;
312 : : }
313 : 52960 : }
314 : 57750 : void toggle_top()
315 : : {
316 [ - + ]: 57750 : assert(m_stack_size > 0);
317 [ + + ]: 57750 : if (m_first_false_pos == NO_FALSE) {
318 : : // The current stack is all true values; the first false will be the top.
319 : 18595 : m_first_false_pos = m_stack_size - 1;
320 [ + + ]: 39155 : } 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 : 35388 : 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 : 57750 : }
328 : : };
329 : : }
330 : :
331 : 198042 : 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 [ - + ]: 198042 : assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
334 : :
335 : : // Subset of script starting at the most recent codeseparator
336 : 198042 : CScript scriptCode(pbegincodehash, pend);
337 : :
338 : : // Drop the signature in pre-segwit scripts but not segwit scripts
339 [ + + ]: 198042 : if (sigversion == SigVersion::BASE) {
340 [ - + + - ]: 130367 : int found = FindAndDelete(scriptCode, CScript() << vchSig);
341 [ + + + + ]: 130367 : if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
342 [ + - ]: 233 : return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
343 : : }
344 : :
345 [ + - + + : 197809 : if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
+ + ]
346 : : //serror is set
347 : 20645 : return false;
348 : : }
349 [ + - ]: 177164 : fSuccess = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
350 : :
351 [ + + + + : 184340 : if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
+ + ]
352 [ + + ]: 199604 : return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
353 : :
354 : : return true;
355 : 198042 : }
356 : :
357 : 121403 : 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 [ - + ]: 121403 : 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 : 121403 : success = !sig.empty();
368 [ + + ]: 121403 : if (success) {
369 : : // Implement the sigops/witnesssize ratio test.
370 : : // Passing with an upgradable public key version is also counted.
371 [ - + ]: 28343 : assert(execdata.m_validation_weight_left_init);
372 : 28343 : execdata.m_validation_weight_left -= VALIDATION_WEIGHT_PER_SIGOP_PASSED;
373 [ + + ]: 28343 : if (execdata.m_validation_weight_left < 0) {
374 [ + - ]: 49 : return set_error(serror, SCRIPT_ERR_TAPSCRIPT_VALIDATION_WEIGHT);
375 : : }
376 : : }
377 [ - + + + ]: 121354 : if (pubkey.size() == 0) {
378 [ + - ]: 268 : return set_error(serror, SCRIPT_ERR_TAPSCRIPT_EMPTY_PUBKEY);
379 [ + + ]: 121086 : } else if (pubkey.size() == 32) {
380 [ + + - + : 117989 : if (success && !checker.CheckSchnorrSignature(sig, pubkey, sigversion, execdata, serror)) {
+ + ]
381 : 415 : 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 [ + + ]: 3097 : if ((flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_PUBKEYTYPE) != 0) {
390 [ + - ]: 6 : 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 : 319445 : 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 [ + + - ]: 319445 : switch (sigversion) {
405 : 198042 : case SigVersion::BASE:
406 : 198042 : case SigVersion::WITNESS_V0:
407 : 198042 : return EvalChecksigPreTapscript(sig, pubkey, pbegincodehash, pend, flags, checker, sigversion, serror, success);
408 : 121403 : case SigVersion::TAPSCRIPT:
409 : 121403 : 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 : 1923897 : 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 [ + + + + ]: 1923897 : static const CScriptNum bnZero(0);
420 [ + + + - ]: 1923897 : static const CScriptNum bnOne(1);
421 : : // static const CScriptNum bnFalse(0);
422 : : // static const CScriptNum bnTrue(1);
423 [ + + + - : 1925082 : static const valtype vchFalse(0);
+ - ]
424 : : // static const valtype vchZero(0);
425 [ + + + - : 1924404 : static const valtype vchTrue(1, 1);
+ - ]
426 : :
427 : : // sigversion cannot be TAPROOT here, as it admits no script execution.
428 [ + + - + ]: 1923897 : assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0 || sigversion == SigVersion::TAPSCRIPT);
429 : :
430 [ + + ]: 1923897 : CScript::const_iterator pc = script.begin();
431 : 1923897 : CScript::const_iterator pend = script.end();
432 [ + + ]: 1923897 : CScript::const_iterator pbegincodehash = script.begin();
433 : 1923897 : opcodetype opcode;
434 : 1923897 : valtype vchPushValue;
435 : 1923897 : ConditionStack vfExec;
436 : 1923897 : std::vector<valtype> altstack;
437 [ + + ]: 1923897 : set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
438 [ + + + + : 1923897 : if ((sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) && script.size() > MAX_SCRIPT_SIZE) {
+ + ]
439 [ + - ]: 93 : return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
440 : : }
441 : 1923804 : int nOpCount = 0;
442 : 1923804 : bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
443 : 1923804 : uint32_t opcode_pos = 0;
444 : 1923804 : execdata.m_codeseparator_pos = 0xFFFFFFFFUL;
445 : 1923804 : execdata.m_codeseparator_pos_init = true;
446 : :
447 : 1923804 : try
448 : : {
449 [ + + + + ]: 31635722 : for (; pc < pend; ++opcode_pos) {
450 : 14105564 : bool fExec = vfExec.all_true();
451 : :
452 : : //
453 : : // Read instruction
454 : : //
455 [ + - + + ]: 14105564 : if (!script.GetOp(pc, opcode, vchPushValue))
456 [ + - ]: 283 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
457 [ - + + + ]: 14105281 : if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
458 [ + - ]: 533 : return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
459 : :
460 [ + + ]: 14104748 : if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) {
461 : : // Note how OP_RESERVED does not count towards the opcode limit.
462 [ + + + + ]: 5807587 : if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT) {
463 [ + - ]: 748 : return set_error(serror, SCRIPT_ERR_OP_COUNT);
464 : : }
465 : : }
466 : :
467 : 14104000 : if (opcode == OP_CAT ||
468 : : opcode == OP_SUBSTR ||
469 [ + + ]: 14104000 : opcode == OP_LEFT ||
470 [ + + ]: 14102826 : opcode == OP_RIGHT ||
471 [ + + ]: 14102618 : opcode == OP_INVERT ||
472 [ + + ]: 14102511 : opcode == OP_AND ||
473 [ + + ]: 14102413 : opcode == OP_OR ||
474 [ + + ]: 14102314 : opcode == OP_XOR ||
475 [ + + ]: 14102116 : opcode == OP_2MUL ||
476 [ + + ]: 14101916 : opcode == OP_2DIV ||
477 [ + + ]: 14101719 : opcode == OP_MUL ||
478 [ + + ]: 14101515 : opcode == OP_DIV ||
479 [ + + ]: 14101313 : opcode == OP_MOD ||
480 [ + + ]: 14101108 : opcode == OP_LSHIFT ||
481 : : opcode == OP_RSHIFT)
482 [ + - ]: 3102 : 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 [ + + + + : 14100898 : if (opcode == OP_CODESEPARATOR && sigversion == SigVersion::BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
+ + ]
486 [ + - ]: 587 : return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
487 : :
488 [ + + + - : 14100311 : if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
+ + ]
489 [ + + + - : 3384371 : if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
+ + ]
490 [ + - ]: 2818 : return set_error(serror, SCRIPT_ERR_MINIMALDATA);
491 : : }
492 [ + - ]: 3381553 : stack.push_back(vchPushValue);
493 [ + + ]: 426589 : } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
494 [ + + + + : 10356046 : switch (opcode)
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ]
495 : : {
496 : : //
497 : : // Push value
498 : : //
499 : 664262 : case OP_1NEGATE:
500 : 664262 : case OP_1:
501 : 664262 : case OP_2:
502 : 664262 : case OP_3:
503 : 664262 : case OP_4:
504 : 664262 : case OP_5:
505 : 664262 : case OP_6:
506 : 664262 : case OP_7:
507 : 664262 : case OP_8:
508 : 664262 : case OP_9:
509 : 664262 : case OP_10:
510 : 664262 : case OP_11:
511 : 664262 : case OP_12:
512 : 664262 : case OP_13:
513 : 664262 : case OP_14:
514 : 664262 : case OP_15:
515 : 664262 : case OP_16:
516 : 664262 : {
517 : : // ( -- value)
518 [ + - ]: 664262 : CScriptNum bn((int)opcode - (int)(OP_1 - 1));
519 [ + - + - ]: 664262 : 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 : 664262 : break;
524 : :
525 : :
526 : : //
527 : : // Control
528 : : //
529 : : case OP_NOP:
530 : : break;
531 : :
532 : 13654 : case OP_CHECKLOCKTIMEVERIFY:
533 : 13654 : {
534 [ + + ]: 13654 : if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
535 : : // not enabled; treat as a NOP2
536 : : break;
537 : : }
538 : :
539 [ - + + + ]: 7679 : if (stack.size() < 1)
540 [ + - ]: 211 : 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 [ + - + + ]: 7468 : 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 [ + + + + ]: 14432 : if (nLockTime < 0)
562 [ + - ]: 241 : return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
563 : :
564 : : // Actually compare the specified lock time with the transaction.
565 [ + - + + ]: 6975 : if (!checker.CheckLockTime(nLockTime))
566 [ + - ]: 6256 : return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
567 : :
568 : : break;
569 : : }
570 : :
571 : 20637 : case OP_CHECKSEQUENCEVERIFY:
572 : 20637 : {
573 [ + + ]: 20637 : if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
574 : : // not enabled; treat as a NOP3
575 : : break;
576 : : }
577 : :
578 [ - + + + ]: 14248 : if (stack.size() < 1)
579 [ + - ]: 165 : 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 [ + - + + ]: 14083 : 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 [ + + + + ]: 27378 : if (nSequence < 0)
590 [ + - ]: 386 : 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 [ + + ]: 13303 : if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
596 : : break;
597 : :
598 : : // Compare the specified sequence number with the input.
599 [ + - + + ]: 12603 : if (!checker.CheckSequence(nSequence))
600 [ + - ]: 5950 : return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
601 : :
602 : : break;
603 : : }
604 : :
605 : 10058 : case OP_NOP1: case OP_NOP4: case OP_NOP5:
606 : 10058 : case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
607 : 10058 : {
608 [ + + ]: 10058 : if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
609 [ + - ]: 2193 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
610 : : }
611 : : break;
612 : :
613 : 78667 : case OP_IF:
614 : 78667 : case OP_NOTIF:
615 : 78667 : {
616 : : // <expression> if [statements] [else [statements]] endif
617 : 78667 : bool fValue = false;
618 [ + + ]: 78667 : if (fExec)
619 : : {
620 [ - + + + ]: 75407 : if (stack.size() < 1)
621 [ + - ]: 2766 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
622 [ + - ]: 72641 : valtype& vch = stacktop(-1);
623 : : // Tapscript requires minimal IF/NOTIF inputs as a consensus rule.
624 [ + + ]: 72641 : 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 [ - + + + : 1383 : 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 [ + + + + ]: 72123 : if (sigversion == SigVersion::WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
633 [ - + + + ]: 6369 : if (vch.size() > 1)
634 [ + - ]: 1296 : return set_error(serror, SCRIPT_ERR_MINIMALIF);
635 [ + + + + ]: 5073 : if (vch.size() == 1 && vch[0] != 1)
636 [ + - ]: 2596 : return set_error(serror, SCRIPT_ERR_MINIMALIF);
637 : : }
638 [ + - ]: 68231 : fValue = CastToBool(vch);
639 [ + + ]: 68231 : if (opcode == OP_NOTIF)
640 : 8572 : fValue = !fValue;
641 [ + - ]: 68231 : popstack(stack);
642 : : }
643 [ + + ]: 71491 : vfExec.push_back(fValue);
644 : : }
645 : 71491 : break;
646 : :
647 : 58420 : case OP_ELSE:
648 : 58420 : {
649 [ + + ]: 58420 : if (vfExec.empty())
650 [ + - ]: 670 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
651 : 57750 : vfExec.toggle_top();
652 : : }
653 : 57750 : break;
654 : :
655 : 54281 : case OP_ENDIF:
656 : 54281 : {
657 [ + + ]: 54281 : if (vfExec.empty())
658 [ + - ]: 1321 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
659 : 52960 : vfExec.pop_back();
660 : : }
661 : 52960 : break;
662 : :
663 : 8799 : case OP_VERIFY:
664 : 8799 : {
665 : : // (true -- ) or
666 : : // (false -- false) and return
667 [ - + + + ]: 8799 : if (stack.size() < 1)
668 [ + - ]: 92 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
669 [ + - + - ]: 8707 : bool fValue = CastToBool(stacktop(-1));
670 [ + + ]: 8707 : if (fValue)
671 [ + - ]: 8497 : popstack(stack);
672 : : else
673 [ + - ]: 210 : return set_error(serror, SCRIPT_ERR_VERIFY);
674 : : }
675 : : break;
676 : :
677 : 1439 : case OP_RETURN:
678 [ + - ]: 1439 : return set_error(serror, SCRIPT_ERR_OP_RETURN);
679 : :
680 : : //
681 : : // Stack ops
682 : : //
683 : 9677 : case OP_TOALTSTACK:
684 : 9677 : {
685 [ - + + + ]: 9677 : if (stack.size() < 1)
686 [ + - ]: 95 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
687 [ + - + - ]: 9582 : altstack.push_back(stacktop(-1));
688 [ + - ]: 9582 : popstack(stack);
689 : : }
690 : : break;
691 : :
692 : 5986 : case OP_FROMALTSTACK:
693 : 5986 : {
694 [ - + + + ]: 5986 : if (altstack.size() < 1)
695 [ + - ]: 485 : return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
696 [ + - + - ]: 5501 : stack.push_back(altstacktop(-1));
697 [ + - ]: 5501 : popstack(altstack);
698 : : }
699 : : break;
700 : :
701 : 42696 : case OP_2DROP:
702 : 42696 : {
703 : : // (x1 x2 -- )
704 [ - + + + ]: 42696 : if (stack.size() < 2)
705 [ + - ]: 186 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
706 [ + - ]: 42510 : popstack(stack);
707 [ + - ]: 42510 : popstack(stack);
708 : : }
709 : : break;
710 : :
711 : 52030 : case OP_2DUP:
712 : 52030 : {
713 : : // (x1 x2 -- x1 x2 x1 x2)
714 [ - + + + ]: 52030 : if (stack.size() < 2)
715 [ + - ]: 510 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
716 [ + - + - ]: 51520 : valtype vch1 = stacktop(-2);
717 [ - + + - : 51520 : valtype vch2 = stacktop(-1);
+ - ]
718 [ + - ]: 51520 : stack.push_back(vch1);
719 [ + - ]: 51520 : stack.push_back(vch2);
720 : 51520 : }
721 : 51520 : break;
722 : :
723 : 315106 : case OP_3DUP:
724 : 315106 : {
725 : : // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
726 [ - + + + ]: 315106 : if (stack.size() < 3)
727 [ + - ]: 692 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
728 [ + - + - ]: 314414 : valtype vch1 = stacktop(-3);
729 [ - + + - : 314414 : valtype vch2 = stacktop(-2);
+ - ]
730 [ - + + - : 314414 : valtype vch3 = stacktop(-1);
+ - ]
731 [ + - ]: 314414 : stack.push_back(vch1);
732 [ + - ]: 314414 : stack.push_back(vch2);
733 [ + - ]: 314414 : stack.push_back(vch3);
734 : 314414 : }
735 : 314414 : break;
736 : :
737 : 975 : case OP_2OVER:
738 : 975 : {
739 : : // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
740 [ - + + + ]: 975 : if (stack.size() < 4)
741 [ + - ]: 461 : 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 : 3533 : case OP_2ROT:
750 : 3533 : {
751 : : // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
752 [ - + + + ]: 3533 : if (stack.size() < 6)
753 [ + - ]: 192 : 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 : 980 : case OP_2SWAP:
763 : 980 : {
764 : : // (x1 x2 x3 x4 -- x3 x4 x1 x2)
765 [ - + + + ]: 980 : if (stack.size() < 4)
766 [ + - ]: 466 : 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 : 1841 : case OP_IFDUP:
773 : 1841 : {
774 : : // (x - 0 | x x)
775 [ - + + + ]: 1841 : if (stack.size() < 1)
776 [ + - ]: 185 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
777 [ + - + - ]: 1656 : valtype vch = stacktop(-1);
778 [ + - + + ]: 1656 : if (CastToBool(vch))
779 [ + - ]: 846 : stack.push_back(vch);
780 : 0 : }
781 : 1656 : break;
782 : :
783 : 19374 : case OP_DEPTH:
784 : 19374 : {
785 : : // -- stacksize
786 [ - + + - ]: 19374 : CScriptNum bn(stack.size());
787 [ + - + - ]: 19374 : stack.push_back(bn.getvch());
788 : : }
789 : 19374 : break;
790 : :
791 : 48069 : case OP_DROP:
792 : 48069 : {
793 : : // (x -- )
794 [ - + + + ]: 48069 : if (stack.size() < 1)
795 [ + - ]: 200 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
796 [ + - ]: 47869 : popstack(stack);
797 : : }
798 : : break;
799 : :
800 : 167627 : case OP_DUP:
801 : 167627 : {
802 : : // (x -- x x)
803 [ - + + + ]: 167627 : if (stack.size() < 1)
804 [ + + ]: 84072 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
805 [ + - + - ]: 83555 : valtype vch = stacktop(-1);
806 [ + - ]: 83555 : stack.push_back(vch);
807 : 0 : }
808 : 83555 : break;
809 : :
810 : 1189 : case OP_NIP:
811 : 1189 : {
812 : : // (x1 x2 -- x2)
813 [ - + + + ]: 1189 : if (stack.size() < 2)
814 [ + - ]: 404 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
815 : 785 : stack.erase(stack.end() - 2);
816 : : }
817 : : break;
818 : :
819 : 1187 : case OP_OVER:
820 : 1187 : {
821 : : // (x1 x2 -- x1 x2 x1)
822 [ - + + + ]: 1187 : if (stack.size() < 2)
823 [ + - ]: 479 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
824 [ + - + - ]: 708 : valtype vch = stacktop(-2);
825 [ + - ]: 708 : stack.push_back(vch);
826 : 0 : }
827 : 708 : break;
828 : :
829 : 6578 : case OP_PICK:
830 : 6578 : case OP_ROLL:
831 : 6578 : {
832 : : // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
833 : : // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
834 [ - + + + ]: 6578 : if (stack.size() < 2)
835 [ + - ]: 562 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
836 [ + - + + ]: 6016 : int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
837 [ + - ]: 5768 : popstack(stack);
838 [ + + + + ]: 11165 : if (n < 0 || n >= (int)stack.size())
839 [ + - ]: 968 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
840 [ + - + - ]: 4800 : valtype vch = stacktop(-n-1);
841 [ + + ]: 4800 : if (opcode == OP_ROLL)
842 : 2382 : stack.erase(stack.end()-n-1);
843 [ + - ]: 4800 : stack.push_back(vch);
844 : 0 : }
845 : 4800 : break;
846 : :
847 : 3144 : case OP_ROT:
848 : 3144 : {
849 : : // (x1 x2 x3 -- x2 x3 x1)
850 : : // x2 x1 x3 after first swap
851 : : // x2 x3 x1 after second swap
852 [ - + + + ]: 3144 : if (stack.size() < 3)
853 [ + - ]: 478 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
854 [ + - - + : 2666 : swap(stacktop(-3), stacktop(-2));
+ - ]
855 [ - + + - : 2666 : swap(stacktop(-2), stacktop(-1));
- + + - ]
856 : : }
857 : 2666 : break;
858 : :
859 : 3863 : case OP_SWAP:
860 : 3863 : {
861 : : // (x1 x2 -- x2 x1)
862 [ - + + + ]: 3863 : if (stack.size() < 2)
863 [ + - ]: 465 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
864 [ + - - + : 3398 : swap(stacktop(-2), stacktop(-1));
+ - ]
865 : : }
866 : 3398 : break;
867 : :
868 : 18466 : case OP_TUCK:
869 : 18466 : {
870 : : // (x1 x2 -- x2 x1 x2)
871 [ - + + + ]: 18466 : if (stack.size() < 2)
872 [ + - ]: 471 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
873 [ + - + - ]: 17995 : valtype vch = stacktop(-1);
874 [ + - ]: 17995 : stack.insert(stack.end()-2, vch);
875 : 0 : }
876 : 17995 : break;
877 : :
878 : :
879 : 8380 : case OP_SIZE:
880 : 8380 : {
881 : : // (in -- in size)
882 [ - + + + ]: 8380 : if (stack.size() < 1)
883 [ + - ]: 182 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
884 [ + - - + : 8198 : CScriptNum bn(stacktop(-1).size());
+ - ]
885 [ + - + - ]: 8198 : stack.push_back(bn.getvch());
886 : : }
887 : 8198 : break;
888 : :
889 : :
890 : : //
891 : : // Bitwise logic
892 : : //
893 : 207075 : case OP_EQUAL:
894 : 207075 : case OP_EQUALVERIFY:
895 : : //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
896 : 207075 : {
897 : : // (x1 x2 - bool)
898 [ - + + + ]: 207075 : if (stack.size() < 2)
899 [ + - ]: 784 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
900 [ + - ]: 206291 : valtype& vch1 = stacktop(-2);
901 [ - + + - ]: 206291 : valtype& vch2 = stacktop(-1);
902 : 206291 : 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 [ + - ]: 206291 : popstack(stack);
909 [ + - ]: 206291 : popstack(stack);
910 [ + + + - ]: 210780 : stack.push_back(fEqual ? vchTrue : vchFalse);
911 [ + + ]: 206291 : if (opcode == OP_EQUALVERIFY)
912 : : {
913 [ + + ]: 86033 : if (fEqual)
914 [ + - ]: 84046 : popstack(stack);
915 : : else
916 [ + - ]: 1987 : return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
917 : : }
918 : : }
919 : : break;
920 : :
921 : :
922 : : //
923 : : // Numeric
924 : : //
925 : 7610276 : case OP_1ADD:
926 : 7610276 : case OP_1SUB:
927 : 7610276 : case OP_NEGATE:
928 : 7610276 : case OP_ABS:
929 : 7610276 : case OP_NOT:
930 : 7610276 : case OP_0NOTEQUAL:
931 : 7610276 : {
932 : : // (in -- out)
933 [ - + + + ]: 7610276 : if (stack.size() < 1)
934 [ + - ]: 598 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
935 [ + - + + ]: 7609678 : CScriptNum bn(stacktop(-1), fRequireMinimal);
936 [ + + + + : 7605904 : switch (opcode)
+ + - ]
937 : : {
938 : 1816 : 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 : 21961 : case OP_NOT: bn = (bn == bnZero); break;
943 : 7579000 : case OP_0NOTEQUAL: bn = (bn != bnZero); break;
944 : 0 : default: assert(!"invalid opcode"); break;
945 : : }
946 [ + - ]: 7605904 : popstack(stack);
947 [ + - + - ]: 7605904 : stack.push_back(bn.getvch());
948 : : }
949 : 7605904 : break;
950 : :
951 : 49979 : case OP_ADD:
952 : 49979 : case OP_SUB:
953 : 49979 : case OP_BOOLAND:
954 : 49979 : case OP_BOOLOR:
955 : 49979 : case OP_NUMEQUAL:
956 : 49979 : case OP_NUMEQUALVERIFY:
957 : 49979 : case OP_NUMNOTEQUAL:
958 : 49979 : case OP_LESSTHAN:
959 : 49979 : case OP_GREATERTHAN:
960 : 49979 : case OP_LESSTHANOREQUAL:
961 : 49979 : case OP_GREATERTHANOREQUAL:
962 : 49979 : case OP_MIN:
963 : 49979 : case OP_MAX:
964 : 49979 : {
965 : : // (x1 x2 -- out)
966 [ - + + + ]: 49979 : if (stack.size() < 2)
967 [ + - ]: 2528 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
968 [ + - + + ]: 47451 : CScriptNum bn1(stacktop(-2), fRequireMinimal);
969 [ - + + - : 44720 : CScriptNum bn2(stacktop(-1), fRequireMinimal);
+ + ]
970 [ + + + + : 43061 : CScriptNum bn(0);
+ + + + +
+ + + +
- ]
971 [ + + + + : 43061 : switch (opcode)
+ + + + +
+ + + +
- ]
972 : : {
973 : 8904 : case OP_ADD:
974 : 8904 : bn = bn1 + bn2;
975 : 8904 : break;
976 : :
977 : 1423 : case OP_SUB:
978 : 1423 : bn = bn1 - bn2;
979 : 1423 : break;
980 : :
981 [ + + + + ]: 7180 : case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
982 [ + + + + ]: 2856 : case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
983 : 8900 : case OP_NUMEQUAL: bn = (bn1 == bn2); break;
984 : 1226 : 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 [ + - ]: 43061 : popstack(stack);
995 [ + - ]: 43061 : popstack(stack);
996 [ + - + - ]: 43061 : stack.push_back(bn.getvch());
997 : :
998 [ + + ]: 43061 : if (opcode == OP_NUMEQUALVERIFY)
999 : : {
1000 [ - + + - : 1226 : if (CastToBool(stacktop(-1)))
+ - + + ]
1001 [ + - ]: 1031 : popstack(stack);
1002 : : else
1003 [ + - ]: 195 : return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
1004 : : }
1005 : : }
1006 : : break;
1007 : :
1008 : 3765 : case OP_WITHIN:
1009 : 3765 : {
1010 : : // (x min max -- out)
1011 [ - + + + ]: 3765 : if (stack.size() < 3)
1012 [ + - ]: 191 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1013 [ + - + + ]: 3574 : CScriptNum bn1(stacktop(-3), fRequireMinimal);
1014 [ - + + - : 3437 : CScriptNum bn2(stacktop(-2), fRequireMinimal);
+ + ]
1015 [ - + + - : 3311 : 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 : 158769 : case OP_RIPEMD160:
1029 : 158769 : case OP_SHA1:
1030 : 158769 : case OP_SHA256:
1031 : 158769 : case OP_HASH160:
1032 : 158769 : case OP_HASH256:
1033 : 158769 : {
1034 : : // (in -- hash)
1035 [ - + + + ]: 158769 : if (stack.size() < 1)
1036 [ + + ]: 8061 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1037 [ + - ]: 150708 : valtype& vch = stacktop(-1);
1038 [ + + + + : 154159 : valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
+ - ]
1039 [ + + ]: 150708 : if (opcode == OP_RIPEMD160)
1040 [ + - + - : 2652 : CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
+ - ]
1041 [ + + ]: 149382 : else if (opcode == OP_SHA1)
1042 [ + - + - : 22690 : CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
+ - ]
1043 [ + + ]: 138037 : else if (opcode == OP_SHA256)
1044 [ + - + - : 4050 : CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
+ - ]
1045 [ + + ]: 136012 : else if (opcode == OP_HASH160)
1046 [ + - - + : 134586 : CHash160().Write(vch).Finalize(vchHash);
+ - - + +
- ]
1047 [ + - ]: 1426 : else if (opcode == OP_HASH256)
1048 [ + - - + : 1426 : CHash256().Write(vch).Finalize(vchHash);
+ - - + +
- ]
1049 [ + - ]: 150708 : popstack(stack);
1050 [ + - ]: 150708 : stack.push_back(vchHash);
1051 : 0 : }
1052 : 150708 : break;
1053 : :
1054 : 3980 : case OP_CODESEPARATOR:
1055 : 3980 : {
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 : 3980 : pbegincodehash = pc;
1061 : 3980 : execdata.m_codeseparator_pos = opcode_pos;
1062 : : }
1063 : 3980 : break;
1064 : :
1065 : 234141 : case OP_CHECKSIG:
1066 : 234141 : case OP_CHECKSIGVERIFY:
1067 : 234141 : {
1068 : : // (sig pubkey -- bool)
1069 [ - + + + ]: 234141 : if (stack.size() < 2)
1070 [ + + ]: 9900 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1071 : :
1072 [ + - ]: 224241 : valtype& vchSig = stacktop(-2);
1073 [ - + + - ]: 224241 : valtype& vchPubKey = stacktop(-1);
1074 : :
1075 : 224241 : bool fSuccess = true;
1076 [ + - + + ]: 224241 : if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, fSuccess)) return false;
1077 [ + - ]: 201445 : popstack(stack);
1078 [ + - ]: 201445 : popstack(stack);
1079 [ + + + - ]: 226149 : stack.push_back(fSuccess ? vchTrue : vchFalse);
1080 [ + + ]: 201445 : if (opcode == OP_CHECKSIGVERIFY)
1081 : : {
1082 [ + + ]: 57174 : if (fSuccess)
1083 [ + - ]: 56791 : popstack(stack);
1084 : : else
1085 [ + - ]: 383 : return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
1086 : : }
1087 : : }
1088 : : break;
1089 : :
1090 : 95627 : case OP_CHECKSIGADD:
1091 : 95627 : {
1092 : : // OP_CHECKSIGADD is only available in Tapscript
1093 [ + + + + ]: 95627 : if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1094 : :
1095 : : // (sig num pubkey -- num)
1096 [ - + + + : 95208 : if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+ - ]
1097 : :
1098 [ + - ]: 95207 : const valtype& sig = stacktop(-3);
1099 [ - + + - : 95207 : const CScriptNum num(stacktop(-2), fRequireMinimal);
+ + ]
1100 [ - + + - ]: 95204 : const valtype& pubkey = stacktop(-1);
1101 : :
1102 : 95204 : bool success = true;
1103 [ + - + + ]: 95204 : if (!EvalChecksig(sig, pubkey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, success)) return false;
1104 [ + - ]: 94819 : popstack(stack);
1105 [ + - ]: 94819 : popstack(stack);
1106 [ + - ]: 94819 : popstack(stack);
1107 [ + + + - : 187167 : stack.push_back((num + (success ? 1 : 0)).getvch());
+ - ]
1108 : : }
1109 : 94819 : break;
1110 : :
1111 : 168929 : case OP_CHECKMULTISIG:
1112 : 168929 : case OP_CHECKMULTISIGVERIFY:
1113 : 168929 : {
1114 [ + + + - ]: 168929 : 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 : 168926 : int i = 1;
1119 [ - + + + ]: 168926 : if ((int)stack.size() < i)
1120 [ + - ]: 132 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1121 : :
1122 [ + - + + ]: 168794 : int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1123 [ + + ]: 168538 : if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
1124 [ + - ]: 322 : return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
1125 : 168216 : nOpCount += nKeysCount;
1126 [ + + ]: 168216 : if (nOpCount > MAX_OPS_PER_SCRIPT)
1127 [ + - ]: 387 : return set_error(serror, SCRIPT_ERR_OP_COUNT);
1128 : 167829 : 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 : 167829 : int ikey2 = nKeysCount + 2;
1132 : 167829 : i += nKeysCount;
1133 [ - + + + ]: 167829 : if ((int)stack.size() < i)
1134 [ + - ]: 138 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1135 : :
1136 [ + - + + ]: 167691 : int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1137 [ + + ]: 167296 : if (nSigsCount < 0 || nSigsCount > nKeysCount)
1138 [ + - ]: 305 : return set_error(serror, SCRIPT_ERR_SIG_COUNT);
1139 : 166991 : int isig = ++i;
1140 : 166991 : i += nSigsCount;
1141 [ - + + + ]: 166991 : if ((int)stack.size() < i)
1142 [ + + ]: 336 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1143 : :
1144 : : // Subset of script starting at the most recent codeseparator
1145 : 166655 : CScript scriptCode(pbegincodehash, pend);
1146 : :
1147 : : // Drop the signature in pre-segwit scripts but not segwit scripts
1148 [ + + ]: 233062 : for (int k = 0; k < nSigsCount; k++)
1149 : : {
1150 [ - + + - ]: 66698 : valtype& vchSig = stacktop(-isig-k);
1151 [ + + ]: 66698 : if (sigversion == SigVersion::BASE) {
1152 [ - + + - ]: 59655 : int found = FindAndDelete(scriptCode, CScript() << vchSig);
1153 [ + + + + ]: 59655 : if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
1154 [ + - ]: 291 : return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
1155 : : }
1156 : : }
1157 : :
1158 : : bool fSuccess = true;
1159 [ + + ]: 191080 : while (fSuccess && nSigsCount > 0)
1160 : : {
1161 [ - + + - ]: 30664 : valtype& vchSig = stacktop(-isig);
1162 [ - + + - ]: 30664 : 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 [ + - + + : 30664 : if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
+ + ]
1168 : : // serror is set
1169 : 5948 : return false;
1170 : : }
1171 : :
1172 : : // Check signature
1173 [ + - ]: 24716 : bool fOk = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
1174 : :
1175 [ + + ]: 24716 : if (fOk) {
1176 : 14368 : isig++;
1177 : 14368 : nSigsCount--;
1178 : : }
1179 : 24716 : ikey++;
1180 : 24716 : 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 [ + + ]: 24716 : if (nSigsCount > nKeysCount)
1186 : 7159 : fSuccess = false;
1187 : : }
1188 : :
1189 : : // Clean up stack of actual arguments
1190 [ + + ]: 854387 : while (i-- > 1) {
1191 : : // If the operation failed, we require that all signatures must be empty vector
1192 [ + + + + : 704358 : if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
+ + + - -
+ + + ]
1193 [ + + ]: 1060 : return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
1194 [ + + ]: 693971 : if (ikey2 > 0)
1195 : 643071 : ikey2--;
1196 [ + - ]: 693971 : 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 [ - + - + ]: 159356 : if (stack.size() < 1)
1206 [ # # ]: 0 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1207 [ + + + - : 159356 : if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
- + + + ]
1208 [ + - ]: 724 : return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1209 [ + - ]: 158632 : popstack(stack);
1210 : :
1211 [ + + + - ]: 164534 : stack.push_back(fSuccess ? vchTrue : vchFalse);
1212 : :
1213 [ + + ]: 158632 : if (opcode == OP_CHECKMULTISIGVERIFY)
1214 : : {
1215 [ + + ]: 62687 : if (fSuccess)
1216 [ + - ]: 62441 : popstack(stack);
1217 : : else
1218 [ + - ]: 8515 : return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1219 : : }
1220 : 8269 : }
1221 : 158386 : break;
1222 : :
1223 : 16218 : default:
1224 [ + - ]: 16218 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1225 : : }
1226 : :
1227 : : // Size limits
1228 [ - + - + : 13895178 : if (stack.size() + altstack.size() > MAX_STACK_SIZE)
+ + ]
1229 [ + - ]: 1121 : return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1230 : : }
1231 : : }
1232 [ + - ]: 10114 : catch (const scriptnum_error&)
1233 : : {
1234 [ + - ]: 10114 : return set_error(serror, SCRIPT_ERR_SCRIPTNUM);
1235 : 10114 : }
1236 : 0 : catch (...)
1237 : : {
1238 [ - - ]: 0 : return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1239 [ - - ]: 0 : }
1240 : :
1241 [ + + ]: 1712297 : if (!vfExec.empty())
1242 [ + - ]: 690 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1243 : :
1244 [ + + ]: 1711607 : return set_success(serror);
1245 : 1923897 : }
1246 : :
1247 : 1747303 : 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 : 1747303 : ScriptExecutionData execdata;
1250 : 1747303 : 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 : 127467 : CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1272 : 127467 : txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1273 : 127467 : fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1274 : 127467 : fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1275 : 127467 : fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1276 : :
1277 : : /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1278 : : template<typename S>
1279 : 127467 : void SerializeScriptCode(S &s) const {
1280 [ + + ]: 127467 : CScript::const_iterator it = scriptCode.begin();
1281 : 127467 : CScript::const_iterator itBegin = it;
1282 : : opcodetype opcode;
1283 : 127467 : unsigned int nCodeSeparators = 0;
1284 [ + + ]: 717424 : while (scriptCode.GetOp(it, opcode)) {
1285 [ + + ]: 589957 : if (opcode == OP_CODESEPARATOR)
1286 : 26506 : nCodeSeparators++;
1287 : : }
1288 [ + + ]: 159479 : ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1289 : 127467 : it = itBegin;
1290 [ + + ]: 844891 : while (scriptCode.GetOp(it, opcode)) {
1291 [ + + ]: 589957 : if (opcode == OP_CODESEPARATOR) {
1292 : 26506 : s.write(std::as_bytes(std::span{&itBegin[0], size_t(it - itBegin - 1)}));
1293 : 26506 : itBegin = it;
1294 : : }
1295 : : }
1296 [ + + ]: 127467 : if (itBegin != scriptCode.end())
1297 : 117377 : s.write(std::as_bytes(std::span{&itBegin[0], size_t(it - itBegin)}));
1298 : 127467 : }
1299 : :
1300 : : /** Serialize an input of txTo */
1301 : : template<typename S>
1302 : 964028 : void SerializeInput(S &s, unsigned int nInput) const {
1303 : : // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1304 [ + + ]: 964028 : if (fAnyoneCanPay)
1305 : 26294 : nInput = nIn;
1306 : : // Serialize the prevout
1307 : 964028 : ::Serialize(s, txTo.vin[nInput].prevout);
1308 : : // Serialize the script
1309 [ + + ]: 964028 : if (nInput != nIn)
1310 : : // Blank out other inputs' signatures
1311 [ + - ]: 1673122 : ::Serialize(s, CScript());
1312 : : else
1313 : 127467 : SerializeScriptCode(s);
1314 : : // Serialize the nSequence
1315 [ + + + + : 964028 : if (nInput != nIn && (fHashSingle || fHashNone))
+ + ]
1316 : : // let the others update at will
1317 : 2841 : ::Serialize(s, int32_t{0});
1318 : : else
1319 : 961187 : ::Serialize(s, txTo.vin[nInput].nSequence);
1320 : 964028 : }
1321 : :
1322 : : /** Serialize an output of txTo */
1323 : : template<typename S>
1324 : 478246 : void SerializeOutput(S &s, unsigned int nOutput) const {
1325 [ + + + + ]: 478246 : if (fHashSingle && nOutput != nIn)
1326 : : // Do not lock-in the txout payee at other indices as txin
1327 [ + - ]: 2940 : ::Serialize(s, CTxOut());
1328 : : else
1329 : 476776 : ::Serialize(s, txTo.vout[nOutput]);
1330 : 478246 : }
1331 : :
1332 : : /** Serialize txTo */
1333 : : template<typename S>
1334 : 127467 : void Serialize(S &s) const {
1335 : : // Serialize version
1336 : 127467 : ::Serialize(s, txTo.version);
1337 : : // Serialize vin
1338 [ + + - + ]: 127467 : unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1339 : 127467 : ::WriteCompactSize(s, nInputs);
1340 [ + + ]: 1091495 : for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1341 : 964028 : SerializeInput(s, nInput);
1342 : : // Serialize vout
1343 [ + + + + : 127467 : unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
- + ]
1344 : 127467 : ::WriteCompactSize(s, nOutputs);
1345 [ + + ]: 605713 : for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1346 : 478246 : SerializeOutput(s, nOutput);
1347 : : // Serialize nLockTime
1348 : 127467 : ::Serialize(s, txTo.nLockTime);
1349 : 127467 : }
1350 : : };
1351 : :
1352 : : /** Compute the (single) SHA256 of the concatenation of all prevouts of a tx. */
1353 : : template <class T>
1354 : 84185 : uint256 GetPrevoutsSHA256(const T& txTo)
1355 : : {
1356 : 84185 : HashWriter ss{};
1357 [ + + ]: 20519015 : for (const auto& txin : txTo.vin) {
1358 : 20434830 : ss << txin.prevout;
1359 : : }
1360 : 84185 : return ss.GetSHA256();
1361 : : }
1362 : :
1363 : : /** Compute the (single) SHA256 of the concatenation of all nSequences of a tx. */
1364 : : template <class T>
1365 : 81166 : uint256 GetSequencesSHA256(const T& txTo)
1366 : : {
1367 : 81166 : HashWriter ss{};
1368 [ + + ]: 7015976 : for (const auto& txin : txTo.vin) {
1369 : 6934810 : ss << txin.nSequence;
1370 : : }
1371 : 81166 : return ss.GetSHA256();
1372 : : }
1373 : :
1374 : : /** Compute the (single) SHA256 of the concatenation of all txouts of a tx. */
1375 : : template <class T>
1376 : 82687 : uint256 GetOutputsSHA256(const T& txTo)
1377 : : {
1378 : 82687 : HashWriter ss{};
1379 [ + + ]: 13980361 : for (const auto& txout : txTo.vout) {
1380 : 13897674 : ss << txout;
1381 : : }
1382 : 82687 : return ss.GetSHA256();
1383 : : }
1384 : :
1385 : : /** Compute the (single) SHA256 of the concatenation of all amounts spent by a tx. */
1386 : 65341 : uint256 GetSpentAmountsSHA256(const std::vector<CTxOut>& outputs_spent)
1387 : : {
1388 : 65341 : HashWriter ss{};
1389 [ + + ]: 201971 : for (const auto& txout : outputs_spent) {
1390 : 136630 : ss << txout.nValue;
1391 : : }
1392 : 65341 : return ss.GetSHA256();
1393 : : }
1394 : :
1395 : : /** Compute the (single) SHA256 of the concatenation of all scriptPubKeys spent by a tx. */
1396 : 65341 : uint256 GetSpentScriptsSHA256(const std::vector<CTxOut>& outputs_spent)
1397 : : {
1398 : 65341 : HashWriter ss{};
1399 [ + + ]: 201971 : for (const auto& txout : outputs_spent) {
1400 : 136630 : ss << txout.scriptPubKey;
1401 : : }
1402 : 65341 : return ss.GetSHA256();
1403 : : }
1404 : :
1405 : :
1406 : : } // namespace
1407 : :
1408 : : template <class T>
1409 : 96484 : void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent_outputs, bool force)
1410 : : {
1411 [ - + ]: 96484 : assert(!m_spent_outputs_ready);
1412 : :
1413 : 96484 : m_spent_outputs = std::move(spent_outputs);
1414 [ + + ]: 96484 : if (!m_spent_outputs.empty()) {
1415 [ - + - + : 96003 : assert(m_spent_outputs.size() == txTo.vin.size());
- + ]
1416 : 96003 : 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 [ - + + + : 213982 : for (size_t inpos = 0; inpos < txTo.vin.size() && !(uses_bip143_segwit && uses_bip341_taproot); ++inpos) {
+ + ]
1423 [ + + ]: 118414 : if (!txTo.vin[inpos].scriptWitness.empty()) {
1424 [ + + - + : 83302 : if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.size() == 2 + WITNESS_V1_TAPROOT_SIZE &&
+ + ]
1425 [ + - + + ]: 136764 : 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 [ + + ]: 118414 : if (uses_bip341_taproot && uses_bip143_segwit) break; // No need to scan further if we already need all.
1439 : : }
1440 : :
1441 [ + + ]: 96484 : if (uses_bip143_segwit || uses_bip341_taproot) {
1442 : : // Computations shared between both sighash schemes.
1443 : 71442 : m_prevouts_single_hash = GetPrevoutsSHA256(txTo);
1444 : 71442 : m_sequences_single_hash = GetSequencesSHA256(txTo);
1445 : 71442 : m_outputs_single_hash = GetOutputsSHA256(txTo);
1446 : : }
1447 [ + + ]: 71442 : if (uses_bip143_segwit) {
1448 : 26519 : hashPrevouts = SHA256Uint256(m_prevouts_single_hash);
1449 : 26519 : hashSequence = SHA256Uint256(m_sequences_single_hash);
1450 : 26519 : hashOutputs = SHA256Uint256(m_outputs_single_hash);
1451 : 26519 : m_bip143_segwit_ready = true;
1452 : : }
1453 [ + + + + ]: 96484 : if (uses_bip341_taproot && m_spent_outputs_ready) {
1454 : 65341 : m_spent_amounts_single_hash = GetSpentAmountsSHA256(m_spent_outputs);
1455 : 65341 : m_spent_scripts_single_hash = GetSpentScriptsSHA256(m_spent_outputs);
1456 : 65341 : m_bip341_taproot_ready = true;
1457 : : }
1458 : 96484 : }
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 : 37 : static bool HandleMissingData(MissingDataBehavior mdb)
1477 : : {
1478 [ - + - ]: 37 : switch (mdb) {
1479 : 0 : case MissingDataBehavior::ASSERT_FAIL:
1480 : 0 : assert(!"Missing data");
1481 : : break;
1482 : 37 : case MissingDataBehavior::FAIL:
1483 : 37 : return false;
1484 : : }
1485 : 0 : assert(!"Unknown MissingDataBehavior value");
1486 : : }
1487 : :
1488 : : template<typename T>
1489 : 38088 : 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 [ + - + ]: 38088 : switch (sigversion) {
1493 : : case SigVersion::TAPROOT:
1494 : : ext_flag = 0;
1495 : : // key_version is not used and left uninitialized.
1496 : : break;
1497 : 24316 : case SigVersion::TAPSCRIPT:
1498 : 24316 : 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 : 24316 : key_version = 0;
1504 : 24316 : break;
1505 : 0 : default:
1506 : 0 : assert(false);
1507 : : }
1508 [ - + - + ]: 38088 : assert(in_pos < tx_to.vin.size());
1509 [ + - - + ]: 38088 : if (!(cache.m_bip341_taproot_ready && cache.m_spent_outputs_ready)) {
1510 : 0 : return HandleMissingData(mdb);
1511 : : }
1512 : :
1513 : 38088 : HashWriter ss{HASHER_TAPSIGHASH};
1514 : :
1515 : : // Epoch
1516 : : static constexpr uint8_t EPOCH = 0;
1517 : 38088 : ss << EPOCH;
1518 : :
1519 : : // Hash type
1520 [ + + ]: 38088 : 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 : 37450 : const uint8_t input_type = hash_type & SIGHASH_INPUT_MASK;
1522 [ + + + + ]: 18759 : if (!(hash_type <= 0x03 || (hash_type >= 0x81 && hash_type <= 0x83))) return false;
1523 : 37450 : ss << hash_type;
1524 : :
1525 : : // Transaction level data
1526 : 37450 : ss << tx_to.version;
1527 : 37450 : ss << tx_to.nLockTime;
1528 [ + + ]: 37450 : if (input_type != SIGHASH_ANYONECANPAY) {
1529 : 28997 : ss << cache.m_prevouts_single_hash;
1530 : 28997 : ss << cache.m_spent_amounts_single_hash;
1531 : 28997 : ss << cache.m_spent_scripts_single_hash;
1532 : 28997 : ss << cache.m_sequences_single_hash;
1533 : : }
1534 [ + + ]: 37450 : if (output_type == SIGHASH_ALL) {
1535 : 26350 : ss << cache.m_outputs_single_hash;
1536 : : }
1537 : :
1538 : : // Data about the input/prevout being spent
1539 [ - + ]: 37450 : assert(execdata.m_annex_init);
1540 : 37450 : const bool have_annex = execdata.m_annex_present;
1541 [ + + ]: 73373 : const uint8_t spend_type = (ext_flag << 1) + (have_annex ? 1 : 0); // The low bit indicates whether an annex is present.
1542 : 37450 : ss << spend_type;
1543 [ + + ]: 37450 : if (input_type == SIGHASH_ANYONECANPAY) {
1544 : 8453 : ss << tx_to.vin[in_pos].prevout;
1545 : 8453 : ss << cache.m_spent_outputs[in_pos];
1546 : 8453 : ss << tx_to.vin[in_pos].nSequence;
1547 : : } else {
1548 : 28997 : ss << in_pos;
1549 : : }
1550 [ + + ]: 37450 : if (have_annex) {
1551 : 1527 : ss << execdata.m_annex_hash;
1552 : : }
1553 : :
1554 : : // Data about the output (if only one).
1555 [ + + ]: 37450 : if (output_type == SIGHASH_SINGLE) {
1556 [ - + + + ]: 4296 : if (in_pos >= tx_to.vout.size()) return false;
1557 [ + + ]: 4286 : if (!execdata.m_output_hash) {
1558 : 306 : HashWriter sha_single_output{};
1559 : 306 : sha_single_output << tx_to.vout[in_pos];
1560 [ - + ]: 306 : execdata.m_output_hash = sha_single_output.GetSHA256();
1561 : : }
1562 [ + - ]: 4286 : ss << execdata.m_output_hash.value();
1563 : : }
1564 : :
1565 : : // Additional data for BIP 342 signatures
1566 [ + + ]: 37440 : if (sigversion == SigVersion::TAPSCRIPT) {
1567 [ - + ]: 23994 : assert(execdata.m_tapleaf_hash_init);
1568 : 23994 : ss << execdata.m_tapleaf_hash;
1569 : 23994 : ss << key_version;
1570 [ - + ]: 23994 : assert(execdata.m_codeseparator_pos_init);
1571 : 23994 : ss << execdata.m_codeseparator_pos;
1572 : : }
1573 : :
1574 : 37440 : hash_out = ss.GetSHA256();
1575 : 37440 : return true;
1576 : : }
1577 : :
1578 : : // explicit instantiation
1579 : : template bool SignatureHashSchnorr<CTransaction>(uint256&, ScriptExecutionData&, const CTransaction&, uint32_t, uint8_t, SigVersion, const PrecomputedTransactionData&, MissingDataBehavior);
1580 : : template bool SignatureHashSchnorr<CMutableTransaction>(uint256&, ScriptExecutionData&, const CMutableTransaction&, uint32_t, uint8_t, SigVersion, const PrecomputedTransactionData&, MissingDataBehavior);
1581 : :
1582 : 311799 : int SigHashCache::CacheIndex(int32_t hash_type) const noexcept
1583 : : {
1584 : : // Note that we do not distinguish between BASE and WITNESS_V0 to determine the cache index,
1585 : : // because no input can simultaneously use both.
1586 [ + + ]: 311799 : return 3 * !!(hash_type & SIGHASH_ANYONECANPAY) +
1587 [ + + ]: 311799 : 2 * ((hash_type & 0x1f) == SIGHASH_SINGLE) +
1588 : 311799 : 1 * ((hash_type & 0x1f) == SIGHASH_NONE);
1589 : : }
1590 : :
1591 : 176691 : bool SigHashCache::Load(int32_t hash_type, const CScript& script_code, HashWriter& writer) const noexcept
1592 : : {
1593 : 176691 : auto& entry = m_cache_entries[CacheIndex(hash_type)];
1594 [ + + ]: 176691 : if (entry.has_value()) {
1595 [ + + ]: 42429 : if (script_code == entry->first) {
1596 : 41659 : writer = HashWriter(entry->second);
1597 : 41659 : return true;
1598 : : }
1599 : : }
1600 : : return false;
1601 : : }
1602 : :
1603 : 135108 : void SigHashCache::Store(int32_t hash_type, const CScript& script_code, const HashWriter& writer) noexcept
1604 : : {
1605 : 135108 : auto& entry = m_cache_entries[CacheIndex(hash_type)];
1606 : 135108 : entry.emplace(script_code, writer);
1607 : 135108 : }
1608 : :
1609 : : template <class T>
1610 : 246276 : 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)
1611 : : {
1612 [ - + - + ]: 246276 : assert(nIn < txTo.vin.size());
1613 : :
1614 [ + + ]: 246276 : if (sigversion != SigVersion::WITNESS_V0) {
1615 : : // Check for invalid use of SIGHASH_SINGLE
1616 [ + + ]: 166673 : if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1617 [ - + + + ]: 2408 : if (nIn >= txTo.vout.size()) {
1618 : : // nOut out of range
1619 : 287 : return uint256::ONE;
1620 : : }
1621 : : }
1622 : : }
1623 : :
1624 : 245989 : HashWriter ss{};
1625 : :
1626 : : // Try to compute using cached SHA256 midstate.
1627 [ + + + + ]: 245989 : if (sighash_cache && sighash_cache->Load(nHashType, scriptCode, ss)) {
1628 : : // Add sighash type and hash.
1629 : 41545 : ss << nHashType;
1630 : 41545 : return ss.GetHash();
1631 : : }
1632 : :
1633 [ + + ]: 204444 : if (sigversion == SigVersion::WITNESS_V0) {
1634 : 76977 : uint256 hashPrevouts;
1635 : 76977 : uint256 hashSequence;
1636 : 76977 : uint256 hashOutputs;
1637 [ + + - + ]: 76977 : const bool cacheready = cache && cache->m_bip143_segwit_ready;
1638 : :
1639 [ + + ]: 76977 : if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1640 [ + + ]: 64937 : hashPrevouts = cacheready ? cache->hashPrevouts : SHA256Uint256(GetPrevoutsSHA256(txTo));
1641 : : }
1642 : :
1643 [ + + + + ]: 64937 : if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1644 [ + + ]: 58108 : hashSequence = cacheready ? cache->hashSequence : SHA256Uint256(GetSequencesSHA256(txTo));
1645 : : }
1646 : :
1647 [ + + ]: 76977 : if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1648 [ + + ]: 63296 : hashOutputs = cacheready ? cache->hashOutputs : SHA256Uint256(GetOutputsSHA256(txTo));
1649 [ + + - + : 13681 : } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
+ + ]
1650 : 6349 : HashWriter inner_ss{};
1651 : 6349 : inner_ss << txTo.vout[nIn];
1652 : 6349 : hashOutputs = inner_ss.GetHash();
1653 : : }
1654 : :
1655 : : // Version
1656 : 76977 : ss << txTo.version;
1657 : : // Input prevouts/nSequence (none/all, depending on flags)
1658 : 76977 : ss << hashPrevouts;
1659 : 76977 : ss << hashSequence;
1660 : : // The input being signed (replacing the scriptSig with scriptCode + amount)
1661 : : // The prevout may already be contained in hashPrevout, and the nSequence
1662 : : // may already be contain in hashSequence.
1663 : 76977 : ss << txTo.vin[nIn].prevout;
1664 : 76977 : ss << scriptCode;
1665 : 76977 : ss << amount;
1666 : 76977 : ss << txTo.vin[nIn].nSequence;
1667 : : // Outputs (none/one/all, depending on flags)
1668 : 76977 : ss << hashOutputs;
1669 : : // Locktime
1670 : 76977 : ss << txTo.nLockTime;
1671 : : } else {
1672 : : // Wrapper to serialize only the necessary parts of the transaction being signed
1673 : 127467 : CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
1674 : :
1675 : : // Serialize
1676 : 127467 : ss << txTmp;
1677 : : }
1678 : :
1679 : : // If a cache object was provided, store the midstate there.
1680 [ + + ]: 204444 : if (sighash_cache != nullptr) {
1681 : 135032 : sighash_cache->Store(nHashType, scriptCode, ss);
1682 : : }
1683 : :
1684 : : // Add sighash type and hash.
1685 : 204444 : ss << nHashType;
1686 : 204444 : return ss.GetHash();
1687 : : }
1688 : :
1689 : : // explicit instantiation
1690 : : template uint256 SignatureHash<CTransaction>(const CScript&, const CTransaction&, unsigned int, int32_t, const CAmount&, SigVersion, const PrecomputedTransactionData*, SigHashCache*);
1691 : : template uint256 SignatureHash<CMutableTransaction>(const CScript&, const CMutableTransaction&, unsigned int, int32_t, const CAmount&, SigVersion, const PrecomputedTransactionData*, SigHashCache*);
1692 : :
1693 : : template <class T>
1694 : 126239 : bool GenericTransactionSignatureChecker<T>::VerifyECDSASignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1695 : : {
1696 : 126239 : return pubkey.Verify(sighash, vchSig);
1697 : : }
1698 : :
1699 : : template <class T>
1700 : 24239 : bool GenericTransactionSignatureChecker<T>::VerifySchnorrSignature(std::span<const unsigned char> sig, const XOnlyPubKey& pubkey, const uint256& sighash) const
1701 : : {
1702 : 24239 : return pubkey.VerifySchnorr(sighash, sig);
1703 : : }
1704 : :
1705 : : template <class T>
1706 [ - + ]: 202421 : bool GenericTransactionSignatureChecker<T>::CheckECDSASignature(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1707 : : {
1708 [ + + ]: 202421 : CPubKey pubkey(vchPubKey);
1709 [ + + ]: 202421 : if (!pubkey.IsValid())
1710 : : return false;
1711 : :
1712 : : // Hash type is one byte tacked on to the end of the signature
1713 : 197003 : std::vector<unsigned char> vchSig(vchSigIn);
1714 [ + + ]: 197003 : if (vchSig.empty())
1715 : : return false;
1716 [ + + ]: 176598 : int nHashType = vchSig.back();
1717 : 176598 : vchSig.pop_back();
1718 : :
1719 : : // Witness sighashes need the amount.
1720 [ + + - + ]: 176598 : if (sigversion == SigVersion::WITNESS_V0 && amount < 0) return HandleMissingData(m_mdb);
1721 : :
1722 [ + - ]: 176598 : uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata, &m_sighash_cache);
1723 : :
1724 [ + - + + ]: 176598 : if (!VerifyECDSASignature(vchSig, pubkey, sighash))
1725 : 10630 : return false;
1726 : :
1727 : : return true;
1728 : 197003 : }
1729 : :
1730 : : template <class T>
1731 : 36554 : bool GenericTransactionSignatureChecker<T>::CheckSchnorrSignature(std::span<const unsigned char> sig, std::span<const unsigned char> pubkey_in, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) const
1732 : : {
1733 [ - + ]: 36554 : assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
1734 : : // Schnorr signatures have 32-byte public keys. The caller is responsible for enforcing this.
1735 [ - + ]: 36554 : assert(pubkey_in.size() == 32);
1736 : : // Note that in Tapscript evaluation, empty signatures are treated specially (invalid signature that does not
1737 : : // abort script execution). This is implemented in EvalChecksigTapscript, which won't invoke
1738 : : // CheckSchnorrSignature in that case. In other contexts, they are invalid like every other signature with
1739 : : // size different from 64 or 65.
1740 [ + + + + ]: 36554 : if (sig.size() != 64 && sig.size() != 65) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_SIZE);
1741 : :
1742 : 36527 : XOnlyPubKey pubkey{pubkey_in};
1743 : :
1744 [ + + ]: 36527 : uint8_t hashtype = SIGHASH_DEFAULT;
1745 [ + + ]: 36527 : if (sig.size() == 65) {
1746 : 18734 : hashtype = SpanPopBack(sig);
1747 [ + + ]: 18734 : if (hashtype == SIGHASH_DEFAULT) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
1748 : : }
1749 : 36516 : uint256 sighash;
1750 [ + + ]: 36516 : if (!this->txdata) return HandleMissingData(m_mdb);
1751 [ + + ]: 36479 : if (!SignatureHashSchnorr(sighash, execdata, *txTo, nIn, hashtype, sigversion, *this->txdata, m_mdb)) {
1752 : 36554 : return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
1753 : : }
1754 [ + + ]: 35832 : if (!VerifySchnorrSignature(sig, pubkey, sighash)) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG);
1755 : : return true;
1756 : : }
1757 : :
1758 : : template <class T>
1759 : 7775 : bool GenericTransactionSignatureChecker<T>::CheckLockTime(const CScriptNum& nLockTime) const
1760 : : {
1761 : : // There are two kinds of nLockTime: lock-by-blockheight
1762 : : // and lock-by-blocktime, distinguished by whether
1763 : : // nLockTime < LOCKTIME_THRESHOLD.
1764 : : //
1765 : : // We want to compare apples to apples, so fail the script
1766 : : // unless the type of nLockTime being tested is the same as
1767 : : // the nLockTime in the transaction.
1768 : : if (!(
1769 [ + + + + : 15132 : (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
+ + + + ]
1770 [ + + + + ]: 836 : (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1771 : : ))
1772 : 411 : return false;
1773 : :
1774 : : // Now that we know we're comparing apples-to-apples, the
1775 : : // comparison is a simple numeric one.
1776 [ + + + + ]: 14728 : if (nLockTime > (int64_t)txTo->nLockTime)
1777 : : return false;
1778 : :
1779 : : // Finally the nLockTime feature can be disabled in IsFinalTx()
1780 : : // and thus CHECKLOCKTIMEVERIFY bypassed if every txin has
1781 : : // been finalized by setting nSequence to maxint. The
1782 : : // transaction would be allowed into the blockchain, making
1783 : : // the opcode ineffective.
1784 : : //
1785 : : // Testing if this vin is not final is sufficient to
1786 : : // prevent this condition. Alternatively we could test all
1787 : : // inputs, but testing just this input minimizes the data
1788 : : // required to prove correct CHECKLOCKTIMEVERIFY execution.
1789 [ + + ]: 1625 : if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1790 : 283 : return false;
1791 : :
1792 : : return true;
1793 : : }
1794 : :
1795 : : template <class T>
1796 : 6620 : bool GenericTransactionSignatureChecker<T>::CheckSequence(const CScriptNum& nSequence) const
1797 : : {
1798 : : // Relative lock times are supported by comparing the passed
1799 : : // in operand to the sequence number of the input.
1800 [ + + ]: 6620 : const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1801 : :
1802 : : // Fail if the transaction's version number is not set high
1803 : : // enough to trigger BIP 68 rules.
1804 [ + + ]: 6620 : if (txTo->version < 2)
1805 : : return false;
1806 : :
1807 : : // Sequence numbers with their most significant bit set are not
1808 : : // consensus constrained. Testing that the transaction's sequence
1809 : : // number do not have this bit set prevents using this property
1810 : : // to get around a CHECKSEQUENCEVERIFY check.
1811 [ + + ]: 6128 : if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1812 : : return false;
1813 : :
1814 : : // Mask off any bits that do not have consensus-enforced meaning
1815 : : // before doing the integer comparisons
1816 : 6089 : const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1817 : 6089 : const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1818 [ + + ]: 6089 : const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1819 : :
1820 : : // There are two kinds of nSequence: lock-by-blockheight
1821 : : // and lock-by-blocktime, distinguished by whether
1822 : : // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1823 : : //
1824 : : // We want to compare apples to apples, so fail the script
1825 : : // unless the type of nSequenceMasked being tested is the same as
1826 : : // the nSequenceMasked in the transaction.
1827 : : if (!(
1828 [ + + + + : 11794 : (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
+ + ]
1829 [ + + + + ]: 768 : (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1830 : : )) {
1831 : 188 : return false;
1832 : : }
1833 : :
1834 : : // Now that we know we're comparing apples-to-apples, the
1835 : : // comparison is a simple numeric one.
1836 [ + + ]: 5901 : if (nSequenceMasked > txToSequenceMasked)
1837 : 5260 : return false;
1838 : :
1839 : : return true;
1840 : : }
1841 : :
1842 : : // explicit instantiation
1843 : : template class GenericTransactionSignatureChecker<CTransaction>;
1844 : : template class GenericTransactionSignatureChecker<CMutableTransaction>;
1845 : :
1846 : : /** Execute the script of a witness program spend (exec_script), with the remaining witness elements
1847 : : * (stack) as its initial stack. */
1848 : 179311 : static bool ExecuteWitnessScript(std::vector<valtype> stack, const CScript& exec_script, script_verify_flags flags, SigVersion sigversion, const BaseSignatureChecker& checker, ScriptExecutionData& execdata, ScriptError* serror)
1849 : : {
1850 [ + + ]: 179311 : if (sigversion == SigVersion::TAPSCRIPT) {
1851 : : // OP_SUCCESSx processing overrides everything, including stack element size limits
1852 [ + + ]: 94727 : CScript::const_iterator pc = exec_script.begin();
1853 [ + + + + ]: 17192178 : while (pc < exec_script.end()) {
1854 : 8503666 : opcodetype opcode;
1855 [ + + ]: 8503666 : if (!exec_script.GetOp(pc, opcode)) {
1856 : : // Note how this condition would not be reached if an unknown OP_SUCCESSx was found
1857 [ + - ]: 382 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1858 : : }
1859 : : // New opcodes will be listed here. May use a different sigversion to modify existing opcodes.
1860 [ + + ]: 8503284 : if (IsOpSuccess(opcode)) {
1861 [ + + ]: 1922 : if (flags & SCRIPT_VERIFY_DISCOURAGE_OP_SUCCESS) {
1862 [ + - ]: 414 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_OP_SUCCESS);
1863 : : }
1864 [ + - ]: 1508 : return set_success(serror);
1865 : : }
1866 : : }
1867 : :
1868 : : // Tapscript enforces initial stack size limits (altstack is empty here)
1869 [ - + + + : 92423 : if (stack.size() > MAX_STACK_SIZE) return set_error(serror, SCRIPT_ERR_STACK_SIZE);
+ - ]
1870 : : }
1871 : :
1872 : : // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
1873 [ + + ]: 484228 : for (const valtype& elem : stack) {
1874 [ - + + + : 307634 : if (elem.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
+ - ]
1875 : : }
1876 : :
1877 : : // Run the script interpreter.
1878 [ + + ]: 176594 : if (!EvalScript(stack, exec_script, flags, checker, sigversion, execdata, serror)) return false;
1879 : :
1880 : : // Scripts inside witness implicitly require cleanstack behaviour
1881 [ - + + + : 159347 : if (stack.size() != 1) return set_error(serror, SCRIPT_ERR_CLEANSTACK);
+ + ]
1882 [ + + + - ]: 156027 : if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1883 : : return true;
1884 : : }
1885 : :
1886 : 145852 : uint256 ComputeTapleafHash(uint8_t leaf_version, std::span<const unsigned char> script)
1887 : : {
1888 : 145852 : return (HashWriter{HASHER_TAPLEAF} << leaf_version << CompactSizeWriter(script.size()) << script).GetSHA256();
1889 : : }
1890 : :
1891 : 60631 : uint256 ComputeTapbranchHash(std::span<const unsigned char> a, std::span<const unsigned char> b)
1892 : : {
1893 : 60631 : HashWriter ss_branch{HASHER_TAPBRANCH};
1894 [ + + ]: 60631 : if (std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end())) {
1895 : 23202 : ss_branch << a << b;
1896 : : } else {
1897 : 37429 : ss_branch << b << a;
1898 : : }
1899 : 60631 : return ss_branch.GetSHA256();
1900 : : }
1901 : :
1902 : 100188 : uint256 ComputeTaprootMerkleRoot(std::span<const unsigned char> control, const uint256& tapleaf_hash)
1903 : : {
1904 [ - + ]: 100188 : assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE);
1905 [ - + ]: 100188 : assert(control.size() <= TAPROOT_CONTROL_MAX_SIZE);
1906 [ - + ]: 100188 : assert((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE == 0);
1907 : :
1908 : 100188 : const int path_len = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
1909 : 100188 : uint256 k = tapleaf_hash;
1910 [ + + ]: 137978 : for (int i = 0; i < path_len; ++i) {
1911 : 37790 : std::span node{std::span{control}.subspan(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * i, TAPROOT_CONTROL_NODE_SIZE)};
1912 : 37790 : k = ComputeTapbranchHash(k, node);
1913 : : }
1914 : 100188 : return k;
1915 : : }
1916 : :
1917 : 96548 : static bool VerifyTaprootCommitment(const std::vector<unsigned char>& control, const std::vector<unsigned char>& program, const uint256& tapleaf_hash)
1918 : : {
1919 [ - + - + ]: 96548 : assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE);
1920 [ - + - + ]: 96548 : assert(program.size() >= uint256::size());
1921 : : //! The internal pubkey (x-only, so no Y coordinate parity).
1922 : 96548 : const XOnlyPubKey p{std::span{control}.subspan(1, TAPROOT_CONTROL_BASE_SIZE - 1)};
1923 : : //! The output pubkey (taken from the scriptPubKey).
1924 [ - + ]: 96548 : const XOnlyPubKey q{program};
1925 : : // Compute the Merkle root from the leaf and the provided path.
1926 [ - + ]: 96548 : const uint256 merkle_root = ComputeTaprootMerkleRoot(control, tapleaf_hash);
1927 : : // Verify that the output pubkey matches the tweaked internal pubkey, after correcting for parity.
1928 : 96548 : return q.CheckTapTweak(p, merkle_root, control[0] & 1);
1929 : : }
1930 : :
1931 : 268980 : 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)
1932 : : {
1933 : 268980 : CScript exec_script; //!< Actually executed script (last stack item in P2WSH; implied P2PKH script in P2WPKH; leaf script in P2TR)
1934 : : // The witness stack. Elements with other roles (the witness script, the annex, the control block,
1935 : : // and the leaf script) are popped from it, and the remaining elements are moved into the initial
1936 : : // execution stack.
1937 [ + - ]: 268980 : auto stack = witness.ToVectors();
1938 : : // Remove the top element from the stack, and return it.
1939 : 492485 : const auto pop{[&] {
1940 : 223505 : auto ret{std::move(stack.back())};
1941 : 223505 : stack.pop_back();
1942 : 223505 : return ret;
1943 : 268980 : }};
1944 [ + + ]: 268980 : ScriptExecutionData execdata;
1945 : :
1946 [ + + ]: 268980 : if (witversion == 0) {
1947 [ - + + + ]: 139385 : if (program.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
1948 : : // BIP141 P2WSH: 32-byte witness v0 program (which encodes SHA256(script))
1949 [ - + + + ]: 31468 : if (stack.size() == 0) {
1950 [ + + ]: 1230 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1951 : : }
1952 : 30238 : const valtype script_bytes = pop();
1953 : 30238 : exec_script = CScript(script_bytes.begin(), script_bytes.end());
1954 : 30238 : uint256 hash_exec_script;
1955 [ + - + + : 71934 : CSHA256().Write(exec_script.data(), exec_script.size()).Finalize(hash_exec_script.begin());
+ - + - ]
1956 [ + + ]: 30238 : if (memcmp(hash_exec_script.begin(), program.data(), 32)) {
1957 [ + - ]: 31266 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1958 : : }
1959 [ + - ]: 29210 : return ExecuteWitnessScript(std::move(stack), exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
1960 [ + + ]: 138155 : } else if (program.size() == WITNESS_V0_KEYHASH_SIZE) {
1961 : : // BIP141 P2WPKH: 20-byte witness v0 program (which encodes Hash160(pubkey))
1962 [ - + + + ]: 107317 : if (stack.size() != 2) {
1963 [ + + ]: 51943 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1964 : : }
1965 [ + - + - : 55374 : exec_script << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
- + + - +
- ]
1966 [ + - ]: 55374 : return ExecuteWitnessScript(std::move(stack), exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
1967 : : } else {
1968 [ + - ]: 600 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
1969 : : }
1970 [ + + + + : 258562 : } else if (witversion == 1 && program.size() == WITNESS_V1_TAPROOT_SIZE && !is_p2sh) {
+ + ]
1971 : : // BIP341 Taproot: 32-byte non-P2SH witness v1 program (which encodes a P2C-tweaked pubkey)
1972 [ + + + + ]: 128409 : if (!(flags & SCRIPT_VERIFY_TAPROOT)) return set_success(serror);
1973 [ - + + + : 120883 : if (stack.size() == 0) return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
+ + ]
1974 [ + + + + : 109541 : if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
+ + ]
1975 : : // Drop annex (this is non-standard; see IsWitnessStandard)
1976 : 157 : const valtype annex = pop();
1977 [ + - + - : 157 : execdata.m_annex_hash = (HashWriter{} << annex).GetSHA256();
+ - ]
1978 : 157 : execdata.m_annex_present = true;
1979 : 157 : } else {
1980 : 109384 : execdata.m_annex_present = false;
1981 : : }
1982 : 109541 : execdata.m_annex_init = true;
1983 [ - + + + ]: 109541 : if (stack.size() == 1) {
1984 : : // Key path spending (stack size is 1 after removing optional annex)
1985 [ - + - + : 12986 : if (!checker.CheckSchnorrSignature(stack.front(), program, SigVersion::TAPROOT, execdata, serror)) {
+ - + + ]
1986 : : return false; // serror is set
1987 : : }
1988 [ + + ]: 7561 : return set_success(serror);
1989 : : } else {
1990 : : // Script path spending (stack size is >1 after removing optional annex)
1991 : 96555 : const valtype control = pop();
1992 : 96555 : const valtype script = pop();
1993 [ - + + + : 96555 : if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE || ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) {
+ + + + ]
1994 [ + - ]: 7 : return set_error(serror, SCRIPT_ERR_TAPROOT_WRONG_CONTROL_SIZE);
1995 : : }
1996 [ - + + - ]: 96548 : execdata.m_tapleaf_hash = ComputeTapleafHash(control[0] & TAPROOT_LEAF_MASK, script);
1997 [ + - + + ]: 96548 : if (!VerifyTaprootCommitment(control, program, execdata.m_tapleaf_hash)) {
1998 [ + - ]: 262 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1999 : : }
2000 : 96286 : execdata.m_tapleaf_hash_init = true;
2001 [ + + ]: 96286 : if ((control[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
2002 : : // Tapscript (leaf version 0xc0)
2003 : 94727 : exec_script = CScript(script.begin(), script.end());
2004 : 94727 : execdata.m_validation_weight_left = ::GetSerializeSize(witness) + VALIDATION_WEIGHT_OFFSET;
2005 : 94727 : execdata.m_validation_weight_left_init = true;
2006 [ + - ]: 94727 : return ExecuteWitnessScript(std::move(stack), exec_script, flags, SigVersion::TAPSCRIPT, checker, execdata, serror);
2007 : : }
2008 [ + + ]: 1559 : if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION) {
2009 [ + - ]: 360 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION);
2010 : : }
2011 [ + - ]: 97754 : return set_success(serror);
2012 : 96555 : }
2013 [ + + + - : 1186 : } else if (!is_p2sh && CScript::IsPayToAnchor(witversion, program)) {
+ + ]
2014 : : return true;
2015 : : } else {
2016 [ + + ]: 1176 : if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
2017 [ + - ]: 658 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
2018 : : }
2019 : : // Other version/size/p2sh combinations return true for future softfork compatibility
2020 : : return true;
2021 : : }
2022 : : // 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.
2023 : 268980 : }
2024 : :
2025 : 824552 : bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, script_verify_flags flags, const BaseSignatureChecker& checker, ScriptError* serror)
2026 : : {
2027 [ + + + - ]: 825059 : static const CScriptWitness emptyWitness;
2028 [ + + ]: 824552 : if (witness == nullptr) {
2029 : 67569 : witness = &emptyWitness;
2030 : : }
2031 : 824552 : bool hadWitness = false;
2032 : :
2033 [ + + ]: 824552 : set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
2034 : :
2035 [ + + + + ]: 824552 : if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
2036 [ + - ]: 834256 : return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
2037 : : }
2038 : :
2039 : : // scriptSig and scriptPubKey must be evaluated sequentially on the same stack
2040 : : // rather than being simply concatenated (see CVE-2010-5141)
2041 : 814848 : std::vector<std::vector<unsigned char> > stack, stackCopy;
2042 [ + - + + ]: 814848 : if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
2043 : : // serror is set
2044 : : return false;
2045 [ + + ]: 807862 : if (flags & SCRIPT_VERIFY_P2SH)
2046 [ + - ]: 605375 : stackCopy = stack;
2047 [ + - + + ]: 807862 : if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
2048 : : // serror is set
2049 : : return false;
2050 [ + + ]: 631434 : if (stack.empty())
2051 [ + - ]: 2643 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2052 [ + - + + ]: 628791 : if (CastToBool(stack.back()) == false)
2053 [ + - ]: 7712 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2054 : :
2055 : : // Bare witness programs
2056 : 621079 : int witnessversion;
2057 : 621079 : std::vector<unsigned char> witnessprogram;
2058 [ + + ]: 621079 : if (flags & SCRIPT_VERIFY_WITNESS) {
2059 [ + - + + ]: 353685 : if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2060 : 254782 : hadWitness = true;
2061 [ + + + + ]: 254784 : if (scriptSig.size() != 0) {
2062 : : // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
2063 [ + - ]: 1074 : return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
2064 : : }
2065 [ + - + + ]: 253708 : if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /*is_p2sh=*/false)) {
2066 : : return false;
2067 : : }
2068 : : // Bypass the cleanstack check at the end. The actual stack is obviously not clean
2069 : : // for witness programs.
2070 [ + - ]: 166505 : stack.resize(1);
2071 : : }
2072 : : }
2073 : :
2074 : : // Additional validation for spend-to-script-hash transactions:
2075 [ + + + - : 532802 : if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
+ + ]
2076 : : {
2077 : : // scriptSig must be literals-only or validation fails
2078 [ + - + + ]: 52117 : if (!scriptSig.IsPushOnly())
2079 [ + - ]: 251 : return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
2080 : :
2081 : : // Restore stack.
2082 : 51866 : swap(stack, stackCopy);
2083 : :
2084 : : // stack cannot be empty here, because if it was the
2085 : : // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
2086 : : // an empty stack and the EvalScript above would return false.
2087 [ - + ]: 51866 : assert(!stack.empty());
2088 : :
2089 : 51866 : const valtype& pubKeySerialized = stack.back();
2090 : 51866 : CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
2091 [ + - ]: 51866 : popstack(stack);
2092 : :
2093 [ + - + + ]: 51866 : if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
2094 : : // serror is set
2095 : : return false;
2096 [ + + ]: 40242 : if (stack.empty())
2097 [ + - ]: 1285 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2098 [ + - + + ]: 38957 : if (!CastToBool(stack.back()))
2099 [ + - ]: 257 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2100 : :
2101 : : // P2SH witness program
2102 [ + + ]: 38700 : if (flags & SCRIPT_VERIFY_WITNESS) {
2103 [ + - + + ]: 33637 : if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
2104 : 15786 : hadWitness = true;
2105 [ - + + - : 31572 : if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
+ + ]
2106 : : // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
2107 : : // reintroduce malleability.
2108 [ + - ]: 23371 : return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
2109 : : }
2110 [ + - + + ]: 15272 : if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /*is_p2sh=*/true)) {
2111 : : return false;
2112 : : }
2113 : : // Bypass the cleanstack check at the end. The actual stack is obviously not clean
2114 : : // for witness programs.
2115 [ + - ]: 6095 : stack.resize(1);
2116 : : }
2117 : : }
2118 : 51866 : }
2119 : :
2120 : : // The CLEANSTACK check is only performed after potential P2SH evaluation,
2121 : : // as the non-P2SH evaluation of a P2SH script will obviously not result in
2122 : : // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
2123 [ + + ]: 509694 : if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
2124 : : // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
2125 : : // would be possible, which is not a softfork (and P2SH should be one).
2126 [ - + ]: 118955 : assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2127 [ - + ]: 118955 : assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
2128 [ - + + + ]: 118955 : if (stack.size() != 1) {
2129 [ + - ]: 1172 : return set_error(serror, SCRIPT_ERR_CLEANSTACK);
2130 : : }
2131 : : }
2132 : :
2133 [ + + ]: 508522 : if (flags & SCRIPT_VERIFY_WITNESS) {
2134 : : // We can't check for correct unexpected witness data if P2SH was off, so require
2135 : : // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
2136 : : // possible, which is not a softfork.
2137 [ - + ]: 242458 : assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2138 [ + + + + ]: 242458 : if (!hadWitness && !witness->empty()) {
2139 [ + - ]: 911 : return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
2140 : : }
2141 : : }
2142 : :
2143 [ + + ]: 1103623 : return set_success(serror);
2144 : 814848 : }
2145 : :
2146 : 130852 : size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness)
2147 : : {
2148 [ + + ]: 130852 : if (witversion == 0) {
2149 [ - + + + ]: 26749 : if (witprogram.size() == WITNESS_V0_KEYHASH_SIZE)
2150 : : return 1;
2151 : :
2152 [ + - + + ]: 10475 : if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.size() > 0) {
2153 : 10461 : const auto script = witness.back();
2154 : 10461 : CScript subscript(script.begin(), script.end());
2155 [ + - ]: 10461 : return subscript.GetSigOpCount(true);
2156 : 10461 : }
2157 : : }
2158 : :
2159 : : // Future flags may be implemented here.
2160 : : return 0;
2161 : : }
2162 : :
2163 : 169368 : size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness& witness, script_verify_flags flags)
2164 : : {
2165 [ + + ]: 169368 : if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
2166 : : return 0;
2167 : : }
2168 [ - + ]: 169365 : assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2169 : :
2170 : 169365 : int witnessversion;
2171 : 169365 : std::vector<unsigned char> witnessprogram;
2172 [ + - + + ]: 169365 : if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2173 [ + - ]: 127764 : return WitnessSigOps(witnessversion, witnessprogram, witness);
2174 : : }
2175 : :
2176 [ + - + + : 41601 : if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
+ - + - ]
2177 [ + + ]: 10914 : CScript::const_iterator pc = scriptSig.begin();
2178 : 10914 : std::vector<unsigned char> data;
2179 [ + + + + ]: 60404 : while (pc < scriptSig.end()) {
2180 : 19288 : opcodetype opcode;
2181 [ + - ]: 19288 : scriptSig.GetOp(pc, opcode, data);
2182 : : }
2183 : 10914 : CScript subscript(data.begin(), data.end());
2184 [ + - + + ]: 10914 : if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
2185 [ + - ]: 3088 : return WitnessSigOps(witnessversion, witnessprogram, witness);
2186 : : }
2187 : 10914 : }
2188 : :
2189 : : return 0;
2190 : 169365 : }
2191 : :
2192 : 356 : const std::map<std::string, script_verify_flag_name>& ScriptFlagNamesToEnum()
2193 : : {
2194 : : #define FLAG_NAME(flag) {std::string(#flag), SCRIPT_VERIFY_##flag}
2195 : 356 : static const std::map<std::string, script_verify_flag_name> g_names_to_enum{
2196 [ + - ]: 342 : FLAG_NAME(P2SH),
2197 : 342 : FLAG_NAME(STRICTENC),
2198 : 342 : FLAG_NAME(DERSIG),
2199 : 342 : FLAG_NAME(LOW_S),
2200 : 342 : FLAG_NAME(SIGPUSHONLY),
2201 : 342 : FLAG_NAME(MINIMALDATA),
2202 : 342 : FLAG_NAME(NULLDUMMY),
2203 : 342 : FLAG_NAME(DISCOURAGE_UPGRADABLE_NOPS),
2204 : 342 : FLAG_NAME(CLEANSTACK),
2205 : 342 : FLAG_NAME(MINIMALIF),
2206 : 342 : FLAG_NAME(NULLFAIL),
2207 : 342 : FLAG_NAME(CHECKLOCKTIMEVERIFY),
2208 : 342 : FLAG_NAME(CHECKSEQUENCEVERIFY),
2209 : 342 : FLAG_NAME(WITNESS),
2210 : 342 : FLAG_NAME(DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM),
2211 : 342 : FLAG_NAME(WITNESS_PUBKEYTYPE),
2212 : 342 : FLAG_NAME(CONST_SCRIPTCODE),
2213 : 342 : FLAG_NAME(TAPROOT),
2214 : 342 : FLAG_NAME(DISCOURAGE_UPGRADABLE_PUBKEYTYPE),
2215 : 342 : FLAG_NAME(DISCOURAGE_OP_SUCCESS),
2216 : 342 : FLAG_NAME(DISCOURAGE_UPGRADABLE_TAPROOT_VERSION),
2217 [ + + + - : 4118 : };
+ + - - ]
2218 : : #undef FLAG_NAME
2219 : 356 : return g_names_to_enum;
2220 [ + - + - : 3591 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- - + -
- ]
2221 : :
2222 : 235 : std::vector<std::string> GetScriptFlagNames(script_verify_flags flags)
2223 : : {
2224 : 235 : std::vector<std::string> res;
2225 [ + + ]: 235 : if (flags == SCRIPT_VERIFY_NONE) {
2226 : : return res;
2227 : : }
2228 : 197 : script_verify_flags leftover = flags;
2229 [ + - + + : 4334 : for (const auto& [name, flag] : ScriptFlagNamesToEnum()) {
+ + ]
2230 [ + + ]: 4137 : if ((flags & flag) != 0) {
2231 [ + - ]: 794 : res.push_back(name);
2232 : 794 : leftover &= ~flag;
2233 : : }
2234 : : }
2235 [ + + ]: 197 : if (leftover != 0) {
2236 [ + - ]: 8 : res.push_back(strprintf("0x%08x", leftover.as_int()));
2237 : : }
2238 : : return res;
2239 : 0 : }
|