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