hopper-runtime 0.5.0

Canonical low-level runtime surface for Hopper programs: direct account memory, validation, borrow guards, CPI, and zero-copy state access.
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Layout contracts as runtime truth.
//!
//! `LayoutContract` is the central trait for Hopper's state-first architecture.
//! It ties together discriminator, version, and layout fingerprint into a single
//! compile-time contract that the runtime can validate before granting typed access.
//!
//! Layouts are not just metadata or serialization hints. They are runtime
//! contracts that gate account access, enforce compatibility, and enable schema
//! evolution.

use crate::error::ProgramError;
use crate::field_map::{FieldInfo, FieldMap};
use crate::ProgramResult;

/// Values that can populate a layout through an existing mutable borrow.
///
/// Generated `<State>Fields` types implement this trait. Application crates may
/// also implement it for their own inputs, including fallible validation before
/// writing. This trait grants no account access: ownership, layout, write policy,
/// and borrow checks belong to the caller acquiring the mutable layout.
///
/// An error does not undo writes already made by an implementation. Propagate
/// errors to the instruction boundary to obtain transaction rollback on Solana.
pub trait AccountFields {
    type Layout;

    fn write(self, layout: &mut Self::Layout) -> ProgramResult;
}

/// A layout whose `#[bump]`-marked field stores its PDA bump.
///
/// Implemented by `#[hopper::state]` for every layout that marks a field
/// with `#[bump]`. `#[derive(Accounts)]`'s `init` helper writes the
/// canonical bump it just signed the creation with into this byte, so an
/// account created by Hopper always stores a canonical bump, and
/// `bump = stored` then verifies the PDA with one hash.
pub trait StoredBump {
    /// Account-absolute offset of the bump byte.
    const BUMP_ABS_OFFSET: usize;
}

/// Selector for [`StoredBump`] in generated code: `(&BumpProbe::<T>(..))
/// .write_stored_bump(..)` resolves to the writing impl when `T:
/// StoredBump` and to the no-op otherwise, with no trait bound on `T`.
#[doc(hidden)]
pub struct BumpProbe<T>(pub core::marker::PhantomData<T>);

#[doc(hidden)]
pub trait WriteStoredBump {
    /// Write `bump` into the layout's bump byte of `data`.
    fn write_stored_bump_into(&self, data: &mut [u8], bump: u8) -> ProgramResult;

    /// Borrow `account` mutably and write `bump` into its bump byte. The
    /// borrow is taken here, inside the marked-layout impl only, so an
    /// unmarked layout's `init` pays nothing for the probe.
    fn write_stored_bump(
        &self,
        account: &crate::account::AccountView<'_>,
        bump: u8,
    ) -> ProgramResult;
}

impl<T: StoredBump> WriteStoredBump for BumpProbe<T> {
    #[inline(always)]
    fn write_stored_bump_into(&self, data: &mut [u8], bump: u8) -> ProgramResult {
        match data.get_mut(T::BUMP_ABS_OFFSET) {
            Some(slot) => {
                *slot = bump;
                Ok(())
            }
            None => Err(ProgramError::AccountDataTooSmall),
        }
    }

    #[inline(always)]
    fn write_stored_bump(
        &self,
        account: &crate::account::AccountView<'_>,
        bump: u8,
    ) -> ProgramResult {
        let mut data = account.try_borrow_mut()?;
        self.write_stored_bump_into(&mut data, bump)
    }
}

#[doc(hidden)]
pub trait NoStoredBump {
    #[inline(always)]
    fn write_stored_bump_into(&self, _data: &mut [u8], _bump: u8) -> ProgramResult {
        Ok(())
    }

    #[inline(always)]
    fn write_stored_bump(
        &self,
        _account: &crate::account::AccountView<'_>,
        _bump: u8,
    ) -> ProgramResult {
        Ok(())
    }
}

impl<T> NoStoredBump for &BumpProbe<T> {}

/// A layout with value rules: `#[check(..)]` on a field of a
/// `#[hopper::state]` struct implements this.
pub trait FieldRules {
    /// Check every rule against this value and return the first failure.
    fn check_rules(&self) -> ProgramResult;

