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