1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// SPDX-License-Identifier: CC0-1.0
#[cfg(feature = "alloc")]
#[cfg(feature = "hex")]
use alloc::string::String;
use core::marker::PhantomData;
use core::ops::{
Bound, Index, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
};
#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
use encoding::{Encode, PrefixedBytesEncoder};
use super::{ScriptBuf, P2A_PROGRAM};
use crate::opcodes::all::{OP_CHECKSIG, OP_DUP, OP_EQUAL, OP_EQUALVERIFY, OP_HASH160, OP_RETURN};
use crate::opcodes::{Opcode, OP_PUSHBYTES_2, OP_PUSHBYTES_20, OP_PUSHBYTES_32};
use crate::prelude::{Box, ToOwned, Vec};
use crate::script::{
Builder, RedeemScriptSizeError, ScriptHash, ScriptHashableTag, WScriptHash,
WitnessScriptSizeError,
};
use crate::witness_version::WitnessVersion;
use crate::{ScriptPubKey, WitnessScript};
// Defined in `REPO_DIR/include/newtype.rs`.
crate::transparent_newtype! {
/// Bitcoin script slice.
///
/// *[See also the `bitcoin::script` module](super).*
///
/// `Script` is a script slice, the most primitive script type. It's usually seen in its borrowed
/// form `&Script`. It is always encoded as a series of bytes representing the opcodes and data
/// pushes.
///
/// # Validity
///
/// `Script` does not have any validity invariants - it's essentially just a marked slice of
/// bytes. This is similar to [`Path`](std::path::Path) vs [`OsStr`](std::ffi::OsStr) where they
/// are trivially cast-able to each-other and `Path` doesn't guarantee being a usable FS path but
/// having a newtype still has value because of added methods, readability and basic type checking.
///
/// Although at least data pushes could be checked not to overflow the script, bad scripts are
/// allowed to be in a transaction (outputs just become unspendable) and there even are such
/// transactions in the chain. Thus we must allow such scripts to be placed in the transaction.
///
/// # Slicing safety
///
/// Slicing is similar to how `str` works: some ranges may be incorrect and indexing by
/// `usize` is not supported. However, as opposed to `std`, we have no way of checking
/// correctness without causing linear complexity so there are **no panics on invalid
/// ranges!** If you supply an invalid range, you'll get a garbled script.
///
/// The range is considered valid if it's at a boundary of instruction. Care must be taken
/// especially with push operations because you could get a reference to arbitrary
/// attacker-supplied bytes that look like a valid script.
///
/// It is recommended to use `.instructions()` method to get an iterator over script
/// instructions and work with that instead.
///
/// # Memory safety
///
/// The type is `#[repr(transparent)]` for internal purposes only!
/// No consumer crate may rely on the representation of the struct!
///
/// # Hexadecimal strings
///
/// Scripts are consensus encoded with a length prefix and as a result of this in some places in
/// the ecosystem one will encounter hex strings that include the prefix while in other places
/// the prefix is excluded. To support parsing and formatting scripts as hex we provide a bunch
/// of different APIs and trait implementations. Please see [`examples/script.rs`] for a
/// thorough example of all the APIs.
///
/// [`examples/script.rs`]: <https://github.com/rust-bitcoin/rust-bitcoin/blob/master/bitcoin/examples/script.rs>
///
/// # Bitcoin Core References
///
/// * [CScript definition](https://github.com/bitcoin/bitcoin/blob/d492dc1cdaabdc52b0766bf4cba4bd73178325d0/src/script/script.h#L410)
///
#[derive(PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Script<T>(PhantomData<T>, [u8]);
impl<T> Script<T> {
/// Treat byte slice as `Script`
pub const fn from_bytes(bytes: &_) -> &Self;
/// Treat mutable byte slice as `Script`
pub fn from_bytes_mut(bytes: &mut _) -> &mut Self;
pub(crate) fn from_boxed_bytes(bytes: Box<_>) -> Box<Self>;
pub(crate) fn from_rc_bytes(bytes: Rc<_>) -> Rc<Self>;
pub(crate) fn from_arc_bytes(bytes: Arc<_>) -> Arc<Self>;
}
}
impl<T: 'static> Default for &Script<T> {
#[inline]
fn default() -> Self { Script::new() }
}
impl<T> ToOwned for Script<T> {
type Owned = ScriptBuf<T>;
#[inline]
fn to_owned(&self) -> Self::Owned { ScriptBuf::from_bytes(self.to_vec()) }
}
impl<T> Script<T> {
/// Constructs a new empty script.
#[inline]
pub const fn new() -> &'static Self { Self::from_bytes(&[]) }
/// Returns the script data as a byte slice.
///
/// This is just the script bytes **not** consensus encoding (which includes a length prefix).
#[inline]
pub const fn as_bytes(&self) -> &[u8] { &self.1 }
/// Returns the script data as a mutable byte slice.
///
/// This is just the script bytes **not** consensus encoding (which includes a length prefix).
#[inline]
pub fn as_mut_bytes(&mut self) -> &mut [u8] { &mut self.1 }
/// Returns a copy of the script data.
///
/// This is just the script bytes **not** consensus encoding (which includes a length prefix).
#[inline]
pub fn to_vec(&self) -> Vec<u8> { self.as_bytes().to_owned() }
/// Returns a copy of the script data.
#[inline]
#[deprecated(since = "0.101.0", note = "use to_vec instead")]
pub fn to_bytes(&self) -> Vec<u8> { self.to_vec() }
/// Consensus encodes the script as lower-case hex.
///
/// Consensus encoding includes a length prefix. To hex encode without the length prefix use
/// `to_hex_string_no_length_prefix`.
#[cfg(feature = "alloc")]
#[cfg(feature = "hex")]
pub fn to_hex_string_prefixed(&self) -> String {
use hex::{BytesToHexIter, Case};
let iter = encoding::EncoderByteIter::new(self.encoder());
BytesToHexIter::new(iter, Case::Lower).flatten().map(char::from).collect()
}
/// Encodes the script as lower-case hex.
///
/// This is **not** consensus encoding. The returned hex string will not include the length
/// prefix. See `to_hex_string_prefixed`.
#[cfg(feature = "alloc")]
#[cfg(feature = "hex")]
pub fn to_hex_string_no_length_prefix(&self) -> String {
use hex::DisplayHex as _;
self.as_bytes().to_lower_hex_string()
}
/// Returns the length in bytes of the script.
#[inline]
pub const fn len(&self) -> usize { self.as_bytes().len() }
/// Returns whether the script is the empty script.
#[inline]
pub const fn is_empty(&self) -> bool { self.as_bytes().is_empty() }
/// Converts a [`Box<Script>`](Box) into a [`ScriptBuf`] without copying or allocating.
#[must_use]
#[inline]
pub fn into_script_buf(self: Box<Self>) -> ScriptBuf<T> {
let rw = Box::into_raw(self) as *mut [u8];
// SAFETY: copied from `std`
// The pointer was just created from a box without deallocating
// Casting a transparent struct wrapping a slice to the slice pointer is sound (same
// layout).
let inner = unsafe { Box::from_raw(rw) };
ScriptBuf::from_bytes(Vec::from(inner))
}
/// Gets the hex representation of this script.
///
/// # Returns
///
/// Just the script bytes in hexadecimal **not** consensus encoding of the script i.e., the
/// string will not include a length prefix.
#[cfg(feature = "hex")]
#[inline]
#[deprecated(since = "1.0.0-rc.0", note = "use `format!(\"{var:x}\")` instead")]
pub fn to_hex(&self) -> alloc::string::String { alloc::format!("{:x}", self) }
/// Constructs a new script builder
pub fn builder() -> Builder<T> { Builder::new() }
/// Returns witness version of the script, if any.
///
/// # Returns
///
/// The witness version if this script is found to conform to the SegWit rules:
///
/// > A scriptPubKey (or redeemScript as defined in BIP-0016/P2SH) that consists of a 1-byte
/// > push opcode (for 0 to 16) followed by a data push between 2 and 40 bytes gets a new
/// > special meaning. The value of the first push is called the "version byte". The following
/// > byte vector pushed is called the "witness program".
#[inline]
pub fn witness_version(&self) -> Option<WitnessVersion>
where
T: ScriptHashableTag,
{
let script_len = self.len();
if !(4..=42).contains(&script_len) {
return None;
}
let ver_opcode = Opcode::from(self.as_bytes()[0]); // Version 0 or PUSHNUM_1-PUSHNUM_16
let push_opbyte = self.as_bytes()[1]; // Second byte push opcode 2-40 bytes
// If push_opbyte < OP_PUSHBYTES_2 || push_opbyte > OP_PUSHBYTES_40
if push_opbyte < 0x02 || push_opbyte > 0x28 {
return None;
}
// Check that the rest of the script has the correct size
if script_len - 2 != push_opbyte as usize {
return None;
}
WitnessVersion::try_from(ver_opcode).ok()
}
/// Checks whether a script pubkey is a P2WSH output.
#[inline]
pub fn is_p2wsh(&self) -> bool
where
T: ScriptHashableTag,
{
self.len() == 34
&& self.witness_version() == Some(WitnessVersion::V0)
&& self.as_bytes()[1] == OP_PUSHBYTES_32.to_u8()
}
/// Checks whether a script pubkey is a P2WPKH output.
#[inline]
pub fn is_p2wpkh(&self) -> bool
where
T: ScriptHashableTag,
{
self.len() == 22
&& self.witness_version() == Some(WitnessVersion::V0)
&& self.as_bytes()[1] == OP_PUSHBYTES_20.to_u8()
}
}
impl ScriptPubKey {
/// Checks whether a script pubkey is a Segregated Witness (SegWit) program.
#[inline]
pub fn is_witness_program(&self) -> bool { self.witness_version().is_some() }
/// Checks whether a script pubkey is a P2SH output.
#[inline]
pub fn is_p2sh(&self) -> bool {
self.len() == 23
&& self.as_bytes()[0] == OP_HASH160.to_u8()
&& self.as_bytes()[1] == OP_PUSHBYTES_20.to_u8()
&& self.as_bytes()[22] == OP_EQUAL.to_u8()
}
/// Checks whether a script pubkey is a P2PKH output.
#[inline]
pub fn is_p2pkh(&self) -> bool {
self.len() == 25
&& self.as_bytes()[0] == OP_DUP.to_u8()
&& self.as_bytes()[1] == OP_HASH160.to_u8()
&& self.as_bytes()[2] == OP_PUSHBYTES_20.to_u8()
&& self.as_bytes()[23] == OP_EQUALVERIFY.to_u8()
&& self.as_bytes()[24] == OP_CHECKSIG.to_u8()
}
/// Checks whether a script pubkey is a P2A output.
#[inline]
pub fn is_p2a(&self) -> bool {
self.len() == 4
&& self.witness_version() == Some(WitnessVersion::V1)
&& self.as_bytes()[1] == OP_PUSHBYTES_2.to_u8()
&& self.as_bytes()[2..] == P2A_PROGRAM
}
/// Check if this is a consensus-valid `OP_RETURN` output.
///
/// To validate if the `OP_RETURN` obeys Bitcoin Core's current standardness policy, use
/// `bitcoin::ScriptPubKeyExt::is_standard_op_return()` instead.
#[inline]
pub fn is_op_return(&self) -> bool {
self.as_bytes().first().is_some_and(|&b| b == OP_RETURN.to_u8())
}
}
impl WitnessScript {
/// Returns 256-bit hash of the script for P2WSH outputs.
///
/// # Errors
///
/// Returns an error if the script exceeds 10,000 bytes.
#[inline]
pub fn wscript_hash(&self) -> Result<WScriptHash, WitnessScriptSizeError> {
WScriptHash::from_script(self)
}
}
impl<T: ScriptHashableTag> Script<T> {
/// Returns 160-bit hash of the script for P2SH outputs.
///
/// # Errors
///
/// Returns an error if the script exceeds 520 bytes.
#[inline]
pub fn script_hash(&self) -> Result<ScriptHash, RedeemScriptSizeError> {
ScriptHash::from_script(self)
}
}
impl<T> Encode for Script<T> {
type Encoder<'e>
= ScriptEncoder<'e>
where
Self: 'e;
fn encoder(&self) -> Self::Encoder<'_> {
ScriptEncoder::new(PrefixedBytesEncoder::new(self.as_bytes()))
}
}
encoding::encoder_newtype_exact! {
/// The encoder for the [`Script<T>`] type.
#[derive(Debug, Clone)]
pub struct ScriptEncoder<'e>(PrefixedBytesEncoder<'e>);
}
#[cfg(feature = "arbitrary")]
impl<'a, T> Arbitrary<'a> for &'a Script<T> {
#[inline]
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let v = <&'a [u8]>::arbitrary(u)?;
Ok(Script::from_bytes(v))
}
}
macro_rules! delegate_index {
($($type:ty),* $(,)?) => {
$(
/// Script subslicing operation - read [slicing safety](#slicing-safety)!
impl<T> Index<$type> for Script<T> {
type Output = Self;
#[inline]
fn index(&self, index: $type) -> &Self::Output {
Self::from_bytes(&self.as_bytes()[index])
}
}
)*
}
}
delegate_index!(
Range<usize>,
RangeFrom<usize>,
RangeTo<usize>,
RangeFull,
RangeInclusive<usize>,
RangeToInclusive<usize>,
(Bound<usize>, Bound<usize>)
);