    /// Load the layout from `account` and check its rules.
    fn check_account(account: &crate::account::AccountView<'_>) -> ProgramResult;
}

/// Selector for [`FieldRules`] in generated code:
/// `(&RulesProbe::<T>(..)).check_account_rules(view)` resolves to the
/// checking impl when `T: FieldRules` and to the no-op otherwise, with no
/// trait bound on `T`, so a layout without rules pays nothing.
#[doc(hidden)]
pub struct RulesProbe<T>(pub core::marker::PhantomData<T>);

#[doc(hidden)]
pub trait CheckFieldRules {
    /// Load the layout from `account` and check its rules.
    fn check_account_rules(&self, account: &crate::account::AccountView<'_>) -> ProgramResult;
}

impl<T: FieldRules> CheckFieldRules for RulesProbe<T> {
    #[inline(always)]
    fn check_account_rules(&self, account: &crate::account::AccountView<'_>) -> ProgramResult {
        T::check_account(account)
    }
}

#[doc(hidden)]
pub trait NoFieldRules {
    #[inline(always)]
    fn check_account_rules(&self, _account: &crate::account::AccountView<'_>) -> ProgramResult {
        Ok(())
    }
}

impl<T> NoFieldRules for &RulesProbe<T> {}

// ══════════════════════════════════════════════════════════════════════
//  HopperHeader -- the 16-byte on-chain header used by headered Hopper
//  accounts. Compact accounts use `[disc][body]` without this header.
// ══════════════════════════════════════════════════════════════════════

/// The canonical 16-byte header at the start of a headered Hopper account.
///
/// The reserved header tail carries a `schema_epoch: u32` so the runtime
/// can distinguish schema-compatible minor versions from wire-
/// incompatible revisions without bumping the single `version` byte.
///
/// ```text
/// byte 0     : disc (u8)
/// byte 1     : version (u8)
/// bytes 2-3  : flags (u16 LE)
/// bytes 4-11 : layout_id (first 8 bytes of canonical wire fingerprint)
/// bytes 12-15: schema_epoch (u32 LE), audit-added
/// ```
///
/// `schema_epoch` defaults to `1` at account initialisation via
/// [`init_header`]. Programs that publish a migration bump this
/// field to advertise the new shape while retaining the same
/// `disc`/`version`. Runtime header validation checks these values. Current
/// generated headered clients compare the stored `layout_id` before decoding;
/// compact clients use their separate size/discriminator path.
#[repr(C, packed)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct HopperHeader {
    pub disc: u8,
    pub version: u8,
    pub flags: u16,
    pub layout_id: [u8; 8],
    /// Schema-evolution epoch. Little-endian u32. `1` for freshly
    /// initialised headers; bumped by migration helpers.
    pub schema_epoch: u32,
}

impl HopperHeader {
    /// The header is always 16 bytes.
    pub const SIZE: usize = 16;

    /// Read a header from the start of a raw data slice.
    #[inline(always)]
    pub fn from_bytes(data: &[u8]) -> Option<&Self> {
        if data.len() < Self::SIZE {
            return None;
        }
        // SAFETY: HopperHeader is packed to alignment 1.
        Some(unsafe { &*(data.as_ptr() as *const Self) })
    }

    /// Read a mutable header from the start of a raw data slice.
    #[inline(always)]
    pub fn from_bytes_mut(data: &mut [u8]) -> Option<&mut Self> {
        if data.len() < Self::SIZE {
            return None;
        }
        // SAFETY: `data.len() >= Self::SIZE` was checked above;
        // `HopperHeader` is `repr(C, packed)`, so it has alignment 1 and no
        // padding, and every bit pattern is valid.
        Some(unsafe { &mut *(data.as_mut_ptr() as *mut Self) })
    }
}

// ══════════════════════════════════════════════════════════════════════
//  LayoutInfo -- runtime-inspectable metadata snapshot
// ══════════════════════════════════════════════════════════════════════

/// Runtime metadata snapshot of an account's layout identity.
///
/// Returned by `AccountView::layout_info()`. Enables manager inspection,
/// schema comparison, and version-aware loading without knowing the
/// concrete layout type at compile time.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct LayoutInfo {
    pub disc: u8,
    pub version: u8,
    pub flags: u16,
    pub layout_id: [u8; 8],
    /// Schema-evolution epoch read from the header's bytes 12..16.
    /// A value of `0` means "legacy" (accounts created before epochs) and is
    /// treated as equivalent to `DEFAULT_SCHEMA_EPOCH` when comparing
    /// against `AccountLayout::SCHEMA_EPOCH`.
    pub schema_epoch: u32,
    pub data_len: usize,
}

