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