Skip to main content

hopper_runtime/
layout.rs

1//! Layout contracts as runtime truth.
2//!
3//! `LayoutContract` is the central trait for Hopper's state-first architecture.
4//! It ties together discriminator, version, and layout fingerprint into a single
5//! compile-time contract that the runtime can validate before granting typed access.
6//!
7//! This is what makes Hopper different from every other Solana framework:
8//! layouts are not just metadata or serialization hints. They are runtime contracts
9//! that gate account access, enforce compatibility, and enable schema evolution.
10//!
11//! No competitor (Pinocchio, Steel, Quasar) has anything equivalent.
12
13use crate::error::ProgramError;
14use crate::field_map::{FieldInfo, FieldMap};
15use crate::ProgramResult;
16
17// ══════════════════════════════════════════════════════════════════════
18//  HopperHeader -- the 16-byte on-chain header present in every Hopper
19//  account.
20// ══════════════════════════════════════════════════════════════════════
21
22/// The canonical 16-byte header at the start of every Hopper account.
23///
24/// The Hopper Safety Audit's "header epoching" recommendation asked
25/// the reserved tail to carry a `schema_epoch: u32` so the runtime
26/// can distinguish schema-compatible minor versions from wire-
27/// incompatible revisions without bumping the single `version` byte.
28///
29/// ```text
30/// byte 0     : disc (u8)
31/// byte 1     : version (u8)
32/// bytes 2-3  : flags (u16 LE)
33/// bytes 4-11 : layout_id (first 8 bytes of canonical wire fingerprint)
34/// bytes 12-15: schema_epoch (u32 LE), audit-added
35/// ```
36///
37/// `schema_epoch` defaults to `1` at account initialisation via
38/// [`init_header`]. Programs that publish a migration bump this
39/// field to advertise the new shape while retaining the same
40/// `disc`/`version`; on-chain manifests (future work) pin the
41/// `(disc, version, schema_epoch, layout_id)` tuple so clients can
42/// verify they're reading the expected wire format.
43#[repr(C, packed)]
44#[derive(Copy, Clone, Debug, PartialEq, Eq)]
45pub struct HopperHeader {
46    pub disc: u8,
47    pub version: u8,
48    pub flags: u16,
49    pub layout_id: [u8; 8],
50    /// Schema-evolution epoch. Little-endian u32. `1` for freshly
51    /// initialised headers; bumped by migration helpers.
52    pub schema_epoch: u32,
53}
54
55impl HopperHeader {
56    /// The header is always 16 bytes.
57    pub const SIZE: usize = 16;
58
59    /// Read a header from the start of a raw data slice.
60    #[inline(always)]
61    pub fn from_bytes(data: &[u8]) -> Option<&Self> {
62        if data.len() < Self::SIZE {
63            return None;
64        }
65        // SAFETY: HopperHeader is packed to alignment 1.
66        Some(unsafe { &*(data.as_ptr() as *const Self) })
67    }
68
69    /// Read a mutable header from the start of a raw data slice.
70    #[inline(always)]
71    pub fn from_bytes_mut(data: &mut [u8]) -> Option<&mut Self> {
72        if data.len() < Self::SIZE {
73            return None;
74        }
75        Some(unsafe { &mut *(data.as_mut_ptr() as *mut Self) })
76    }
77}
78
79// ══════════════════════════════════════════════════════════════════════
80//  LayoutInfo -- runtime-inspectable metadata snapshot
81// ══════════════════════════════════════════════════════════════════════
82
83/// Runtime metadata snapshot of an account's layout identity.
84///
85/// Returned by `AccountView::layout_info()`. Enables manager inspection,
86/// schema comparison, and version-aware loading without knowing the
87/// concrete layout type at compile time.
88#[derive(Copy, Clone, Debug, PartialEq, Eq)]
89pub struct LayoutInfo {
90    pub disc: u8,
91    pub version: u8,
92    pub flags: u16,
93    pub layout_id: [u8; 8],
94    /// Schema-evolution epoch read from the header's bytes 12..16.
95    /// A value of `0` means "legacy" (pre-audit accounts) and is
96    /// treated as equivalent to `DEFAULT_SCHEMA_EPOCH` when comparing
97    /// against `AccountLayout::SCHEMA_EPOCH`.
98    pub schema_epoch: u32,
99    pub data_len: usize,
100}
101
102impl LayoutInfo {
103    /// Read layout info from an account's raw data.
104    #[inline(always)]
105    pub fn from_data(data: &[u8]) -> Option<Self> {
106        let hdr = HopperHeader::from_bytes(data)?;
107        // Packed-struct field reads must go through a copy, reading
108        // an unaligned `u32` reference directly is undefined behaviour.
109        let schema_epoch = hdr.schema_epoch;
110        let layout_id = hdr.layout_id;
111        Some(Self {
112            disc: hdr.disc,
113            version: hdr.version,
114            flags: hdr.flags,
115            layout_id,
116            schema_epoch,
117            data_len: data.len(),
118        })
119    }
120
121    /// Whether this account matches the given layout contract.
122    #[inline(always)]
123    pub fn matches<T: LayoutContract>(&self) -> bool {
124        self.disc == T::DISC
125            && self.version == T::VERSION
126            && self.layout_id == T::LAYOUT_ID
127            && self.data_len >= T::required_len()
128    }
129
130    /// Length of the account body after the Hopper header.
131    #[inline(always)]
132    pub const fn body_len(&self) -> usize {
133        self.data_len.saturating_sub(HopperHeader::SIZE)
134    }
135
136    /// Whether the account contains bytes beyond a given absolute offset.
137    #[inline(always)]
138    pub const fn has_bytes_after(&self, offset: usize) -> bool {
139        self.data_len > offset
140    }
141}
142
143// ══════════════════════════════════════════════════════════════════════
144//  LayoutContract -- the central state contract trait
145// ══════════════════════════════════════════════════════════════════════
146
147/// A compile-time layout contract binding type identity to wire format.
148///
149/// Implementors declare their discriminator, version, layout fingerprint,
150/// and wire size. The runtime uses these to validate accounts before granting
151/// typed access via `overlay` or `load`.
152///
153/// # Wire format (Hopper account header)
154///
155/// ```text
156/// byte 0   : discriminator (u8)
157/// byte 1   : version (u8)
158/// bytes 2-3: flags (u16 LE)
159/// bytes 4-11: layout_id (first 8 bytes of SHA-256 fingerprint)
160/// bytes 12-15: reserved
161/// ```
162///
163/// # Example
164///
165/// ```ignore
166/// impl LayoutContract for Vault {
167///     const DISC: u8 = 1;
168///     const VERSION: u8 = 1;
169///     const LAYOUT_ID: [u8; 8] = compute_layout_id("Vault", 1, "authority:[u8;32]:32,balance:LeU64:8,");
170///     const SIZE: usize = 16 + 32 + 8; // header + fields
171/// }
172/// ```
173pub trait LayoutContract: Sized + Copy + FieldMap {
174    /// Account type discriminator (byte 0 of data).
175    const DISC: u8;
176
177    /// Schema version for this layout (byte 1 of data).
178    const VERSION: u8;
179
180    /// First 8 bytes of the deterministic layout fingerprint.
181    /// Computed from `SHA-256("hopper:v1:" + name + ":" + version + ":" + field_spec)`.
182    const LAYOUT_ID: [u8; 8];
183
184    /// Total wire size in bytes (including the 16-byte header).
185    const SIZE: usize;
186
187    /// Byte offset where the typed projection begins.
188    ///
189    /// Body-only runtime layouts keep the default `HopperHeader::SIZE`, while
190    /// header-inclusive layouts set this to `0` so `AccountView::load()`
191    /// projects the full account struct.
192    const TYPE_OFFSET: usize = HopperHeader::SIZE;
193
194    /// Number of reserved bytes at the end of the layout. Reserved bytes
195    /// provide forward-compatible padding that future versions can claim
196    /// without a realloc.
197    const RESERVED_BYTES: usize = 0;
198
199    /// Byte offset where an extension region begins, if the layout supports one.
200    /// Extension regions allow appending variable-length data beyond the fixed
201    /// layout without breaking existing readers.
202    const EXTENSION_OFFSET: Option<usize> = None;
203
204    /// Validate a raw data slice against this contract.
205    ///
206    /// Returns `Ok(())` if the discriminator, version, and layout_id all match.
207    /// This is the canonical "is this account what I think it is?" check.
208    #[inline(always)]
209    fn validate_header(data: &[u8]) -> ProgramResult {
210        if data.len() < Self::required_len() {
211            return ProgramError::err_data_too_small();
212        }
213        let disc = read_disc(data);
214        if disc != Some(Self::DISC) {
215            return ProgramError::err_invalid_data();
216        }
217        let version = read_version(data);
218        if version != Some(Self::VERSION) {
219            return ProgramError::err_invalid_data();
220        }
221        if let Some(id) = read_layout_id(data) {
222            if *id != Self::LAYOUT_ID {
223                return ProgramError::err_invalid_data();
224            }
225        } else {
226            return ProgramError::err_data_too_small();
227        }
228        Ok(())
229    }
230
231    /// Byte length required to project this typed view safely.
232    #[inline(always)]
233    fn projected_len() -> usize {
234        Self::TYPE_OFFSET + core::mem::size_of::<Self>()
235    }
236
237    /// Minimum account data length required by both the wire contract and projection shape.
238    #[inline(always)]
239    fn required_len() -> usize {
240        if Self::SIZE > Self::projected_len() {
241            Self::SIZE
242        } else {
243            Self::projected_len()
244        }
245    }
246
247    /// Lightweight boolean validation helper for foreign readers and tools.
248    #[inline(always)]
249    fn validate(data: &[u8]) -> bool {
250        Self::validate_header(data).is_ok()
251    }
252
253    /// Check only the discriminator (fast path for dispatch).
254    #[inline(always)]
255    fn check_disc(data: &[u8]) -> ProgramResult {
256        match read_disc(data) {
257            Some(d) if d == Self::DISC => Ok(()),
258            _ => ProgramError::err_invalid_data(),
259        }
260    }
261
262    /// Check only the version (for migration gates).
263    #[inline(always)]
264    fn check_version(data: &[u8]) -> ProgramResult {
265        match read_version(data) {
266            Some(v) if v == Self::VERSION => Ok(()),
267            _ => ProgramError::err_invalid_data(),
268        }
269    }
270
271    /// Check whether a given version is compatible with this layout.
272    ///
273    /// The default implementation accepts only the exact version, but
274    /// implementors can override this to accept older versions for
275    /// backward-compatible migration.
276    #[inline(always)]
277    fn compatible(version: u8) -> bool {
278        version == Self::VERSION
279    }
280
281    /// Check whether the account data contains an extension region
282    /// (data beyond the fixed layout boundary).
283    #[inline(always)]
284    fn has_extension_region(data: &[u8]) -> bool {
285        match Self::EXTENSION_OFFSET {
286            Some(offset) => data.len() > offset,
287            None => false,
288        }
289    }
290
291    /// Build a `LayoutInfo` snapshot from this contract's compile-time constants.
292    #[inline(always)]
293    fn layout_info_static() -> LayoutInfo {
294        LayoutInfo {
295            disc: Self::DISC,
296            version: Self::VERSION,
297            flags: 0,
298            layout_id: Self::LAYOUT_ID,
299            schema_epoch: DEFAULT_SCHEMA_EPOCH,
300            data_len: Self::required_len(),
301        }
302    }
303
304    /// Compile-time field metadata for this layout.
305    #[inline(always)]
306    fn fields() -> &'static [FieldInfo] {
307        Self::FIELDS
308    }
309}
310
311/// Read the discriminator from account data (byte 0).
312#[inline(always)]
313pub fn read_disc(data: &[u8]) -> Option<u8> {
314    data.first().copied()
315}
316
317/// Read the version from account data (byte 1).
318#[inline(always)]
319pub fn read_version(data: &[u8]) -> Option<u8> {
320    if data.len() < 2 { None } else { Some(data[1]) }
321}
322
323/// Read the 8-byte layout_id from account data (bytes 4..12).
324#[inline(always)]
325pub fn read_layout_id(data: &[u8]) -> Option<&[u8; 8]> {
326    if data.len() < 12 {
327        None
328    } else {
329        // SAFETY: bounds checked above, alignment is 1 for [u8; 8].
330        Some(unsafe { &*(data.as_ptr().add(4) as *const [u8; 8]) })
331    }
332}
333
334/// Read the flags from account data (bytes 2..4) as u16 LE.
335#[inline(always)]
336pub fn read_flags(data: &[u8]) -> Option<u16> {
337    if data.len() < 4 {
338        None
339    } else {
340        let bytes = [data[2], data[3]];
341        Some(u16::from_le_bytes(bytes))
342    }
343}
344
345/// Default schema-evolution epoch written by `init_header`.
346///
347/// Accounts initialised by pre-audit Hopper had the epoch region
348/// zeroed, so `0` is treated as "legacy, equivalent to 1" by the
349/// runtime checks that compare against an `AccountLayout::SCHEMA_EPOCH`.
350/// Freshly-initialised accounts now carry `1` so migrations can bump
351/// monotonically without any lookback.
352pub const DEFAULT_SCHEMA_EPOCH: u32 = 1;
353
354/// Write a complete Hopper header to the beginning of `data`.
355///
356/// Writes disc, version, flags (zeroed), layout_id, and the
357/// audit-added `schema_epoch = 1` (bytes 12..16).
358/// Returns `Err` if `data` is shorter than 16 bytes.
359#[inline(always)]
360pub fn write_header(
361    data: &mut [u8],
362    disc: u8,
363    version: u8,
364    layout_id: &[u8; 8],
365) -> ProgramResult {
366    write_header_with_epoch(data, disc, version, layout_id, DEFAULT_SCHEMA_EPOCH)
367}
368
369/// Write a Hopper header with a caller-specified schema epoch.
370///
371/// Used by migration helpers that need to stamp a new epoch while
372/// preserving `disc`/`version`/`layout_id`. Regular account creation
373/// should go through [`write_header`] (which defaults the epoch to
374/// `1`) or [`init_header`].
375#[inline(always)]
376pub fn write_header_with_epoch(
377    data: &mut [u8],
378    disc: u8,
379    version: u8,
380    layout_id: &[u8; 8],
381    schema_epoch: u32,
382) -> ProgramResult {
383    if data.len() < 16 {
384        return Err(ProgramError::AccountDataTooSmall);
385    }
386    data[0] = disc;
387    data[1] = version;
388    data[2] = 0;
389    data[3] = 0;
390    data[4..12].copy_from_slice(layout_id);
391    data[12..16].copy_from_slice(&schema_epoch.to_le_bytes());
392    Ok(())
393}
394
395/// Read the `schema_epoch` field from an already-written header.
396///
397/// Returns `None` if `data` is too short. Returns the stored value
398/// verbatim, callers that want the "0 means legacy" compatibility
399/// rule should apply it themselves:
400///
401/// ```ignore
402/// let stored = read_schema_epoch(data)?;
403/// let effective = if stored == 0 { DEFAULT_SCHEMA_EPOCH } else { stored };
404/// ```
405#[inline(always)]
406pub fn read_schema_epoch(data: &[u8]) -> Option<u32> {
407    if data.len() < 16 {
408        return None;
409    }
410    Some(u32::from_le_bytes([data[12], data[13], data[14], data[15]]))
411}
412
413/// Initialize an account's header from a layout contract type.
414///
415/// Convenience wrapper that pulls disc, version, and layout_id from
416/// the type and stamps `schema_epoch = DEFAULT_SCHEMA_EPOCH`.
417#[inline(always)]
418pub fn init_header<T: LayoutContract>(data: &mut [u8]) -> ProgramResult {
419    write_header(data, T::DISC, T::VERSION, &T::LAYOUT_ID)
420}