impl LayoutInfo {
    /// Read layout info from an account's raw data.
    #[inline(always)]
    pub fn from_data(data: &[u8]) -> Option<Self> {
        let hdr = HopperHeader::from_bytes(data)?;
        // Packed-struct field reads must go through a copy, reading
        // an unaligned `u32` reference directly is undefined behaviour.
        let schema_epoch = hdr.schema_epoch;
        let layout_id = hdr.layout_id;
        Some(Self {
            disc: hdr.disc,
            version: hdr.version,
            flags: hdr.flags,
            layout_id,
            schema_epoch,
            data_len: data.len(),
        })
    }

    /// Whether this account matches the given layout contract.
    #[inline(always)]
    pub fn matches<T: LayoutContract>(&self) -> bool {
        let schema_epoch = effective_schema_epoch(self.schema_epoch);
        self.disc == T::DISC
            && self.version == T::VERSION
            && self.layout_id == T::LAYOUT_ID
            && schema_epoch == T::SCHEMA_EPOCH
            && self.data_len >= T::required_len()
    }

    /// Length of the account body after the Hopper header.
    #[inline(always)]
    pub const fn body_len(&self) -> usize {
        self.data_len.saturating_sub(HopperHeader::SIZE)
    }

    /// Whether the account contains bytes beyond a given absolute offset.
    #[inline(always)]
    pub const fn has_bytes_after(&self, offset: usize) -> bool {
        self.data_len > offset
    }
}

// ══════════════════════════════════════════════════════════════════════
//  LayoutContract -- the central state contract trait
// ══════════════════════════════════════════════════════════════════════

/// A compile-time layout contract binding type identity to wire format.
///
/// Implementors declare their discriminator, version, layout fingerprint,
/// and wire size. The runtime uses these to validate accounts before granting
/// typed access via `overlay` or `load`.
///
/// # Wire format (Hopper account header)
///
/// ```text
/// byte 0   : discriminator (u8)
/// byte 1   : version (u8)
/// bytes 2-3: flags (u16 LE)
/// bytes 4-11: layout_id (first 8 bytes of SHA-256 fingerprint)
/// bytes 12-15: schema_epoch (u32 LE; zero is accepted as legacy epoch 1)
/// ```
///
/// # Example
///
/// ```ignore
/// impl LayoutContract for Vault {
///     const DISC: u8 = 1;
///     const VERSION: u8 = 1;
///     const LAYOUT_ID: [u8; 8] = compute_layout_id("Vault", 1, "authority:[u8;32]:32,balance:LeU64:8,");
///     const SIZE: usize = 16 + 32 + 8; // header + fields
/// }
/// ```
pub trait LayoutContract: Sized + Copy + FieldMap {
    /// Account type discriminator (byte 0 of data).
    const DISC: u8;

    /// Schema version for this layout (byte 1 of data).
    const VERSION: u8;

    /// First 8 bytes of the deterministic layout fingerprint.
    /// Computed from `SHA-256("hopper:v1:" + name + ":" + version + ":" + field_spec)`.
    const LAYOUT_ID: [u8; 8];

    /// Total wire size in bytes (including the 16-byte header).
    const SIZE: usize;

    /// Byte offset where the typed projection begins.
    ///
    /// Body-only runtime layouts keep the default `HopperHeader::SIZE`, while
    /// header-inclusive layouts set this to `0` so `AccountView::load()`
    /// projects the full account struct.
    const TYPE_OFFSET: usize = HopperHeader::SIZE;

    /// Schema-evolution epoch expected in the Hopper header.
    ///
    /// Fresh accounts default to epoch 1. A stored header epoch of 0
    /// is treated as legacy epoch 1 for backwards compatibility, but
    /// non-default layout epochs must match exactly before typed access
    /// is granted.
    const SCHEMA_EPOCH: u32 = DEFAULT_SCHEMA_EPOCH;

