Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-2022 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 : 2258095 : inline bool set_success(ScriptError* ret)
20 : : {
21 [ + + ]: 2258095 : if (ret)
22 : 1812477 : *ret = SCRIPT_ERR_OK;
23 : 2258095 : return true;
24 : : }
25 : :
26 : 4643192 : inline bool set_error(ScriptError* ret, const ScriptError serror)
27 : : {
28 [ + + ]: 4643192 : if (ret)
29 : 3348173 : *ret = serror;
30 : 4643192 : return false;
31 : : }
32 : :
33 : : } // namespace
34 : :
35 : 1199979 : bool CastToBool(const valtype& vch)
36 : : {
37 [ + + - + : 2620347 : for (unsigned int i = 0; i < vch.size(); i++)
+ ]
38 : : {
39 [ + + ]: 1420368 : if (vch[i] != 0)
40 : : {
41 : : // Can be negative zero
42 [ + + + + ]: 962246 : if (i == vch.size()-1 && vch[i] == 0x80)
43 : 8607 : return false;
44 : 953639 : return true;
45 : : }
46 : 458122 : }
47 : 237733 : return false;
48 : 1199979 : }
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(stack.size()+(i)))
55 : : #define altstacktop(i) (altstack.at(altstack.size()+(i)))
56 : 5384045 : static inline void popstack(std::vector<valtype>& stack)
57 : : {
58 [ + - ]: 5384045 : if (stack.empty())
59 [ # # ]: 0 : throw std::runtime_error("popstack(): stack empty");
60 : 5384045 : stack.pop_back();
61 : 5384045 : }
62 : :
63 : 107638 : bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
64 [ + + ]: 107638 : if (vchPubKey.size() < CPubKey::COMPRESSED_SIZE) {
65 : : // Non-canonical public key: too short
66 : 4368 : return false;
67 : : }
68 [ + + ]: 103270 : if (vchPubKey[0] == 0x04) {
69 [ + + ]: 16066 : if (vchPubKey.size() != CPubKey::SIZE) {
70 : : // Non-canonical public key: invalid length for uncompressed key
71 : 1115 : return false;
72 : : }
73 [ + + + + ]: 102155 : } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
74 [ + + ]: 84971 : if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
75 : : // Non-canonical public key: invalid length for compressed key
76 : 1883 : return false;
77 : : }
78 : 83088 : } else {
79 : : // Non-canonical public key: neither compressed nor uncompressed
80 : 2233 : return false;
81 : : }
82 : 98039 : return true;
83 : 107638 : }
84 : :
85 : 66635 : bool static IsCompressedPubKey(const valtype &vchPubKey) {
86 [ + + ]: 66635 : if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
87 : : // Non-canonical public key: invalid length for compressed key
88 : 217 : return false;
89 : : }
90 [ + + + + ]: 66418 : if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
91 : : // Non-canonical public key: invalid prefix for compressed key
92 : 18 : return false;
93 : : }
94 : 66400 : return true;
95 : 66635 : }
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 : 341465 : 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 [ + + ]: 341465 : if (sig.size() < 9) return false;
122 [ + + ]: 324731 : if (sig.size() > 73) return false;
123 : :
124 : : // A signature is of type 0x30 (compound).
125 [ + + ]: 322029 : if (sig[0] != 0x30) return false;
126 : :
127 : : // Make sure the length covers the entire signature.
128 [ + + ]: 244482 : if (sig[1] != sig.size() - 3) return false;
129 : :
130 : : // Extract the length of the R element.
131 : 240603 : unsigned int lenR = sig[3];
132 : :
133 : : // Make sure the length of the S element is still inside the signature.
134 [ + + ]: 240603 : if (5 + lenR >= sig.size()) return false;
135 : :
136 : : // Extract the length of the S element.
137 : 239417 : 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 [ + + ]: 239417 : if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
142 : :
143 : : // Check whether the R element is an integer.
144 [ + + ]: 237520 : if (sig[2] != 0x02) return false;
145 : :
146 : : // Zero-length integers are not allowed for R.
147 [ + + ]: 236791 : if (lenR == 0) return false;
148 : :
149 : : // Negative numbers are not allowed for R.
150 [ + + ]: 235514 : 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 [ + + + + : 234818 : if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
+ + ]
155 : :
156 : : // Check whether the S element is an integer.
157 [ + + ]: 233954 : if (sig[lenR + 4] != 0x02) return false;
158 : :
159 : : // Zero-length integers are not allowed for S.
160 [ + + ]: 232923 : if (lenS == 0) return false;
161 : :
162 : : // Negative numbers are not allowed for S.
163 [ + + ]: 232189 : 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 [ + + + + : 231241 : if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
+ + ]
168 : :
169 : 230564 : return true;
170 : 341465 : }
171 : :
172 : 97555 : bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
173 [ - + ]: 97555 : if (!IsValidSignatureEncoding(vchSig)) {
174 : 0 : 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 [ + - ]: 97555 : 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 [ + - + + ]: 97555 : if (!CPubKey::CheckLowS(vchSigCopy)) {
184 : 3172 : return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
185 : : }
186 : 94383 : return true;
187 : 97555 : }
188 : :
189 : 99480 : bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
190 [ + - ]: 99480 : if (vchSig.size() == 0) {
191 : 0 : return false;
192 : : }
193 : 99480 : unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
194 [ + + + + ]: 99480 : if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
195 : 16775 : return false;
196 : :
197 : 82705 : return true;
198 : 99480 : }
199 : :
200 : 436513 : 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 [ + + ]: 436513 : if (vchSig.size() == 0) {
204 : 70033 : return true;
205 : : }
206 [ + + + + ]: 366480 : if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
207 : 110901 : return set_error(serror, SCRIPT_ERR_SIG_DER);
208 [ + + + + ]: 255579 : } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
209 : : // serror is set
210 : 3172 : return false;
211 [ + + + + ]: 252407 : } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
212 : 16775 : return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
213 : : }
214 : 235632 : return true;
215 : 436513 : }
216 : :
217 : 299622 : bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
218 [ + + + + ]: 299622 : if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
219 : 9599 : return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
220 : : }
221 : : // Only compressed keys are accepted in segwit
222 [ + + + + : 290023 : if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SigVersion::WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
+ + ]
223 : 235 : return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
224 : : }
225 : 289788 : return true;
226 : 299622 : }
227 : :
228 : 227230 : int FindAndDelete(CScript& script, const CScript& b)
229 : : {
230 : 227230 : int nFound = 0;
231 [ + + ]: 227230 : if (b.empty())
232 : 69 : return nFound;
233 : 227161 : CScript result;
234 [ + - + - : 227161 : CScript::const_iterator pc = script.begin(), pc2 = script.begin(), end = script.end();
+ - + - +
- + - ]
235 : 227161 : opcodetype opcode;
236 : 227161 : do
237 : : {
238 [ + - + - ]: 83963863 : result.insert(result.end(), pc2, pc);
239 [ + - + - : 195377359 : while (static_cast<size_t>(end - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
+ + + - +
- + - +
+ ]
240 : : {
241 [ + - + - ]: 14380857 : pc = pc + b.size();
242 : 14380857 : ++nFound;
243 : : }
244 : 83963863 : pc2 = pc;
245 [ + + ]: 167927726 : }
246 [ + - ]: 83963863 : while (script.GetOp(pc, opcode));
247 : :
248 [ + + ]: 227161 : if (nFound > 0) {
249 [ + - + - ]: 60531 : result.insert(result.end(), pc2, end);
250 : 60531 : script = std::move(result);
251 : 60531 : }
252 : :
253 : 227161 : return nFound;
254 : 227230 : }
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 : 2566450 : 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 : 2566450 : 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 : 2566450 : uint32_t m_first_false_pos = NO_FALSE;
281 : :
282 : : public:
283 : 2221136 : bool empty() const { return m_stack_size == 0; }
284 : 39444160 : bool all_true() const { return m_first_false_pos == NO_FALSE; }
285 : 578688 : void push_back(bool f)
286 : : {
287 [ + + + + ]: 578688 : 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 : 34239 : m_first_false_pos = m_stack_size;
291 : 34239 : }
292 : 578688 : ++m_stack_size;
293 : 578688 : }
294 : 206873 : void pop_back()
295 : : {
296 [ + - ]: 206873 : assert(m_stack_size > 0);
297 : 206873 : --m_stack_size;
298 [ + + ]: 206873 : if (m_first_false_pos == m_stack_size) {
299 : : // When popping off the first false value, everything becomes true.
300 : 28635 : m_first_false_pos = NO_FALSE;
301 : 28635 : }
302 : 206873 : }
303 : 48110 : void toggle_top()
304 : : {
305 [ + - ]: 48110 : assert(m_stack_size > 0);
306 [ + + ]: 48110 : if (m_first_false_pos == NO_FALSE) {
307 : : // The current stack is all true values; the first false will be the top.
308 : 13996 : m_first_false_pos = m_stack_size - 1;
309 [ + + ]: 48110 : } 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 : 10936 : m_first_false_pos = NO_FALSE;
312 : 10936 : } 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 : 48110 : }
317 : : };
318 : : }
319 : :
320 : 176788 : 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 [ + + + - ]: 176788 : assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
323 : :
324 : : // Subset of script starting at the most recent codeseparator
325 : 176788 : CScript scriptCode(pbegincodehash, pend);
326 : :
327 : : // Drop the signature in pre-segwit scripts but not segwit scripts
328 [ + + ]: 176788 : if (sigversion == SigVersion::BASE) {
329 [ + - + - ]: 110599 : int found = FindAndDelete(scriptCode, CScript() << vchSig);
330 [ + + + + ]: 110599 : if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
331 : 8419 : return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
332 [ + + ]: 110599 : }
333 : :
334 [ + - + + : 168369 : if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
+ - + + ]
335 : : //serror is set
336 : 31065 : return false;
337 : : }
338 [ + - ]: 137304 : fSuccess = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
339 : :
340 [ + + + + : 137304 : if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
+ + ]
341 : 45795 : return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
342 : :
343 : 91509 : return true;
344 : 176788 : }
345 : :
346 : 26964 : 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 [ + - ]: 26964 : 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 : 26964 : success = !sig.empty();
357 [ + + ]: 26964 : if (success) {
358 : : // Implement the sigops/witnesssize ratio test.
359 : : // Passing with an upgradable public key version is also counted.
360 [ + - ]: 10540 : assert(execdata.m_validation_weight_left_init);
361 : 10540 : execdata.m_validation_weight_left -= VALIDATION_WEIGHT_PER_SIGOP_PASSED;
362 [ + + ]: 10540 : if (execdata.m_validation_weight_left < 0) {
363 : 32 : return set_error(serror, SCRIPT_ERR_TAPSCRIPT_VALIDATION_WEIGHT);
364 : : }
365 : 10508 : }
366 [ + + ]: 26932 : if (pubkey.size() == 0) {
367 : 6 : return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
368 [ + + ]: 26926 : } else if (pubkey.size() == 32) {
369 [ + + + + ]: 26092 : if (success && !checker.CheckSchnorrSignature(sig, pubkey, sigversion, execdata, serror)) {
370 : 78 : return false; // serror is set
371 : : }
372 : 26014 : } 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 [ + + ]: 834 : if ((flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_PUBKEYTYPE) != 0) {
379 : 10 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_PUBKEYTYPE);
380 : : }
381 : : }
382 : :
383 : 26838 : return true;
384 : 26964 : }
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 : 203752 : 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 [ + + - ]: 203752 : switch (sigversion) {
394 : : case SigVersion::BASE:
395 : : case SigVersion::WITNESS_V0:
396 : 176788 : return EvalChecksigPreTapscript(sig, pubkey, pbegincodehash, pend, flags, checker, sigversion, serror, success);
397 : : case SigVersion::TAPSCRIPT:
398 : 26964 : 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 : 203752 : }
405 : :
406 : 2567955 : 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 [ + + - + : 2567955 : static const CScriptNum bnZero(0);
+ - ]
409 [ + + - + : 2567955 : static const CScriptNum bnOne(1);
+ - ]
410 : : // static const CScriptNum bnFalse(0);
411 : : // static const CScriptNum bnTrue(1);
412 : : static const valtype vchFalse(0);
413 : : // static const valtype vchZero(0);
414 [ + + - + : 2567955 : static const valtype vchTrue(1, 1);
+ - ]
415 : :
416 : : // sigversion cannot be TAPROOT here, as it admits no script execution.
417 [ + + + + : 2567955 : assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0 || sigversion == SigVersion::TAPSCRIPT);
+ - ]
418 : :
419 : 2567955 : CScript::const_iterator pc = script.begin();
420 : 2567955 : CScript::const_iterator pend = script.end();
421 : 2567955 : CScript::const_iterator pbegincodehash = script.begin();
422 : 2567955 : opcodetype opcode;
423 : 2567955 : valtype vchPushValue;
424 : 2567955 : ConditionStack vfExec;
425 : 2567955 : std::vector<valtype> altstack;
426 [ + + ]: 2567955 : set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
427 [ + + + + : 2566451 : if ((sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) && script.size() > MAX_SCRIPT_SIZE) {
+ + + + ]
428 [ + - ]: 1508 : return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
429 : : }
430 : 2566447 : int nOpCount = 0;
431 : 2566447 : bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
432 : 2566447 : uint32_t opcode_pos = 0;
433 : 2566447 : execdata.m_codeseparator_pos = 0xFFFFFFFFUL;
434 : 2566447 : execdata.m_codeseparator_pos_init = true;
435 : :
436 : : try
437 : : {
438 [ + - + + ]: 41431953 : for (; pc < pend; ++opcode_pos) {
439 [ + + ]: 39472841 : bool fExec = vfExec.all_true();
440 : :
441 : : //
442 : : // Read instruction
443 : : //
444 [ + + + + ]: 39444160 : if (!script.GetOp(pc, opcode, vchPushValue))
445 [ + - ]: 103393 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
446 [ + + ]: 39340768 : if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
447 [ + - ]: 1742 : return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
448 : :
449 [ + + + + ]: 39339026 : if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) {
450 : : // Note how OP_RESERVED does not count towards the opcode limit.
451 [ + + + + ]: 38843365 : if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT) {
452 [ + - ]: 3951 : return set_error(serror, SCRIPT_ERR_OP_COUNT);
453 : : }
454 : 38839414 : }
455 : :
456 [ + + + + ]: 78633574 : if (opcode == OP_CAT ||
457 [ + + ]: 39331741 : opcode == OP_SUBSTR ||
458 [ + + ]: 39327386 : opcode == OP_LEFT ||
459 [ + + ]: 39324862 : opcode == OP_RIGHT ||
460 [ + + ]: 39323066 : opcode == OP_INVERT ||
461 [ + + ]: 39320435 : opcode == OP_AND ||
462 [ + + ]: 39318051 : opcode == OP_OR ||
463 [ + + ]: 39316113 : opcode == OP_XOR ||
464 [ + + ]: 39313774 : opcode == OP_2MUL ||
465 [ + + ]: 39311751 : opcode == OP_2DIV ||
466 [ + + ]: 39309786 : opcode == OP_MUL ||
467 [ + + ]: 39306785 : opcode == OP_DIV ||
468 [ + + ]: 39304361 : opcode == OP_MOD ||
469 [ + + ]: 39301843 : opcode == OP_LSHIFT ||
470 : 39298499 : opcode == OP_RSHIFT)
471 [ + + ]: 67685 : 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 [ + + + + : 39329608 : if (opcode == OP_CODESEPARATOR && sigversion == SigVersion::BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
+ + ]
475 [ + - ]: 3855 : return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
476 : :
477 [ + + + - : 39325753 : if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
+ + ]
478 [ + + + - : 15704240 : if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
+ + ]
479 [ + - ]: 7176 : return set_error(serror, SCRIPT_ERR_MINIMALDATA);
480 : : }
481 [ + - ]: 15697064 : stack.push_back(vchPushValue);
482 [ + + + + : 39318577 : } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
+ + ]
483 [ + + + + : 20121480 : switch (opcode)
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ]
484 : : {
485 : : //
486 : : // Push value
487 : : //
488 : : case OP_1NEGATE:
489 : : case OP_1:
490 : : case OP_2:
491 : : case OP_3:
492 : : case OP_4:
493 : : case OP_5:
494 : : case OP_6:
495 : : case OP_7:
496 : : case OP_8:
497 : : case OP_9:
498 : : case OP_10:
499 : : case OP_11:
500 : : case OP_12:
501 : : case OP_13:
502 : : case OP_14:
503 : : case OP_15:
504 : : case OP_16:
505 : : {
506 : : // ( -- value)
507 [ - + ]: 5887631 : CScriptNum bn((int)opcode - (int)(OP_1 - 1));
508 [ - + + - ]: 5887631 : 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 : 5887631 : }
512 : 5887631 : break;
513 : :
514 : :
515 : : //
516 : : // Control
517 : : //
518 : : case OP_NOP:
519 : : break;
520 : :
521 : : case OP_CHECKLOCKTIMEVERIFY:
522 : : {
523 [ + + ]: 37787 : if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
524 : : // not enabled; treat as a NOP2
525 : 11537 : break;
526 : : }
527 : :
528 [ + + ]: 26250 : if (stack.size() < 1)
529 [ + - ]: 2058 : 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 [ + - + + ]: 24192 : 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 [ - + + + ]: 22864 : if (nLockTime < 0)
551 [ + - ]: 3172 : return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
552 : :
553 : : // Actually compare the specified lock time with the transaction.
554 [ + - + + ]: 19692 : if (!checker.CheckLockTime(nLockTime))
555 [ + - ]: 7498 : return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
556 : :
557 : 12194 : break;
558 : 24192 : }
559 : :
560 : : case OP_CHECKSEQUENCEVERIFY:
561 : : {
562 [ + + ]: 133466 : if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
563 : : // not enabled; treat as a NOP3
564 : 96157 : break;
565 : : }
566 : :
567 [ + + ]: 37309 : if (stack.size() < 1)
568 [ + - ]: 3084 : 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 [ + - + + ]: 34225 : 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 [ - + + + ]: 32557 : if (nSequence < 0)
579 [ + - ]: 2370 : 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 [ - + - + : 30187 : if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
+ + ]
585 : 2870 : break;
586 : :
587 : : // Compare the specified sequence number with the input.
588 [ + - + + ]: 27317 : if (!checker.CheckSequence(nSequence))
589 [ + - ]: 8845 : return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
590 : :
591 : 18472 : break;
592 : 34225 : }
593 : :
594 : : case OP_NOP1: case OP_NOP4: case OP_NOP5:
595 : : case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
596 : : {
597 [ + + ]: 238828 : if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
598 [ + - ]: 6841 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
599 : : }
600 : 231987 : break;
601 : :
602 : : case OP_IF:
603 : : case OP_NOTIF:
604 : : {
605 : : // <expression> if [statements] [else [statements]] endif
606 : 584983 : bool fValue = false;
607 [ + + ]: 584983 : if (fExec)
608 : : {
609 [ + + ]: 315074 : if (stack.size() < 1)
610 [ + - ]: 6135 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
611 [ + - ]: 308939 : valtype& vch = stacktop(-1);
612 : : // Tapscript requires minimal IF/NOTIF inputs as a consensus rule.
613 [ + + ]: 308939 : 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 [ + + + + : 8652 : if (vch.size() > 1 || (vch.size() == 1 && vch[0] != 1)) {
+ + ]
617 [ + - ]: 8 : return set_error(serror, SCRIPT_ERR_TAPSCRIPT_MINIMALIF);
618 : : }
619 : 8644 : }
620 : : // Under witness v0 rules it is only a policy rule, enabled through SCRIPT_VERIFY_MINIMALIF.
621 [ + + + + ]: 308931 : if (sigversion == SigVersion::WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
622 [ + + ]: 23187 : if (vch.size() > 1)
623 [ + - ]: 74 : return set_error(serror, SCRIPT_ERR_MINIMALIF);
624 [ + + + + ]: 23113 : if (vch.size() == 1 && vch[0] != 1)
625 [ + - ]: 78 : return set_error(serror, SCRIPT_ERR_MINIMALIF);
626 : 23035 : }
627 : 308779 : fValue = CastToBool(vch);
628 [ + + ]: 308779 : if (opcode == OP_NOTIF)
629 : 185697 : fValue = !fValue;
630 [ + - ]: 308779 : popstack(stack);
631 [ + + ]: 308939 : }
632 [ + - ]: 578688 : vfExec.push_back(fValue);
633 [ + + ]: 584983 : }
634 : 578688 : break;
635 : :
636 : : case OP_ELSE:
637 : : {
638 [ + - + + ]: 50802 : if (vfExec.empty())
639 [ + - ]: 2692 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
640 [ + - ]: 48110 : vfExec.toggle_top();
641 : : }
642 : 48110 : break;
643 : :
644 : : case OP_ENDIF:
645 : : {
646 [ + - + + ]: 217584 : if (vfExec.empty())
647 [ + - ]: 10711 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
648 [ + - ]: 206873 : vfExec.pop_back();
649 : : }
650 : 206873 : break;
651 : :
652 : : case OP_VERIFY:
653 : : {
654 : : // (true -- ) or
655 : : // (false -- false) and return
656 [ + + ]: 29883 : if (stack.size() < 1)
657 [ + - ]: 2980 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
658 [ + - ]: 26903 : bool fValue = CastToBool(stacktop(-1));
659 [ + + ]: 26903 : if (fValue)
660 [ + - ]: 24579 : popstack(stack);
661 : : else
662 [ + - ]: 2324 : return set_error(serror, SCRIPT_ERR_VERIFY);
663 [ + + ]: 26903 : }
664 : 24579 : break;
665 : :
666 : : case OP_RETURN:
667 : : {
668 [ + - ]: 9008 : return set_error(serror, SCRIPT_ERR_OP_RETURN);
669 : : }
670 : : break;
671 : :
672 : :
673 : : //
674 : : // Stack ops
675 : : //
676 : : case OP_TOALTSTACK:
677 : : {
678 [ + + ]: 89070 : if (stack.size() < 1)
679 [ + - ]: 5121 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
680 [ + - + - ]: 83949 : altstack.push_back(stacktop(-1));
681 [ + - ]: 83949 : popstack(stack);
682 : : }
683 : 83949 : break;
684 : :
685 : : case OP_FROMALTSTACK:
686 : : {
687 [ + + ]: 22545 : if (altstack.size() < 1)
688 [ + - ]: 4101 : return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
689 [ + - + - ]: 18444 : stack.push_back(altstacktop(-1));
690 [ + - ]: 18444 : popstack(altstack);
691 : : }
692 : 18444 : break;
693 : :
694 : : case OP_2DROP:
695 : : {
696 : : // (x1 x2 -- )
697 [ + + ]: 28581 : if (stack.size() < 2)
698 [ + - ]: 3204 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
699 [ + - ]: 25377 : popstack(stack);
700 [ + - ]: 25377 : popstack(stack);
701 : : }
702 : 25377 : break;
703 : :
704 : : case OP_2DUP:
705 : : {
706 : : // (x1 x2 -- x1 x2 x1 x2)
707 [ + + ]: 52453 : if (stack.size() < 2)
708 [ + - ]: 3618 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
709 [ + - + - ]: 48835 : valtype vch1 = stacktop(-2);
710 [ + - + - ]: 48835 : valtype vch2 = stacktop(-1);
711 [ + - ]: 48835 : stack.push_back(vch1);
712 [ + - ]: 48835 : stack.push_back(vch2);
713 : 48835 : }
714 : 48835 : break;
715 : :
716 : : case OP_3DUP:
717 : : {
718 : : // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
719 [ + + ]: 133742 : if (stack.size() < 3)
720 [ + - ]: 5496 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
721 [ + - + - ]: 128246 : valtype vch1 = stacktop(-3);
722 [ + - + - ]: 128246 : valtype vch2 = stacktop(-2);
723 [ + - + - ]: 128246 : valtype vch3 = stacktop(-1);
724 [ + - ]: 128246 : stack.push_back(vch1);
725 [ + - ]: 128246 : stack.push_back(vch2);
726 [ + - ]: 128246 : stack.push_back(vch3);
727 : 128246 : }
728 : 128246 : break;
729 : :
730 : : case OP_2OVER:
731 : : {
732 : : // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
733 [ + + ]: 61959 : if (stack.size() < 4)
734 [ + - ]: 3432 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
735 [ + - + - ]: 58527 : valtype vch1 = stacktop(-4);
736 [ + - + - ]: 58527 : valtype vch2 = stacktop(-3);
737 [ + - ]: 58527 : stack.push_back(vch1);
738 [ + - ]: 58527 : stack.push_back(vch2);
739 : 58527 : }
740 : 58527 : break;
741 : :
742 : : case OP_2ROT:
743 : : {
744 : : // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
745 [ + + ]: 183332 : if (stack.size() < 6)
746 [ + - ]: 3237 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
747 [ + - + - ]: 180095 : valtype vch1 = stacktop(-6);
748 [ + - + - ]: 180095 : valtype vch2 = stacktop(-5);
749 [ - + ]: 180095 : stack.erase(stack.end()-6, stack.end()-4);
750 [ + - ]: 180095 : stack.push_back(vch1);
751 [ + - ]: 180095 : stack.push_back(vch2);
752 : 180095 : }
753 : 180095 : break;
754 : :
755 : : case OP_2SWAP:
756 : : {
757 : : // (x1 x2 x3 x4 -- x3 x4 x1 x2)
758 [ + + ]: 16878 : if (stack.size() < 4)
759 [ + - ]: 3639 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
760 [ + - + - ]: 13239 : swap(stacktop(-4), stacktop(-2));
761 [ + - + - ]: 13239 : swap(stacktop(-3), stacktop(-1));
762 : : }
763 : 13239 : break;
764 : :
765 : : case OP_IFDUP:
766 : : {
767 : : // (x - 0 | x x)
768 [ + + ]: 59047 : if (stack.size() < 1)
769 [ + - ]: 3688 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
770 [ + - + - ]: 55359 : valtype vch = stacktop(-1);
771 [ + + ]: 55359 : if (CastToBool(vch))
772 [ + - ]: 28365 : stack.push_back(vch);
773 : 55359 : }
774 : 55359 : break;
775 : :
776 : : case OP_DEPTH:
777 : : {
778 : : // -- stacksize
779 [ - + ]: 198720 : CScriptNum bn(stack.size());
780 [ - + + - ]: 198720 : stack.push_back(bn.getvch());
781 : 198720 : }
782 : 198720 : break;
783 : :
784 : : case OP_DROP:
785 : : {
786 : : // (x -- )
787 [ + + ]: 38351 : if (stack.size() < 1)
788 [ + - ]: 3201 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
789 [ + - ]: 35150 : popstack(stack);
790 : : }
791 : 35150 : break;
792 : :
793 : : case OP_DUP:
794 : : {
795 : : // (x -- x x)
796 [ + + ]: 162852 : if (stack.size() < 1)
797 [ + - ]: 20891 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
798 [ + - + - ]: 141961 : valtype vch = stacktop(-1);
799 [ + - ]: 141961 : stack.push_back(vch);
800 : 141961 : }
801 : 141961 : break;
802 : :
803 : : case OP_NIP:
804 : : {
805 : : // (x1 x2 -- x2)
806 [ + + ]: 401988 : if (stack.size() < 2)
807 [ + - ]: 2907 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
808 [ + - ]: 399081 : stack.erase(stack.end() - 2);
809 : : }
810 : 399081 : break;
811 : :
812 : : case OP_OVER:
813 : : {
814 : : // (x1 x2 -- x1 x2 x1)
815 [ + + ]: 33010 : if (stack.size() < 2)
816 [ + - ]: 2574 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
817 [ + - + - ]: 30436 : valtype vch = stacktop(-2);
818 [ + - ]: 30436 : stack.push_back(vch);
819 : 30436 : }
820 : 30436 : break;
821 : :
822 : : case OP_PICK:
823 : : case OP_ROLL:
824 : : {
825 : : // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
826 : : // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
827 [ + + ]: 97992 : if (stack.size() < 2)
828 [ + - ]: 4675 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
829 [ + - + + : 93317 : int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
+ - ]
830 [ + - ]: 91141 : popstack(stack);
831 [ + + + + ]: 91141 : if (n < 0 || n >= (int)stack.size())
832 [ + - ]: 4657 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
833 [ + - + - ]: 86484 : valtype vch = stacktop(-n-1);
834 [ + + ]: 86484 : if (opcode == OP_ROLL)
835 [ - + ]: 66009 : stack.erase(stack.end()-n-1);
836 [ + - ]: 86484 : stack.push_back(vch);
837 [ + + ]: 93317 : }
838 : 86484 : break;
839 : :
840 : : case OP_ROT:
841 : : {
842 : : // (x1 x2 x3 -- x2 x3 x1)
843 : : // x2 x1 x3 after first swap
844 : : // x2 x3 x1 after second swap
845 [ + + ]: 24533 : if (stack.size() < 3)
846 [ + - ]: 2933 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
847 [ + - + - ]: 21600 : swap(stacktop(-3), stacktop(-2));
848 [ + - + - ]: 21600 : swap(stacktop(-2), stacktop(-1));
849 : : }
850 : 21600 : break;
851 : :
852 : : case OP_SWAP:
853 : : {
854 : : // (x1 x2 -- x2 x1)
855 [ + + ]: 31564 : if (stack.size() < 2)
856 [ + - ]: 3062 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
857 [ + - + - ]: 28502 : swap(stacktop(-2), stacktop(-1));
858 : : }
859 : 28502 : break;
860 : :
861 : : case OP_TUCK:
862 : : {
863 : : // (x1 x2 -- x2 x1 x2)
864 [ + + ]: 109501 : if (stack.size() < 2)
865 [ + - ]: 3875 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
866 [ + - + - ]: 105626 : valtype vch = stacktop(-1);
867 [ - + ]: 105626 : stack.insert(stack.end()-2, vch);
868 : 105626 : }
869 : 105626 : break;
870 : :
871 : :
872 : : case OP_SIZE:
873 : : {
874 : : // (in -- in size)
875 [ + + ]: 26171 : if (stack.size() < 1)
876 [ + - ]: 1800 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
877 [ + - + - ]: 24371 : CScriptNum bn(stacktop(-1).size());
878 [ - + + - ]: 24371 : stack.push_back(bn.getvch());
879 : 24371 : }
880 : 24371 : break;
881 : :
882 : :
883 : : //
884 : : // Bitwise logic
885 : : //
886 : : case OP_EQUAL:
887 : : case OP_EQUALVERIFY:
888 : : //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
889 : : {
890 : : // (x1 x2 - bool)
891 [ + + ]: 389348 : if (stack.size() < 2)
892 [ + - ]: 3788 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
893 [ - + ]: 385560 : valtype& vch1 = stacktop(-2);
894 [ - + ]: 385560 : valtype& vch2 = stacktop(-1);
895 [ + - ]: 385560 : 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 [ + - ]: 385560 : popstack(stack);
902 [ + - ]: 385560 : popstack(stack);
903 [ + + + - ]: 385560 : stack.push_back(fEqual ? vchTrue : vchFalse);
904 [ + + ]: 385560 : if (opcode == OP_EQUALVERIFY)
905 : : {
906 [ + + ]: 100126 : if (fEqual)
907 [ + - ]: 94549 : popstack(stack);
908 : : else
909 [ + - ]: 5577 : return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
910 : 94549 : }
911 [ + + ]: 385560 : }
912 : 379983 : break;
913 : :
914 : :
915 : : //
916 : : // Numeric
917 : : //
918 : : case OP_1ADD:
919 : : case OP_1SUB:
920 : : case OP_NEGATE:
921 : : case OP_ABS:
922 : : case OP_NOT:
923 : : case OP_0NOTEQUAL:
924 : : {
925 : : // (in -- out)
926 [ + + ]: 416761 : if (stack.size() < 1)
927 [ + - ]: 5985 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
928 [ + - + + ]: 410776 : CScriptNum bn(stacktop(-1), fRequireMinimal);
929 [ + + + - : 407693 : switch (opcode)
+ + + ]
930 : : {
931 [ + - ]: 22514 : case OP_1ADD: bn += bnOne; break;
932 [ + - ]: 37120 : case OP_1SUB: bn -= bnOne; break;
933 [ + - ]: 21606 : case OP_NEGATE: bn = -bn; break;
934 [ + - + + : 169080 : case OP_ABS: if (bn < bnZero) bn = -bn; break;
+ - ]
935 [ + - + - ]: 27004 : case OP_NOT: bn = (bn == bnZero); break;
936 [ + - + - ]: 130369 : case OP_0NOTEQUAL: bn = (bn != bnZero); break;
937 : 0 : default: assert(!"invalid opcode"); break;
938 : : }
939 [ + - ]: 407693 : popstack(stack);
940 [ - + - + ]: 407693 : stack.push_back(bn.getvch());
941 : 410776 : }
942 : 407693 : break;
943 : :
944 : : case OP_ADD:
945 : : case OP_SUB:
946 : : case OP_BOOLAND:
947 : : case OP_BOOLOR:
948 : : case OP_NUMEQUAL:
949 : : case OP_NUMEQUALVERIFY:
950 : : case OP_NUMNOTEQUAL:
951 : : case OP_LESSTHAN:
952 : : case OP_GREATERTHAN:
953 : : case OP_LESSTHANOREQUAL:
954 : : case OP_GREATERTHANOREQUAL:
955 : : case OP_MIN:
956 : : case OP_MAX:
957 : : {
958 : : // (x1 x2 -- out)
959 [ + + ]: 277962 : if (stack.size() < 2)
960 [ + - ]: 10949 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
961 [ + - + + ]: 267013 : CScriptNum bn1(stacktop(-2), fRequireMinimal);
962 [ + - + + ]: 263219 : CScriptNum bn2(stacktop(-1), fRequireMinimal);
963 [ - + ]: 260070 : CScriptNum bn(0);
964 [ + + - + : 260070 : switch (opcode)
+ + + + +
+ + + +
+ ]
965 : : {
966 : : case OP_ADD:
967 [ + - ]: 15314 : bn = bn1 + bn2;
968 : 15314 : break;
969 : :
970 : : case OP_SUB:
971 [ + - ]: 17310 : bn = bn1 - bn2;
972 : 17310 : break;
973 : :
974 [ + - + + : 29106 : case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
+ - + - ]
975 [ + - + + : 33708 : case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
+ - + - ]
976 [ + - + - ]: 7284 : case OP_NUMEQUAL: bn = (bn1 == bn2); break;
977 [ + - + - ]: 8481 : case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
978 [ + - + - ]: 15838 : case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
979 [ + - + - ]: 17596 : case OP_LESSTHAN: bn = (bn1 < bn2); break;
980 [ + - + - ]: 7773 : case OP_GREATERTHAN: bn = (bn1 > bn2); break;
981 [ + - + - ]: 24793 : case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
982 [ + - + - ]: 17783 : case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
983 [ + - + + ]: 52093 : case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
984 [ + - + + ]: 23345 : case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
985 : 0 : default: assert(!"invalid opcode"); break;
986 : : }
987 [ + - ]: 260070 : popstack(stack);
988 [ + - ]: 260070 : popstack(stack);
989 [ - + - + ]: 260070 : stack.push_back(bn.getvch());
990 : :
991 [ + + ]: 260070 : if (opcode == OP_NUMEQUALVERIFY)
992 : : {
993 [ + - + + ]: 8481 : if (CastToBool(stacktop(-1)))
994 [ + - ]: 5816 : popstack(stack);
995 : : else
996 [ + - ]: 2665 : return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
997 : 5816 : }
998 [ + + ]: 267013 : }
999 : 257405 : break;
1000 : :
1001 : : case OP_WITHIN:
1002 : : {
1003 : : // (x min max -- out)
1004 [ + + ]: 56758 : if (stack.size() < 3)
1005 [ + - ]: 3324 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1006 [ + - + + ]: 53434 : CScriptNum bn1(stacktop(-3), fRequireMinimal);
1007 [ + - + + ]: 51425 : CScriptNum bn2(stacktop(-2), fRequireMinimal);
1008 [ + - + + ]: 50283 : CScriptNum bn3(stacktop(-1), fRequireMinimal);
1009 [ + - + + : 82181 : bool fValue = (bn2 <= bn1 && bn1 < bn3);
+ - ]
1010 [ + - ]: 49141 : popstack(stack);
1011 [ + - ]: 49141 : popstack(stack);
1012 [ + - ]: 49141 : popstack(stack);
1013 [ + + + - ]: 49141 : stack.push_back(fValue ? vchTrue : vchFalse);
1014 : 53434 : }
1015 : 49141 : break;
1016 : :
1017 : :
1018 : : //
1019 : : // Crypto
1020 : : //
1021 : : case OP_RIPEMD160:
1022 : : case OP_SHA1:
1023 : : case OP_SHA256:
1024 : : case OP_HASH160:
1025 : : case OP_HASH256:
1026 : : {
1027 : : // (in -- hash)
1028 [ + + ]: 1371412 : if (stack.size() < 1)
1029 [ + - ]: 37829 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1030 [ - + ]: 1333583 : valtype& vch = stacktop(-1);
1031 [ + + + + : 1333583 : valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
- + ]
1032 [ + + ]: 1333583 : if (opcode == OP_RIPEMD160)
1033 [ + - + - : 908948 : CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
+ - ]
1034 [ + + ]: 424635 : else if (opcode == OP_SHA1)
1035 [ + - + - : 124676 : CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
+ - ]
1036 [ + + ]: 299959 : else if (opcode == OP_SHA256)
1037 [ + - + - : 23929 : CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
+ - ]
1038 [ + + ]: 276030 : else if (opcode == OP_HASH160)
1039 [ + - + - : 166709 : CHash160().Write(vch).Finalize(vchHash);
+ - + - +
- ]
1040 [ - + ]: 109321 : else if (opcode == OP_HASH256)
1041 [ + - + - : 109321 : CHash256().Write(vch).Finalize(vchHash);
+ - + - +
- ]
1042 [ + - ]: 1333583 : popstack(stack);
1043 [ + - ]: 1333583 : stack.push_back(vchHash);
1044 : 1333583 : }
1045 : 1333583 : break;
1046 : :
1047 : : case OP_CODESEPARATOR:
1048 : : {
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 : 161406 : pbegincodehash = pc;
1054 : 161406 : execdata.m_codeseparator_pos = opcode_pos;
1055 : : }
1056 : 161406 : break;
1057 : :
1058 : : case OP_CHECKSIG:
1059 : : case OP_CHECKSIGVERIFY:
1060 : : {
1061 : : // (sig pubkey -- bool)
1062 [ + + ]: 205501 : if (stack.size() < 2)
1063 [ + - ]: 20382 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1064 : :
1065 [ - + ]: 185119 : valtype& vchSig = stacktop(-2);
1066 [ - + ]: 185119 : valtype& vchPubKey = stacktop(-1);
1067 : :
1068 : 185119 : bool fSuccess = true;
1069 [ + - + + ]: 185119 : if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, fSuccess)) return false;
1070 [ + - ]: 99737 : popstack(stack);
1071 [ + - ]: 99737 : popstack(stack);
1072 [ + + + - ]: 99737 : stack.push_back(fSuccess ? vchTrue : vchFalse);
1073 [ + + ]: 99737 : if (opcode == OP_CHECKSIGVERIFY)
1074 : : {
1075 [ + + ]: 10027 : if (fSuccess)
1076 [ + - ]: 8266 : popstack(stack);
1077 : : else
1078 [ + - ]: 1761 : return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
1079 : 8266 : }
1080 [ + + ]: 185119 : }
1081 : 97976 : break;
1082 : :
1083 : : case OP_CHECKSIGADD:
1084 : : {
1085 : : // OP_CHECKSIGADD is only available in Tapscript
1086 [ + + + + : 21276 : if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
+ - ]
1087 : :
1088 : : // (sig num pubkey -- num)
1089 [ + + + - ]: 18645 : if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1090 : :
1091 [ - + ]: 18643 : const valtype& sig = stacktop(-3);
1092 [ + - + + ]: 18643 : const CScriptNum num(stacktop(-2), fRequireMinimal);
1093 [ - + ]: 18633 : const valtype& pubkey = stacktop(-1);
1094 : :
1095 : 18633 : bool success = true;
1096 [ + - + + ]: 18633 : if (!EvalChecksig(sig, pubkey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, success)) return false;
1097 [ + - ]: 18610 : popstack(stack);
1098 [ + - ]: 18610 : popstack(stack);
1099 [ + - ]: 18610 : popstack(stack);
1100 [ + - + - : 18610 : stack.push_back((num + (success ? 1 : 0)).getvch());
+ - ]
1101 [ + + ]: 18643 : }
1102 : 18610 : break;
1103 : :
1104 : : case OP_CHECKMULTISIG:
1105 : : case OP_CHECKMULTISIGVERIFY:
1106 : : {
1107 [ + + + - ]: 253439 : 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 : 253437 : int i = 1;
1112 [ + + ]: 253437 : if ((int)stack.size() < i)
1113 [ + - ]: 3825 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1114 : :
1115 [ + - + + : 249612 : int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
+ - ]
1116 [ + + + + ]: 246402 : if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
1117 [ + - ]: 3592 : return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
1118 : 242810 : nOpCount += nKeysCount;
1119 [ + + ]: 242810 : if (nOpCount > MAX_OPS_PER_SCRIPT)
1120 [ + - ]: 1904 : return set_error(serror, SCRIPT_ERR_OP_COUNT);
1121 : 240906 : 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 : 240906 : int ikey2 = nKeysCount + 2;
1125 : 240906 : i += nKeysCount;
1126 [ + + ]: 240906 : if ((int)stack.size() < i)
1127 [ + - ]: 3620 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1128 : :
1129 [ + - + + : 237286 : int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
+ - ]
1130 [ + + + + ]: 236060 : if (nSigsCount < 0 || nSigsCount > nKeysCount)
1131 [ - + ]: 3482 : return set_error(serror, SCRIPT_ERR_SIG_COUNT);
1132 : 232578 : int isig = ++i;
1133 : 232578 : i += nSigsCount;
1134 [ + + ]: 232578 : if ((int)stack.size() < i)
1135 [ + - ]: 3173 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1136 : :
1137 : : // Subset of script starting at the most recent codeseparator
1138 [ - + ]: 229405 : CScript scriptCode(pbegincodehash, pend);
1139 : :
1140 : : // Drop the signature in pre-segwit scripts but not segwit scripts
1141 [ + + + + ]: 388126 : for (int k = 0; k < nSigsCount; k++)
1142 : : {
1143 [ - + ]: 158721 : valtype& vchSig = stacktop(-isig-k);
1144 [ + + ]: 158721 : if (sigversion == SigVersion::BASE) {
1145 [ + - + - ]: 116158 : int found = FindAndDelete(scriptCode, CScript() << vchSig);
1146 [ + + + + ]: 116158 : if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
1147 [ - + ]: 4454 : return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
1148 [ + + ]: 116158 : }
1149 [ + + ]: 158721 : }
1150 : :
1151 : 224951 : bool fSuccess = true;
1152 [ + + + + ]: 377435 : while (fSuccess && nSigsCount > 0)
1153 : : {
1154 [ - + ]: 161583 : valtype& vchSig = stacktop(-isig);
1155 [ + - ]: 161583 : 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 [ + - + + : 161583 : if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
+ - + + ]
1161 : : // serror is set
1162 : 9099 : return false;
1163 : : }
1164 : :
1165 : : // Check signature
1166 [ + - ]: 152484 : bool fOk = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
1167 : :
1168 [ + + ]: 152484 : if (fOk) {
1169 : 15912 : isig++;
1170 : 15912 : nSigsCount--;
1171 : 15912 : }
1172 : 152484 : ikey++;
1173 : 152484 : 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 [ + + ]: 152484 : if (nSigsCount > nKeysCount)
1179 : 23844 : fSuccess = false;
1180 [ + + ]: 161583 : }
1181 : :
1182 : : // Clean up stack of actual arguments
1183 [ + + ]: 1170737 : while (i-- > 1) {
1184 : : // If the operation failed, we require that all signatures must be empty vector
1185 [ + + + + : 958255 : if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
+ + + - +
+ ]
1186 [ + - ]: 3370 : return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
1187 [ + + ]: 954885 : if (ikey2 > 0)
1188 : 843070 : ikey2--;
1189 [ + - ]: 954885 : 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 [ - + ]: 212482 : if (stack.size() < 1)
1199 [ # # ]: 0 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1200 [ + + + - : 212482 : if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
+ + ]
1201 [ + - ]: 2645 : return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1202 [ + - ]: 209837 : popstack(stack);
1203 : :
1204 [ + + + - ]: 209837 : stack.push_back(fSuccess ? vchTrue : vchFalse);
1205 : :
1206 [ + + ]: 209837 : if (opcode == OP_CHECKMULTISIGVERIFY)
1207 : : {
1208 [ + + ]: 20299 : if (fSuccess)
1209 [ + - ]: 19245 : popstack(stack);
1210 : : else
1211 [ + - ]: 1054 : return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1212 : 19245 : }
1213 [ + + ]: 253437 : }
1214 : 208783 : break;
1215 : :
1216 : : default:
1217 [ + - ]: 52937 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1218 : 19636563 : }
1219 : :
1220 : : // Size limits
1221 [ + + ]: 38833660 : if (stack.size() + altstack.size() > MAX_STACK_SIZE)
1222 [ + - ]: 1690 : return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1223 [ + + ]: 39477699 : }
1224 : 1976687 : }
1225 : : catch (...)
1226 : : {
1227 [ + - ]: 23937 : return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1228 [ + - # # ]: 23937 : }
1229 : :
1230 [ + + + + ]: 1952750 : if (!vfExec.empty())
1231 [ + - ]: 6134 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1232 : :
1233 [ + + ]: 1946614 : return set_success(serror);
1234 : 2650762 : }
1235 : :
1236 : 2248511 : bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
1237 : : {
1238 : 2248511 : ScriptExecutionData execdata;
1239 : 4497022 : return EvalScript(stack, script, flags, checker, sigversion, execdata, serror);
1240 : 2248511 : }
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 : 65594 : CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1261 : 65594 : txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1262 : 65594 : fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1263 : 65594 : fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1264 : 65594 : fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1265 : :
1266 : : /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1267 : : template<typename S>
1268 : 65594 : void SerializeScriptCode(S &s) const {
1269 : 65594 : CScript::const_iterator it = scriptCode.begin();
1270 : 65594 : CScript::const_iterator itBegin = it;
1271 : 65594 : opcodetype opcode;
1272 : 65594 : unsigned int nCodeSeparators = 0;
1273 [ + + + + ]: 47486404 : while (scriptCode.GetOp(it, opcode)) {
1274 [ + + + + ]: 47420810 : if (opcode == OP_CODESEPARATOR)
1275 : 83892 : nCodeSeparators++;
1276 : : }
1277 : 65594 : ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1278 : 65594 : it = itBegin;
1279 [ + + + + ]: 47486404 : while (scriptCode.GetOp(it, opcode)) {
1280 [ + + + + ]: 47420810 : if (opcode == OP_CODESEPARATOR) {
1281 : 83892 : s.write(AsBytes(Span{&itBegin[0], size_t(it - itBegin - 1)}));
1282 : 83892 : itBegin = it;
1283 : 83892 : }
1284 : : }
1285 [ + + + + ]: 65594 : if (itBegin != scriptCode.end())
1286 : 63378 : s.write(AsBytes(Span{&itBegin[0], size_t(it - itBegin)}));
1287 : 65594 : }
1288 : :
1289 : : /** Serialize an input of txTo */
1290 : : template<typename S>
1291 : 7949379 : void SerializeInput(S &s, unsigned int nInput) const {
1292 : : // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1293 [ + + + + ]: 7949379 : if (fAnyoneCanPay)
1294 : 6602 : nInput = nIn;
1295 : : // Serialize the prevout
1296 : 7949379 : ::Serialize(s, txTo.vin[nInput].prevout);
1297 : : // Serialize the script
1298 [ + + + + ]: 7949379 : if (nInput != nIn)
1299 : : // Blank out other inputs' signatures
1300 [ + - + - ]: 7883785 : ::Serialize(s, CScript());
1301 : : else
1302 : 65594 : SerializeScriptCode(s);
1303 : : // Serialize the nSequence
1304 [ + + + + : 7949379 : if (nInput != nIn && (fHashSingle || fHashNone))
+ + + + +
+ + + ]
1305 : : // let the others update at will
1306 : 910220 : ::Serialize(s, int{0});
1307 : : else
1308 : 7039159 : ::Serialize(s, txTo.vin[nInput].nSequence);
1309 : 7949379 : }
1310 : :
1311 : : /** Serialize an output of txTo */
1312 : : template<typename S>
1313 : 777908 : void SerializeOutput(S &s, unsigned int nOutput) const {
1314 [ + + + + : 777908 : if (fHashSingle && nOutput != nIn)
+ + + + ]
1315 : : // Do not lock-in the txout payee at other indices as txin
1316 [ + - + - ]: 194181 : ::Serialize(s, CTxOut());
1317 : : else
1318 : 583727 : ::Serialize(s, txTo.vout[nOutput]);
1319 : 777908 : }
1320 : :
1321 : : /** Serialize txTo */
1322 : : template<typename S>
1323 : 65594 : void Serialize(S &s) const {
1324 : : // Serialize version
1325 : 65594 : ::Serialize(s, txTo.version);
1326 : : // Serialize vin
1327 [ + + + + ]: 65594 : unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1328 : 65594 : ::WriteCompactSize(s, nInputs);
1329 [ + + + + ]: 8014973 : for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1330 : 7949379 : SerializeInput(s, nInput);
1331 : : // Serialize vout
1332 [ + + + + : 65594 : unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
+ + + + ]
1333 : 65594 : ::WriteCompactSize(s, nOutputs);
1334 [ + + + + ]: 843502 : for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1335 : 777908 : SerializeOutput(s, nOutput);
1336 : : // Serialize nLockTime
1337 : 65594 : ::Serialize(s, txTo.nLockTime);
1338 : 65594 : }
1339 : : };
1340 : :
1341 : : /** Compute the (single) SHA256 of the concatenation of all prevouts of a tx. */
1342 : : template <class T>
1343 : 149796 : uint256 GetPrevoutsSHA256(const T& txTo)
1344 : : {
1345 : 149796 : HashWriter ss{};
1346 [ + + + + ]: 794240 : for (const auto& txin : txTo.vin) {
1347 : 644444 : ss << txin.prevout;
1348 : 644444 : }
1349 : 149796 : return ss.GetSHA256();
1350 : 149796 : }
1351 : :
1352 : : /** Compute the (single) SHA256 of the concatenation of all nSequences of a tx. */
1353 : : template <class T>
1354 : 149750 : uint256 GetSequencesSHA256(const T& txTo)
1355 : : {
1356 : 149750 : HashWriter ss{};
1357 [ + + + + ]: 793868 : for (const auto& txin : txTo.vin) {
1358 : 644118 : ss << txin.nSequence;
1359 : 644118 : }
1360 : 149750 : return ss.GetSHA256();
1361 : 149750 : }
1362 : :
1363 : : /** Compute the (single) SHA256 of the concatenation of all txouts of a tx. */
1364 : : template <class T>
1365 : 149819 : uint256 GetOutputsSHA256(const T& txTo)
1366 : : {
1367 : 149819 : HashWriter ss{};
1368 [ + + + + ]: 1522917 : for (const auto& txout : txTo.vout) {
1369 : 1373098 : ss << txout;
1370 : 1373098 : }
1371 : 149819 : return ss.GetSHA256();
1372 : 149819 : }
1373 : :
1374 : : /** Compute the (single) SHA256 of the concatenation of all amounts spent by a tx. */
1375 : 8171 : uint256 GetSpentAmountsSHA256(const std::vector<CTxOut>& outputs_spent)
1376 : : {
1377 : 8171 : HashWriter ss{};
1378 [ + + ]: 31498 : for (const auto& txout : outputs_spent) {
1379 : 23327 : ss << txout.nValue;
1380 : 23327 : }
1381 : 8171 : return ss.GetSHA256();
1382 : 8171 : }
1383 : :
1384 : : /** Compute the (single) SHA256 of the concatenation of all scriptPubKeys spent by a tx. */
1385 : 8171 : uint256 GetSpentScriptsSHA256(const std::vector<CTxOut>& outputs_spent)
1386 : : {
1387 : 8171 : HashWriter ss{};
1388 [ + + ]: 31498 : for (const auto& txout : outputs_spent) {
1389 : 23327 : ss << txout.scriptPubKey;
1390 : 23327 : }
1391 : 8171 : return ss.GetSHA256();
1392 : 8171 : }
1393 : :
1394 : :
1395 : : } // namespace
1396 : :
1397 : : template <class T>
1398 : 169220 : void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent_outputs, bool force)
1399 : : {
1400 [ + - + - ]: 169220 : assert(!m_spent_outputs_ready);
1401 : :
1402 : 169220 : m_spent_outputs = std::move(spent_outputs);
1403 [ + + + + ]: 169220 : if (!m_spent_outputs.empty()) {
1404 [ + - + - ]: 152615 : assert(m_spent_outputs.size() == txTo.vin.size());
1405 : 152615 : m_spent_outputs_ready = true;
1406 : 152615 : }
1407 : :
1408 : : // Determine which precomputation-impacting features this transaction uses.
1409 : 169220 : bool uses_bip143_segwit = force;
1410 : 169220 : bool uses_bip341_taproot = force;
1411 [ + + + + : 605401 : for (size_t inpos = 0; inpos < txTo.vin.size() && !(uses_bip143_segwit && uses_bip341_taproot); ++inpos) {
+ + + + -
+ - + ]
1412 [ + + # # ]: 436181 : if (!txTo.vin[inpos].scriptWitness.IsNull()) {
1413 [ + + + + : 244023 : if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.size() == 2 + WITNESS_V1_TAPROOT_SIZE &&
+ + # # #
# # # ]
1414 : 228427 : 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 : 838 : uses_bip341_taproot = true;
1420 : 838 : } 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 : 243185 : uses_bip143_segwit = true;
1425 : : }
1426 : 244023 : }
1427 [ + + + + : 436181 : if (uses_bip341_taproot && uses_bip143_segwit) break; // No need to scan further if we already need all.
# # # # ]
1428 : 436043 : }
1429 : :
1430 [ + + + + : 169220 : if (uses_bip143_segwit || uses_bip341_taproot) {
- + # # ]
1431 : : // Computations shared between both sighash schemes.
1432 : 149612 : m_prevouts_single_hash = GetPrevoutsSHA256(txTo);
1433 : 149612 : m_sequences_single_hash = GetSequencesSHA256(txTo);
1434 : 149612 : m_outputs_single_hash = GetOutputsSHA256(txTo);
1435 : 149612 : }
1436 [ + + - + ]: 169220 : if (uses_bip143_segwit) {
1437 : 149038 : hashPrevouts = SHA256Uint256(m_prevouts_single_hash);
1438 : 149038 : hashSequence = SHA256Uint256(m_sequences_single_hash);
1439 : 149038 : hashOutputs = SHA256Uint256(m_outputs_single_hash);
1440 : 149038 : m_bip143_segwit_ready = true;
1441 : 149038 : }
1442 [ + + + + : 169220 : if (uses_bip341_taproot && m_spent_outputs_ready) {
+ - + + ]
1443 : 8171 : m_spent_amounts_single_hash = GetSpentAmountsSHA256(m_spent_outputs);
1444 : 8171 : m_spent_scripts_single_hash = GetSpentScriptsSHA256(m_spent_outputs);
1445 : 8171 : m_bip341_taproot_ready = true;
1446 : 8171 : }
1447 : 169220 : }
1448 : :
1449 : : template <class T>
1450 : 227 : PrecomputedTransactionData::PrecomputedTransactionData(const T& txTo)
1451 : : {
1452 [ + - # # ]: 227 : Init(txTo, {});
1453 : 0 : }
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 [ + - + - ]: 1 : const HashWriter HASHER_TAPSIGHASH{TaggedHash("TapSighash")};
1462 [ + - + - ]: 1 : const HashWriter HASHER_TAPLEAF{TaggedHash("TapLeaf")};
1463 [ + - + - ]: 1 : const HashWriter HASHER_TAPBRANCH{TaggedHash("TapBranch")};
1464 : :
1465 : 290 : static bool HandleMissingData(MissingDataBehavior mdb)
1466 : : {
1467 [ + - - ]: 290 : switch (mdb) {
1468 : : case MissingDataBehavior::ASSERT_FAIL:
1469 : 0 : assert(!"Missing data");
1470 : : break;
1471 : : case MissingDataBehavior::FAIL:
1472 : 290 : return false;
1473 : : }
1474 : 0 : assert(!"Unknown MissingDataBehavior value");
1475 : : }
1476 : :
1477 : : template<typename T>
1478 : 1887 : 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 : 1887 : uint8_t ext_flag, key_version;
1481 [ - + + - : 1887 : switch (sigversion) {
+ - ]
1482 : : case SigVersion::TAPROOT:
1483 : 359 : ext_flag = 0;
1484 : : // key_version is not used and left uninitialized.
1485 : 359 : break;
1486 : : case SigVersion::TAPSCRIPT:
1487 : 1528 : 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 : 1528 : key_version = 0;
1493 : 1528 : break;
1494 : : default:
1495 : 0 : assert(false);
1496 : : }
1497 [ + - + - ]: 1887 : assert(in_pos < tx_to.vin.size());
1498 [ + + - + : 1887 : if (!(cache.m_bip341_taproot_ready && cache.m_spent_outputs_ready)) {
- + # # ]
1499 : 37 : return HandleMissingData(mdb);
1500 : : }
1501 : :
1502 : 1850 : HashWriter ss{HASHER_TAPSIGHASH};
1503 : :
1504 : : // Epoch
1505 : : static constexpr uint8_t EPOCH = 0;
1506 : 1850 : ss << EPOCH;
1507 : :
1508 : : // Hash type
1509 [ + + # # ]: 1850 : 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 : 1850 : const uint8_t input_type = hash_type & SIGHASH_INPUT_MASK;
1511 [ + + + + : 1850 : if (!(hash_type <= 0x03 || (hash_type >= 0x81 && hash_type <= 0x83))) return false;
+ + # # #
# # # ]
1512 : 1816 : ss << hash_type;
1513 : :
1514 : : // Transaction level data
1515 : 1816 : ss << tx_to.version;
1516 : 1816 : ss << tx_to.nLockTime;
1517 [ + + # # ]: 1816 : if (input_type != SIGHASH_ANYONECANPAY) {
1518 : 1495 : ss << cache.m_prevouts_single_hash;
1519 : 1495 : ss << cache.m_spent_amounts_single_hash;
1520 : 1495 : ss << cache.m_spent_scripts_single_hash;
1521 : 1495 : ss << cache.m_sequences_single_hash;
1522 : 1495 : }
1523 [ + + # # ]: 1816 : if (output_type == SIGHASH_ALL) {
1524 : 1303 : ss << cache.m_outputs_single_hash;
1525 : 1303 : }
1526 : :
1527 : : // Data about the input/prevout being spent
1528 [ + - # # ]: 1816 : assert(execdata.m_annex_init);
1529 : 1816 : const bool have_annex = execdata.m_annex_present;
1530 : 1816 : const uint8_t spend_type = (ext_flag << 1) + (have_annex ? 1 : 0); // The low bit indicates whether an annex is present.
1531 : 1816 : ss << spend_type;
1532 [ + + # # ]: 1816 : if (input_type == SIGHASH_ANYONECANPAY) {
1533 : 321 : ss << tx_to.vin[in_pos].prevout;
1534 : 321 : ss << cache.m_spent_outputs[in_pos];
1535 : 321 : ss << tx_to.vin[in_pos].nSequence;
1536 : 321 : } else {
1537 : 1495 : ss << in_pos;
1538 : : }
1539 [ + + # # ]: 1816 : if (have_annex) {
1540 : 554 : ss << execdata.m_annex_hash;
1541 : 554 : }
1542 : :
1543 : : // Data about the output (if only one).
1544 [ + + # # ]: 1816 : if (output_type == SIGHASH_SINGLE) {
1545 [ + + # # ]: 233 : if (in_pos >= tx_to.vout.size()) return false;
1546 [ + + # # ]: 214 : if (!execdata.m_output_hash) {
1547 : 80 : HashWriter sha_single_output{};
1548 : 80 : sha_single_output << tx_to.vout[in_pos];
1549 : 80 : execdata.m_output_hash = sha_single_output.GetSHA256();
1550 : 80 : }
1551 : 214 : ss << execdata.m_output_hash.value();
1552 : 214 : }
1553 : :
1554 : : // Additional data for BIP 342 signatures
1555 [ + + # # ]: 1797 : if (sigversion == SigVersion::TAPSCRIPT) {
1556 [ + - # # ]: 1518 : assert(execdata.m_tapleaf_hash_init);
1557 : 1518 : ss << execdata.m_tapleaf_hash;
1558 : 1518 : ss << key_version;
1559 [ + - # # ]: 1518 : assert(execdata.m_codeseparator_pos_init);
1560 : 1518 : ss << execdata.m_codeseparator_pos;
1561 : 1518 : }
1562 : :
1563 : 1797 : hash_out = ss.GetSHA256();
1564 : 1797 : return true;
1565 : 1887 : }
1566 : :
1567 : : template <class T>
1568 : 130453 : uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1569 : : {
1570 [ + - + - ]: 130453 : assert(nIn < txTo.vin.size());
1571 : :
1572 [ + + + + ]: 130453 : if (sigversion == SigVersion::WITNESS_V0) {
1573 : 61293 : uint256 hashPrevouts;
1574 : 61293 : uint256 hashSequence;
1575 : 61293 : uint256 hashOutputs;
1576 [ + + + + ]: 61293 : const bool cacheready = cache && cache->m_bip143_segwit_ready;
1577 : :
1578 [ + + + + ]: 61293 : if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1579 [ + + + + ]: 58659 : hashPrevouts = cacheready ? cache->hashPrevouts : SHA256Uint256(GetPrevoutsSHA256(txTo));
1580 : 58659 : }
1581 : :
1582 [ + + + + : 61293 : if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
+ + + + +
+ + + ]
1583 [ + + + + ]: 33957 : hashSequence = cacheready ? cache->hashSequence : SHA256Uint256(GetSequencesSHA256(txTo));
1584 : 33957 : }
1585 : :
1586 : :
1587 [ + + + + : 61293 : if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
+ + + + ]
1588 [ + + + + ]: 34551 : hashOutputs = cacheready ? cache->hashOutputs : SHA256Uint256(GetOutputsSHA256(txTo));
1589 [ + + + + : 61293 : } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
+ + + + ]
1590 : 7809 : HashWriter ss{};
1591 : 7809 : ss << txTo.vout[nIn];
1592 : 7809 : hashOutputs = ss.GetHash();
1593 : 7809 : }
1594 : :
1595 : 61293 : HashWriter ss{};
1596 : : // Version
1597 : 61293 : ss << txTo.version;
1598 : : // Input prevouts/nSequence (none/all, depending on flags)
1599 : 61293 : ss << hashPrevouts;
1600 : 61293 : ss << hashSequence;
1601 : : // The input being signed (replacing the scriptSig with scriptCode + amount)
1602 : : // The prevout may already be contained in hashPrevout, and the nSequence
1603 : : // may already be contain in hashSequence.
1604 : 61293 : ss << txTo.vin[nIn].prevout;
1605 : 61293 : ss << scriptCode;
1606 : 61293 : ss << amount;
1607 : 61293 : ss << txTo.vin[nIn].nSequence;
1608 : : // Outputs (none/one/all, depending on flags)
1609 : 61293 : ss << hashOutputs;
1610 : : // Locktime
1611 : 61293 : ss << txTo.nLockTime;
1612 : : // Sighash type
1613 : 61293 : ss << nHashType;
1614 : :
1615 : 61293 : return ss.GetHash();
1616 : 61293 : }
1617 : :
1618 : : // Check for invalid use of SIGHASH_SINGLE
1619 [ + + + + ]: 69160 : if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1620 [ + + + + ]: 8431 : if (nIn >= txTo.vout.size()) {
1621 : : // nOut out of range
1622 : 3566 : return uint256::ONE;
1623 : : }
1624 : 4865 : }
1625 : :
1626 : : // Wrapper to serialize only the necessary parts of the transaction being signed
1627 : 65594 : CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
1628 : :
1629 : : // Serialize and hash
1630 : 65594 : HashWriter ss{};
1631 : 65594 : ss << txTmp << nHashType;
1632 : 65594 : return ss.GetHash();
1633 : 130453 : }
1634 : :
1635 : : template <class T>
1636 : 100622 : bool GenericTransactionSignatureChecker<T>::VerifyECDSASignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1637 : : {
1638 : 100622 : return pubkey.Verify(sighash, vchSig);
1639 : : }
1640 : :
1641 : : template <class T>
1642 : 1876 : bool GenericTransactionSignatureChecker<T>::VerifySchnorrSignature(Span<const unsigned char> sig, const XOnlyPubKey& pubkey, const uint256& sighash) const
1643 : : {
1644 : 1876 : return pubkey.VerifySchnorr(sighash, sig);
1645 : : }
1646 : :
1647 : : template <class T>
1648 : 203032 : bool GenericTransactionSignatureChecker<T>::CheckECDSASignature(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1649 : : {
1650 : 203032 : CPubKey pubkey(vchPubKey);
1651 [ + + - + ]: 203032 : if (!pubkey.IsValid())
1652 : 97816 : return false;
1653 : :
1654 : : // Hash type is one byte tacked on to the end of the signature
1655 : 105216 : std::vector<unsigned char> vchSig(vchSigIn);
1656 [ + + + + ]: 105216 : if (vchSig.empty())
1657 : 4725 : return false;
1658 : 100491 : int nHashType = vchSig.back();
1659 : 100491 : vchSig.pop_back();
1660 : :
1661 : : // Witness sighashes need the amount.
1662 [ + + + - : 100491 : if (sigversion == SigVersion::WITNESS_V0 && amount < 0) return HandleMissingData(m_mdb);
# # + + +
+ + - ]
1663 : :
1664 [ + - + - ]: 100475 : uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
1665 : :
1666 [ + - + + : 100475 : if (!VerifyECDSASignature(vchSig, pubkey, sighash))
+ - + + ]
1667 : 92333 : return false;
1668 : :
1669 : 8142 : return true;
1670 : 203032 : }
1671 : :
1672 : : template <class T>
1673 : 5178 : bool GenericTransactionSignatureChecker<T>::CheckSchnorrSignature(Span<const unsigned char> sig, Span<const unsigned char> pubkey_in, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) const
1674 : : {
1675 [ + + + - : 5178 : assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
+ - + - ]
1676 : : // Schnorr signatures have 32-byte public keys. The caller is responsible for enforcing this.
1677 [ + - + - ]: 5178 : assert(pubkey_in.size() == 32);
1678 : : // Note that in Tapscript evaluation, empty signatures are treated specially (invalid signature that does not
1679 : : // abort script execution). This is implemented in EvalChecksigTapscript, which won't invoke
1680 : : // CheckSchnorrSignature in that case. In other contexts, they are invalid like every other signature with
1681 : : // size different from 64 or 65.
1682 [ + + + + : 5178 : if (sig.size() != 64 && sig.size() != 65) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_SIZE);
+ + + + ]
1683 : :
1684 : 2155 : XOnlyPubKey pubkey{pubkey_in};
1685 : :
1686 : 2155 : uint8_t hashtype = SIGHASH_DEFAULT;
1687 [ + + + + ]: 2155 : if (sig.size() == 65) {
1688 : 1641 : hashtype = SpanPopBack(sig);
1689 [ + + + + ]: 1641 : if (hashtype == SIGHASH_DEFAULT) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
1690 : 1610 : }
1691 : 2124 : uint256 sighash;
1692 [ + - + + ]: 2124 : if (!this->txdata) return HandleMissingData(m_mdb);
1693 [ + + - + ]: 1887 : if (!SignatureHashSchnorr(sighash, execdata, *txTo, nIn, hashtype, sigversion, *this->txdata, m_mdb)) {
1694 : 90 : return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
1695 : : }
1696 [ + + # # ]: 1797 : if (!VerifySchnorrSignature(sig, pubkey, sighash)) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG);
1697 : 1469 : return true;
1698 : 5178 : }
1699 : :
1700 : : template <class T>
1701 : 17500 : bool GenericTransactionSignatureChecker<T>::CheckLockTime(const CScriptNum& nLockTime) const
1702 : : {
1703 : : // There are two kinds of nLockTime: lock-by-blockheight
1704 : : // and lock-by-blocktime, distinguished by whether
1705 : : // nLockTime < LOCKTIME_THRESHOLD.
1706 : : //
1707 : : // We want to compare apples to apples, so fail the script
1708 : : // unless the type of nLockTime being tested is the same as
1709 : : // the nLockTime in the transaction.
1710 [ + + + + ]: 17500 : if (!(
1711 [ + + + + : 25050 : (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
+ + + + ]
1712 [ + + + + ]: 7550 : (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1713 : : ))
1714 : 3607 : return false;
1715 : :
1716 : : // Now that we know we're comparing apples-to-apples, the
1717 : : // comparison is a simple numeric one.
1718 [ + + + + ]: 13893 : if (nLockTime > (int64_t)txTo->nLockTime)
1719 : 3491 : return false;
1720 : :
1721 : : // Finally the nLockTime feature can be disabled in IsFinalTx()
1722 : : // and thus CHECKLOCKTIMEVERIFY bypassed if every txin has
1723 : : // been finalized by setting nSequence to maxint. The
1724 : : // transaction would be allowed into the blockchain, making
1725 : : // the opcode ineffective.
1726 : : //
1727 : : // Testing if this vin is not final is sufficient to
1728 : : // prevent this condition. Alternatively we could test all
1729 : : // inputs, but testing just this input minimizes the data
1730 : : // required to prove correct CHECKLOCKTIMEVERIFY execution.
1731 [ + + + + ]: 10402 : if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1732 : 373 : return false;
1733 : :
1734 : 10029 : return true;
1735 : 17500 : }
1736 : :
1737 : : template <class T>
1738 : 25136 : bool GenericTransactionSignatureChecker<T>::CheckSequence(const CScriptNum& nSequence) const
1739 : : {
1740 : : // Relative lock times are supported by comparing the passed
1741 : : // in operand to the sequence number of the input.
1742 : 25136 : const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1743 : :
1744 : : // Fail if the transaction's version number is not set high
1745 : : // enough to trigger BIP 68 rules.
1746 [ + + + + ]: 25136 : if (txTo->version < 2)
1747 : 1537 : return false;
1748 : :
1749 : : // Sequence numbers with their most significant bit set are not
1750 : : // consensus constrained. Testing that the transaction's sequence
1751 : : // number do not have this bit set prevents using this property
1752 : : // to get around a CHECKSEQUENCEVERIFY check.
1753 [ + + + + ]: 23599 : if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1754 : 867 : return false;
1755 : :
1756 : : // Mask off any bits that do not have consensus-enforced meaning
1757 : : // before doing the integer comparisons
1758 : 22732 : const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1759 : 22732 : const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1760 : 22732 : const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1761 : :
1762 : : // There are two kinds of nSequence: lock-by-blockheight
1763 : : // and lock-by-blocktime, distinguished by whether
1764 : : // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1765 : : //
1766 : : // We want to compare apples to apples, so fail the script
1767 : : // unless the type of nSequenceMasked being tested is the same as
1768 : : // the nSequenceMasked in the transaction.
1769 [ + + + + ]: 22732 : if (!(
1770 [ + + + + : 32019 : (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
+ + + + ]
1771 [ + + + + ]: 9287 : (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1772 : : )) {
1773 : 4506 : return false;
1774 : : }
1775 : :
1776 : : // Now that we know we're comparing apples-to-apples, the
1777 : : // comparison is a simple numeric one.
1778 [ + + + + ]: 18226 : if (nSequenceMasked > txToSequenceMasked)
1779 : 1901 : return false;
1780 : :
1781 : 16325 : return true;
1782 : 25136 : }
1783 : :
1784 : : // explicit instantiation
1785 : : template class GenericTransactionSignatureChecker<CTransaction>;
1786 : : template class GenericTransactionSignatureChecker<CMutableTransaction>;
1787 : :
1788 : 318344 : static bool ExecuteWitnessScript(const Span<const valtype>& stack_span, const CScript& exec_script, unsigned int flags, SigVersion sigversion, const BaseSignatureChecker& checker, ScriptExecutionData& execdata, ScriptError* serror)
1789 : : {
1790 [ + - ]: 318344 : std::vector<valtype> stack{stack_span.begin(), stack_span.end()};
1791 : :
1792 [ + + ]: 318344 : if (sigversion == SigVersion::TAPSCRIPT) {
1793 : : // OP_SUCCESSx processing overrides everything, including stack element size limits
1794 [ + - ]: 1797 : CScript::const_iterator pc = exec_script.begin();
1795 [ + - + - : 575679 : while (pc < exec_script.end()) {
+ + ]
1796 : 573971 : opcodetype opcode;
1797 [ + - + + ]: 573971 : if (!exec_script.GetOp(pc, opcode)) {
1798 : : // Note how this condition would not be reached if an unknown OP_SUCCESSx was found
1799 : 2 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1800 : : }
1801 : : // New opcodes will be listed here. May use a different sigversion to modify existing opcodes.
1802 [ + - + + ]: 573969 : if (IsOpSuccess(opcode)) {
1803 [ + + ]: 87 : if (flags & SCRIPT_VERIFY_DISCOURAGE_OP_SUCCESS) {
1804 : 66 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_OP_SUCCESS);
1805 : : }
1806 : 21 : return set_success(serror);
1807 : : }
1808 [ + + ]: 573971 : }
1809 : :
1810 : : // Tapscript enforces initial stack size limits (altstack is empty here)
1811 [ + + ]: 1708 : if (stack.size() > MAX_STACK_SIZE) return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1812 [ + + ]: 1797 : }
1813 : :
1814 : : // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
1815 [ + + + + ]: 966293 : for (const valtype& elem : stack) {
1816 [ + + ]: 648069 : if (elem.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
1817 [ + + ]: 648069 : }
1818 : :
1819 : : // Run the script interpreter.
1820 [ + - + + ]: 317941 : if (!EvalScript(stack, exec_script, flags, checker, sigversion, execdata, serror)) return false;
1821 : :
1822 : : // Scripts inside witness implicitly require cleanstack behaviour
1823 [ + + ]: 281204 : if (stack.size() != 1) return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1824 [ + + ]: 277660 : if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1825 : 270305 : return true;
1826 : 318344 : }
1827 : :
1828 : 103964 : uint256 ComputeTapleafHash(uint8_t leaf_version, Span<const unsigned char> script)
1829 : : {
1830 : 103964 : return (HashWriter{HASHER_TAPLEAF} << leaf_version << CompactSizeWriter(script.size()) << script).GetSHA256();
1831 : : }
1832 : :
1833 : 104604 : uint256 ComputeTapbranchHash(Span<const unsigned char> a, Span<const unsigned char> b)
1834 : : {
1835 : 104604 : HashWriter ss_branch{HASHER_TAPBRANCH};
1836 [ + + ]: 104604 : if (std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end())) {
1837 : 25142 : ss_branch << a << b;
1838 : 25142 : } else {
1839 : 79462 : ss_branch << b << a;
1840 : : }
1841 : 104604 : return ss_branch.GetSHA256();
1842 : 104604 : }
1843 : :
1844 : 6488 : uint256 ComputeTaprootMerkleRoot(Span<const unsigned char> control, const uint256& tapleaf_hash)
1845 : : {
1846 [ + - ]: 6488 : assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE);
1847 [ + - ]: 6488 : assert(control.size() <= TAPROOT_CONTROL_MAX_SIZE);
1848 [ + - ]: 6488 : assert((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE == 0);
1849 : :
1850 : 6488 : const int path_len = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
1851 : 6488 : uint256 k = tapleaf_hash;
1852 [ + + ]: 23732 : for (int i = 0; i < path_len; ++i) {
1853 : 17244 : Span node{Span{control}.subspan(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * i, TAPROOT_CONTROL_NODE_SIZE)};
1854 : 17244 : k = ComputeTapbranchHash(k, node);
1855 : 17244 : }
1856 : : return k;
1857 : 6488 : }
1858 : :
1859 : 3943 : static bool VerifyTaprootCommitment(const std::vector<unsigned char>& control, const std::vector<unsigned char>& program, const uint256& tapleaf_hash)
1860 : : {
1861 [ + - ]: 3943 : assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE);
1862 [ + - ]: 3943 : assert(program.size() >= uint256::size());
1863 : : //! The internal pubkey (x-only, so no Y coordinate parity).
1864 : 3943 : const XOnlyPubKey p{Span{control}.subspan(1, TAPROOT_CONTROL_BASE_SIZE - 1)};
1865 : : //! The output pubkey (taken from the scriptPubKey).
1866 : 3943 : const XOnlyPubKey q{program};
1867 : : // Compute the Merkle root from the leaf and the provided path.
1868 : 3943 : const uint256 merkle_root = ComputeTaprootMerkleRoot(control, tapleaf_hash);
1869 : : // Verify that the output pubkey matches the tweaked internal pubkey, after correcting for parity.
1870 : 7886 : return q.CheckTapTweak(p, merkle_root, control[0] & 1);
1871 : 3943 : }
1872 : :
1873 : 386835 : 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)
1874 : : {
1875 : 386835 : CScript exec_script; //!< Actually executed script (last stack item in P2WSH; implied P2PKH script in P2WPKH; leaf script in P2TR)
1876 [ + - ]: 386835 : Span stack{witness.stack};
1877 [ + - ]: 386835 : ScriptExecutionData execdata;
1878 : :
1879 [ + + ]: 386835 : if (witversion == 0) {
1880 [ + + ]: 364287 : if (program.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
1881 : : // BIP141 P2WSH: 32-byte witness v0 program (which encodes SHA256(script))
1882 [ + + ]: 315500 : if (stack.size() == 0) {
1883 : 20864 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1884 : : }
1885 [ + - ]: 294636 : const valtype& script_bytes = SpanPopBack(stack);
1886 [ + - ]: 294636 : exec_script = CScript(script_bytes.begin(), script_bytes.end());
1887 [ + - ]: 294636 : uint256 hash_exec_script;
1888 [ + - + - : 294636 : CSHA256().Write(exec_script.data(), exec_script.size()).Finalize(hash_exec_script.begin());
+ - + - +
- ]
1889 [ + + ]: 294636 : if (memcmp(hash_exec_script.begin(), program.data(), 32)) {
1890 : 14532 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1891 : : }
1892 [ + - ]: 280104 : return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
1893 [ + + ]: 343423 : } else if (program.size() == WITNESS_V0_KEYHASH_SIZE) {
1894 : : // BIP141 P2WPKH: 20-byte witness v0 program (which encodes Hash160(pubkey))
1895 [ + + ]: 46632 : if (stack.size() != 2) {
1896 : 10189 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1897 : : }
1898 [ + - + - : 36443 : exec_script << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
+ - + - +
- ]
1899 [ + - ]: 36443 : return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
1900 : : } else {
1901 : 2155 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
1902 : : }
1903 [ + + + + : 22548 : } else if (witversion == 1 && program.size() == WITNESS_V1_TAPROOT_SIZE && !is_p2sh) {
+ + ]
1904 : : // BIP341 Taproot: 32-byte non-P2SH witness v1 program (which encodes a P2C-tweaked pubkey)
1905 [ + + ]: 19966 : if (!(flags & SCRIPT_VERIFY_TAPROOT)) return set_success(serror);
1906 [ + + ]: 19762 : if (stack.size() == 0) return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1907 [ + + + + : 9785 : if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
+ + ]
1908 : : // Drop annex (this is non-standard; see IsWitnessStandard)
1909 [ + - ]: 700 : const valtype& annex = SpanPopBack(stack);
1910 [ + - + - : 700 : execdata.m_annex_hash = (HashWriter{} << annex).GetSHA256();
+ - ]
1911 : 700 : execdata.m_annex_present = true;
1912 : 700 : } else {
1913 : 9085 : execdata.m_annex_present = false;
1914 : : }
1915 : 9785 : execdata.m_annex_init = true;
1916 [ + + ]: 9785 : if (stack.size() == 1) {
1917 : : // Key path spending (stack size is 1 after removing optional annex)
1918 [ + - + - : 3657 : if (!checker.CheckSchnorrSignature(stack.front(), program, SigVersion::TAPROOT, execdata, serror)) {
+ - + + ]
1919 : 3631 : return false; // serror is set
1920 : : }
1921 : 26 : return set_success(serror);
1922 : : } else {
1923 : : // Script path spending (stack size is >1 after removing optional annex)
1924 [ + - ]: 6128 : const valtype& control = SpanPopBack(stack);
1925 [ + - ]: 6128 : const valtype& script = SpanPopBack(stack);
1926 [ + + + + : 6128 : if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE || ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) {
+ + ]
1927 : 2185 : return set_error(serror, SCRIPT_ERR_TAPROOT_WRONG_CONTROL_SIZE);
1928 : : }
1929 [ + - + - ]: 3943 : execdata.m_tapleaf_hash = ComputeTapleafHash(control[0] & TAPROOT_LEAF_MASK, script);
1930 [ + - + + ]: 3943 : if (!VerifyTaprootCommitment(control, program, execdata.m_tapleaf_hash)) {
1931 : 2124 : return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1932 : : }
1933 : 1819 : execdata.m_tapleaf_hash_init = true;
1934 [ + + ]: 1819 : if ((control[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
1935 : : // Tapscript (leaf version 0xc0)
1936 [ + - ]: 1797 : exec_script = CScript(script.begin(), script.end());
1937 [ + - ]: 1797 : execdata.m_validation_weight_left = ::GetSerializeSize(witness.stack) + VALIDATION_WEIGHT_OFFSET;
1938 : 1797 : execdata.m_validation_weight_left_init = true;
1939 [ + - ]: 1797 : return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::TAPSCRIPT, checker, execdata, serror);
1940 : : }
1941 [ + + ]: 22 : if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION) {
1942 : 14 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION);
1943 : : }
1944 : 8 : return set_success(serror);
1945 : 6128 : }
1946 [ + + + - : 2582 : } else if (!is_p2sh && CScript::IsPayToAnchor(witversion, program)) {
+ - ]
1947 : 0 : return true;
1948 : : } else {
1949 [ + + ]: 2582 : if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
1950 : 2258 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
1951 : : }
1952 : : // Other version/size/p2sh combinations return true for future softfork compatibility
1953 : 324 : return true;
1954 : : }
1955 : : // 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.
1956 : 386835 : }
1957 : :
1958 : 1124785 : bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1959 : : {
1960 : : static const CScriptWitness emptyWitness;
1961 [ + + ]: 1124785 : if (witness == nullptr) {
1962 : 1705 : witness = &emptyWitness;
1963 : 1705 : }
1964 : 1124785 : bool hadWitness = false;
1965 : :
1966 : 1124785 : set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1967 : :
1968 [ + + + + ]: 1124785 : if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1969 : 25699 : return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1970 : : }
1971 : :
1972 : : // scriptSig and scriptPubKey must be evaluated sequentially on the same stack
1973 : : // rather than being simply concatenated (see CVE-2010-5141)
1974 : 1099086 : std::vector<std::vector<unsigned char> > stack, stackCopy;
1975 [ + + + + ]: 1099086 : if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
1976 : : // serror is set
1977 : 185525 : return false;
1978 [ + + ]: 913558 : if (flags & SCRIPT_VERIFY_P2SH)
1979 [ + - ]: 801649 : stackCopy = stack;
1980 [ + + + + ]: 913558 : if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
1981 : : // serror is set
1982 : 356690 : return false;
1983 [ + + ]: 556871 : if (stack.empty())
1984 [ + - ]: 72858 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1985 [ + + ]: 484013 : if (CastToBool(stack.back()) == false)
1986 [ + - ]: 18851 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1987 : :
1988 : : // Bare witness programs
1989 : 465162 : int witnessversion;
1990 : 465162 : std::vector<unsigned char> witnessprogram;
1991 [ + + ]: 465162 : if (flags & SCRIPT_VERIFY_WITNESS) {
1992 [ + + + + ]: 431965 : if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1993 : 369561 : hadWitness = true;
1994 [ + - + + ]: 369561 : if (scriptSig.size() != 0) {
1995 : : // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
1996 [ + - ]: 17624 : return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
1997 : : }
1998 [ + - + + ]: 351937 : if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /*is_p2sh=*/false)) {
1999 : 83451 : return false;
2000 : : }
2001 : : // Bypass the cleanstack check at the end. The actual stack is obviously not clean
2002 : : // for witness programs.
2003 [ + - ]: 268486 : stack.resize(1);
2004 : 268486 : }
2005 : 330887 : }
2006 : :
2007 : : // Additional validation for spend-to-script-hash transactions:
2008 [ + + + + : 364084 : if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
+ + ]
2009 : : {
2010 : : // scriptSig must be literals-only or validation fails
2011 [ + - + + ]: 43893 : if (!scriptSig.IsPushOnly())
2012 [ + - ]: 505 : return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
2013 : :
2014 : : // Restore stack.
2015 : 43388 : swap(stack, stackCopy);
2016 : :
2017 : : // stack cannot be empty here, because if it was the
2018 : : // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
2019 : : // an empty stack and the EvalScript above would return false.
2020 [ + - ]: 43388 : assert(!stack.empty());
2021 : :
2022 : 43388 : const valtype& pubKeySerialized = stack.back();
2023 [ + - ]: 43388 : CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
2024 [ + - ]: 43388 : popstack(stack);
2025 : :
2026 [ + - + + ]: 43388 : if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
2027 : : // serror is set
2028 : 2758 : return false;
2029 [ + + ]: 40630 : if (stack.empty())
2030 [ + - ]: 2613 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2031 [ + + ]: 38017 : if (!CastToBool(stack.back()))
2032 [ + - ]: 1084 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2033 : :
2034 : : // P2SH witness program
2035 [ + + ]: 36933 : if (flags & SCRIPT_VERIFY_WITNESS) {
2036 [ + - + + ]: 35478 : if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
2037 : 34934 : hadWitness = true;
2038 [ + - + - : 34934 : if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
+ - + - +
- + + ]
2039 : : // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
2040 : : // reintroduce malleability.
2041 [ + - ]: 36 : return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
2042 : : }
2043 [ + - + + ]: 34898 : if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /*is_p2sh=*/true)) {
2044 : 32496 : return false;
2045 : : }
2046 : : // Bypass the cleanstack check at the end. The actual stack is obviously not clean
2047 : : // for witness programs.
2048 [ + - ]: 2402 : stack.resize(1);
2049 : 2402 : }
2050 : 2946 : }
2051 [ + + ]: 43388 : }
2052 : :
2053 : : // The CLEANSTACK check is only performed after potential P2SH evaluation,
2054 : : // as the non-P2SH evaluation of a P2SH script will obviously not result in
2055 : : // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
2056 [ + + ]: 324594 : if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
2057 : : // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
2058 : : // would be possible, which is not a softfork (and P2SH should be one).
2059 [ + - ]: 238744 : assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2060 [ + - ]: 238744 : assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
2061 [ + + ]: 238744 : if (stack.size() != 1) {
2062 [ + - ]: 10569 : return set_error(serror, SCRIPT_ERR_CLEANSTACK);
2063 : : }
2064 : 228175 : }
2065 : :
2066 [ + + ]: 314025 : if (flags & SCRIPT_VERIFY_WITNESS) {
2067 : : // We can't check for correct unexpected witness data if P2SH was off, so require
2068 : : // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
2069 : : // possible, which is not a softfork.
2070 [ + - ]: 280853 : assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2071 [ + + + - : 280853 : if (!hadWitness && !witness->IsNull()) {
+ + ]
2072 [ + - ]: 2793 : return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
2073 : : }
2074 : 278060 : }
2075 : :
2076 [ + + ]: 311232 : return set_success(serror);
2077 : 1124795 : }
2078 : :
2079 : 2421786 : size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness)
2080 : : {
2081 [ + + ]: 2421786 : if (witversion == 0) {
2082 [ + + ]: 2420694 : if (witprogram.size() == WITNESS_V0_KEYHASH_SIZE)
2083 : 794 : return 1;
2084 : :
2085 [ + + + + ]: 2419900 : if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.stack.size() > 0) {
2086 : 2399447 : CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
2087 [ + - ]: 2399447 : return subscript.GetSigOpCount(true);
2088 : 2399447 : }
2089 : 20453 : }
2090 : :
2091 : : // Future flags may be implemented here.
2092 : 21545 : return 0;
2093 : 2421786 : }
2094 : :
2095 : 2433944 : size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags)
2096 : : {
2097 : : static const CScriptWitness witnessEmpty;
2098 : :
2099 [ + + ]: 2433944 : if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
2100 : 970 : return 0;
2101 : : }
2102 [ + - ]: 2432974 : assert((flags & SCRIPT_VERIFY_P2SH) != 0);
2103 : :
2104 : 2432974 : int witnessversion;
2105 : 2432974 : std::vector<unsigned char> witnessprogram;
2106 [ + - + + ]: 2432974 : if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2107 [ + - + - ]: 2421661 : return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
2108 : : }
2109 : :
2110 [ + - + + : 11313 : if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
+ - + + ]
2111 [ + - ]: 1309 : CScript::const_iterator pc = scriptSig.begin();
2112 : 1309 : std::vector<unsigned char> data;
2113 [ + - + - : 299303 : while (pc < scriptSig.end()) {
+ + ]
2114 : 297994 : opcodetype opcode;
2115 [ + - ]: 297994 : scriptSig.GetOp(pc, opcode, data);
2116 : 297994 : }
2117 [ + - ]: 1309 : CScript subscript(data.begin(), data.end());
2118 [ + - + + ]: 1309 : if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
2119 [ + - + - ]: 125 : return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty);
2120 : : }
2121 [ + + ]: 1309 : }
2122 : :
2123 : 11188 : return 0;
2124 : 2433944 : }
|