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 / tests / store_v1_golden_vectors.rs

551 lines · 18968 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//! ADR 0015 golden vectors: the kernel's own Store v1 encoders must reproduce
17//! every byte of docs/adr/0015-golden-vectors.json, and every vector must
18//! decode back to the value that produced it.
19//!
20//! Every section is read through [`Section`], which records the keys it
21//! checked; each section check ends with [`Section::finish`], which fails if
22//! the JSON carries a field this test did not assert. Adding a vector to the
23//! frozen file therefore requires adding its assertion here.
24
25use std::cell::RefCell;
26use std::collections::BTreeSet;
27
28use aienos_kernel::crypto::sha256::Sha256;
29use aienos_kernel::store::v1::{
30 crc32c, Catalog, CatalogEntry, CommitRecord, ObjectId, Superblock, CATALOG_HEADER_BYTES,
31 STORE_UNIT_BYTES, SUPERBLOCK_CRC_OFFSET,
32};
33use serde_json::Value;
34
35const VECTORS: &str = include_str!("../../../docs/adr/0015-golden-vectors.json");
36const UUID: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
37/// ObjectId preimage domain from ADR 0015 (NUL-terminated).
38const OBJECT_DOMAIN: &[u8] = b"AIENOS-STORE-OBJECT-V1\0";
39
40fn vectors() -> Value {
41 serde_json::from_str(VECTORS).expect("golden vector JSON parses")
42}
43
44fn decode_hex(s: &str, what: &str) -> Vec<u8> {
45 assert!(s.len().is_multiple_of(2), "{what} has odd hex length");
46 (0..s.len())
47 .step_by(2)
48 .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap_or_else(|_| panic!("{what}: bad hex")))
49 .collect()
50}
51
52fn sha256(data: &[u8]) -> Vec<u8> {
53 let mut h = Sha256::new();
54 h.update(data);
55 h.finalize().to_vec()
56}
57
58/// One JSON section plus the set of keys the test has asserted.
59struct Section<'a> {
60 name: &'static str,
61 obj: &'a serde_json::Map<String, Value>,
62 used: RefCell<BTreeSet<String>>,
63}
64
65impl<'a> Section<'a> {
66 fn new(v: &'a Value, name: &'static str) -> Self {
67 let obj = v[name]
68 .as_object()
69 .unwrap_or_else(|| panic!("missing section {name}"));
70 Self {
71 name,
72 obj,
73 used: RefCell::new(BTreeSet::new()),
74 }
75 }
76
77 fn raw(&self, key: &str) -> &'a Value {
78 self.used.borrow_mut().insert(key.to_string());
79 self.obj
80 .get(key)
81 .unwrap_or_else(|| panic!("missing {}.{key}", self.name))
82 }
83
84 fn str(&self, key: &str) -> &'a str {
85 self.raw(key)
86 .as_str()
87 .unwrap_or_else(|| panic!("{}.{key} is not a string", self.name))
88 }
89
90 fn u64(&self, key: &str) -> u64 {
91 self.raw(key)
92 .as_u64()
93 .unwrap_or_else(|| panic!("{}.{key} is not an integer", self.name))
94 }
95
96 fn hex(&self, key: &str) -> Vec<u8> {
97 decode_hex(self.str(key), &format!("{}.{key}", self.name))
98 }
99
100 /// Assert `actual` equals the hex field `key` byte for byte.
101 fn bytes(&self, key: &str, actual: &[u8]) {
102 let expected = self.hex(key);
103 assert_eq!(
104 actual.len(),
105 expected.len(),
106 "{}.{key}: length differs",
107 self.name
108 );
109 if let Some(i) = actual.iter().zip(&expected).position(|(a, b)| a != b) {
110 panic!(
111 "{}.{key}: first mismatch at byte {i}: kernel {:#04x}, vector {:#04x}",
112 self.name, actual[i], expected[i]
113 );
114 }
115 }
116
117 /// Assert the `*_sha256` field `key` is SHA-256 of `data`.
118 fn digest(&self, key: &str, data: &[u8]) {
119 assert!(key.ends_with("sha256"), "{key} is not a digest field");
120 self.bytes(key, &sha256(data));
121 }
122
123 /// Every key present in the JSON section must have been asserted.
124 fn finish(self) {
125 let present: BTreeSet<String> = self.obj.keys().cloned().collect();
126 let used = self.used.into_inner();
127 let unchecked: Vec<_> = present.difference(&used).collect();
128 assert!(
129 unchecked.is_empty(),
130 "{}: fields not asserted by this test: {unchecked:?}",
131 self.name
132 );
133 }
134}
135
136fn unit(semantic: &[u8]) -> Vec<u8> {
137 assert!(!semantic.is_empty() && semantic.len() <= STORE_UNIT_BYTES);
138 let mut u = semantic.to_vec();
139 u.resize(STORE_UNIT_BYTES, 0);
140 u
141}
142
143fn id(kind: u16, version: u16, semantic: &[u8]) -> ObjectId {
144 ObjectId::calculate(kind, version, semantic).expect("object id")
145}
146
147/// ADR 0015 ObjectId preimage, built independently of the kernel so the
148/// vector's preimage bytes are checked against the contract, then tied to the
149/// kernel's ObjectId by hashing.
150fn preimage(kind: u16, version: u16, semantic: &[u8]) -> Vec<u8> {
151 let mut p = OBJECT_DOMAIN.to_vec();
152 p.extend_from_slice(&kind.to_le_bytes());
153 p.extend_from_slice(&version.to_le_bytes());
154 p.extend_from_slice(&(semantic.len() as u64).to_le_bytes());
155 p.extend_from_slice(semantic);
156 p
157}
158
159struct Graph {
160 empty_catalog: Vec<u8>,
161 empty_catalog_id: ObjectId,
162 one_entry: CatalogEntry,
163 one_catalog: Vec<u8>,
164 one_catalog_id: ObjectId,
165 app_semantic: Vec<u8>,
166 app_id: ObjectId,
167 genesis_commit: CommitRecord,
168 gen2_commit: CommitRecord,
169}
170
171fn graph() -> Graph {
172 let empty_catalog = Catalog { entries: vec![] }.encode().unwrap();
173 let empty_catalog_id = id(1, 1, &empty_catalog);
174 let app_semantic: Vec<u8> = (0u8..16).collect();
175 let app_id = id(3, 1, &app_semantic);
176 let one_entry = CatalogEntry {
177 object_id: app_id,
178 kind: 3,
179 version: 1,
180 first_unit: 4,
181 byte_length: 16,
182 unit_count: 1,
183 flags: 0,
184 };
185 let one_catalog = Catalog {
186 entries: vec![one_entry],
187 }
188 .encode()
189 .unwrap();
190 let one_catalog_id = id(1, 1, &one_catalog);
191 let genesis_commit = CommitRecord {
192 store_uuid: UUID,
193 region_units: 16,
194 generation: 1,
195 previous_generation: 0,
196 previous_commit_id: ObjectId([0; 32]),
197 previous_catalog_id: ObjectId([0; 32]),
198 catalog_id: empty_catalog_id,
199 catalog_first_unit: 2,
200 catalog_byte_length: empty_catalog.len() as u64,
201 catalog_unit_count: 1,
202 catalog_entry_count: 0,
203 committed_high_water: 4,
204 };
205 let gen2_commit = CommitRecord {
206 store_uuid: UUID,
207 region_units: 16,
208 generation: 2,
209 previous_generation: 1,
210 previous_commit_id: genesis_commit.object_id().unwrap(),
211 previous_catalog_id: empty_catalog_id,
212 catalog_id: one_catalog_id,
213 catalog_first_unit: 5,
214 catalog_byte_length: one_catalog.len() as u64,
215 catalog_unit_count: 1,
216 catalog_entry_count: 1,
217 committed_high_water: 7,
218 };
219 Graph {
220 empty_catalog,
221 empty_catalog_id,
222 one_entry,
223 one_catalog,
224 one_catalog_id,
225 app_semantic,
226 app_id,
227 genesis_commit,
228 gen2_commit,
229 }
230}
231
232fn superblock(slot: u32, commit: &CommitRecord, commit_unit: u64) -> Superblock {
233 Superblock {
234 store_uuid: commit.store_uuid,
235 slot_id: slot,
236 region_units: commit.region_units,
237 generation: commit.generation,
238 commit_record_id: commit.object_id().unwrap(),
239 commit_record_unit: commit_unit,
240 catalog_id: commit.catalog_id,
241 catalog_first_unit: commit.catalog_first_unit,
242 catalog_byte_length: commit.catalog_byte_length,
243 catalog_unit_count: commit.catalog_unit_count,
244 catalog_entry_count: commit.catalog_entry_count,
245 committed_high_water: commit.committed_high_water,
246 }
247}
248
249/// Encode a superblock, prove it round-trips and that its stored CRC is the
250/// kernel CRC32C of the unit with the CRC field zeroed.
251fn encode_superblock(sb: &Superblock) -> Vec<u8> {
252 let bytes = sb.encode().unwrap().to_vec();
253 assert_eq!(Superblock::decode(&bytes, sb.slot_id).unwrap(), *sb);
254 assert!(
255 Superblock::decode(&bytes, 1 - sb.slot_id).is_err(),
256 "slot id is bound into the superblock"
257 );
258 let mut zeroed = bytes.clone();
259 zeroed[SUPERBLOCK_CRC_OFFSET..SUPERBLOCK_CRC_OFFSET + 4].fill(0);
260 let stored = u32::from_le_bytes(
261 bytes[SUPERBLOCK_CRC_OFFSET..SUPERBLOCK_CRC_OFFSET + 4]
262 .try_into()
263 .unwrap(),
264 );
265 assert_eq!(crc32c(&zeroed), stored, "superblock CRC domain");
266 bytes
267}
268
269fn crc_field(bytes: &[u8]) -> &[u8] {
270 &bytes[SUPERBLOCK_CRC_OFFSET..SUPERBLOCK_CRC_OFFSET + 4]
271}
272
273#[test]
274fn top_level_is_the_frozen_schema() {
275 let v = vectors();
276 assert_eq!(v["schema"], "AIENOS-STORE-V1-GOLDEN-VECTORS-1");
277 assert_eq!(v["source_contract"], "ADR 0015, format layout tables");
278 let keys: BTreeSet<&str> = v.as_object().unwrap().keys().map(String::as_str).collect();
279 let expected: BTreeSet<&str> = [
280 "schema",
281 "source_contract",
282 "object_id",
283 "empty_catalog",
284 "one_entry_catalog",
285 "crc32c",
286 "genesis",
287 "adjacent_generations",
288 "equivalent_roots",
289 ]
290 .into_iter()
291 .collect();
292 assert_eq!(keys, expected, "top-level sections");
293}
294
295#[test]
296fn object_id() {
297 let v = vectors();
298 let s = Section::new(&v, "object_id");
299 let (kind, version) = (0x1234u16, 0x5678u16);
300 let semantic: Vec<u8> = (0u8..16).collect();
301 let oid = id(kind, version, &semantic);
302 let pre = preimage(kind, version, &semantic);
303
304 s.bytes("kind_u16le", &kind.to_le_bytes());
305 s.bytes("version_u16le", &version.to_le_bytes());
306 s.bytes("semantic_bytes_hex", &semantic);
307 s.bytes("preimage_hex", &pre);
308 s.bytes("object_id_hex", &oid.0);
309 s.digest("preimage_sha256", &pre);
310 s.digest("semantic_sha256", &semantic);
311 assert_eq!(sha256(&pre), oid.0, "ObjectId is SHA-256 of the preimage");
312 s.finish();
313}
314
315#[test]
316fn empty_catalog() {
317 let v = vectors();
318 let g = graph();
319 let s = Section::new(&v, "empty_catalog");
320 assert_eq!(g.empty_catalog.len(), CATALOG_HEADER_BYTES);
321 s.bytes("semantic_bytes_hex", &g.empty_catalog);
322 s.bytes("object_id_hex", &g.empty_catalog_id.0);
323 s.bytes("unit_hex", &unit(&g.empty_catalog));
324 s.digest("unit_sha256", &unit(&g.empty_catalog));
325 s.digest("semantic_sha256", &g.empty_catalog);
326 assert!(Catalog::decode(&g.empty_catalog)
327 .unwrap()
328 .entries
329 .is_empty());
330 s.finish();
331}
332
333#[test]
334fn one_entry_catalog() {
335 let v = vectors();
336 let g = graph();
337 let s = Section::new(&v, "one_entry_catalog");
338 let entry = g.one_entry.encode().unwrap();
339 assert_eq!(g.one_catalog.len(), 80);
340 assert_eq!(&g.one_catalog[CATALOG_HEADER_BYTES..], &entry[..]);
341
342 s.bytes("entry_object_id_hex", &entry[0..32]);
343 s.bytes("entry_kind_u16le", &entry[32..34]);
344 s.bytes("entry_version_u16le", &entry[34..36]);
345 s.bytes("entry_first_unit_u64le", &entry[36..44]);
346 s.bytes("entry_byte_length_u64le", &entry[44..52]);
347 s.bytes("entry_unit_count_u32le", &entry[52..56]);
348 s.bytes("entry_flags_u16le", &entry[56..58]);
349 s.bytes("entry_reserved_hex", &entry[58..64]);
350 assert_eq!(&entry[0..32], &g.app_id.0);
351 s.bytes("semantic_bytes_hex", &g.one_catalog);
352 s.bytes("object_id_hex", &g.one_catalog_id.0);
353 s.bytes("unit_hex", &unit(&g.one_catalog));
354 s.digest("unit_sha256", &unit(&g.one_catalog));
355 s.digest("semantic_sha256", &g.one_catalog);
356
357 assert_eq!(CatalogEntry::decode(&entry).unwrap(), g.one_entry);
358 assert_eq!(
359 Catalog::decode(&g.one_catalog).unwrap().entries,
360 vec![g.one_entry]
361 );
362 s.finish();
363}
364
365#[test]
366fn crc32c_check_value() {
367 let v = vectors();
368 let s = Section::new(&v, "crc32c");
369 let input = s.str("check_input_ascii");
370 assert_eq!(input, "123456789");
371 let crc = crc32c(input.as_bytes());
372 let numeric = s.str("check_output_numeric");
373 let parsed = u32::from_str_radix(numeric.trim_start_matches("0x"), 16).unwrap();
374 assert_eq!(crc, parsed, "check_output_numeric");
375 assert_eq!(crc, 0xe306_9283);
376 s.bytes("check_output_u32le", &crc.to_le_bytes());
377 assert_eq!(
378 s.str("algorithm"),
379 "reflected Castagnoli polynomial 0x82f63b78, init/xorout 0xffffffff"
380 );
381 s.finish();
382}
383
384#[test]
385fn genesis() {
386 let v = vectors();
387 let g = graph();
388 let s = Section::new(&v, "genesis");
389 let c = &g.genesis_commit;
390
391 s.bytes("store_uuid_hex", &UUID);
392 s.bytes("region_units_u64le", &c.region_units.to_le_bytes());
393 assert_eq!(s.u64("catalog_first_unit"), c.catalog_first_unit);
394 assert_eq!(s.u64("commit_record_unit_number"), 3);
395 let map = s.raw("unit_map");
396 for (unit_no, what) in [
397 ("0", "superblock A"),
398 ("1", "superblock B"),
399 ("2", "genesis catalog"),
400 ("3", "genesis CommitRecord"),
401 ] {
402 assert_eq!(map[unit_no], what, "genesis.unit_map[{unit_no}]");
403 }
404 assert_eq!(map.as_object().unwrap().len(), 4);
405
406 s.bytes("catalog_semantic_hex", &g.empty_catalog);
407 s.bytes("catalog_unit_hex", &unit(&g.empty_catalog));
408 s.bytes("catalog_object_id_hex", &g.empty_catalog_id.0);
409
410 let sem = c.encode().unwrap();
411 let cid = c.object_id().unwrap();
412 let pre = preimage(2, 1, &sem);
413 s.bytes("commit_record_semantic_hex", &sem);
414 s.bytes("commit_record_object_id_hex", &cid.0);
415 s.bytes("commit_record_unit_hex", &unit(&sem));
416 s.digest("commit_record_unit_sha256", &unit(&sem));
417 s.bytes("commit_record_crc_domain_preimage_hex", &pre);
418 assert_eq!(
419 sha256(&pre),
420 cid.0,
421 "CommitRecord id is SHA-256 of preimage"
422 );
423 assert_eq!(CommitRecord::decode(&sem).unwrap(), *c);
424
425 let a = encode_superblock(&superblock(0, c, 3));
426 let b = encode_superblock(&superblock(1, c, 3));
427 s.bytes("superblock_a_unit_hex", &a);
428 s.digest("superblock_a_unit_sha256", &a);
429 s.bytes("superblock_a_crc_u32le", crc_field(&a));
430 s.bytes("superblock_b_unit_hex", &b);
431 s.digest("superblock_b_unit_sha256", &b);
432 s.bytes("superblock_b_crc_u32le", crc_field(&b));
433 assert_ne!(a, b);
434 assert_ne!(crc_field(&a), crc_field(&b));
435
436 assert_eq!(
437 s.str("expected_root_classification"),
438 "redundant valid copies; equivalent logical roots"
439 );
440 let (da, db) = (
441 Superblock::decode(&a, 0).unwrap(),
442 Superblock::decode(&b, 1).unwrap(),
443 );
444 assert!(da.equivalent_root(&db), "genesis A/B are equivalent roots");
445 da.validate_commit(cid, c)
446 .expect("superblock A binds genesis commit");
447 db.validate_commit(cid, c)
448 .expect("superblock B binds genesis commit");
449 s.finish();
450}
451
452#[test]
453fn adjacent_generations() {
454 let v = vectors();
455 let g = graph();
456 let s = Section::new(&v, "adjacent_generations");
457 let g1 = &g.genesis_commit;
458 let g2 = &g.gen2_commit;
459 let g1_id = g1.object_id().unwrap();
460
461 s.bytes("generation_1_commit_record_object_id_hex", &g1_id.0);
462 s.bytes("generation_1_catalog_object_id_hex", &g.empty_catalog_id.0);
463 assert_eq!(
464 s.u64("generation_1_committed_high_water"),
465 g1.committed_high_water
466 );
467 let map = s.raw("unit_map");
468 for (unit_no, what) in [
469 ("0", "generation 2 superblock A"),
470 ("1", "generation 1 superblock B"),
471 ("2", "generation 1 catalog"),
472 ("3", "generation 1 CommitRecord"),
473 ("4", "generation 2 application object"),
474 ("5", "generation 2 catalog"),
475 ("6", "generation 2 CommitRecord"),
476 ] {
477 assert_eq!(
478 map[unit_no], what,
479 "adjacent_generations.unit_map[{unit_no}]"
480 );
481 }
482 assert_eq!(map.as_object().unwrap().len(), 7);
483
484 s.bytes("application_object_semantic_hex", &g.app_semantic);
485 s.bytes("application_object_id_hex", &g.app_id.0);
486 s.bytes("application_object_unit_hex", &unit(&g.app_semantic));
487 s.digest("application_object_unit_sha256", &unit(&g.app_semantic));
488
489 s.bytes("generation_2_catalog_semantic_hex", &g.one_catalog);
490 s.bytes("generation_2_catalog_object_id_hex", &g.one_catalog_id.0);
491 s.bytes("generation_2_catalog_unit_hex", &unit(&g.one_catalog));
492 s.digest("generation_2_catalog_unit_sha256", &unit(&g.one_catalog));
493
494 let sem = g2.encode().unwrap();
495 let g2_id = g2.object_id().unwrap();
496 let pre = preimage(2, 1, &sem);
497 s.bytes("generation_2_commit_record_semantic_hex", &sem);
498 s.bytes("generation_2_commit_record_object_id_hex", &g2_id.0);
499 s.bytes("generation_2_commit_record_unit_hex", &unit(&sem));
500 s.digest("generation_2_commit_record_unit_sha256", &unit(&sem));
501 s.bytes("generation_2_commit_record_preimage_hex", &pre);
502 assert_eq!(sha256(&pre), g2_id.0);
503 assert_eq!(CommitRecord::decode(&sem).unwrap(), *g2);
504
505 let sb_value = superblock(0, g2, 6);
506 sb_value
507 .validate_commit(g2_id, g2)
508 .expect("generation 2 superblock binds its commit");
509 let sb = encode_superblock(&sb_value);
510 s.bytes("generation_2_superblock_a_unit_hex", &sb);
511 s.digest("generation_2_superblock_a_unit_sha256", &sb);
512 s.bytes("generation_2_superblock_a_crc_u32le", crc_field(&sb));
513 assert_eq!(
514 s.u64("generation_2_committed_high_water"),
515 g2.committed_high_water
516 );
517
518 assert_eq!(
519 s.str("expected_root_classification"),
520 "normal adjacent history; generation 2 follows generation 1 exactly"
521 );
522 assert!(g2.identifies_predecessor(g1, g1_id));
523 assert_eq!(&sem[72..104], &g1_id.0, "previous_commit_id links genesis");
524 assert_eq!(&sem[104..136], &g.empty_catalog_id.0);
525 s.finish();
526}
527
528#[test]
529fn equivalent_roots() {
530 let v = vectors();
531 let g = graph();
532 let s = Section::new(&v, "equivalent_roots");
533 let a_sb = superblock(0, &g.genesis_commit, 3);
534 let b_sb = superblock(1, &g.genesis_commit, 3);
535 let a = encode_superblock(&a_sb);
536 let b = encode_superblock(&b_sb);
537
538 s.bytes("superblock_a_unit_hex", &a);
539 s.digest("superblock_a_unit_sha256", &a);
540 s.bytes("superblock_b_unit_hex", &b);
541 s.digest("superblock_b_unit_sha256", &b);
542 s.bytes("superblock_a_crc_u32le", crc_field(&a));
543 s.bytes("superblock_b_crc_u32le", crc_field(&b));
544 assert_eq!(
545 s.str("expected_root_classification"),
546 "same generation and equivalent logical root; redundant valid copies"
547 );
548 assert!(a_sb.equivalent_root(&b_sb));
549 assert_ne!(a, b, "slot id and CRC differ between redundant copies");
550 s.finish();
551}