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