    /// Number of reserved bytes at the end of the layout. Reserved bytes
    /// provide forward-compatible padding that future versions can claim
    /// without a realloc.
    const RESERVED_BYTES: usize = 0;

    /// Byte offset where an extension region begins, if the layout supports one.
    /// Extension regions allow appending variable-length data beyond the fixed
    /// layout without breaking existing readers.
    const EXTENSION_OFFSET: Option<usize> = None;

    /// Validate a raw data slice against this contract.
    ///
    /// Returns `Ok(())` if the discriminator, version, layout_id, schema
    /// epoch, and required length all match. This is the canonical "is this
    /// account what I think it is?" check.
    #[inline(always)]
    fn validate_header(data: &[u8]) -> ProgramResult {
        if data.len() < Self::required_len() {
            return ProgramError::err_data_too_small();
        }
        let disc = read_disc(data);
        if disc != Some(Self::DISC) {
            return ProgramError::err_invalid_data();
        }
        let version = read_version(data);
        if version != Some(Self::VERSION) {
            return ProgramError::err_invalid_data();
        }
        if let Some(id) = read_layout_id(data) {
            if *id != Self::LAYOUT_ID {
                return ProgramError::err_invalid_data();
            }
        } else {
            return ProgramError::err_data_too_small();
        }
        match read_schema_epoch(data) {
            Some(stored) if effective_schema_epoch(stored) == Self::SCHEMA_EPOCH => {}
            Some(_) => return ProgramError::err_invalid_data(),
            None => return ProgramError::err_data_too_small(),
        }
        Ok(())
    }

    /// Byte length required to project this typed view safely.
    #[inline(always)]
    fn projected_len() -> usize {
        Self::TYPE_OFFSET + core::mem::size_of::<Self>()
    }

    /// Minimum account data length required by both the wire contract and projection shape.
    #[inline(always)]
    fn required_len() -> usize {
        if Self::SIZE > Self::projected_len() {
            Self::SIZE
        } else {
            Self::projected_len()
        }
    }

    /// Lightweight boolean validation helper for foreign readers and tools.
    #[inline(always)]
    fn validate(data: &[u8]) -> bool {
        Self::validate_header(data).is_ok()
    }

    /// Check only the discriminator (fast path for dispatch).
    #[inline(always)]
    fn check_disc(data: &[u8]) -> ProgramResult {
        match read_disc(data) {
            Some(d) if d == Self::DISC => Ok(()),
            _ => ProgramError::err_invalid_data(),
        }
    }

    /// Check only the version (for migration gates).
    #[inline(always)]
    fn check_version(data: &[u8]) -> ProgramResult {
        match read_version(data) {
            Some(v) if v == Self::VERSION => Ok(()),
            _ => ProgramError::err_invalid_data(),
        }
    }

    /// Check whether a given version is compatible with this layout.
    ///
    /// The default implementation accepts only the exact version, but
    /// implementors can override this to accept older versions for
    /// backward-compatible migration.
    #[inline(always)]
    fn compatible(version: u8) -> bool {
        version == Self::VERSION
    }

    /// Check whether the account data contains an extension region
    /// (data beyond the fixed layout boundary).
    #[inline(always)]
    fn has_extension_region(data: &[u8]) -> bool {
        match Self::EXTENSION_OFFSET {
            Some(offset) => data.len() > offset,
            None => false,
        }
    }

    /// Build a `LayoutInfo` snapshot from this contract's compile-time constants.
    #[inline(always)]
    fn layout_info_static() -> LayoutInfo {
        LayoutInfo {
            disc: Self::DISC,
            version: Self::VERSION,
            flags: 0,
            layout_id: Self::LAYOUT_ID,
            schema_epoch: Self::SCHEMA_EPOCH,
            data_len: Self::required_len(),
        }
    }

    /// Compile-time field metadata for this layout.
    #[inline(always)]
    fn fields() -> &'static [FieldInfo] {
        Self::FIELDS
    }
}

/// Read the discriminator from account data (byte 0).
#[inline(always)]
pub fn read_disc(data: &[u8]) -> Option<u8> {
    data.first().copied()
}

