Skip to main content

hopper_native/
instruction.rs

1//! CPI instruction types: InstructionView, InstructionAccount, Seed, Signer.
2//!
3//! These types match the Solana runtime's C ABI for cross-program invocation.
4//! Matching the C descriptor ABI does not make Rust types interchangeable with
5//! types defined in other crates. Construct Hopper descriptors explicitly.
6
7use crate::account_view::AccountView;
8use crate::address::Address;
9use crate::error::ProgramError;
10use crate::raw_account::RuntimeAccount;
11use crate::{ProgramResult, NOT_BORROWED};
12use core::marker::PhantomData;
13
14// ── InstructionAccount ───────────────────────────────────────────────
15
16/// Metadata for an account referenced in a CPI instruction.
17#[repr(C)]
18#[derive(Debug, Clone)]
19pub struct InstructionAccount<'a> {
20    /// Public key of the account.
21    pub address: &'a Address,
22    /// Whether the account should be writable.
23    pub is_writable: bool,
24    /// Whether the account should sign.
25    pub is_signer: bool,
26}
27
28impl<'a> InstructionAccount<'a> {
29    /// Construct with explicit flags.
30    #[inline(always)]
31    pub const fn new(address: &'a Address, is_writable: bool, is_signer: bool) -> Self {
32        Self {
33            address,
34            is_writable,
35            is_signer,
36        }
37    }
38
39    /// Read-only, non-signer.
40    #[inline(always)]
41    pub const fn readonly(address: &'a Address) -> Self {
42        Self {
43            address,
44            is_writable: false,
45            is_signer: false,
46        }
47    }
48
49    /// Writable, non-signer.
50    #[inline(always)]
51    pub const fn writable(address: &'a Address) -> Self {
52        Self {
53            address,
54            is_writable: true,
55            is_signer: false,
56        }
57    }
58
59    /// Read-only signer.
60    #[inline(always)]
61    pub const fn readonly_signer(address: &'a Address) -> Self {
62        Self {
63            address,
64            is_writable: false,
65            is_signer: true,
66        }
67    }
68
69    /// Writable signer.
70    #[inline(always)]
71    pub const fn writable_signer(address: &'a Address) -> Self {
72        Self {
73            address,
74            is_writable: true,
75            is_signer: true,
76        }
77    }
78}
79
80impl<'a> From<&'a AccountView<'a>> for InstructionAccount<'a> {
81    #[inline(always)]
82    fn from(view: &'a AccountView<'a>) -> Self {
83        Self {
84            address: view.address(),
85            is_writable: view.is_writable(),
86            is_signer: view.is_signer(),
87        }
88    }
89}
90
91// ── InstructionView ──────────────────────────────────────────────────
92
93/// A cross-program instruction to invoke.
94#[derive(Debug, Clone)]
95pub struct InstructionView<'a, 'b, 'c, 'd>
96where
97    'a: 'b,
98{
99    /// Program to call.
100    pub program_id: &'c Address,
101    /// Instruction data.
102    pub data: &'d [u8],
103    /// Account metadata.
104    pub accounts: &'b [InstructionAccount<'a>],
105}
106
107// ── CpiAccount ───────────────────────────────────────────────────────
108
109/// C-ABI account info passed to `sol_invoke_signed_c`.
110///
111/// This matches the Solana runtime's expected layout for CPI account infos.
112#[repr(C)]
113#[derive(Clone, Copy, Debug)]
114pub struct CpiAccount<'a> {
115    address: *const Address,
116    lamports: *const u64,
117    data_len: u64,
118    data: *const u8,
119    owner: *const Address,
120    rent_epoch: u64,
121    is_signer: bool,
122    is_writable: bool,
123    executable: bool,
124    _account_view: PhantomData<&'a AccountView<'a>>,
125}
126
127impl<'a> From<&'a AccountView<'a>> for CpiAccount<'a> {
128    #[inline(always)]
129    fn from(view: &'a AccountView<'a>) -> Self {
130        let raw = view.account_ptr();
131        // Single u32 read extracts [borrow_state, is_signer, is_writable, executable].
132        // On little-endian BPF: byte 1 = is_signer, byte 2 = is_writable, byte 3 = executable.
133        // SAFETY: `raw` points at the RuntimeAccount header in the Solana input
134        // buffer; its first 4 bytes pack [borrow_state, is_signer, is_writable,
135        // executable]. `read_unaligned` reads them as a u32 without assuming
136        // 4-byte pointer alignment.
137        let header = unsafe { core::ptr::read_unaligned(raw as *const u32) };
138        Self {
139            address: unsafe { &(*raw).address as *const Address },
140            // SAFETY: This block is part of Hopper's reviewed zero-copy/backend boundary; surrounding checks and caller contracts uphold the required raw-pointer, layout, and aliasing invariants.
141            lamports: unsafe { &(*raw).lamports as *const u64 },
142            data_len: view.data_len() as u64,
143            data: view.data_ptr_unchecked(),
144            // SAFETY: This block is part of Hopper's reviewed zero-copy/backend boundary; surrounding checks and caller contracts uphold the required raw-pointer, layout, and aliasing invariants.
145            owner: unsafe { &(*raw).owner as *const Address },
146            rent_epoch: 0,
147            is_signer: header & 0x0000_FF00 != 0,
148            is_writable: header & 0x00FF_0000 != 0,
149            executable: header & 0xFF00_0000 != 0,
150            _account_view: PhantomData,
151        }
152    }
153}
154
155impl<'a> CpiAccount<'a> {
156    /// Rebuild one instruction meta from protocol-declared flags.
157    ///
158    /// The flags deliberately do not come from the outer account view: a PDA
159    /// may be a signer only for this CPI, and an outer-writable account may be
160    /// intentionally read-only to the callee.
161    #[inline(always)]
162    pub(crate) fn instruction_account(
163        &self,
164        is_writable: bool,
165        is_signer: bool,
166    ) -> InstructionAccount<'a> {
167        // SAFETY: `CpiAccount::from` captured this pointer from an
168        // `AccountView<'a>` and the private fields prevent safe fabrication.
169        let address = unsafe { &*self.address };
170        InstructionAccount::new(address, is_writable, is_signer)
171    }
172}
173
174/// Validate the borrow state and writable privilege encoded by specialized
175/// CPI builders before entering a syscall.
176///
177/// `writable_mask` describes the callee instruction metas, not the outer
178/// transaction privileges: bit `i` is set when account `i` will be writable
179/// in the CPI. Read-only metas need shared-borrow compatibility; writable
180/// metas need both outer writable privilege and exclusive-borrow compatibility.
181#[inline(always)]
182pub(crate) fn preflight_cpi_accounts(
183    accounts: &[CpiAccount<'_>],
184    writable_mask: usize,
185    signer_mask: usize,
186    has_pda_signers: bool,
187) -> ProgramResult {
188    let mut index = 0usize;
189    while index < accounts.len() {
190        let account = &accounts[index];
191        // With no PDA signer seeds, a missing outer signature cannot be
192        // satisfied by the runtime. Match the generic checked invoke path.
193        // Nonempty seeds are NOT proof of authority: the SVM derives and
194        // authenticates the instruction's PDA signers at the syscall boundary.
195        if signer_mask & (1usize << index) != 0 && !account.is_signer && !has_pda_signers {
196            return Err(ProgramError::MissingRequiredSignature);
197        }
198        let is_writable_meta = writable_mask & (1usize << index) != 0;
199        if is_writable_meta && !account.is_writable {
200            return Err(ProgramError::Immutable);
201        }
202
203        // `CpiAccount::from` always derives `data` from the byte immediately
204        // after its RuntimeAccount header. The fields are private, so safe
205        // callers cannot synthesize a CpiAccount with a different relation.
206        let raw = unsafe { account.data.sub(RuntimeAccount::SIZE) as *const RuntimeAccount };
207        // SAFETY: `raw` was recovered from the invariant above and remains
208        // valid for the `CpiAccount` lifetime.
209        let borrow_state = unsafe { (*raw).borrow_state };
210        let compatible = if is_writable_meta {
211            borrow_state == NOT_BORROWED
212        } else {
213            borrow_state != 0
214        };
215        if !compatible {
216            return Err(ProgramError::AccountBorrowFailed);
217        }
218
219        index += 1;
220    }
221    Ok(())
222}
223
224// Pin the two C structures handed to `sol_invoke_signed_c`. Rust `bool` is one
225// byte, matching the syscall ABI's byte flags; the tail padding rounds each
226// record to pointer alignment.
227const _: () = {
228    assert!(core::mem::size_of::<InstructionAccount<'static>>() == 16);
229    assert!(core::mem::align_of::<InstructionAccount<'static>>() == 8);
230    assert!(core::mem::offset_of!(InstructionAccount<'static>, address) == 0);
231    assert!(core::mem::offset_of!(InstructionAccount<'static>, is_writable) == 8);
232    assert!(core::mem::offset_of!(InstructionAccount<'static>, is_signer) == 9);
233
234    assert!(core::mem::size_of::<CpiAccount<'static>>() == 56);
235    assert!(core::mem::align_of::<CpiAccount<'static>>() == 8);
236    assert!(core::mem::offset_of!(CpiAccount<'static>, address) == 0);
237    assert!(core::mem::offset_of!(CpiAccount<'static>, lamports) == 8);
238    assert!(core::mem::offset_of!(CpiAccount<'static>, data_len) == 16);
239    assert!(core::mem::offset_of!(CpiAccount<'static>, data) == 24);
240    assert!(core::mem::offset_of!(CpiAccount<'static>, owner) == 32);
241    assert!(core::mem::offset_of!(CpiAccount<'static>, rent_epoch) == 40);
242    assert!(core::mem::offset_of!(CpiAccount<'static>, is_signer) == 48);
243    assert!(core::mem::offset_of!(CpiAccount<'static>, is_writable) == 49);
244    assert!(core::mem::offset_of!(CpiAccount<'static>, executable) == 50);
245};
246
247// ── Seed ─────────────────────────────────────────────────────────────
248
249/// A single PDA seed for CPI signing.
250#[repr(C)]
251#[derive(Debug, Clone)]
252pub struct Seed<'a> {
253    pub(crate) seed: *const u8,
254    pub(crate) len: u64,
255    _bytes: PhantomData<&'a [u8]>,
256}
257
258impl<'a> From<&'a [u8]> for Seed<'a> {
259    #[inline(always)]
260    fn from(bytes: &'a [u8]) -> Self {
261        Self {
262            seed: bytes.as_ptr(),
263            len: bytes.len() as u64,
264            _bytes: PhantomData,
265        }
266    }
267}
268
269impl<'a, const N: usize> From<&'a [u8; N]> for Seed<'a> {
270    #[inline(always)]
271    fn from(bytes: &'a [u8; N]) -> Self {
272        Self {
273            seed: bytes.as_ptr(),
274            len: N as u64,
275            _bytes: PhantomData,
276        }
277    }
278}
279
280impl core::ops::Deref for Seed<'_> {
281    type Target = [u8];
282
283    #[inline(always)]
284    fn deref(&self) -> &[u8] {
285        // SAFETY: This block is part of Hopper's reviewed zero-copy/backend boundary; surrounding checks and caller contracts uphold the required raw-pointer, layout, and aliasing invariants.
286        unsafe { core::slice::from_raw_parts(self.seed, self.len as usize) }
287    }
288}
289
290// ── Signer ───────────────────────────────────────────────────────────
291
292/// A PDA signer: a set of seeds that derive the signing PDA.
293#[repr(C)]
294#[derive(Debug, Clone)]
295pub struct Signer<'a, 'b> {
296    pub(crate) seeds: *const Seed<'a>,
297    pub(crate) len: u64,
298    _seeds: PhantomData<&'b [Seed<'a>]>,
299}
300
301impl<'a, 'b> From<&'b [Seed<'a>]> for Signer<'a, 'b> {
302    #[inline(always)]
303    fn from(seeds: &'b [Seed<'a>]) -> Self {
304        Self {
305            seeds: seeds.as_ptr(),
306            len: seeds.len() as u64,
307            _seeds: PhantomData,
308        }
309    }
310}
311
312impl<'a, 'b, const N: usize> From<&'b [Seed<'a>; N]> for Signer<'a, 'b> {
313    #[inline(always)]
314    fn from(seeds: &'b [Seed<'a>; N]) -> Self {
315        Self {
316            seeds: seeds.as_ptr(),
317            len: N as u64,
318            _seeds: PhantomData,
319        }
320    }
321}
322
323/// Convenience macro for building an array of `Seed` from expressions.
324///
325/// Usage: `let seeds = seeds!(b"vault", mint_key.as_ref(), &[bump]);`
326#[macro_export]
327macro_rules! seeds {
328    ( $($seed:expr),* $(,)? ) => {
329        [$(
330            $crate::instruction::Seed::from($seed),
331        )*]
332    };
333}