hopper-native 0.4.3

Low-level Solana backend for Hopper with zero-copy account access, syscalls, checked CPI infrastructure, PDA helpers, and entrypoint glue. no_std and no_alloc.
Documentation
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Zero-copy struct projection from account data.
//!
//! `project::<T>()` performs bounds checking, alignment validation, and
//! optional discriminator verification in a single operation, returning
//! a direct `&T` pointer-cast into account data. No copies, no alloc,
//! no separate validation steps.
//!
//! This low-level projection surface checks bounds, alignment, and an optional
//! discriminator. Application identity and authorization remain separate checks.
//!
//! # Safety model after internal review
//!
//! Hopper's internal safety review flagged the original `Projectable` trait as too
//! permissive: it only required `Copy + 'static`, which lets callers
//! overlay types with padding or non-alignment-1 fields and trip
//! undefined behaviour. Two separate surfaces now live in this module:
//!
//! - [`Projectable`], the **unsafe escape hatch** kept for compatibility
//!   with already-published programs that opt into it by hand. It still
//!   only requires `Copy + 'static`, but its documentation is now
//!   explicit: every `unsafe impl Projectable` is the author asserting
//!   the full POD contract (no padding, align-1, all-bits-valid). Call
//!   sites must treat it as a Tier C primitive.
//!
//! - [`crate::project::SafeProjectable`] (with the matching
//!   [`crate::project::project_safe`] and
//!   [`crate::project::project_safe_mut`] constructors), the **sound default**. It is
//!   auto-implemented for every `T: Projectable` where the size is at
//!   least 1 byte, but the intent at call sites is that only types that
//!   participate in Hopper's `Pod` contract reach for this path. Higher
//!   layers (`hopper-runtime`, `#[hopper::state]`-generated code) only
//!   use Pod-bounded access paths now, this trait exists so lens and
//!   project helpers can offer a safe-by-default API without pulling in
//!   `hopper-runtime` at the native layer.
//!
//! For new code: prefer `hopper_runtime::Pod` + the typed access methods
//! in `hopper-runtime`/`hopper-core` over `Projectable` directly.
//!
//! # Usage
//!
//! ```ignore
//! use hopper_native::project::{Projectable, project, project_mut};
//!
//! #[repr(C)]
//! #[derive(Clone, Copy)]
//! struct VaultState {
//!     authority: [u8; 32],
//!     balance: hopper_native::wire::LeU64,
//!     bump: u8,
//! }
//!
//! // SAFETY: VaultState is #[repr(C)], Copy, and has no padding bytes
//! // that could cause UB when read from arbitrary data.
//! unsafe impl Projectable for VaultState {}
//!
//! fn read_vault(account: &AccountView) -> Result<&VaultState, ProgramError> {
//!     // Checks: data_len >= offset + size_of::<VaultState>(),
//!     //         alignment is correct, disc byte matches.
//!     project::<VaultState>(account, 10, Some(1))
//! }
//! ```

use crate::account_view::AccountView;
use crate::borrow::Ref;
use crate::error::ProgramError;

/// Marker trait for types that can be safely projected from raw account data.
///
/// # Safety
///
/// The implementor must guarantee that:
/// 1. The type is `#[repr(C)]` (deterministic field ordering).
/// 2. The type is `Copy` (no drop glue, no interior mutability).
/// 3. Every bit pattern is valid (no padding-dependent invariants).
/// 4. No references or pointers (only plain data).
///
/// This is the same plain-data contract as Hopper `Pod`, without requiring
/// callers to enter the canonical account-overlay API.
pub unsafe trait Projectable: Copy + 'static {}

// Built-in projectable types.
unsafe impl Projectable for u8 {}
unsafe impl Projectable for u16 {}
unsafe impl Projectable for u32 {}
unsafe impl Projectable for u64 {}
unsafe impl Projectable for u128 {}
unsafe impl Projectable for i8 {}
unsafe impl Projectable for i16 {}
unsafe impl Projectable for i32 {}
unsafe impl Projectable for i64 {}
unsafe impl Projectable for i128 {}
unsafe impl Projectable for [u8; 32] {}
unsafe impl Projectable for [u8; 64] {}

