Skip to main content

ic_storage/stable_cell/
mod.rs

1//! Cell framing and read-only payload admission.
2//!
3//! This module owns the persisted envelope, not application codecs or leases.
4
5use crate::{Memory, WASM_PAGE_SIZE_BYTES};
6
7/// Number of bytes preceding a Cell payload in the current format.
8pub const STABLE_CELL_HEADER_SIZE: usize = 24;
9
10const DISCRIMINATOR: [u8; 8] = *b"STORCELL";
11const VERSION: u32 = 1;
12const PAYLOAD_OFFSET: u64 = STABLE_CELL_HEADER_SIZE as u64;
13
14///
15/// `StableCellPayloadError`
16///
17/// A framing or size refusal detected before reading the application payload.
18///
19
20#[derive(Debug, Clone, Copy, Eq, PartialEq, thiserror::Error)]
21#[non_exhaustive]
22pub enum StableCellPayloadError {
23    /// The payload exceeds the caller's ceiling or the host's buffer limit.
24    #[error("Cell payload length {value_len} exceeds the admitted limit")]
25    TooLarge {
26        /// Declared payload length in bytes, excluding the Cell header.
27        value_len: u64,
28    },
29    /// The allocation does not contain supported Cell framing.
30    #[error("allocation does not contain supported Cell framing")]
31    NotStableCell,
32    /// The declared payload extends beyond the allocation.
33    #[error("Cell payload length {value_len} exceeds available bytes {available_bytes}")]
34    InvalidLength {
35        /// Declared payload length in bytes, excluding the Cell header.
36        value_len: u64,
37        /// Allocation bytes available after the Cell header.
38        available_bytes: u64,
39    },
40}
41
42/// Admit the current Cell framing and return its payload length without reading
43/// or decoding the payload.
44///
45/// # Errors
46/// Returns an error for unsupported framing, an impossible extent, or a payload
47/// above `maximum` or the host's addressable buffer limit.
48///
49/// # Panics
50/// Panics if the supplied memory implementation refuses a size query or read.
51pub fn stable_cell_payload_length<M: Memory>(
52    memory: &M,
53    maximum: usize,
54) -> Result<usize, StableCellPayloadError> {
55    let capacity = memory
56        .size()
57        .checked_mul(WASM_PAGE_SIZE_BYTES)
58        .filter(|capacity| *capacity >= PAYLOAD_OFFSET)
59        .ok_or(StableCellPayloadError::NotStableCell)?;
60    let mut header = [0; STABLE_CELL_HEADER_SIZE];
61    memory.read(0, &mut header);
62    if header[..8] != DISCRIMINATOR
63        || header[8..12] != VERSION.to_le_bytes()
64        || header[12..16] != [0; 4]
65    {
66        return Err(StableCellPayloadError::NotStableCell);
67    }
68    let mut length = [0; 8];
69    length.copy_from_slice(&header[16..]);
70    let value_len = u64::from_le_bytes(length);
71    let available_bytes = capacity - PAYLOAD_OFFSET;
72    if value_len > available_bytes {
73        return Err(StableCellPayloadError::InvalidLength {
74            value_len,
75            available_bytes,
76        });
77    }
78    let length =
79        usize::try_from(value_len).map_err(|_| StableCellPayloadError::TooLarge { value_len })?;
80    if length > maximum || length > isize::MAX as usize {
81        return Err(StableCellPayloadError::TooLarge { value_len });
82    }
83    Ok(length)
84}
85
86fn header(value_len: u64) -> [u8; STABLE_CELL_HEADER_SIZE] {
87    let mut bytes = [0; STABLE_CELL_HEADER_SIZE];
88    bytes[..8].copy_from_slice(&DISCRIMINATOR);
89    bytes[8..12].copy_from_slice(&VERSION.to_le_bytes());
90    bytes[16..].copy_from_slice(&value_len.to_le_bytes());
91    bytes
92}
93
94pub fn read_payload<M: Memory>(memory: &M, length: usize) -> Vec<u8> {
95    // The caller has admitted this complete extent before allocating the buffer.
96    let mut bytes = Vec::with_capacity(length);
97    if length != 0 {
98        // SAFETY: Fresh capacity provides exclusive, correctly aligned storage
99        // for at least `length` bytes, disjoint from the backing and its state.
100        // A successful read initializes the entire destination before set_len
101        // publishes it. If reading unwinds after a partial copy, the Vec still
102        // has length zero and drops without exposing uninitialized bytes.
103        #[expect(
104            unsafe_code,
105            reason = "The admitted read initializes fresh Vec capacity."
106        )]
107        unsafe {
108            memory.read_unsafe(PAYLOAD_OFFSET, bytes.as_mut_ptr(), length);
109            bytes.set_len(length);
110        }
111    }
112    bytes
113}
114
115pub fn write_payload<M: Memory>(memory: &M, bytes: &[u8], previous_length: Option<usize>) -> bool {
116    let Ok(length) = u64::try_from(bytes.len()) else {
117        return false;
118    };
119    let Some(end) = PAYLOAD_OFFSET.checked_add(length) else {
120        return false;
121    };
122    // The exclusive lease keeps the previously admitted extent valid. A
123    // replacement inside that extent requires neither reservation nor a query.
124    if previous_length.is_none_or(|previous| bytes.len() > previous) {
125        let needed_pages = end.div_ceil(WASM_PAGE_SIZE_BYTES);
126        if needed_pages.checked_mul(WASM_PAGE_SIZE_BYTES).is_none() {
127            return false;
128        }
129        let current_pages = memory.size();
130        if current_pages.checked_mul(WASM_PAGE_SIZE_BYTES).is_none() {
131            return false;
132        }
133        if needed_pages > current_pages {
134            if memory.grow(needed_pages - current_pages) < 0 {
135                return false;
136            }
137            // Check a successful growth before publishing any bytes.
138            if memory
139                .size()
140                .checked_mul(WASM_PAGE_SIZE_BYTES)
141                .is_none_or(|capacity| capacity < end)
142            {
143                return false;
144            }
145        }
146    }
147    if !bytes.is_empty() {
148        memory.write(PAYLOAD_OFFSET, bytes);
149    }
150    // Publishing the header last does not promise native atomicity. The owner
151    // health guard covers every write; IC executions supply their own rollback.
152    if previous_length != Some(bytes.len()) {
153        memory.write(0, &header(length));
154    }
155    true
156}
157
158#[cfg(test)]
159mod tests;