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