hbros_solana_program/sysvar/
instructions.rs

1//! The serialized instructions of the current transaction.
2//!
3//! The _instructions sysvar_ provides access to the serialized instruction data
4//! for the currently-running transaction. This allows for [instruction
5//! introspection][in], which is required for correctly interoperating with
6//! native programs like the [secp256k1] and [ed25519] programs.
7//!
8//! [in]: https://docs.solanalabs.com/implemented-proposals/instruction_introspection
9//! [secp256k1]: crate::secp256k1_program
10//! [ed25519]: crate::ed25519_program
11//!
12//! Unlike other sysvars, the data in the instructions sysvar is not accessed
13//! through a type that implements the [`Sysvar`] trait. Instead, the
14//! instruction sysvar is accessed through several free functions within this
15//! module.
16//!
17//! [`Sysvar`]: crate::sysvar::Sysvar
18//!
19//! See also the Solana [documentation on the instructions sysvar][sdoc].
20//!
21//! [sdoc]: https://docs.solanalabs.com/runtime/sysvars#instructions
22//!
23//! # Examples
24//!
25//! For a complete example of how the instructions sysvar is used see the
26//! documentation for [`secp256k1_instruction`] in the `solana-sdk` crate.
27//!
28//! [`secp256k1_instruction`]: https://docs.rs/solana-sdk/latest/solana_sdk/secp256k1_instruction/index.html
29
30#![allow(clippy::arithmetic_side_effects)]
31
32#[cfg(feature = "dev-context-only-utils")]
33use qualifier_attr::qualifiers;
34#[cfg(not(target_os = "solana"))]
35use {
36    crate::serialize_utils::{append_slice, append_u16, append_u8},
37    bitflags::bitflags,
38};
39use {
40    crate::{
41        account_info::AccountInfo,
42        instruction::{AccountMeta, Instruction},
43        program_error::ProgramError,
44        pubkey::Pubkey,
45        serialize_utils::{read_pubkey, read_slice, read_u16, read_u8},
46    },
47    solana_sanitize::SanitizeError,
48};
49
50/// Instructions sysvar, dummy type.
51///
52/// This type exists for consistency with other sysvar modules, but is a dummy
53/// type that does not contain sysvar data. It implements the [`SysvarId`] trait
54/// but does not implement the [`Sysvar`] trait.
55///
56/// [`SysvarId`]: crate::sysvar::SysvarId
57/// [`Sysvar`]: crate::sysvar::Sysvar
58///
59/// Use the free functions in this module to access the instructions sysvar.
60pub struct Instructions();
61
62crate::declare_sysvar_id!("Sysvar1nstructions1111111111111111111111111", Instructions);
63
64/// Construct the account data for the instructions sysvar.
65///
66/// This function is used by the runtime and not available to Solana programs.
67#[cfg(not(target_os = "solana"))]
68pub fn construct_instructions_data(instructions: &[BorrowedInstruction]) -> Vec<u8> {
69    let mut data = serialize_instructions(instructions);
70    // add room for current instruction index.
71    data.resize(data.len() + 2, 0);
72
73    data
74}
75
76/// Borrowed version of `AccountMeta`.
77///
78/// This struct is used by the runtime when constructing the sysvar. It is not
79/// useful to Solana programs.
80pub struct BorrowedAccountMeta<'a> {
81    pub pubkey: &'a Pubkey,
82    pub is_signer: bool,
83    pub is_writable: bool,
84}
85
86/// Borrowed version of `Instruction`.
87///
88/// This struct is used by the runtime when constructing the sysvar. It is not
89/// useful to Solana programs.
90pub struct BorrowedInstruction<'a> {
91    pub program_id: &'a Pubkey,
92    pub accounts: Vec<BorrowedAccountMeta<'a>>,
93    pub data: &'a [u8],
94}
95
96#[cfg(not(target_os = "solana"))]
97bitflags! {
98    struct InstructionsSysvarAccountMeta: u8 {
99        const IS_SIGNER = 0b00000001;
100        const IS_WRITABLE = 0b00000010;
101    }
102}
103
104// First encode the number of instructions:
105// [0..2 - num_instructions
106//
107// Then a table of offsets of where to find them in the data
108//  3..2 * num_instructions table of instruction offsets
109//
110// Each instruction is then encoded as:
111//   0..2 - num_accounts
112//   2 - meta_byte -> (bit 0 signer, bit 1 is_writable)
113//   3..35 - pubkey - 32 bytes
114//   35..67 - program_id
115//   67..69 - data len - u16
116//   69..data_len - data
117#[cfg(not(target_os = "solana"))]
118fn serialize_instructions(instructions: &[BorrowedInstruction]) -> Vec<u8> {
119    // 64 bytes is a reasonable guess, calculating exactly is slower in benchmarks
120    let mut data = Vec::with_capacity(instructions.len() * (32 * 2));
121    append_u16(&mut data, instructions.len() as u16);
122    for _ in 0..instructions.len() {
123        append_u16(&mut data, 0);
124    }
125
126    for (i, instruction) in instructions.iter().enumerate() {
127        let start_instruction_offset = data.len() as u16;
128        let start = 2 + (2 * i);
129        data[start..start + 2].copy_from_slice(&start_instruction_offset.to_le_bytes());
130        append_u16(&mut data, instruction.accounts.len() as u16);
131        for account_meta in &instruction.accounts {
132            let mut account_meta_flags = InstructionsSysvarAccountMeta::empty();
133            if account_meta.is_signer {
134                account_meta_flags |= InstructionsSysvarAccountMeta::IS_SIGNER;
135            }
136            if account_meta.is_writable {
137                account_meta_flags |= InstructionsSysvarAccountMeta::IS_WRITABLE;
138            }
139            append_u8(&mut data, account_meta_flags.bits());
140            append_slice(&mut data, account_meta.pubkey.as_ref());
141        }
142
143        append_slice(&mut data, instruction.program_id.as_ref());
144        append_u16(&mut data, instruction.data.len() as u16);
145        append_slice(&mut data, instruction.data);
146    }
147    data
148}
149
150/// Load the current `Instruction`'s index in the currently executing
151/// `Transaction`.
152///
153/// `data` is the instructions sysvar account data.
154///
155/// Unsafe because the sysvar accounts address is not checked; only used
156/// internally after such a check.
157fn load_current_index(data: &[u8]) -> u16 {
158    let mut instr_fixed_data = [0u8; 2];
159    let len = data.len();
160    instr_fixed_data.copy_from_slice(&data[len - 2..len]);
161    u16::from_le_bytes(instr_fixed_data)
162}
163
164/// Load the current `Instruction`'s index in the currently executing
165/// `Transaction`.
166///
167/// # Errors
168///
169/// Returns [`ProgramError::UnsupportedSysvar`] if the given account's ID is not equal to [`ID`].
170pub fn load_current_index_checked(
171    instruction_sysvar_account_info: &AccountInfo,
172) -> Result<u16, ProgramError> {
173    if !check_id(instruction_sysvar_account_info.key) {
174        return Err(ProgramError::UnsupportedSysvar);
175    }
176
177    let instruction_sysvar = instruction_sysvar_account_info.try_borrow_data()?;
178    let index = load_current_index(&instruction_sysvar);
179    Ok(index)
180}
181
182/// Store the current `Instruction`'s index in the instructions sysvar data.
183pub fn store_current_index(data: &mut [u8], instruction_index: u16) {
184    let last_index = data.len() - 2;
185    data[last_index..last_index + 2].copy_from_slice(&instruction_index.to_le_bytes());
186}
187
188fn deserialize_instruction(index: usize, data: &[u8]) -> Result<Instruction, SanitizeError> {
189    const IS_SIGNER_BIT: usize = 0;
190    const IS_WRITABLE_BIT: usize = 1;
191
192    let mut current = 0;
193    let num_instructions = read_u16(&mut current, data)?;
194    if index >= num_instructions as usize {
195        return Err(SanitizeError::IndexOutOfBounds);
196    }
197
198    // index into the instruction byte-offset table.
199    current += index * 2;
200    let start = read_u16(&mut current, data)?;
201
202    current = start as usize;
203    let num_accounts = read_u16(&mut current, data)?;
204    let mut accounts = Vec::with_capacity(num_accounts as usize);
205    for _ in 0..num_accounts {
206        let meta_byte = read_u8(&mut current, data)?;
207        let mut is_signer = false;
208        let mut is_writable = false;
209        if meta_byte & (1 << IS_SIGNER_BIT) != 0 {
210            is_signer = true;
211        }
212        if meta_byte & (1 << IS_WRITABLE_BIT) != 0 {
213            is_writable = true;
214        }
215        let pubkey = read_pubkey(&mut current, data)?;
216        accounts.push(AccountMeta {
217            pubkey,
218            is_signer,
219            is_writable,
220        });
221    }
222    let program_id = read_pubkey(&mut current, data)?;
223    let data_len = read_u16(&mut current, data)?;
224    let data = read_slice(&mut current, data, data_len as usize)?;
225    Ok(Instruction {
226        program_id,
227        accounts,
228        data,
229    })
230}
231
232/// Load an `Instruction` in the currently executing `Transaction` at the
233/// specified index.
234///
235/// `data` is the instructions sysvar account data.
236///
237/// Unsafe because the sysvar accounts address is not checked; only used
238/// internally after such a check.
239#[cfg_attr(feature = "dev-context-only-utils", qualifiers(pub))]
240fn load_instruction_at(index: usize, data: &[u8]) -> Result<Instruction, SanitizeError> {
241    deserialize_instruction(index, data)
242}
243
244/// Load an `Instruction` in the currently executing `Transaction` at the
245/// specified index.
246///
247/// # Errors
248///
249/// Returns [`ProgramError::UnsupportedSysvar`] if the given account's ID is not equal to [`ID`].
250pub fn load_instruction_at_checked(
251    index: usize,
252    instruction_sysvar_account_info: &AccountInfo,
253) -> Result<Instruction, ProgramError> {
254    if !check_id(instruction_sysvar_account_info.key) {
255        return Err(ProgramError::UnsupportedSysvar);
256    }
257
258    let instruction_sysvar = instruction_sysvar_account_info.try_borrow_data()?;
259    load_instruction_at(index, &instruction_sysvar).map_err(|err| match err {
260        SanitizeError::IndexOutOfBounds => ProgramError::InvalidArgument,
261        _ => ProgramError::InvalidInstructionData,
262    })
263}
264
265/// Returns the `Instruction` relative to the current `Instruction` in the
266/// currently executing `Transaction`.
267///
268/// # Errors
269///
270/// Returns [`ProgramError::UnsupportedSysvar`] if the given account's ID is not equal to [`ID`].
271pub fn get_instruction_relative(
272    index_relative_to_current: i64,
273    instruction_sysvar_account_info: &AccountInfo,
274) -> Result<Instruction, ProgramError> {
275    if !check_id(instruction_sysvar_account_info.key) {
276        return Err(ProgramError::UnsupportedSysvar);
277    }
278
279    let instruction_sysvar = instruction_sysvar_account_info.data.borrow();
280    let current_index = load_current_index(&instruction_sysvar) as i64;
281    let index = current_index.saturating_add(index_relative_to_current);
282    if index < 0 {
283        return Err(ProgramError::InvalidArgument);
284    }
285    load_instruction_at(
286        current_index.saturating_add(index_relative_to_current) as usize,
287        &instruction_sysvar,
288    )
289    .map_err(|err| match err {
290        SanitizeError::IndexOutOfBounds => ProgramError::InvalidArgument,
291        _ => ProgramError::InvalidInstructionData,
292    })
293}
294
295#[cfg(test)]
296mod tests {
297    use {
298        super::*,
299        crate::{
300            instruction::AccountMeta,
301            message::{Message as LegacyMessage, SanitizedMessage},
302            pubkey::Pubkey,
303        },
304        std::collections::HashSet,
305    };
306
307    fn new_sanitized_message(message: LegacyMessage) -> SanitizedMessage {
308        SanitizedMessage::try_from_legacy_message(message, &HashSet::default()).unwrap()
309    }
310
311    #[test]
312    fn test_load_store_instruction() {
313        let mut data = [4u8; 10];
314        store_current_index(&mut data, 3);
315        #[allow(deprecated)]
316        let index = load_current_index(&data);
317        assert_eq!(index, 3);
318        assert_eq!([4u8; 8], data[0..8]);
319    }
320
321    #[test]
322    fn test_load_instruction_at_checked() {
323        let instruction0 = Instruction::new_with_bincode(
324            Pubkey::new_unique(),
325            &0,
326            vec![AccountMeta::new(Pubkey::new_unique(), false)],
327        );
328        let instruction1 = Instruction::new_with_bincode(
329            Pubkey::new_unique(),
330            &0,
331            vec![AccountMeta::new(Pubkey::new_unique(), false)],
332        );
333        let message = LegacyMessage::new(
334            &[instruction0.clone(), instruction1.clone()],
335            Some(&Pubkey::new_unique()),
336        );
337        let sanitized_message = new_sanitized_message(message);
338
339        let key = id();
340        let mut lamports = 0;
341        let mut data = construct_instructions_data(&sanitized_message.decompile_instructions());
342        let owner = crate::sysvar::id();
343        let mut account_info = AccountInfo::new(
344            &key,
345            false,
346            false,
347            &mut lamports,
348            &mut data,
349            &owner,
350            false,
351            0,
352        );
353
354        assert_eq!(
355            instruction0,
356            load_instruction_at_checked(0, &account_info).unwrap()
357        );
358        assert_eq!(
359            instruction1,
360            load_instruction_at_checked(1, &account_info).unwrap()
361        );
362        assert_eq!(
363            Err(ProgramError::InvalidArgument),
364            load_instruction_at_checked(2, &account_info)
365        );
366
367        let key = Pubkey::new_unique();
368        account_info.key = &key;
369        assert_eq!(
370            Err(ProgramError::UnsupportedSysvar),
371            load_instruction_at_checked(2, &account_info)
372        );
373    }
374
375    #[test]
376    fn test_load_current_index_checked() {
377        let instruction0 = Instruction::new_with_bincode(
378            Pubkey::new_unique(),
379            &0,
380            vec![AccountMeta::new(Pubkey::new_unique(), false)],
381        );
382        let instruction1 = Instruction::new_with_bincode(
383            Pubkey::new_unique(),
384            &0,
385            vec![AccountMeta::new(Pubkey::new_unique(), false)],
386        );
387        let message =
388            LegacyMessage::new(&[instruction0, instruction1], Some(&Pubkey::new_unique()));
389        let sanitized_message = new_sanitized_message(message);
390
391        let key = id();
392        let mut lamports = 0;
393        let mut data = construct_instructions_data(&sanitized_message.decompile_instructions());
394        store_current_index(&mut data, 1);
395        let owner = crate::sysvar::id();
396        let mut account_info = AccountInfo::new(
397            &key,
398            false,
399            false,
400            &mut lamports,
401            &mut data,
402            &owner,
403            false,
404            0,
405        );
406
407        assert_eq!(1, load_current_index_checked(&account_info).unwrap());
408        {
409            let mut data = account_info.try_borrow_mut_data().unwrap();
410            store_current_index(&mut data, 0);
411        }
412        assert_eq!(0, load_current_index_checked(&account_info).unwrap());
413
414        let key = Pubkey::new_unique();
415        account_info.key = &key;
416        assert_eq!(
417            Err(ProgramError::UnsupportedSysvar),
418            load_current_index_checked(&account_info)
419        );
420    }
421
422    #[test]
423    fn test_get_instruction_relative() {
424        let instruction0 = Instruction::new_with_bincode(
425            Pubkey::new_unique(),
426            &0,
427            vec![AccountMeta::new(Pubkey::new_unique(), false)],
428        );
429        let instruction1 = Instruction::new_with_bincode(
430            Pubkey::new_unique(),
431            &0,
432            vec![AccountMeta::new(Pubkey::new_unique(), false)],
433        );
434        let instruction2 = Instruction::new_with_bincode(
435            Pubkey::new_unique(),
436            &0,
437            vec![AccountMeta::new(Pubkey::new_unique(), false)],
438        );
439        let message = LegacyMessage::new(
440            &[
441                instruction0.clone(),
442                instruction1.clone(),
443                instruction2.clone(),
444            ],
445            Some(&Pubkey::new_unique()),
446        );
447        let sanitized_message = new_sanitized_message(message);
448
449        let key = id();
450        let mut lamports = 0;
451        let mut data = construct_instructions_data(&sanitized_message.decompile_instructions());
452        store_current_index(&mut data, 1);
453        let owner = crate::sysvar::id();
454        let mut account_info = AccountInfo::new(
455            &key,
456            false,
457            false,
458            &mut lamports,
459            &mut data,
460            &owner,
461            false,
462            0,
463        );
464
465        assert_eq!(
466            Err(ProgramError::InvalidArgument),
467            get_instruction_relative(-2, &account_info)
468        );
469        assert_eq!(
470            instruction0,
471            get_instruction_relative(-1, &account_info).unwrap()
472        );
473        assert_eq!(
474            instruction1,
475            get_instruction_relative(0, &account_info).unwrap()
476        );
477        assert_eq!(
478            instruction2,
479            get_instruction_relative(1, &account_info).unwrap()
480        );
481        assert_eq!(
482            Err(ProgramError::InvalidArgument),
483            get_instruction_relative(2, &account_info)
484        );
485        {
486            let mut data = account_info.try_borrow_mut_data().unwrap();
487            store_current_index(&mut data, 0);
488        }
489        assert_eq!(
490            Err(ProgramError::InvalidArgument),
491            get_instruction_relative(-1, &account_info)
492        );
493        assert_eq!(
494            instruction0,
495            get_instruction_relative(0, &account_info).unwrap()
496        );
497        assert_eq!(
498            instruction1,
499            get_instruction_relative(1, &account_info).unwrap()
500        );
501        assert_eq!(
502            instruction2,
503            get_instruction_relative(2, &account_info).unwrap()
504        );
505        assert_eq!(
506            Err(ProgramError::InvalidArgument),
507            get_instruction_relative(3, &account_info)
508        );
509
510        let key = Pubkey::new_unique();
511        account_info.key = &key;
512        assert_eq!(
513            Err(ProgramError::UnsupportedSysvar),
514            get_instruction_relative(0, &account_info)
515        );
516    }
517
518    #[test]
519    fn test_serialize_instructions() {
520        let program_id0 = Pubkey::new_unique();
521        let program_id1 = Pubkey::new_unique();
522        let id0 = Pubkey::new_unique();
523        let id1 = Pubkey::new_unique();
524        let id2 = Pubkey::new_unique();
525        let id3 = Pubkey::new_unique();
526        let instructions = vec![
527            Instruction::new_with_bincode(program_id0, &0, vec![AccountMeta::new(id0, false)]),
528            Instruction::new_with_bincode(program_id0, &0, vec![AccountMeta::new(id1, true)]),
529            Instruction::new_with_bincode(
530                program_id1,
531                &0,
532                vec![AccountMeta::new_readonly(id2, false)],
533            ),
534            Instruction::new_with_bincode(
535                program_id1,
536                &0,
537                vec![AccountMeta::new_readonly(id3, true)],
538            ),
539        ];
540
541        let message = LegacyMessage::new(&instructions, Some(&id1));
542        let sanitized_message = new_sanitized_message(message);
543        let serialized = serialize_instructions(&sanitized_message.decompile_instructions());
544
545        // assert that deserialize_instruction is compatible with SanitizedMessage::serialize_instructions
546        for (i, instruction) in instructions.iter().enumerate() {
547            assert_eq!(
548                deserialize_instruction(i, &serialized).unwrap(),
549                *instruction
550            );
551        }
552    }
553
554    #[test]
555    fn test_decompile_instructions_out_of_bounds() {
556        let program_id0 = Pubkey::new_unique();
557        let id0 = Pubkey::new_unique();
558        let id1 = Pubkey::new_unique();
559        let instructions = vec![
560            Instruction::new_with_bincode(program_id0, &0, vec![AccountMeta::new(id0, false)]),
561            Instruction::new_with_bincode(program_id0, &0, vec![AccountMeta::new(id1, true)]),
562        ];
563
564        let message = LegacyMessage::new(&instructions, Some(&id1));
565        let sanitized_message = new_sanitized_message(message);
566        let serialized = serialize_instructions(&sanitized_message.decompile_instructions());
567        assert_eq!(
568            deserialize_instruction(instructions.len(), &serialized).unwrap_err(),
569            SanitizeError::IndexOutOfBounds,
570        );
571    }
572}