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