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 : 4255194 : inline bool set_success(ScriptError* ret)
20 : : {
21 : 4255194 : if (ret)
22 : 3543861 : *ret = SCRIPT_ERR_OK;
23 : : return true;
24 : : }
25 : :
26 : 7581645 : inline bool set_error(ScriptError* ret, const ScriptError serror)
27 : : {
28 [ - + - + : 5967 : if (ret)
- + - + +
- + - + -
+ - ]
29 : 5450325 : *ret = serror;
30 : 6307098 : return false;
31 : : }
32 : :
33 : : } // namespace
34 : :
35 : 3155455 : bool CastToBool(const valtype& vch)
36 : : {
37 [ - + + + ]: 3833443 : for (unsigned int i = 0; i < vch.size(); i++)
38 : : {
39 [ + + ]: 3587061 : if (vch[i] != 0)
40 : : {
41 : : // Can be negative zero
42 [ + + + + ]: 2909073 : if (i == vch.size()-1 && vch[i] == 0x80)
43 : : return false;
44 : 2895662 : 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 : 8583338 : static inline void popstack(std::vector<valtype>& stack)
57 : : {
58 [ - + ]: 8583338 : if (stack.empty())
59 [ # # ]: 0 : throw std::runtime_error("popstack(): stack empty");
60 : 8583338 : stack.pop_back();
61 : 8583338 : }
62 : :
63 : 180615 : bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
64 [ - + + + ]: 180615 : if (vchPubKey.size() < CPubKey::COMPRESSED_SIZE) {
65 : : // Non-canonical public key: too short
66 : : return false;
67 : : }
68 [ + + ]: 174058 : if (vchPubKey[0] == 0x04) {
69 [ + + ]: 35019 : if (vchPubKey.size() != CPubKey::SIZE) {
70 : : // Non-canonical public key: invalid length for uncompressed key
71 : 1531 : return false;
72 : : }
73 [ + + + + ]: 139039 : } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
74 [ + + ]: 136247 : if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
75 : : // Non-canonical public key: invalid length for compressed key
76 : 3291 : return false;
77 : : }
78 : : } else {
79 : : // Non-canonical public key: neither compressed nor uncompressed
80 : : return false;
81 : : }
82 : : return true;
83 : : }
84 : :
85 : 84032 : bool static IsCompressedPubKey(const valtype &vchPubKey) {
86 [ - + + + ]: 84032 : if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
87 : : // Non-canonical public key: invalid length for compressed key
88 : : return false;
89 : : }
90 [ + + + + ]: 83732 : if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
91 : : // Non-canonical public key: invalid prefix for compressed key
92 : 24 : 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 : 533888 : 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 [ - + + + ]: 533888 : if (sig.size() < 9) return false;
122 [ + + ]: 513492 : if (sig.size() > 73) return false;
123 : :
124 : : // A signature is of type 0x30 (compound).
125 [ + + ]: 510721 : if (sig[0] != 0x30) return false;
126 : :
127 : : // Make sure the length covers the entire signature.
128 [ + + ]: 417493 : if (sig[1] != sig.size() - 3) return false;
129 : :
130 : : // Extract the length of the R element.
131 : 412542 : unsigned int lenR = sig[3];
132 : :
133 : : // Make sure the length of the S element is still inside the signature.
134 [ + + ]: 412542 : if (5 + lenR >= sig.size()) return false;
135 : :
136 : : // Extract the length of the S element.
137 [ + + ]: 410150 : 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 [ + + ]: 410150 : if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
142 : :
143 : : // Check whether the R element is an integer.
144 [ + + ]: 406702 : if (sig[2] != 0x02) return false;
145 : :
146 : : // Zero-length integers are not allowed for R.
147 [ + + ]: 405868 : if (lenR == 0) return false;
148 : :
149 : : // Negative numbers are not allowed for R.
150 [ + + ]: 404382 : 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 [ + + + + : 403581 : if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
+ + ]
155 : :
156 : : // Check whether the S element is an integer.
157 [ + + ]: 402754 : if (sig[lenR + 4] != 0x02) return false;
158 : :
159 : : // Zero-length integers are not allowed for S.
160 [ + + ]: 401345 : if (lenS == 0) return false;
161 : :
162 : : // Negative numbers are not allowed for S.
163 [ + + ]: 400571 : 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 [ + + + + : 399569 : if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
+ + ]
168 : :
169 : : return true;
170 : : }
171 : :
172 : 178371 : bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
173 [ - + ]: 178371 : if (!IsValidSignatureEncoding(vchSig)) {
174 [ - - ]: 178371 : 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 [ - + ]: 178371 : 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 [ + - + + ]: 178371 : if (!CPubKey::CheckLowS(vchSigCopy)) {
184 [ + + ]: 180833 : return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
185 : : }
186 : : return true;
187 : 178371 : }
188 : :
189 : 183843 : bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
190 [ - + + - ]: 183843 : if (vchSig.size() == 0) {
191 : : return false;
192 : : }
193 [ + + ]: 183843 : unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
194 [ + + ]: 183843 : if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
195 : 37870 : return false;
196 : :
197 : : return true;
198 : : }
199 : :
200 : 590171 : 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 [ - + + + ]: 590171 : if (vchSig.size() == 0) {
204 : : return true;
205 : : }
206 [ + + + + ]: 512457 : if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
207 [ + + ]: 135585 : return set_error(serror, SCRIPT_ERR_SIG_DER);
208 [ + + + + ]: 376872 : } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
209 : : // serror is set
210 : : return false;
211 [ + + + + ]: 374381 : } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
212 [ + + ]: 37870 : return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
213 : : }
214 : : return true;
215 : : }
216 : :
217 : 405816 : bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
218 [ + + + + ]: 405816 : if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
219 [ + + ]: 14171 : return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
220 : : }
221 : : // Only compressed keys are accepted in segwit
222 [ + + + + : 391645 : if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SigVersion::WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
+ + ]
223 [ + + ]: 324 : return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
224 : : }
225 : : return true;
226 : : }
227 : :
228 : 348120 : int FindAndDelete(CScript& script, const CScript& b)
229 : : {
230 : 348120 : int nFound = 0;
231 [ + + + + ]: 474281 : if (b.empty())
232 : : return nFound;
233 : 348014 : CScript result;
234 [ + + + + ]: 1044042 : CScript::const_iterator pc = script.begin(), pc2 = script.begin(), end = script.end();
235 : 94740078 : opcodetype opcode;
236 : 94740078 : do
237 : : {
238 : 94740078 : result.insert(result.end(), pc2, pc);
239 [ + + + + : 237823787 : while (static_cast<size_t>(end - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
+ + + + ]
240 : : {
241 : 8467002 : pc = pc + b.size();
242 : 8467002 : ++nFound;
243 : : }
244 : 94740078 : pc2 = pc;
245 : : }
246 [ + - + + ]: 94740078 : while (script.GetOp(pc, opcode));
247 : :
248 [ + + ]: 348014 : if (nFound > 0) {
249 : 71297 : result.insert(result.end(), pc2, end);
250 : 71297 : script = std::move(result);
251 : : }
252 : :
253 : 348014 : return nFound;
254 : 348014 : }
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 : 4005190 : bool empty() const { return m_stack_size == 0; }
284 : 67287521 : bool all_true() const { return m_first_false_pos == NO_FALSE; }
285 : 1844009 : void push_back(bool f)
286 : : {
287 [ + + ]: 1354507 : 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 : 38008 : m_first_false_pos = m_stack_size;
291 : : }
292 : 1844009 : ++m_stack_size;
293 : 1844009 : }
294 : 288895 : void pop_back()
295 : : {
296 [ - + ]: 288895 : assert(m_stack_size > 0);
297 : 288895 : --m_stack_size;
298 [ + + ]: 288895 : if (m_first_false_pos == m_stack_size) {
299 : : // When popping off the first false value, everything becomes true.
300 : 27199 : m_first_false_pos = NO_FALSE;
301 : : }
302 : 288895 : }
303 : 135403 : void toggle_top()
304 : : {
305 [ - + ]: 135403 : assert(m_stack_size > 0);
306 [ + + ]: 135403 : if (m_first_false_pos == NO_FALSE) {
307 : : // The current stack is all true values; the first false will be the top.
308 : 49872 : m_first_false_pos = m_stack_size - 1;
309 [ + + ]: 85531 : } 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 : 45944 : 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 : 135403 : }
317 : : };
318 : : }
319 : :
320 : 288178 : 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 [ - + ]: 288178 : assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
323 : :
324 : : // Subset of script starting at the most recent codeseparator
325 : 288178 : CScript scriptCode(pbegincodehash, pend);
326 : :
327 : : // Drop the signature in pre-segwit scripts but not segwit scripts
328 [ + + ]: 288178 : if (sigversion == SigVersion::BASE) {
329 [ - + + - ]: 196015 : int found = FindAndDelete(scriptCode, CScript() << vchSig);
330 [ + + + + ]: 196015 : if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
331 [ + + ]: 11752 : return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
332 : : }
333 : :
334 [ + - + + : 276426 : if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
+ + ]
335 : : //serror is set
336 : 53809 : return false;
337 : : }
338 [ + - ]: 222617 : fSuccess = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
339 : :
340 [ + + + + : 339609 : if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
+ + ]
341 [ + + ]: 342983 : return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
342 : :
343 : : return true;
344 : 288178 : }
345 : :
346 : 41178 : 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 [ - + ]: 41178 : 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 : 41178 : success = !sig.empty();
357 [ + + ]: 41178 : if (success) {
358 : : // Implement the sigops/witnesssize ratio test.
359 : : // Passing with an upgradable public key version is also counted.
360 [ - + ]: 13810 : assert(execdata.m_validation_weight_left_init);
361 : 13810 : execdata.m_validation_weight_left -= VALIDATION_WEIGHT_PER_SIGOP_PASSED;
362 [ + + ]: 13810 : if (execdata.m_validation_weight_left < 0) {
363 [ + - ]: 33 : return set_error(serror, SCRIPT_ERR_TAPSCRIPT_VALIDATION_WEIGHT);
364 : : }
365 : : }
366 [ - + + + ]: 41145 : if (pubkey.size() == 0) {
367 [ + - ]: 6 : return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
368 [ + + ]: 41139 : } else if (pubkey.size() == 32) {
369 [ + + - + : 40313 : if (success && !checker.CheckSchnorrSignature(sig, pubkey, sigversion, execdata, serror)) {
+ + ]
370 : 165 : 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 [ + + ]: 826 : if ((flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_PUBKEYTYPE) != 0) {
379 [ + - ]: 11 : 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 : 329356 : 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 [ + + - ]: 329356 : switch (sigversion) {
394 : 288178 : case SigVersion::BASE:
395 : 288178 : case SigVersion::WITNESS_V0:
396 : 288178 : return EvalChecksigPreTapscript(sig, pubkey, pbegincodehash, pend, flags, checker, sigversion, serror, success);
397 : 41178 : case SigVersion::TAPSCRIPT:
398 : 41178 : 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 : 4467879 : 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 [ + + + - ]: 4467879 : static const CScriptNum bnZero(0);
409 [ + + + - ]: 4467879 : static const CScriptNum bnOne(1);
410 : : // static const CScriptNum bnFalse(0);
411 : : // static const CScriptNum bnTrue(1);
412 [ + + + - : 4467920 : static const valtype vchFalse(0);
+ - ]
413 : : // static const valtype vchZero(0);
414 [ + + + - : 4467896 : static const valtype vchTrue(1, 1);
+ - ]
415 : :
416 : : // sigversion cannot be TAPROOT here, as it admits no script execution.
417 [ + + - + ]: 4467879 : assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0 || sigversion == SigVersion::TAPSCRIPT);
418 : :
419 [ + + ]: 4467879 : CScript::const_iterator pc = script.begin();
420 : 4467879 : CScript::const_iterator pend = script.end();
421 [ + + ]: 4467879 : CScript::const_iterator pbegincodehash = script.begin();
422 : 4467879 : opcodetype opcode;
423 : 4467879 : valtype vchPushValue;
424 : 4467879 : ConditionStack vfExec;
425 : 4467879 : std::vector<valtype> altstack;
426 [ + + ]: 4467879 : set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
427 [ + + + + : 4467879 : if ((sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) && script.size() > MAX_SCRIPT_SIZE) {
+ + ]
428 [ + + ]: 826 : return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
429 : : }
430 : 4467053 : int nOpCount = 0;
431 : 4467053 : bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
432 : 4467053 : uint32_t opcode_pos = 0;
433 : 4467053 : execdata.m_codeseparator_pos = 0xFFFFFFFFUL;
434 : 4467053 : execdata.m_codeseparator_pos_init = true;
435 : :
436 : 4467053 : try
437 : : {
438 [ + + ]: 70853688 : for (; pc < pend; ++opcode_pos) {
439 : 67287521 : bool fExec = vfExec.all_true();
440 : :
441 : : //
442 : : // Read instruction
443 : : //
444 [ + - + + ]: 67287521 : if (!script.GetOp(pc, opcode, vchPushValue))
445 [ + + ]: 163658 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
446 [ - + + + ]: 67123863 : if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
447 [ + + ]: 3249 : return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
448 : :
449 [ + + ]: 67120614 : if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) {
450 : : // Note how OP_RESERVED does not count towards the opcode limit.
451 [ + + + + ]: 66406737 : if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT) {
452 [ + + ]: 8421 : return set_error(serror, SCRIPT_ERR_OP_COUNT);
453 : : }
454 : : }
455 : :
456 : 67112193 : if (opcode == OP_CAT ||
457 : : opcode == OP_SUBSTR ||
458 [ + + ]: 67112193 : opcode == OP_LEFT ||
459 [ + + ]: 67099180 : opcode == OP_RIGHT ||
460 [ + + ]: 67096222 : opcode == OP_INVERT ||
461 [ + + ]: 67093546 : opcode == OP_AND ||
462 [ + + ]: 67090883 : opcode == OP_OR ||
463 [ + + ]: 67088150 : opcode == OP_XOR ||
464 [ + + ]: 67085481 : opcode == OP_2MUL ||
465 [ + + ]: 67083365 : opcode == OP_2DIV ||
466 [ + + ]: 67079390 : opcode == OP_MUL ||
467 [ + + ]: 67076480 : opcode == OP_DIV ||
468 [ + + ]: 67073533 : opcode == OP_MOD ||
469 [ + + ]: 67070626 : opcode == OP_LSHIFT ||
470 : : opcode == OP_RSHIFT)
471 [ + + ]: 44220 : 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 [ + + + + : 67067973 : if (opcode == OP_CODESEPARATOR && sigversion == SigVersion::BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
+ + ]
475 [ + + ]: 4940 : return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
476 : :
477 [ + + + - : 67063033 : if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
+ + ]
478 [ + + + - : 20742181 : if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
+ + ]
479 [ + + ]: 9384 : return set_error(serror, SCRIPT_ERR_MINIMALDATA);
480 : : }
481 [ + - ]: 20732797 : stack.push_back(vchPushValue);
482 [ + + ]: 9728028 : } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
483 [ + + + + : 37434787 : switch (opcode)
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ]
484 : : {
485 : : //
486 : : // Push value
487 : : //
488 : 12213898 : case OP_1NEGATE:
489 : 12213898 : case OP_1:
490 : 12213898 : case OP_2:
491 : 12213898 : case OP_3:
492 : 12213898 : case OP_4:
493 : 12213898 : case OP_5:
494 : 12213898 : case OP_6:
495 : 12213898 : case OP_7:
496 : 12213898 : case OP_8:
497 : 12213898 : case OP_9:
498 : 12213898 : case OP_10:
499 : 12213898 : case OP_11:
500 : 12213898 : case OP_12:
501 : 12213898 : case OP_13:
502 : 12213898 : case OP_14:
503 : 12213898 : case OP_15:
504 : 12213898 : case OP_16:
505 : 12213898 : {
506 : : // ( -- value)
507 [ + - ]: 12213898 : CScriptNum bn((int)opcode - (int)(OP_1 - 1));
508 [ + - + - ]: 12213898 : 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 : 12213898 : break;
513 : :
514 : :
515 : : //
516 : : // Control
517 : : //
518 : : case OP_NOP:
519 : : break;
520 : :
521 : 87200 : case OP_CHECKLOCKTIMEVERIFY:
522 : 87200 : {
523 [ + + ]: 87200 : if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
524 : : // not enabled; treat as a NOP2
525 : : break;
526 : : }
527 : :
528 [ - + + + ]: 71040 : if (stack.size() < 1)
529 [ + + ]: 3324 : 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 [ + - + + ]: 67716 : 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 [ + + ]: 65576 : if (nLockTime < 0)
551 [ + + ]: 3667 : return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
552 : :
553 : : // Actually compare the specified lock time with the transaction.
554 [ + - + + ]: 61909 : if (!checker.CheckLockTime(nLockTime))
555 [ + + ]: 11596 : return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
556 : :
557 : : break;
558 : : }
559 : :
560 : 342676 : case OP_CHECKSEQUENCEVERIFY:
561 : 342676 : {
562 [ + + ]: 342676 : if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
563 : : // not enabled; treat as a NOP3
564 : : break;
565 : : }
566 : :
567 [ - + + + ]: 72669 : if (stack.size() < 1)
568 [ + + ]: 3550 : 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 [ + - + + ]: 69119 : 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 [ + + ]: 66939 : if (nSequence < 0)
579 [ + + ]: 3078 : 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 [ + + ]: 63861 : if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
585 : : break;
586 : :
587 : : // Compare the specified sequence number with the input.
588 [ + - + + ]: 59736 : if (!checker.CheckSequence(nSequence))
589 [ + + ]: 17150 : return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
590 : :
591 : : break;
592 : : }
593 : :
594 : 239335 : case OP_NOP1: case OP_NOP4: case OP_NOP5:
595 : 239335 : case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
596 : 239335 : {
597 [ + + ]: 239335 : if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
598 [ + + ]: 8669 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
599 : : }
600 : : break;
601 : :
602 : 1851857 : case OP_IF:
603 : 1851857 : case OP_NOTIF:
604 : 1851857 : {
605 : : // <expression> if [statements] [else [statements]] endif
606 : 1851857 : bool fValue = false;
607 [ + + ]: 1851857 : if (fExec)
608 : : {
609 [ - + + + ]: 1362355 : if (stack.size() < 1)
610 [ + + ]: 7545 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
611 [ + - ]: 1354810 : valtype& vch = stacktop(-1);
612 : : // Tapscript requires minimal IF/NOTIF inputs as a consensus rule.
613 [ + + ]: 1354810 : 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 [ - + + + : 10288 : 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 [ + + + + ]: 1354802 : if (sigversion == SigVersion::WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
622 [ - + + + ]: 25011 : if (vch.size() > 1)
623 [ + + ]: 214 : return set_error(serror, SCRIPT_ERR_MINIMALIF);
624 [ + + + + ]: 24797 : if (vch.size() == 1 && vch[0] != 1)
625 [ + + ]: 81 : return set_error(serror, SCRIPT_ERR_MINIMALIF);
626 : : }
627 [ + - ]: 1354507 : fValue = CastToBool(vch);
628 [ + + ]: 1354507 : if (opcode == OP_NOTIF)
629 : 181441 : fValue = !fValue;
630 [ + - ]: 1354507 : popstack(stack);
631 : : }
632 [ + + ]: 1844009 : vfExec.push_back(fValue);
633 : : }
634 : 1844009 : break;
635 : :
636 : 138555 : case OP_ELSE:
637 : 138555 : {
638 [ + + ]: 138555 : if (vfExec.empty())
639 [ + + ]: 3152 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
640 : 135403 : vfExec.toggle_top();
641 : : }
642 : 135403 : break;
643 : :
644 : 300468 : case OP_ENDIF:
645 : 300468 : {
646 [ + + ]: 300468 : if (vfExec.empty())
647 [ + + ]: 11573 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
648 : 288895 : vfExec.pop_back();
649 : : }
650 : 288895 : break;
651 : :
652 : 26929 : case OP_VERIFY:
653 : 26929 : {
654 : : // (true -- ) or
655 : : // (false -- false) and return
656 [ - + + + ]: 26929 : if (stack.size() < 1)
657 [ + + ]: 4569 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
658 [ + - + - ]: 22360 : bool fValue = CastToBool(stacktop(-1));
659 [ + + ]: 22360 : if (fValue)
660 [ + - ]: 19568 : popstack(stack);
661 : : else
662 [ + + ]: 2792 : return set_error(serror, SCRIPT_ERR_VERIFY);
663 : : }
664 : : break;
665 : :
666 : 8938 : case OP_RETURN:
667 : 8938 : {
668 [ + + ]: 8938 : return set_error(serror, SCRIPT_ERR_OP_RETURN);
669 : : }
670 : 91954 : break;
671 : :
672 : :
673 : : //
674 : : // Stack ops
675 : : //
676 : 91954 : case OP_TOALTSTACK:
677 : 91954 : {
678 [ - + + + ]: 91954 : if (stack.size() < 1)
679 [ + + ]: 4258 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
680 [ + - + - ]: 87696 : altstack.push_back(stacktop(-1));
681 [ + - ]: 87696 : popstack(stack);
682 : : }
683 : : break;
684 : :
685 : 27665 : case OP_FROMALTSTACK:
686 : 27665 : {
687 [ - + + + ]: 27665 : if (altstack.size() < 1)
688 [ + + ]: 4289 : return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
689 [ + - + - ]: 23376 : stack.push_back(altstacktop(-1));
690 [ + - ]: 23376 : popstack(altstack);
691 : : }
692 : : break;
693 : :
694 : 24268 : case OP_2DROP:
695 : 24268 : {
696 : : // (x1 x2 -- )
697 [ - + + + ]: 24268 : if (stack.size() < 2)
698 [ + + ]: 3455 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
699 [ + - ]: 20813 : popstack(stack);
700 [ + - ]: 20813 : popstack(stack);
701 : : }
702 : : break;
703 : :
704 : 65511 : case OP_2DUP:
705 : 65511 : {
706 : : // (x1 x2 -- x1 x2 x1 x2)
707 [ - + + + ]: 65511 : if (stack.size() < 2)
708 [ + + ]: 4083 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
709 [ + - + - ]: 61428 : valtype vch1 = stacktop(-2);
710 [ - + + - : 61428 : valtype vch2 = stacktop(-1);
+ - ]
711 [ + - ]: 61428 : stack.push_back(vch1);
712 [ + - ]: 61428 : stack.push_back(vch2);
713 : 61428 : }
714 : 61428 : break;
715 : :
716 : 170349 : case OP_3DUP:
717 : 170349 : {
718 : : // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
719 [ - + + + ]: 170349 : if (stack.size() < 3)
720 [ + + ]: 6718 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
721 [ + - + - ]: 163631 : valtype vch1 = stacktop(-3);
722 [ - + + - : 163631 : valtype vch2 = stacktop(-2);
+ - ]
723 [ - + + - : 163631 : valtype vch3 = stacktop(-1);
+ - ]
724 [ + - ]: 163631 : stack.push_back(vch1);
725 [ + - ]: 163631 : stack.push_back(vch2);
726 [ + - ]: 163631 : stack.push_back(vch3);
727 : 163631 : }
728 : 163631 : break;
729 : :
730 : 59342 : case OP_2OVER:
731 : 59342 : {
732 : : // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
733 [ - + + + ]: 59342 : if (stack.size() < 4)
734 [ + + ]: 3353 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
735 [ + - + - ]: 55989 : valtype vch1 = stacktop(-4);
736 [ - + + - : 55989 : valtype vch2 = stacktop(-3);
+ - ]
737 [ + - ]: 55989 : stack.push_back(vch1);
738 [ + - ]: 55989 : stack.push_back(vch2);
739 : 55989 : }
740 : 55989 : break;
741 : :
742 : 1631841 : case OP_2ROT:
743 : 1631841 : {
744 : : // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
745 [ - + + + ]: 1631841 : if (stack.size() < 6)
746 [ + + ]: 3918 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
747 [ + - + - ]: 1627923 : valtype vch1 = stacktop(-6);
748 [ - + + - : 1627923 : valtype vch2 = stacktop(-5);
+ - ]
749 : 1627923 : stack.erase(stack.end()-6, stack.end()-4);
750 [ + - ]: 1627923 : stack.push_back(vch1);
751 [ + - ]: 1627923 : stack.push_back(vch2);
752 : 1627923 : }
753 : 1627923 : break;
754 : :
755 : 29998 : case OP_2SWAP:
756 : 29998 : {
757 : : // (x1 x2 x3 x4 -- x3 x4 x1 x2)
758 [ - + + + ]: 29998 : if (stack.size() < 4)
759 [ + + ]: 4313 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
760 [ + - - + : 25685 : swap(stacktop(-4), stacktop(-2));
+ - ]
761 [ - + + - : 25685 : swap(stacktop(-3), stacktop(-1));
- + + - ]
762 : : }
763 : 25685 : break;
764 : :
765 : 104172 : case OP_IFDUP:
766 : 104172 : {
767 : : // (x - 0 | x x)
768 [ - + + + ]: 104172 : if (stack.size() < 1)
769 [ + + ]: 4196 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
770 [ + - + - ]: 99976 : valtype vch = stacktop(-1);
771 [ + - + + ]: 99976 : if (CastToBool(vch))
772 [ + - ]: 64780 : stack.push_back(vch);
773 : 0 : }
774 : 99976 : break;
775 : :
776 : 259104 : case OP_DEPTH:
777 : 259104 : {
778 : : // -- stacksize
779 [ - + + - ]: 259104 : CScriptNum bn(stack.size());
780 [ + - + - ]: 259104 : stack.push_back(bn.getvch());
781 : : }
782 : 259104 : break;
783 : :
784 : 47607 : case OP_DROP:
785 : 47607 : {
786 : : // (x -- )
787 [ - + + + ]: 47607 : if (stack.size() < 1)
788 [ + + ]: 4148 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
789 [ + - ]: 43459 : popstack(stack);
790 : : }
791 : : break;
792 : :
793 : 300205 : case OP_DUP:
794 : 300205 : {
795 : : // (x -- x x)
796 [ - + + + ]: 300205 : if (stack.size() < 1)
797 [ + + ]: 37905 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
798 [ + - + - ]: 262300 : valtype vch = stacktop(-1);
799 [ + - ]: 262300 : stack.push_back(vch);
800 : 0 : }
801 : 262300 : break;
802 : :
803 : 549740 : case OP_NIP:
804 : 549740 : {
805 : : // (x1 x2 -- x2)
806 [ - + + + ]: 549740 : if (stack.size() < 2)
807 [ + + ]: 4010 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
808 : 545730 : stack.erase(stack.end() - 2);
809 : : }
810 : : break;
811 : :
812 : 61113 : case OP_OVER:
813 : 61113 : {
814 : : // (x1 x2 -- x1 x2 x1)
815 [ - + + + ]: 61113 : if (stack.size() < 2)
816 [ + + ]: 3333 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
817 [ + - + - ]: 57780 : valtype vch = stacktop(-2);
818 [ + - ]: 57780 : stack.push_back(vch);
819 : 0 : }
820 : 57780 : break;
821 : :
822 : 118187 : case OP_PICK:
823 : 118187 : case OP_ROLL:
824 : 118187 : {
825 : : // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
826 : : // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
827 [ - + + + ]: 118187 : if (stack.size() < 2)
828 [ + + ]: 5656 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
829 [ + - + + ]: 112531 : int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
830 [ + - ]: 110022 : popstack(stack);
831 [ + + + + ]: 217575 : if (n < 0 || n >= (int)stack.size())
832 [ + + ]: 7737 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
833 [ + - + - ]: 102285 : valtype vch = stacktop(-n-1);
834 [ + + ]: 102285 : if (opcode == OP_ROLL)
835 : 86171 : stack.erase(stack.end()-n-1);
836 [ + - ]: 102285 : stack.push_back(vch);
837 : 0 : }
838 : 102285 : break;
839 : :
840 : 45024 : case OP_ROT:
841 : 45024 : {
842 : : // (x1 x2 x3 -- x2 x3 x1)
843 : : // x2 x1 x3 after first swap
844 : : // x2 x3 x1 after second swap
845 [ - + + + ]: 45024 : if (stack.size() < 3)
846 [ + + ]: 3619 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
847 [ + - - + : 41405 : swap(stacktop(-3), stacktop(-2));
+ - ]
848 [ - + + - : 41405 : swap(stacktop(-2), stacktop(-1));
- + + - ]
849 : : }
850 : 41405 : break;
851 : :
852 : 51226 : case OP_SWAP:
853 : 51226 : {
854 : : // (x1 x2 -- x2 x1)
855 [ - + + + ]: 51226 : if (stack.size() < 2)
856 [ + + ]: 3501 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
857 [ + - - + : 47725 : swap(stacktop(-2), stacktop(-1));
+ - ]
858 : : }
859 : 47725 : break;
860 : :
861 : 239744 : case OP_TUCK:
862 : 239744 : {
863 : : // (x1 x2 -- x2 x1 x2)
864 [ - + + + ]: 239744 : if (stack.size() < 2)
865 [ + + ]: 4441 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
866 [ + - + - ]: 235303 : valtype vch = stacktop(-1);
867 [ + - ]: 235303 : stack.insert(stack.end()-2, vch);
868 : 0 : }
869 : 235303 : break;
870 : :
871 : :
872 : 44912 : case OP_SIZE:
873 : 44912 : {
874 : : // (in -- in size)
875 [ - + + + ]: 44912 : if (stack.size() < 1)
876 [ + + ]: 3266 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
877 [ + - - + : 41646 : CScriptNum bn(stacktop(-1).size());
+ - ]
878 [ + - + - ]: 41646 : stack.push_back(bn.getvch());
879 : : }
880 : 41646 : break;
881 : :
882 : :
883 : : //
884 : : // Bitwise logic
885 : : //
886 : 510480 : case OP_EQUAL:
887 : 510480 : case OP_EQUALVERIFY:
888 : : //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
889 : 510480 : {
890 : : // (x1 x2 - bool)
891 [ - + + + ]: 510480 : if (stack.size() < 2)
892 [ + + ]: 3891 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
893 [ + - ]: 506589 : valtype& vch1 = stacktop(-2);
894 [ - + + - ]: 506589 : valtype& vch2 = stacktop(-1);
895 : 506589 : 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 [ + - ]: 506589 : popstack(stack);
902 [ + - ]: 506589 : popstack(stack);
903 [ + + + - ]: 632213 : stack.push_back(fEqual ? vchTrue : vchFalse);
904 [ + + ]: 506589 : if (opcode == OP_EQUALVERIFY)
905 : : {
906 [ + + ]: 194934 : if (fEqual)
907 [ + - ]: 188672 : popstack(stack);
908 : : else
909 [ + + ]: 6262 : return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
910 : : }
911 : : }
912 : : break;
913 : :
914 : :
915 : : //
916 : : // Numeric
917 : : //
918 : 388082 : case OP_1ADD:
919 : 388082 : case OP_1SUB:
920 : 388082 : case OP_NEGATE:
921 : 388082 : case OP_ABS:
922 : 388082 : case OP_NOT:
923 : 388082 : case OP_0NOTEQUAL:
924 : 388082 : {
925 : : // (in -- out)
926 [ - + + + ]: 388082 : if (stack.size() < 1)
927 [ + + ]: 4939 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
928 [ + - + + ]: 383143 : CScriptNum bn(stacktop(-1), fRequireMinimal);
929 [ + + + + : 379730 : switch (opcode)
+ + - ]
930 : : {
931 : 31639 : case OP_1ADD: bn += bnOne; break;
932 : 43318 : case OP_1SUB: bn -= bnOne; break;
933 : 42179 : case OP_NEGATE: bn = -bn; break;
934 [ + + ]: 171482 : case OP_ABS: if (bn < bnZero) bn = -bn; break;
935 : 26444 : case OP_NOT: bn = (bn == bnZero); break;
936 : 64668 : case OP_0NOTEQUAL: bn = (bn != bnZero); break;
937 : 0 : default: assert(!"invalid opcode"); break;
938 : : }
939 [ + - ]: 379730 : popstack(stack);
940 [ + - + - ]: 379730 : stack.push_back(bn.getvch());
941 : : }
942 : 379730 : break;
943 : :
944 : 356617 : case OP_ADD:
945 : 356617 : case OP_SUB:
946 : 356617 : case OP_BOOLAND:
947 : 356617 : case OP_BOOLOR:
948 : 356617 : case OP_NUMEQUAL:
949 : 356617 : case OP_NUMEQUALVERIFY:
950 : 356617 : case OP_NUMNOTEQUAL:
951 : 356617 : case OP_LESSTHAN:
952 : 356617 : case OP_GREATERTHAN:
953 : 356617 : case OP_LESSTHANOREQUAL:
954 : 356617 : case OP_GREATERTHANOREQUAL:
955 : 356617 : case OP_MIN:
956 : 356617 : case OP_MAX:
957 : 356617 : {
958 : : // (x1 x2 -- out)
959 [ - + + + ]: 356617 : if (stack.size() < 2)
960 [ + + ]: 13356 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
961 [ + - + + ]: 343261 : CScriptNum bn1(stacktop(-2), fRequireMinimal);
962 [ - + + - : 338259 : CScriptNum bn2(stacktop(-1), fRequireMinimal);
+ + ]
963 [ + + + + : 334232 : CScriptNum bn(0);
+ + + + +
+ + + +
- ]
964 [ + + + + : 334232 : switch (opcode)
+ + + + +
+ + + +
- ]
965 : : {
966 : 22359 : case OP_ADD:
967 : 22359 : bn = bn1 + bn2;
968 : 22359 : break;
969 : :
970 : 24414 : case OP_SUB:
971 : 24414 : bn = bn1 - bn2;
972 : 24414 : break;
973 : :
974 [ + + + + ]: 28324 : case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
975 [ + + + + ]: 31683 : case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
976 : 20857 : case OP_NUMEQUAL: bn = (bn1 == bn2); break;
977 : 32197 : case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
978 : 24374 : case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
979 : 18315 : case OP_LESSTHAN: bn = (bn1 < bn2); break;
980 : 11964 : case OP_GREATERTHAN: bn = (bn1 > bn2); break;
981 : 34691 : case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
982 : 18771 : case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
983 [ + + ]: 53894 : case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
984 [ + + ]: 22300 : case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
985 : 0 : default: assert(!"invalid opcode"); break;
986 : : }
987 [ + - ]: 334232 : popstack(stack);
988 [ + - ]: 334232 : popstack(stack);
989 [ + - + - ]: 334232 : stack.push_back(bn.getvch());
990 : :
991 [ + + ]: 334232 : if (opcode == OP_NUMEQUALVERIFY)
992 : : {
993 [ - + + - : 32197 : if (CastToBool(stacktop(-1)))
+ - + + ]
994 [ + - ]: 28160 : popstack(stack);
995 : : else
996 [ + + ]: 4037 : return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
997 : : }
998 : : }
999 : : break;
1000 : :
1001 : 81298 : case OP_WITHIN:
1002 : 81298 : {
1003 : : // (x min max -- out)
1004 [ - + + + ]: 81298 : if (stack.size() < 3)
1005 [ + + ]: 4258 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1006 [ + - + + ]: 77040 : CScriptNum bn1(stacktop(-3), fRequireMinimal);
1007 [ - + + - : 74545 : CScriptNum bn2(stacktop(-2), fRequireMinimal);
+ + ]
1008 [ - + + - : 73130 : CScriptNum bn3(stacktop(-1), fRequireMinimal);
+ + ]
1009 [ + + + + ]: 70414 : bool fValue = (bn2 <= bn1 && bn1 < bn3);
1010 [ + - ]: 70414 : popstack(stack);
1011 [ + - ]: 70414 : popstack(stack);
1012 [ + - ]: 70414 : popstack(stack);
1013 [ + + + - ]: 129163 : stack.push_back(fValue ? vchTrue : vchFalse);
1014 : : }
1015 : : break;
1016 : :
1017 : :
1018 : : //
1019 : : // Crypto
1020 : : //
1021 : 3075189 : case OP_RIPEMD160:
1022 : 3075189 : case OP_SHA1:
1023 : 3075189 : case OP_SHA256:
1024 : 3075189 : case OP_HASH160:
1025 : 3075189 : case OP_HASH256:
1026 : 3075189 : {
1027 : : // (in -- hash)
1028 [ - + + + ]: 3075189 : if (stack.size() < 1)
1029 [ + + ]: 61737 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1030 [ + - ]: 3013452 : valtype& vch = stacktop(-1);
1031 [ + + + + : 3151821 : valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
+ - ]
1032 [ + + ]: 3013452 : if (opcode == OP_RIPEMD160)
1033 [ + - + - : 4107260 : CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
+ - ]
1034 [ + + ]: 959822 : else if (opcode == OP_SHA1)
1035 [ + - + - : 672688 : CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
+ - ]
1036 [ + + ]: 623478 : else if (opcode == OP_SHA256)
1037 [ + - + - : 68588 : CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
+ - ]
1038 [ + + ]: 589184 : else if (opcode == OP_HASH160)
1039 [ + - - + : 485109 : CHash160().Write(vch).Finalize(vchHash);
+ - - + +
- ]
1040 [ + - ]: 104075 : else if (opcode == OP_HASH256)
1041 [ + - - + : 104075 : CHash256().Write(vch).Finalize(vchHash);
+ - - + +
- ]
1042 [ + - ]: 3013452 : popstack(stack);
1043 [ + - ]: 3013452 : stack.push_back(vchHash);
1044 : 0 : }
1045 : 3013452 : break;
1046 : :
1047 : 178400 : case OP_CODESEPARATOR:
1048 : 178400 : {
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 : 178400 : pbegincodehash = pc;
1054 : 178400 : execdata.m_codeseparator_pos = opcode_pos;
1055 : : }
1056 : 178400 : break;
1057 : :
1058 : 323404 : case OP_CHECKSIG:
1059 : 323404 : case OP_CHECKSIGVERIFY:
1060 : 323404 : {
1061 : : // (sig pubkey -- bool)
1062 [ - + + + ]: 323404 : if (stack.size() < 2)
1063 [ + + ]: 24335 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1064 : :
1065 [ + - ]: 299069 : valtype& vchSig = stacktop(-2);
1066 [ - + + - ]: 299069 : valtype& vchPubKey = stacktop(-1);
1067 : :
1068 : 299069 : bool fSuccess = true;
1069 [ + - + + ]: 299069 : if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, fSuccess)) return false;
1070 [ + - ]: 128483 : popstack(stack);
1071 [ + - ]: 128483 : popstack(stack);
1072 [ + + + - ]: 235056 : stack.push_back(fSuccess ? vchTrue : vchFalse);
1073 [ + + ]: 128483 : if (opcode == OP_CHECKSIGVERIFY)
1074 : : {
1075 [ + + ]: 15543 : if (fSuccess)
1076 [ + - ]: 9773 : popstack(stack);
1077 : : else
1078 [ + + ]: 5770 : return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
1079 : : }
1080 : : }
1081 : : break;
1082 : :
1083 : 34452 : case OP_CHECKSIGADD:
1084 : 34452 : {
1085 : : // OP_CHECKSIGADD is only available in Tapscript
1086 [ + + + + ]: 34452 : if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1087 : :
1088 : : // (sig num pubkey -- num)
1089 [ - + + + : 30318 : if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+ - ]
1090 : :
1091 [ + - ]: 30316 : const valtype& sig = stacktop(-3);
1092 [ - + + - : 30316 : const CScriptNum num(stacktop(-2), fRequireMinimal);
+ + ]
1093 [ - + + - ]: 30287 : const valtype& pubkey = stacktop(-1);
1094 : :
1095 : 30287 : bool success = true;
1096 [ + - + + ]: 30287 : if (!EvalChecksig(sig, pubkey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, success)) return false;
1097 [ + - ]: 30245 : popstack(stack);
1098 [ + - ]: 30245 : popstack(stack);
1099 [ + - ]: 30245 : popstack(stack);
1100 [ + + + - : 54393 : stack.push_back((num + (success ? 1 : 0)).getvch());
+ - ]
1101 : : }
1102 : 30245 : break;
1103 : :
1104 : 211004 : case OP_CHECKMULTISIG:
1105 : 211004 : case OP_CHECKMULTISIGVERIFY:
1106 : 211004 : {
1107 [ + + + - ]: 211004 : 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 : 211002 : int i = 1;
1112 [ - + + + ]: 211002 : if ((int)stack.size() < i)
1113 [ + + ]: 5600 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1114 : :
1115 [ + - + + ]: 205402 : int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1116 [ + + ]: 201814 : if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
1117 [ + + ]: 5504 : return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
1118 : 196310 : nOpCount += nKeysCount;
1119 [ + + ]: 196310 : if (nOpCount > MAX_OPS_PER_SCRIPT)
1120 [ + + ]: 2186 : return set_error(serror, SCRIPT_ERR_OP_COUNT);
1121 : 194124 : 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 : 194124 : int ikey2 = nKeysCount + 2;
1125 : 194124 : i += nKeysCount;
1126 [ - + + + ]: 194124 : if ((int)stack.size() < i)
1127 [ + + ]: 5874 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1128 : :
1129 [ + - + + ]: 188250 : int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1130 [ + + ]: 186620 : if (nSigsCount < 0 || nSigsCount > nKeysCount)
1131 [ + + ]: 5641 : return set_error(serror, SCRIPT_ERR_SIG_COUNT);
1132 : 180979 : int isig = ++i;
1133 : 180979 : i += nSigsCount;
1134 [ - + + + ]: 180979 : if ((int)stack.size() < i)
1135 [ + + ]: 3768 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1136 : :
1137 : : // Subset of script starting at the most recent codeseparator
1138 : 177211 : CScript scriptCode(pbegincodehash, pend);
1139 : :
1140 : : // Drop the signature in pre-segwit scripts but not segwit scripts
1141 [ + + ]: 368744 : for (int k = 0; k < nSigsCount; k++)
1142 : : {
1143 [ - + + - ]: 197645 : valtype& vchSig = stacktop(-isig-k);
1144 [ + + ]: 197645 : if (sigversion == SigVersion::BASE) {
1145 [ - + + - ]: 151521 : int found = FindAndDelete(scriptCode, CScript() << vchSig);
1146 [ + + + + ]: 151521 : if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
1147 [ + + ]: 6112 : return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
1148 : : }
1149 : : }
1150 : :
1151 : : bool fSuccess = true;
1152 [ + + ]: 339803 : while (fSuccess && nSigsCount > 0)
1153 : : {
1154 [ - + + - ]: 181288 : valtype& vchSig = stacktop(-isig);
1155 [ - + + - ]: 181288 : 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 [ + - + + : 181288 : if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
+ + ]
1161 : : // serror is set
1162 : 12584 : return false;
1163 : : }
1164 : :
1165 : : // Check signature
1166 [ + - ]: 168704 : bool fOk = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
1167 : :
1168 [ + + ]: 168704 : if (fOk) {
1169 : 15312 : isig++;
1170 : 15312 : nSigsCount--;
1171 : : }
1172 : 168704 : ikey++;
1173 : 168704 : 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 [ + + ]: 168704 : if (nSigsCount > nKeysCount)
1179 : 26897 : fSuccess = false;
1180 : : }
1181 : :
1182 : : // Clean up stack of actual arguments
1183 [ + + ]: 960028 : while (i-- > 1) {
1184 : : // If the operation failed, we require that all signatures must be empty vector
1185 [ + + + + : 841072 : if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
+ + + - -
+ + + ]
1186 [ + + ]: 5382 : return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
1187 [ + + ]: 801513 : if (ikey2 > 0)
1188 : 687827 : ikey2--;
1189 [ + - ]: 801513 : 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 [ - + - + ]: 153133 : if (stack.size() < 1)
1199 [ # # ]: 0 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1200 [ + + + - : 153133 : if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
- + + + ]
1201 [ + + ]: 3598 : return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1202 [ + - ]: 149535 : popstack(stack);
1203 : :
1204 [ + + + - ]: 170072 : stack.push_back(fSuccess ? vchTrue : vchFalse);
1205 : :
1206 [ + + ]: 149535 : if (opcode == OP_CHECKMULTISIGVERIFY)
1207 : : {
1208 [ + + ]: 22456 : if (fSuccess)
1209 [ + - ]: 21394 : popstack(stack);
1210 : : else
1211 [ + + ]: 29662 : return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1212 : : }
1213 : 28738 : }
1214 : 148473 : break;
1215 : :
1216 : 65991 : default:
1217 [ + + ]: 65991 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1218 : : }
1219 : :
1220 : : // Size limits
1221 [ - + - + : 66389747 : if (stack.size() + altstack.size() > MAX_STACK_SIZE)
+ + ]
1222 [ + + ]: 3112 : return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1223 : : }
1224 : : }
1225 : 31144 : catch (...)
1226 : : {
1227 [ + + ]: 31144 : return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1228 [ + - ]: 31144 : }
1229 : :
1230 [ + + ]: 3566167 : if (!vfExec.empty())
1231 [ + + ]: 10364 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1232 : :
1233 [ + + ]: 3555803 : return set_success(serror);
1234 : 4467879 : }
1235 : :
1236 : 3742793 : bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
1237 : : {
1238 : 3742793 : ScriptExecutionData execdata;
1239 : 3742793 : 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 : 132964 : CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1261 : 132964 : txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1262 : 132964 : fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1263 : 132964 : fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1264 : 132964 : fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1265 : :
1266 : : /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1267 : : template<typename S>
1268 : 132964 : void SerializeScriptCode(S &s) const {
1269 [ + + ]: 132964 : CScript::const_iterator it = scriptCode.begin();
1270 : 132964 : CScript::const_iterator itBegin = it;
1271 : : opcodetype opcode;
1272 : 132964 : unsigned int nCodeSeparators = 0;
1273 [ + + ]: 79045954 : while (scriptCode.GetOp(it, opcode)) {
1274 [ + + ]: 78912990 : if (opcode == OP_CODESEPARATOR)
1275 : 42618 : nCodeSeparators++;
1276 : : }
1277 [ + + ]: 148970 : ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1278 : 132964 : it = itBegin;
1279 [ + + ]: 79178918 : while (scriptCode.GetOp(it, opcode)) {
1280 [ + + ]: 78912990 : if (opcode == OP_CODESEPARATOR) {
1281 : 42618 : s.write(std::as_bytes(std::span{&itBegin[0], size_t(it - itBegin - 1)}));
1282 : 42618 : itBegin = it;
1283 : : }
1284 : : }
1285 [ + + ]: 132964 : if (itBegin != scriptCode.end())
1286 : 123104 : s.write(std::as_bytes(std::span{&itBegin[0], size_t(it - itBegin)}));
1287 : 132964 : }
1288 : :
1289 : : /** Serialize an input of txTo */
1290 : : template<typename S>
1291 : 15812115 : void SerializeInput(S &s, unsigned int nInput) const {
1292 : : // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1293 [ + + ]: 15812115 : if (fAnyoneCanPay)
1294 : 18016 : nInput = nIn;
1295 : : // Serialize the prevout
1296 : 15812115 : ::Serialize(s, txTo.vin[nInput].prevout);
1297 : : // Serialize the script
1298 [ + + ]: 15812115 : if (nInput != nIn)
1299 : : // Blank out other inputs' signatures
1300 [ + - ]: 31358302 : ::Serialize(s, CScript());
1301 : : else
1302 : 132964 : SerializeScriptCode(s);
1303 : : // Serialize the nSequence
1304 [ + + + + : 15812115 : if (nInput != nIn && (fHashSingle || fHashNone))
+ + ]
1305 : : // let the others update at will
1306 : 4174354 : ::Serialize(s, int32_t{0});
1307 : : else
1308 : 11637761 : ::Serialize(s, txTo.vin[nInput].nSequence);
1309 : 15812115 : }
1310 : :
1311 : : /** Serialize an output of txTo */
1312 : : template<typename S>
1313 : 1218594 : void SerializeOutput(S &s, unsigned int nOutput) const {
1314 [ + + + + ]: 1218594 : if (fHashSingle && nOutput != nIn)
1315 : : // Do not lock-in the txout payee at other indices as txin
1316 [ + - ]: 590622 : ::Serialize(s, CTxOut());
1317 : : else
1318 : 923283 : ::Serialize(s, txTo.vout[nOutput]);
1319 : 1218594 : }
1320 : :
1321 : : /** Serialize txTo */
1322 : : template<typename S>
1323 : 132964 : void Serialize(S &s) const {
1324 : : // Serialize version
1325 : 132964 : ::Serialize(s, txTo.version);
1326 : : // Serialize vin
1327 [ + + - + ]: 132964 : unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1328 : 132964 : ::WriteCompactSize(s, nInputs);
1329 [ + + ]: 15945079 : for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1330 : 15812115 : SerializeInput(s, nInput);
1331 : : // Serialize vout
1332 [ + + + + : 132964 : unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
- + ]
1333 : 132964 : ::WriteCompactSize(s, nOutputs);
1334 [ + + ]: 1351558 : for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1335 : 1218594 : SerializeOutput(s, nOutput);
1336 : : // Serialize nLockTime
1337 : 132964 : ::Serialize(s, txTo.nLockTime);
1338 : 132964 : }
1339 : : };
1340 : :
1341 : : /** Compute the (single) SHA256 of the concatenation of all prevouts of a tx. */
1342 : : template <class T>
1343 : 370110 : uint256 GetPrevoutsSHA256(const T& txTo)
1344 : : {
1345 : 370110 : HashWriter ss{};
1346 [ + + ]: 1613253 : for (const auto& txin : txTo.vin) {
1347 : 1243143 : ss << txin.prevout;
1348 : : }
1349 : 370110 : return ss.GetSHA256();
1350 : : }
1351 : :
1352 : : /** Compute the (single) SHA256 of the concatenation of all nSequences of a tx. */
1353 : : template <class T>
1354 : 368356 : uint256 GetSequencesSHA256(const T& txTo)
1355 : : {
1356 : 368356 : HashWriter ss{};
1357 [ + + ]: 1606380 : for (const auto& txin : txTo.vin) {
1358 : 1238024 : ss << txin.nSequence;
1359 : : }
1360 : 368356 : return ss.GetSHA256();
1361 : : }
1362 : :
1363 : : /** Compute the (single) SHA256 of the concatenation of all txouts of a tx. */
1364 : : template <class T>
1365 : 371358 : uint256 GetOutputsSHA256(const T& txTo)
1366 : : {
1367 : 371358 : HashWriter ss{};
1368 [ + + ]: 4698028 : for (const auto& txout : txTo.vout) {
1369 : 4326670 : ss << txout;
1370 : : }
1371 : 371358 : return ss.GetSHA256();
1372 : : }
1373 : :
1374 : : /** Compute the (single) SHA256 of the concatenation of all amounts spent by a tx. */
1375 : 17435 : uint256 GetSpentAmountsSHA256(const std::vector<CTxOut>& outputs_spent)
1376 : : {
1377 : 17435 : HashWriter ss{};
1378 [ + + ]: 53797 : for (const auto& txout : outputs_spent) {
1379 : 36362 : ss << txout.nValue;
1380 : : }
1381 : 17435 : return ss.GetSHA256();
1382 : : }
1383 : :
1384 : : /** Compute the (single) SHA256 of the concatenation of all scriptPubKeys spent by a tx. */
1385 : 17435 : uint256 GetSpentScriptsSHA256(const std::vector<CTxOut>& outputs_spent)
1386 : : {
1387 : 17435 : HashWriter ss{};
1388 [ + + ]: 53797 : for (const auto& txout : outputs_spent) {
1389 : 36362 : ss << txout.scriptPubKey;
1390 : : }
1391 : 17435 : return ss.GetSHA256();
1392 : : }
1393 : :
1394 : :
1395 : : } // namespace
1396 : :
1397 : : template <class T>
1398 : 398333 : void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent_outputs, bool force)
1399 : : {
1400 [ - + ]: 398333 : assert(!m_spent_outputs_ready);
1401 : :
1402 : 398333 : m_spent_outputs = std::move(spent_outputs);
1403 [ + + ]: 398333 : if (!m_spent_outputs.empty()) {
1404 [ - + - + : 373747 : assert(m_spent_outputs.size() == txTo.vin.size());
- + ]
1405 : 373747 : 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 [ - + + + : 1177694 : for (size_t inpos = 0; inpos < txTo.vin.size() && !(uses_bip143_segwit && uses_bip341_taproot); ++inpos) {
+ + ]
1412 [ + + ]: 779748 : if (!txTo.vin[inpos].scriptWitness.IsNull()) {
1413 [ + + + + : 541993 : if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.size() == 2 + WITNESS_V1_TAPROOT_SIZE &&
+ + ]
1414 [ + - + + ]: 1020908 : 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 [ + + ]: 779748 : if (uses_bip341_taproot && uses_bip143_segwit) break; // No need to scan further if we already need all.
1428 : : }
1429 : :
1430 [ + + ]: 398333 : if (uses_bip143_segwit || uses_bip341_taproot) {
1431 : : // Computations shared between both sighash schemes.
1432 : 365131 : m_prevouts_single_hash = GetPrevoutsSHA256(txTo);
1433 : 365131 : m_sequences_single_hash = GetSequencesSHA256(txTo);
1434 : 365131 : m_outputs_single_hash = GetOutputsSHA256(txTo);
1435 : : }
1436 [ + + ]: 365131 : if (uses_bip143_segwit) {
1437 : 362955 : hashPrevouts = SHA256Uint256(m_prevouts_single_hash);
1438 : 362955 : hashSequence = SHA256Uint256(m_sequences_single_hash);
1439 : 362955 : hashOutputs = SHA256Uint256(m_outputs_single_hash);
1440 : 362955 : m_bip143_segwit_ready = true;
1441 : : }
1442 [ + + + + ]: 398333 : if (uses_bip341_taproot && m_spent_outputs_ready) {
1443 : 17435 : m_spent_amounts_single_hash = GetSpentAmountsSHA256(m_spent_outputs);
1444 : 17435 : m_spent_scripts_single_hash = GetSpentScriptsSHA256(m_spent_outputs);
1445 : 17435 : m_bip341_taproot_ready = true;
1446 : : }
1447 : 398333 : }
1448 : :
1449 : : template <class T>
1450 [ + - ]: 265 : PrecomputedTransactionData::PrecomputedTransactionData(const T& txTo)
1451 : : {
1452 [ + - ]: 265 : Init(txTo, {});
1453 : 265 : }
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 : 402 : static bool HandleMissingData(MissingDataBehavior mdb)
1466 : : {
1467 [ - + - ]: 402 : switch (mdb) {
1468 : 0 : case MissingDataBehavior::ASSERT_FAIL:
1469 : 0 : assert(!"Missing data");
1470 : : break;
1471 : 402 : case MissingDataBehavior::FAIL:
1472 : 402 : return false;
1473 : : }
1474 : 0 : assert(!"Unknown MissingDataBehavior value");
1475 : : }
1476 : :
1477 : : template<typename T>
1478 : 3686 : 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 [ + - + ]: 3686 : switch (sigversion) {
1482 : : case SigVersion::TAPROOT:
1483 : : ext_flag = 0;
1484 : : // key_version is not used and left uninitialized.
1485 : : break;
1486 : 2321 : case SigVersion::TAPSCRIPT:
1487 : 2321 : 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 : 2321 : key_version = 0;
1493 : 2321 : break;
1494 : 0 : default:
1495 : 0 : assert(false);
1496 : : }
1497 [ - + - + ]: 3686 : assert(in_pos < tx_to.vin.size());
1498 [ + + - + ]: 3686 : if (!(cache.m_bip341_taproot_ready && cache.m_spent_outputs_ready)) {
1499 : 53 : return HandleMissingData(mdb);
1500 : : }
1501 : :
1502 : 3633 : HashWriter ss{HASHER_TAPSIGHASH};
1503 : :
1504 : : // Epoch
1505 : : static constexpr uint8_t EPOCH = 0;
1506 : 3633 : ss << EPOCH;
1507 : :
1508 : : // Hash type
1509 [ + + ]: 3633 : 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 : 3518 : const uint8_t input_type = hash_type & SIGHASH_INPUT_MASK;
1511 [ + + + + ]: 2436 : if (!(hash_type <= 0x03 || (hash_type >= 0x81 && hash_type <= 0x83))) return false;
1512 : 3518 : ss << hash_type;
1513 : :
1514 : : // Transaction level data
1515 : 3518 : ss << tx_to.version;
1516 : 3518 : ss << tx_to.nLockTime;
1517 [ + + ]: 3518 : if (input_type != SIGHASH_ANYONECANPAY) {
1518 : 2772 : ss << cache.m_prevouts_single_hash;
1519 : 2772 : ss << cache.m_spent_amounts_single_hash;
1520 : 2772 : ss << cache.m_spent_scripts_single_hash;
1521 : 2772 : ss << cache.m_sequences_single_hash;
1522 : : }
1523 [ + + ]: 3518 : if (output_type == SIGHASH_ALL) {
1524 : 2426 : ss << cache.m_outputs_single_hash;
1525 : : }
1526 : :
1527 : : // Data about the input/prevout being spent
1528 [ - + ]: 3518 : assert(execdata.m_annex_init);
1529 : 3518 : const bool have_annex = execdata.m_annex_present;
1530 [ + + ]: 6437 : const uint8_t spend_type = (ext_flag << 1) + (have_annex ? 1 : 0); // The low bit indicates whether an annex is present.
1531 : 3518 : ss << spend_type;
1532 [ + + ]: 3518 : if (input_type == SIGHASH_ANYONECANPAY) {
1533 : 746 : ss << tx_to.vin[in_pos].prevout;
1534 : 746 : ss << cache.m_spent_outputs[in_pos];
1535 : 746 : ss << tx_to.vin[in_pos].nSequence;
1536 : : } else {
1537 : 2772 : ss << in_pos;
1538 : : }
1539 [ + + ]: 3518 : if (have_annex) {
1540 : 599 : ss << execdata.m_annex_hash;
1541 : : }
1542 : :
1543 : : // Data about the output (if only one).
1544 [ + + ]: 3518 : if (output_type == SIGHASH_SINGLE) {
1545 [ - + + + ]: 519 : if (in_pos >= tx_to.vout.size()) return false;
1546 [ + + ]: 501 : if (!execdata.m_output_hash) {
1547 : 253 : HashWriter sha_single_output{};
1548 : 253 : sha_single_output << tx_to.vout[in_pos];
1549 [ - + ]: 253 : execdata.m_output_hash = sha_single_output.GetSHA256();
1550 : : }
1551 [ + - ]: 501 : ss << execdata.m_output_hash.value();
1552 : : }
1553 : :
1554 : : // Additional data for BIP 342 signatures
1555 [ + + ]: 3500 : if (sigversion == SigVersion::TAPSCRIPT) {
1556 [ - + ]: 2315 : assert(execdata.m_tapleaf_hash_init);
1557 : 2315 : ss << execdata.m_tapleaf_hash;
1558 : 2315 : ss << key_version;
1559 [ - + ]: 2315 : assert(execdata.m_codeseparator_pos_init);
1560 : 2315 : ss << execdata.m_codeseparator_pos;
1561 : : }
1562 : :
1563 : 3500 : hash_out = ss.GetSHA256();
1564 : 3500 : return true;
1565 : : }
1566 : :
1567 : 320410 : 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 [ + + ]: 320410 : return 3 * !!(hash_type & SIGHASH_ANYONECANPAY) +
1572 [ + + ]: 320410 : 2 * ((hash_type & 0x1f) == SIGHASH_SINGLE) +
1573 : 320410 : 1 * ((hash_type & 0x1f) == SIGHASH_NONE);
1574 : : }
1575 : :
1576 : 199180 : bool SigHashCache::Load(int32_t hash_type, const CScript& script_code, HashWriter& writer) const noexcept
1577 : : {
1578 : 199180 : auto& entry = m_cache_entries[CacheIndex(hash_type)];
1579 [ + + ]: 199180 : if (entry.has_value()) {
1580 [ + + ]: 78695 : if (script_code == entry->first) {
1581 : 77950 : writer = HashWriter(entry->second);
1582 : 77950 : return true;
1583 : : }
1584 : : }
1585 : : return false;
1586 : : }
1587 : :
1588 : 121230 : void SigHashCache::Store(int32_t hash_type, const CScript& script_code, const HashWriter& writer) noexcept
1589 : : {
1590 : 121230 : auto& entry = m_cache_entries[CacheIndex(hash_type)];
1591 : 121230 : entry.emplace(script_code, writer);
1592 : 121230 : }
1593 : :
1594 : : template <class T>
1595 : 312728 : 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 [ - + - + ]: 312728 : assert(nIn < txTo.vin.size());
1598 : :
1599 [ + + ]: 312728 : if (sigversion != SigVersion::WITNESS_V0) {
1600 : : // Check for invalid use of SIGHASH_SINGLE
1601 [ + + ]: 200415 : if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1602 [ - + + + ]: 23800 : if (nIn >= txTo.vout.size()) {
1603 : : // nOut out of range
1604 : 14965 : return uint256::ONE;
1605 : : }
1606 : : }
1607 : : }
1608 : :
1609 : 297763 : HashWriter ss{};
1610 : :
1611 : : // Try to compute using cached SHA256 midstate.
1612 [ + + + + ]: 297763 : if (sighash_cache && sighash_cache->Load(nHashType, scriptCode, ss)) {
1613 : : // Add sighash type and hash.
1614 : 77950 : ss << nHashType;
1615 : 77950 : return ss.GetHash();
1616 : : }
1617 : :
1618 [ + + ]: 219813 : if (sigversion == SigVersion::WITNESS_V0) {
1619 : 86849 : uint256 hashPrevouts;
1620 : 86849 : uint256 hashSequence;
1621 : 86849 : uint256 hashOutputs;
1622 [ + + + + ]: 86849 : const bool cacheready = cache && cache->m_bip143_segwit_ready;
1623 : :
1624 [ + + ]: 86849 : if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1625 [ + + ]: 77630 : hashPrevouts = cacheready ? cache->hashPrevouts : SHA256Uint256(GetPrevoutsSHA256(txTo));
1626 : : }
1627 : :
1628 [ + + + + ]: 77630 : if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1629 [ + + ]: 29813 : hashSequence = cacheready ? cache->hashSequence : SHA256Uint256(GetSequencesSHA256(txTo));
1630 : : }
1631 : :
1632 [ + + ]: 86849 : if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1633 [ + + ]: 33689 : hashOutputs = cacheready ? cache->hashOutputs : SHA256Uint256(GetOutputsSHA256(txTo));
1634 [ + + - + : 53160 : } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
+ + ]
1635 : 19399 : HashWriter inner_ss{};
1636 : 19399 : inner_ss << txTo.vout[nIn];
1637 : 19399 : hashOutputs = inner_ss.GetHash();
1638 : : }
1639 : :
1640 : : // Version
1641 : 86849 : ss << txTo.version;
1642 : : // Input prevouts/nSequence (none/all, depending on flags)
1643 : 86849 : ss << hashPrevouts;
1644 : 86849 : 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 : 86849 : ss << txTo.vin[nIn].prevout;
1649 : 86849 : ss << scriptCode;
1650 : 86849 : ss << amount;
1651 : 86849 : ss << txTo.vin[nIn].nSequence;
1652 : : // Outputs (none/one/all, depending on flags)
1653 : 86849 : ss << hashOutputs;
1654 : : // Locktime
1655 : 86849 : ss << txTo.nLockTime;
1656 : : } else {
1657 : : // Wrapper to serialize only the necessary parts of the transaction being signed
1658 : 132964 : CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
1659 : :
1660 : : // Serialize
1661 : 132964 : ss << txTmp;
1662 : : }
1663 : :
1664 : : // If a cache object was provided, store the midstate there.
1665 [ + + ]: 219813 : if (sighash_cache != nullptr) {
1666 : 121230 : sighash_cache->Store(nHashType, scriptCode, ss);
1667 : : }
1668 : :
1669 : : // Add sighash type and hash.
1670 : 219813 : ss << nHashType;
1671 : 219813 : return ss.GetHash();
1672 : : }
1673 : :
1674 : : template <class T>
1675 : 175258 : bool GenericTransactionSignatureChecker<T>::VerifyECDSASignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1676 : : {
1677 : 175258 : return pubkey.Verify(sighash, vchSig);
1678 : : }
1679 : :
1680 : : template <class T>
1681 : 3777 : bool GenericTransactionSignatureChecker<T>::VerifySchnorrSignature(std::span<const unsigned char> sig, const XOnlyPubKey& pubkey, const uint256& sighash) const
1682 : : {
1683 : 3777 : return pubkey.VerifySchnorr(sighash, sig);
1684 : : }
1685 : :
1686 : : template <class T>
1687 [ - + ]: 286682 : bool GenericTransactionSignatureChecker<T>::CheckECDSASignature(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1688 : : {
1689 [ + + ]: 286682 : CPubKey pubkey(vchPubKey);
1690 [ + + ]: 286682 : if (!pubkey.IsValid())
1691 : : return false;
1692 : :
1693 : : // Hash type is one byte tacked on to the end of the signature
1694 : 185609 : std::vector<unsigned char> vchSig(vchSigIn);
1695 [ + + ]: 185609 : if (vchSig.empty())
1696 : : return false;
1697 [ + + ]: 175027 : int nHashType = vchSig.back();
1698 : 175027 : vchSig.pop_back();
1699 : :
1700 : : // Witness sighashes need the amount.
1701 [ + + + + ]: 175027 : if (sigversion == SigVersion::WITNESS_V0 && amount < 0) return HandleMissingData(m_mdb);
1702 : :
1703 [ + - ]: 175009 : uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata, &m_sighash_cache);
1704 : :
1705 [ + - + + ]: 175009 : if (!VerifyECDSASignature(vchSig, pubkey, sighash))
1706 : 166116 : return false;
1707 : :
1708 : : return true;
1709 : 185609 : }
1710 : :
1711 : : template <class T>
1712 : 8483 : 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 [ - + ]: 8483 : assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
1715 : : // Schnorr signatures have 32-byte public keys. The caller is responsible for enforcing this.
1716 [ - + ]: 8483 : 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 [ + + + + ]: 8483 : if (sig.size() != 64 && sig.size() != 65) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_SIZE);
1722 : :
1723 : 4091 : XOnlyPubKey pubkey{pubkey_in};
1724 : :
1725 [ + + ]: 4091 : uint8_t hashtype = SIGHASH_DEFAULT;
1726 [ + + ]: 4091 : if (sig.size() == 65) {
1727 : 2785 : hashtype = SpanPopBack(sig);
1728 [ + + ]: 2785 : if (hashtype == SIGHASH_DEFAULT) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
1729 : : }
1730 : 4017 : uint256 sighash;
1731 [ + + ]: 4017 : if (!this->txdata) return HandleMissingData(m_mdb);
1732 [ + + ]: 3686 : if (!SignatureHashSchnorr(sighash, execdata, *txTo, nIn, hashtype, sigversion, *this->txdata, m_mdb)) {
1733 : 8483 : return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
1734 : : }
1735 [ + + ]: 3500 : if (!VerifySchnorrSignature(sig, pubkey, sighash)) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG);
1736 : : return true;
1737 : : }
1738 : :
1739 : : template <class T>
1740 : 59350 : 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 [ + + + + : 59350 : (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
+ + ]
1751 [ + + ]: 10338 : (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 [ + + ]: 52718 : 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 [ + + ]: 48390 : if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1771 : 691 : return false;
1772 : :
1773 : : return true;
1774 : : }
1775 : :
1776 : : template <class T>
1777 : 56991 : 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 [ + + ]: 56991 : 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 [ + + ]: 56991 : 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 [ + + ]: 54481 : 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 : 53543 : const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1798 : 53543 : const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1799 [ + + ]: 53543 : 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 [ + + + + ]: 53543 : (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1810 [ + + ]: 24015 : (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 [ + + ]: 43716 : if (nSequenceMasked > txToSequenceMasked)
1818 : 3861 : return false;
1819 : :
1820 : : return true;
1821 : : }
1822 : :
1823 : : // explicit instantiation
1824 : : template class GenericTransactionSignatureChecker<CTransaction>;
1825 : : template class GenericTransactionSignatureChecker<CMutableTransaction>;
1826 : :
1827 : 725459 : 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 : 725459 : std::vector<valtype> stack{stack_span.begin(), stack_span.end()};
1830 : :
1831 [ + + ]: 725459 : if (sigversion == SigVersion::TAPSCRIPT) {
1832 : : // OP_SUCCESSx processing overrides everything, including stack element size limits
1833 [ + + ]: 4684 : CScript::const_iterator pc = exec_script.begin();
1834 [ + + ]: 841121 : while (pc < exec_script.end()) {
1835 : 838886 : opcodetype opcode;
1836 [ + - + + ]: 838886 : 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 [ + - + + ]: 838884 : if (IsOpSuccess(opcode)) {
1842 [ + + ]: 105 : if (flags & SCRIPT_VERIFY_DISCOURAGE_OP_SUCCESS) {
1843 [ + - ]: 70 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_OP_SUCCESS);
1844 : : }
1845 [ + - ]: 35 : return set_success(serror);
1846 : : }
1847 : : }
1848 : :
1849 : : // Tapscript enforces initial stack size limits (altstack is empty here)
1850 [ - + + + : 2235 : 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 [ + + ]: 1956737 : for (const valtype& elem : stack) {
1855 [ - + + + : 1231651 : if (elem.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
+ + ]
1856 : : }
1857 : :
1858 : : // Run the script interpreter.
1859 [ + - + + ]: 725086 : if (!EvalScript(stack, exec_script, flags, checker, sigversion, execdata, serror)) return false;
1860 : :
1861 : : // Scripts inside witness implicitly require cleanstack behaviour
1862 [ - + + + : 661849 : if (stack.size() != 1) return set_error(serror, SCRIPT_ERR_CLEANSTACK);
+ + ]
1863 [ + - + + : 659420 : if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
+ + ]
1864 : : return true;
1865 : 725459 : }
1866 : :
1867 : 238304 : uint256 ComputeTapleafHash(uint8_t leaf_version, std::span<const unsigned char> script)
1868 : : {
1869 : 238304 : return (HashWriter{HASHER_TAPLEAF} << leaf_version << CompactSizeWriter(script.size()) << script).GetSHA256();
1870 : : }
1871 : :
1872 : 298252 : uint256 ComputeTapbranchHash(std::span<const unsigned char> a, std::span<const unsigned char> b)
1873 : : {
1874 : 298252 : HashWriter ss_branch{HASHER_TAPBRANCH};
1875 [ + + ]: 298252 : if (std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end())) {
1876 : 105859 : ss_branch << a << b;
1877 : : } else {
1878 : 192393 : ss_branch << b << a;
1879 : : }
1880 : 298252 : return ss_branch.GetSHA256();
1881 : : }
1882 : :
1883 : 40468 : uint256 ComputeTaprootMerkleRoot(std::span<const unsigned char> control, const uint256& tapleaf_hash)
1884 : : {
1885 [ - + ]: 40468 : assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE);
1886 [ - + ]: 40468 : assert(control.size() <= TAPROOT_CONTROL_MAX_SIZE);
1887 [ - + ]: 40468 : assert((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE == 0);
1888 : :
1889 : 40468 : const int path_len = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
1890 : 40468 : uint256 k = tapleaf_hash;
1891 [ + + ]: 190094 : for (int i = 0; i < path_len; ++i) {
1892 : 149626 : std::span node{std::span{control}.subspan(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * i, TAPROOT_CONTROL_NODE_SIZE)};
1893 : 149626 : k = ComputeTapbranchHash(k, node);
1894 : : }
1895 : 40468 : return k;
1896 : : }
1897 : :
1898 : 5395 : static bool VerifyTaprootCommitment(const std::vector<unsigned char>& control, const std::vector<unsigned char>& program, const uint256& tapleaf_hash)
1899 : : {
1900 [ - + - + ]: 5395 : assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE);
1901 [ - + - + ]: 5395 : assert(program.size() >= uint256::size());
1902 : : //! The internal pubkey (x-only, so no Y coordinate parity).
1903 : 5395 : const XOnlyPubKey p{std::span{control}.subspan(1, TAPROOT_CONTROL_BASE_SIZE - 1)};
1904 : : //! The output pubkey (taken from the scriptPubKey).
1905 [ - + ]: 5395 : const XOnlyPubKey q{program};
1906 : : // Compute the Merkle root from the leaf and the provided path.
1907 [ - + ]: 5395 : const uint256 merkle_root = ComputeTaprootMerkleRoot(control, tapleaf_hash);
1908 : : // Verify that the output pubkey matches the tweaked internal pubkey, after correcting for parity.
1909 : 5395 : return q.CheckTapTweak(p, merkle_root, control[0] & 1);
1910 : : }
1911 : :
1912 : 809845 : 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 : 809845 : CScript exec_script; //!< Actually executed script (last stack item in P2WSH; implied P2PKH script in P2WPKH; leaf script in P2TR)
1915 [ - + ]: 809845 : std::span stack{witness.stack};
1916 [ + + ]: 809845 : ScriptExecutionData execdata;
1917 : :
1918 [ + + ]: 809845 : if (witversion == 0) {
1919 [ - + + + ]: 770843 : if (program.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
1920 : : // BIP141 P2WSH: 32-byte witness v0 program (which encodes SHA256(script))
1921 [ + + ]: 692026 : if (stack.size() == 0) {
1922 [ + + ]: 20151 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1923 : : }
1924 : 671875 : const valtype& script_bytes = SpanPopBack(stack);
1925 : 671875 : exec_script = CScript(script_bytes.begin(), script_bytes.end());
1926 : 671875 : uint256 hash_exec_script;
1927 [ + - + + : 1356632 : CSHA256().Write(exec_script.data(), exec_script.size()).Finalize(hash_exec_script.begin());
+ - + - ]
1928 [ + + ]: 671875 : if (memcmp(hash_exec_script.begin(), program.data(), 32)) {
1929 [ + + ]: 13713 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1930 : : }
1931 [ + - ]: 658162 : return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
1932 [ + + ]: 78817 : } else if (program.size() == WITNESS_V0_KEYHASH_SIZE) {
1933 : : // BIP141 P2WPKH: 20-byte witness v0 program (which encodes Hash160(pubkey))
1934 [ + + ]: 75012 : if (stack.size() != 2) {
1935 [ + + ]: 10057 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1936 : : }
1937 [ + - + - : 64955 : exec_script << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
- + + - +
- ]
1938 [ + - ]: 64955 : return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
1939 : : } else {
1940 [ + + ]: 3805 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
1941 : : }
1942 [ + + + + : 74433 : } 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 [ + + + + ]: 28808 : if (!(flags & SCRIPT_VERIFY_TAPROOT)) return set_success(serror);
1945 [ + + + + ]: 28617 : if (stack.size() == 0) return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1946 [ + + + + : 15082 : if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
+ + ]
1947 : : // Drop annex (this is non-standard; see IsWitnessStandard)
1948 : 722 : const valtype& annex = SpanPopBack(stack);
1949 [ + - + - : 722 : execdata.m_annex_hash = (HashWriter{} << annex).GetSHA256();
+ - ]
1950 : 722 : execdata.m_annex_present = true;
1951 : : } else {
1952 : 14360 : execdata.m_annex_present = false;
1953 : : }
1954 : 15082 : execdata.m_annex_init = true;
1955 [ + + ]: 15082 : if (stack.size() == 1) {
1956 : : // Key path spending (stack size is 1 after removing optional annex)
1957 [ - + - + : 6419 : if (!checker.CheckSchnorrSignature(stack.front(), program, SigVersion::TAPROOT, execdata, serror)) {
+ - + + ]
1958 : : return false; // serror is set
1959 : : }
1960 [ + + ]: 286 : return set_success(serror);
1961 : : } else {
1962 : : // Script path spending (stack size is >1 after removing optional annex)
1963 : 8663 : const valtype& control = SpanPopBack(stack);
1964 : 8663 : const valtype& script = SpanPopBack(stack);
1965 [ - + + + : 8663 : 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 [ + + ]: 3268 : return set_error(serror, SCRIPT_ERR_TAPROOT_WRONG_CONTROL_SIZE);
1967 : : }
1968 [ - + + - ]: 5395 : execdata.m_tapleaf_hash = ComputeTapleafHash(control[0] & TAPROOT_LEAF_MASK, script);
1969 [ + - + + ]: 5395 : if (!VerifyTaprootCommitment(control, program, execdata.m_tapleaf_hash)) {
1970 [ + + ]: 3014 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1971 : : }
1972 : 2381 : execdata.m_tapleaf_hash_init = true;
1973 [ + + ]: 2381 : if ((control[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
1974 : : // Tapscript (leaf version 0xc0)
1975 : 2342 : exec_script = CScript(script.begin(), script.end());
1976 : 2342 : execdata.m_validation_weight_left = ::GetSerializeSize(witness.stack) + VALIDATION_WEIGHT_OFFSET;
1977 : 2342 : execdata.m_validation_weight_left_init = true;
1978 [ + - ]: 2342 : return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::TAPSCRIPT, checker, execdata, serror);
1979 : : }
1980 [ + + ]: 39 : if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION) {
1981 [ + - ]: 20 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION);
1982 : : }
1983 [ + - ]: 19 : return set_success(serror);
1984 : : }
1985 [ + + + - : 10194 : } else if (!is_p2sh && CScript::IsPayToAnchor(witversion, program)) {
+ + ]
1986 : : return true;
1987 : : } else {
1988 [ + + ]: 8802 : if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
1989 [ + + ]: 815255 : 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 : 809845 : }
1996 : :
1997 : 1808075 : bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1998 : : {
1999 [ + + + - ]: 1808089 : static const CScriptWitness emptyWitness;
2000 [ + + ]: 1808075 : if (witness == nullptr) {
2001 : 2568 : witness = &emptyWitness;
2002 : : }
2003 : 1808075 : bool hadWitness = false;
2004 : :
2005 [ + + ]: 1808075 : set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
2006 : :
2007 [ + + + + ]: 1808075 : if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
2008 [ + + ]: 1831037 : 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 : 1784804 : std::vector<std::vector<unsigned char> > stack, stackCopy;
2014 [ + - + + ]: 1784804 : if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
2015 : : // serror is set
2016 : : return false;
2017 [ + + ]: 1569147 : if (flags & SCRIPT_VERIFY_P2SH)
2018 [ + - ]: 1427040 : stackCopy = stack;
2019 [ + - + + ]: 1569147 : if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
2020 : : // serror is set
2021 : : return false;
2022 [ + + ]: 1010714 : if (stack.empty())
2023 [ + + ]: 87476 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2024 [ + - + + ]: 923238 : if (CastToBool(stack.back()) == false)
2025 [ + + ]: 30743 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2026 : :
2027 : : // Bare witness programs
2028 : 892495 : int witnessversion;
2029 : 892495 : std::vector<unsigned char> witnessprogram;
2030 [ + + ]: 892495 : if (flags & SCRIPT_VERIFY_WITNESS) {
2031 [ + - + + ]: 854259 : if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2032 : 759179 : hadWitness = true;
2033 [ + + + + ]: 770572 : if (scriptSig.size() != 0) {
2034 : : // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
2035 [ + + ]: 9154 : return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
2036 : : }
2037 [ + - + + ]: 750025 : 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 [ + - ]: 647107 : stack.resize(1);
2043 : : }
2044 : : }
2045 : :
2046 : : // Additional validation for spend-to-script-hash transactions:
2047 [ + + + - : 780423 : if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
+ + ]
2048 : : {
2049 : : // scriptSig must be literals-only or validation fails
2050 [ + - + + ]: 71245 : if (!scriptSig.IsPushOnly())
2051 [ + + ]: 975 : return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
2052 : :
2053 : : // Restore stack.
2054 : 70270 : 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 [ - + ]: 70270 : assert(!stack.empty());
2060 : :
2061 : 70270 : const valtype& pubKeySerialized = stack.back();
2062 : 70270 : CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
2063 [ + - ]: 70270 : popstack(stack);
2064 : :
2065 [ + - + + ]: 70270 : if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
2066 : : // serror is set
2067 : : return false;
2068 [ + + ]: 68280 : if (stack.empty())
2069 [ + + ]: 5392 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2070 [ + - + + ]: 62888 : if (!CastToBool(stack.back()))
2071 [ + + ]: 994 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2072 : :
2073 : : // P2SH witness program
2074 [ + + ]: 61894 : if (flags & SCRIPT_VERIFY_WITNESS) {
2075 [ + - + + ]: 60421 : if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
2076 : 59861 : hadWitness = true;
2077 [ - + + - : 119722 : 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 [ + + ]: 65658 : return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
2081 : : }
2082 [ + - + + ]: 59820 : 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 [ + - ]: 2587 : stack.resize(1);
2088 : : }
2089 : : }
2090 : 70270 : }
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 [ + + ]: 713798 : 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 [ - + ]: 520523 : assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2099 [ - + ]: 520523 : assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
2100 [ - + + + ]: 520523 : if (stack.size() != 1) {
2101 [ + + ]: 12094 : return set_error(serror, SCRIPT_ERR_CLEANSTACK);
2102 : : }
2103 : : }
2104 : :
2105 [ + + ]: 701704 : 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 [ - + ]: 663561 : assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2110 [ + + + + ]: 663561 : if (!hadWitness && !witness->IsNull()) {
2111 [ + + ]: 2844 : return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
2112 : : }
2113 : : }
2114 : :
2115 [ + + ]: 1581478 : return set_success(serror);
2116 : 1784804 : }
2117 : :
2118 : 4756169 : size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness)
2119 : : {
2120 [ + + ]: 4756169 : if (witversion == 0) {
2121 [ - + + + ]: 4751213 : if (witprogram.size() == WITNESS_V0_KEYHASH_SIZE)
2122 : : return 1;
2123 : :
2124 [ + + - + : 4749640 : if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.stack.size() > 0) {
+ + ]
2125 : 4713788 : CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
2126 [ + - ]: 4713788 : return subscript.GetSigOpCount(true);
2127 : 4713788 : }
2128 : : }
2129 : :
2130 : : // Future flags may be implemented here.
2131 : : return 0;
2132 : : }
2133 : :
2134 : 4789124 : size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags)
2135 : : {
2136 [ + + + - ]: 4789134 : static const CScriptWitness witnessEmpty;
2137 : :
2138 [ + + ]: 4789124 : if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
2139 : : return 0;
2140 : : }
2141 [ - + ]: 4787711 : assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2142 : :
2143 : 4787711 : int witnessversion;
2144 : 4787711 : std::vector<unsigned char> witnessprogram;
2145 [ + - + + ]: 4787711 : if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2146 [ - + + - ]: 4756092 : return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
2147 : : }
2148 : :
2149 [ + - + + : 31619 : if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
+ - + + ]
2150 [ + + ]: 2790 : CScript::const_iterator pc = scriptSig.begin();
2151 : 2790 : std::vector<unsigned char> data;
2152 [ + + ]: 175615 : while (pc < scriptSig.end()) {
2153 : 172825 : opcodetype opcode;
2154 [ + - ]: 172825 : scriptSig.GetOp(pc, opcode, data);
2155 : : }
2156 : 2790 : CScript subscript(data.begin(), data.end());
2157 [ + - + + ]: 2790 : if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
2158 [ - + + - ]: 77 : return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
2159 : : }
2160 : 2790 : }
2161 : :
2162 : : return 0;
2163 : 4787711 : }
|