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
7pub const STABLE_CELL_MAGIC: &[u8; 3] = b"SCL";
9pub const STABLE_CELL_LAYOUT_VERSION: u8 = 1;
11pub const STABLE_CELL_HEADER_SIZE: usize = 8;
13pub const STABLE_CELL_VALUE_OFFSET: u64 = 8;
15
16#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
27#[serde(deny_unknown_fields)]
28pub struct StableCellLedgerRecord {
29 store: LedgerCommitStore,
30}
31
32impl StableCellLedgerRecord {
33 #[must_use]
35 pub const fn new(store: LedgerCommitStore) -> Self {
36 Self { store }
37 }
38
39 #[must_use]
41 pub const fn store(&self) -> &LedgerCommitStore {
42 &self.store
43 }
44
45 pub const fn store_mut(&mut self) -> &mut LedgerCommitStore {
47 &mut self.store
48 }
49
50 #[must_use]
52 pub fn into_store(self) -> LedgerCommitStore {
53 self.store
54 }
55}
56
57impl Storable for StableCellLedgerRecord {
58 const BOUND: Bound = Bound::Unbounded;
59
60 fn to_bytes(&self) -> Cow<'_, [u8]> {
61 Cow::Owned(serialize_record(self))
62 }
63
64 fn into_bytes(self) -> Vec<u8> {
65 serialize_record(&self)
66 }
67
68 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
69 decode_stable_cell_ledger_record(&bytes).unwrap_or_else(|err| {
70 panic!("StableCellLedgerRecord deserialize failed: {err}");
71 })
72 }
73}
74
75#[non_exhaustive]
80#[derive(Clone, Debug, Eq, Error, PartialEq)]
81pub enum StableCellPayloadError {
82 #[error("stable-cell ledger payload length {value_len} exceeds recovery limit")]
84 TooLarge { value_len: u64 },
85 #[error("memory is not an ic-stable-structures Cell")]
87 NotStableCell,
88 #[error("unexpected stable-cell layout version {version}")]
90 UnexpectedLayoutVersion {
91 version: u8,
93 },
94 #[error("stable-cell payload length {value_len} exceeds available bytes {available_bytes}")]
96 InvalidLength {
97 value_len: u64,
99 available_bytes: u64,
101 },
102 #[error("stable-cell payload length {value_len} cannot fit in usize")]
104 LengthOverflow {
105 value_len: u64,
107 },
108}
109
110#[non_exhaustive]
115#[derive(Debug, Error)]
116pub enum StableCellLedgerError {
117 #[error(transparent)]
119 Payload(#[from] StableCellPayloadError),
120 #[error("stable-cell ledger record decode failed")]
122 Record(#[source] ciborium::de::Error<std::io::Error>),
123}
124
125pub fn decode_stable_cell_payload<M: Memory>(
131 memory: &M,
132) -> Result<Vec<u8>, StableCellPayloadError> {
133 if memory.size() == 0 {
134 return Err(StableCellPayloadError::NotStableCell);
135 }
136
137 let mut header = [0; STABLE_CELL_HEADER_SIZE];
138 memory.read(0, &mut header);
139 if &header[0..3] != STABLE_CELL_MAGIC {
140 return Err(StableCellPayloadError::NotStableCell);
141 }
142 if header[3] != STABLE_CELL_LAYOUT_VERSION {
143 return Err(StableCellPayloadError::UnexpectedLayoutVersion { version: header[3] });
144 }
145
146 let value_len = u64::from(u32::from_le_bytes([
147 header[4], header[5], header[6], header[7],
148 ]));
149 let available_bytes = memory.size().saturating_mul(WASM_PAGE_SIZE_BYTES);
150 let payload_capacity = available_bytes.saturating_sub(STABLE_CELL_VALUE_OFFSET);
151 if value_len > payload_capacity {
152 return Err(StableCellPayloadError::InvalidLength {
153 value_len,
154 available_bytes: payload_capacity,
155 });
156 }
157 if value_len > crate::constants::MAX_LEDGER_RECORD_BYTES as u64 {
158 return Err(StableCellPayloadError::TooLarge { value_len });
159 }
160 let value_len = usize::try_from(value_len)
161 .map_err(|_| StableCellPayloadError::LengthOverflow { value_len })?;
162
163 let mut bytes = vec![0; value_len];
164 memory.read(STABLE_CELL_VALUE_OFFSET, &mut bytes);
165 Ok(bytes)
166}
167
168pub fn decode_stable_cell_ledger_record(
177 bytes: &[u8],
178) -> Result<StableCellLedgerRecord, ciborium::de::Error<std::io::Error>> {
179 crate::cbor::from_slice_exact(bytes)
180}
181
182pub fn decode_stable_cell_ledger_record_from_memory<M: Memory>(
183 memory: &M,
184) -> Result<StableCellLedgerRecord, StableCellLedgerError> {
185 if memory.size() == 0 {
186 return Ok(StableCellLedgerRecord::default());
187 }
188
189 let payload = decode_stable_cell_payload(memory)?;
190 decode_stable_cell_ledger_record(&payload).map_err(StableCellLedgerError::Record)
191}
192
193pub fn validate_stable_cell_ledger_memory<M: Memory>(
201 memory: &M,
202) -> Result<(), StableCellLedgerError> {
203 decode_stable_cell_ledger_record_from_memory(memory)?;
204 Ok(())
205}
206
207fn serialize_record(record: &StableCellLedgerRecord) -> Vec<u8> {
208 let mut bytes = Vec::new();
209 ciborium::into_writer(record, &mut bytes).unwrap_or_else(|err| {
210 panic!("StableCellLedgerRecord serialize failed: {err}");
211 });
212 bytes
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218 use crate::test_cbor::hex_fixture;
219 use ic_stable_structures::{Cell, VectorMemory};
220
221 #[test]
222 fn stable_cell_ledger_record_round_trips_through_cell() {
223 let memory = VectorMemory::default();
224 let record = StableCellLedgerRecord::default();
225 let cell = Cell::init(memory.clone(), record.clone());
226
227 assert_eq!(cell.get(), &record);
228 let payload = decode_stable_cell_payload(&memory).expect("decode stable cell payload");
229 let decoded = StableCellLedgerRecord::from_bytes(Cow::Owned(payload));
230 assert_eq!(decoded, record);
231 }
232
233 #[test]
234 fn current_stable_cell_record_fixture_recovers() {
235 let bytes = hex_fixture(include_str!(
236 "../fixtures/current/stable_cell_record.cbor.hex"
237 ));
238 let record = decode_stable_cell_ledger_record(&bytes).expect("stable-cell fixture");
239
240 assert_eq!(
241 bytes,
242 crate::test_cbor::to_vec(&record).expect("re-encoded stable-cell fixture")
243 );
244 assert_eq!(
245 record
246 .store()
247 .recover()
248 .expect("fixture store recovers")
249 .current_generation(),
250 1
251 );
252 }
253
254 #[test]
255 fn malformed_payload_bytes_fail_closed_without_mutating_memory() {
256 let original = hex_fixture(include_str!(
257 "../fixtures/current/stable_cell_record.cbor.hex"
258 ));
259 let start = original
260 .windows(8)
261 .position(|bytes| bytes == b"\x67payload")
262 .unwrap()
263 + 8;
264 let oversized = u32::try_from(crate::constants::MAX_COMMITTED_PAYLOAD_BYTES + 1).unwrap();
265 let mut cases = Vec::new();
266 for replacement in [
267 vec![0x5a, 0xff, 0xff, 0xff, 0xff],
268 vec![0x5f, 0xff],
269 vec![0x41],
270 vec![0xff],
271 ] {
272 let mut bytes = original[..start].to_vec();
273 bytes.extend(replacement);
274 cases.push(bytes);
275 }
276 let mut bytes = original[..start].to_vec();
277 bytes.push(0x5a);
278 bytes.extend_from_slice(&oversized.to_be_bytes());
279 bytes.resize(bytes.len() + oversized as usize, 0);
280 cases.push(bytes);
281 for bytes in cases {
282 let memory = VectorMemory::default();
283 let pages = (bytes.len() + STABLE_CELL_HEADER_SIZE).div_ceil(65_536);
284 memory.grow(pages as u64);
285 memory.write(0, STABLE_CELL_MAGIC);
286 memory.write(3, &[STABLE_CELL_LAYOUT_VERSION]);
287 memory.write(4, &u32::try_from(bytes.len()).unwrap().to_le_bytes());
288 memory.write(STABLE_CELL_VALUE_OFFSET, &bytes);
289 let before = memory.borrow().clone();
290 for _ in 0..2 {
291 assert!(matches!(
292 decode_stable_cell_ledger_record_from_memory(&memory),
293 Err(StableCellLedgerError::Record(_))
294 ));
295 assert!(matches!(
296 validate_stable_cell_ledger_memory(&memory),
297 Err(StableCellLedgerError::Record(_))
298 ));
299 }
300 assert_eq!(*memory.borrow(), before);
301 }
302 }
303
304 #[test]
305 fn stable_cell_ledger_record_rejects_trailing_bytes() {
306 let mut bytes = serialize_record(&StableCellLedgerRecord::default());
307 bytes.push(0);
308
309 let err =
310 decode_stable_cell_ledger_record(&bytes).expect_err("trailing bytes must fail closed");
311
312 assert!(err.to_string().contains("trailing bytes"));
313 }
314
315 #[test]
316 fn stable_cell_ledger_record_rejects_unknown_top_level_fields() {
317 use crate::test_cbor::Value;
318
319 let mut map = Vec::new();
320 crate::test_cbor::map_insert(
321 &mut map,
322 Value::Text("store".to_string()),
323 crate::test_cbor::to_value(LedgerCommitStore::default()).expect("store value"),
324 );
325 crate::test_cbor::map_insert(
326 &mut map,
327 Value::Text("future_field".to_string()),
328 Value::Bool(true),
329 );
330 let bytes = crate::test_cbor::to_vec(&Value::Map(map)).expect("unknown-field stable cell");
331
332 let err = decode_stable_cell_ledger_record(&bytes)
333 .expect_err("unknown stable-cell record field must fail closed");
334
335 assert!(err.to_string().contains("future_field"));
336 }
337
338 #[test]
339 fn stable_cell_ledger_record_requires_both_commit_slot_fields() {
340 use crate::test_cbor::Value;
341
342 for (missing, present) in [("slot0", "slot1"), ("slot1", "slot0")] {
343 let mut physical = Vec::new();
344 crate::test_cbor::map_insert(
345 &mut physical,
346 Value::Text(present.to_string()),
347 Value::Null,
348 );
349 let mut store = Vec::new();
350 crate::test_cbor::map_insert(
351 &mut store,
352 Value::Text("physical".to_string()),
353 Value::Map(physical),
354 );
355 let mut record = Vec::new();
356 crate::test_cbor::map_insert(
357 &mut record,
358 Value::Text("store".to_string()),
359 Value::Map(store),
360 );
361 let bytes = crate::test_cbor::to_vec(&Value::Map(record)).expect("record bytes");
362
363 let err = decode_stable_cell_ledger_record(&bytes)
364 .expect_err("missing commit slot must fail closed");
365
366 assert!(err.to_string().contains(missing));
367 }
368 }
369
370 #[test]
371 fn stable_cell_payload_rejects_non_cell_memory() {
372 let memory = VectorMemory::default();
373 memory.grow(1);
374 memory.write(0, b"BAD");
375
376 assert_eq!(
377 decode_stable_cell_payload(&memory),
378 Err(StableCellPayloadError::NotStableCell)
379 );
380 }
381
382 #[test]
383 fn stable_cell_payload_rejects_empty_memory_without_panic() {
384 let memory = VectorMemory::default();
385
386 assert_eq!(
387 decode_stable_cell_payload(&memory),
388 Err(StableCellPayloadError::NotStableCell)
389 );
390 }
391
392 #[test]
393 fn stable_cell_ledger_preflight_classifies_bad_record_without_panic() {
394 let memory = VectorMemory::default();
395 memory.grow(1);
396 memory.write(0, STABLE_CELL_MAGIC);
397 memory.write(3, &[STABLE_CELL_LAYOUT_VERSION]);
398 memory.write(4, &1_u32.to_le_bytes());
399 memory.write(STABLE_CELL_VALUE_OFFSET, &[0xff]);
400
401 let err =
402 validate_stable_cell_ledger_memory(&memory).expect_err("bad record must be classified");
403
404 assert!(matches!(err, StableCellLedgerError::Record(_)));
405 }
406 #[test]
407 fn oversized_cell_length_is_rejected_before_payload_read() {
408 struct HeaderOnly;
409 impl Memory for HeaderOnly {
410 fn size(&self) -> u64 {
411 2048
412 }
413 fn grow(&self, _: u64) -> i64 {
414 panic!("must not grow")
415 }
416 fn write(&self, _: u64, _: &[u8]) {
417 panic!("must not write")
418 }
419 fn read(&self, offset: u64, bytes: &mut [u8]) {
420 assert_eq!(offset, 0);
421 assert_eq!(bytes.len(), STABLE_CELL_HEADER_SIZE);
422 bytes[..4].copy_from_slice(b"SCL\x01");
423 bytes[4..8].copy_from_slice(
424 &u32::try_from(crate::constants::MAX_LEDGER_RECORD_BYTES + 1)
425 .unwrap()
426 .to_le_bytes(),
427 );
428 }
429 }
430 assert!(matches!(
431 decode_stable_cell_ledger_record_from_memory(&HeaderOnly),
432 Err(StableCellLedgerError::Payload(
433 StableCellPayloadError::TooLarge { .. }
434 ))
435 ));
436 }
437
438 #[test]
439 fn hostile_cbor_is_rejected_on_production_record_decode() {
440 let huge_array = [0x9b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
441 let huge_string = [0x7b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
442 let mut nested = vec![0x81; crate::constants::MAX_LEDGER_NESTING + 1];
443 nested.push(0);
444 for bytes in [&huge_array[..], &huge_string[..], &nested, &[0xa1], &[0xff]] {
445 assert!(decode_stable_cell_ledger_record(bytes).is_err());
446 }
447 }
448}