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
use {
crate::{
bytes::{
advance_offset_for_array, check_remaining, optimized_read_compressed_u16, read_byte,
read_slice_data,
},
result::Result,
},
clone_solana_svm_transaction::instruction::SVMInstruction,
core::fmt::{Debug, Formatter},
};
/// Contains metadata about the instructions in a transaction packet.
#[derive(Debug, Default)]
pub(crate) struct InstructionsFrame {
/// The number of instructions in the transaction.
pub(crate) num_instructions: u16,
/// The offset to the first instruction in the transaction.
pub(crate) offset: u16,
}
impl InstructionsFrame {
/// Get the number of instructions and offset to the first instruction.
/// The offset will be updated to point to the first byte after the last
/// instruction.
/// This function will parse each individual instruction to ensure the
/// instruction data is well-formed, but will not cache data related to
/// these instructions.
#[inline(always)]
pub(crate) fn try_new(bytes: &[u8], offset: &mut usize) -> Result<Self> {
// Read the number of instructions at the current offset.
// Each instruction needs at least 3 bytes, so do a sanity check here to
// ensure we have enough bytes to read the number of instructions.
let num_instructions = optimized_read_compressed_u16(bytes, offset)?;
check_remaining(
bytes,
*offset,
3usize.wrapping_mul(usize::from(num_instructions)),
)?;
// We know the offset does not exceed packet length, and our packet
// length is less than u16::MAX, so we can safely cast to u16.
let instructions_offset = *offset as u16;
// The instructions do not have a fixed size. So we must iterate over
// each instruction to find the total size of the instructions,
// and check for any malformed instructions or buffer overflows.
for _index in 0..num_instructions {
// Each instruction has 3 pieces:
// 1. Program ID index (u8)
// 2. Accounts indexes ([u8])
// 3. Data ([u8])
// Read the program ID index.
let _program_id_index = read_byte(bytes, offset)?;
// Read the number of account indexes, and then update the offset
// to skip over the account indexes.
let num_accounts = optimized_read_compressed_u16(bytes, offset)?;
advance_offset_for_array::<u8>(bytes, offset, num_accounts)?;
// Read the length of the data, and then update the offset to skip
// over the data.
let data_len = optimized_read_compressed_u16(bytes, offset)?;
advance_offset_for_array::<u8>(bytes, offset, data_len)?
}
Ok(Self {
num_instructions,
offset: instructions_offset,
})
}
}
#[derive(Clone)]
pub struct InstructionsIterator<'a> {
pub(crate) bytes: &'a [u8],
pub(crate) offset: usize,
pub(crate) num_instructions: u16,
pub(crate) index: u16,
}
impl<'a> Iterator for InstructionsIterator<'a> {
type Item = SVMInstruction<'a>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.num_instructions {
self.index = self.index.wrapping_add(1);
// Each instruction has 3 pieces:
// 1. Program ID index (u8)
// 2. Accounts indexes ([u8])
// 3. Data ([u8])
// Read the program ID index.
let program_id_index = read_byte(self.bytes, &mut self.offset).ok()?;
// Read the number of account indexes, and then update the offset
// to skip over the account indexes.
let num_accounts = optimized_read_compressed_u16(self.bytes, &mut self.offset).ok()?;
const _: () = assert!(core::mem::align_of::<u8>() == 1, "u8 alignment");
// SAFETY:
// - The offset is checked to be valid in the byte slice.
// - The alignment of u8 is 1.
// - The slice length is checked to be valid.
// - `u8` cannot be improperly initialized.
let accounts =
unsafe { read_slice_data::<u8>(self.bytes, &mut self.offset, num_accounts) }
.ok()?;
// Read the length of the data, and then update the offset to skip
// over the data.
let data_len = optimized_read_compressed_u16(self.bytes, &mut self.offset).ok()?;
const _: () = assert!(core::mem::align_of::<u8>() == 1, "u8 alignment");
// SAFETY:
// - The offset is checked to be valid in the byte slice.
// - The alignment of u8 is 1.
// - The slice length is checked to be valid.
// - `u8` cannot be improperly initialized.
let data =
unsafe { read_slice_data::<u8>(self.bytes, &mut self.offset, data_len) }.ok()?;
Some(SVMInstruction {
program_id_index,
accounts,
data,
})
} else {
None
}
}
}
impl ExactSizeIterator for InstructionsIterator<'_> {
fn len(&self) -> usize {
usize::from(self.num_instructions.wrapping_sub(self.index))
}
}
impl Debug for InstructionsIterator<'_> {
fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
#[cfg(test)]
mod tests {
use {
super::*, clone_solana_message::compiled_instruction::CompiledInstruction,
clone_solana_short_vec::ShortVec,
};
#[test]
fn test_zero_instructions() {
let bytes = bincode::serialize(&ShortVec(Vec::<CompiledInstruction>::new())).unwrap();
let mut offset = 0;
let instructions_frame = InstructionsFrame::try_new(&bytes, &mut offset).unwrap();
assert_eq!(instructions_frame.num_instructions, 0);
assert_eq!(instructions_frame.offset, 1);
assert_eq!(offset, bytes.len());
}
#[test]
fn test_num_instructions_too_high() {
let mut bytes = bincode::serialize(&ShortVec(vec![CompiledInstruction {
program_id_index: 0,
accounts: vec![],
data: vec![],
}]))
.unwrap();
// modify the number of instructions to be too high
bytes[0] = 0x02;
let mut offset = 0;
assert!(InstructionsFrame::try_new(&bytes, &mut offset).is_err());
}
#[test]
fn test_single_instruction() {
let bytes = bincode::serialize(&ShortVec(vec![CompiledInstruction {
program_id_index: 0,
accounts: vec![1, 2, 3],
data: vec![4, 5, 6, 7, 8, 9, 10],
}]))
.unwrap();
let mut offset = 0;
let instructions_frame = InstructionsFrame::try_new(&bytes, &mut offset).unwrap();
assert_eq!(instructions_frame.num_instructions, 1);
assert_eq!(instructions_frame.offset, 1);
assert_eq!(offset, bytes.len());
}
#[test]
fn test_multiple_instructions() {
let bytes = bincode::serialize(&ShortVec(vec![
CompiledInstruction {
program_id_index: 0,
accounts: vec![1, 2, 3],
data: vec![4, 5, 6, 7, 8, 9, 10],
},
CompiledInstruction {
program_id_index: 1,
accounts: vec![4, 5, 6],
data: vec![7, 8, 9, 10, 11, 12, 13],
},
]))
.unwrap();
let mut offset = 0;
let instructions_frame = InstructionsFrame::try_new(&bytes, &mut offset).unwrap();
assert_eq!(instructions_frame.num_instructions, 2);
assert_eq!(instructions_frame.offset, 1);
assert_eq!(offset, bytes.len());
}
#[test]
fn test_invalid_instruction_accounts_vec() {
let mut bytes = bincode::serialize(&ShortVec(vec![CompiledInstruction {
program_id_index: 0,
accounts: vec![1, 2, 3],
data: vec![4, 5, 6, 7, 8, 9, 10],
}]))
.unwrap();
// modify the number of accounts to be too high
bytes[2] = 127;
let mut offset = 0;
assert!(InstructionsFrame::try_new(&bytes, &mut offset).is_err());
}
#[test]
fn test_invalid_instruction_data_vec() {
let mut bytes = bincode::serialize(&ShortVec(vec![CompiledInstruction {
program_id_index: 0,
accounts: vec![1, 2, 3],
data: vec![4, 5, 6, 7, 8, 9, 10],
}]))
.unwrap();
// modify the number of data bytes to be too high
bytes[6] = 127;
let mut offset = 0;
assert!(InstructionsFrame::try_new(&bytes, &mut offset).is_err());
}
}