Skip to main content

tari_script/
op_codes.rs

1// Copyright 2020. The Tari Project
2// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
3// following conditions are met:
4// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
5// disclaimer.
6// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
7// following disclaimer in the documentation and/or other materials provided with the distribution.
8// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
9// products derived from this software without specific prior written permission.
10// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
11// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
13// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
14// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
15// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
16// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17
18use std::{fmt, ops::Deref};
19
20use integer_encoding::VarInt;
21use serde::{Deserialize, Serialize};
22use tari_crypto::{compressed_key::CompressedKey, ristretto::RistrettoPublicKey, tari_utilities::ByteArray};
23use tari_max_size::MaxSizeVecError;
24use tari_utilities::{ByteArrayError, hex::Hex};
25
26use super::ScriptError;
27
28pub type HashValue = [u8; 32];
29pub type ScalarValue = [u8; 32];
30pub type Message = [u8; MESSAGE_LENGTH];
31
32const PUBLIC_KEY_LENGTH: usize = 32;
33const MESSAGE_LENGTH: usize = 32;
34type MultiSigArgs = (u8, u8, Vec<CompressedKey<RistrettoPublicKey>>, Box<Message>, usize);
35
36/// Convert a slice into a HashValue.
37///
38/// Returns [ScriptError::InvalidData] if the slice is not exactly 32 bytes long.
39pub fn slice_to_hash(slice: &[u8]) -> Result<HashValue, ScriptError> {
40    HashValue::try_from(slice).map_err(|_| ScriptError::InvalidData)
41}
42
43/// Convert a slice into a Boxed HashValue.
44///
45/// Returns [ScriptError::InvalidData] if the slice is not exactly 32 bytes long.
46pub fn slice_to_boxed_hash(slice: &[u8]) -> Result<Box<HashValue>, ScriptError> {
47    Ok(Box::new(slice_to_hash(slice)?))
48}
49
50/// Convert a slice into a Message.
51///
52/// Returns [ScriptError::InvalidData] if the slice is not exactly `MESSAGE_LENGTH` (32) bytes long.
53pub fn slice_to_message(slice: &[u8]) -> Result<Message, ScriptError> {
54    Message::try_from(slice).map_err(|_| ScriptError::InvalidData)
55}
56
57/// Convert a slice into a Boxed Message.
58///
59/// Returns [ScriptError::InvalidData] if the slice is not exactly `MESSAGE_LENGTH` (32) bytes long.
60pub fn slice_to_boxed_message(slice: &[u8]) -> Result<Box<Message>, ScriptError> {
61    Ok(Box::new(slice_to_message(slice)?))
62}
63
64/// Returns the bytes following an opcode byte and the `size`-byte varint that succeeds it.
65fn bytes_after_varint(bytes: &[u8], size: usize) -> Result<&[u8], ScriptError> {
66    bytes
67        .get(size.checked_add(1).ok_or(ScriptError::InvalidData)?..)
68        .ok_or(ScriptError::InvalidData)
69}
70
71/// Convert a slice into a vector of Public Keys.
72pub fn slice_to_vec_pubkeys(slice: &[u8], num: usize) -> Result<Vec<CompressedKey<RistrettoPublicKey>>, ScriptError> {
73    let required_len = num.checked_mul(PUBLIC_KEY_LENGTH).ok_or(ScriptError::InvalidData)?;
74    if slice.len() < required_len {
75        return Err(ScriptError::InvalidData);
76    }
77
78    let public_keys = slice
79        .as_chunks::<PUBLIC_KEY_LENGTH>()
80        .0
81        .iter()
82        .take(num)
83        .map(|chunk| CompressedKey::from_canonical_bytes(chunk))
84        .collect::<Result<Vec<CompressedKey<RistrettoPublicKey>>, ByteArrayError>>()?;
85
86    Ok(public_keys)
87}
88
89// Opcode constants: Block Height Checks
90const OP_CHECK_HEIGHT_VERIFY: u8 = 0x66;
91const OP_CHECK_HEIGHT: u8 = 0x67;
92const OP_COMPARE_HEIGHT_VERIFY: u8 = 0x68;
93const OP_COMPARE_HEIGHT: u8 = 0x69;
94
95// Opcode constants: Stack Manipulation
96const OP_DROP: u8 = 0x70;
97const OP_DUP: u8 = 0x71;
98const OP_REV_ROT: u8 = 0x72;
99const OP_PUSH_HASH: u8 = 0x7a;
100const OP_PUSH_ZERO: u8 = 0x7b;
101const OP_NOP: u8 = 0x73;
102const OP_PUSH_ONE: u8 = 0x7c;
103const OP_PUSH_INT: u8 = 0x7d;
104const OP_PUSH_PUBKEY: u8 = 0x7e;
105
106// Opcode constants: Math Operations
107const OP_EQUAL: u8 = 0x80;
108const OP_EQUAL_VERIFY: u8 = 0x81;
109const OP_ADD: u8 = 0x93;
110const OP_SUB: u8 = 0x94;
111const OP_GE_ZERO: u8 = 0x82;
112const OP_GT_ZERO: u8 = 0x83;
113const OP_LE_ZERO: u8 = 0x84;
114const OP_LT_ZERO: u8 = 0x85;
115
116// Opcode constants: Boolean Logic
117pub const OP_OR_VERIFY: u8 = 0x64;
118pub const OP_OR: u8 = 0x65;
119
120// Opcode constants: Cryptographic Operations
121const OP_CHECK_SIG: u8 = 0xac;
122const OP_CHECK_SIG_VERIFY: u8 = 0xad;
123const OP_CHECK_MULTI_SIG: u8 = 0xae;
124const OP_CHECK_MULTI_SIG_VERIFY: u8 = 0xaf;
125const OP_HASH_BLAKE256: u8 = 0xb0;
126const OP_HASH_SHA256: u8 = 0xb1;
127const OP_HASH_SHA3: u8 = 0xb2;
128const OP_TO_RISTRETTO_POINT: u8 = 0xb3;
129const OP_CHECK_MULTI_SIG_VERIFY_AGGREGATE_PUB_KEY: u8 = 0xb4;
130
131// Opcode constants: Miscellaneous
132const OP_RETURN: u8 = 0x60;
133const OP_IF_THEN: u8 = 0x61;
134const OP_ELSE: u8 = 0x62;
135const OP_END_IF: u8 = 0x63;
136
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub enum Opcode {
139    // Block Height Checks
140    /// Compare the current block height to `height`. Fails with
141    /// `IncompatibleTypes` if u64 is not a valid 64-bit unsigned integer. Fails with `VerifyFailed` if the block
142    /// height < `height`.
143    CheckHeightVerify(u64),
144    /// Pushes the value of (the current tip height - `height`) to the stack. In
145    /// other words, the top of the stack will hold the height difference between `height` and the current height.
146    /// If the chain has progressed beyond `height`, the value is positive; and negative if the chain has yet to
147    /// reach `height`. Fails with `IncompatibleTypes` if u64 is not a valid 64-bit unsigned integer. Fails with
148    /// `StackOverflow` if the stack would exceed the max stack height.
149    CheckHeight(u64),
150    /// Pops the top of the stack as an unsigned (u64) `height` and compares it to the current block height.
151    /// Fails with `StackUnderflow` if the stack is empty. Fails with `InvalidInput` if the top of the stack is not a
152    /// `Number`. Fails with `ValueExceedsBounds` if the `Number` is negative (it cannot be converted to a u64).
153    /// Fails with `VerifyFailed` if the block height < `height`.
154    ///
155    /// Note that this differs from `CompareHeight`, which pops a signed (i64) value.
156    CompareHeightVerify,
157    /// Pops the top of the stack as a signed (i64) `height`, then pushes the value of (the current height - `height`)
158    /// to the stack. In other words, this opcode replaces the top of the stack with the difference between `height`
159    /// and the current height; `height` may be negative. Fails with `StackUnderflow` if the stack is empty. Fails with
160    /// `InvalidInput` if the top of the stack is not a `Number`. Fails with `ValueExceedsBounds` if the current block
161    /// height does not fit in an i64, and with `CompareFailed` if the subtraction overflows.
162    CompareHeight,
163
164    // Stack Manipulation
165    /// No op. Does nothing. Never fails.
166    Nop,
167    /// Pushes a zero onto the stack. This is a very common opcode and has the same effect as PushInt(0) but is more
168    /// compact. Fails with `StackOverflow` if the stack would exceed the max stack height.
169    PushZero,
170    /// Pushes a one onto the stack. This is a very common opcode and has the same effect as PushInt(1) but is more
171    /// compact. Fails with `StackOverflow` if the stack would exceed the max stack height.
172    PushOne,
173    /// Pushes the associated 32-byte value onto the stack. Fails with `IncompatibleTypes` if HashValue is not a valid
174    /// 32 byte sequence. Fails with `StackOverflow` if the stack would exceed the max stack height.
175    PushHash(Box<HashValue>),
176    /// Pushes the associated 64-bit signed integer onto the stack Fails with `IncompatibleTypes` if i64 is not a valid
177    /// 64-bit integer. Fails with `StackOverflow` if the stack would exceed the max stack height.
178    PushInt(i64),
179    /// Pushes the associated 32-byte value onto the stack. It will be interpreted as a public key or a commitment.
180    /// Fails with `IncompatibleTypes` if RistrettoPublicKey is not a valid 32 byte sequence. Fails with
181    /// `StackOverflow` if the stack would exceed the max stack height.
182    PushPubKey(Box<CompressedKey<RistrettoPublicKey>>),
183    /// Drops the top stack item. Fails with `StackUnderflow` if the stack is empty.
184    Drop,
185    /// Duplicates the top stack item. Fails with `StackUnderflow` if the stack is empty. Fails with `StackOverflow` if
186    /// the stack would exceed the max stack height.
187    Dup,
188    /// Reverse rotation. The top stack item moves into 3rd place (counting from the top). Written bottom-first with
189    /// `c` on top: `[a, b, c] => [c, a, b]`. Fails with `StackUnderflow` if the stack has fewer than three items.
190    RevRot,
191
192    // Math Operations
193    /// Pops the top stack element as `val`. If `val` is greater than or equal to zero, push a 1 to the stack,
194    /// otherwise push 0. Fails with `StackUnderflow` if the stack is empty. Fails with `InvalidInput` if `val` is
195    /// not an integer.
196    GeZero,
197    /// Pops the top stack element as `val`. If `val` is strictly greater than zero, push a 1 to the stack, otherwise
198    /// push 0. Fails with `StackUnderflow` if the stack is empty. Fails with `InvalidInput` if the item is not an
199    /// integer.
200    GtZero,
201    /// Pops the top stack element as `val`. If `val` is less than or equal to zero, push a 1 to the stack, otherwise
202    /// push 0. Fails with `StackUnderflow` if the stack is empty. Fails with `InvalidInput` if the item is not an
203    /// integer.
204    LeZero,
205    /// Pops the top stack element as `val`. If `val` is strictly less than zero, push a 1 to the stack, otherwise push
206    /// 0. Fails with `StackUnderflow` if the stack is empty. Fails with `InvalidInput` if the items is not an
207    /// integer.
208    LtZero,
209    /// Pops two items from the stack and pushes their sum to the stack. Fails with `StackUnderflow` if the stack has
210    /// fewer than two items. Fails with `InvalidInput` if the items cannot be added to each other (e.g. an integer and
211    /// public key).
212    Add,
213    /// Pops two items from the stack and pushes the second minus the top to the stack. Fails with `StackUnderflow` if
214    /// the stack has fewer than two items. Fails with `InvalidInput` if the items cannot be subtracted from each other
215    /// (e.g. an integer and public key).
216    Sub,
217    /// Pops the top two items from the stack, and pushes 1 to the stack if the inputs are exactly equal, 0 otherwise.
218    /// Only two items of the same type can be compared: `Number`, `Hash`, `PublicKey`, `Commitment` or `Signature`.
219    /// Fails with `StackUnderflow` if the stack has fewer than two items. Fails with `IncompatibleTypes` (aborting
220    /// the script, rather than pushing 0) if the two items are of different types (e.g. an integer and a public
221    /// key), or if either item is a `Scalar` (scalars are not comparable, not even with another scalar).
222    Equal,
223    /// Pops the top two items from the stack, and compares their values using the same rules as `Equal`. Fails with
224    /// `StackUnderflow` if the stack has fewer than two items. Fails with `IncompatibleTypes` if the items cannot be
225    /// compared (see `Equal`). Fails with `VerifyFailed` if the top two stack elements are not equal.
226    EqualVerify,
227
228    // Boolean Logic
229    /// Pops `n` + 1 items from the stack (with u8 as `n`). If the last item matches at least one of the first `n`
230    /// items, push 1 onto the stack, otherwise push 0 onto the stack. Fails with `StackUnderflow` if the stack has
231    /// fewer than `n` + 1 items. Fails with `InvalidInput` if the `n` + 1 items are not all of the same type.
232    Or(u8),
233    /// Pops `n` + 1 items from the stack (with u8 as `n`). If the last item matches at least one of the first n items,
234    /// continue. Fails with `StackUnderflow` if the stack has fewer than `n` + 1 items. Fails with `InvalidInput` if
235    /// the `n` + 1 items are not all of the same type. Fails with `VerifyFailed` if the last item does not match at
236    /// least one of the first `n` items.
237    OrVerify(u8),
238
239    // Cryptographic Operations
240    //
241    // The hash opcodes below hash the raw, untagged 32-byte payload of the popped item: no type tag or domain
242    // separator is included. A `Hash`, a `PublicKey` and a `Commitment` holding the same 32 bytes therefore produce
243    // the same digest. `Number`, `Scalar` and `Signature` items cannot be hashed.
244    /// Pops the top element (a `Hash`, `PublicKey` or `Commitment`), hashes its raw 32 bytes with the Blake2b<U32>
245    /// hash function and pushes the result to the stack as a `Hash`. Fails with `StackUnderflow` if the stack is
246    /// empty. Fails with `IncompatibleTypes` if the item is a `Number`, `Scalar` or `Signature`.
247    HashBlake256,
248    /// Pops the top element (a `Hash`, `PublicKey` or `Commitment`), hashes its raw 32 bytes with the SHA256 hash
249    /// function and pushes the result to the stack as a `Hash`. Fails with `StackUnderflow` if the stack is empty.
250    /// Fails with `IncompatibleTypes` if the item is a `Number`, `Scalar` or `Signature`.
251    HashSha256,
252    /// Pops the top element (a `Hash`, `PublicKey` or `Commitment`), hashes its raw 32 bytes with the SHA-3 hash
253    /// function and pushes the result to the stack as a `Hash`. Fails with `StackUnderflow` if the stack is empty.
254    /// Fails with `IncompatibleTypes` if the item is a `Number`, `Scalar` or `Signature`.
255    HashSha3,
256    /// Pops the public key and then the signature from the stack. If signature validation using the 32-byte message
257    /// and public key succeeds, push 1 to the stack, otherwise push 0. Fails with `StackUnderflow` if the stack has
258    /// fewer than 2 items. Fails with `IncompatibleTypes` if the top stack element is not a `PublicKey` or the second
259    /// stack element is not a `Signature`. Fails with `InvalidInput` if the public key cannot be decompressed.
260    ///
261    /// # Security
262    ///
263    /// The message is a constant embedded in the script; it is not derived from the spending transaction. A valid
264    /// signature is therefore replayable: it satisfies this opcode in any script, on any output, that uses the same
265    /// (public key, message) pair. The only binding between a script execution and a particular spend is the
266    /// input's script signature, which is checked outside the script engine. To avoid cross-output replay, use a
267    /// message that is unique to the output, such as the output commitment (as the pre-mine scripts do).
268    CheckSig(Box<Message>),
269    /// Identical to CheckSig, except that nothing is pushed to the stack if the signature is valid, and the operation
270    /// fails with `VerifyFailed` if the signature is invalid. The replay caveat on `CheckSig` applies.
271    CheckSigVerify(Box<Message>),
272    /// Pops exactly `m` signatures from the stack. The multiple signature validation will not succeed if the `m`
273    /// signatures are not unique or if Vec<RistrettoPublicKey> contains a duplicate public key. Each signature is
274    /// validated using the 32-byte message and a public key that match. If signature validation for m unique
275    /// signatures succeeds, push 1 to the stack, otherwise push 0.
276    /// Fails with `IncompatibleTypes` if either `m` (the 1st u8) or `n` (the 2nd u8) is not a valid 8-bit unsigned
277    /// integer, if Vec<RistrettoPublicKey> contains an invalid public key or if Message is not a valid 32-byte
278    /// sequence.
279    /// Fails with `ValueExceedsBounds` if `m` == 0 or if `n` == 0 or if `m` > `n` or if `n` > `MAX_MULTISIG_LIMIT`
280    /// (32) or if the number of public keys provided != `n`.
281    /// Fails with `StackUnderflow` if the stack has fewer than m items.
282    /// Fails with `IncompatibleTypes` if any of the m signatures from the stack is not a valid signature.
283    /// Fails with `InvalidInput` if each of the top m elements is not a Signature.
284    ///
285    /// [TariScript::new](crate::TariScript::new) rejects a `CheckMultiSig*` opcode whose `n` differs from the number
286    /// of public keys, since such an opcode cannot be serialised faithfully.
287    ///
288    /// # Security
289    ///
290    /// As with `CheckSig`, the message is a script constant, so the signatures are replayable across every output
291    /// that shares the same (public keys, message). Binding to a particular spend comes only from the input's script
292    /// signature. Prefer a message unique to the output, such as the output commitment.
293    CheckMultiSig(u8, u8, Vec<CompressedKey<RistrettoPublicKey>>, Box<Message>),
294    /// Identical to CheckMultiSig, except that nothing is pushed to the stack if the multiple signature validation is
295    /// either valid or invalid. Fails with `VerifyFailed` if any signature is invalid.
296    CheckMultiSigVerify(u8, u8, Vec<CompressedKey<RistrettoPublicKey>>, Box<Message>),
297    /// Identical to CheckMultiSig, except that the aggregate of the public keys is pushed to the stack if multiple
298    /// signature validation succeeds. Fails with `VerifyFailed` if any signature is invalid.
299    CheckMultiSigVerifyAggregatePubKey(u8, u8, Vec<CompressedKey<RistrettoPublicKey>>, Box<Message>),
300    /// Pops the top element from the stack (either a scalar or a hash), parses it canonically as a Ristretto secret
301    /// key if possible, computes the corresponding Ristretto public key, and pushes this value to the stack.
302    /// Fails with `StackUnderflow` if the stack is empty.
303    /// Fails with `IncompatibleTypes` if the stack item is not either a scalar or a hash.
304    /// Fails with `InvalidInput` if the stack item cannot be canonically parsed as a Ristretto secret key.
305    ToRistrettoPoint,
306
307    // Miscellaneous
308    /// Always fails with `Return`.
309    Return,
310    /// Pops the top element of the stack into `pred`. If `pred` is 1, the instructions between `IfThen` and `Else` are
311    /// executed. If `pred` is 0, instructions are popped until `Else` or `EndIf` is encountered. If `Else` is
312    /// encountered, instructions are executed until `EndIf` is reached. `EndIf` is a marker opcode and a no-op.
313    /// Fails with `StackUnderflow` if the stack is empty.
314    /// Fails with `InvalidInput` if pred is anything other than 0 or 1.
315    /// Fails with the corresponding failure code if any instruction during execution of the clause causes a failure.
316    IfThen,
317    /// Marks the beginning of the `Else` branch.
318    Else,
319    /// Marks the end of the `IfThen` statement.
320    EndIf,
321}
322
323impl Opcode {
324    pub fn get_version(&self) -> OpcodeVersion {
325        match self {
326            Opcode::CheckHeightVerify(..) |
327            Opcode::CheckHeight(..) |
328            Opcode::CompareHeightVerify |
329            Opcode::CompareHeight |
330            Opcode::Nop |
331            Opcode::PushZero |
332            Opcode::PushOne |
333            Opcode::PushHash(..) |
334            Opcode::PushInt(..) |
335            Opcode::PushPubKey(..) |
336            Opcode::Drop |
337            Opcode::Dup |
338            Opcode::RevRot |
339            Opcode::GeZero |
340            Opcode::GtZero |
341            Opcode::LeZero |
342            Opcode::LtZero |
343            Opcode::Add |
344            Opcode::Sub |
345            Opcode::Equal |
346            Opcode::EqualVerify |
347            Opcode::Or(..) |
348            Opcode::OrVerify(..) |
349            Opcode::HashBlake256 |
350            Opcode::HashSha256 |
351            Opcode::HashSha3 |
352            Opcode::CheckSig(..) |
353            Opcode::CheckSigVerify(..) |
354            Opcode::CheckMultiSig(..) |
355            Opcode::CheckMultiSigVerify(..) |
356            Opcode::CheckMultiSigVerifyAggregatePubKey(..) |
357            Opcode::ToRistrettoPoint |
358            Opcode::Return |
359            Opcode::IfThen |
360            Opcode::Else |
361            Opcode::EndIf => OpcodeVersion::V0,
362        }
363    }
364
365    /// Parse a byte slice into a list of opcodes. Parsing stops with an error as soon as more than `max_opcodes`
366    /// opcodes would be read, so that an oversized script is rejected without materialising all of its opcodes.
367    pub fn parse(bytes: &[u8], max_opcodes: usize) -> Result<Vec<Opcode>, ScriptError> {
368        let mut script = Vec::new();
369        let mut bytes_copy = bytes;
370
371        while !bytes_copy.is_empty() {
372            if script.len() >= max_opcodes {
373                return Err(MaxSizeVecError::MaxSizeVecLengthError {
374                    expected: max_opcodes,
375                    actual: script.len().saturating_add(1),
376                }
377                .into());
378            }
379            let (opcode, bytes_left) = Opcode::read_next(bytes_copy)?;
380            script.push(opcode);
381            bytes_copy = bytes_left;
382        }
383
384        Ok(script)
385    }
386
387    /// Take a byte slice and read the next opcode from it, including any associated data. `read_next` returns a tuple
388    /// of the deserialised opcode, and an updated slice that has the Opcode and data removed.
389    fn read_next(bytes: &[u8]) -> Result<(Opcode, &[u8]), ScriptError> {
390        let code = bytes.first().ok_or(ScriptError::InvalidOpcode)?;
391        #[allow(clippy::enum_glob_use)]
392        use Opcode::*;
393        let scrubbed_bytes = bytes.get(1..).ok_or(ScriptError::InvalidData)?;
394        match *code {
395            OP_CHECK_HEIGHT_VERIFY => {
396                let (height, size) = u64::decode_var(scrubbed_bytes).ok_or(ScriptError::InvalidData)?;
397                Ok((CheckHeightVerify(height), bytes_after_varint(bytes, size)?))
398            },
399            OP_CHECK_HEIGHT => {
400                let (height, size) = u64::decode_var(scrubbed_bytes).ok_or(ScriptError::InvalidData)?;
401                Ok((CheckHeight(height), bytes_after_varint(bytes, size)?))
402            },
403            OP_COMPARE_HEIGHT_VERIFY => Ok((CompareHeightVerify, scrubbed_bytes)),
404            OP_COMPARE_HEIGHT => Ok((CompareHeight, scrubbed_bytes)),
405            OP_NOP => Ok((Nop, scrubbed_bytes)),
406            OP_PUSH_ZERO => Ok((PushZero, scrubbed_bytes)),
407            OP_PUSH_ONE => Ok((PushOne, scrubbed_bytes)),
408            OP_PUSH_HASH => {
409                let hash = slice_to_boxed_hash(bytes.get(1..33).ok_or(ScriptError::InvalidData)?)?;
410                Ok((PushHash(hash), bytes.get(33..).ok_or(ScriptError::InvalidData)?))
411            },
412            OP_PUSH_INT => {
413                let (n, size) = i64::decode_var(scrubbed_bytes).ok_or(ScriptError::InvalidData)?;
414                Ok((PushInt(n), bytes_after_varint(bytes, size)?))
415            },
416            OP_PUSH_PUBKEY => {
417                let p = CompressedKey::from_canonical_bytes(bytes.get(1..33).ok_or(ScriptError::InvalidData)?)?;
418                Ok((
419                    PushPubKey(Box::new(p)),
420                    bytes.get(33..).ok_or(ScriptError::InvalidData)?,
421                ))
422            },
423            OP_DROP => Ok((Drop, scrubbed_bytes)),
424            OP_DUP => Ok((Dup, scrubbed_bytes)),
425            OP_REV_ROT => Ok((RevRot, scrubbed_bytes)),
426            OP_GE_ZERO => Ok((GeZero, scrubbed_bytes)),
427            OP_GT_ZERO => Ok((GtZero, scrubbed_bytes)),
428            OP_LE_ZERO => Ok((LeZero, scrubbed_bytes)),
429            OP_LT_ZERO => Ok((LtZero, scrubbed_bytes)),
430            OP_ADD => Ok((Add, scrubbed_bytes)),
431            OP_SUB => Ok((Sub, scrubbed_bytes)),
432            OP_EQUAL => Ok((Equal, scrubbed_bytes)),
433            OP_EQUAL_VERIFY => Ok((EqualVerify, scrubbed_bytes)),
434            OP_OR => {
435                let n = bytes.get(1).ok_or(ScriptError::InvalidData)?;
436                Ok((Or(*n), bytes.get(2..).ok_or(ScriptError::InvalidData)?))
437            },
438            OP_OR_VERIFY => {
439                let n = bytes.get(1).ok_or(ScriptError::InvalidData)?;
440                Ok((OrVerify(*n), bytes.get(2..).ok_or(ScriptError::InvalidData)?))
441            },
442            OP_HASH_BLAKE256 => Ok((HashBlake256, scrubbed_bytes)),
443            OP_HASH_SHA256 => Ok((HashSha256, scrubbed_bytes)),
444            OP_HASH_SHA3 => Ok((HashSha3, scrubbed_bytes)),
445            OP_CHECK_SIG => {
446                let msg = slice_to_boxed_message(bytes.get(1..33).ok_or(ScriptError::InvalidData)?)?;
447                Ok((CheckSig(msg), bytes.get(33..).ok_or(ScriptError::InvalidData)?))
448            },
449            OP_CHECK_SIG_VERIFY => {
450                let msg = slice_to_boxed_message(bytes.get(1..33).ok_or(ScriptError::InvalidData)?)?;
451                Ok((CheckSigVerify(msg), bytes.get(33..).ok_or(ScriptError::InvalidData)?))
452            },
453            OP_CHECK_MULTI_SIG => {
454                let (m, n, keys, msg, end) = Opcode::read_multisig_args(bytes)?;
455                Ok((
456                    CheckMultiSig(m, n, keys, msg),
457                    bytes.get(end..).ok_or(ScriptError::InvalidData)?,
458                ))
459            },
460            OP_CHECK_MULTI_SIG_VERIFY => {
461                let (m, n, keys, msg, end) = Opcode::read_multisig_args(bytes)?;
462                Ok((
463                    CheckMultiSigVerify(m, n, keys, msg),
464                    bytes.get(end..).ok_or(ScriptError::InvalidData)?,
465                ))
466            },
467            OP_CHECK_MULTI_SIG_VERIFY_AGGREGATE_PUB_KEY => {
468                let (m, n, keys, msg, end) = Opcode::read_multisig_args(bytes)?;
469                Ok((
470                    CheckMultiSigVerifyAggregatePubKey(m, n, keys, msg),
471                    bytes.get(end..).ok_or(ScriptError::InvalidData)?,
472                ))
473            },
474            OP_TO_RISTRETTO_POINT => Ok((ToRistrettoPoint, scrubbed_bytes)),
475            OP_RETURN => Ok((Return, scrubbed_bytes)),
476            OP_IF_THEN => Ok((IfThen, scrubbed_bytes)),
477            OP_ELSE => Ok((Else, scrubbed_bytes)),
478            OP_END_IF => Ok((EndIf, scrubbed_bytes)),
479            _ => Err(ScriptError::InvalidOpcode),
480        }
481    }
482
483    fn read_multisig_args(bytes: &[u8]) -> Result<MultiSigArgs, ScriptError> {
484        if bytes.len() < 3 {
485            return Err(ScriptError::InvalidData);
486        }
487        let m = bytes.get(1).ok_or(ScriptError::InvalidData)?;
488        let n = bytes.get(2).ok_or(ScriptError::InvalidData)?;
489        let num = *n as usize;
490        let len = num
491            .checked_mul(PUBLIC_KEY_LENGTH)
492            .and_then(|v| v.checked_add(3))
493            .ok_or(ScriptError::InvalidData)?;
494        let end = len.checked_add(MESSAGE_LENGTH).ok_or(ScriptError::InvalidData)?;
495        let keys = slice_to_vec_pubkeys(bytes.get(3..len).ok_or(ScriptError::InvalidData)?, num)?;
496        let msg = slice_to_boxed_message(bytes.get(len..end).ok_or(ScriptError::InvalidData)?)?;
497
498        Ok((*m, *n, keys, msg, end))
499    }
500
501    /// Convert an opcode into its binary representation and append it to the array. The function returns the byte slice
502    /// that matches the opcode as a convenience
503    pub fn to_bytes<'a>(&self, array: &'a mut Vec<u8>) -> &'a [u8] {
504        let n = array.len();
505        #[allow(clippy::enum_glob_use)]
506        use Opcode::*;
507        match self {
508            CheckHeightVerify(height) => {
509                array.push(OP_CHECK_HEIGHT_VERIFY);
510                let mut buf = [0u8; 10];
511                let used = height.encode_var(&mut buf[..]);
512                array.extend_from_slice(buf.get(0..used).expect("Length is always valid"));
513            },
514            CheckHeight(height) => {
515                array.push(OP_CHECK_HEIGHT);
516                let mut buf = [0u8; 10];
517                let used = height.encode_var(&mut buf[..]);
518                array.extend_from_slice(buf.get(0..used).expect("Length is always valid"));
519            },
520            CompareHeightVerify => array.push(OP_COMPARE_HEIGHT_VERIFY),
521            CompareHeight => array.push(OP_COMPARE_HEIGHT),
522            Nop => array.push(OP_NOP),
523            PushZero => array.push(OP_PUSH_ZERO),
524            PushOne => array.push(OP_PUSH_ONE),
525            PushHash(h) => {
526                array.push(OP_PUSH_HASH);
527                array.extend_from_slice(h.deref());
528            },
529            PushInt(n) => {
530                array.push(OP_PUSH_INT);
531                let mut buf = [0u8; 10];
532                let used = n.encode_var(&mut buf[..]);
533                array.extend_from_slice(buf.get(0..used).expect("Length is always valid"));
534            },
535            PushPubKey(p) => {
536                array.push(OP_PUSH_PUBKEY);
537                array.extend_from_slice(p.deref().as_bytes());
538            },
539            Drop => array.push(OP_DROP),
540            Dup => array.push(OP_DUP),
541            RevRot => array.push(OP_REV_ROT),
542            GeZero => array.push(OP_GE_ZERO),
543            GtZero => array.push(OP_GT_ZERO),
544            LeZero => array.push(OP_LE_ZERO),
545            LtZero => array.push(OP_LT_ZERO),
546            Add => array.push(OP_ADD),
547            Sub => array.push(OP_SUB),
548            Equal => array.push(OP_EQUAL),
549            EqualVerify => array.push(OP_EQUAL_VERIFY),
550            Or(n) => {
551                array.push(OP_OR);
552                array.push(*n);
553            },
554            OrVerify(n) => {
555                array.push(OP_OR_VERIFY);
556                array.push(*n);
557            },
558            HashBlake256 => array.push(OP_HASH_BLAKE256),
559            HashSha256 => array.push(OP_HASH_SHA256),
560            HashSha3 => array.push(OP_HASH_SHA3),
561            CheckSig(msg) => {
562                array.push(OP_CHECK_SIG);
563                array.extend_from_slice(msg.deref());
564            },
565            CheckSigVerify(msg) => {
566                array.push(OP_CHECK_SIG_VERIFY);
567                array.extend_from_slice(msg.deref());
568            },
569            CheckMultiSig(m, n, public_keys, msg) => {
570                array.extend_from_slice(&[OP_CHECK_MULTI_SIG, *m, *n]);
571                for public_key in public_keys {
572                    array.extend(public_key.as_bytes());
573                }
574                array.extend_from_slice(msg.deref());
575            },
576            CheckMultiSigVerify(m, n, public_keys, msg) => {
577                array.extend_from_slice(&[OP_CHECK_MULTI_SIG_VERIFY, *m, *n]);
578                for public_key in public_keys {
579                    array.extend(public_key.as_bytes());
580                }
581                array.extend_from_slice(msg.deref());
582            },
583            CheckMultiSigVerifyAggregatePubKey(m, n, public_keys, msg) => {
584                array.extend_from_slice(&[OP_CHECK_MULTI_SIG_VERIFY_AGGREGATE_PUB_KEY, *m, *n]);
585                for public_key in public_keys {
586                    array.extend(public_key.as_bytes());
587                }
588                array.extend_from_slice(msg.deref());
589            },
590            ToRistrettoPoint => array.push(OP_TO_RISTRETTO_POINT),
591            Return => array.push(OP_RETURN),
592            IfThen => array.push(OP_IF_THEN),
593            Else => array.push(OP_ELSE),
594            EndIf => array.push(OP_END_IF),
595        };
596
597        array.get(n..).expect("Length is always valid")
598    }
599}
600
601impl fmt::Display for Opcode {
602    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
603        #[allow(clippy::enum_glob_use)]
604        use Opcode::*;
605        match self {
606            CheckHeightVerify(height) => write!(fmt, "CheckHeightVerify({})", *height),
607            CheckHeight(height) => write!(fmt, "CheckHeight({})", *height),
608            CompareHeightVerify => write!(fmt, "CompareHeightVerify"),
609            CompareHeight => write!(fmt, "CompareHeight"),
610            Nop => write!(fmt, "Nop"),
611            PushZero => write!(fmt, "PushZero"),
612            PushOne => write!(fmt, "PushOne"),
613            PushHash(h) => write!(fmt, "PushHash({})", (*h).to_hex()),
614            PushInt(n) => write!(fmt, "PushInt({})", *n),
615            PushPubKey(h) => write!(fmt, "PushPubKey({})", (*h).to_hex()),
616            Drop => write!(fmt, "Drop"),
617            Dup => write!(fmt, "Dup"),
618            RevRot => write!(fmt, "RevRot"),
619            GeZero => write!(fmt, "GeZero"),
620            GtZero => write!(fmt, "GtZero"),
621            LeZero => write!(fmt, "LeZero"),
622            LtZero => write!(fmt, "LtZero"),
623            Add => write!(fmt, "Add"),
624            Sub => write!(fmt, "Sub"),
625            Equal => write!(fmt, "Equal"),
626            EqualVerify => write!(fmt, "EqualVerify"),
627            Or(n) => write!(fmt, "Or({})", *n),
628            OrVerify(n) => write!(fmt, "OrVerify({})", *n),
629            HashBlake256 => write!(fmt, "HashBlake256"),
630            HashSha256 => write!(fmt, "HashSha256"),
631            HashSha3 => write!(fmt, "HashSha3"),
632            CheckSig(msg) => write!(fmt, "CheckSig({})", (*msg).to_hex()),
633            CheckSigVerify(msg) => write!(fmt, "CheckSigVerify({})", (*msg).to_hex()),
634            CheckMultiSig(m, n, public_keys, msg) => {
635                let keys: Vec<String> = public_keys.iter().map(|p| p.to_hex()).collect();
636                write!(
637                    fmt,
638                    "CheckMultiSig({}, {}, [{}], {})",
639                    *m,
640                    *n,
641                    keys.join(", "),
642                    (*msg).to_hex()
643                )
644            },
645            CheckMultiSigVerify(m, n, public_keys, msg) => {
646                let keys: Vec<String> = public_keys.iter().map(|p| p.to_hex()).collect();
647                write!(
648                    fmt,
649                    "CheckMultiSigVerify({}, {}, [{}], {})",
650                    *m,
651                    *n,
652                    keys.join(", "),
653                    (*msg).to_hex()
654                )
655            },
656            CheckMultiSigVerifyAggregatePubKey(m, n, public_keys, msg) => {
657                let keys: Vec<String> = public_keys.iter().map(|p| p.to_hex()).collect();
658                write!(
659                    fmt,
660                    "CheckMultiSigVerifyAggregatePubKey({}, {}, [{}], {})",
661                    *m,
662                    *n,
663                    keys.join(", "),
664                    (*msg).to_hex()
665                )
666            },
667            ToRistrettoPoint => write!(fmt, "ToRistrettoPoint"),
668            Return => write!(fmt, "Return"),
669            IfThen => write!(fmt, "IfThen"),
670            Else => write!(fmt, "Else"),
671            EndIf => write!(fmt, "EndIf"),
672        }
673    }
674}
675
676/// The script opcode version, used by consensus to restrict which opcodes may appear in output scripts.
677///
678/// Note on how this gate is (and is not) applied:
679/// * The parser ([Opcode::parse] / `Opcode::read_next`) rejects any byte it does not recognise with `InvalidOpcode`
680///   *before* the consensus opcode-version range is ever consulted. An opcode that the parser does not know about can
681///   therefore never be admitted by widening the version range alone.
682/// * The consensus version range is only applied to output scripts, not to input scripts.
683///
684/// Adding a new opcode therefore requires changing `read_next` first, and then applying the version range to input
685/// scripts as well, so that a node cannot be made to execute an opcode that is newer than the consensus rules allow.
686#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
687#[repr(u8)]
688pub enum OpcodeVersion {
689    V0 = 0,
690}
691
692#[cfg(test)]
693mod test {
694    #![allow(clippy::indexing_slicing)]
695    use crate::{op_codes::*, script::MAX_SCRIPT_OPCODES};
696
697    #[test]
698    fn empty_script() {
699        assert_eq!(Opcode::parse(&[], MAX_SCRIPT_OPCODES).unwrap(), Vec::new())
700    }
701
702    #[test]
703    fn parse() {
704        let script = [0xFF, 0x71, 0x00];
705        let err = Opcode::parse(&script, MAX_SCRIPT_OPCODES).unwrap_err();
706        assert!(matches!(err, ScriptError::InvalidOpcode));
707
708        let script = [0x60u8, 0x71];
709        let opcodes = Opcode::parse(&script, MAX_SCRIPT_OPCODES).unwrap();
710        let code = opcodes.first().unwrap();
711        assert_eq!(code, &Opcode::Return);
712        let code = opcodes.get(1).unwrap();
713        assert_eq!(code, &Opcode::Dup);
714
715        let err = Opcode::parse(&[0x7a], MAX_SCRIPT_OPCODES).unwrap_err();
716        assert!(matches!(err, ScriptError::InvalidData));
717    }
718
719    #[test]
720    fn parse_stops_at_max_opcodes() {
721        // Exactly the maximum number of opcodes parses
722        let script = vec![OP_NOP; MAX_SCRIPT_OPCODES];
723        assert_eq!(
724            Opcode::parse(&script, MAX_SCRIPT_OPCODES).unwrap().len(),
725            MAX_SCRIPT_OPCODES
726        );
727
728        // One more is rejected as soon as it would be pushed, before any of the following bytes are read (the trailing
729        // invalid opcode would otherwise have produced `InvalidOpcode`)
730        let mut script = vec![OP_NOP; MAX_SCRIPT_OPCODES + 1];
731        script.push(0xFF);
732        let err = Opcode::parse(&script, MAX_SCRIPT_OPCODES).unwrap_err();
733        assert_eq!(
734            err,
735            ScriptError::MaxSizeVecError(MaxSizeVecError::MaxSizeVecLengthError {
736                expected: MAX_SCRIPT_OPCODES,
737                actual: MAX_SCRIPT_OPCODES + 1,
738            })
739        );
740    }
741
742    #[test]
743    fn push_hash() {
744        let (code, b) = Opcode::read_next(b"\x7a/thirty-two~character~hash~val./").unwrap();
745        assert!(matches!(code, Opcode::PushHash(v) if &*v == b"/thirty-two~character~hash~val./"));
746        assert!(b.is_empty());
747    }
748
749    #[test]
750    fn check_height() {
751        fn test_check_height(op: &Opcode, val: u8, display: &str) {
752            // Serialize
753            assert!(matches!(Opcode::read_next(&[val, 255]), Err(ScriptError::InvalidData)));
754            let s = &[val, 63, 1, 2, 3];
755            let (opcode, rem) = Opcode::read_next(s).unwrap();
756            assert_eq!(opcode, *op);
757            assert_eq!(rem, &[1, 2, 3]);
758            // Deserialise
759            let mut arr = vec![1, 2, 3];
760            op.to_bytes(&mut arr);
761            assert_eq!(&arr, &[1, 2, 3, val, 63]);
762            // Format
763            assert_eq!(format!("{op}").as_str(), display);
764        }
765        test_check_height(&Opcode::CheckHeight(63), 0x67, "CheckHeight(63)");
766        test_check_height(&Opcode::CheckHeightVerify(63), 0x66, "CheckHeightVerify(63)");
767    }
768
769    #[test]
770    fn push_int() {
771        // Serialise
772        assert!(matches!(Opcode::read_next(&[0x7d, 255]), Err(ScriptError::InvalidData)));
773        let s = &[OP_PUSH_INT, 130, 4];
774        let (opcode, rem) = Opcode::read_next(s).unwrap();
775        let mut arr = vec![];
776        Opcode::PushInt(257).to_bytes(&mut arr);
777        assert!(matches!(opcode, Opcode::PushInt(257)));
778        assert!(rem.is_empty());
779        // Deserialise
780        let op = Opcode::PushInt(257);
781        let mut arr = vec![];
782        op.to_bytes(&mut arr);
783        assert_eq!(&arr, &[OP_PUSH_INT, 130, 4]);
784        // Format
785        assert_eq!(format!("{op}").as_str(), "PushInt(257)");
786    }
787
788    #[test]
789    fn push_pubkey() {
790        // Serialise
791        assert!(matches!(
792            Opcode::read_next(b"\x7eshort_needs_33_bytes"),
793            Err(ScriptError::InvalidData)
794        ));
795        let key = CompressedKey::<RistrettoPublicKey>::from_hex(
796            "6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401",
797        )
798        .unwrap();
799        let s = &[
800            OP_PUSH_PUBKEY,
801            108,
802            156,
803            180,
804            211,
805            229,
806            115,
807            81,
808            70,
809            33,
810            34,
811            49,
812            15,
813            162,
814            44,
815            144,
816            177,
817            230,
818            223,
819            181,
820            40,
821            214,
822            70,
823            21,
824            54,
825            61,
826            18,
827            97,
828            167,
829            93,
830            163,
831            228,
832            1,
833        ];
834        let op = Opcode::PushPubKey(Box::new(key));
835        let (opcode, rem) = Opcode::read_next(s).unwrap();
836        assert_eq!(opcode, op);
837        assert!(rem.is_empty());
838        // Deserialise
839        let mut arr = vec![];
840        op.to_bytes(&mut arr);
841        assert_eq!(&arr, s);
842        // Format
843        assert_eq!(
844            format!("{op}").as_str(),
845            "PushPubKey(6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401)"
846        );
847    }
848
849    #[test]
850    fn or() {
851        fn test_or(op: &Opcode, val: u8, display: &str) {
852            // Serialise
853            assert!(matches!(Opcode::read_next(&[val]), Err(ScriptError::InvalidData)));
854            let s = &[val, 5, 83];
855            let (opcode, rem) = Opcode::read_next(s).unwrap();
856            assert_eq!(opcode, *op);
857            assert_eq!(rem, &[83]);
858            // Deserialise
859            let mut arr = vec![];
860            op.to_bytes(&mut arr);
861            assert_eq!(&arr, &[val, 5]);
862            // Format
863            assert_eq!(format!("{op}").as_str(), display);
864        }
865        test_or(&Opcode::Or(5), OP_OR, "Or(5)");
866        test_or(&Opcode::OrVerify(5), OP_OR_VERIFY, "OrVerify(5)");
867    }
868
869    #[test]
870    fn check_sig() {
871        fn test_checksig(op: &Opcode, val: u8, display: &str) {
872            // Serialise
873            assert!(matches!(Opcode::read_next(&[val]), Err(ScriptError::InvalidData)));
874            let msg = &[
875                val, 108, 156, 180, 211, 229, 115, 81, 70, 33, 34, 49, 15, 162, 44, 144, 177, 230, 223, 181, 40, 214,
876                70, 21, 54, 61, 18, 97, 167, 93, 163, 228, 1,
877            ];
878            let (opcode, rem) = Opcode::read_next(msg).unwrap();
879            assert_eq!(opcode, *op);
880            assert!(rem.is_empty());
881            // Deserialise
882            let mut arr = vec![];
883            op.to_bytes(&mut arr);
884            assert_eq!(arr, msg);
885            // Format
886            assert_eq!(format!("{op}").as_str(), display);
887        }
888        let msg = &[
889            108, 156, 180, 211, 229, 115, 81, 70, 33, 34, 49, 15, 162, 44, 144, 177, 230, 223, 181, 40, 214, 70, 21,
890            54, 61, 18, 97, 167, 93, 163, 228, 1,
891        ];
892        test_checksig(
893            &Opcode::CheckSig(Box::new(*msg)),
894            OP_CHECK_SIG,
895            "CheckSig(6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401)",
896        );
897        test_checksig(
898            &Opcode::CheckSigVerify(Box::new(*msg)),
899            OP_CHECK_SIG_VERIFY,
900            "CheckSigVerify(6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401)",
901        );
902    }
903
904    #[test]
905    fn check_multisig() {
906        fn test_checkmultisig(op: &Opcode, val: u8, display: &str) {
907            // Serialise
908            assert!(matches!(Opcode::read_next(&[val]), Err(ScriptError::InvalidData)));
909            let bytes = &[
910                val, 1, 2, 156, 139, 197, 249, 13, 34, 17, 145, 116, 142, 141, 215, 104, 111, 9, 225, 17, 75, 75, 173,
911                164, 195, 103, 237, 88, 174, 25, 156, 81, 235, 16, 11, 86, 233, 240, 24, 177, 56, 186, 132, 53, 33,
912                179, 36, 58, 41, 216, 23, 48, 195, 164, 194, 81, 8, 177, 8, 177, 202, 71, 194, 19, 45, 181, 105, 108,
913                156, 180, 211, 229, 115, 81, 70, 33, 34, 49, 15, 162, 44, 144, 177, 230, 223, 181, 40, 214, 70, 21, 54,
914                61, 18, 97, 167, 93, 163, 228, 1,
915            ];
916            let (opcode, rem) = Opcode::read_next(bytes).unwrap();
917            assert_eq!(opcode, *op);
918            assert!(rem.is_empty());
919            // Deserialise
920            let mut arr = vec![];
921            op.to_bytes(&mut arr);
922            assert_eq!(arr, bytes);
923            // Format
924            assert_eq!(format!("{op}").as_str(), display);
925        }
926        let msg = &[
927            108, 156, 180, 211, 229, 115, 81, 70, 33, 34, 49, 15, 162, 44, 144, 177, 230, 223, 181, 40, 214, 70, 21,
928            54, 61, 18, 97, 167, 93, 163, 228, 1,
929        ];
930        let p1 = "9c8bc5f90d221191748e8dd7686f09e1114b4bada4c367ed58ae199c51eb100b";
931        let p2 = "56e9f018b138ba843521b3243a29d81730c3a4c25108b108b1ca47c2132db569";
932        let keys = vec![
933            CompressedKey::<RistrettoPublicKey>::from_hex(p1).unwrap(),
934            CompressedKey::<RistrettoPublicKey>::from_hex(p2).unwrap(),
935        ];
936
937        test_checkmultisig(
938            &Opcode::CheckMultiSig(1, 2, keys.clone(), Box::new(*msg)),
939            OP_CHECK_MULTI_SIG,
940            "CheckMultiSig(1, 2, [9c8bc5f90d221191748e8dd7686f09e1114b4bada4c367ed58ae199c51eb100b, \
941             56e9f018b138ba843521b3243a29d81730c3a4c25108b108b1ca47c2132db569], \
942             6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401)",
943        );
944        test_checkmultisig(
945            &Opcode::CheckMultiSigVerify(1, 2, keys.clone(), Box::new(*msg)),
946            OP_CHECK_MULTI_SIG_VERIFY,
947            "CheckMultiSigVerify(1, 2, [9c8bc5f90d221191748e8dd7686f09e1114b4bada4c367ed58ae199c51eb100b, \
948             56e9f018b138ba843521b3243a29d81730c3a4c25108b108b1ca47c2132db569], \
949             6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401)",
950        );
951        test_checkmultisig(
952            &Opcode::CheckMultiSigVerifyAggregatePubKey(1, 2, keys, Box::new(*msg)),
953            OP_CHECK_MULTI_SIG_VERIFY_AGGREGATE_PUB_KEY,
954            "CheckMultiSigVerifyAggregatePubKey(1, 2, \
955             [9c8bc5f90d221191748e8dd7686f09e1114b4bada4c367ed58ae199c51eb100b, \
956             56e9f018b138ba843521b3243a29d81730c3a4c25108b108b1ca47c2132db569], \
957             6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401)",
958        );
959    }
960
961    #[test]
962    fn deserialise_no_param_opcodes() {
963        fn test_opcode(code: u8, expected: &Opcode) {
964            let s = &[code, 1, 2, 3];
965            let (opcode, rem) = Opcode::read_next(s).unwrap();
966            assert_eq!(opcode, *expected);
967            assert_eq!(rem, &[1, 2, 3]);
968        }
969        test_opcode(OP_COMPARE_HEIGHT_VERIFY, &Opcode::CompareHeightVerify);
970        test_opcode(OP_COMPARE_HEIGHT, &Opcode::CompareHeight);
971        test_opcode(OP_NOP, &Opcode::Nop);
972        test_opcode(OP_PUSH_ZERO, &Opcode::PushZero);
973        test_opcode(OP_PUSH_ONE, &Opcode::PushOne);
974        test_opcode(OP_DROP, &Opcode::Drop);
975        test_opcode(OP_DUP, &Opcode::Dup);
976        test_opcode(OP_REV_ROT, &Opcode::RevRot);
977        test_opcode(OP_GE_ZERO, &Opcode::GeZero);
978        test_opcode(OP_GT_ZERO, &Opcode::GtZero);
979        test_opcode(OP_LE_ZERO, &Opcode::LeZero);
980        test_opcode(OP_LT_ZERO, &Opcode::LtZero);
981        test_opcode(OP_EQUAL, &Opcode::Equal);
982        test_opcode(OP_EQUAL_VERIFY, &Opcode::EqualVerify);
983        test_opcode(OP_HASH_SHA3, &Opcode::HashSha3);
984        test_opcode(OP_HASH_BLAKE256, &Opcode::HashBlake256);
985        test_opcode(OP_HASH_SHA256, &Opcode::HashSha256);
986        test_opcode(OP_TO_RISTRETTO_POINT, &Opcode::ToRistrettoPoint);
987        test_opcode(OP_IF_THEN, &Opcode::IfThen);
988        test_opcode(OP_ELSE, &Opcode::Else);
989        test_opcode(OP_END_IF, &Opcode::EndIf);
990        test_opcode(OP_ADD, &Opcode::Add);
991        test_opcode(OP_SUB, &Opcode::Sub);
992        test_opcode(OP_RETURN, &Opcode::Return);
993    }
994
995    #[test]
996    fn serialise_no_param_opcodes() {
997        fn test_opcode(val: u8, opcode: &Opcode) {
998            let mut arr = vec![];
999            assert_eq!(opcode.to_bytes(&mut arr), &[val]);
1000        }
1001        test_opcode(OP_COMPARE_HEIGHT_VERIFY, &Opcode::CompareHeightVerify);
1002        test_opcode(OP_COMPARE_HEIGHT, &Opcode::CompareHeight);
1003        test_opcode(OP_NOP, &Opcode::Nop);
1004        test_opcode(OP_PUSH_ZERO, &Opcode::PushZero);
1005        test_opcode(OP_PUSH_ONE, &Opcode::PushOne);
1006        test_opcode(OP_DROP, &Opcode::Drop);
1007        test_opcode(OP_DUP, &Opcode::Dup);
1008        test_opcode(OP_REV_ROT, &Opcode::RevRot);
1009        test_opcode(OP_GE_ZERO, &Opcode::GeZero);
1010        test_opcode(OP_GT_ZERO, &Opcode::GtZero);
1011        test_opcode(OP_LE_ZERO, &Opcode::LeZero);
1012        test_opcode(OP_LT_ZERO, &Opcode::LtZero);
1013        test_opcode(OP_EQUAL, &Opcode::Equal);
1014        test_opcode(OP_EQUAL_VERIFY, &Opcode::EqualVerify);
1015        test_opcode(OP_HASH_SHA3, &Opcode::HashSha3);
1016        test_opcode(OP_HASH_BLAKE256, &Opcode::HashBlake256);
1017        test_opcode(OP_HASH_SHA256, &Opcode::HashSha256);
1018        test_opcode(OP_TO_RISTRETTO_POINT, &Opcode::ToRistrettoPoint);
1019        test_opcode(OP_IF_THEN, &Opcode::IfThen);
1020        test_opcode(OP_ELSE, &Opcode::Else);
1021        test_opcode(OP_END_IF, &Opcode::EndIf);
1022        test_opcode(OP_ADD, &Opcode::Add);
1023        test_opcode(OP_SUB, &Opcode::Sub);
1024        test_opcode(OP_RETURN, &Opcode::Return);
1025    }
1026
1027    #[test]
1028    fn display() {
1029        fn test_opcode(opcode: &Opcode, expected: &str) {
1030            let s = format!("{opcode}");
1031            assert_eq!(s.as_str(), expected);
1032        }
1033        test_opcode(&Opcode::CompareHeightVerify, "CompareHeightVerify");
1034        test_opcode(&Opcode::CompareHeight, "CompareHeight");
1035        test_opcode(&Opcode::Nop, "Nop");
1036        test_opcode(&Opcode::PushZero, "PushZero");
1037        test_opcode(&Opcode::PushOne, "PushOne");
1038        test_opcode(&Opcode::Drop, "Drop");
1039        test_opcode(&Opcode::Dup, "Dup");
1040        test_opcode(&Opcode::RevRot, "RevRot");
1041        test_opcode(&Opcode::GeZero, "GeZero");
1042        test_opcode(&Opcode::GtZero, "GtZero");
1043        test_opcode(&Opcode::LeZero, "LeZero");
1044        test_opcode(&Opcode::LtZero, "LtZero");
1045        test_opcode(&Opcode::Equal, "Equal");
1046        test_opcode(&Opcode::EqualVerify, "EqualVerify");
1047        test_opcode(&Opcode::HashSha3, "HashSha3");
1048        test_opcode(&Opcode::HashBlake256, "HashBlake256");
1049        test_opcode(&Opcode::HashSha256, "HashSha256");
1050        test_opcode(&Opcode::ToRistrettoPoint, "ToRistrettoPoint");
1051        test_opcode(&Opcode::IfThen, "IfThen");
1052        test_opcode(&Opcode::Else, "Else");
1053        test_opcode(&Opcode::EndIf, "EndIf");
1054        test_opcode(&Opcode::Add, "Add");
1055        test_opcode(&Opcode::Sub, "Sub");
1056        test_opcode(&Opcode::Return, "Return");
1057    }
1058
1059    #[test]
1060    fn test_slice_to_vec_pubkeys() {
1061        let key = CompressedKey::<RistrettoPublicKey>::from_hex(
1062            "6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401",
1063        )
1064        .unwrap();
1065        let bytes = key.as_bytes();
1066        let vec = [bytes, bytes, bytes].concat();
1067        let slice = vec.as_bytes();
1068        let vec = slice_to_vec_pubkeys(slice, 3).unwrap();
1069        for pk in vec {
1070            assert_eq!(key, pk);
1071        }
1072    }
1073
1074    #[test]
1075    fn test_read_multisig_args() {
1076        let key = CompressedKey::<RistrettoPublicKey>::from_hex(
1077            "6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401",
1078        )
1079        .unwrap();
1080        let bytes = key.as_bytes();
1081        let message = &[
1082            108, 156, 180, 211, 229, 115, 81, 70, 33, 34, 49, 15, 162, 44, 144, 177, 230, 223, 181, 40, 214, 70, 21,
1083            54, 61, 18, 97, 167, 93, 163, 228, 1,
1084        ];
1085        let vec = [&[OP_CHECK_MULTI_SIG, 1, 2], bytes, bytes, message].concat();
1086        let slice = vec.as_bytes();
1087        let (m, n, keys, msg, end) = Opcode::read_multisig_args(slice).unwrap();
1088        assert_eq!(m, 1);
1089        assert_eq!(n, 2);
1090        assert_eq!(*msg, *message);
1091        assert_eq!(end, vec.len());
1092        for p in keys {
1093            assert_eq!(key, p);
1094        }
1095    }
1096
1097    #[test]
1098    fn slice_helpers_reject_wrong_lengths() {
1099        let bytes = [7u8; 33];
1100        assert_eq!(slice_to_hash(&bytes[..32]), Ok([7u8; 32]));
1101        assert_eq!(slice_to_boxed_hash(&bytes[..32]), Ok(Box::new([7u8; 32])));
1102        assert_eq!(slice_to_message(&bytes[..32]), Ok([7u8; 32]));
1103        assert_eq!(slice_to_boxed_message(&bytes[..32]), Ok(Box::new([7u8; 32])));
1104        for len in [0, 1, 31, 33] {
1105            assert_eq!(slice_to_hash(&bytes[..len]), Err(ScriptError::InvalidData));
1106            assert_eq!(slice_to_boxed_hash(&bytes[..len]), Err(ScriptError::InvalidData));
1107            assert_eq!(slice_to_message(&bytes[..len]), Err(ScriptError::InvalidData));
1108            assert_eq!(slice_to_boxed_message(&bytes[..len]), Err(ScriptError::InvalidData));
1109        }
1110    }
1111
1112    /// Pins the current (lenient) varint decoding of `integer-encoding` 3.0.4: a non-minimal encoding of zero is
1113    /// accepted, and re-serialised minimally. If a dependency bump makes the decoder strict, this test must fail,
1114    /// because it would change which scripts are valid (a consensus change).
1115    #[test]
1116    fn non_minimal_varint_is_accepted_pinned() {
1117        let opcodes = Opcode::parse(&[0x67, 0x80, 0x00], MAX_SCRIPT_OPCODES).unwrap();
1118        assert_eq!(opcodes, vec![Opcode::CheckHeight(0)]);
1119        let mut bytes = Vec::new();
1120        opcodes[0].to_bytes(&mut bytes);
1121        assert_eq!(bytes, vec![0x67, 0x00]);
1122
1123        // The same holds for the other varint-carrying opcodes
1124        assert_eq!(
1125            Opcode::parse(&[0x66, 0x81, 0x80, 0x00], MAX_SCRIPT_OPCODES).unwrap(),
1126            vec![Opcode::CheckHeightVerify(1)]
1127        );
1128        // PushInt is zig-zag encoded: 0x02 is 1
1129        assert_eq!(Opcode::parse(&[0x7d, 0x82, 0x00], MAX_SCRIPT_OPCODES).unwrap(), vec![
1130            Opcode::PushInt(1)
1131        ]);
1132    }
1133}