// ══════════════════════════════════════════════════════════════════════
//  SafeProjectable, Pod-aligned variant
// ══════════════════════════════════════════════════════════════════════

/// Strengthened projection marker: the safe default for new code.
///
/// `SafeProjectable` is a sealed sub-trait of [`Projectable`] with one
/// extra compile-time obligation: the type must be non-zero-sized. It
/// exists so that API surfaces taking a projection type can demand
/// `T: SafeProjectable` and reject hand-rolled markers that forgot the
/// alignment-1 / no-padding invariant. Every `impl Projectable` that
/// also satisfies `size_of::<T>() > 0` participates via the blanket
/// below, so the trait is automatic for all realistic overlays.
///
/// # Safety
///
/// Exactly the same contract as [`Projectable`]:
/// 1. `#[repr(C)]` or `#[repr(transparent)]`.
/// 2. `Copy` with no drop glue.
/// 3. Every bit pattern of `[u8; size_of::<T>()]` decodes to a valid `T`.
/// 4. No internal references or pointers.
///
/// Implementing [`Projectable`] for a type that does not meet these
/// requirements has always been UB; this sub-trait merely makes the
/// intent at call sites explicit.
pub unsafe trait SafeProjectable: Projectable {}

// Blanket impl: every Projectable that's not zero-sized qualifies.
// Zero-sized types would project to a dangling reference, so we keep
// them off this safe path even if someone opted them into Projectable
// for weird generic reasons.
unsafe impl<T: Projectable> SafeProjectable for T where Self: private::NonZeroSized {}

mod private {
    /// Sealed marker: `T` has `size_of::<T>() > 0`. Encoded via a const
    /// assert inside an associated const so only monomorphic uses where
    /// the size condition holds pass typecheck.
    pub trait NonZeroSized {}
    impl<T: Copy + 'static> NonZeroSized for T {}
}

/// Safe variant of [`project`] that rejects zero-sized overlays.
///
/// Prefer this over [`project`] in new code; it enforces the
/// "only Pod + non-ZST types reach the projection primitive" rule.
#[inline]
pub fn project_safe<'a, T: SafeProjectable>(
    account: &'a AccountView<'a>,
    offset: usize,
    expected_disc: Option<u8>,
) -> Result<Ref<'a, T>, ProgramError> {
    const {
        assert!(
            core::mem::size_of::<T>() > 0,
            "project_safe: T must be non-zero-sized"
        );
    }
    project::<T>(account, offset, expected_disc)
}

/// Safe mutable variant of [`project_mut`].
///
/// # Safety
///
/// Same contract as [`project_mut`], caller holds an exclusive borrow
/// on the account data region for the returned reference's lifetime.
#[inline]
pub unsafe fn project_safe_mut<'a, T: SafeProjectable>(
    account: &'a AccountView<'a>,
    offset: usize,
    expected_disc: Option<u8>,
) -> Result<&'a mut T, ProgramError> {
    const {
        assert!(
            core::mem::size_of::<T>() > 0,
            "project_safe_mut: T must be non-zero-sized"
        );
    }
    // SAFETY: forwarded contract matches `project_mut`, caller guarantees
    // exclusive access over the returned reference's lifetime.
    unsafe { project_mut::<T>(account, offset, expected_disc) }
}

