Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
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
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
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
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.
196 }
197 return true;
198}
199
201 if (vchSig.size() == 0) {
202 return false;
203 }
204 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
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 }
219 } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
220 // serror is set
221 return false;
224 }
225 return true;
226}
227
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();
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
332{
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
340 int found = FindAndDelete(scriptCode, CScript() << vchSig);
341 if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
343 }
344
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())
353
354 return true;
355}
356
358{
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.
371 assert(execdata.m_validation_weight_left_init);
372 execdata.m_validation_weight_left -= VALIDATION_WEIGHT_PER_SIGOP_PASSED;
373 if (execdata.m_validation_weight_left < 0) {
375 }
376 }
377 if (pubkey.size() == 0) {
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 */
391 }
392 }
393
394 return true;
395}
396
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.
429
435 ConditionStack vfExec;
436 std::vector<valtype> altstack;
440 }
441 int nOpCount = 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))
459
461 // Note how OP_RESERVED does not count towards the opcode limit.
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
487
488 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
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)
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)
563
564 // Actually compare the specified lock time with the transaction.
565 if (!checker.CheckLockTime(nLockTime))
567
568 break;
569 }
570
572 {
574 // not enabled; treat as a NOP3
575 break;
576 }
577
578 if (stack.size() < 1)
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)
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))
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 {
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)
622 valtype& vch = stacktop(-1);
623 // Tapscript requires minimal IF/NOTIF inputs as a consensus rule.
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)) {
629 }
630 }
631 // Under witness v0 rules it is only a policy rule, enabled through SCRIPT_VERIFY_MINIMALIF.
633 if (vch.size() > 1)
635 if (vch.size() == 1 && vch[0] != 1)
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())
651 vfExec.toggle_top();
652 }
653 break;
654
655 case OP_ENDIF:
656 {
657 if (vfExec.empty())
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)
669 bool fValue = CastToBool(stacktop(-1));
670 if (fValue)
671 popstack(stack);
672 else
674 }
675 break;
676
677 case OP_RETURN:
679
680 //
681 // Stack ops
682 //
683 case OP_TOALTSTACK:
684 {
685 if (stack.size() < 1)
687 altstack.push_back(stacktop(-1));
688 popstack(stack);
689 }
690 break;
691
692 case OP_FROMALTSTACK:
693 {
694 if (altstack.size() < 1)
696 stack.push_back(altstacktop(-1));
698 }
699 break;
700
701 case OP_2DROP:
702 {
703 // (x1 x2 -- )
704 if (stack.size() < 2)
706 popstack(stack);
707 popstack(stack);
708 }
709 break;
710
711 case OP_2DUP:
712 {
713 // (x1 x2 -- x1 x2 x1 x2)
714 if (stack.size() < 2)
716 valtype vch1 = stacktop(-2);
717 valtype vch2 = stacktop(-1);
718 stack.push_back(vch1);
719 stack.push_back(vch2);
720 }
721 break;
722
723 case OP_3DUP:
724 {
725 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
726 if (stack.size() < 3)
728 valtype vch1 = stacktop(-3);
729 valtype vch2 = stacktop(-2);
730 valtype vch3 = stacktop(-1);
731 stack.push_back(vch1);
732 stack.push_back(vch2);
733 stack.push_back(vch3);
734 }
735 break;
736
737 case OP_2OVER:
738 {
739 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
740 if (stack.size() < 4)
742 valtype vch1 = stacktop(-4);
743 valtype vch2 = stacktop(-3);
744 stack.push_back(vch1);
745 stack.push_back(vch2);
746 }
747 break;
748
749 case OP_2ROT:
750 {
751 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
752 if (stack.size() < 6)
754 valtype vch1 = stacktop(-6);
755 valtype vch2 = stacktop(-5);
756 stack.erase(stack.end()-6, stack.end()-4);
757 stack.push_back(vch1);
758 stack.push_back(vch2);
759 }
760 break;
761
762 case OP_2SWAP:
763 {
764 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
765 if (stack.size() < 4)
767 swap(stacktop(-4), stacktop(-2));
768 swap(stacktop(-3), stacktop(-1));
769 }
770 break;
771
772 case OP_IFDUP:
773 {
774 // (x - 0 | x x)
775 if (stack.size() < 1)
777 valtype vch = stacktop(-1);
778 if (CastToBool(vch))
779 stack.push_back(vch);
780 }
781 break;
782
783 case OP_DEPTH:
784 {
785 // -- stacksize
786 CScriptNum bn(stack.size());
787 stack.push_back(bn.getvch());
788 }
789 break;
790
791 case OP_DROP:
792 {
793 // (x -- )
794 if (stack.size() < 1)
796 popstack(stack);
797 }
798 break;
799
800 case OP_DUP:
801 {
802 // (x -- x x)
803 if (stack.size() < 1)
805 valtype vch = stacktop(-1);
806 stack.push_back(vch);
807 }
808 break;
809
810 case OP_NIP:
811 {
812 // (x1 x2 -- x2)
813 if (stack.size() < 2)
815 stack.erase(stack.end() - 2);
816 }
817 break;
818
819 case OP_OVER:
820 {
821 // (x1 x2 -- x1 x2 x1)
822 if (stack.size() < 2)
824 valtype vch = stacktop(-2);
825 stack.push_back(vch);
826 }
827 break;
828
829 case OP_PICK:
830 case OP_ROLL:
831 {
832 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
833 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
834 if (stack.size() < 2)
837 popstack(stack);
838 if (n < 0 || n >= (int)stack.size())
840 valtype vch = stacktop(-n-1);
841 if (opcode == OP_ROLL)
842 stack.erase(stack.end()-n-1);
843 stack.push_back(vch);
844 }
845 break;
846
847 case OP_ROT:
848 {
849 // (x1 x2 x3 -- x2 x3 x1)
850 // x2 x1 x3 after first swap
851 // x2 x3 x1 after second swap
852 if (stack.size() < 3)
854 swap(stacktop(-3), stacktop(-2));
855 swap(stacktop(-2), stacktop(-1));
856 }
857 break;
858
859 case OP_SWAP:
860 {
861 // (x1 x2 -- x2 x1)
862 if (stack.size() < 2)
864 swap(stacktop(-2), stacktop(-1));
865 }
866 break;
867
868 case OP_TUCK:
869 {
870 // (x1 x2 -- x2 x1 x2)
871 if (stack.size() < 2)
873 valtype vch = stacktop(-1);
874 stack.insert(stack.end()-2, vch);
875 }
876 break;
877
878
879 case OP_SIZE:
880 {
881 // (in -- in size)
882 if (stack.size() < 1)
884 CScriptNum bn(stacktop(-1).size());
885 stack.push_back(bn.getvch());
886 }
887 break;
888
889
890 //
891 // Bitwise logic
892 //
893 case OP_EQUAL:
894 case OP_EQUALVERIFY:
895 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
896 {
897 // (x1 x2 - bool)
898 if (stack.size() < 2)
900 valtype& vch1 = stacktop(-2);
901 valtype& vch2 = stacktop(-1);
902 bool fEqual = (vch1 == vch2);
903 // OP_NOTEQUAL is disabled because it would be too easy to say
904 // something like n != 1 and have some wiseguy pass in 1 with extra
905 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
906 //if (opcode == OP_NOTEQUAL)
907 // fEqual = !fEqual;
908 popstack(stack);
909 popstack(stack);
910 stack.push_back(fEqual ? vchTrue : vchFalse);
911 if (opcode == OP_EQUALVERIFY)
912 {
913 if (fEqual)
914 popstack(stack);
915 else
917 }
918 }
919 break;
920
921
922 //
923 // Numeric
924 //
925 case OP_1ADD:
926 case OP_1SUB:
927 case OP_NEGATE:
928 case OP_ABS:
929 case OP_NOT:
930 case OP_0NOTEQUAL:
931 {
932 // (in -- out)
933 if (stack.size() < 1)
936 switch (opcode)
937 {
938 case OP_1ADD: bn += bnOne; break;
939 case OP_1SUB: bn -= bnOne; break;
940 case OP_NEGATE: bn = -bn; break;
941 case OP_ABS: if (bn < bnZero) bn = -bn; break;
942 case OP_NOT: bn = (bn == bnZero); break;
943 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
944 default: assert(!"invalid opcode"); break;
945 }
946 popstack(stack);
947 stack.push_back(bn.getvch());
948 }
949 break;
950
951 case OP_ADD:
952 case OP_SUB:
953 case OP_BOOLAND:
954 case OP_BOOLOR:
955 case OP_NUMEQUAL:
957 case OP_NUMNOTEQUAL:
958 case OP_LESSTHAN:
959 case OP_GREATERTHAN:
962 case OP_MIN:
963 case OP_MAX:
964 {
965 // (x1 x2 -- out)
966 if (stack.size() < 2)
970 CScriptNum bn(0);
971 switch (opcode)
972 {
973 case OP_ADD:
974 bn = bn1 + bn2;
975 break;
976
977 case OP_SUB:
978 bn = bn1 - bn2;
979 break;
980
981 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
982 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
983 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
984 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
985 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
986 case OP_LESSTHAN: bn = (bn1 < bn2); break;
987 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
988 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
989 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
990 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
991 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
992 default: assert(!"invalid opcode"); break;
993 }
994 popstack(stack);
995 popstack(stack);
996 stack.push_back(bn.getvch());
997
999 {
1000 if (CastToBool(stacktop(-1)))
1001 popstack(stack);
1002 else
1004 }
1005 }
1006 break;
1007
1008 case OP_WITHIN:
1009 {
1010 // (x min max -- out)
1011 if (stack.size() < 3)
1016 bool fValue = (bn2 <= bn1 && bn1 < bn3);
1017 popstack(stack);
1018 popstack(stack);
1019 popstack(stack);
1020 stack.push_back(fValue ? vchTrue : vchFalse);
1021 }
1022 break;
1023
1024
1025 //
1026 // Crypto
1027 //
1028 case OP_RIPEMD160:
1029 case OP_SHA1:
1030 case OP_SHA256:
1031 case OP_HASH160:
1032 case OP_HASH256:
1033 {
1034 // (in -- hash)
1035 if (stack.size() < 1)
1037 valtype& vch = stacktop(-1);
1038 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
1039 if (opcode == OP_RIPEMD160)
1040 CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1041 else if (opcode == OP_SHA1)
1042 CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1043 else if (opcode == OP_SHA256)
1044 CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1045 else if (opcode == OP_HASH160)
1047 else if (opcode == OP_HASH256)
1049 popstack(stack);
1050 stack.push_back(vchHash);
1051 }
1052 break;
1053
1054 case OP_CODESEPARATOR:
1055 {
1056 // If SCRIPT_VERIFY_CONST_SCRIPTCODE flag is set, use of OP_CODESEPARATOR is rejected in pre-segwit
1057 // script, even in an unexecuted branch (this is checked above the opcode case statement).
1058
1059 // Hash starts after the code separator
1061 execdata.m_codeseparator_pos = opcode_pos;
1062 }
1063 break;
1064
1065 case OP_CHECKSIG:
1066 case OP_CHECKSIGVERIFY:
1067 {
1068 // (sig pubkey -- bool)
1069 if (stack.size() < 2)
1071
1072 valtype& vchSig = stacktop(-2);
1073 valtype& vchPubKey = stacktop(-1);
1074
1075 bool fSuccess = true;
1077 popstack(stack);
1078 popstack(stack);
1079 stack.push_back(fSuccess ? vchTrue : vchFalse);
1081 {
1082 if (fSuccess)
1083 popstack(stack);
1084 else
1086 }
1087 }
1088 break;
1089
1090 case OP_CHECKSIGADD:
1091 {
1092 // OP_CHECKSIGADD is only available in Tapscript
1094
1095 // (sig num pubkey -- num)
1096 if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1097
1098 const valtype& sig = stacktop(-3);
1099 const CScriptNum num(stacktop(-2), fRequireMinimal);
1100 const valtype& pubkey = stacktop(-1);
1101
1102 bool success = true;
1103 if (!EvalChecksig(sig, pubkey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, success)) return false;
1104 popstack(stack);
1105 popstack(stack);
1106 popstack(stack);
1107 stack.push_back((num + (success ? 1 : 0)).getvch());
1108 }
1109 break;
1110
1111 case OP_CHECKMULTISIG:
1113 {
1115
1116 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1117
1118 int i = 1;
1119 if ((int)stack.size() < i)
1121
1128 int ikey = ++i;
1129 // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
1130 // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
1131 int ikey2 = nKeysCount + 2;
1132 i += nKeysCount;
1133 if ((int)stack.size() < i)
1135
1139 int isig = ++i;
1140 i += nSigsCount;
1141 if ((int)stack.size() < i)
1143
1144 // Subset of script starting at the most recent codeseparator
1145 CScript scriptCode(pbegincodehash, pend);
1146
1147 // Drop the signature in pre-segwit scripts but not segwit scripts
1148 for (int k = 0; k < nSigsCount; k++)
1149 {
1152 int found = FindAndDelete(scriptCode, CScript() << vchSig);
1153 if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
1155 }
1156 }
1157
1158 bool fSuccess = true;
1159 while (fSuccess && nSigsCount > 0)
1160 {
1163
1164 // Note how this makes the exact order of pubkey/signature evaluation
1165 // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
1166 // See the script_(in)valid tests for details.
1168 // serror is set
1169 return false;
1170 }
1171
1172 // Check signature
1173 bool fOk = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
1174
1175 if (fOk) {
1176 isig++;
1177 nSigsCount--;
1178 }
1179 ikey++;
1180 nKeysCount--;
1181
1182 // If there are more signatures left than keys left,
1183 // then too many signatures have failed. Exit early,
1184 // without checking any further signatures.
1185 if (nSigsCount > nKeysCount)
1186 fSuccess = false;
1187 }
1188
1189 // Clean up stack of actual arguments
1190 while (i-- > 1) {
1191 // If the operation failed, we require that all signatures must be empty vector
1192 if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
1194 if (ikey2 > 0)
1195 ikey2--;
1196 popstack(stack);
1197 }
1198
1199 // A bug causes CHECKMULTISIG to consume one extra argument
1200 // whose contents were not checked in any way.
1201 //
1202 // Unfortunately this is a potential source of mutability,
1203 // so optionally verify it is exactly equal to zero prior
1204 // to removing it from the stack.
1205 if (stack.size() < 1)
1207 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1209 popstack(stack);
1210
1211 stack.push_back(fSuccess ? vchTrue : vchFalse);
1212
1214 {
1215 if (fSuccess)
1216 popstack(stack);
1217 else
1219 }
1220 }
1221 break;
1222
1223 default:
1225 }
1226
1227 // Size limits
1228 if (stack.size() + altstack.size() > MAX_STACK_SIZE)
1230 }
1231 }
1232 catch (const scriptnum_error&)
1233 {
1235 }
1236 catch (...)
1237 {
1239 }
1240
1241 if (!vfExec.empty())
1243
1244 return set_success(serror);
1245}
1246
1247bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
1248{
1250 return EvalScript(stack, script, flags, checker, sigversion, execdata, serror);
1251}
1252
1253namespace {
1254
1259template <class T>
1260class CTransactionSignatureSerializer
1261{
1262private:
1263 const T& txTo;
1264 const CScript& scriptCode;
1265 const unsigned int nIn;
1266 const bool fAnyoneCanPay;
1267 const bool fHashSingle;
1268 const bool fHashNone;
1269
1270public:
1271 CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1272 txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1273 fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1274 fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1275 fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1276
1278 template<typename S>
1279 void SerializeScriptCode(S &s) const {
1280 CScript::const_iterator it = scriptCode.begin();
1283 unsigned int nCodeSeparators = 0;
1284 while (scriptCode.GetOp(it, opcode)) {
1285 if (opcode == OP_CODESEPARATOR)
1287 }
1288 ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1289 it = itBegin;
1290 while (scriptCode.GetOp(it, opcode)) {
1291 if (opcode == OP_CODESEPARATOR) {
1292 s.write(std::as_bytes(std::span{&itBegin[0], size_t(it - itBegin - 1)}));
1293 itBegin = it;
1294 }
1295 }
1296 if (itBegin != scriptCode.end())
1297 s.write(std::as_bytes(std::span{&itBegin[0], size_t(it - itBegin)}));
1298 }
1299
1301 template<typename S>
1302 void SerializeInput(S &s, unsigned int nInput) const {
1303 // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1304 if (fAnyoneCanPay)
1305 nInput = nIn;
1306 // Serialize the prevout
1307 ::Serialize(s, txTo.vin[nInput].prevout);
1308 // Serialize the script
1309 if (nInput != nIn)
1310 // Blank out other inputs' signatures
1311 ::Serialize(s, CScript());
1312 else
1314 // Serialize the nSequence
1315 if (nInput != nIn && (fHashSingle || fHashNone))
1316 // let the others update at will
1317 ::Serialize(s, int32_t{0});
1318 else
1319 ::Serialize(s, txTo.vin[nInput].nSequence);
1320 }
1321
1323 template<typename S>
1324 void SerializeOutput(S &s, unsigned int nOutput) const {
1325 if (fHashSingle && nOutput != nIn)
1326 // Do not lock-in the txout payee at other indices as txin
1327 ::Serialize(s, CTxOut());
1328 else
1329 ::Serialize(s, txTo.vout[nOutput]);
1330 }
1331
1333 template<typename S>
1334 void Serialize(S &s) const {
1335 // Serialize version
1336 ::Serialize(s, txTo.version);
1337 // Serialize vin
1338 unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1340 for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1342 // Serialize vout
1343 unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1345 for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1347 // Serialize nLockTime
1348 ::Serialize(s, txTo.nLockTime);
1349 }
1350};
1351
1353template <class T>
1354uint256 GetPrevoutsSHA256(const T& txTo)
1355{
1356 HashWriter ss{};
1357 for (const auto& txin : txTo.vin) {
1358 ss << txin.prevout;
1359 }
1360 return ss.GetSHA256();
1361}
1362
1364template <class T>
1365uint256 GetSequencesSHA256(const T& txTo)
1366{
1367 HashWriter ss{};
1368 for (const auto& txin : txTo.vin) {
1369 ss << txin.nSequence;
1370 }
1371 return ss.GetSHA256();
1372}
1373
1375template <class T>
1376uint256 GetOutputsSHA256(const T& txTo)
1377{
1378 HashWriter ss{};
1379 for (const auto& txout : txTo.vout) {
1380 ss << txout;
1381 }
1382 return ss.GetSHA256();
1383}
1384
1386uint256 GetSpentAmountsSHA256(const std::vector<CTxOut>& outputs_spent)
1387{
1388 HashWriter ss{};
1389 for (const auto& txout : outputs_spent) {
1390 ss << txout.nValue;
1391 }
1392 return ss.GetSHA256();
1393}
1394
1396uint256 GetSpentScriptsSHA256(const std::vector<CTxOut>& outputs_spent)
1397{
1398 HashWriter ss{};
1399 for (const auto& txout : outputs_spent) {
1400 ss << txout.scriptPubKey;
1401 }
1402 return ss.GetSHA256();
1403}
1404
1405
1406} // namespace
1407
1408template <class T>
1409void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent_outputs, bool force)
1410{
1412
1413 m_spent_outputs = std::move(spent_outputs);
1414 if (!m_spent_outputs.empty()) {
1415 assert(m_spent_outputs.size() == txTo.vin.size());
1416 m_spent_outputs_ready = true;
1417 }
1418
1419 // Determine which precomputation-impacting features this transaction uses.
1422 for (size_t inpos = 0; inpos < txTo.vin.size() && !(uses_bip143_segwit && uses_bip341_taproot); ++inpos) {
1423 if (!txTo.vin[inpos].scriptWitness.IsNull()) {
1424 if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.size() == 2 + WITNESS_V1_TAPROOT_SIZE &&
1425 m_spent_outputs[inpos].scriptPubKey[0] == OP_1) {
1426 // Treat every witness-bearing spend with 34-byte scriptPubKey that starts with OP_1 as a Taproot
1427 // spend. This only works if spent_outputs was provided as well, but if it wasn't, actual validation
1428 // will fail anyway. Note that this branch may trigger for scriptPubKeys that aren't actually segwit
1429 // but in that case validation will fail as SCRIPT_ERR_WITNESS_UNEXPECTED anyway.
1430 uses_bip341_taproot = true;
1431 } else {
1432 // Treat every spend that's not known to native witness v1 as a Witness v0 spend. This branch may
1433 // also be taken for unknown witness versions, but it is harmless, and being precise would require
1434 // P2SH evaluation to find the redeemScript.
1435 uses_bip143_segwit = true;
1436 }
1437 }
1438 if (uses_bip341_taproot && uses_bip143_segwit) break; // No need to scan further if we already need all.
1439 }
1440
1442 // Computations shared between both sighash schemes.
1446 }
1447 if (uses_bip143_segwit) {
1451 m_bip143_segwit_ready = true;
1452 }
1457 }
1458}
1459
1460template <class T>
1462{
1463 Init(txTo, {});
1464}
1465
1466// explicit instantiation
1467template void PrecomputedTransactionData::Init(const CTransaction& txTo, std::vector<CTxOut>&& spent_outputs, bool force);
1468template void PrecomputedTransactionData::Init(const CMutableTransaction& txTo, std::vector<CTxOut>&& spent_outputs, bool force);
1471
1475
1477{
1478 switch (mdb) {
1480 assert(!"Missing data");
1481 break;
1483 return false;
1484 }
1485 assert(!"Unknown MissingDataBehavior value");
1486}
1487
1488template<typename T>
1490{
1492 switch (sigversion) {
1494 ext_flag = 0;
1495 // key_version is not used and left uninitialized.
1496 break;
1498 ext_flag = 1;
1499 // key_version must be 0 for now, representing the current version of
1500 // 32-byte public keys in the tapscript signature opcode execution.
1501 // An upgradable public key version (with a size not 32-byte) may
1502 // request a different key_version with a new sigversion.
1503 key_version = 0;
1504 break;
1505 default:
1506 assert(false);
1507 }
1508 assert(in_pos < tx_to.vin.size());
1509 if (!(cache.m_bip341_taproot_ready && cache.m_spent_outputs_ready)) {
1510 return HandleMissingData(mdb);
1511 }
1512
1514
1515 // Epoch
1516 static constexpr uint8_t EPOCH = 0;
1517 ss << EPOCH;
1518
1519 // Hash type
1520 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
1522 if (!(hash_type <= 0x03 || (hash_type >= 0x81 && hash_type <= 0x83))) return false;
1523 ss << hash_type;
1524
1525 // Transaction level data
1526 ss << tx_to.version;
1527 ss << tx_to.nLockTime;
1529 ss << cache.m_prevouts_single_hash;
1532 ss << cache.m_sequences_single_hash;
1533 }
1534 if (output_type == SIGHASH_ALL) {
1535 ss << cache.m_outputs_single_hash;
1536 }
1537
1538 // Data about the input/prevout being spent
1539 assert(execdata.m_annex_init);
1540 const bool have_annex = execdata.m_annex_present;
1541 const uint8_t spend_type = (ext_flag << 1) + (have_annex ? 1 : 0); // The low bit indicates whether an annex is present.
1542 ss << spend_type;
1544 ss << tx_to.vin[in_pos].prevout;
1545 ss << cache.m_spent_outputs[in_pos];
1546 ss << tx_to.vin[in_pos].nSequence;
1547 } else {
1548 ss << in_pos;
1549 }
1550 if (have_annex) {
1551 ss << execdata.m_annex_hash;
1552 }
1553
1554 // Data about the output (if only one).
1555 if (output_type == SIGHASH_SINGLE) {
1556 if (in_pos >= tx_to.vout.size()) return false;
1557 if (!execdata.m_output_hash) {
1560 execdata.m_output_hash = sha_single_output.GetSHA256();
1561 }
1562 ss << execdata.m_output_hash.value();
1563 }
1564
1565 // Additional data for BIP 342 signatures
1567 assert(execdata.m_tapleaf_hash_init);
1568 ss << execdata.m_tapleaf_hash;
1569 ss << key_version;
1570 assert(execdata.m_codeseparator_pos_init);
1571 ss << execdata.m_codeseparator_pos;
1572 }
1573
1574 hash_out = ss.GetSHA256();
1575 return true;
1576}
1577
1579{
1580 // Note that we do not distinguish between BASE and WITNESS_V0 to determine the cache index,
1581 // because no input can simultaneously use both.
1582 return 3 * !!(hash_type & SIGHASH_ANYONECANPAY) +
1583 2 * ((hash_type & 0x1f) == SIGHASH_SINGLE) +
1584 1 * ((hash_type & 0x1f) == SIGHASH_NONE);
1585}
1586
1588{
1589 auto& entry = m_cache_entries[CacheIndex(hash_type)];
1590 if (entry.has_value()) {
1591 if (script_code == entry->first) {
1592 writer = HashWriter(entry->second);
1593 return true;
1594 }
1595 }
1596 return false;
1597}
1598
1600{
1601 auto& entry = m_cache_entries[CacheIndex(hash_type)];
1602 entry.emplace(script_code, writer);
1603}
1604
1605template <class T>
1606uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int32_t nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache, SigHashCache* sighash_cache)
1607{
1608 assert(nIn < txTo.vin.size());
1609
1611 // Check for invalid use of SIGHASH_SINGLE
1612 if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1613 if (nIn >= txTo.vout.size()) {
1614 // nOut out of range
1615 return uint256::ONE;
1616 }
1617 }
1618 }
1619
1620 HashWriter ss{};
1621
1622 // Try to compute using cached SHA256 midstate.
1623 if (sighash_cache && sighash_cache->Load(nHashType, scriptCode, ss)) {
1624 // Add sighash type and hash.
1625 ss << nHashType;
1626 return ss.GetHash();
1627 }
1628
1630 uint256 hashPrevouts;
1631 uint256 hashSequence;
1632 uint256 hashOutputs;
1633 const bool cacheready = cache && cache->m_bip143_segwit_ready;
1634
1636 hashPrevouts = cacheready ? cache->hashPrevouts : SHA256Uint256(GetPrevoutsSHA256(txTo));
1637 }
1638
1639 if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1640 hashSequence = cacheready ? cache->hashSequence : SHA256Uint256(GetSequencesSHA256(txTo));
1641 }
1642
1643 if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1644 hashOutputs = cacheready ? cache->hashOutputs : SHA256Uint256(GetOutputsSHA256(txTo));
1645 } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
1647 inner_ss << txTo.vout[nIn];
1648 hashOutputs = inner_ss.GetHash();
1649 }
1650
1651 // Version
1652 ss << txTo.version;
1653 // Input prevouts/nSequence (none/all, depending on flags)
1654 ss << hashPrevouts;
1655 ss << hashSequence;
1656 // The input being signed (replacing the scriptSig with scriptCode + amount)
1657 // The prevout may already be contained in hashPrevout, and the nSequence
1658 // may already be contain in hashSequence.
1659 ss << txTo.vin[nIn].prevout;
1660 ss << scriptCode;
1661 ss << amount;
1662 ss << txTo.vin[nIn].nSequence;
1663 // Outputs (none/one/all, depending on flags)
1664 ss << hashOutputs;
1665 // Locktime
1666 ss << txTo.nLockTime;
1667 } else {
1668 // Wrapper to serialize only the necessary parts of the transaction being signed
1669 CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
1670
1671 // Serialize
1672 ss << txTmp;
1673 }
1674
1675 // If a cache object was provided, store the midstate there.
1676 if (sighash_cache != nullptr) {
1677 sighash_cache->Store(nHashType, scriptCode, ss);
1678 }
1679
1680 // Add sighash type and hash.
1681 ss << nHashType;
1682 return ss.GetHash();
1683}
1684
1685template <class T>
1686bool GenericTransactionSignatureChecker<T>::VerifyECDSASignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1687{
1688 return pubkey.Verify(sighash, vchSig);
1689}
1690
1691template <class T>
1692bool GenericTransactionSignatureChecker<T>::VerifySchnorrSignature(std::span<const unsigned char> sig, const XOnlyPubKey& pubkey, const uint256& sighash) const
1693{
1694 return pubkey.VerifySchnorr(sighash, sig);
1695}
1696
1697template <class T>
1698bool GenericTransactionSignatureChecker<T>::CheckECDSASignature(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1699{
1700 CPubKey pubkey(vchPubKey);
1701 if (!pubkey.IsValid())
1702 return false;
1703
1704 // Hash type is one byte tacked on to the end of the signature
1705 std::vector<unsigned char> vchSig(vchSigIn);
1706 if (vchSig.empty())
1707 return false;
1708 int nHashType = vchSig.back();
1709 vchSig.pop_back();
1710
1711 // Witness sighashes need the amount.
1712 if (sigversion == SigVersion::WITNESS_V0 && amount < 0) return HandleMissingData(m_mdb);
1713
1714 uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata, &m_sighash_cache);
1715
1716 if (!VerifyECDSASignature(vchSig, pubkey, sighash))
1717 return false;
1718
1719 return true;
1720}
1721
1722template <class T>
1724{
1726 // Schnorr signatures have 32-byte public keys. The caller is responsible for enforcing this.
1727 assert(pubkey_in.size() == 32);
1728 // Note that in Tapscript evaluation, empty signatures are treated specially (invalid signature that does not
1729 // abort script execution). This is implemented in EvalChecksigTapscript, which won't invoke
1730 // CheckSchnorrSignature in that case. In other contexts, they are invalid like every other signature with
1731 // size different from 64 or 65.
1732 if (sig.size() != 64 && sig.size() != 65) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_SIZE);
1733
1734 XOnlyPubKey pubkey{pubkey_in};
1735
1737 if (sig.size() == 65) {
1738 hashtype = SpanPopBack(sig);
1740 }
1742 if (!this->txdata) return HandleMissingData(m_mdb);
1743 if (!SignatureHashSchnorr(sighash, execdata, *txTo, nIn, hashtype, sigversion, *this->txdata, m_mdb)) {
1745 }
1746 if (!VerifySchnorrSignature(sig, pubkey, sighash)) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG);
1747 return true;
1748}
1749
1750template <class T>
1752{
1753 // There are two kinds of nLockTime: lock-by-blockheight
1754 // and lock-by-blocktime, distinguished by whether
1755 // nLockTime < LOCKTIME_THRESHOLD.
1756 //
1757 // We want to compare apples to apples, so fail the script
1758 // unless the type of nLockTime being tested is the same as
1759 // the nLockTime in the transaction.
1760 if (!(
1761 (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
1762 (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1763 ))
1764 return false;
1765
1766 // Now that we know we're comparing apples-to-apples, the
1767 // comparison is a simple numeric one.
1768 if (nLockTime > (int64_t)txTo->nLockTime)
1769 return false;
1770
1771 // Finally the nLockTime feature can be disabled in IsFinalTx()
1772 // and thus CHECKLOCKTIMEVERIFY bypassed if every txin has
1773 // been finalized by setting nSequence to maxint. The
1774 // transaction would be allowed into the blockchain, making
1775 // the opcode ineffective.
1776 //
1777 // Testing if this vin is not final is sufficient to
1778 // prevent this condition. Alternatively we could test all
1779 // inputs, but testing just this input minimizes the data
1780 // required to prove correct CHECKLOCKTIMEVERIFY execution.
1781 if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1782 return false;
1783
1784 return true;
1785}
1786
1787template <class T>
1789{
1790 // Relative lock times are supported by comparing the passed
1791 // in operand to the sequence number of the input.
1792 const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1793
1794 // Fail if the transaction's version number is not set high
1795 // enough to trigger BIP 68 rules.
1796 if (txTo->version < 2)
1797 return false;
1798
1799 // Sequence numbers with their most significant bit set are not
1800 // consensus constrained. Testing that the transaction's sequence
1801 // number do not have this bit set prevents using this property
1802 // to get around a CHECKSEQUENCEVERIFY check.
1804 return false;
1805
1806 // Mask off any bits that do not have consensus-enforced meaning
1807 // before doing the integer comparisons
1810 const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1811
1812 // There are two kinds of nSequence: lock-by-blockheight
1813 // and lock-by-blocktime, distinguished by whether
1814 // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1815 //
1816 // We want to compare apples to apples, so fail the script
1817 // unless the type of nSequenceMasked being tested is the same as
1818 // the nSequenceMasked in the transaction.
1819 if (!(
1822 )) {
1823 return false;
1824 }
1825
1826 // Now that we know we're comparing apples-to-apples, the
1827 // comparison is a simple numeric one.
1829 return false;
1830
1831 return true;
1832}
1833
1834// explicit instantiation
1837
1839{
1840 std::vector<valtype> stack{stack_span.begin(), stack_span.end()};
1841
1843 // OP_SUCCESSx processing overrides everything, including stack element size limits
1845 while (pc < exec_script.end()) {
1847 if (!exec_script.GetOp(pc, opcode)) {
1848 // Note how this condition would not be reached if an unknown OP_SUCCESSx was found
1850 }
1851 // New opcodes will be listed here. May use a different sigversion to modify existing opcodes.
1852 if (IsOpSuccess(opcode)) {
1855 }
1856 return set_success(serror);
1857 }
1858 }
1859
1860 // Tapscript enforces initial stack size limits (altstack is empty here)
1861 if (stack.size() > MAX_STACK_SIZE) return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1862 }
1863
1864 // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
1865 for (const valtype& elem : stack) {
1867 }
1868
1869 // Run the script interpreter.
1870 if (!EvalScript(stack, exec_script, flags, checker, sigversion, execdata, serror)) return false;
1871
1872 // Scripts inside witness implicitly require cleanstack behaviour
1873 if (stack.size() != 1) return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1874 if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1875 return true;
1876}
1877
1878uint256 ComputeTapleafHash(uint8_t leaf_version, std::span<const unsigned char> script)
1879{
1880 return (HashWriter{HASHER_TAPLEAF} << leaf_version << CompactSizeWriter(script.size()) << script).GetSHA256();
1881}
1882
1883uint256 ComputeTapbranchHash(std::span<const unsigned char> a, std::span<const unsigned char> b)
1884{
1886 if (std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end())) {
1887 ss_branch << a << b;
1888 } else {
1889 ss_branch << b << a;
1890 }
1891 return ss_branch.GetSHA256();
1892}
1893
1894uint256 ComputeTaprootMerkleRoot(std::span<const unsigned char> control, const uint256& tapleaf_hash)
1895{
1899
1902 for (int i = 0; i < path_len; ++i) {
1905 }
1906 return k;
1907}
1908
1909static bool VerifyTaprootCommitment(const std::vector<unsigned char>& control, const std::vector<unsigned char>& program, const uint256& tapleaf_hash)
1910{
1912 assert(program.size() >= uint256::size());
1914 const XOnlyPubKey p{std::span{control}.subspan(1, TAPROOT_CONTROL_BASE_SIZE - 1)};
1916 const XOnlyPubKey q{program};
1917 // Compute the Merkle root from the leaf and the provided path.
1919 // Verify that the output pubkey matches the tweaked internal pubkey, after correcting for parity.
1920 return q.CheckTapTweak(p, merkle_root, control[0] & 1);
1921}
1922
1923static 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)
1924{
1926 std::span stack{witness.stack};
1928
1929 if (witversion == 0) {
1930 if (program.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
1931 // BIP141 P2WSH: 32-byte witness v0 program (which encodes SHA256(script))
1932 if (stack.size() == 0) {
1934 }
1935 const valtype& script_bytes = SpanPopBack(stack);
1936 exec_script = CScript(script_bytes.begin(), script_bytes.end());
1938 CSHA256().Write(exec_script.data(), exec_script.size()).Finalize(hash_exec_script.begin());
1939 if (memcmp(hash_exec_script.begin(), program.data(), 32)) {
1941 }
1943 } else if (program.size() == WITNESS_V0_KEYHASH_SIZE) {
1944 // BIP141 P2WPKH: 20-byte witness v0 program (which encodes Hash160(pubkey))
1945 if (stack.size() != 2) {
1946 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1947 }
1950 } else {
1952 }
1953 } else if (witversion == 1 && program.size() == WITNESS_V1_TAPROOT_SIZE && !is_p2sh) {
1954 // BIP341 Taproot: 32-byte non-P2SH witness v1 program (which encodes a P2C-tweaked pubkey)
1956 if (stack.size() == 0) return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1957 if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
1958 // Drop annex (this is non-standard; see IsWitnessStandard)
1959 const valtype& annex = SpanPopBack(stack);
1960 execdata.m_annex_hash = (HashWriter{} << annex).GetSHA256();
1961 execdata.m_annex_present = true;
1962 } else {
1963 execdata.m_annex_present = false;
1964 }
1965 execdata.m_annex_init = true;
1966 if (stack.size() == 1) {
1967 // Key path spending (stack size is 1 after removing optional annex)
1968 if (!checker.CheckSchnorrSignature(stack.front(), program, SigVersion::TAPROOT, execdata, serror)) {
1969 return false; // serror is set
1970 }
1971 return set_success(serror);
1972 } else {
1973 // Script path spending (stack size is >1 after removing optional annex)
1974 const valtype& control = SpanPopBack(stack);
1975 const valtype& script = SpanPopBack(stack);
1978 }
1980 if (!VerifyTaprootCommitment(control, program, execdata.m_tapleaf_hash)) {
1982 }
1983 execdata.m_tapleaf_hash_init = true;
1985 // Tapscript (leaf version 0xc0)
1986 exec_script = CScript(script.begin(), script.end());
1987 execdata.m_validation_weight_left = ::GetSerializeSize(witness.stack) + VALIDATION_WEIGHT_OFFSET;
1988 execdata.m_validation_weight_left_init = true;
1990 }
1993 }
1994 return set_success(serror);
1995 }
1997 return true;
1998 } else {
2001 }
2002 // Other version/size/p2sh combinations return true for future softfork compatibility
2003 return true;
2004 }
2005 // 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.
2006}
2007
2008bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, script_verify_flags flags, const BaseSignatureChecker& checker, ScriptError* serror)
2009{
2010 static const CScriptWitness emptyWitness;
2011 if (witness == nullptr) {
2012 witness = &emptyWitness;
2013 }
2014 bool hadWitness = false;
2015
2017
2018 if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
2020 }
2021
2022 // scriptSig and scriptPubKey must be evaluated sequentially on the same stack
2023 // rather than being simply concatenated (see CVE-2010-5141)
2024 std::vector<std::vector<unsigned char> > stack, stackCopy;
2025 if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
2026 // serror is set
2027 return false;
2029 stackCopy = stack;
2030 if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
2031 // serror is set
2032 return false;
2033 if (stack.empty())
2035 if (CastToBool(stack.back()) == false)
2037
2038 // Bare witness programs
2039 int witnessversion;
2040 std::vector<unsigned char> witnessprogram;
2042 if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2043 hadWitness = true;
2044 if (scriptSig.size() != 0) {
2045 // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
2047 }
2048 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /*is_p2sh=*/false)) {
2049 return false;
2050 }
2051 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
2052 // for witness programs.
2053 stack.resize(1);
2054 }
2055 }
2056
2057 // Additional validation for spend-to-script-hash transactions:
2058 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
2059 {
2060 // scriptSig must be literals-only or validation fails
2061 if (!scriptSig.IsPushOnly())
2063
2064 // Restore stack.
2065 swap(stack, stackCopy);
2066
2067 // stack cannot be empty here, because if it was the
2068 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
2069 // an empty stack and the EvalScript above would return false.
2070 assert(!stack.empty());
2071
2072 const valtype& pubKeySerialized = stack.back();
2074 popstack(stack);
2075
2076 if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
2077 // serror is set
2078 return false;
2079 if (stack.empty())
2081 if (!CastToBool(stack.back()))
2083
2084 // P2SH witness program
2086 if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
2087 hadWitness = true;
2088 if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
2089 // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
2090 // reintroduce malleability.
2092 }
2093 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /*is_p2sh=*/true)) {
2094 return false;
2095 }
2096 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
2097 // for witness programs.
2098 stack.resize(1);
2099 }
2100 }
2101 }
2102
2103 // The CLEANSTACK check is only performed after potential P2SH evaluation,
2104 // as the non-P2SH evaluation of a P2SH script will obviously not result in
2105 // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
2106 if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
2107 // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
2108 // would be possible, which is not a softfork (and P2SH should be one).
2111 if (stack.size() != 1) {
2113 }
2114 }
2115
2117 // We can't check for correct unexpected witness data if P2SH was off, so require
2118 // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
2119 // possible, which is not a softfork.
2121 if (!hadWitness && !witness->IsNull()) {
2123 }
2124 }
2125
2126 return set_success(serror);
2127}
2128
2129size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness)
2130{
2131 if (witversion == 0) {
2132 if (witprogram.size() == WITNESS_V0_KEYHASH_SIZE)
2133 return 1;
2134
2135 if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.stack.size() > 0) {
2136 CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
2137 return subscript.GetSigOpCount(true);
2138 }
2139 }
2140
2141 // Future flags may be implemented here.
2142 return 0;
2143}
2144
2145size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness& witness, script_verify_flags flags)
2146{
2147 if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
2148 return 0;
2149 }
2151
2152 int witnessversion;
2153 std::vector<unsigned char> witnessprogram;
2154 if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2156 }
2157
2158 if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
2159 CScript::const_iterator pc = scriptSig.begin();
2160 std::vector<unsigned char> data;
2161 while (pc < scriptSig.end()) {
2163 scriptSig.GetOp(pc, opcode, data);
2164 }
2165 CScript subscript(data.begin(), data.end());
2166 if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
2168 }
2169 }
2170
2171 return 0;
2172}
2173
2174const std::map<std::string, script_verify_flag_name>& ScriptFlagNamesToEnum()
2175{
2176#define FLAG_NAME(flag) {std::string(#flag), SCRIPT_VERIFY_##flag}
2177 static const std::map<std::string, script_verify_flag_name> g_names_to_enum{
2178 FLAG_NAME(P2SH),
2180 FLAG_NAME(DERSIG),
2184 FLAG_NAME(NULLDUMMY),
2189 FLAG_NAME(CHECKLOCKTIMEVERIFY),
2190 FLAG_NAME(CHECKSEQUENCEVERIFY),
2191 FLAG_NAME(WITNESS),
2199 };
2200#undef FLAG_NAME
2201 return g_names_to_enum;
2202}
2203
2205{
2206 std::vector<std::string> res;
2207 if (flags == SCRIPT_VERIFY_NONE) {
2208 return res;
2209 }
2210 script_verify_flags leftover = flags;
2211 for (const auto& [name, flag] : ScriptFlagNamesToEnum()) {
2212 if ((flags & flag) != 0) {
2213 res.push_back(name);
2214 leftover &= ~flag;
2215 }
2216 }
2217 if (leftover != 0) {
2218 res.push_back(strprintf("0x%08x", leftover.as_int()));
2219 }
2220 return res;
2221}
std::vector< unsigned char > valtype
int64_t CAmount
Amount in satoshis (Can be negative)
Definition amount.h:12
int ret
int flags
virtual bool CheckLockTime(const CScriptNum &nLockTime) const
virtual bool CheckSchnorrSignature(std::span< const unsigned char > sig, std::span< const unsigned char > pubkey, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror=nullptr) const
virtual bool CheckSequence(const CScriptNum &nSequence) const
virtual bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const
A hasher class for Bitcoin's 160-bit hash (SHA-256 + RIPEMD-160).
Definition hash.h:57
CHash160 & Write(std::span< const unsigned char > input)
Definition hash.h:70
void Finalize(std::span< unsigned char > output)
Definition hash.h:63
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition hash.h:32
void Finalize(std::span< unsigned char > output)
Definition hash.h:38
CHash256 & Write(std::span< const unsigned char > input)
Definition hash.h:45
An encapsulated public key.
Definition pubkey.h:43
static constexpr unsigned int COMPRESSED_SIZE
Definition pubkey.h:49
static bool CheckLowS(const std::vector< unsigned char > &vchSig)
Check whether a signature is normalized (lower-S).
Definition pubkey.cpp:393
bool IsValid() const
Definition pubkey.h:194
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:48
A hasher class for RIPEMD-160.
Definition ripemd160.h:13
CRIPEMD160 & Write(const unsigned char *data, size_t len)
void Finalize(unsigned char hash[OUTPUT_SIZE])
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
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
int getint() const
Definition script.h:326
The basic transaction that is broadcasted on the network and contained in blocks.
static constexpr uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition transaction.h:77
static constexpr 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...
static constexpr uint32_t SEQUENCE_LOCKTIME_MASK
If CTxIn::nSequence encodes a relative lock-time, this mask is applied to extract that lock-time from...
static constexpr uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
If this flag is set, CTxIn::nSequence is NOT interpreted as a relative lock-time.
Definition transaction.h:94
An output of a transaction.
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:109
uint256 GetSHA256()
Compute the SHA256 hash of all data written to this object.
Definition hash.h:134
Definition init.h:13
Data structure to cache SHA256 midstates for the ECDSA sighash calculations (bare,...
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
bool empty() const
Definition prevector.h:251
size_type size() const
Definition prevector.h:247
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
256-bit opaque blob.
Definition uint256.h:196
static const uint256 ONE
Definition uint256.h:205
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
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
#define T(expected, seed, data)
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)
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)
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)
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
static bool IsCompressedOrUncompressedPubKey(const valtype &vchPubKey)
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...
const HashWriter HASHER_TAPLEAF
Hasher with tag "TapLeaf" pre-fed to it.
#define altstacktop(i)
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.
constexpr size_t WITNESS_V0_KEYHASH_SIZE
SigVersion
@ 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.
constexpr uint8_t TAPROOT_LEAF_MASK
constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
constexpr size_t WITNESS_V0_SCRIPTHASH_SIZE
Signature hash sizes.
@ 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
constexpr size_t TAPROOT_CONTROL_NODE_SIZE
constexpr size_t WITNESS_V1_TAPROOT_SIZE
MissingDataBehavior
Enum to specify what *TransactionSignatureChecker's behavior should be when dealing with missing tran...
@ ASSERT_FAIL
Abort execution through assertion failure (for consensus code)
@ FAIL
Just act as if the signature was invalid.
constexpr size_t TAPROOT_CONTROL_MAX_SIZE
@ SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION
@ SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM
@ SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_PUBKEYTYPE
constexpr script_verify_flags SCRIPT_VERIFY_NONE
Script verification flags.
Definition interpreter.h:48
constexpr size_t TAPROOT_CONTROL_BASE_SIZE
#define S(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)
const char * name
Definition rest.cpp:71
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
constexpr int64_t VALIDATION_WEIGHT_PER_SIGOP_PASSED
Definition script.h:62
constexpr 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
constexpr unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition script.h:29
constexpr int MAX_PUBKEYS_PER_MULTISIG
Definition script.h:35
constexpr int MAX_STACK_SIZE
Definition script.h:44
constexpr int64_t VALIDATION_WEIGHT_OFFSET
Definition script.h:65
constexpr unsigned int LOCKTIME_THRESHOLD
Definition script.h:48
constexpr int MAX_OPS_PER_SCRIPT
Definition script.h:32
constexpr unsigned int ANNEX_TAG
Definition script.h:59
enum ScriptError_t ScriptError
@ SCRIPT_ERR_OP_CODESEPARATOR
@ SCRIPT_ERR_SIG_PUSHONLY
@ SCRIPT_ERR_OP_COUNT
@ SCRIPT_ERR_DISCOURAGE_UPGRADABLE_PUBKEYTYPE
@ SCRIPT_ERR_EVAL_FALSE
@ SCRIPT_ERR_NUMEQUALVERIFY
@ SCRIPT_ERR_VERIFY
@ SCRIPT_ERR_TAPSCRIPT_CHECKMULTISIG
@ SCRIPT_ERR_DISABLED_OPCODE
@ SCRIPT_ERR_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION
@ SCRIPT_ERR_INVALID_ALTSTACK_OPERATION
@ SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM
@ SCRIPT_ERR_TAPSCRIPT_EMPTY_PUBKEY
@ SCRIPT_ERR_SCRIPT_SIZE
@ SCRIPT_ERR_TAPSCRIPT_MINIMALIF
@ SCRIPT_ERR_UNKNOWN_ERROR
@ SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH
@ SCRIPT_ERR_SIG_HASHTYPE
@ SCRIPT_ERR_MINIMALDATA
@ SCRIPT_ERR_SCRIPTNUM
@ SCRIPT_ERR_CHECKSIGVERIFY
@ SCRIPT_ERR_STACK_SIZE
@ SCRIPT_ERR_WITNESS_MALLEATED_P2SH
@ SCRIPT_ERR_SCHNORR_SIG_SIZE
@ SCRIPT_ERR_WITNESS_MALLEATED
@ SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS
@ SCRIPT_ERR_EQUALVERIFY
@ SCRIPT_ERR_TAPSCRIPT_VALIDATION_WEIGHT
@ SCRIPT_ERR_INVALID_STACK_OPERATION
@ SCRIPT_ERR_DISCOURAGE_OP_SUCCESS
@ SCRIPT_ERR_SIG_COUNT
@ SCRIPT_ERR_SIG_HIGH_S
@ SCRIPT_ERR_SIG_DER
@ SCRIPT_ERR_WITNESS_UNEXPECTED
@ SCRIPT_ERR_NEGATIVE_LOCKTIME
@ SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH
@ SCRIPT_ERR_OP_RETURN
@ SCRIPT_ERR_PUSH_SIZE
@ SCRIPT_ERR_SIG_NULLFAIL
@ SCRIPT_ERR_OK
@ SCRIPT_ERR_SIG_NULLDUMMY
@ SCRIPT_ERR_PUBKEYTYPE
@ SCRIPT_ERR_CHECKMULTISIGVERIFY
@ SCRIPT_ERR_TAPROOT_WRONG_CONTROL_SIZE
@ SCRIPT_ERR_SCHNORR_SIG
@ SCRIPT_ERR_UNSATISFIED_LOCKTIME
@ SCRIPT_ERR_WITNESS_PUBKEYTYPE
@ SCRIPT_ERR_SIG_FINDANDDELETE
@ SCRIPT_ERR_BAD_OPCODE
@ SCRIPT_ERR_PUBKEY_COUNT
@ SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY
@ SCRIPT_ERR_SCHNORR_SIG_HASHTYPE
@ SCRIPT_ERR_CLEANSTACK
@ SCRIPT_ERR_UNBALANCED_CONDITIONAL
@ SCRIPT_ERR_MINIMALIF
void Serialize(Stream &, V)=delete
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition serialize.h:1151
uint64_t GetSerializeSize(const T &t)
Definition serialize.h:1157
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.
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.
PrecomputedTransactionData()=default
bool m_bip143_segwit_ready
Whether the 3 fields above are initialized.
bool m_spent_outputs_ready
Whether m_spent_outputs is initialized.
std::vector< CTxOut > m_spent_outputs
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
DataStream ss
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
assert(!tx.IsCoinBase())