/// Read the version from account data (byte 1).
#[inline(always)]
pub fn read_version(data: &[u8]) -> Option<u8> {
    if data.len() < 2 {
        None
    } else {
        Some(data[1])
    }
}

/// Read the 8-byte layout_id from account data (bytes 4..12).
#[inline(always)]
pub fn read_layout_id(data: &[u8]) -> Option<&[u8; 8]> {
    if data.len() < 12 {
        None
    } else {
        // SAFETY: bounds checked above, alignment is 1 for [u8; 8].
        Some(unsafe { &*(data.as_ptr().add(4) as *const [u8; 8]) })
    }
}

/// Read the flags from account data (bytes 2..4) as u16 LE.
#[inline(always)]
pub fn read_flags(data: &[u8]) -> Option<u16> {
    if data.len() < 4 {
        None
    } else {
        let bytes = [data[2], data[3]];
        Some(u16::from_le_bytes(bytes))
    }
}

/// Default schema-evolution epoch written by `init_header`.
///
/// Accounts initialized before schema epochs had the epoch region
/// zeroed, so `0` is treated as "legacy, equivalent to 1" by the
/// runtime checks that compare against an `AccountLayout::SCHEMA_EPOCH`.
/// Freshly-initialised accounts now carry `1` so migrations can bump
/// monotonically without any lookback.
pub const DEFAULT_SCHEMA_EPOCH: u32 = 1;

/// Convert a stored header epoch into the effective value used by
/// runtime validation. Epoch 0 is legacy pre-epoch Hopper data and is
/// treated as epoch 1 only for default-epoch layouts.
#[inline(always)]
pub const fn effective_schema_epoch(stored: u32) -> u32 {
    if stored == 0 {
        DEFAULT_SCHEMA_EPOCH
    } else {
        stored
    }
}

/// Write a complete Hopper header to the beginning of `data`.
///
/// Writes disc, version, flags (zeroed), layout_id, and the
/// audit-added `schema_epoch = 1` (bytes 12..16).
/// Returns `Err` if `data` is shorter than 16 bytes.
#[inline(always)]
pub fn write_header(data: &mut [u8], disc: u8, version: u8, layout_id: &[u8; 8]) -> ProgramResult {
    write_header_with_epoch(data, disc, version, layout_id, DEFAULT_SCHEMA_EPOCH)
}

/// Write a Hopper header with a caller-specified schema epoch.
///
/// Used by migration helpers that need to stamp a new epoch while
/// preserving `disc`/`version`/`layout_id`. Regular account creation
/// should go through [`write_header`] (which defaults the epoch to
/// `1`) or [`init_header`].
#[inline(always)]
pub fn write_header_with_epoch(
    data: &mut [u8],
    disc: u8,
    version: u8,
    layout_id: &[u8; 8],
    schema_epoch: u32,
) -> ProgramResult {
    if data.len() < 16 {
        return Err(ProgramError::AccountDataTooSmall);
    }
    data[0] = disc;
    data[1] = version;
    data[2] = 0;
    data[3] = 0;
    data[4..12].copy_from_slice(layout_id);
    data[12..16].copy_from_slice(&schema_epoch.to_le_bytes());
    Ok(())
}

/// Read the `schema_epoch` field from an already-written header.
///
/// Returns `None` if `data` is too short. Returns the stored value
/// verbatim, callers that want the "0 means legacy" compatibility
/// rule should apply it themselves:
///
/// ```ignore
/// let stored = read_schema_epoch(data)?;
/// let effective = if stored == 0 { DEFAULT_SCHEMA_EPOCH } else { stored };
/// ```
#[inline(always)]
pub fn read_schema_epoch(data: &[u8]) -> Option<u32> {
    if data.len() < 16 {
        return None;
    }
    Some(u32::from_le_bytes([data[12], data[13], data[14], data[15]]))
}

/// Initialize an account's header from a layout contract type.
///
/// Convenience wrapper that pulls disc, version, layout_id, and
/// schema_epoch from the type.
#[inline(always)]
pub fn init_header<T: LayoutContract>(data: &mut [u8]) -> ProgramResult {
    write_header_with_epoch(data, T::DISC, T::VERSION, &T::LAYOUT_ID, T::SCHEMA_EPOCH)
}