Bitcoin ABC 0.26.3
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-2016 The Bitcoin Core developers
3// Copyright (c) 2017-2020 The Bitcoin developers
4// Distributed under the MIT software license, see the accompanying
5// file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
8
9#include <crypto/ripemd160.h>
10#include <crypto/sha1.h>
11#include <crypto/sha256.h>
12#include <pubkey.h>
13#include <script/bitfield.h>
14#include <script/script.h>
15#include <script/sigencoding.h>
16#include <uint256.h>
17#include <util/bitmanip.h>
18
19bool CastToBool(const valtype &vch) {
20 for (size_t i = 0; i < vch.size(); i++) {
21 if (vch[i] != 0) {
22 // Can be negative zero
23 if (i == vch.size() - 1 && vch[i] == 0x80) {
24 return false;
25 }
26 return true;
27 }
28 }
29 return false;
30}
31
36#define stacktop(i) (stack.at(stack.size() + (i)))
37#define altstacktop(i) (altstack.at(altstack.size() + (i)))
38static inline void popstack(std::vector<valtype> &stack) {
39 if (stack.empty()) {
40 throw std::runtime_error("popstack(): stack empty");
41 }
42 stack.pop_back();
43}
44
45int FindAndDelete(CScript &script, const CScript &b) {
46 int nFound = 0;
47 if (b.empty()) {
48 return nFound;
49 }
50
51 CScript result;
52 CScript::const_iterator pc = script.begin(), pc2 = script.begin(),
53 end = script.end();
54 opcodetype opcode;
55 do {
56 result.insert(result.end(), pc2, pc);
57 while (static_cast<size_t>(end - pc) >= b.size() &&
58 std::equal(b.begin(), b.end(), pc)) {
59 pc = pc + b.size();
60 ++nFound;
61 }
62 pc2 = pc;
63 } while (script.GetOp(pc, opcode));
64
65 if (nFound > 0) {
66 result.insert(result.end(), pc2, end);
67 script = std::move(result);
68 }
69
70 return nFound;
71}
72
73static void CleanupScriptCode(CScript &scriptCode,
74 const std::vector<uint8_t> &vchSig,
76 // Drop the signature in scripts when SIGHASH_FORKID is not used.
77 SigHashType sigHashType = GetHashType(vchSig);
78 if (!(flags & SCRIPT_ENABLE_SIGHASH_FORKID) || !sigHashType.hasForkId()) {
79 FindAndDelete(scriptCode, CScript() << vchSig);
80 }
81}
82
84 switch (opcode) {
85 case OP_INVERT:
86 case OP_2MUL:
87 case OP_2DIV:
88 case OP_MUL:
89 case OP_LSHIFT:
90 case OP_RSHIFT:
91 // Disabled opcodes.
92 return true;
93
94 default:
95 break;
96 }
97
98 return false;
99}
100
108static bool EvalChecksig(const valtype &vchSig, const valtype &vchPubKey,
109 CScript::const_iterator pbegincodehash,
111 const BaseSignatureChecker &checker,
113 bool &fSuccess) {
115 !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
116 // serror is set
117 return false;
118 }
119
120 if (vchSig.size()) {
121 // Subset of script starting at the most recent
122 // codeseparator
123 CScript scriptCode(pbegincodehash, pend);
124
125 // Remove signature for pre-fork scripts
126 CleanupScriptCode(scriptCode, vchSig, flags);
127
128 fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, flags);
129 metrics.nSigChecks += 1;
130
133 }
134 }
135 return true;
136}
137
142 : stack(stackIn), script(scriptIn), checker(checkerIn), metrics(metricsIn) {
143 this->pc = scriptIn.begin();
144 this->pend = scriptIn.end();
145 this->pbegincodehash = scriptIn.begin();
146 this->flags = flags;
148}
149
151 return pc >= pend;
152}
153
155 if (script.size() > MAX_SCRIPT_SIZE) {
157 }
158 return true;
159}
160
162 if (!GetConditionStack().empty()) {
164 }
165 return true;
166}
167
169 std::vector<uint8_t> &vchRet) const {
172}
173
175 if (!CheckPreConditions()) {
176 // script_error is set
177 return false;
178 }
179
180 try {
181 while (!IsAtEnd()) {
182 if (!RunNextOp()) {
183 // script_error is set
184 return false;
185 }
186 }
187 } catch (...) {
189 }
190
191 if (!CheckPostConditions()) {
192 // script_error is set
193 return false;
194 }
195
196 return set_success(&script_error);
197}
198
200 static const CScriptNum bnZero(0);
201 static const CScriptNum bnOne(1);
202 static const valtype vchFalse(0);
203 static const valtype vchTrue(1, 1);
204
205 opcodetype opcode;
207
210 bool fExec = vfExec.all_true();
211
212 //
213 // Read instruction
214 //
215 if (!script.GetOp(pc, opcode, vchPushValue)) {
217 }
220 }
221
222 // Note how OP_RESERVED does not count towards the opcode limit.
223 if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT) {
225 }
226
227 // Some opcodes are disabled (CVE-2010-5137).
228 if (IsOpcodeDisabled(opcode, flags)) {
230 }
231
232 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
235 }
236 stack.push_back(vchPushValue);
237 } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF)) {
238 switch (opcode) {
239 //
240 // Push value
241 //
242 case OP_1NEGATE:
243 case OP_1:
244 case OP_2:
245 case OP_3:
246 case OP_4:
247 case OP_5:
248 case OP_6:
249 case OP_7:
250 case OP_8:
251 case OP_9:
252 case OP_10:
253 case OP_11:
254 case OP_12:
255 case OP_13:
256 case OP_14:
257 case OP_15:
258 case OP_16: {
259 // ( -- value)
260 CScriptNum bn((int)opcode - (int)(OP_1 - 1));
261 stack.push_back(bn.getvch());
262 // The result of these opcodes should always be the
263 // minimal way to push the data they push, so no need
264 // for a CheckMinimalPush here.
265 } break;
266
267 //
268 // Control
269 //
270 case OP_NOP:
271 break;
272
275 break;
276 }
277
278 if (stack.size() < 1) {
279 return set_error(serror,
281 }
282
283 // Note that elsewhere numeric opcodes are limited to
284 // operands in the range -2**31+1 to 2**31-1, however it
285 // is legal for opcodes to produce results exceeding
286 // that range. This limitation is implemented by
287 // CScriptNum's default 4-byte limit.
288 //
289 // If we kept to that limit we'd have a year 2038
290 // problem, even though the nLockTime field in
291 // transactions themselves is uint32 which only becomes
292 // meaningless after the year 2106.
293 //
294 // Thus as a special case we tell CScriptNum to accept
295 // up to 5-byte bignums, which are good until 2**39-1,
296 // well beyond the 2**32-1 limit of the nLockTime field
297 // itself.
298 const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
299
300 // In the rare event that the argument may be < 0 due to
301 // some arithmetic being done first, you can always use
302 // 0 MAX CHECKLOCKTIMEVERIFY.
303 if (nLockTime < 0) {
305 }
306
307 // Actually compare the specified lock time with the
308 // transaction.
309 if (!checker.CheckLockTime(nLockTime)) {
311 }
312
313 break;
314 }
315
318 break;
319 }
320
321 if (stack.size() < 1) {
322 return set_error(serror,
324 }
325
326 // nSequence, like nLockTime, is a 32-bit unsigned
327 // integer field. See the comment in CHECKLOCKTIMEVERIFY
328 // regarding 5-byte numeric operands.
329 const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
330
331 // In the rare event that the argument may be < 0 due to
332 // some arithmetic being done first, you can always use
333 // 0 MAX CHECKSEQUENCEVERIFY.
334 if (nSequence < 0) {
336 }
337
338 // To provide for future soft-fork extensibility, if the
339 // operand has the disabled lock-time flag set,
340 // CHECKSEQUENCEVERIFY behaves as a NOP.
341 if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0) {
342 break;
343 }
344
345 // Compare the specified sequence number with the input.
346 if (!checker.CheckSequence(nSequence)) {
348 }
349
350 break;
351 }
352
353 case OP_NOP1:
354 case OP_NOP4:
355 case OP_NOP5:
356 case OP_NOP6:
357 case OP_NOP7:
358 case OP_NOP8:
359 case OP_NOP9:
360 case OP_NOP10: {
362 return set_error(serror,
364 }
365 } break;
366
367 case OP_IF:
368 case OP_NOTIF: {
369 // <expression> if [statements] [else [statements]]
370 // endif
371 bool fValue = false;
372 if (fExec) {
373 if (stack.size() < 1) {
374 return set_error(serror,
376 }
377 valtype &vch = stacktop(-1);
379 if (vch.size() > 1) {
381 }
382 if (vch.size() == 1 && vch[0] != 1) {
384 }
385 }
386 fValue = CastToBool(vch);
387 if (opcode == OP_NOTIF) {
388 fValue = !fValue;
389 }
391 }
393 } break;
394
395 case OP_ELSE: {
396 if (vfExec.empty()) {
397 return set_error(serror,
399 }
401 } break;
402
403 case OP_ENDIF: {
404 if (vfExec.empty()) {
405 return set_error(serror,
407 }
409 } break;
410
411 case OP_VERIFY: {
412 // (true -- ) or
413 // (false -- false) and return
414 if (stack.size() < 1) {
415 return set_error(serror,
417 }
418 bool fValue = CastToBool(stacktop(-1));
419 if (fValue) {
421 } else {
423 }
424 } break;
425
426 case OP_RETURN: {
428 } break;
429
430 //
431 // Stack ops
432 //
433 case OP_TOALTSTACK: {
434 if (stack.size() < 1) {
435 return set_error(serror,
437 }
438 altstack.push_back(stacktop(-1));
440 } break;
441
442 case OP_FROMALTSTACK: {
443 if (altstack.size() < 1) {
444 return set_error(serror,
446 }
447 stack.push_back(altstacktop(-1));
449 } break;
450
451 case OP_2DROP: {
452 // (x1 x2 -- )
453 if (stack.size() < 2) {
454 return set_error(serror,
456 }
459 } break;
460
461 case OP_2DUP: {
462 // (x1 x2 -- x1 x2 x1 x2)
463 if (stack.size() < 2) {
464 return set_error(serror,
466 }
467 valtype vch1 = stacktop(-2);
468 valtype vch2 = stacktop(-1);
469 stack.push_back(vch1);
470 stack.push_back(vch2);
471 } break;
472
473 case OP_3DUP: {
474 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
475 if (stack.size() < 3) {
476 return set_error(serror,
478 }
479 valtype vch1 = stacktop(-3);
480 valtype vch2 = stacktop(-2);
481 valtype vch3 = stacktop(-1);
482 stack.push_back(vch1);
483 stack.push_back(vch2);
484 stack.push_back(vch3);
485 } break;
486
487 case OP_2OVER: {
488 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
489 if (stack.size() < 4) {
490 return set_error(serror,
492 }
493 valtype vch1 = stacktop(-4);
494 valtype vch2 = stacktop(-3);
495 stack.push_back(vch1);
496 stack.push_back(vch2);
497 } break;
498
499 case OP_2ROT: {
500 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
501 if (stack.size() < 6) {
502 return set_error(serror,
504 }
505 valtype vch1 = stacktop(-6);
506 valtype vch2 = stacktop(-5);
507 stack.erase(stack.end() - 6, stack.end() - 4);
508 stack.push_back(vch1);
509 stack.push_back(vch2);
510 } break;
511
512 case OP_2SWAP: {
513 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
514 if (stack.size() < 4) {
515 return set_error(serror,
517 }
518 swap(stacktop(-4), stacktop(-2));
519 swap(stacktop(-3), stacktop(-1));
520 } break;
521
522 case OP_IFDUP: {
523 // (x - 0 | x x)
524 if (stack.size() < 1) {
525 return set_error(serror,
527 }
528 valtype vch = stacktop(-1);
529 if (CastToBool(vch)) {
530 stack.push_back(vch);
531 }
532 } break;
533
534 case OP_DEPTH: {
535 // -- stacksize
536 CScriptNum bn(stack.size());
537 stack.push_back(bn.getvch());
538 } break;
539
540 case OP_DROP: {
541 // (x -- )
542 if (stack.size() < 1) {
543 return set_error(serror,
545 }
547 } break;
548
549 case OP_DUP: {
550 // (x -- x x)
551 if (stack.size() < 1) {
552 return set_error(serror,
554 }
555 valtype vch = stacktop(-1);
556 stack.push_back(vch);
557 } break;
558
559 case OP_NIP: {
560 // (x1 x2 -- x2)
561 if (stack.size() < 2) {
562 return set_error(serror,
564 }
565 stack.erase(stack.end() - 2);
566 } break;
567
568 case OP_OVER: {
569 // (x1 x2 -- x1 x2 x1)
570 if (stack.size() < 2) {
571 return set_error(serror,
573 }
574 valtype vch = stacktop(-2);
575 stack.push_back(vch);
576 } break;
577
578 case OP_PICK:
579 case OP_ROLL: {
580 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
581 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
582 if (stack.size() < 2) {
583 return set_error(serror,
585 }
588 if (n < 0 || uint64_t(n) >= uint64_t(stack.size())) {
589 return set_error(serror,
591 }
592 valtype vch = stacktop(-n - 1);
593 if (opcode == OP_ROLL) {
594 stack.erase(stack.end() - n - 1);
595 }
596 stack.push_back(vch);
597 } break;
598
599 case OP_ROT: {
600 // (x1 x2 x3 -- x2 x3 x1)
601 // x2 x1 x3 after first swap
602 // x2 x3 x1 after second swap
603 if (stack.size() < 3) {
604 return set_error(serror,
606 }
607 swap(stacktop(-3), stacktop(-2));
608 swap(stacktop(-2), stacktop(-1));
609 } break;
610
611 case OP_SWAP: {
612 // (x1 x2 -- x2 x1)
613 if (stack.size() < 2) {
614 return set_error(serror,
616 }
617 swap(stacktop(-2), stacktop(-1));
618 } break;
619
620 case OP_TUCK: {
621 // (x1 x2 -- x2 x1 x2)
622 if (stack.size() < 2) {
623 return set_error(serror,
625 }
626 valtype vch = stacktop(-1);
627 stack.insert(stack.end() - 2, vch);
628 } break;
629
630 case OP_SIZE: {
631 // (in -- in size)
632 if (stack.size() < 1) {
633 return set_error(serror,
635 }
636 CScriptNum bn(stacktop(-1).size());
637 stack.push_back(bn.getvch());
638 } break;
639
640 //
641 // Bitwise logic
642 //
643 case OP_AND:
644 case OP_OR:
645 case OP_XOR: {
646 // (x1 x2 - out)
647 if (stack.size() < 2) {
648 return set_error(serror,
650 }
651 valtype &vch1 = stacktop(-2);
652 valtype &vch2 = stacktop(-1);
653
654 // Inputs must be the same size
655 if (vch1.size() != vch2.size()) {
657 }
658
659 // To avoid allocating, we modify vch1 in place.
660 switch (opcode) {
661 case OP_AND:
662 for (size_t i = 0; i < vch1.size(); ++i) {
663 vch1[i] &= vch2[i];
664 }
665 break;
666 case OP_OR:
667 for (size_t i = 0; i < vch1.size(); ++i) {
668 vch1[i] |= vch2[i];
669 }
670 break;
671 case OP_XOR:
672 for (size_t i = 0; i < vch1.size(); ++i) {
673 vch1[i] ^= vch2[i];
674 }
675 break;
676 default:
677 break;
678 }
679
680 // And pop vch2.
682 } break;
683
684 case OP_EQUAL:
685 case OP_EQUALVERIFY:
686 // case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
687 {
688 // (x1 x2 - bool)
689 if (stack.size() < 2) {
690 return set_error(serror,
692 }
693 valtype &vch1 = stacktop(-2);
694 valtype &vch2 = stacktop(-1);
695
696 bool fEqual = (vch1 == vch2);
697 // OP_NOTEQUAL is disabled because it would be too
698 // easy to say something like n != 1 and have some
699 // wiseguy pass in 1 with extra zero bytes after it
700 // (numerically, 0x01 == 0x0001 == 0x000001)
701 // if (opcode == OP_NOTEQUAL)
702 // fEqual = !fEqual;
705 stack.push_back(fEqual ? vchTrue : vchFalse);
706 if (opcode == OP_EQUALVERIFY) {
707 if (fEqual) {
709 } else {
711 }
712 }
713 }
714 break;
715
716 //
717 // Numeric
718 //
719 case OP_1ADD:
720 case OP_1SUB:
721 case OP_NEGATE:
722 case OP_ABS:
723 case OP_NOT:
724 case OP_0NOTEQUAL: {
725 // (in -- out)
726 if (stack.size() < 1) {
727 return set_error(serror,
729 }
731 switch (opcode) {
732 case OP_1ADD:
733 bn += bnOne;
734 break;
735 case OP_1SUB:
736 bn -= bnOne;
737 break;
738 case OP_NEGATE:
739 bn = -bn;
740 break;
741 case OP_ABS:
742 if (bn < bnZero) {
743 bn = -bn;
744 }
745 break;
746 case OP_NOT:
747 bn = (bn == bnZero);
748 break;
749 case OP_0NOTEQUAL:
750 bn = (bn != bnZero);
751 break;
752 default:
753 assert(!"invalid opcode");
754 break;
755 }
757 stack.push_back(bn.getvch());
758 } break;
759
760 case OP_ADD:
761 case OP_SUB:
762 case OP_DIV:
763 case OP_MOD:
764 case OP_BOOLAND:
765 case OP_BOOLOR:
766 case OP_NUMEQUAL:
768 case OP_NUMNOTEQUAL:
769 case OP_LESSTHAN:
770 case OP_GREATERTHAN:
773 case OP_MIN:
774 case OP_MAX: {
775 // (x1 x2 -- out)
776 if (stack.size() < 2) {
777 return set_error(serror,
779 }
782 CScriptNum bn(0);
783 switch (opcode) {
784 case OP_ADD:
785 bn = bn1 + bn2;
786 break;
787
788 case OP_SUB:
789 bn = bn1 - bn2;
790 break;
791
792 case OP_DIV:
793 // denominator must not be 0
794 if (bn2 == 0) {
796 }
797 bn = bn1 / bn2;
798 break;
799
800 case OP_MOD:
801 // divisor must not be 0
802 if (bn2 == 0) {
804 }
805 bn = bn1 % bn2;
806 break;
807
808 case OP_BOOLAND:
809 bn = (bn1 != bnZero && bn2 != bnZero);
810 break;
811 case OP_BOOLOR:
812 bn = (bn1 != bnZero || bn2 != bnZero);
813 break;
814 case OP_NUMEQUAL:
815 bn = (bn1 == bn2);
816 break;
818 bn = (bn1 == bn2);
819 break;
820 case OP_NUMNOTEQUAL:
821 bn = (bn1 != bn2);
822 break;
823 case OP_LESSTHAN:
824 bn = (bn1 < bn2);
825 break;
826 case OP_GREATERTHAN:
827 bn = (bn1 > bn2);
828 break;
830 bn = (bn1 <= bn2);
831 break;
833 bn = (bn1 >= bn2);
834 break;
835 case OP_MIN:
836 bn = (bn1 < bn2 ? bn1 : bn2);
837 break;
838 case OP_MAX:
839 bn = (bn1 > bn2 ? bn1 : bn2);
840 break;
841 default:
842 assert(!"invalid opcode");
843 break;
844 }
847 stack.push_back(bn.getvch());
848
849 if (opcode == OP_NUMEQUALVERIFY) {
850 if (CastToBool(stacktop(-1))) {
852 } else {
854 }
855 }
856 } break;
857
858 case OP_WITHIN: {
859 // (x min max -- out)
860 if (stack.size() < 3) {
861 return set_error(serror,
863 }
867 bool fValue = (bn2 <= bn1 && bn1 < bn3);
871 stack.push_back(fValue ? vchTrue : vchFalse);
872 } break;
873
874 //
875 // Crypto
876 //
877 case OP_RIPEMD160:
878 case OP_SHA1:
879 case OP_SHA256:
880 case OP_HASH160:
881 case OP_HASH256: {
882 // (in -- hash)
883 if (stack.size() < 1) {
884 return set_error(serror,
886 }
887 valtype &vch = stacktop(-1);
888 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 ||
889 opcode == OP_HASH160)
890 ? 20
891 : 32);
892 if (opcode == OP_RIPEMD160) {
893 CRIPEMD160()
894 .Write(vch.data(), vch.size())
895 .Finalize(vchHash.data());
896 } else if (opcode == OP_SHA1) {
897 CSHA1()
898 .Write(vch.data(), vch.size())
899 .Finalize(vchHash.data());
900 } else if (opcode == OP_SHA256) {
901 CSHA256()
902 .Write(vch.data(), vch.size())
903 .Finalize(vchHash.data());
904 } else if (opcode == OP_HASH160) {
906 } else if (opcode == OP_HASH256) {
908 }
910 stack.push_back(vchHash);
911 } break;
912
913 case OP_CODESEPARATOR: {
914 // Hash starts after the code separator
916 } break;
917
918 case OP_CHECKSIG:
919 case OP_CHECKSIGVERIFY: {
920 // (sig pubkey -- bool)
921 if (stack.size() < 2) {
922 return set_error(serror,
924 }
925 valtype &vchSig = stacktop(-2);
926 valtype &vchPubKey = stacktop(-1);
927
928 bool fSuccess = false;
929 if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend,
931 return false;
932 }
935 stack.push_back(fSuccess ? vchTrue : vchFalse);
936 if (opcode == OP_CHECKSIGVERIFY) {
937 if (fSuccess) {
939 } else {
941 }
942 }
943 } break;
944
945 case OP_CHECKDATASIG:
947 // (sig message pubkey -- bool)
948 if (stack.size() < 3) {
949 return set_error(serror,
951 }
952
953 valtype &vchSig = stacktop(-3);
955 valtype &vchPubKey = stacktop(-1);
956
958 !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
959 // serror is set
960 return false;
961 }
962
963 bool fSuccess = false;
964 if (vchSig.size()) {
965 valtype vchHash(32);
966 CSHA256()
967 .Write(vchMessage.data(), vchMessage.size())
968 .Finalize(vchHash.data());
970 vchSig, CPubKey(vchPubKey), uint256(vchHash));
971 metrics.nSigChecks += 1;
972
975 }
976 }
977
981 stack.push_back(fSuccess ? vchTrue : vchFalse);
982 if (opcode == OP_CHECKDATASIGVERIFY) {
983 if (fSuccess) {
985 } else {
986 return set_error(serror,
988 }
989 }
990 } break;
991
992 case OP_CHECKMULTISIG:
994 // ([dummy] [sig ...] num_of_signatures [pubkey ...]
995 // num_of_pubkeys -- bool)
996 const size_t idxKeyCount = 1;
997 if (stack.size() < idxKeyCount) {
998 return set_error(serror,
1000 }
1001 const int64_t nKeysCount =
1003 .getint();
1006 }
1010 }
1011
1012 // stack depth of the top pubkey
1013 const size_t idxTopKey = idxKeyCount + 1;
1014
1015 // stack depth of nSigsCount
1016 const size_t idxSigCount = idxTopKey + nKeysCount;
1017 if (stack.size() < idxSigCount) {
1018 return set_error(serror,
1020 }
1021 const int64_t nSigsCount =
1023 .getint();
1026 }
1027
1028 // stack depth of the top signature
1029 const size_t idxTopSig = idxSigCount + 1;
1030
1031 // stack depth of the dummy element
1032 const size_t idxDummy = idxTopSig + nSigsCount;
1033 if (stack.size() < idxDummy) {
1034 return set_error(serror,
1036 }
1037
1038 // Subset of script starting at the most recent
1039 // codeseparator
1040 CScript scriptCode(pbegincodehash, pend);
1041
1042 // Assuming success is usually a bad idea, but the
1043 // schnorr path can only succeed.
1044 bool fSuccess = true;
1045
1047 stacktop(-idxDummy).size() != 0) {
1048 // SCHNORR MULTISIG
1049 static_assert(MAX_PUBKEYS_PER_MULTISIG < 32,
1050 "Schnorr multisig checkbits implementation "
1051 "assumes < 32 pubkeys.");
1052 uint32_t checkBits = 0;
1053
1054 // Dummy element is to be interpreted as a bitfield
1055 // that represent which pubkeys should be checked.
1058 serror)) {
1059 // serror is set
1060 return false;
1061 }
1062
1063 // The bitfield doesn't set the right number of
1064 // signatures.
1066 return set_error(serror,
1068 }
1069
1070 const size_t idxBottomKey = idxTopKey + nKeysCount - 1;
1071 const size_t idxBottomSig = idxTopSig + nSigsCount - 1;
1072
1073 int iKey = 0;
1074 for (int iSig = 0; iSig < nSigsCount; iSig++, iKey++) {
1075 if ((checkBits >> iKey) == 0) {
1076 // This is a sanity check and should be
1077 // unreachable.
1078 return set_error(serror,
1080 }
1081
1082 // Find the next suitable key.
1083 while (((checkBits >> iKey) & 0x01) == 0) {
1084 iKey++;
1085 }
1086
1087 if (iKey >= nKeysCount) {
1088 // This is a sanity check and should be
1089 // unreachable.
1091 }
1092
1093 // Check the signature.
1095 valtype &vchPubKey = stacktop(-idxBottomKey + iKey);
1096
1097 // Note that only pubkeys associated with a
1098 // signature are checked for validity.
1100 vchSig, flags, serror) ||
1101 !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
1102 // serror is set
1103 return false;
1104 }
1105
1106 // Check signature
1107 if (!checker.CheckSig(vchSig, vchPubKey, scriptCode,
1108 flags)) {
1109 // This can fail if the signature is empty,
1110 // which also is a NULLFAIL error as the
1111 // bitfield should have been null in this
1112 // situation.
1114 }
1115
1116 // this is guaranteed to execute exactly
1117 // nSigsCount times (if not script error)
1118 metrics.nSigChecks += 1;
1119 }
1120
1121 if ((checkBits >> iKey) != 0) {
1122 // This is a sanity check and should be
1123 // unreachable.
1124 return set_error(serror,
1126 }
1127 } else {
1128 // LEGACY MULTISIG (ECDSA / NULL)
1129
1130 // Remove signature for pre-fork scripts
1131 for (int k = 0; k < nSigsCount; k++) {
1133 CleanupScriptCode(scriptCode, vchSig, flags);
1134 }
1135
1138 while (fSuccess && nSigsRemaining > 0) {
1141 valtype &vchPubKey = stacktop(
1143
1144 // Note how this makes the exact order of
1145 // pubkey/signature evaluation distinguishable
1146 // by CHECKMULTISIG NOT if the STRICTENC flag is
1147 // set. See the script_(in)valid tests for
1148 // details.
1150 vchSig, flags, serror) ||
1151 !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
1152 // serror is set
1153 return false;
1154 }
1155
1156 // Check signature
1157 bool fOk = checker.CheckSig(vchSig, vchPubKey,
1158 scriptCode, flags);
1159
1160 if (fOk) {
1162 }
1164
1165 // If there are more signatures left than keys
1166 // left, then too many signatures have failed.
1167 // Exit early, without checking any further
1168 // signatures.
1170 fSuccess = false;
1171 }
1172 }
1173
1174 bool areAllSignaturesNull = true;
1175 for (int i = 0; i < nSigsCount; i++) {
1176 if (stacktop(-idxTopSig - i).size()) {
1177 areAllSignaturesNull = false;
1178 break;
1179 }
1180 }
1181
1182 // If the operation failed, we may require that all
1183 // signatures must be empty vector
1187 }
1188
1189 if (!areAllSignaturesNull) {
1190 // This is not identical to the number of actual
1191 // ECDSA verifies, but, it is an upper bound
1192 // that can be easily determined without doing
1193 // CPU-intensive checks.
1195 }
1196 }
1197
1198 // Clean up stack of all arguments
1199 for (size_t i = 0; i < idxDummy; i++) {
1200 popstack(stack);
1201 }
1202
1203 stack.push_back(fSuccess ? vchTrue : vchFalse);
1204 if (opcode == OP_CHECKMULTISIGVERIFY) {
1205 if (fSuccess) {
1206 popstack(stack);
1207 } else {
1208 return set_error(serror,
1210 }
1211 }
1212 } break;
1213
1214 //
1215 // Byte string operations
1216 //
1217 case OP_CAT: {
1218 // (x1 x2 -- out)
1219 if (stack.size() < 2) {
1220 return set_error(serror,
1222 }
1223 valtype &vch1 = stacktop(-2);
1224 valtype &vch2 = stacktop(-1);
1225 if (vch1.size() + vch2.size() > MAX_SCRIPT_ELEMENT_SIZE) {
1227 }
1228 vch1.insert(vch1.end(), vch2.begin(), vch2.end());
1229 popstack(stack);
1230 } break;
1231
1232 case OP_SPLIT: {
1233 // (in position -- x1 x2)
1234 if (stack.size() < 2) {
1235 return set_error(serror,
1237 }
1238
1239 const valtype &data = stacktop(-2);
1240
1241 // Make sure the split point is appropriate.
1244 if (position > data.size()) {
1246 }
1247
1248 // Prepare the results in their own buffer as `data`
1249 // will be invalidated.
1250 valtype n1(data.begin(), data.begin() + position);
1251 valtype n2(data.begin() + position, data.end());
1252
1253 // Replace existing stack values by the new values.
1254 stacktop(-2) = std::move(n1);
1255 stacktop(-1) = std::move(n2);
1256 } break;
1257
1258 case OP_REVERSEBYTES: {
1259 // (in -- out)
1260 if (stack.size() < 1) {
1261 return set_error(serror,
1263 }
1264
1265 valtype &data = stacktop(-1);
1266 std::reverse(data.begin(), data.end());
1267 } break;
1268
1269 //
1270 // Conversion operations
1271 //
1272 case OP_NUM2BIN: {
1273 // (in size -- out)
1274 if (stack.size() < 2) {
1275 return set_error(serror,
1277 }
1278
1279 uint64_t size =
1281 if (size > MAX_SCRIPT_ELEMENT_SIZE) {
1283 }
1284
1285 popstack(stack);
1286 valtype &rawnum = stacktop(-1);
1287
1288 // Try to see if we can fit that number in the number of
1289 // byte requested.
1291 if (rawnum.size() > size) {
1292 // We definitively cannot.
1294 }
1295
1296 // We already have an element of the right size, we
1297 // don't need to do anything.
1298 if (rawnum.size() == size) {
1299 break;
1300 }
1301
1302 uint8_t signbit = 0x00;
1303 if (rawnum.size() > 0) {
1304 signbit = rawnum.back() & 0x80;
1305 rawnum[rawnum.size() - 1] &= 0x7f;
1306 }
1307
1308 rawnum.reserve(size);
1309 while (rawnum.size() < size - 1) {
1310 rawnum.push_back(0x00);
1311 }
1312
1313 rawnum.push_back(signbit);
1314 } break;
1315
1316 case OP_BIN2NUM: {
1317 // (in -- out)
1318 if (stack.size() < 1) {
1319 return set_error(serror,
1321 }
1322
1323 valtype &n = stacktop(-1);
1325
1326 // The resulting number must be a valid number.
1329 }
1330 } break;
1331
1332 default:
1334 }
1335 }
1336
1337 // Size limits
1338 if (stack.size() + altstack.size() > MAX_STACK_SIZE) {
1340 }
1341
1342 return true;
1343}
1344
1345bool EvalScript(std::vector<valtype> &stack, const CScript &script,
1346 uint32_t flags, const BaseSignatureChecker &checker,
1348 ScriptInterpreter interpreter(stack, script, flags, checker, metrics);
1349 bool result = interpreter.RunUntilEnd();
1350 set_error(serror, interpreter.GetScriptError());
1351 return result;
1352}
1353
1354namespace {
1355
1360template <class T> class CTransactionSignatureSerializer {
1361private:
1363 const T &txTo;
1365 const CScript &scriptCode;
1367 const unsigned int nIn;
1369 const SigHashType sigHashType;
1370
1371public:
1372 CTransactionSignatureSerializer(const T &txToIn,
1373 const CScript &scriptCodeIn,
1374 unsigned int nInIn,
1376 : txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1377 sigHashType(sigHashTypeIn) {}
1378
1380 template <typename S> void SerializeScriptCode(S &s) const {
1381 CScript::const_iterator it = scriptCode.begin();
1383 opcodetype opcode;
1384 unsigned int nCodeSeparators = 0;
1385 while (scriptCode.GetOp(it, opcode)) {
1386 if (opcode == OP_CODESEPARATOR) {
1388 }
1389 }
1390 ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1391 it = itBegin;
1392 while (scriptCode.GetOp(it, opcode)) {
1393 if (opcode == OP_CODESEPARATOR) {
1394 s.write(AsBytes(Span{&itBegin[0], size_t(it - itBegin - 1)}));
1395 itBegin = it;
1396 }
1397 }
1398 if (itBegin != scriptCode.end()) {
1399 s.write(AsBytes(Span{&itBegin[0], size_t(it - itBegin)}));
1400 }
1401 }
1402
1404 template <typename S> void SerializeInput(S &s, unsigned int nInput) const {
1405 // In case of SIGHASH_ANYONECANPAY, only the input being signed is
1406 // serialized
1407 if (sigHashType.hasAnyoneCanPay()) {
1408 nInput = nIn;
1409 }
1410 // Serialize the prevout
1411 ::Serialize(s, txTo.vin[nInput].prevout);
1412 // Serialize the script
1413 if (nInput != nIn) {
1414 // Blank out other inputs' signatures
1415 ::Serialize(s, CScript());
1416 } else {
1418 }
1419 // Serialize the nSequence
1420 if (nInput != nIn &&
1421 (sigHashType.getBaseType() == BaseSigHashType::SINGLE ||
1422 sigHashType.getBaseType() == BaseSigHashType::NONE)) {
1423 // let the others update at will
1424 ::Serialize(s, (int)0);
1425 } else {
1426 ::Serialize(s, txTo.vin[nInput].nSequence);
1427 }
1428 }
1429
1431 template <typename S>
1432 void SerializeOutput(S &s, unsigned int nOutput) const {
1433 if (sigHashType.getBaseType() == BaseSigHashType::SINGLE &&
1434 nOutput != nIn) {
1435 // Do not lock-in the txout payee at other indices as txin
1436 ::Serialize(s, CTxOut());
1437 } else {
1438 ::Serialize(s, txTo.vout[nOutput]);
1439 }
1440 }
1441
1443 template <typename S> void Serialize(S &s) const {
1444 // Serialize nVersion
1445 ::Serialize(s, txTo.nVersion);
1446 // Serialize vin
1447 unsigned int nInputs =
1448 sigHashType.hasAnyoneCanPay() ? 1 : txTo.vin.size();
1450 for (unsigned int nInput = 0; nInput < nInputs; nInput++) {
1452 }
1453 // Serialize vout
1454 unsigned int nOutputs =
1455 (sigHashType.getBaseType() == BaseSigHashType::NONE)
1456 ? 0
1457 : ((sigHashType.getBaseType() == BaseSigHashType::SINGLE)
1458 ? nIn + 1
1459 : txTo.vout.size());
1461 for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++) {
1463 }
1464 // Serialize nLockTime
1465 ::Serialize(s, txTo.nLockTime);
1466 }
1467};
1468
1469template <class T> uint256 GetPrevoutHash(const T &txTo) {
1470 HashWriter ss{};
1471 for (const auto &txin : txTo.vin) {
1472 ss << txin.prevout;
1473 }
1474 return ss.GetHash();
1475}
1476
1477template <class T> uint256 GetSequenceHash(const T &txTo) {
1478 HashWriter ss{};
1479 for (const auto &txin : txTo.vin) {
1480 ss << txin.nSequence;
1481 }
1482 return ss.GetHash();
1483}
1484
1485template <class T> uint256 GetOutputsHash(const T &txTo) {
1486 HashWriter ss{};
1487 for (const auto &txout : txTo.vout) {
1488 ss << txout;
1489 }
1490 return ss.GetHash();
1491}
1492
1493} // namespace
1494
1495template <class T>
1501
1502// explicit instantiation
1504 const CTransaction &txTo);
1506 const CMutableTransaction &txTo);
1507
1508template <class T>
1509uint256 SignatureHash(const CScript &scriptCode, const T &txTo,
1510 unsigned int nIn, SigHashType sigHashType,
1511 const Amount amount,
1513 assert(nIn < txTo.vin.size());
1514
1516 // Legacy chain's value for fork id must be of the form 0xffxxxx.
1517 // By xoring with 0xdead, we ensure that the value will be different
1518 // from the original one, even if it already starts with 0xff.
1519 uint32_t newForkValue = sigHashType.getForkValue() ^ 0xdead;
1520 sigHashType = sigHashType.withForkValue(0xff0000 | newForkValue);
1521 }
1522
1523 if (sigHashType.hasForkId() && (flags & SCRIPT_ENABLE_SIGHASH_FORKID)) {
1524 uint256 hashPrevouts;
1525 uint256 hashSequence;
1526 uint256 hashOutputs;
1527
1528 if (!sigHashType.hasAnyoneCanPay()) {
1529 hashPrevouts = cache ? cache->hashPrevouts : GetPrevoutHash(txTo);
1530 }
1531
1532 if (!sigHashType.hasAnyoneCanPay() &&
1533 (sigHashType.getBaseType() != BaseSigHashType::SINGLE) &&
1534 (sigHashType.getBaseType() != BaseSigHashType::NONE)) {
1535 hashSequence = cache ? cache->hashSequence : GetSequenceHash(txTo);
1536 }
1537
1538 if ((sigHashType.getBaseType() != BaseSigHashType::SINGLE) &&
1539 (sigHashType.getBaseType() != BaseSigHashType::NONE)) {
1540 hashOutputs = cache ? cache->hashOutputs : GetOutputsHash(txTo);
1541 } else if ((sigHashType.getBaseType() == BaseSigHashType::SINGLE) &&
1542 (nIn < txTo.vout.size())) {
1543 HashWriter ss{};
1544 ss << txTo.vout[nIn];
1545 hashOutputs = ss.GetHash();
1546 }
1547
1548 HashWriter ss{};
1549 // Version
1550 ss << txTo.nVersion;
1551 // Input prevouts/nSequence (none/all, depending on flags)
1552 ss << hashPrevouts;
1553 ss << hashSequence;
1554 // The input being signed (replacing the scriptSig with scriptCode +
1555 // amount). The prevout may already be contained in hashPrevout, and the
1556 // nSequence may already be contain in hashSequence.
1557 ss << txTo.vin[nIn].prevout;
1558 ss << scriptCode;
1559 ss << amount;
1560 ss << txTo.vin[nIn].nSequence;
1561 // Outputs (none/one/all, depending on flags)
1562 ss << hashOutputs;
1563 // Locktime
1564 ss << txTo.nLockTime;
1565 // Sighash type
1566 ss << sigHashType;
1567
1568 return ss.GetHash();
1569 }
1570
1571 // Check for invalid use of SIGHASH_SINGLE
1572 if ((sigHashType.getBaseType() == BaseSigHashType::SINGLE) &&
1573 (nIn >= txTo.vout.size())) {
1574 // nOut out of range
1575 return uint256::ONE;
1576 }
1577
1578 // Wrapper to serialize only the necessary parts of the transaction being
1579 // signed
1580 CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn,
1581 sigHashType);
1582
1583 // Serialize and hash
1584 HashWriter ss{};
1585 ss << txTmp << sigHashType;
1586 return ss.GetHash();
1587}
1588
1589bool BaseSignatureChecker::VerifySignature(const std::vector<uint8_t> &vchSig,
1590 const CPubKey &pubkey,
1591 const uint256 &sighash) const {
1592 if (vchSig.size() == 64) {
1593 return pubkey.VerifySchnorr(sighash, vchSig);
1594 } else {
1595 return pubkey.VerifyECDSA(sighash, vchSig);
1596 }
1597}
1598
1599template <class T>
1601 const std::vector<uint8_t> &vchSigIn, const std::vector<uint8_t> &vchPubKey,
1602 const CScript &scriptCode, uint32_t flags) const {
1603 CPubKey pubkey(vchPubKey);
1604 if (!pubkey.IsValid()) {
1605 return false;
1606 }
1607
1608 // Hash type is one byte tacked on to the end of the signature
1609 std::vector<uint8_t> vchSig(vchSigIn);
1610 if (vchSig.empty()) {
1611 return false;
1612 }
1613 SigHashType sigHashType = GetHashType(vchSig);
1614 vchSig.pop_back();
1615
1616 uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, sigHashType, amount,
1617 this->txdata, flags);
1618
1619 if (!VerifySignature(vchSig, pubkey, sighash)) {
1620 return false;
1621 }
1622
1623 return true;
1624}
1625
1626template <class T>
1628 const CScriptNum &nLockTime) const {
1629 // There are two kinds of nLockTime: lock-by-blockheight and
1630 // lock-by-blocktime, distinguished by whether nLockTime <
1631 // LOCKTIME_THRESHOLD.
1632 //
1633 // We want to compare apples to apples, so fail the script unless the type
1634 // of nLockTime being tested is the same as the nLockTime in the
1635 // transaction.
1636 if (!((txTo->nLockTime < LOCKTIME_THRESHOLD &&
1637 nLockTime < LOCKTIME_THRESHOLD) ||
1638 (txTo->nLockTime >= LOCKTIME_THRESHOLD &&
1639 nLockTime >= LOCKTIME_THRESHOLD))) {
1640 return false;
1641 }
1642
1643 // Now that we know we're comparing apples-to-apples, the comparison is a
1644 // simple numeric one.
1645 if (nLockTime > int64_t(txTo->nLockTime)) {
1646 return false;
1647 }
1648
1649 // Finally the nLockTime feature can be disabled and thus
1650 // CHECKLOCKTIMEVERIFY bypassed if every txin has been finalized by setting
1651 // nSequence to maxint. The transaction would be allowed into the
1652 // blockchain, making the opcode ineffective.
1653 //
1654 // Testing if this vin is not final is sufficient to prevent this condition.
1655 // Alternatively we could test all inputs, but testing just this input
1656 // minimizes the data required to prove correct CHECKLOCKTIMEVERIFY
1657 // execution.
1658 if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence) {
1659 return false;
1660 }
1661
1662 return true;
1663}
1664
1665template <class T>
1667 const CScriptNum &nSequence) const {
1668 // Relative lock times are supported by comparing the passed in operand to
1669 // the sequence number of the input.
1670 const int64_t txToSequence = int64_t(txTo->vin[nIn].nSequence);
1671
1672 // Fail if the transaction's version number is not set high enough to
1673 // trigger BIP 68 rules.
1674 if (static_cast<uint32_t>(txTo->nVersion) < 2) {
1675 return false;
1676 }
1677
1678 // Sequence numbers with their most significant bit set are not consensus
1679 // constrained. Testing that the transaction's sequence number do not have
1680 // this bit set prevents using this property to get around a
1681 // CHECKSEQUENCEVERIFY check.
1683 return false;
1684 }
1685
1686 // Mask off any bits that do not have consensus-enforced meaning before
1687 // doing the integer comparisons
1688 const uint32_t nLockTimeMask =
1691 const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1692
1693 // There are two kinds of nSequence: lock-by-blockheight and
1694 // lock-by-blocktime, distinguished by whether nSequenceMasked <
1695 // CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1696 //
1697 // We want to compare apples to apples, so fail the script unless the type
1698 // of nSequenceMasked being tested is the same as the nSequenceMasked in the
1699 // transaction.
1704 return false;
1705 }
1706
1707 // Now that we know we're comparing apples-to-apples, the comparison is a
1708 // simple numeric one.
1710 return false;
1711 }
1712
1713 return true;
1714}
1715
1716// explicit instantiation
1719
1720bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey,
1721 uint32_t flags, const BaseSignatureChecker &checker,
1724
1725 // If FORKID is enabled, we also ensure strict encoding.
1728 }
1729
1730 if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1732 }
1733
1734 ScriptExecutionMetrics metrics = {};
1735
1736 // scriptSig and scriptPubKey must be evaluated sequentially on the same
1737 // stack rather than being simply concatenated (see CVE-2010-5141)
1738 std::vector<valtype> stack, stackCopy;
1739 if (!EvalScript(stack, scriptSig, flags, checker, metrics, serror)) {
1740 // serror is set
1741 return false;
1742 }
1743 if (flags & SCRIPT_VERIFY_P2SH) {
1744 stackCopy = stack;
1745 }
1746 if (!EvalScript(stack, scriptPubKey, flags, checker, metrics, serror)) {
1747 // serror is set
1748 return false;
1749 }
1750 if (stack.empty()) {
1752 }
1753 if (CastToBool(stack.back()) == false) {
1755 }
1756
1757 // Additional validation for spend-to-script-hash transactions:
1758 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash()) {
1759 // scriptSig must be literals-only or validation fails
1760 if (!scriptSig.IsPushOnly()) {
1762 }
1763
1764 // Restore stack.
1765 swap(stack, stackCopy);
1766
1767 // stack cannot be empty here, because if it was the P2SH HASH <> EQUAL
1768 // scriptPubKey would be evaluated with an empty stack and the
1769 // EvalScript above would return false.
1770 assert(!stack.empty());
1771
1772 const valtype &pubKeySerialized = stack.back();
1774 popstack(stack);
1775
1776 // Bail out early if SCRIPT_DISALLOW_SEGWIT_RECOVERY is not set, the
1777 // redeem script is a p2sh segwit program, and it was the only item
1778 // pushed onto the stack.
1779 if ((flags & SCRIPT_DISALLOW_SEGWIT_RECOVERY) == 0 && stack.empty() &&
1780 pubKey2.IsWitnessProgram()) {
1781 // must set metricsOut for all successful returns
1782 metricsOut = metrics;
1783 return set_success(serror);
1784 }
1785
1786 if (!EvalScript(stack, pubKey2, flags, checker, metrics, serror)) {
1787 // serror is set
1788 return false;
1789 }
1790 if (stack.empty()) {
1792 }
1793 if (!CastToBool(stack.back())) {
1795 }
1796 }
1797
1798 // The CLEANSTACK check is only performed after potential P2SH evaluation,
1799 // as the non-P2SH evaluation of a P2SH script will obviously not result in
1800 // a clean stack (the P2SH inputs remain). The same holds for witness
1801 // evaluation.
1802 if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
1803 // Disallow CLEANSTACK without P2SH, as otherwise a switch
1804 // CLEANSTACK->P2SH+CLEANSTACK would be possible, which is not a
1805 // softfork (and P2SH should be one).
1807 if (stack.size() != 1) {
1809 }
1810 }
1811
1813 // This limit is intended for standard use, and is based on an
1814 // examination of typical and historical standard uses.
1815 // - allowing P2SH ECDSA multisig with compressed keys, which at an
1816 // extreme (1-of-15) may have 15 SigChecks in ~590 bytes of scriptSig.
1817 // - allowing Bare ECDSA multisig, which at an extreme (1-of-3) may have
1818 // 3 sigchecks in ~72 bytes of scriptSig.
1819 // - Since the size of an input is 41 bytes + length of scriptSig, then
1820 // the most dense possible inputs satisfying this rule would be:
1821 // 2 sigchecks and 26 bytes: 1/33.50 sigchecks/byte.
1822 // 3 sigchecks and 69 bytes: 1/36.66 sigchecks/byte.
1823 // The latter can be readily done with 1-of-3 bare multisignatures,
1824 // however the former is not practically doable with standard scripts,
1825 // so the practical density limit is 1/36.66.
1826 static_assert(INT_MAX > MAX_SCRIPT_SIZE,
1827 "overflow sanity check on max script size");
1828 static_assert(INT_MAX / 43 / 3 > MAX_OPS_PER_SCRIPT,
1829 "overflow sanity check on maximum possible sigchecks "
1830 "from sig+redeem+pub scripts");
1831 if (int(scriptSig.size()) < metrics.nSigChecks * 43 - 60) {
1833 }
1834 }
1835
1836 metricsOut = metrics;
1837 return set_success(serror);
1838}
int flags
bool DecodeBitfield(const std::vector< uint8_t > &vch, unsigned size, uint32_t &bitfield, ScriptError *serror)
Definition bitfield.cpp:12
uint32_t countBits(uint32_t v)
Definition bitmanip.h:12
virtual bool VerifySignature(const std::vector< uint8_t > &vchSig, const CPubKey &vchPubKey, const uint256 &sighash) const
virtual bool CheckLockTime(const CScriptNum &nLockTime) const
Definition interpreter.h:46
virtual bool CheckSequence(const CScriptNum &nSequence) const
Definition interpreter.h:50
virtual bool CheckSig(const std::vector< uint8_t > &vchSigIn, const std::vector< uint8_t > &vchPubKey, const CScript &scriptCode, uint32_t flags) const
Definition interpreter.h:40
A hasher class for Bitcoin's 160-bit hash (SHA-256 + RIPEMD-160).
Definition hash.h:49
CHash160 & Write(Span< const uint8_t > input)
Definition hash.h:63
void Finalize(Span< uint8_t > output)
Definition hash.h:56
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition hash.h:23
CHash256 & Write(Span< const uint8_t > input)
Definition hash.h:37
void Finalize(Span< uint8_t > output)
Definition hash.h:30
A mutable version of CTransaction.
An encapsulated public key.
Definition pubkey.h:31
bool VerifySchnorr(const uint256 &hash, const std::array< uint8_t, SCHNORR_SIZE > &sig) const
Verify a Schnorr signature (=64 bytes).
Definition pubkey.cpp:199
bool VerifyECDSA(const uint256 &hash, const std::vector< uint8_t > &vchSig) const
Verify a DER-serialized ECDSA signature (~72 bytes).
Definition pubkey.cpp:172
bool IsValid() const
Definition pubkey.h:147
A hasher class for RIPEMD-160.
Definition ripemd160.h:12
CRIPEMD160 & Write(const uint8_t *data, size_t len)
void Finalize(uint8_t hash[OUTPUT_SIZE])
A hasher class for SHA1.
Definition sha1.h:12
void Finalize(uint8_t hash[OUTPUT_SIZE])
Definition sha1.cpp:183
CSHA1 & Write(const uint8_t *data, size_t len)
Definition sha1.cpp:158
A hasher class for SHA-256.
Definition sha256.h:13
CSHA256 & Write(const uint8_t *data, size_t len)
Definition sha256.cpp:819
void Finalize(uint8_t hash[OUTPUT_SIZE])
Definition sha256.cpp:844
Serialized script, used inside transaction inputs and outputs.
Definition script.h:424
bool IsPushOnly(const_iterator pc) const
Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical).
Definition script.cpp:404
bool IsPayToScriptHash() const
Definition script.cpp:373
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< uint8_t > &vchRet) const
Definition script.h:495
int64_t getint() const
Definition script.h:352
static bool MinimallyEncode(std::vector< uint8_t > &data)
Definition script.cpp:327
static bool IsMinimallyEncoded(const std::vector< uint8_t > &vch, const size_t nMaxNumSize=CScriptNum::MAXIMUM_ELEMENT_SIZE)
Definition script.cpp:299
The basic transaction that is broadcasted on the network and contained in blocks.
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
If this flag set, CTxIn::nSequence is NOT interpreted as a relative lock-time.
Definition transaction.h:76
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:89
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime.
Definition transaction.h:69
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:83
An output of a transaction.
void push_back(bool f)
bool empty() const
bool all_true() const
bool CheckSig(const std::vector< uint8_t > &vchSigIn, const std::vector< uint8_t > &vchPubKey, const CScript &scriptCode, uint32_t flags) const final override
bool CheckSequence(const CScriptNum &nSequence) const final override
bool CheckLockTime(const CScriptNum &nLockTime) const final override
A writer stream (for serialization) that computes a 256-bit hash.
Definition hash.h:100
uint256 GetHash()
Compute the double-SHA256 hash of all data written to this object.
Definition hash.h:114
CScript::const_iterator pend
ConditionStack vfExec
ScriptError script_error
const CScript & script
Definition interpreter.h:96
std::vector< std::vector< uint8_t > > altstack
Definition interpreter.h:93
CScript::const_iterator pbegincodehash
const ConditionStack & GetConditionStack()
const BaseSignatureChecker & checker
CScript::const_iterator pc
Definition interpreter.h:99
ScriptInterpreter(std::vector< std::vector< uint8_t > > &stack, const CScript &script, uint32_t flags, const BaseSignatureChecker &checker, ScriptExecutionMetrics &metrics)
std::vector< std::vector< uint8_t > > & stack
Definition interpreter.h:91
bool GetNextOp(opcodetype &opcodeRet, std::vector< uint8_t > &vchRet) const
ScriptExecutionMetrics & metrics
Signature hash type wrapper class.
Definition sighashtype.h:37
BaseSigHashType getBaseType() const
Definition sighashtype.h:64
bool hasAnyoneCanPay() const
Definition sighashtype.h:79
SigHashType withForkValue(uint32_t forkId) const
Definition sighashtype.h:50
bool hasForkId() const
Definition sighashtype.h:77
uint32_t getForkValue() const
Definition sighashtype.h:68
A Span is an object that can refer to a contiguous sequence of objects.
Definition span.h:93
size_type size() const
Definition prevector.h:394
iterator begin()
Definition prevector.h:398
iterator end()
Definition prevector.h:400
iterator insert(iterator pos, const T &value)
Definition prevector.h:451
256-bit opaque blob.
Definition uint256.h:129
static const uint256 ONE
Definition uint256.h:135
static bool IsOpcodeDisabled(opcodetype opcode, uint32_t flags)
static void CleanupScriptCode(CScript &scriptCode, const std::vector< uint8_t > &vchSig, uint32_t flags)
uint256 SignatureHash(const CScript &scriptCode, const T &txTo, unsigned int nIn, SigHashType sigHashType, const Amount amount, const PrecomputedTransactionData *cache, uint32_t flags)
bool EvalScript(std::vector< valtype > &stack, const CScript &script, uint32_t flags, const BaseSignatureChecker &checker, ScriptExecutionMetrics &metrics, ScriptError *serror)
static bool EvalChecksig(const valtype &vchSig, const valtype &vchPubKey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, uint32_t flags, const BaseSignatureChecker &checker, ScriptExecutionMetrics &metrics, ScriptError *serror, bool &fSuccess)
Helper for OP_CHECKSIG and OP_CHECKSIGVERIFY.
bool CastToBool(const valtype &vch)
int FindAndDelete(CScript &script, const CScript &b)
static void popstack(std::vector< valtype > &stack)
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, uint32_t flags, const BaseSignatureChecker &checker, ScriptExecutionMetrics &metricsOut, ScriptError *serror)
Execute an unlocking and locking script together.
#define stacktop(i)
Script is a stack machine (like Forth) that evaluates a predicate returning a bool indicating valid o...
#define altstacktop(i)
bool CastToBool(const std::vector< uint8_t > &vch)
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
bool CheckMinimalPush(const std::vector< uint8_t > &data, opcodetype opcode)
Check whether the given stack element data would be minimally pushed using the given opcode.
Definition script.cpp:268
static const unsigned int LOCKTIME_THRESHOLD
Definition script.h:40
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition script.h:24
static const int MAX_SCRIPT_SIZE
Definition script.h:33
opcodetype
Script opcodes.
Definition script.h:47
@ OP_NUMNOTEQUAL
Definition script.h:146
@ OP_SPLIT
Definition script.h:109
@ OP_2
Definition script.h:58
@ OP_SHA256
Definition script.h:159
@ OP_PUSHDATA4
Definition script.h:53
@ OP_NOP5
Definition script.h:175
@ OP_CHECKDATASIG
Definition script.h:183
@ OP_BOOLAND
Definition script.h:142
@ OP_CHECKMULTISIG
Definition script.h:165
@ OP_NEGATE
Definition script.h:129
@ OP_IF
Definition script.h:77
@ OP_13
Definition script.h:69
@ OP_ROT
Definition script.h:103
@ OP_SWAP
Definition script.h:104
@ OP_1NEGATE
Definition script.h:54
@ OP_CHECKSIG
Definition script.h:163
@ OP_CHECKLOCKTIMEVERIFY
Definition script.h:170
@ OP_LESSTHAN
Definition script.h:147
@ OP_16
Definition script.h:72
@ OP_14
Definition script.h:70
@ OP_CHECKDATASIGVERIFY
Definition script.h:184
@ OP_NOP10
Definition script.h:180
@ OP_2DIV
Definition script.h:128
@ OP_NOT
Definition script.h:131
@ OP_EQUAL
Definition script.h:119
@ OP_NUMEQUAL
Definition script.h:144
@ OP_MOD
Definition script.h:138
@ OP_NOTIF
Definition script.h:78
@ OP_4
Definition script.h:60
@ OP_10
Definition script.h:66
@ OP_SIZE
Definition script.h:112
@ OP_3DUP
Definition script.h:91
@ OP_ENDIF
Definition script.h:82
@ OP_NOP1
Definition script.h:169
@ OP_DUP
Definition script.h:98
@ OP_GREATERTHAN
Definition script.h:148
@ OP_NOP
Definition script.h:75
@ OP_NUM2BIN
Definition script.h:110
@ OP_TOALTSTACK
Definition script.h:87
@ OP_CODESEPARATOR
Definition script.h:162
@ OP_RIPEMD160
Definition script.h:157
@ OP_MIN
Definition script.h:151
@ OP_HASH256
Definition script.h:161
@ OP_MAX
Definition script.h:152
@ OP_1SUB
Definition script.h:126
@ OP_FROMALTSTACK
Definition script.h:88
@ OP_SUB
Definition script.h:135
@ OP_NUMEQUALVERIFY
Definition script.h:145
@ OP_OVER
Definition script.h:100
@ OP_NOP8
Definition script.h:178
@ OP_DIV
Definition script.h:137
@ OP_HASH160
Definition script.h:160
@ OP_2DUP
Definition script.h:90
@ OP_NIP
Definition script.h:99
@ OP_2MUL
Definition script.h:127
@ OP_NOP4
Definition script.h:174
@ OP_1
Definition script.h:56
@ OP_LESSTHANOREQUAL
Definition script.h:149
@ OP_2DROP
Definition script.h:89
@ OP_DEPTH
Definition script.h:96
@ OP_NOP9
Definition script.h:179
@ OP_BIN2NUM
Definition script.h:111
@ OP_VERIFY
Definition script.h:83
@ OP_12
Definition script.h:68
@ OP_ADD
Definition script.h:134
@ OP_CHECKMULTISIGVERIFY
Definition script.h:166
@ OP_NOP7
Definition script.h:177
@ OP_8
Definition script.h:64
@ OP_BOOLOR
Definition script.h:143
@ OP_XOR
Definition script.h:118
@ OP_DROP
Definition script.h:97
@ OP_MUL
Definition script.h:136
@ OP_WITHIN
Definition script.h:154
@ OP_ELSE
Definition script.h:81
@ OP_15
Definition script.h:71
@ OP_CHECKSIGVERIFY
Definition script.h:164
@ OP_TUCK
Definition script.h:105
@ OP_2OVER
Definition script.h:92
@ OP_0NOTEQUAL
Definition script.h:132
@ OP_9
Definition script.h:65
@ OP_3
Definition script.h:59
@ OP_11
Definition script.h:67
@ OP_SHA1
Definition script.h:158
@ OP_GREATERTHANOREQUAL
Definition script.h:150
@ OP_RSHIFT
Definition script.h:140
@ OP_2SWAP
Definition script.h:94
@ OP_2ROT
Definition script.h:93
@ OP_6
Definition script.h:62
@ OP_INVERT
Definition script.h:115
@ OP_ABS
Definition script.h:130
@ OP_LSHIFT
Definition script.h:139
@ OP_RETURN
Definition script.h:84
@ OP_IFDUP
Definition script.h:95
@ OP_PICK
Definition script.h:101
@ OP_AND
Definition script.h:116
@ OP_EQUALVERIFY
Definition script.h:120
@ OP_CAT
Definition script.h:108
@ OP_REVERSEBYTES
Definition script.h:187
@ OP_1ADD
Definition script.h:125
@ OP_7
Definition script.h:63
@ OP_OR
Definition script.h:117
@ OP_ROLL
Definition script.h:102
@ OP_NOP6
Definition script.h:176
@ OP_5
Definition script.h:61
@ OP_CHECKSEQUENCEVERIFY
Definition script.h:172
static const int MAX_STACK_SIZE
Definition script.h:36
static const int MAX_OPS_PER_SCRIPT
Definition script.h:27
static const int MAX_PUBKEYS_PER_MULTISIG
Definition script.h:30
ScriptError
@ DISCOURAGE_UPGRADABLE_NOPS
@ INVALID_ALTSTACK_OPERATION
@ UNSATISFIED_LOCKTIME
@ INVALID_OPERAND_SIZE
@ INVALID_STACK_OPERATION
@ UNBALANCED_CONDITIONAL
@ INVALID_NUMBER_RANGE
@ SCRIPT_VERIFY_P2SH
@ SCRIPT_VERIFY_SIGPUSHONLY
@ SCRIPT_VERIFY_MINIMALIF
@ SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
@ SCRIPT_ENABLE_REPLAY_PROTECTION
@ SCRIPT_ENABLE_SCHNORR_MULTISIG
@ SCRIPT_VERIFY_STRICTENC
@ SCRIPT_VERIFY_NULLFAIL
@ SCRIPT_VERIFY_CLEANSTACK
@ SCRIPT_VERIFY_MINIMALDATA
@ SCRIPT_DISALLOW_SEGWIT_RECOVERY
@ SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS
@ SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
@ SCRIPT_ENABLE_SIGHASH_FORKID
@ SCRIPT_VERIFY_INPUT_SIGCHECKS
void Serialize(Stream &, char)=delete
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition serialize.h:1254
bool CheckTransactionSchnorrSignatureEncoding(const valtype &vchSig, uint32_t flags, ScriptError *serror)
Check that the signature provided to authentify a transaction is properly encoded Schnorr signature (...
bool CheckDataSignatureEncoding(const valtype &vchSig, uint32_t flags, ScriptError *serror)
Check that the signature provided on some data is properly encoded.
bool CheckTransactionECDSASignatureEncoding(const valtype &vchSig, uint32_t flags, ScriptError *serror)
Check that the signature provided to authentify a transaction is properly encoded ECDSA signature.
bool CheckTransactionSignatureEncoding(const valtype &vchSig, uint32_t flags, ScriptError *serror)
Check that the signature provided to authentify a transaction is properly encoded.
bool CheckPubKeyEncoding(const valtype &vchPubKey, uint32_t flags, ScriptError *serror)
Check that a public key is encoded properly.
std::vector< uint8_t > valtype
Definition sigencoding.h:16
BaseSigHashType
Base signature hash types Base sig hash types not defined in this enum may be used,...
Definition sighashtype.h:29
Span< const std::byte > AsBytes(Span< T > s) noexcept
Definition span.h:294
Precompute sighash midstate to avoid quadratic hashing.
Struct for holding cumulative results from executing a script or a sequence of scripts.
assert(!tx.IsCoinBase())