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