Skip to main content

ic_storage/
stable_cell.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![0; length];
97    memory.read(PAYLOAD_OFFSET, &mut bytes);
98    bytes
99}
100
101pub fn write_payload<M: Memory>(memory: &M, bytes: &[u8], previous_length: Option<usize>) -> bool {
102    let Ok(length) = u64::try_from(bytes.len()) else {
103        return false;
104    };
105    let Some(end) = PAYLOAD_OFFSET.checked_add(length) else {
106        return false;
107    };
108    // The exclusive lease keeps the previously admitted extent valid. A
109    // replacement inside that extent requires neither reservation nor a query.
110    if previous_length.is_none_or(|previous| bytes.len() > previous) {
111        let needed_pages = end.div_ceil(WASM_PAGE_SIZE_BYTES);
112        if needed_pages.checked_mul(WASM_PAGE_SIZE_BYTES).is_none() {
113            return false;
114        }
115        let current_pages = memory.size();
116        if current_pages.checked_mul(WASM_PAGE_SIZE_BYTES).is_none() {
117            return false;
118        }
119        if needed_pages > current_pages {
120            if memory.grow(needed_pages - current_pages) < 0 {
121                return false;
122            }
123            // Check a successful growth before publishing any bytes.
124            if memory
125                .size()
126                .checked_mul(WASM_PAGE_SIZE_BYTES)
127                .is_none_or(|capacity| capacity < end)
128            {
129                return false;
130            }
131        }
132    }
133    if !bytes.is_empty() {
134        memory.write(PAYLOAD_OFFSET, bytes);
135    }
136    // Publishing the header last does not promise native atomicity. The owner
137    // health guard covers every write; IC executions supply their own rollback.
138    if previous_length != Some(bytes.len()) {
139        memory.write(0, &header(length));
140    }
141    true
142}