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