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