Skip to main content

ic_memory/
stable_cell.rs

1use crate::{LedgerCommitStore, constants::WASM_PAGE_SIZE_BYTES};
2use ic_platform::stable_structures::{Memory, Storable, storable::Bound};
3use std::borrow::Cow;
4use thiserror::Error;
5
6/// Stable-cell magic prefix written by `ic-stable-structures::Cell`.
7pub const STABLE_CELL_MAGIC: &[u8; 3] = b"SCL";
8/// Stable-cell layout version supported by this adapter.
9pub const STABLE_CELL_LAYOUT_VERSION: u8 = 1;
10/// Stable-cell header byte length.
11pub const STABLE_CELL_HEADER_SIZE: usize = 8;
12/// Byte offset where the stable-cell value payload starts.
13pub const STABLE_CELL_VALUE_OFFSET: u64 = 8;
14
15///
16/// StableCellPayloadError
17///
18/// Stable-cell payload decode failure.
19///
20
21#[non_exhaustive]
22#[derive(Clone, Debug, Eq, Error, PartialEq)]
23pub enum StableCellPayloadError {
24    /// Declared bytes exceed the current recovery ceiling before allocation.
25    #[error("stable-cell ledger payload length {value_len} exceeds recovery limit")]
26    TooLarge { value_len: u64 },
27    /// Memory contents do not start with the stable-cell marker.
28    #[error("memory is not an ic-stable-structures Cell")]
29    NotStableCell,
30    /// Stable-cell layout version does not match the adapter's current shape.
31    #[error("unexpected stable-cell layout version {version}")]
32    UnexpectedLayoutVersion {
33        /// Observed stable-cell version.
34        version: u8,
35    },
36    /// Stable-cell header length does not fit inside the memory.
37    #[error("stable-cell payload length {value_len} exceeds available bytes {available_bytes}")]
38    InvalidLength {
39        /// Encoded value length.
40        value_len: u64,
41        /// Available payload bytes in memory.
42        available_bytes: u64,
43    },
44}
45
46///
47/// StableCellLedgerError
48///
49/// Stable-cell ledger record validation failure.
50///
51/// Record errors retain the IC Wire decoder's typed source. Ledger recovery and
52/// allocation integrity remain separate checks after decoding.
53///
54
55#[non_exhaustive]
56#[derive(Debug, Error)]
57pub enum StableCellLedgerError {
58    /// Stable-cell envelope is corrupt or unexpected.
59    #[error(transparent)]
60    Payload(#[from] StableCellPayloadError),
61    /// Stable-cell value bytes are not a valid ledger record.
62    #[error("stable-cell ledger record decode failed: {0}")]
63    Record(#[source] ic_wire::Error),
64}
65
66/// Decode the raw value payload from an `ic-stable-structures::Cell` memory.
67///
68/// This helper is intentionally narrow: it recognizes the physical stable-cell
69/// envelope and returns the value bytes. It does not deserialize those bytes or
70/// decide whether they represent a valid allocation ledger.
71pub fn decode_stable_cell_payload<M: Memory>(
72    memory: &M,
73) -> Result<Vec<u8>, StableCellPayloadError> {
74    let value_len = stable_cell_payload_length(memory, crate::constants::MAX_LEDGER_RECORD_BYTES)?;
75    let mut bytes = vec![0; value_len];
76    memory.read(STABLE_CELL_VALUE_OFFSET, &mut bytes);
77    Ok(bytes)
78}
79
80/// Validate a stable-cell envelope and return its payload length.
81///
82/// Reject empty/foreign memory, unsupported layouts, lengths beyond the backing
83/// extent, and lengths above the caller's `maximum`. No payload is allocated or
84/// read, and memory is never written or grown. This does not validate the value's
85/// codec or schema. The ledger reader retains its separate recovery ceiling.
86///
87/// # Panics
88/// Propagates backing `size`/`read` failures.
89pub fn stable_cell_payload_length<M: Memory>(
90    memory: &M,
91    maximum: usize,
92) -> Result<usize, StableCellPayloadError> {
93    if memory.size() == 0 {
94        return Err(StableCellPayloadError::NotStableCell);
95    }
96
97    let mut header = [0; STABLE_CELL_HEADER_SIZE];
98    memory.read(0, &mut header);
99    if &header[0..3] != STABLE_CELL_MAGIC {
100        return Err(StableCellPayloadError::NotStableCell);
101    }
102    if header[3] != STABLE_CELL_LAYOUT_VERSION {
103        return Err(StableCellPayloadError::UnexpectedLayoutVersion { version: header[3] });
104    }
105
106    let value_len = u64::from(u32::from_le_bytes([
107        header[4], header[5], header[6], header[7],
108    ]));
109    let available_bytes = memory.size().saturating_mul(WASM_PAGE_SIZE_BYTES);
110    let payload_capacity = available_bytes.saturating_sub(STABLE_CELL_VALUE_OFFSET);
111    if value_len > payload_capacity {
112        return Err(StableCellPayloadError::InvalidLength {
113            value_len,
114            available_bytes: payload_capacity,
115        });
116    }
117    if value_len > maximum as u64 {
118        return Err(StableCellPayloadError::TooLarge { value_len });
119    }
120    #[expect(
121        clippy::cast_possible_truncation,
122        reason = "the admitted caller ceiling is representable as usize"
123    )]
124    let value_len = value_len as usize;
125    Ok(value_len)
126}
127
128/// Decode a `LedgerCommitStore` from stable-cell value bytes.
129///
130/// This decodes only the cell value payload, not the enclosing stable-cell
131/// header. Use [`decode_stable_cell_payload`] first when inspecting raw stable
132/// memory.
133///
134/// The returned record is decoded DTO state, not authority. The runtime
135/// validates protected commit recovery before trusting any ledger payload.
136pub fn decode_stable_cell_commit_store(bytes: &[u8]) -> Result<LedgerCommitStore, ic_wire::Error> {
137    use crate::encoding::{RECORD_LIMITS, RECORD_MAGIC};
138    if bytes.len() > crate::constants::MAX_LEDGER_RECORD_BYTES {
139        return Err(ic_wire::Error::Limit);
140    }
141    let payload = bytes
142        .strip_prefix(RECORD_MAGIC)
143        .ok_or(ic_wire::Error::Malformed)?;
144    ic_wire::native::decode(payload, RECORD_LIMITS)
145}
146
147/// Fallibly decode a ledger record from its stable-cell envelope and value.
148///
149/// Empty memory returns an uninitialized record without writing a cell. Nonempty
150/// memory must pass the current envelope, byte bounds and record decoding. The
151/// returned DTO still requires protected ledger recovery before it is authority.
152/// The runtime retains this decoded record for recovery and separately prepares
153/// bounded publication bytes; reading never initializes a Cell.
154pub fn decode_stable_cell_commit_store_from_memory<M: Memory>(
155    memory: &M,
156) -> Result<LedgerCommitStore, StableCellLedgerError> {
157    if memory.size() == 0 {
158        return Ok(LedgerCommitStore::default());
159    }
160
161    let payload = decode_stable_cell_payload(memory)?;
162    decode_stable_cell_commit_store(&payload).map_err(StableCellLedgerError::Record)
163}
164
165///
166/// EncodedLedgerRecord
167///
168/// Temporary publication bytes, never recovered authority or retained runtime state.
169///
170
171pub struct EncodedLedgerRecord {
172    bytes: Vec<u8>,
173}
174
175impl EncodedLedgerRecord {
176    pub(crate) fn new(record: &LedgerCommitStore) -> Result<Self, ic_wire::Error> {
177        use crate::encoding::{RECORD_LIMITS, RECORD_MAGIC};
178        let payload = ic_wire::native::encode(record, RECORD_LIMITS)?;
179        let mut bytes = Vec::with_capacity(RECORD_MAGIC.len() + payload.len());
180        bytes.extend_from_slice(RECORD_MAGIC);
181        bytes.extend_from_slice(&payload);
182        Ok(Self { bytes })
183    }
184
185    pub(crate) const fn len(&self) -> usize {
186        self.bytes.len()
187    }
188}
189
190impl Storable for EncodedLedgerRecord {
191    const BOUND: Bound = Bound::Unbounded;
192
193    fn to_bytes(&self) -> Cow<'_, [u8]> {
194        Cow::Borrowed(&self.bytes)
195    }
196    fn into_bytes(self) -> Vec<u8> {
197        self.bytes
198    }
199    fn from_bytes(_: Cow<'_, [u8]>) -> Self {
200        panic!("publication bytes cannot recover ledger authority")
201    }
202}
203
204#[cfg(test)]
205mod tests;