Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #ifndef BITCOIN_SCRIPT_SCRIPT_H
7 : : #define BITCOIN_SCRIPT_SCRIPT_H
8 : :
9 : : #include <attributes.h>
10 : : #include <crypto/common.h>
11 : : #include <prevector.h>
12 : : #include <serialize.h>
13 : : #include <span.h>
14 : : #include <streams.h>
15 : : #include <uint256.h>
16 : : #include <util/hash_type.h>
17 : :
18 : : #include <algorithm>
19 : : #include <cassert>
20 : : #include <cstddef>
21 : : #include <cstdint>
22 : : #include <ios>
23 : : #include <limits>
24 : : #include <memory>
25 : : #include <ranges>
26 : : #include <span>
27 : : #include <stdexcept>
28 : : #include <string>
29 : : #include <type_traits>
30 : : #include <utility>
31 : : #include <vector>
32 : :
33 : : // Maximum number of bytes pushable to the stack
34 : : inline constexpr unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520;
35 : :
36 : : // Maximum number of non-push operations per script
37 : : inline constexpr int MAX_OPS_PER_SCRIPT = 201;
38 : :
39 : : // Maximum number of public keys per multisig
40 : : inline constexpr int MAX_PUBKEYS_PER_MULTISIG = 20;
41 : :
42 : : /** The limit of keys in OP_CHECKSIGADD-based scripts. It is due to the stack limit in BIP342. */
43 : : inline constexpr unsigned int MAX_PUBKEYS_PER_MULTI_A = 999;
44 : :
45 : : // Maximum script length in bytes
46 : : inline constexpr int MAX_SCRIPT_SIZE{10'000};
47 : :
48 : : // Maximum number of values on script interpreter stack
49 : : inline constexpr int MAX_STACK_SIZE = 1000;
50 : :
51 : : // Threshold for nLockTime: below this value it is interpreted as block number,
52 : : // otherwise as UNIX timestamp.
53 : : inline constexpr unsigned int LOCKTIME_THRESHOLD{500'000'000}; // Tue Nov 5 00:53:20 1985 UTC
54 : :
55 : : // Maximum nLockTime. Since a lock time indicates the last invalid timestamp, a
56 : : // transaction with this lock time will never be valid unless lock time
57 : : // checking is disabled (by setting all input sequence numbers to
58 : : // SEQUENCE_FINAL).
59 : : inline constexpr uint32_t LOCKTIME_MAX = 0xFFFFFFFFU;
60 : :
61 : : // Tag for input annex. If there are at least two witness elements for a transaction input,
62 : : // and the first byte of the last element is 0x50, this last element is called annex, and
63 : : // has meanings independent of the script
64 : : inline constexpr unsigned int ANNEX_TAG = 0x50;
65 : :
66 : : // Validation weight per passing signature (Tapscript only, see BIP 342).
67 : : inline constexpr int64_t VALIDATION_WEIGHT_PER_SIGOP_PASSED{50};
68 : :
69 : : // How much weight budget is added to the witness size (Tapscript only, see BIP 342).
70 : : inline constexpr int64_t VALIDATION_WEIGHT_OFFSET{50};
71 : :
72 : : template <typename T>
73 : 3773964 : std::vector<unsigned char> ToByteVector(const T& in)
74 : : {
75 [ + - ]: 3773965 : return std::vector<unsigned char>(in.begin(), in.end());
76 : : }
77 : :
78 : : /** Script opcodes */
79 : : enum opcodetype
80 : : {
81 : : // push value
82 : : OP_0 = 0x00,
83 : : OP_FALSE = OP_0,
84 : : OP_PUSHDATA1 = 0x4c,
85 : : OP_PUSHDATA2 = 0x4d,
86 : : OP_PUSHDATA4 = 0x4e,
87 : : OP_1NEGATE = 0x4f,
88 : : OP_RESERVED = 0x50,
89 : : OP_1 = 0x51,
90 : : OP_TRUE=OP_1,
91 : : OP_2 = 0x52,
92 : : OP_3 = 0x53,
93 : : OP_4 = 0x54,
94 : : OP_5 = 0x55,
95 : : OP_6 = 0x56,
96 : : OP_7 = 0x57,
97 : : OP_8 = 0x58,
98 : : OP_9 = 0x59,
99 : : OP_10 = 0x5a,
100 : : OP_11 = 0x5b,
101 : : OP_12 = 0x5c,
102 : : OP_13 = 0x5d,
103 : : OP_14 = 0x5e,
104 : : OP_15 = 0x5f,
105 : : OP_16 = 0x60,
106 : :
107 : : // control
108 : : OP_NOP = 0x61,
109 : : OP_VER = 0x62,
110 : : OP_IF = 0x63,
111 : : OP_NOTIF = 0x64,
112 : : OP_VERIF = 0x65,
113 : : OP_VERNOTIF = 0x66,
114 : : OP_ELSE = 0x67,
115 : : OP_ENDIF = 0x68,
116 : : OP_VERIFY = 0x69,
117 : : OP_RETURN = 0x6a,
118 : :
119 : : // stack ops
120 : : OP_TOALTSTACK = 0x6b,
121 : : OP_FROMALTSTACK = 0x6c,
122 : : OP_2DROP = 0x6d,
123 : : OP_2DUP = 0x6e,
124 : : OP_3DUP = 0x6f,
125 : : OP_2OVER = 0x70,
126 : : OP_2ROT = 0x71,
127 : : OP_2SWAP = 0x72,
128 : : OP_IFDUP = 0x73,
129 : : OP_DEPTH = 0x74,
130 : : OP_DROP = 0x75,
131 : : OP_DUP = 0x76,
132 : : OP_NIP = 0x77,
133 : : OP_OVER = 0x78,
134 : : OP_PICK = 0x79,
135 : : OP_ROLL = 0x7a,
136 : : OP_ROT = 0x7b,
137 : : OP_SWAP = 0x7c,
138 : : OP_TUCK = 0x7d,
139 : :
140 : : // splice ops
141 : : OP_CAT = 0x7e,
142 : : OP_SUBSTR = 0x7f,
143 : : OP_LEFT = 0x80,
144 : : OP_RIGHT = 0x81,
145 : : OP_SIZE = 0x82,
146 : :
147 : : // bit logic
148 : : OP_INVERT = 0x83,
149 : : OP_AND = 0x84,
150 : : OP_OR = 0x85,
151 : : OP_XOR = 0x86,
152 : : OP_EQUAL = 0x87,
153 : : OP_EQUALVERIFY = 0x88,
154 : : OP_RESERVED1 = 0x89,
155 : : OP_RESERVED2 = 0x8a,
156 : :
157 : : // numeric
158 : : OP_1ADD = 0x8b,
159 : : OP_1SUB = 0x8c,
160 : : OP_2MUL = 0x8d,
161 : : OP_2DIV = 0x8e,
162 : : OP_NEGATE = 0x8f,
163 : : OP_ABS = 0x90,
164 : : OP_NOT = 0x91,
165 : : OP_0NOTEQUAL = 0x92,
166 : :
167 : : OP_ADD = 0x93,
168 : : OP_SUB = 0x94,
169 : : OP_MUL = 0x95,
170 : : OP_DIV = 0x96,
171 : : OP_MOD = 0x97,
172 : : OP_LSHIFT = 0x98,
173 : : OP_RSHIFT = 0x99,
174 : :
175 : : OP_BOOLAND = 0x9a,
176 : : OP_BOOLOR = 0x9b,
177 : : OP_NUMEQUAL = 0x9c,
178 : : OP_NUMEQUALVERIFY = 0x9d,
179 : : OP_NUMNOTEQUAL = 0x9e,
180 : : OP_LESSTHAN = 0x9f,
181 : : OP_GREATERTHAN = 0xa0,
182 : : OP_LESSTHANOREQUAL = 0xa1,
183 : : OP_GREATERTHANOREQUAL = 0xa2,
184 : : OP_MIN = 0xa3,
185 : : OP_MAX = 0xa4,
186 : :
187 : : OP_WITHIN = 0xa5,
188 : :
189 : : // crypto
190 : : OP_RIPEMD160 = 0xa6,
191 : : OP_SHA1 = 0xa7,
192 : : OP_SHA256 = 0xa8,
193 : : OP_HASH160 = 0xa9,
194 : : OP_HASH256 = 0xaa,
195 : : OP_CODESEPARATOR = 0xab,
196 : : OP_CHECKSIG = 0xac,
197 : : OP_CHECKSIGVERIFY = 0xad,
198 : : OP_CHECKMULTISIG = 0xae,
199 : : OP_CHECKMULTISIGVERIFY = 0xaf,
200 : :
201 : : // expansion
202 : : OP_NOP1 = 0xb0,
203 : : OP_CHECKLOCKTIMEVERIFY = 0xb1,
204 : : OP_NOP2 = OP_CHECKLOCKTIMEVERIFY,
205 : : OP_CHECKSEQUENCEVERIFY = 0xb2,
206 : : OP_NOP3 = OP_CHECKSEQUENCEVERIFY,
207 : : OP_NOP4 = 0xb3,
208 : : OP_NOP5 = 0xb4,
209 : : OP_NOP6 = 0xb5,
210 : : OP_NOP7 = 0xb6,
211 : : OP_NOP8 = 0xb7,
212 : : OP_NOP9 = 0xb8,
213 : : OP_NOP10 = 0xb9,
214 : :
215 : : // Opcode added by BIP 342 (Tapscript)
216 : : OP_CHECKSIGADD = 0xba,
217 : :
218 : : OP_INVALIDOPCODE = 0xff,
219 : : };
220 : :
221 : : // Maximum value that an opcode can be
222 : : inline constexpr unsigned int MAX_OPCODE = OP_NOP10;
223 : :
224 : : std::string GetOpName(opcodetype opcode);
225 : :
226 : : class scriptnum_error : public std::runtime_error
227 : : {
228 : : public:
229 [ + - ]: 58273 : explicit scriptnum_error(const std::string& str) : std::runtime_error(str) {}
[ + - + - ]
230 : : };
231 : :
232 : : class CScriptNum
233 : : {
234 : : /**
235 : : * Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers.
236 : : * The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1],
237 : : * but results may overflow (and are valid as long as they are not used in a subsequent
238 : : * numeric operation). CScriptNum enforces those semantics by storing results as
239 : : * an int64 and allowing out-of-range values to be returned as a vector of bytes but
240 : : * throwing an exception if arithmetic is done or the result is interpreted as an integer.
241 : : */
242 : : public:
243 : :
244 : 13883459 : explicit CScriptNum(const int64_t& n)
245 : 13883459 : {
246 [ + - ]: 11143044 : m_value = n;
[ # # # # ]
[ + + + +
+ + + + +
+ + + +
+ ]
[ + - + -
+ - + + +
+ + + + +
+ + + + +
- ]
247 : : }
248 : :
249 : : static constexpr size_t nDefaultMaxNumSize{4};
250 : :
251 : 5237309 : explicit CScriptNum(const std::vector<unsigned char>& vch, bool fRequireMinimal,
252 : : const size_t nMaxNumSize = nDefaultMaxNumSize)
253 : 5237309 : {
254 [ - + + + ]: 5237309 : if (vch.size() > nMaxNumSize) {
255 [ + - ]: 85348 : throw scriptnum_error("script number overflow");
256 : : }
257 [ + + + + ]: 5194635 : if (fRequireMinimal && vch.size() > 0) {
258 : : // Check that the number is encoded with the minimum possible
259 : : // number of bytes.
260 : : //
261 : : // If the most-significant-byte - excluding the sign bit - is zero
262 : : // then we're not minimal. Note how this test also rejects the
263 : : // negative-zero encoding, 0x80.
264 [ + + ]: 785790 : if ((vch.back() & 0x7f) == 0) {
265 : : // One exception: if there's more than one byte and the most
266 : : // significant bit of the second-most-significant-byte is set
267 : : // it would conflict with the sign bit. An example of this case
268 : : // is +-255, which encode to 0xff00 and 0xff80 respectively.
269 : : // (big-endian).
270 [ + + + + ]: 29968 : if (vch.size() <= 1 || (vch[vch.size() - 2] & 0x80) == 0) {
271 [ + - ]: 28862 : throw scriptnum_error("non-minimally encoded script number");
272 : : }
273 : : }
274 : : }
275 : 5180204 : m_value = set_vch(vch);
276 : 5180204 : }
277 : :
278 [ + + + + : 628163 : inline bool operator==(const int64_t& rhs) const { return m_value == rhs; }
+ + ]
279 : 1666162 : inline auto operator<=>(const int64_t& rhs) const { return m_value <=> rhs; }
[ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ]
[ + + + +
+ + + + +
+ + + + -
+ + + - +
+ + + + +
+ + + + +
+ + + + +
+ + + - +
+ + - + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ]
280 : :
281 [ + + + + ]: 1084423 : inline bool operator==(const CScriptNum& rhs) const { return operator==(rhs.m_value); }
[ + + + +
+ + + + ]
282 : 1042434 : inline auto operator<=>(const CScriptNum& rhs) const { return operator<=>(rhs.m_value); }
[ + + + +
- + + + +
+ - + + +
+ + + + +
+ ]
[ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + ]
283 : :
284 : 326776 : inline CScriptNum operator+( const int64_t& rhs) const { return CScriptNum(m_value + rhs);}
285 : 130332 : inline CScriptNum operator-( const int64_t& rhs) const { return CScriptNum(m_value - rhs);}
286 [ + - + - ]: 177212 : inline CScriptNum operator+( const CScriptNum& rhs) const { return operator+(rhs.m_value); }
287 [ + - + + ]: 173579 : inline CScriptNum operator-( const CScriptNum& rhs) const { return operator-(rhs.m_value); }
288 : :
289 : 34707 : inline CScriptNum& operator+=( const CScriptNum& rhs) { return operator+=(rhs.m_value); }
290 : 49808 : inline CScriptNum& operator-=( const CScriptNum& rhs) { return operator-=(rhs.m_value); }
291 : :
292 [ + + + + : 85010 : inline CScriptNum operator&( const int64_t& rhs) const { return CScriptNum(m_value & rhs);}
+ + ]
293 : 4490 : inline CScriptNum operator&( const CScriptNum& rhs) const { return operator&(rhs.m_value); }
294 : :
295 : 5780 : inline CScriptNum& operator&=( const CScriptNum& rhs) { return operator&=(rhs.m_value); }
296 : :
297 : 1075986 : inline CScriptNum operator-() const
298 : : {
299 [ - + ]: 1075986 : assert(m_value != std::numeric_limits<int64_t>::min());
300 : 1075986 : return CScriptNum(-m_value);
301 : : }
302 : :
303 : 252092 : inline CScriptNum& operator=( const int64_t& rhs)
304 : : {
305 : 264683 : m_value = rhs;
306 : 264683 : return *this;
307 : : }
308 : :
309 : 45346 : inline CScriptNum& operator+=( const int64_t& rhs)
310 : : {
311 [ + + + + : 45346 : assert(rhs == 0 || (rhs > 0 && m_value <= std::numeric_limits<int64_t>::max() - rhs) ||
- + + - -
+ ]
312 : : (rhs < 0 && m_value >= std::numeric_limits<int64_t>::min() - rhs));
313 : 45346 : m_value += rhs;
314 : 45346 : return *this;
315 : : }
316 : :
317 : 56559 : inline CScriptNum& operator-=( const int64_t& rhs)
318 : : {
319 [ + + + + : 56559 : assert(rhs == 0 || (rhs > 0 && m_value >= std::numeric_limits<int64_t>::min() + rhs) ||
- + + - -
+ ]
320 : : (rhs < 0 && m_value <= std::numeric_limits<int64_t>::max() + rhs));
321 : 56559 : m_value -= rhs;
322 : 56559 : return *this;
323 : : }
324 : :
325 : 8922 : inline CScriptNum& operator&=( const int64_t& rhs)
326 : : {
327 : 8922 : m_value &= rhs;
328 : 8922 : return *this;
329 : : }
330 : :
331 : 5120601 : int getint() const
332 : : {
333 [ + - ][ + - : 5120601 : if (m_value > std::numeric_limits<int>::max())
+ - + - ]
334 : : return std::numeric_limits<int>::max();
335 [ + - ][ + - : 5120601 : else if (m_value < std::numeric_limits<int>::min())
+ - + - ]
336 : : return std::numeric_limits<int>::min();
337 [ + + ]: 5120601 : return m_value;
338 : : }
339 : :
340 : 149990 : int64_t GetInt64() const { return m_value; }
341 : :
342 : 12531805 : std::vector<unsigned char> getvch() const
343 : : {
344 [ + - ]: 12531805 : return serialize(m_value);
[ + - + -
+ - + - +
- + - ]
345 : : }
346 : :
347 : 14592911 : static std::vector<unsigned char> serialize(const int64_t& value)
348 : : {
349 [ + + ]: 14592911 : if(value == 0)
350 : 251044 : return std::vector<unsigned char>();
351 : :
352 : 14341867 : std::vector<unsigned char> result;
353 : 14341867 : const bool neg = value < 0;
354 [ + + ]: 14341867 : uint64_t absvalue = neg ? ~static_cast<uint64_t>(value) + 1 : static_cast<uint64_t>(value);
355 : :
356 [ + + ]: 42473428 : while(absvalue)
357 : : {
358 [ + - ]: 28131561 : result.push_back(absvalue & 0xff);
359 : 28131561 : absvalue >>= 8;
360 : : }
361 : :
362 : : // - If the most significant byte is >= 0x80 and the value is positive, push a
363 : : // new zero-byte to make the significant byte < 0x80 again.
364 : :
365 : : // - If the most significant byte is >= 0x80 and the value is negative, push a
366 : : // new 0x80 byte that will be popped off when converting to an integral.
367 : :
368 : : // - If the most significant byte is < 0x80 and the value is negative, add
369 : : // 0x80 to it, since it will be subtracted and interpreted as a negative when
370 : : // converting to an integral.
371 : :
372 [ + + ]: 14341867 : if (result.back() & 0x80)
373 [ + + + - ]: 1100004 : result.push_back(neg ? 0x80 : 0);
374 [ + + ]: 13733697 : else if (neg)
375 : 2420383 : result.back() |= 0x80;
376 : :
377 : 14341867 : return result;
378 : 14341867 : }
379 : :
380 : : private:
381 : 5180204 : static int64_t set_vch(const std::vector<unsigned char>& vch)
382 : : {
383 [ + + ]: 5180204 : if (vch.empty())
384 : : return 0;
385 : :
386 : : int64_t result = 0;
387 [ - + + + ]: 5957160 : for (size_t i = 0; i != vch.size(); ++i)
388 : 3450266 : result |= static_cast<int64_t>(vch[i]) << 8*i;
389 : :
390 : : // If the input vector's most significant byte is 0x80, remove it from
391 : : // the result's msb and return a negative.
392 [ + + ]: 2506894 : if (vch.back() & 0x80)
393 : 148284 : return -((int64_t)(result & ~(0x80ULL << (8 * (vch.size() - 1)))));
394 : :
395 : : return result;
396 : : }
397 : :
398 : : int64_t m_value;
399 : : };
400 : :
401 : : /**
402 : : * We use a prevector for the script to reduce the considerable memory overhead
403 : : * of vectors in cases where they normally contain a small number of small elements.
404 : : */
405 : : using CScriptBase = prevector<36, uint8_t>;
406 : :
407 : : bool GetScriptOp(CScriptBase::const_iterator& pc, CScriptBase::const_iterator end, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet);
408 : :
409 : : /** Serialized script, used inside transaction inputs and outputs */
410 [ + + ][ + + ]: 744949169 : class CScript : public CScriptBase
[ + + + + ]
[ + - + + ]
[ + - + - ]
[ + - + -
+ - ][ + +
+ - + - ]
[ - - + -
+ - ][ - -
+ - + - ]
[ + + + +
+ + + + ]
[ + + + -
+ + + + ]
[ + - + -
+ + + - +
- ][ - - +
- + - + -
+ + ]
[ # # # #
# # # # #
# # # #
# ]
[ - - + -
+ + + - -
+ + - + -
+ - ]
411 : : {
412 : : private:
413 : 25489833 : inline void AppendDataSize(const uint32_t size)
414 : : {
415 [ + + ]: 25489833 : if (size < OP_PUSHDATA1) {
416 : 10294513 : insert(end(), static_cast<value_type>(size));
417 [ + + ]: 15195320 : } else if (size <= 0xff) {
418 : 15160874 : insert(end(), OP_PUSHDATA1);
419 : 15160874 : insert(end(), static_cast<value_type>(size));
420 [ + + ]: 34446 : } else if (size <= 0xffff) {
421 : 23128 : insert(end(), OP_PUSHDATA2);
422 : 23128 : value_type data[2];
423 : 23128 : WriteLE16(data, size);
424 : 23128 : insert(end(), std::cbegin(data), std::cend(data));
425 : : } else {
426 : 11318 : insert(end(), OP_PUSHDATA4);
427 : 11318 : value_type data[4];
428 : 11318 : WriteLE32(data, size);
429 : 11318 : insert(end(), std::cbegin(data), std::cend(data));
430 : : }
431 : 25489833 : }
432 : :
433 : 25489833 : void AppendData(std::span<const value_type> data)
434 : : {
435 : 25489833 : insert(end(), data.begin(), data.end());
436 : 25489833 : }
437 : :
438 : : protected:
439 : 3076509 : CScript& push_int64(int64_t n)
440 : : {
441 [ + + ]: 3076509 : if (n == -1 || (n >= 1 && n <= 16))
442 : : {
443 : 907974 : push_back(n + (OP_1 - 1));
444 : : }
445 [ + + ]: 2168535 : else if (n == 0)
446 : : {
447 : 107429 : push_back(OP_0);
448 : : }
449 : : else
450 : : {
451 [ - + ]: 2061106 : *this << CScriptNum::serialize(n);
452 : : }
453 : 3076509 : return *this;
454 : : }
455 : :
456 : : public:
457 [ + - ][ - + : 148027371 : CScript() = default;
- + - + ]
458 : : template <std::input_iterator InputIterator>
459 : 5920053 : CScript(InputIterator first, InputIterator last) : CScriptBase{first, last} { }
460 : :
461 : 11490578996 : SERIALIZE_METHODS(CScript, obj) { READWRITE(AsBase<CScriptBase>(obj)); }
462 : :
463 : : explicit CScript(int64_t b) { operator<<(b); }
464 [ + - ]: 6964 : explicit CScript(opcodetype b) { operator<<(b); }
465 : : explicit CScript(const CScriptNum& b) { operator<<(b); }
466 : : // delete non-existent constructor to defend against future introduction
467 : : // e.g. via prevector
468 : : explicit CScript(const std::vector<unsigned char>& b) = delete;
469 : :
470 : : /** Delete non-existent operator to defend against future introduction */
471 : : CScript& operator<<(const CScript& b) = delete;
472 : :
473 [ + - ]: 3070159 : CScript& operator<<(int64_t b) LIFETIMEBOUND { return push_int64(b); }
[ + - + - ]
474 : :
475 : 11365419 : CScript& operator<<(opcodetype opcode) LIFETIMEBOUND
476 : : {
477 [ - + ]: 11365419 : if (opcode < 0 || opcode > 0xff)
478 [ # # ]: 0 : throw std::runtime_error("CScript::operator<<(): invalid opcode");
479 : 11365419 : insert(end(), (unsigned char)opcode);
480 : 11365419 : return *this;
481 : : }
482 : :
483 : 339560 : CScript& operator<<(const CScriptNum& b) LIFETIMEBOUND
484 : : {
485 [ - + ]: 339560 : *this << b.getvch();
486 : 339560 : return *this;
487 : : }
488 : :
489 : 25489833 : CScript& operator<<(std::span<const std::byte> b) LIFETIMEBOUND
490 : : {
491 : 25489833 : AppendDataSize(b.size());
492 : 25489833 : AppendData({reinterpret_cast<const value_type*>(b.data()), b.size()});
493 : 25489833 : return *this;
494 : : }
495 : :
496 : : // For compatibility reasons. In new code, prefer using std::byte instead of uint8_t.
497 : 25478529 : CScript& operator<<(std::span<const value_type> b) LIFETIMEBOUND
498 : : {
499 : 25478529 : return *this << std::as_bytes(b);
500 : : }
501 : :
502 : 89954305 : bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
503 : : {
504 : 89954305 : return GetScriptOp(pc, end(), opcodeRet, &vchRet);
505 : : }
506 : :
507 : 539518755 : bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
508 : : {
509 : 539518755 : return GetScriptOp(pc, end(), opcodeRet, nullptr);
510 : : }
511 : :
512 : : /** Encode/decode small integers: */
513 : 122134858 : static int DecodeOP_N(opcodetype opcode)
514 : : {
515 [ + + ]: 122134858 : if (opcode == OP_0)
516 : : return 0;
517 [ - + ]: 2698197 : assert(opcode >= OP_1 && opcode <= OP_16);
518 : 2698197 : return (int)opcode - (int)(OP_1 - 1);
519 : : }
520 : 31401 : static opcodetype EncodeOP_N(int n)
521 : : {
522 [ - + ]: 31401 : assert(n >= 0 && n <= 16);
523 [ + + ]: 31401 : if (n == 0)
524 : : return OP_0;
525 : 31400 : return (opcodetype)(OP_1+n-1);
526 : : }
527 : :
528 : : /**
529 : : * Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
530 : : * as 20 sigops. With pay-to-script-hash, that changed:
531 : : * CHECKMULTISIGs serialized in scriptSigs are
532 : : * counted more accurately, assuming they are of the form
533 : : * ... OP_N CHECKMULTISIG ...
534 : : */
535 : : unsigned int GetSigOpCount(bool fAccurate) const;
536 : :
537 : : /**
538 : : * Accurately count sigOps, including sigOps in
539 : : * pay-to-script-hash transactions:
540 : : */
541 : : unsigned int GetSigOpCount(const CScript& scriptSig) const;
542 : :
543 : : /*
544 : : * OP_1 <0x4e73>
545 : : */
546 : : bool IsPayToAnchor() const;
547 : : /** Checks if output of IsWitnessProgram comes from a P2A output script
548 : : */
549 : : static bool IsPayToAnchor(int version, const std::vector<unsigned char>& program);
550 : :
551 : : bool IsPayToScriptHash() const;
552 : : bool IsPayToWitnessScriptHash() const;
553 : : bool IsWitnessProgram(int& version, std::vector<unsigned char>& program) const;
554 : :
555 : : bool IsPayToTaproot() const;
556 : :
557 : : /** Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical). */
558 : : bool IsPushOnly(const_iterator pc) const;
559 : : bool IsPushOnly() const;
560 : :
561 : : /** Check if the script contains valid OP_CODES */
562 : : bool HasValidOps() const;
563 : :
564 : : /**
565 : : * Returns whether the script is guaranteed to fail at execution,
566 : : * regardless of the initial stack. This allows outputs to be pruned
567 : : * instantly when entering the UTXO set.
568 : : */
569 : 98756421 : bool IsUnspendable() const
570 : : {
571 : 199046254 : return (size() > 0 && *begin() == OP_RETURN) || (size() > MAX_SCRIPT_SIZE);
[ + + + +
+ + + + +
+ + + ]
572 : : }
573 : :
574 : 78333461 : void clear()
575 : : {
576 : : // The default prevector::clear() does not release memory
577 : 78333461 : CScriptBase::clear();
578 : 78333461 : shrink_to_fit();
579 : 78333461 : }
580 : : };
581 : :
582 : : /** A witness stack. Elements are accessed as spans, by forward iteration or by index. A witness
583 : : * can only be constructed as a whole (from a vector of its elements), not modified.
584 : : *
585 : : * The stack is stored as its serialization (the CompactSize-encoded number of elements, followed
586 : : * by each element as a CompactSize-prefixed byte string), in a single allocation. Access by index
587 : : * is O(n) in the position from the bottom of the stack.
588 : : */
589 [ - + ]: 29851648 : class CScriptWitness
[ + + - - ]
[ - + + - ]
[ - + + +
+ + ][ + -
+ - - - -
- ][ - + +
- - + +
- ]
[ + + - -
- - - - -
- - - -
- ]
590 : : {
591 : : /** Null pointer for an empty stack. Otherwise, it points to a header followed by the stack's
592 : : * serialization. For example, the stack {{0xaa}, {}, {0xbb, 0xcc}} is stored as (bytes in
593 : : * hex):
594 : : *
595 : : * |<- header -->|<--------- serialization ---------->|
596 : : * 0 1 3 4 (offsets within the serialization)
597 : : * +-------------+------+---------+------+------------+
598 : : * | 07 00 00 00 | 03 | 01 aa | 00 | 02 bb cc |
599 : : * +-------------+------+---------+------+------------+
600 : : * | | | | |
601 : : * | | | | element 2
602 : : * | | | element 1 (empty)
603 : : * | | element 0: its size (CompactSize), then its bytes
604 : : * | number of elements (CompactSize)
605 : : * size of the serialization (4 bytes, little endian)
606 : : */
607 : : std::unique_ptr<std::byte[]> m_data;
608 : : static constexpr size_t HEADER_SIZE{4};
609 : :
610 : : /** The serialization of the stack. For an empty stack that is a single zero byte, stored outside
611 : : * m_data. As it was produced by this class, ReadCompactSize cannot fail on it, so the accessors
612 : : * below are noexcept. They read it without range check, as a stack constructed from vectors may
613 : : * have more than MAX_SIZE elements, or elements larger than that.
614 : : */
615 : 160342445 : std::span<const std::byte> Data() const noexcept LIFETIMEBOUND
616 : : {
617 : 160342445 : static constexpr std::byte EMPTY_SERIALIZATION[1]{};
618 [ + + ]: 160342445 : if (!m_data) return EMPTY_SERIALIZATION;
619 : 151274829 : return {m_data.get() + HEADER_SIZE, ReadLE32(m_data.get())};
620 : : }
621 : : /** Allocate m_data for a non-empty stack whose serialization has the given size, and write the
622 : : * header. Returns where the serialization goes, which the caller must fill. */
623 : : std::span<std::byte> Allocate(uint64_t size) LIFETIMEBOUND;
624 : :
625 : : public:
626 : : /** Forward iterator over the elements of the stack, exposing them as spans. */
627 : : class Iterator
628 : : {
629 : : std::span<const std::byte> m_rest; //!< The serialization of the remaining elements.
630 : :
631 : : friend CScriptWitness;
632 : 13653630 : explicit Iterator(std::span<const std::byte> rest LIFETIMEBOUND) noexcept : m_rest{rest} {}
633 : :
634 : : public:
635 : : using iterator_category = std::forward_iterator_tag;
636 : : using value_type = std::span<const unsigned char>;
637 : : using difference_type = std::ptrdiff_t;
638 : : using pointer = void;
639 : : using reference = value_type;
640 : :
641 : : Iterator() noexcept = default;
642 : 24603931 : value_type operator*() const noexcept
643 : : {
644 : 24603931 : SpanReader reader{m_rest};
645 : 24603931 : const auto len = ReadCompactSize(reader, /*range_check=*/false);
646 : : // What the reader has left starts with the element. The serialization is std::byte, but elements are
647 : : // returned as unsigned char, like other script data.
648 : 24603931 : return UCharSpanCast(m_rest.last(reader.size()).first(len));
649 : : }
650 : 20294778 : Iterator& operator++() noexcept LIFETIMEBOUND
651 : : {
652 : 20294778 : SpanReader reader{m_rest};
653 : 20294778 : const auto len = ReadCompactSize(reader, /*range_check=*/false);
654 : : // Skip the element, which is at the start of what the reader has left.
655 : 20294778 : m_rest = m_rest.last(reader.size() - len);
656 : 20294778 : return *this;
657 : : }
658 : : Iterator operator++(int) noexcept { auto ret{*this}; ++*this; return ret; }
659 : : /** Iterators over the same stack are equal if they point to the same remaining elements. */
660 [ + + ]: 17607025 : friend bool operator==(const Iterator& a, const Iterator& b) noexcept { return SameSpan(a.m_rest, b.m_rest); }
661 : : };
662 : : using iterator = Iterator;
663 : : using const_iterator = Iterator;
664 : :
665 [ - + - + ]: 47478834 : CScriptWitness() = default;
666 : : explicit CScriptWitness(const std::vector<std::vector<unsigned char>>& stack);
667 : : CScriptWitness(const CScriptWitness& other);
668 : 2585328 : CScriptWitness& operator=(const CScriptWitness& other)
669 : : {
670 [ + - ]: 5170656 : if (this != &other) *this = CScriptWitness{other};
671 : 2585328 : return *this;
672 : : }
673 : : /** Moving leaves the source empty. */
674 : 0 : CScriptWitness(CScriptWitness&&) noexcept = default;
675 [ - + ]: 25089895 : CScriptWitness& operator=(CScriptWitness&&) noexcept = default;
[ + + + + ]
[ - + - + ]
[ + + + +
+ + ][ - +
- + - + -
+ ][ - - -
- + + - -
- - ]
[ - + - +
- + - + -
- - - ]
[ + + - +
- + - + -
+ - + - -
- - ]
[ + + - +
+ + - + -
+ - + + +
- - - - ]
676 : :
677 [ + + ]: 97874399 : bool empty() const noexcept { return !m_data; }
[ + + - - ]
[ + + - -
+ + ][ # #
# # # # ]
[ + + + +
- + - - ]
[ - - - -
+ + + + -
- ]
[ - - + +
- - + + +
+ + + + +
- - ]
678 : :
679 : : /** Number of elements. */
680 : 29842935 : size_t size() const noexcept
681 : : {
682 [ + + ]: 29842935 : if (!m_data) return 0;
683 : 28676629 : SpanReader reader{Data()};
684 : 28676629 : return ReadCompactSize(reader, /*range_check=*/false);
685 : : }
686 : 16077737 : Iterator begin() const noexcept LIFETIMEBOUND
687 : : {
688 [ + + ]: 16077737 : if (!m_data) return end();
689 : 13653630 : const auto data = Data();
690 : 13653630 : SpanReader reader{data};
691 : 13653630 : ReadCompactSize(reader, /*range_check=*/false);
692 : : // The elements are what follows the number of elements.
693 : 13653630 : return Iterator{data.last(reader.size())};
694 : : }
695 : 6573037 : Iterator end() const noexcept LIFETIMEBOUND
696 : : {
697 : 6573037 : return Iterator{Data().last(0)};
698 : : }
699 : : /** The first (bottom) element. The stack must not be empty. */
700 : 0 : std::span<const unsigned char> front() const noexcept LIFETIMEBOUND { return *begin(); }
701 : : /** The last (top) element. This is O(n). The stack must not be empty. */
702 : 7039709 : std::span<const unsigned char> back() const noexcept LIFETIMEBOUND { return (*this)[size() - 1]; }
703 : : /** The element at a given index (from the bottom), which must exist. This is O(index), so avoid it in loops over
704 : : * the elements; iterate instead. */
705 : : std::span<const unsigned char> operator[](size_t index) const noexcept LIFETIMEBOUND;
706 : :
707 : : /** The elements, bottom to top, as vectors. For code that needs to modify or take ownership of them (e.g. to
708 : : * execute a script with them as its initial stack). */
709 : : std::vector<std::vector<unsigned char>> ToVectors() const;
710 : :
711 : : /** The dynamic memory usage of the stack, including that of its elements. */
712 : : size_t DynamicMemoryUsage() const noexcept;
713 : :
714 : : template <typename Stream>
715 : 65343299 : void Serialize(Stream& s) const
716 : : {
717 : 65343299 : s.write(Data());
718 : 65343299 : }
719 : :
720 : : /** Deserialize a witness stack, with the same semantics (and failures) as deserializing a
721 : : * std::vector<std::vector<unsigned char>>. */
722 : : template <typename Stream>
723 : 1577791 : void Unserialize(Stream& s)
724 : : {
725 : : try {
726 [ + + ][ + + ]: 1577791 : std::vector<std::vector<unsigned char>> stack;
727 : 1574957 : s >> stack;
728 [ + - - + ]: 3149914 : *this = CScriptWitness{stack};
[ + - - + ]
729 [ + - ][ + - ]: 1580625 : } catch (const std::length_error&) {
730 : : // A stack that is too large to store is reported like other deserialization failures.
731 [ - - ][ - - ]: 0 : throw std::ios_base::failure("Witness stack too large");
732 : : }
733 : 1574957 : }
734 : :
735 : : std::string ToString() const;
736 : :
737 : : /** Witnesses are equal exactly when their stacks are, as a stack has only one serialization. */
738 : 54221 : friend bool operator==(const CScriptWitness& a, const CScriptWitness& b) noexcept
739 : : {
740 : : // Compared as unsigned chars, for which std::ranges::equal uses memcmp (unlike for std::byte).
741 : 54221 : return std::ranges::equal(UCharSpanCast(a.Data()), UCharSpanCast(b.Data()));
742 : : }
743 : : };
744 : :
745 : : // A CScriptWitness is a multi-pass range over its elements.
746 : : static_assert(std::ranges::forward_range<const CScriptWitness>);
747 : :
748 : : /** A reference to a CScript: the Hash160 of its serialization */
749 : : class CScriptID : public BaseHash<uint160>
750 : : {
751 : : public:
752 : 3231361 : CScriptID() : BaseHash() {}
753 : : explicit CScriptID(const CScript& in);
754 [ + - ]: 852569 : explicit CScriptID(const uint160& in) : BaseHash(in) {}
[ + - + - ]
[ + - + -
+ - ]
755 : : };
756 : :
757 : : /** Test for OP_SUCCESSx opcodes as defined by BIP342. */
758 : : bool IsOpSuccess(const opcodetype& opcode);
759 : :
760 : : bool CheckMinimalPush(const std::vector<unsigned char>& data, opcodetype opcode);
761 : :
762 : : /** Build a script by concatenating other scripts, or any argument accepted by CScript::operator<<. */
763 : : template<typename... Ts>
764 : 3315309 : CScript BuildScript(Ts&&... inputs)
765 : : {
766 : 3315309 : CScript ret;
767 : 3315309 : int cnt{0};
768 : :
769 : 23478318 : ([&ret, &cnt] (Ts&& input) {
770 : : if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<Ts>>, CScript>) {
771 : : // If it is a CScript, extend ret with it. Move or copy the first element instead.
772 : 2774920 : if (cnt == 0) {
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ]
[ + - + -
+ - + - +
- + - - +
- + + - -
+ - + - +
+ - - + +
- - + + -
- + + - -
+ - + + -
- + - + ]
773 : 1222867 : ret = std::forward<Ts>(input);
774 : : } else {
775 : 3104106 : ret.insert(ret.end(), input.begin(), input.end());
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ]
[ - - - -
- - - - -
- - - + +
+ + - - +
+ + + + +
- - + + -
- + + - -
+ + - - +
+ + + - -
+ + + + ]
776 : : }
777 : : } else {
778 : : // Otherwise invoke CScript::operator<<.
779 : 5051186 : ret << input;
[ - - - -
- - - - -
- - - ]
[ - + - +
- + - + -
+ - + - +
- + - + -
+ ]
780 : : }
781 : 7826106 : cnt++;
782 [ + - ][ + - ]: 3315309 : } (std::forward<Ts>(inputs)), ...);
[ + - ][ + - ]
[ + - + - ]
[ + - + - ]
[ + - + - ]
[ + - + - ]
[ + - + -
+ - ][ + -
+ - + - ]
[ + - + -
+ - ][ + -
+ - + - ]
[ + - + -
+ - + - ]
[ + - + -
+ - + - +
- ]
783 : :
784 : 3315309 : return ret;
785 : 0 : }
786 : :
787 : : #endif // BITCOIN_SCRIPT_SCRIPT_H
|