Skip to main content

ic_memory/
stable_cell.rs

1use crate::{LedgerCommitStore, constants::WASM_PAGE_SIZE_BYTES};
2use ic_stable_structures::{Memory, Storable, storable::Bound};
3use serde::{Deserialize, Serialize};
4use std::borrow::Cow;
5use thiserror::Error;
6
7/// Stable-cell magic prefix written by `ic-stable-structures::Cell`.
8pub const STABLE_CELL_MAGIC: &[u8; 3] = b"SCL";
9/// Stable-cell layout version supported by this adapter.
10pub const STABLE_CELL_LAYOUT_VERSION: u8 = 1;
11/// Stable-cell header byte length.
12pub const STABLE_CELL_HEADER_SIZE: usize = 8;
13/// Byte offset where the stable-cell value payload starts.
14pub const STABLE_CELL_VALUE_OFFSET: u64 = 8;
15
16///
17/// StableCellLedgerRecord
18///
19/// `ic-stable-structures::Cell` record containing an `ic-memory` allocation
20/// ledger commit store.
21///
22/// This is a substrate adapter DTO. It owns no framework policy and does not
23/// open application allocations.
24///
25
26#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
27#[serde(deny_unknown_fields)]
28pub struct StableCellLedgerRecord {
29    store: LedgerCommitStore,
30}
31
32impl StableCellLedgerRecord {
33    /// Construct a record from a commit store.
34    #[must_use]
35    #[cfg(test)]
36    pub(crate) const fn new(store: LedgerCommitStore) -> Self {
37        Self { store }
38    }
39
40    /// Borrow the embedded commit store.
41    #[must_use]
42    pub(crate) const fn store(&self) -> &LedgerCommitStore {
43        &self.store
44    }
45
46    /// Mutably borrow the embedded commit store.
47    pub(crate) const fn store_mut(&mut self) -> &mut LedgerCommitStore {
48        &mut self.store
49    }
50}
51
52impl Storable for StableCellLedgerRecord {
53    const BOUND: Bound = Bound::Unbounded;
54
55    fn to_bytes(&self) -> Cow<'_, [u8]> {
56        Cow::Owned(serialize_record(self))
57    }
58
59    fn into_bytes(self) -> Vec<u8> {
60        serialize_record(&self)
61    }
62
63    fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
64        decode_stable_cell_ledger_record(&bytes).unwrap_or_else(|err| {
65            panic!("StableCellLedgerRecord deserialize failed: {err}");
66        })
67    }
68}
69
70///
71/// StableCellPayloadError
72///
73/// Stable-cell payload decode failure.
74///
75
76#[non_exhaustive]
77#[derive(Clone, Debug, Eq, Error, PartialEq)]
78pub enum StableCellPayloadError {
79    /// Declared bytes exceed the current recovery ceiling before allocation.
80    #[error("stable-cell ledger payload length {value_len} exceeds recovery limit")]
81    TooLarge { value_len: u64 },
82    /// Memory contents do not start with the stable-cell marker.
83    #[error("memory is not an ic-stable-structures Cell")]
84    NotStableCell,
85    /// Stable-cell layout version does not match the adapter's current shape.
86    #[error("unexpected stable-cell layout version {version}")]
87    UnexpectedLayoutVersion {
88        /// Observed stable-cell version.
89        version: u8,
90    },
91    /// Stable-cell header length does not fit inside the memory.
92    #[error("stable-cell payload length {value_len} exceeds available bytes {available_bytes}")]
93    InvalidLength {
94        /// Encoded value length.
95        value_len: u64,
96        /// Available payload bytes in memory.
97        available_bytes: u64,
98    },
99}
100
101///
102/// StableCellLedgerError
103///
104/// Stable-cell ledger record validation failure.
105#[non_exhaustive]
106#[derive(Debug, Error)]
107pub enum StableCellLedgerError {
108    /// Stable-cell envelope is corrupt or unexpected.
109    #[error(transparent)]
110    Payload(#[from] StableCellPayloadError),
111    /// Stable-cell value bytes are not a valid ledger record.
112    #[error("stable-cell ledger record decode failed: {0}")]
113    Record(#[source] ciborium::de::Error<std::io::Error>),
114}
115
116/// Decode the raw value payload from an `ic-stable-structures::Cell` memory.
117///
118/// This helper is intentionally narrow: it recognizes the physical stable-cell
119/// envelope and returns the value bytes. It does not deserialize those bytes or
120/// decide whether they represent a valid allocation ledger.
121pub fn decode_stable_cell_payload<M: Memory>(
122    memory: &M,
123) -> Result<Vec<u8>, StableCellPayloadError> {
124    if memory.size() == 0 {
125        return Err(StableCellPayloadError::NotStableCell);
126    }
127
128    let mut header = [0; STABLE_CELL_HEADER_SIZE];
129    memory.read(0, &mut header);
130    if &header[0..3] != STABLE_CELL_MAGIC {
131        return Err(StableCellPayloadError::NotStableCell);
132    }
133    if header[3] != STABLE_CELL_LAYOUT_VERSION {
134        return Err(StableCellPayloadError::UnexpectedLayoutVersion { version: header[3] });
135    }
136
137    let value_len = u64::from(u32::from_le_bytes([
138        header[4], header[5], header[6], header[7],
139    ]));
140    let available_bytes = memory.size().saturating_mul(WASM_PAGE_SIZE_BYTES);
141    let payload_capacity = available_bytes.saturating_sub(STABLE_CELL_VALUE_OFFSET);
142    if value_len > payload_capacity {
143        return Err(StableCellPayloadError::InvalidLength {
144            value_len,
145            available_bytes: payload_capacity,
146        });
147    }
148    if value_len > crate::constants::MAX_LEDGER_RECORD_BYTES as u64 {
149        return Err(StableCellPayloadError::TooLarge { value_len });
150    }
151    #[expect(
152        clippy::cast_possible_truncation,
153        reason = "the admitted recovery ceiling is representable as usize"
154    )]
155    let value_len = value_len as usize;
156
157    let mut bytes = vec![0; value_len];
158    memory.read(STABLE_CELL_VALUE_OFFSET, &mut bytes);
159    Ok(bytes)
160}
161
162/// Decode a `StableCellLedgerRecord` from stable-cell value bytes.
163///
164/// This decodes only the cell value payload, not the enclosing stable-cell
165/// header. Use [`decode_stable_cell_payload`] first when inspecting raw stable
166/// memory.
167///
168/// The returned record is decoded DTO state, not authority. The runtime
169/// validates protected commit recovery before trusting any ledger payload.
170pub fn decode_stable_cell_ledger_record(
171    bytes: &[u8],
172) -> Result<StableCellLedgerRecord, ciborium::de::Error<std::io::Error>> {
173    crate::cbor::from_slice_exact(bytes)
174}
175
176/// Fallibly decode a ledger record from its stable-cell envelope and value.
177///
178/// Empty memory returns an uninitialized record without writing a cell. Nonempty
179/// memory must pass the current envelope, byte bounds and record decoding. The
180/// returned DTO still requires protected ledger recovery before it is authority.
181/// Keep this record for recovery rather than decoding again through the
182/// panic-based [`Storable::from_bytes`] used by `Cell::init`.
183pub fn decode_stable_cell_ledger_record_from_memory<M: Memory>(
184    memory: &M,
185) -> Result<StableCellLedgerRecord, StableCellLedgerError> {
186    if memory.size() == 0 {
187        return Ok(StableCellLedgerRecord::default());
188    }
189
190    let payload = decode_stable_cell_payload(memory)?;
191    decode_stable_cell_ledger_record(&payload).map_err(StableCellLedgerError::Record)
192}
193
194fn serialize_record(record: &StableCellLedgerRecord) -> Vec<u8> {
195    EncodedLedgerRecord::new(record)
196        .unwrap_or_else(|size| panic!("stable-cell ledger record exceeds limit: {size}"))
197        .buffer
198        .bytes
199}
200
201///
202/// EncodedLedgerRecord
203///
204/// Temporary publication bytes, never recovered authority or retained runtime state.
205///
206
207pub struct EncodedLedgerRecord {
208    buffer: crate::bounded_writer::BoundedWriter,
209}
210
211impl EncodedLedgerRecord {
212    pub(crate) fn new(record: &StableCellLedgerRecord) -> Result<Self, usize> {
213        // Payload lengths plus small DTO-sized slack are only a capacity hint,
214        // not a second CBOR layout calculation. The writer owns the exact bound.
215        let physical = record.store().physical();
216        let capacity = physical
217            .current()
218            .map_or(0, |slot| slot.payload().len())
219            .saturating_add(std::mem::size_of::<StableCellLedgerRecord>().saturating_mul(2))
220            .min(crate::constants::MAX_LEDGER_RECORD_BYTES);
221        let mut buffer = crate::bounded_writer::BoundedWriter::new(
222            Vec::with_capacity(capacity),
223            crate::constants::MAX_LEDGER_RECORD_BYTES,
224        );
225        if let Err(error) = ciborium::into_writer(record, &mut buffer) {
226            if buffer.attempted_len > crate::constants::MAX_LEDGER_RECORD_BYTES {
227                return Err(buffer.attempted_len);
228            }
229            panic!("StableCellLedgerRecord serialize failed: {error}");
230        }
231        Ok(Self { buffer })
232    }
233
234    pub(crate) const fn len(&self) -> usize {
235        self.buffer.bytes.len()
236    }
237}
238
239impl Storable for EncodedLedgerRecord {
240    const BOUND: Bound = Bound::Unbounded;
241
242    fn to_bytes(&self) -> Cow<'_, [u8]> {
243        Cow::Borrowed(&self.buffer.bytes)
244    }
245    fn into_bytes(self) -> Vec<u8> {
246        self.buffer.bytes
247    }
248    fn from_bytes(_: Cow<'_, [u8]>) -> Self {
249        panic!("publication bytes cannot recover ledger authority")
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256    use crate::test_cbor::hex_fixture;
257    use ic_stable_structures::{Cell, VectorMemory};
258
259    #[test]
260    fn publication_payload_refuses_oversized_chunks_before_buffering() {
261        use std::io::Write as _;
262
263        let mut encoded = EncodedLedgerRecord {
264            buffer: crate::bounded_writer::BoundedWriter::new(
265                Vec::new(),
266                crate::constants::MAX_LEDGER_RECORD_BYTES,
267            ),
268        };
269        let oversized = vec![0; crate::constants::MAX_LEDGER_RECORD_BYTES + 1];
270        assert!(encoded.buffer.write_all(&oversized).is_err());
271        assert_eq!(encoded.len(), 0);
272        assert_eq!(encoded.buffer.bytes.capacity(), 0);
273    }
274
275    #[test]
276    fn stable_cell_ledger_record_round_trips_through_cell() {
277        let memory = VectorMemory::default();
278        let record = StableCellLedgerRecord::default();
279        let cell = Cell::init(memory.clone(), record.clone());
280
281        assert_eq!(cell.get(), &record);
282        let payload = decode_stable_cell_payload(&memory).expect("decode stable cell payload");
283        let decoded = StableCellLedgerRecord::from_bytes(Cow::Owned(payload));
284        assert_eq!(decoded, record);
285        assert_eq!(
286            crate::decode_stable_cell_ledger_record_from_memory(&memory).unwrap(),
287            record
288        );
289    }
290
291    #[test]
292    fn current_stable_cell_record_fixture_recovers() {
293        let bytes = hex_fixture(include_str!(
294            "../fixtures/current/stable_cell_record.cbor.hex"
295        ));
296        let record = decode_stable_cell_ledger_record(&bytes).expect("stable-cell fixture");
297
298        assert_eq!(
299            EncodedLedgerRecord::new(&record).unwrap().len(),
300            bytes.len()
301        );
302        let encoded = EncodedLedgerRecord::new(&record).unwrap();
303        assert!(matches!(encoded.to_bytes(), Cow::Borrowed(_)));
304        let memory = VectorMemory::default();
305        drop(Cell::new(memory.clone(), encoded));
306        assert_eq!(decode_stable_cell_payload(&memory).unwrap(), bytes);
307        assert_eq!(record.to_bytes().as_ref(), bytes.as_slice());
308        assert_eq!(record.clone().into_bytes(), bytes);
309        assert_eq!(
310            bytes,
311            crate::test_cbor::to_vec(&record).expect("re-encoded stable-cell fixture")
312        );
313        assert_eq!(
314            record
315                .store()
316                .recover()
317                .expect("fixture store recovers")
318                .current_generation(),
319            1
320        );
321    }
322
323    #[test]
324    fn malformed_payload_bytes_fail_closed_without_mutating_memory() {
325        let original = hex_fixture(include_str!(
326            "../fixtures/current/stable_cell_record.cbor.hex"
327        ));
328        let start = original
329            .windows(8)
330            .position(|bytes| bytes == b"\x67payload")
331            .unwrap()
332            + 8;
333        let oversized = u32::try_from(crate::constants::MAX_COMMITTED_PAYLOAD_BYTES + 1).unwrap();
334        let mut cases = Vec::new();
335        for replacement in [
336            vec![0x5a, 0xff, 0xff, 0xff, 0xff],
337            vec![0x5f, 0xff],
338            vec![0x41],
339            vec![0xff],
340        ] {
341            let mut bytes = original[..start].to_vec();
342            bytes.extend(replacement);
343            cases.push(bytes);
344        }
345        let mut bytes = original[..start].to_vec();
346        bytes.push(0x5a);
347        bytes.extend_from_slice(&oversized.to_be_bytes());
348        bytes.resize(bytes.len() + oversized as usize, 0);
349        cases.push(bytes);
350        for bytes in cases {
351            let memory = VectorMemory::default();
352            let pages = (bytes.len() + STABLE_CELL_HEADER_SIZE).div_ceil(65_536);
353            memory.grow(pages as u64);
354            memory.write(0, STABLE_CELL_MAGIC);
355            memory.write(3, &[STABLE_CELL_LAYOUT_VERSION]);
356            memory.write(4, &u32::try_from(bytes.len()).unwrap().to_le_bytes());
357            memory.write(STABLE_CELL_VALUE_OFFSET, &bytes);
358            let before = memory.borrow().clone();
359            for _ in 0..2 {
360                assert!(matches!(
361                    decode_stable_cell_ledger_record_from_memory(&memory),
362                    Err(StableCellLedgerError::Record(_))
363                ));
364            }
365            assert_eq!(*memory.borrow(), before);
366        }
367    }
368
369    #[test]
370    fn stable_cell_ledger_record_rejects_trailing_bytes() {
371        let mut bytes = serialize_record(&StableCellLedgerRecord::default());
372        bytes.push(0);
373
374        let err =
375            decode_stable_cell_ledger_record(&bytes).expect_err("trailing bytes must fail closed");
376
377        assert!(err.to_string().contains("trailing bytes"));
378    }
379
380    #[test]
381    fn stable_cell_ledger_record_rejects_unknown_top_level_fields() {
382        use crate::test_cbor::Value;
383
384        let map = vec![
385            (
386                Value::Text("store".to_string()),
387                crate::test_cbor::to_value(LedgerCommitStore::default()).expect("store value"),
388            ),
389            (Value::Text("future_field".to_string()), Value::Bool(true)),
390        ];
391        let bytes = crate::test_cbor::to_vec(&Value::Map(map)).expect("unknown-field stable cell");
392
393        let err = decode_stable_cell_ledger_record(&bytes)
394            .expect_err("unknown stable-cell record field must fail closed");
395
396        assert!(err.to_string().contains("future_field"));
397    }
398
399    #[test]
400    fn stable_cell_ledger_record_requires_an_explicit_current_snapshot() {
401        let bytes = crate::test_cbor::to_vec(&serde_json::json!({
402            "store": { "physical": {} }
403        }))
404        .unwrap();
405        let err = decode_stable_cell_ledger_record(&bytes)
406            .expect_err("missing current snapshot must not initialize");
407        assert!(err.to_string().contains("current"));
408    }
409
410    #[test]
411    fn stable_cell_payload_rejects_non_cell_memory() {
412        let memory = VectorMemory::default();
413        memory.grow(1);
414        memory.write(0, b"BAD");
415
416        assert_eq!(
417            decode_stable_cell_payload(&memory),
418            Err(StableCellPayloadError::NotStableCell)
419        );
420    }
421
422    #[test]
423    fn stable_cell_payload_rejects_empty_memory_without_panic() {
424        let memory = VectorMemory::default();
425
426        assert_eq!(
427            decode_stable_cell_payload(&memory),
428            Err(StableCellPayloadError::NotStableCell)
429        );
430        assert_eq!(
431            crate::decode_stable_cell_ledger_record_from_memory(&memory).unwrap(),
432            StableCellLedgerRecord::default()
433        );
434        assert_eq!(
435            memory.size(),
436            0,
437            "reading empty memory must not initialize it"
438        );
439    }
440
441    #[test]
442    fn stable_cell_ledger_memory_reader_classifies_bad_record_without_panic() {
443        let memory = VectorMemory::default();
444        memory.grow(1);
445        memory.write(0, STABLE_CELL_MAGIC);
446        memory.write(3, &[STABLE_CELL_LAYOUT_VERSION]);
447        memory.write(4, &1_u32.to_le_bytes());
448        memory.write(STABLE_CELL_VALUE_OFFSET, &[0xff]);
449
450        let err = decode_stable_cell_ledger_record_from_memory(&memory)
451            .expect_err("bad record must be classified");
452
453        assert!(matches!(err, StableCellLedgerError::Record(_)));
454    }
455    #[test]
456    fn oversized_cell_length_is_rejected_before_payload_read() {
457        struct HeaderOnly {
458            value_len: u32,
459            pages: u64,
460        }
461        impl Memory for HeaderOnly {
462            fn size(&self) -> u64 {
463                self.pages
464            }
465            fn grow(&self, _: u64) -> i64 {
466                panic!("must not grow")
467            }
468            fn write(&self, _: u64, _: &[u8]) {
469                panic!("must not write")
470            }
471            fn read(&self, offset: u64, bytes: &mut [u8]) {
472                assert_eq!(offset, 0);
473                assert_eq!(bytes.len(), STABLE_CELL_HEADER_SIZE);
474                bytes[..4].copy_from_slice(b"SCL\x01");
475                bytes[4..8].copy_from_slice(&self.value_len.to_le_bytes());
476            }
477        }
478        for value_len in [
479            u32::try_from(crate::constants::MAX_LEDGER_RECORD_BYTES + 1).unwrap(),
480            u32::MAX,
481        ] {
482            // The advertised value fits the backing, but exceeds the recovery ceiling.
483            let memory = HeaderOnly {
484                value_len,
485                pages: 65_537,
486            };
487            assert!(matches!(
488                decode_stable_cell_ledger_record_from_memory(&memory),
489                Err(StableCellLedgerError::Payload(StableCellPayloadError::TooLarge {
490                    value_len: rejected,
491                })) if rejected == u64::from(value_len)
492            ));
493            // Physical-capacity rejection keeps precedence when both checks fail.
494            let memory = HeaderOnly {
495                value_len,
496                pages: 1,
497            };
498            assert_eq!(
499                decode_stable_cell_payload(&memory),
500                Err(StableCellPayloadError::InvalidLength {
501                    value_len: u64::from(value_len),
502                    available_bytes: WASM_PAGE_SIZE_BYTES - STABLE_CELL_VALUE_OFFSET,
503                })
504            );
505        }
506    }
507
508    #[test]
509    fn hostile_cbor_is_rejected_on_production_record_decode() {
510        let huge_array = [0x9b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
511        let huge_string = [0x7b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
512        let mut nested = vec![0x81; crate::constants::MAX_LEDGER_NESTING + 1];
513        nested.push(0);
514        for bytes in [&huge_array[..], &huge_string[..], &nested, &[0xa1], &[0xff]] {
515            assert!(decode_stable_cell_ledger_record(bytes).is_err());
516        }
517    }
518}