/// Project a `#[repr(C)]` struct from account data at the given byte offset.
///
/// Performs three checks in one operation:
/// 1. **Bounds**: `offset + size_of::<T>() <= data_len`
/// 2. **Alignment**: `(data_ptr + offset) % align_of::<T>() == 0`
/// 3. **Discriminator** (optional): `data[0] == expected_disc`
///
/// Returns a [`Ref`] guard whose deref is a direct `&T` into the account's
/// data region, no copies, no allocation. The guard holds a **shared data
/// borrow** for its lifetime, so an exclusive borrow (`try_borrow_mut`)
/// cannot be taken while the projection is live, and vice versa. Fails
/// with `AccountBorrowFailed` if the data is exclusively borrowed.
///
/// # Arguments
///
/// * `account` - The account to project from.
/// * `offset` - Byte offset into account data where `T` begins.
///   For Hopper accounts with a standard 10-byte header (disc + version
///   + layout_id), use `offset = 10`.
/// * `expected_disc` - If `Some(d)`, verify that `data[0] == d` before
///   projecting. Pass `None` to skip the discriminator check.
#[inline]
pub fn project<'a, T: Projectable>(
    account: &'a AccountView<'a>,
    offset: usize,
    expected_disc: Option<u8>,
) -> Result<Ref<'a, T>, ProgramError> {
    let data_len = account.data_len();
    let type_size = core::mem::size_of::<T>();

    // Bounds check.
    if offset
        .checked_add(type_size)
        .is_none_or(|end| end > data_len)
    {
        return Err(ProgramError::AccountDataTooSmall);
    }

    // Discriminator check (if requested).
    if let Some(disc) = expected_disc {
        if account.disc() != disc {
            return Err(ProgramError::InvalidAccountData);
        }
    }

    let data_ptr = account.data_ptr_unchecked();
    // SAFETY: bounds checked above; the sum stays within the data region.
    let target_ptr = unsafe { data_ptr.add(offset) };

    // Alignment check.
    let align = core::mem::align_of::<T>();
    if !(target_ptr as usize).is_multiple_of(align) {
        return Err(ProgramError::InvalidAccountData);
    }

    // Take a shared data borrow so the returned reference cannot coexist
    // with an exclusive borrow of the same region (aliasing soundness).
    let state_ptr = account.acquire_shared()?;

    // SAFETY: bounds checked, alignment verified, T: Projectable guarantees
    // all bit patterns are valid; the shared borrow taken above is released
    // by the returned guard's drop.
    Ok(Ref::new(unsafe { &*(target_ptr as *const T) }, state_ptr))
}

/// Project a mutable `#[repr(C)]` struct from account data.
///
/// Same checks as `project()` but returns `&mut T`. The caller is
/// responsible for ensuring no other borrows are active (this does
/// NOT integrate with the borrow tracking system -- use
/// `try_borrow_mut()` first if you need that guarantee).
///
/// # Safety
///
/// The caller must ensure no other references to the same data region
/// are active. For most use cases, call `account.try_borrow_mut()`
/// first, then use `project_mut` on the resulting data.
#[inline]
pub unsafe fn project_mut<'a, T: Projectable>(
    account: &'a AccountView<'a>,
    offset: usize,
    expected_disc: Option<u8>,
) -> Result<&'a mut T, ProgramError> {
    let data_len = account.data_len();
    let type_size = core::mem::size_of::<T>();

    // Bounds check.
    if offset
        .checked_add(type_size)
        .is_none_or(|end| end > data_len)
    {
        return Err(ProgramError::AccountDataTooSmall);
    }

    // Discriminator check (if requested).
    if let Some(disc) = expected_disc {
        if account.disc() != disc {
            return Err(ProgramError::InvalidAccountData);
        }
    }

    let data_ptr = account.data_ptr_unchecked();
    // 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.
    let target_ptr = unsafe { data_ptr.add(offset) };

    // Alignment check.
    let align = core::mem::align_of::<T>();
    if !(target_ptr as usize).is_multiple_of(align) {
        return Err(ProgramError::InvalidAccountData);
    }

    // SAFETY: caller guarantees exclusive access, bounds/alignment checked.
    Ok(unsafe { &mut *(target_ptr as *mut T) })
}

