bitcoin/blockdata/script/
instruction.rs1use crate::blockdata::opcodes::{self, Opcode};
4use crate::blockdata::script::{read_uint_iter, Error, PushBytes, Script, ScriptBuf, UintError};
5
6#[derive(Debug, PartialEq, Eq, Copy, Clone)]
8pub enum Instruction<'a> {
9 PushBytes(&'a PushBytes),
11 Op(Opcode),
13}
14
15impl<'a> Instruction<'a> {
16 pub fn opcode(&self) -> Option<Opcode> {
18 match self {
19 Instruction::Op(op) => Some(*op),
20 Instruction::PushBytes(_) => None,
21 }
22 }
23
24 pub fn push_bytes(&self) -> Option<&PushBytes> {
26 match self {
27 Instruction::Op(_) => None,
28 Instruction::PushBytes(bytes) => Some(bytes),
29 }
30 }
31
32 pub fn script_num(&self) -> Option<i64> {
37 match self {
38 Instruction::Op(op) => {
39 let v = op.to_u8();
40 match v {
41 0x51..=0x60 => Some(v as i64 - 0x50),
43 0x4f => Some(-1),
45 _ => None,
46 }
47 }
48 Instruction::PushBytes(bytes) =>
49 super::read_scriptint_non_minimal(bytes.as_bytes()).ok(),
50 }
51 }
52
53 pub(super) fn script_serialized_len(&self) -> usize {
55 match self {
56 Instruction::Op(_) => 1,
57 Instruction::PushBytes(bytes) => ScriptBuf::reserved_len_for_slice(bytes.len()),
58 }
59 }
60}
61
62#[derive(Debug, Clone)]
64pub struct Instructions<'a> {
65 pub(crate) data: core::slice::Iter<'a, u8>,
66 pub(crate) enforce_minimal: bool,
67}
68
69impl<'a> Instructions<'a> {
70 pub fn as_script(&self) -> &'a Script { Script::from_bytes(self.data.as_slice()) }
74
75 pub(super) fn kill(&mut self) {
77 let len = self.data.len();
78 self.data.nth(len.max(1) - 1);
79 }
80
81 pub(super) fn take_slice_or_kill(&mut self, len: u32) -> Result<&'a PushBytes, Error> {
86 let len = len as usize;
87 if self.data.len() >= len {
88 let slice = &self.data.as_slice()[..len];
89 if len > 0 {
90 self.data.nth(len - 1);
91 }
92
93 Ok(slice.try_into().expect("len was created from u32, so can't happen"))
94 } else {
95 self.kill();
96 Err(Error::EarlyEndOfScript)
97 }
98 }
99
100 pub(super) fn next_push_data_len(
101 &mut self,
102 len: PushDataLenLen,
103 min_push_len: usize,
104 ) -> Option<Result<Instruction<'a>, Error>> {
105 let n = match read_uint_iter(&mut self.data, len as usize) {
106 Ok(n) => n,
107 Err(UintError::EarlyEndOfScript) | Err(UintError::NumericOverflow) => {
112 self.kill();
113 return Some(Err(Error::EarlyEndOfScript));
114 }
115 };
116 if self.enforce_minimal && n < min_push_len {
117 self.kill();
118 return Some(Err(Error::NonMinimalPush));
119 }
120 let result = n
121 .try_into()
122 .map_err(|_| Error::NumericOverflow)
123 .and_then(|n| self.take_slice_or_kill(n))
124 .map(Instruction::PushBytes);
125 Some(result)
126 }
127}
128
129pub(super) enum PushDataLenLen {
133 One = 1,
134 Two = 2,
135 Four = 4,
136}
137
138impl<'a> Iterator for Instructions<'a> {
139 type Item = Result<Instruction<'a>, Error>;
140
141 fn next(&mut self) -> Option<Result<Instruction<'a>, Error>> {
142 let &byte = self.data.next()?;
143
144 match Opcode::from(byte).classify(opcodes::ClassifyContext::Legacy) {
147 opcodes::Class::PushBytes(n) => {
148 let n: u32 = n;
150
151 let op_byte = self.data.as_slice().first();
152 match (self.enforce_minimal, op_byte, n) {
153 (true, Some(&op_byte), 1)
154 if op_byte == 0x81 || (op_byte > 0 && op_byte <= 16) =>
155 {
156 self.kill();
157 Some(Err(Error::NonMinimalPush))
158 }
159 (_, None, 0) => {
160 Some(Ok(Instruction::PushBytes(PushBytes::empty())))
163 }
164 _ => Some(self.take_slice_or_kill(n).map(Instruction::PushBytes)),
165 }
166 }
167 opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA1) =>
168 self.next_push_data_len(PushDataLenLen::One, 76),
169 opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA2) =>
170 self.next_push_data_len(PushDataLenLen::Two, 0x100),
171 opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA4) =>
172 self.next_push_data_len(PushDataLenLen::Four, 0x10000),
173 _ => Some(Ok(Instruction::Op(Opcode::from(byte)))),
175 }
176 }
177
178 #[inline]
179 fn size_hint(&self) -> (usize, Option<usize>) {
180 if self.data.len() == 0 {
181 (0, Some(0))
182 } else {
183 (1, Some(self.data.len()))
185 }
186 }
187}
188
189impl<'a> core::iter::FusedIterator for Instructions<'a> {}
190
191#[derive(Debug, Clone)]
197pub struct InstructionIndices<'a> {
198 instructions: Instructions<'a>,
199 pos: usize,
200}
201
202impl<'a> InstructionIndices<'a> {
203 #[inline]
207 pub fn as_script(&self) -> &'a Script { self.instructions.as_script() }
208
209 pub(super) fn from_instructions(instructions: Instructions<'a>) -> Self {
211 InstructionIndices { instructions, pos: 0 }
212 }
213
214 pub(super) fn remaining_bytes(&self) -> usize { self.instructions.as_script().len() }
215
216 pub(super) fn next_with<F: FnOnce(&mut Self) -> Option<Result<Instruction<'a>, Error>>>(
221 &mut self,
222 next_fn: F,
223 ) -> Option<<Self as Iterator>::Item> {
224 let prev_remaining = self.remaining_bytes();
225 let prev_pos = self.pos;
226 let instruction = next_fn(self)?;
227 let consumed = prev_remaining - self.remaining_bytes();
229 self.pos += consumed;
231 Some(instruction.map(move |instruction| (prev_pos, instruction)))
232 }
233}
234
235impl<'a> Iterator for InstructionIndices<'a> {
236 type Item = Result<(usize, Instruction<'a>), Error>;
238
239 fn next(&mut self) -> Option<Self::Item> { self.next_with(|this| this.instructions.next()) }
240
241 #[inline]
242 fn size_hint(&self) -> (usize, Option<usize>) { self.instructions.size_hint() }
243
244 fn nth(&mut self, n: usize) -> Option<Self::Item> {
246 self.next_with(|this| this.instructions.nth(n))
247 }
248}
249
250impl core::iter::FusedIterator for InstructionIndices<'_> {}