interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / store / v1.rs

1069 lines · 39649 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Canonical System Store v1 encodings from ADR 0015.
17//!
18//! This module provides format primitives only. It does not read or write a
19//! device, provision a region, mount a store, or implement transactions.
20
21use alloc::vec;
22use alloc::vec::Vec;
23
24use crate::crypto::sha256::Sha256;
25
26pub const STORE_UNIT_BYTES: usize = 4096;
27pub const MAX_CATALOG_ENTRIES: usize = 4096;
28pub const CATALOG_HEADER_BYTES: usize = 16;
29pub const CATALOG_ENTRY_BYTES: usize = 64;
30pub const MAX_OBJECT_BYTES: u64 = 67_108_864;
31pub const MAX_OBJECT_UNITS: u32 = 16_384;
32pub const MAX_TRANSACTION_OBJECTS: usize = 256;
33pub const MAX_TRANSACTION_UNITS: u64 = 32_768;
34pub const MAX_REGION_UNITS: u64 = 4_294_967_296;
35pub const OBJECT_KIND_CATALOG: u16 = 1;
36pub const OBJECT_KIND_COMMIT_RECORD: u16 = 2;
37pub const OBJECT_VERSION_V1: u16 = 1;
38pub const COMMIT_RECORD_BYTES: usize = 200;
39pub const SUPERBLOCK_CRC_OFFSET: usize = 168;
40pub const SUPERBLOCK_RESERVED_OFFSET: usize = 172;
41
42const OBJECT_DOMAIN: &[u8] = b"AIENOS-STORE-OBJECT-V1\0";
43const CATALOG_MAGIC: &[u8; 8] = b"AIENCAT1";
44const COMMIT_MAGIC: &[u8; 8] = b"AIENCMT1";
45const SUPERBLOCK_MAGIC: &[u8; 8] = b"AIENSTR1";
46
47#[derive(Clone, Copy, Debug, Eq, PartialEq)]
48pub enum FormatError {
49 InvalidLength,
50 InvalidObject,
51 ObjectTooLarge,
52 LengthOverflow,
53 MalformedDescriptor,
54 OutOfBounds,
55 Overlap,
56 CatalogTooLarge,
57 CatalogOrder,
58 DuplicateObject,
59 BadCatalogMagic,
60 UnsupportedVersion,
61 MalformedCommitRecord,
62 MalformedSuperblock,
63 BadSuperblockMagic,
64 BadSuperblockCrc,
65 NonzeroReserved,
66 WrongSuperblockSlot,
67 UnsupportedFeatures,
68 IntegrityFailure,
69 InvalidGeneration,
70 ConflictingRoots,
71 InconsistentHistory,
72}
73
74#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
75pub struct ObjectId(pub [u8; 32]);
76
77impl ObjectId {
78 pub fn calculate(kind: u16, version: u16, semantic_bytes: &[u8]) -> Result<Self, FormatError> {
79 if kind == 0 || version == 0 || semantic_bytes.is_empty() {
80 return Err(FormatError::InvalidObject);
81 }
82 if semantic_bytes.len() as u64 > MAX_OBJECT_BYTES {
83 return Err(FormatError::ObjectTooLarge);
84 }
85 let length =
86 u64::try_from(semantic_bytes.len()).map_err(|_| FormatError::ObjectTooLarge)?;
87 let mut hash = Sha256::new();
88 hash.update(OBJECT_DOMAIN);
89 hash.update(&kind.to_le_bytes());
90 hash.update(&version.to_le_bytes());
91 hash.update(&length.to_le_bytes());
92 hash.update(semantic_bytes);
93 Ok(Self(hash.finalize()))
94 }
95
96 /// Validate an entire physical object extent, including zero final padding.
97 pub fn validate_extent(
98 self,
99 kind: u16,
100 version: u16,
101 byte_length: u64,
102 extent: &[u8],
103 ) -> Result<(), FormatError> {
104 let units = object_unit_count(byte_length)?;
105 let extent_length = usize::try_from(u64::from(units) * STORE_UNIT_BYTES as u64)
106 .map_err(|_| FormatError::LengthOverflow)?;
107 if extent.len() != extent_length {
108 return Err(FormatError::InvalidLength);
109 }
110 let semantic_length =
111 usize::try_from(byte_length).map_err(|_| FormatError::LengthOverflow)?;
112 if extent[semantic_length..].iter().any(|byte| *byte != 0) {
113 return Err(FormatError::NonzeroReserved);
114 }
115 if Self::calculate(kind, version, &extent[..semantic_length])? != self {
116 return Err(FormatError::IntegrityFailure);
117 }
118 Ok(())
119 }
120}
121
122pub fn object_unit_count(byte_length: u64) -> Result<u32, FormatError> {
123 if byte_length == 0 {
124 return Err(FormatError::InvalidObject);
125 }
126 if byte_length > MAX_OBJECT_BYTES {
127 return Err(FormatError::ObjectTooLarge);
128 }
129 let units = byte_length
130 .checked_add(STORE_UNIT_BYTES as u64 - 1)
131 .ok_or(FormatError::LengthOverflow)?
132 / STORE_UNIT_BYTES as u64;
133 let units = u32::try_from(units).map_err(|_| FormatError::LengthOverflow)?;
134 if units > MAX_OBJECT_UNITS {
135 return Err(FormatError::ObjectTooLarge);
136 }
137 Ok(units)
138}
139
140#[derive(Clone, Copy, Debug, Eq, PartialEq)]
141pub struct CatalogEntry {
142 pub object_id: ObjectId,
143 pub kind: u16,
144 pub version: u16,
145 pub first_unit: u64,
146 pub byte_length: u64,
147 pub unit_count: u32,
148 pub flags: u16,
149}
150
151impl CatalogEntry {
152 pub fn encode(self) -> Result<[u8; CATALOG_ENTRY_BYTES], FormatError> {
153 self.validate_shape()?;
154 let mut bytes = [0u8; CATALOG_ENTRY_BYTES];
155 bytes[0..32].copy_from_slice(&self.object_id.0);
156 put_u16(&mut bytes, 32, self.kind);
157 put_u16(&mut bytes, 34, self.version);
158 put_u64(&mut bytes, 36, self.first_unit);
159 put_u64(&mut bytes, 44, self.byte_length);
160 put_u32(&mut bytes, 52, self.unit_count);
161 put_u16(&mut bytes, 56, self.flags);
162 Ok(bytes)
163 }
164
165 pub fn decode(bytes: &[u8]) -> Result<Self, FormatError> {
166 if bytes.len() != CATALOG_ENTRY_BYTES {
167 return Err(FormatError::InvalidLength);
168 }
169 if bytes[58..64].iter().any(|byte| *byte != 0) {
170 return Err(FormatError::NonzeroReserved);
171 }
172 let mut id = [0; 32];
173 id.copy_from_slice(&bytes[..32]);
174 let value = Self {
175 object_id: ObjectId(id),
176 kind: get_u16(bytes, 32)?,
177 version: get_u16(bytes, 34)?,
178 first_unit: get_u64(bytes, 36)?,
179 byte_length: get_u64(bytes, 44)?,
180 unit_count: get_u32(bytes, 52)?,
181 flags: get_u16(bytes, 56)?,
182 };
183 value.validate_shape()?;
184 Ok(value)
185 }
186
187 fn validate_shape(self) -> Result<(), FormatError> {
188 if self.kind < 3 || self.version == 0 || self.flags != 0 {
189 return Err(FormatError::MalformedDescriptor);
190 }
191 if object_unit_count(self.byte_length)? != self.unit_count {
192 return Err(FormatError::MalformedDescriptor);
193 }
194 Ok(())
195 }
196
197 pub fn validate_bounds(
198 self,
199 region_units: u64,
200 catalog_first_unit: u64,
201 committed_high_water: u64,
202 ) -> Result<(), FormatError> {
203 self.validate_shape()?;
204 if !(4..=MAX_REGION_UNITS).contains(&region_units)
205 || committed_high_water < 4
206 || committed_high_water > region_units
207 {
208 return Err(FormatError::OutOfBounds);
209 }
210 let end = self
211 .first_unit
212 .checked_add(u64::from(self.unit_count))
213 .ok_or(FormatError::LengthOverflow)?;
214 if self.first_unit < 2
215 || end > catalog_first_unit
216 || end > committed_high_water
217 || end > region_units
218 {
219 return Err(FormatError::OutOfBounds);
220 }
221 Ok(())
222 }
223}
224
225#[derive(Clone, Debug, Eq, PartialEq)]
226pub struct Catalog {
227 pub entries: Vec<CatalogEntry>,
228}
229
230impl Catalog {
231 pub fn encode(&self) -> Result<Vec<u8>, FormatError> {
232 if self.entries.len() > MAX_CATALOG_ENTRIES {
233 return Err(FormatError::CatalogTooLarge);
234 }
235 self.check_order()?;
236 let bytes_length = CATALOG_HEADER_BYTES
237 .checked_add(
238 self.entries
239 .len()
240 .checked_mul(CATALOG_ENTRY_BYTES)
241 .ok_or(FormatError::LengthOverflow)?,
242 )
243 .ok_or(FormatError::LengthOverflow)?;
244 let mut bytes = vec![0u8; bytes_length];
245 bytes[..8].copy_from_slice(CATALOG_MAGIC);
246 put_u16(&mut bytes, 8, 1);
247 put_u16(&mut bytes, 10, CATALOG_ENTRY_BYTES as u16);
248 put_u32(&mut bytes, 12, self.entries.len() as u32);
249 for (index, entry) in self.entries.iter().copied().enumerate() {
250 let start = CATALOG_HEADER_BYTES + index * CATALOG_ENTRY_BYTES;
251 bytes[start..start + CATALOG_ENTRY_BYTES].copy_from_slice(&entry.encode()?);
252 }
253 Ok(bytes)
254 }
255
256 pub fn decode(bytes: &[u8]) -> Result<Self, FormatError> {
257 if bytes.len() < CATALOG_HEADER_BYTES {
258 return Err(FormatError::InvalidLength);
259 }
260 if &bytes[..8] != CATALOG_MAGIC {
261 return Err(FormatError::BadCatalogMagic);
262 }
263 if get_u16(bytes, 8)? != 1 || get_u16(bytes, 10)? != CATALOG_ENTRY_BYTES as u16 {
264 return Err(FormatError::UnsupportedVersion);
265 }
266 let count =
267 usize::try_from(get_u32(bytes, 12)?).map_err(|_| FormatError::LengthOverflow)?;
268 if count > MAX_CATALOG_ENTRIES {
269 return Err(FormatError::CatalogTooLarge);
270 }
271 let expected = CATALOG_HEADER_BYTES
272 .checked_add(
273 count
274 .checked_mul(CATALOG_ENTRY_BYTES)
275 .ok_or(FormatError::LengthOverflow)?,
276 )
277 .ok_or(FormatError::LengthOverflow)?;
278 if bytes.len() != expected {
279 return Err(FormatError::InvalidLength);
280 }
281 let mut entries = Vec::with_capacity(count);
282 for index in 0..count {
283 let start = CATALOG_HEADER_BYTES + index * CATALOG_ENTRY_BYTES;
284 entries.push(CatalogEntry::decode(
285 &bytes[start..start + CATALOG_ENTRY_BYTES],
286 )?);
287 }
288 let catalog = Self { entries };
289 catalog.check_order()?;
290 Ok(catalog)
291 }
292
293 pub fn validate_extents(
294 &self,
295 region_units: u64,
296 catalog_first_unit: u64,
297 committed_high_water: u64,
298 ) -> Result<(), FormatError> {
299 if !(4..=MAX_REGION_UNITS).contains(&region_units)
300 || committed_high_water < 4
301 || committed_high_water > region_units
302 || catalog_first_unit < 2
303 || catalog_first_unit >= region_units
304 {
305 return Err(FormatError::OutOfBounds);
306 }
307 let mut extents = Vec::with_capacity(self.entries.len());
308 for entry in self.entries.iter().copied() {
309 entry.validate_bounds(region_units, catalog_first_unit, committed_high_water)?;
310 let end = entry
311 .first_unit
312 .checked_add(u64::from(entry.unit_count))
313 .ok_or(FormatError::LengthOverflow)?;
314 extents.push((entry.first_unit, end));
315 }
316 extents.sort_unstable();
317 if extents.windows(2).any(|pair| pair[0].1 > pair[1].0) {
318 return Err(FormatError::Overlap);
319 }
320 Ok(())
321 }
322
323 fn check_order(&self) -> Result<(), FormatError> {
324 for pair in self.entries.windows(2) {
325 if pair[0].object_id >= pair[1].object_id {
326 return if pair[0].object_id == pair[1].object_id {
327 Err(FormatError::DuplicateObject)
328 } else {
329 Err(FormatError::CatalogOrder)
330 };
331 }
332 }
333 Ok(())
334 }
335}
336
337#[derive(Clone, Debug, Eq, PartialEq)]
338pub struct CommitRecord {
339 pub store_uuid: [u8; 16],
340 pub region_units: u64,
341 pub generation: u64,
342 pub previous_generation: u64,
343 pub previous_commit_id: ObjectId,
344 pub previous_catalog_id: ObjectId,
345 pub catalog_id: ObjectId,
346 pub catalog_first_unit: u64,
347 pub catalog_byte_length: u64,
348 pub catalog_unit_count: u32,
349 pub catalog_entry_count: u32,
350 pub committed_high_water: u64,
351}
352
353impl CommitRecord {
354 pub fn encode(&self) -> Result<[u8; COMMIT_RECORD_BYTES], FormatError> {
355 self.validate()?;
356 let mut bytes = [0u8; COMMIT_RECORD_BYTES];
357 bytes[..8].copy_from_slice(COMMIT_MAGIC);
358 put_u16(&mut bytes, 8, 1);
359 put_u16(&mut bytes, 10, COMMIT_RECORD_BYTES as u16);
360 put_u16(&mut bytes, 12, 1);
361 put_u16(&mut bytes, 14, 0);
362 put_u64(&mut bytes, 16, 0);
363 put_u64(&mut bytes, 24, 0);
364 bytes[32..48].copy_from_slice(&self.store_uuid);
365 put_u64(&mut bytes, 48, self.region_units);
366 put_u64(&mut bytes, 56, self.generation);
367 put_u64(&mut bytes, 64, self.previous_generation);
368 bytes[72..104].copy_from_slice(&self.previous_commit_id.0);
369 bytes[104..136].copy_from_slice(&self.previous_catalog_id.0);
370 bytes[136..168].copy_from_slice(&self.catalog_id.0);
371 put_u64(&mut bytes, 168, self.catalog_first_unit);
372 put_u64(&mut bytes, 176, self.catalog_byte_length);
373 put_u32(&mut bytes, 184, self.catalog_unit_count);
374 put_u32(&mut bytes, 188, self.catalog_entry_count);
375 put_u64(&mut bytes, 192, self.committed_high_water);
376 Ok(bytes)
377 }
378
379 pub fn decode(bytes: &[u8]) -> Result<Self, FormatError> {
380 if bytes.len() != COMMIT_RECORD_BYTES || &bytes[..8] != COMMIT_MAGIC {
381 return Err(FormatError::MalformedCommitRecord);
382 }
383 if get_u16(bytes, 8)? != 1 || get_u16(bytes, 10)? as usize != COMMIT_RECORD_BYTES {
384 return Err(FormatError::UnsupportedVersion);
385 }
386 if get_u16(bytes, 12)? != 1 || get_u16(bytes, 14)? != 0 {
387 return Err(FormatError::UnsupportedVersion);
388 }
389 if get_u64(bytes, 16)? != 0 || get_u64(bytes, 24)? != 0 {
390 return Err(FormatError::UnsupportedFeatures);
391 }
392 let mut store_uuid = [0; 16];
393 store_uuid.copy_from_slice(&bytes[32..48]);
394 let mut prev_commit = [0; 32];
395 prev_commit.copy_from_slice(&bytes[72..104]);
396 let mut prev_catalog = [0; 32];
397 prev_catalog.copy_from_slice(&bytes[104..136]);
398 let mut catalog = [0; 32];
399 catalog.copy_from_slice(&bytes[136..168]);
400 let record = Self {
401 store_uuid,
402 region_units: get_u64(bytes, 48)?,
403 generation: get_u64(bytes, 56)?,
404 previous_generation: get_u64(bytes, 64)?,
405 previous_commit_id: ObjectId(prev_commit),
406 previous_catalog_id: ObjectId(prev_catalog),
407 catalog_id: ObjectId(catalog),
408 catalog_first_unit: get_u64(bytes, 168)?,
409 catalog_byte_length: get_u64(bytes, 176)?,
410 catalog_unit_count: get_u32(bytes, 184)?,
411 catalog_entry_count: get_u32(bytes, 188)?,
412 committed_high_water: get_u64(bytes, 192)?,
413 };
414 record.validate()?;
415 Ok(record)
416 }
417
418 pub fn object_id(&self) -> Result<ObjectId, FormatError> {
419 ObjectId::calculate(
420 OBJECT_KIND_COMMIT_RECORD,
421 OBJECT_VERSION_V1,
422 &self.encode()?,
423 )
424 }
425
426 pub fn validate(&self) -> Result<(), FormatError> {
427 if !(4..=MAX_REGION_UNITS).contains(&self.region_units) || self.generation == 0 {
428 return Err(FormatError::MalformedCommitRecord);
429 }
430 let expected_bytes = CATALOG_HEADER_BYTES
431 .checked_add(
432 usize::try_from(self.catalog_entry_count)
433 .map_err(|_| FormatError::LengthOverflow)?
434 .checked_mul(CATALOG_ENTRY_BYTES)
435 .ok_or(FormatError::LengthOverflow)?,
436 )
437 .ok_or(FormatError::LengthOverflow)?;
438 if self.catalog_entry_count as usize > MAX_CATALOG_ENTRIES
439 || self.catalog_byte_length != expected_bytes as u64
440 || object_unit_count(self.catalog_byte_length)? != self.catalog_unit_count
441 {
442 return Err(FormatError::MalformedCommitRecord);
443 }
444 let catalog_end = self
445 .catalog_first_unit
446 .checked_add(u64::from(self.catalog_unit_count))
447 .ok_or(FormatError::LengthOverflow)?;
448 if self.catalog_first_unit < 2
449 || catalog_end >= self.region_units
450 || self.committed_high_water != catalog_end + 1
451 || self.committed_high_water > self.region_units
452 {
453 return Err(FormatError::MalformedCommitRecord);
454 }
455 if self.generation == 1 {
456 if self.previous_generation != 0
457 || self.previous_commit_id != ObjectId([0; 32])
458 || self.previous_catalog_id != ObjectId([0; 32])
459 {
460 return Err(FormatError::InvalidGeneration);
461 }
462 } else if self.previous_generation.checked_add(1) != Some(self.generation)
463 || self.previous_commit_id == ObjectId([0; 32])
464 || self.previous_catalog_id == ObjectId([0; 32])
465 {
466 return Err(FormatError::InvalidGeneration);
467 }
468 Ok(())
469 }
470
471 pub fn validates_catalog(
472 &self,
473 catalog_id: ObjectId,
474 catalog: &Catalog,
475 ) -> Result<(), FormatError> {
476 let semantic = catalog.encode()?;
477 if self.catalog_id != catalog_id
478 || self.catalog_entry_count as usize != catalog.entries.len()
479 || self.catalog_byte_length != semantic.len() as u64
480 || object_unit_count(semantic.len() as u64)? != self.catalog_unit_count
481 || ObjectId::calculate(OBJECT_KIND_CATALOG, OBJECT_VERSION_V1, &semantic)? != catalog_id
482 {
483 return Err(FormatError::IntegrityFailure);
484 }
485 Ok(())
486 }
487
488 pub fn identifies_predecessor(&self, previous: &Self, previous_id: ObjectId) -> bool {
489 self.generation.checked_sub(1) == Some(previous.generation)
490 && self.previous_generation == previous.generation
491 && self.previous_commit_id == previous_id
492 && self.previous_catalog_id == previous.catalog_id
493 && self.store_uuid == previous.store_uuid
494 && self.region_units == previous.region_units
495 && self.catalog_first_unit >= previous.committed_high_water
496 }
497}
498
499#[derive(Clone, Debug, Eq, PartialEq)]
500pub struct Superblock {
501 pub store_uuid: [u8; 16],
502 pub slot_id: u32,
503 pub region_units: u64,
504 pub generation: u64,
505 pub commit_record_id: ObjectId,
506 pub commit_record_unit: u64,
507 pub catalog_id: ObjectId,
508 pub catalog_first_unit: u64,
509 pub catalog_byte_length: u64,
510 pub catalog_unit_count: u32,
511 pub catalog_entry_count: u32,
512 pub committed_high_water: u64,
513}
514
515impl Superblock {
516 pub fn encode(&self) -> Result<[u8; STORE_UNIT_BYTES], FormatError> {
517 self.validate_shape()?;
518 let mut bytes = [0u8; STORE_UNIT_BYTES];
519 bytes[..8].copy_from_slice(SUPERBLOCK_MAGIC);
520 put_u16(&mut bytes, 8, 1);
521 put_u16(&mut bytes, 10, 0);
522 put_u64(&mut bytes, 12, 0);
523 put_u64(&mut bytes, 20, 0);
524 bytes[28..44].copy_from_slice(&self.store_uuid);
525 put_u32(&mut bytes, 44, self.slot_id);
526 put_u64(&mut bytes, 48, self.region_units);
527 put_u64(&mut bytes, 56, self.generation);
528 bytes[64..96].copy_from_slice(&self.commit_record_id.0);
529 put_u64(&mut bytes, 96, self.commit_record_unit);
530 bytes[104..136].copy_from_slice(&self.catalog_id.0);
531 put_u64(&mut bytes, 136, self.catalog_first_unit);
532 put_u64(&mut bytes, 144, self.catalog_byte_length);
533 put_u32(&mut bytes, 152, self.catalog_unit_count);
534 put_u32(&mut bytes, 156, self.catalog_entry_count);
535 put_u64(&mut bytes, 160, self.committed_high_water);
536 let checksum = crc32c(&bytes);
537 put_u32(&mut bytes, SUPERBLOCK_CRC_OFFSET, checksum);
538 Ok(bytes)
539 }
540
541 pub fn decode(bytes: &[u8], expected_slot: u32) -> Result<Self, FormatError> {
542 if bytes.len() != STORE_UNIT_BYTES || &bytes[..8] != SUPERBLOCK_MAGIC {
543 return Err(FormatError::BadSuperblockMagic);
544 }
545 let stored_crc = get_u32(bytes, SUPERBLOCK_CRC_OFFSET)?;
546 let mut canonical = [0u8; STORE_UNIT_BYTES];
547 canonical.copy_from_slice(bytes);
548 canonical[SUPERBLOCK_CRC_OFFSET..SUPERBLOCK_CRC_OFFSET + 4].fill(0);
549 if crc32c(&canonical) != stored_crc {
550 return Err(FormatError::BadSuperblockCrc);
551 }
552 if bytes[SUPERBLOCK_RESERVED_OFFSET..]
553 .iter()
554 .any(|byte| *byte != 0)
555 {
556 return Err(FormatError::NonzeroReserved);
557 }
558 if get_u16(bytes, 8)? != 1 || get_u16(bytes, 10)? != 0 {
559 return Err(FormatError::UnsupportedVersion);
560 }
561 if get_u64(bytes, 12)? != 0 || get_u64(bytes, 20)? != 0 {
562 return Err(FormatError::UnsupportedFeatures);
563 }
564 let slot_id = get_u32(bytes, 44)?;
565 if slot_id != expected_slot || slot_id > 1 {
566 return Err(FormatError::WrongSuperblockSlot);
567 }
568 let mut uuid = [0; 16];
569 uuid.copy_from_slice(&bytes[28..44]);
570 let mut commit = [0; 32];
571 commit.copy_from_slice(&bytes[64..96]);
572 let mut catalog = [0; 32];
573 catalog.copy_from_slice(&bytes[104..136]);
574 let value = Self {
575 store_uuid: uuid,
576 slot_id,
577 region_units: get_u64(bytes, 48)?,
578 generation: get_u64(bytes, 56)?,
579 commit_record_id: ObjectId(commit),
580 commit_record_unit: get_u64(bytes, 96)?,
581 catalog_id: ObjectId(catalog),
582 catalog_first_unit: get_u64(bytes, 136)?,
583 catalog_byte_length: get_u64(bytes, 144)?,
584 catalog_unit_count: get_u32(bytes, 152)?,
585 catalog_entry_count: get_u32(bytes, 156)?,
586 committed_high_water: get_u64(bytes, 160)?,
587 };
588 value.validate_shape()?;
589 Ok(value)
590 }
591
592 pub fn validate_commit(
593 &self,
594 commit_id: ObjectId,
595 commit: &CommitRecord,
596 ) -> Result<(), FormatError> {
597 if self.commit_record_id != commit_id
598 || self.store_uuid != commit.store_uuid
599 || self.region_units != commit.region_units
600 || self.generation != commit.generation
601 || self.catalog_id != commit.catalog_id
602 || self.catalog_first_unit != commit.catalog_first_unit
603 || self.catalog_byte_length != commit.catalog_byte_length
604 || self.catalog_unit_count != commit.catalog_unit_count
605 || self.catalog_entry_count != commit.catalog_entry_count
606 || self.committed_high_water != commit.committed_high_water
607 || self.commit_record_unit.checked_add(1) != Some(commit.committed_high_water)
608 || self
609 .catalog_first_unit
610 .checked_add(u64::from(self.catalog_unit_count))
611 != Some(self.commit_record_unit)
612 {
613 return Err(FormatError::MalformedSuperblock);
614 }
615 Ok(())
616 }
617
618 pub fn equivalent_root(&self, other: &Self) -> bool {
619 self.store_uuid == other.store_uuid
620 && self.region_units == other.region_units
621 && self.generation == other.generation
622 && self.commit_record_id == other.commit_record_id
623 }
624
625 fn validate_shape(&self) -> Result<(), FormatError> {
626 if self.slot_id > 1
627 || !(4..=MAX_REGION_UNITS).contains(&self.region_units)
628 || self.generation == 0
629 || self.committed_high_water > self.region_units
630 || self.committed_high_water < 4
631 {
632 return Err(FormatError::MalformedSuperblock);
633 }
634 let expected_catalog_length = CATALOG_HEADER_BYTES
635 .checked_add(
636 usize::try_from(self.catalog_entry_count)
637 .map_err(|_| FormatError::LengthOverflow)?
638 .checked_mul(CATALOG_ENTRY_BYTES)
639 .ok_or(FormatError::LengthOverflow)?,
640 )
641 .ok_or(FormatError::LengthOverflow)?;
642 let catalog_end = self
643 .catalog_first_unit
644 .checked_add(u64::from(self.catalog_unit_count))
645 .ok_or(FormatError::LengthOverflow)?;
646 if self.catalog_entry_count as usize > MAX_CATALOG_ENTRIES
647 || self.catalog_byte_length != expected_catalog_length as u64
648 || object_unit_count(self.catalog_byte_length)? != self.catalog_unit_count
649 || self.catalog_first_unit < 2
650 || catalog_end != self.commit_record_unit
651 || self.commit_record_unit.checked_add(1) != Some(self.committed_high_water)
652 {
653 return Err(FormatError::MalformedSuperblock);
654 }
655 Ok(())
656 }
657}
658
659/// CRC-32C/Castagnoli, reflected polynomial 0x82f63b78, init/xorout all ones.
660pub fn crc32c(bytes: &[u8]) -> u32 {
661 let mut crc = 0xffff_ffffu32;
662 for byte in bytes {
663 crc ^= u32::from(*byte);
664 for _ in 0..8 {
665 let mask = 0u32.wrapping_sub(crc & 1);
666 crc = (crc >> 1) ^ (0x82f6_3b78 & mask);
667 }
668 }
669 !crc
670}
671
672fn get_u16(bytes: &[u8], offset: usize) -> Result<u16, FormatError> {
673 let field = bytes
674 .get(offset..offset.checked_add(2).ok_or(FormatError::LengthOverflow)?)
675 .ok_or(FormatError::InvalidLength)?;
676 Ok(u16::from_le_bytes([field[0], field[1]]))
677}
678fn get_u32(bytes: &[u8], offset: usize) -> Result<u32, FormatError> {
679 let field = bytes
680 .get(offset..offset.checked_add(4).ok_or(FormatError::LengthOverflow)?)
681 .ok_or(FormatError::InvalidLength)?;
682 Ok(u32::from_le_bytes([field[0], field[1], field[2], field[3]]))
683}
684fn get_u64(bytes: &[u8], offset: usize) -> Result<u64, FormatError> {
685 let field = bytes
686 .get(offset..offset.checked_add(8).ok_or(FormatError::LengthOverflow)?)
687 .ok_or(FormatError::InvalidLength)?;
688 Ok(u64::from_le_bytes([
689 field[0], field[1], field[2], field[3], field[4], field[5], field[6], field[7],
690 ]))
691}
692fn put_u16(bytes: &mut [u8], offset: usize, value: u16) {
693 bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes());
694}
695fn put_u32(bytes: &mut [u8], offset: usize, value: u32) {
696 bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
697}
698fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
699 bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
700}
701
702#[cfg(test)]
703mod tests {
704 use super::*;
705
706 fn from_hex<const N: usize>(value: &str) -> [u8; N] {
707 assert_eq!(value.len(), N * 2);
708 let mut out = [0; N];
709 for (index, byte) in out.iter_mut().enumerate() {
710 *byte = u8::from_str_radix(&value[index * 2..index * 2 + 2], 16).unwrap();
711 }
712 out
713 }
714
715 fn assert_sha256(bytes: &[u8], expected: &str) {
716 let mut hash = Sha256::new();
717 hash.update(bytes);
718 assert_eq!(hash.finalize(), from_hex::<32>(expected));
719 }
720
721 fn sample_genesis() -> (CommitRecord, ObjectId, Superblock) {
722 let catalog = Catalog { entries: vec![] };
723 let catalog_bytes = catalog.encode().unwrap();
724 let catalog_id =
725 ObjectId::calculate(OBJECT_KIND_CATALOG, OBJECT_VERSION_V1, &catalog_bytes).unwrap();
726 let record = CommitRecord {
727 store_uuid: core::array::from_fn(|index| index as u8),
728 region_units: 16,
729 generation: 1,
730 previous_generation: 0,
731 previous_commit_id: ObjectId([0; 32]),
732 previous_catalog_id: ObjectId([0; 32]),
733 catalog_id,
734 catalog_first_unit: 2,
735 catalog_byte_length: catalog_bytes.len() as u64,
736 catalog_unit_count: 1,
737 catalog_entry_count: 0,
738 committed_high_water: 4,
739 };
740 let commit_id = record.object_id().unwrap();
741 let superblock = Superblock {
742 store_uuid: record.store_uuid,
743 slot_id: 0,
744 region_units: record.region_units,
745 generation: record.generation,
746 commit_record_id: commit_id,
747 commit_record_unit: 3,
748 catalog_id,
749 catalog_first_unit: 2,
750 catalog_byte_length: catalog_bytes.len() as u64,
751 catalog_unit_count: 1,
752 catalog_entry_count: 0,
753 committed_high_water: 4,
754 };
755 (record, catalog_id, superblock)
756 }
757
758 #[test]
759 fn object_id_and_catalog_vectors_match_adr_0015() {
760 let semantic: [u8; 16] = core::array::from_fn(|index| index as u8);
761 let standalone = ObjectId::calculate(0x1234, 0x5678, &semantic).unwrap();
762 assert_eq!(
763 standalone.0,
764 from_hex("80b93b4e31915bf7a7fd4607e686e757924425d9a4f9c1e84f51672d1b9b1334")
765 );
766
767 let empty = Catalog { entries: vec![] };
768 let empty_bytes = empty.encode().unwrap();
769 assert_eq!(
770 empty_bytes,
771 from_hex::<16>("4149454e434154310100400000000000")
772 );
773 let empty_id =
774 ObjectId::calculate(OBJECT_KIND_CATALOG, OBJECT_VERSION_V1, &empty_bytes).unwrap();
775 assert_eq!(
776 empty_id.0,
777 from_hex("44197839cf88e93c480d77a0c234ce21362a038d33d398ead10e062906d7be6a")
778 );
779
780 let app_id = ObjectId::calculate(3, 1, &semantic).unwrap();
781 assert_eq!(
782 app_id.0,
783 from_hex("307663335463d5f838fdd1b60950a02c873a28cd6cea13c2ffbfa5d8e41145a6")
784 );
785 let entry = CatalogEntry {
786 object_id: app_id,
787 kind: 3,
788 version: 1,
789 first_unit: 4,
790 byte_length: 16,
791 unit_count: 1,
792 flags: 0,
793 };
794 let one = Catalog {
795 entries: vec![entry],
796 };
797 let one_bytes = one.encode().unwrap();
798 assert_eq!(one_bytes.len(), 80);
799 assert_sha256(
800 &one_bytes,
801 "3b8b9ea39606ad6abba5f20db970872b20487663cfff69024a6cc01d7e951645",
802 );
803 let one_id =
804 ObjectId::calculate(OBJECT_KIND_CATALOG, OBJECT_VERSION_V1, &one_bytes).unwrap();
805 assert_eq!(
806 one_id.0,
807 from_hex("15d05f57a32d04af08fc9ba5d88c2fd9fdf09ba9858cfa35b25bb6e66c1f7c85")
808 );
809 assert_eq!(Catalog::decode(&one_bytes).unwrap(), one);
810 }
811
812 #[test]
813 fn commit_superblock_genesis_and_adjacent_vectors_match_adr_0015() {
814 let (genesis, empty_catalog_id, mut genesis_sb) = sample_genesis();
815 let genesis_bytes = genesis.encode().unwrap();
816 assert_sha256(
817 &genesis_bytes,
818 "54e2090af026678f548a8096a5781caeef14122f2cc22d65f4afa69e65a198f0",
819 );
820 let genesis_id = genesis.object_id().unwrap();
821 assert_eq!(
822 genesis_id.0,
823 from_hex("655010d6bc51309dc8f00d44ea167f65e074cb065881d33eec3af6eda4c2d422")
824 );
825 let mut commit_unit = [0; STORE_UNIT_BYTES];
826 commit_unit[..COMMIT_RECORD_BYTES].copy_from_slice(&genesis_bytes);
827 assert_sha256(
828 &commit_unit,
829 "d23bfa188198e0b285e12411ab8054183f67b2e67cbe03933a2444297a98dc4d",
830 );
831 assert_eq!(CommitRecord::decode(&genesis_bytes).unwrap(), genesis);
832
833 genesis_sb.validate_commit(genesis_id, &genesis).unwrap();
834 let sb_a = genesis_sb.encode().unwrap();
835 assert_sha256(
836 &sb_a,
837 "fd25f10310b662942275d0b72255a9f3a4e389b6e34d111465884a467e7ebdbc",
838 );
839 let crc_a = get_u32(&sb_a, SUPERBLOCK_CRC_OFFSET).unwrap();
840 assert_eq!(crc_a.to_le_bytes(), from_hex("fc775a27"));
841 assert_eq!(Superblock::decode(&sb_a, 0).unwrap(), genesis_sb);
842
843 genesis_sb.slot_id = 1;
844 let sb_b = genesis_sb.encode().unwrap();
845 assert_sha256(
846 &sb_b,
847 "e75a62a7a81ac318487ad1def438933430df9c199a1e5ef8942ef599731018e7",
848 );
849 assert_eq!(
850 get_u32(&sb_b, SUPERBLOCK_CRC_OFFSET).unwrap().to_le_bytes(),
851 from_hex("98353ee3")
852 );
853 let decoded_b = Superblock::decode(&sb_b, 1).unwrap();
854 assert!(Superblock::decode(&sb_a, 0)
855 .unwrap()
856 .equivalent_root(&decoded_b));
857 assert_eq!(crc32c(b"123456789"), 0xe306_9283);
858
859 let semantic: [u8; 16] = core::array::from_fn(|index| index as u8);
860 let app_id = ObjectId::calculate(3, 1, &semantic).unwrap();
861 let gen2_catalog = Catalog {
862 entries: vec![CatalogEntry {
863 object_id: app_id,
864 kind: 3,
865 version: 1,
866 first_unit: 4,
867 byte_length: 16,
868 unit_count: 1,
869 flags: 0,
870 }],
871 };
872 let gen2_catalog_bytes = gen2_catalog.encode().unwrap();
873 let gen2_catalog_id =
874 ObjectId::calculate(OBJECT_KIND_CATALOG, OBJECT_VERSION_V1, &gen2_catalog_bytes)
875 .unwrap();
876 let gen2 = CommitRecord {
877 store_uuid: genesis.store_uuid,
878 region_units: genesis.region_units,
879 generation: 2,
880 previous_generation: 1,
881 previous_commit_id: genesis_id,
882 previous_catalog_id: empty_catalog_id,
883 catalog_id: gen2_catalog_id,
884 catalog_first_unit: 5,
885 catalog_byte_length: 80,
886 catalog_unit_count: 1,
887 catalog_entry_count: 1,
888 committed_high_water: 7,
889 };
890 assert!(gen2.identifies_predecessor(&genesis, genesis_id));
891 let gen2_bytes = gen2.encode().unwrap();
892 assert_sha256(
893 &gen2_bytes,
894 "2a1a929eaae3b473531ee70ee8bb945ffe6ca05caf0b5e7a8c69d2179e1e716c",
895 );
896 let gen2_id = gen2.object_id().unwrap();
897 assert_eq!(
898 gen2_id.0,
899 from_hex("7787f3c9a29560e67987c4c83dd2b49ab402ee27975432a0f43fdf50749d11c1")
900 );
901 let gen2_sb = Superblock {
902 store_uuid: gen2.store_uuid,
903 slot_id: 0,
904 region_units: gen2.region_units,
905 generation: 2,
906 commit_record_id: gen2_id,
907 commit_record_unit: 6,
908 catalog_id: gen2_catalog_id,
909 catalog_first_unit: 5,
910 catalog_byte_length: 80,
911 catalog_unit_count: 1,
912 catalog_entry_count: 1,
913 committed_high_water: 7,
914 };
915 gen2_sb.validate_commit(gen2_id, &gen2).unwrap();
916 assert_sha256(
917 &gen2_sb.encode().unwrap(),
918 "47c84fb7394d4fb5b52d1b600fe67c4f3f07d41ed98ffadde2afa15b4dc9ddcc",
919 );
920 }
921
922 #[test]
923 fn malformed_object_catalog_and_extent_vectors_are_rejected() {
924 let semantic = [0x5au8; 16];
925 assert_eq!(
926 ObjectId::calculate(3, 1, &[]),
927 Err(FormatError::InvalidObject)
928 );
929 assert_eq!(
930 ObjectId::calculate(0, 1, &semantic),
931 Err(FormatError::InvalidObject)
932 );
933 let id = ObjectId::calculate(3, 1, &semantic).unwrap();
934 let entry = CatalogEntry {
935 object_id: id,
936 kind: 3,
937 version: 1,
938 first_unit: 2,
939 byte_length: 16,
940 unit_count: 1,
941 flags: 0,
942 };
943 let mut encoded_entry = entry.encode().unwrap();
944 encoded_entry[58] = 1;
945 assert_eq!(
946 CatalogEntry::decode(&encoded_entry),
947 Err(FormatError::NonzeroReserved)
948 );
949 let mut bad_flags = entry;
950 bad_flags.flags = 1;
951 assert_eq!(bad_flags.encode(), Err(FormatError::MalformedDescriptor));
952
953 let ordered = Catalog {
954 entries: vec![
955 entry,
956 CatalogEntry {
957 object_id: ObjectId([0xff; 32]),
958 ..entry
959 },
960 ],
961 };
962 assert!(ordered.encode().is_ok());
963 let reversed = Catalog {
964 entries: vec![ordered.entries[1], ordered.entries[0]],
965 };
966 assert_eq!(reversed.encode(), Err(FormatError::CatalogOrder));
967 let duplicate = Catalog {
968 entries: vec![entry, entry],
969 };
970 assert_eq!(duplicate.encode(), Err(FormatError::DuplicateObject));
971
972 let mut empty_bytes = Catalog { entries: vec![] }.encode().unwrap();
973 empty_bytes[12..16].copy_from_slice(&1u32.to_le_bytes());
974 assert_eq!(
975 Catalog::decode(&empty_bytes),
976 Err(FormatError::InvalidLength)
977 );
978 let mut bad_magic = Catalog { entries: vec![] }.encode().unwrap();
979 bad_magic[0] ^= 1;
980 assert_eq!(
981 Catalog::decode(&bad_magic),
982 Err(FormatError::BadCatalogMagic)
983 );
984
985 let mut physical = [0; STORE_UNIT_BYTES];
986 physical[..semantic.len()].copy_from_slice(&semantic);
987 id.validate_extent(3, 1, semantic.len() as u64, &physical)
988 .unwrap();
989 physical[STORE_UNIT_BYTES - 1] = 1;
990 assert_eq!(
991 id.validate_extent(3, 1, semantic.len() as u64, &physical),
992 Err(FormatError::NonzeroReserved)
993 );
994 physical[STORE_UNIT_BYTES - 1] = 0;
995 physical[0] ^= 1;
996 assert_eq!(
997 id.validate_extent(3, 1, semantic.len() as u64, &physical),
998 Err(FormatError::IntegrityFailure)
999 );
1000
1001 let first = CatalogEntry {
1002 first_unit: 2,
1003 ..entry
1004 };
1005 let overlap = Catalog {
1006 entries: vec![
1007 entry,
1008 CatalogEntry {
1009 object_id: ObjectId([0xff; 32]),
1010 ..first
1011 },
1012 ],
1013 };
1014 assert_eq!(
1015 overlap.validate_extents(32, 5, 8),
1016 Err(FormatError::Overlap)
1017 );
1018 assert_eq!(
1019 entry.validate_bounds(8, 2, 8),
1020 Err(FormatError::OutOfBounds)
1021 );
1022 }
1023
1024 #[test]
1025 fn malformed_generation_high_water_and_superblock_bytes_are_rejected() {
1026 let (genesis, _, sb) = sample_genesis();
1027 let mut broken_genesis = genesis.clone();
1028 broken_genesis.previous_generation = 1;
1029 assert_eq!(broken_genesis.encode(), Err(FormatError::InvalidGeneration));
1030 let mut broken_high_water = genesis.clone();
1031 broken_high_water.committed_high_water = 5;
1032 assert_eq!(
1033 broken_high_water.encode(),
1034 Err(FormatError::MalformedCommitRecord)
1035 );
1036
1037 let bytes = sb.encode().unwrap();
1038 let mut bad_crc = bytes;
1039 bad_crc[168] ^= 1;
1040 assert_eq!(
1041 Superblock::decode(&bad_crc, 0),
1042 Err(FormatError::BadSuperblockCrc)
1043 );
1044 let mut reserved = bytes;
1045 reserved[SUPERBLOCK_RESERVED_OFFSET] = 1;
1046 reserved[SUPERBLOCK_CRC_OFFSET..SUPERBLOCK_CRC_OFFSET + 4].fill(0);
1047 let corrected_crc = crc32c(&reserved);
1048 put_u32(&mut reserved, SUPERBLOCK_CRC_OFFSET, corrected_crc);
1049 assert_eq!(
1050 Superblock::decode(&reserved, 0),
1051 Err(FormatError::NonzeroReserved)
1052 );
1053 assert_eq!(
1054 Superblock::decode(&bytes, 1),
1055 Err(FormatError::WrongSuperblockSlot)
1056 );
1057
1058 let mut changed_unit = sb.clone();
1059 changed_unit.commit_record_unit = 2;
1060 assert_eq!(
1061 changed_unit.validate_commit(genesis.object_id().unwrap(), &genesis),
1062 Err(FormatError::MalformedSuperblock)
1063 );
1064 assert_eq!(
1065 genesis.validates_catalog(genesis.catalog_id, &Catalog { entries: vec![] }),
1066 Ok(())
1067 );
1068 }
1069}