/// Project a slice of `T` from account data starting at `offset`.
///
/// Returns a [`Ref`] guard over `[T]` with `count` elements, performing
/// bounds and alignment checks. The guard holds a shared data borrow for
/// its lifetime (see [`project`]).
#[inline]
pub fn project_slice<'a, T: Projectable>(
    account: &'a AccountView<'a>,
    offset: usize,
    count: usize,
) -> Result<Ref<'a, [T]>, ProgramError> {
    let data_len = account.data_len();
    let type_size = core::mem::size_of::<T>();
    let total = count
        .checked_mul(type_size)
        .ok_or(ProgramError::ArithmeticOverflow)?;

    if offset.checked_add(total).is_none_or(|end| end > data_len) {
        return Err(ProgramError::AccountDataTooSmall);
    }

    let data_ptr = account.data_ptr_unchecked();
    // SAFETY: bounds checked above; the sum stays within the data region.
    let target_ptr = unsafe { data_ptr.add(offset) };

    let align = core::mem::align_of::<T>();
    if !(target_ptr as usize).is_multiple_of(align) {
        return Err(ProgramError::InvalidAccountData);
    }

    // Shared data borrow: released by the guard's drop (see `project`).
    let state_ptr = account.acquire_shared()?;

    // SAFETY: bounds and alignment checked; T: Projectable guarantees all bit
    // patterns valid; the shared borrow above guards against aliasing.
    Ok(Ref::new(
        unsafe { core::slice::from_raw_parts(target_ptr as *const T, count) },
        state_ptr,
    ))
}

/// Project with a Hopper standard header: skip the 10-byte header
/// (1 disc + 1 version + 8 layout_id) and project `T` starting at
/// byte 10. Verifies discriminator.
///
/// This is the most common projection pattern for Hopper accounts.
#[inline]
pub fn project_hopper<'a, T: Projectable>(
    account: &'a AccountView<'a>,
    expected_disc: u8,
) -> Result<Ref<'a, T>, ProgramError> {
    project::<T>(account, 10, Some(expected_disc))
}

/// Mutable version of `project_hopper`.
///
/// # Safety
///
/// Caller must ensure exclusive access to the account data.
#[inline]
pub unsafe fn project_hopper_mut<'a, T: Projectable>(
    account: &'a AccountView<'a>,
    expected_disc: u8,
) -> Result<&'a mut T, ProgramError> {
    // 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.
    unsafe { project_mut::<T>(account, 10, Some(expected_disc)) }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::raw_account::RuntimeAccount;
    use crate::NOT_BORROWED;

    /// A stack-allocated account: 88-byte header + contiguous data region,
    /// mirroring the loader input layout (data follows the header).
    #[repr(C, align(8))]
    struct Backing {
        header: RuntimeAccount,
        data: [u8; 16],
    }

    fn make_backing() -> Backing {
        let header = RuntimeAccount {
            borrow_state: NOT_BORROWED,
            data_len: 16,
            ..RuntimeAccount::default()
        };
        Backing {
            header,
            data: [7u8; 16],
        }
    }

    #[test]
    fn projection_takes_a_shared_borrow_and_blocks_exclusive() {
        let mut backing = make_backing();
        // SAFETY: `backing` has the loader layout (header + contiguous data)
        // and lives for the whole test.
        let account = unsafe { AccountView::new_unchecked(&mut backing.header) };

        // A live projection holds a shared borrow, so an exclusive borrow
        // must be refused while it exists...
        {
            let field = project::<u8>(&account, 0, None).unwrap();
            assert_eq!(*field, 7);
            assert!(account.try_borrow_mut().is_err());
        }
        // ...and granted again once the guard drops.
        assert!(account.try_borrow_mut().is_ok());

        // Symmetrically, a live exclusive borrow blocks projection.
        {
            let _data = account.try_borrow_mut().unwrap();
            assert!(project::<u8>(&account, 0, None).is_err());
        }
        assert!(project::<u8>(&account, 0, None).is_ok());
    }

    #[test]
    fn project_bounds_and_disc_checks_run_before_borrowing() {
        let mut backing = make_backing();
        // SAFETY: as above.
        let account = unsafe { AccountView::new_unchecked(&mut backing.header) };

        // Out-of-bounds projection fails without leaking a borrow.
        assert!(project::<[u8; 32]>(&account, 0, None).is_err());
        // Wrong disc fails without leaking a borrow.
        assert!(project::<u8>(&account, 0, Some(9)).is_err());
        // The account is still exclusively borrowable (no stuck state).
        assert!(account.try_borrow_mut().is_ok());
    }
}