Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-kernel/src/continuity_vectors.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-kernel / src / continuity_vectors.rs` 350 lines ยท 12484 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 //! D-1 / D-2 golden vectors for the C continuity codec (contract 17 //! native/kernel/CONTINUITY_RECOVERY_CONTRACT.md 6.3, aienos#222, cut 2). 18 //! 19 //! TEST-ONLY emitter: nothing here is compiled outside `cfg(test)` and it 20 //! changes no kernel behaviour. It writes two plain-text fixtures under 21 //! `native/kernel/tests/fixtures/`: 22 //! 23 //! * `continuity_vectors.txt`: canonical bytes and logical ObjectIds (D-1). 24 //! * `continuity_verdicts.txt`: for every vector, the Rust decode verdict of 25 //! the untouched bytes and of every single-bit flip (D-2). 26 //! 27 //! The C host test (`native/kernel/tests/test_continuity_codec.c`) reads both 28 //! files and must reproduce every byte, every ObjectId and every verdict. 29 //! 30 //! Regenerate (the only command): 31 //! AIENOS_CONTINUITY_VECTORS_REGEN=1 cargo test -p aienos-kernel --lib continuity_vectors 32 //! Without the variable the test fails if a committed fixture differs from 33 //! freshly emitted bytes, so the fixtures cannot drift from the oracle. 34 35 use super::*; 36 use crate::recovery::OperatorAuth; 37 use crate::recovery_core::{Action, SlotView, SystemRecord}; 38 use crate::store::engine::{MountState, PeerCondition}; 39 use alloc::format; 40 use alloc::string::String; 41 42 const AGENT: [u8; 32] = [0x11; 32]; 43 const UUID: [u8; 16] = [0x5a; 16]; 44 /// The same TEST operator key recovery_core_tests.rs uses (OPERATOR). 45 const TEST_KEY: [u8; 32] = [0x0f; 32]; 46 47 /// Every decode refusal text continuity.rs can return, as (code, class, why). 48 /// A reason missing from this table makes the emitter panic, so a new Rust 49 /// reason can never be silently dropped from the D-2 comparison. 50 const REASONS: &[(char, &str, &str)] = &[ 51 ('a', "Corrupt", "bad magic"), 52 ('b', "Corrupt", "unsupported continuity format version"), 53 ('c', "Corrupt", "nonzero header reserved"), 54 ('d', "Corrupt", "body length mismatch"), 55 ('e', "Corrupt", "truncated object"), 56 ('f', "Corrupt", "nonzero reserved"), 57 ('g', "Corrupt", "trailing bytes"), 58 ('h', "Corrupt", "unknown provisioning source"), 59 ('i', "Corrupt", "zero agent id"), 60 ('j', "Corrupt", "root branch does not derive from agent"), 61 ('k', "Corrupt", "too many cortex WAL segments"), 62 ('l', "Corrupt", "manifest sequence/previous mismatch"), 63 ('m', "Corrupt", "branch count out of range"), 64 ('n', "Corrupt", "branches not strictly sorted"), 65 ('o', "Corrupt", "unexpected root branch"), 66 ('p', "Corrupt", "parent branch is absent"), 67 ('q', "Corrupt", "branch lineage is inconsistent"), 68 ('r', "Corrupt", "fork indexes are not contiguous"), 69 ('s', "Corrupt", "WAL segment record count"), 70 ('t', "Corrupt", "unknown epistemic status"), 71 ('u', "Corrupt", "statement length"), 72 ]; 73 74 fn hex(b: &[u8]) -> String { 75 let mut s = String::with_capacity(b.len() * 2); 76 for x in b { 77 s.push_str(&format!("{x:02x}")); 78 } 79 s 80 } 81 82 fn verdict(kind: u16, bytes: &[u8]) -> char { 83 let r = match kind { 84 KIND_AGENT_ROOT => AgentRoot::decode(bytes).map(|_| ()), 85 KIND_MANIFEST => Manifest::decode(bytes).map(|_| ()), 86 KIND_AGENT_STATE => AgentState::decode(bytes).map(|_| ()), 87 KIND_CORTEX_WAL => WalSegment::decode(bytes).map(|_| ()), 88 _ => panic!("unknown kind"), 89 }; 90 match r { 91 Ok(()) => '.', 92 Err(ContinuityError::Corrupt(w)) => { 93 REASONS 94 .iter() 95 .find(|(_, c, t)| *c == "Corrupt" && *t == w) 96 .unwrap_or_else(|| panic!("reason not in REASONS: {w}")) 97 .0 98 } 99 Err(ContinuityError::Limit(w)) => { 100 REASONS 101 .iter() 102 .find(|(_, c, t)| *c == "Limit" && *t == w) 103 .unwrap_or_else(|| panic!("reason not in REASONS: {w}")) 104 .0 105 } 106 Err(e) => panic!("decode returned a non-codec error: {e:?}"), 107 } 108 } 109 110 fn root(source: ProvisionSource) -> Vec { 111 AgentRoot { 112 agent_id: AGENT, 113 store_uuid: UUID, 114 root_branch: root_branch_id(&AGENT), 115 provisioned_generation: 0x0102030405060708, 116 source, 117 } 118 .encode() 119 } 120 121 fn manifest(n_wal: usize, sequence: u64) -> Vec { 122 Manifest { 123 root: ObjectId([0xa1; 32]), 124 previous: (sequence > 1).then_some(ObjectId([0xd4; 32])), 125 sequence, 126 incarnation: 1, 127 agent_state: Some(ObjectId([0xb2; 32])), 128 cortex_wal: (0..n_wal).map(|i| ObjectId([i as u8 + 1; 32])).collect(), 129 } 130 .encode() 131 .unwrap() 132 } 133 134 fn wal(status: Epistemic, len: usize) -> Vec { 135 WalSegment { 136 sequence: 3, 137 records: alloc::vec![CortexRecord { 138 status, 139 evidence_hash: [0x40 + status as u8; 32], 140 statement: (0..len).map(|i| b'A' + (i % 26) as u8).collect(), 141 }], 142 } 143 .encode() 144 .unwrap() 145 } 146 147 fn vectors() -> Vec<(String, u16, Vec)> { 148 let mut v: Vec<(String, u16, Vec)> = Vec::new(); 149 v.push(( 150 "root_operator".into(), 151 KIND_AGENT_ROOT, 152 root(ProvisionSource::Operator), 153 )); 154 v.push(( 155 "root_qualification".into(), 156 KIND_AGENT_ROOT, 157 root(ProvisionSource::Qualification), 158 )); 159 for n in [0usize, 1, 64] { 160 v.push((format!("manifest_wal{n}"), KIND_MANIFEST, manifest(n, 1))); 161 } 162 v.push(( 163 "manifest_seq2_previous".into(), 164 KIND_MANIFEST, 165 manifest(1, 2), 166 )); 167 168 let mut s = AgentState::genesis(AGENT, 1); 169 v.push(( 170 "state_genesis".into(), 171 KIND_AGENT_STATE, 172 s.encode().unwrap(), 173 )); 174 let rb = root_branch_id(&AGENT); 175 let c0 = s.fork(&rb).unwrap(); 176 v.push(( 177 "state_fork_depth1".into(), 178 KIND_AGENT_STATE, 179 s.encode().unwrap(), 180 )); 181 // The d1 bytes patched into a hostile table: root claims 2^64-1 forks and 182 // the child 2, so a wrapping sum equals the child count (1). Both 183 // implementations must refuse (Rust #232; contract 1.5, section 9). 184 let mut hostile = s.encode().unwrap(); 185 // 64-byte header+fixed, 80 bytes per branch, forks at +72; sorted order. 186 let (a, b) = if s.branches[0].id == rb { 187 (0, 1) 188 } else { 189 (1, 0) 190 }; 191 hostile[64 + 80 * a + 72..64 + 80 * a + 80].copy_from_slice(&u64::MAX.to_le_bytes()); 192 hostile[64 + 80 * b + 72..64 + 80 * b + 80].copy_from_slice(&2u64.to_le_bytes()); 193 s.fork(&rb).unwrap(); 194 s.fork(&c0).unwrap(); 195 v.push(( 196 "state_fork_depth2".into(), 197 KIND_AGENT_STATE, 198 s.encode().unwrap(), 199 )); 200 v.push(("state_forksum_overflow".into(), KIND_AGENT_STATE, hostile)); 201 202 for st in [ 203 Epistemic::DirectObservation, 204 Epistemic::VerifiedFact, 205 Epistemic::Inference, 206 Epistemic::Hypothesis, 207 Epistemic::Contradiction, 208 Epistemic::OperatorDecision, 209 ] { 210 for len in [1usize, 1024] { 211 v.push(( 212 format!("wal_status{}_len{len}", st as u8), 213 KIND_CORTEX_WAL, 214 wal(st, len), 215 )); 216 } 217 } 218 v 219 } 220 221 fn system_record() -> SystemRecord { 222 SystemRecord { 223 slots: [SlotView::Zero, SlotView::Zero], 224 state_digest: [0x33; 32], 225 store_uuid: Some(UUID), 226 mount: Some((MountState::Valid, PeerCondition::Zero, 7)), 227 reason: None, 228 continuity: None, 229 catalog: None, 230 } 231 } 232 233 /// (vectors.txt, verdicts.txt) contents. 234 fn emit() -> (String, String) { 235 let mut t = String::new(); 236 t.push_str("# continuity golden vectors (D-1), emitted by the Rust oracle.\n"); 237 t.push_str("# DO NOT EDIT. Regenerate with:\n"); 238 t.push_str("# AIENOS_CONTINUITY_VECTORS_REGEN=1 cargo test -p aienos-kernel --lib continuity_vectors\n"); 239 t.push_str( 240 "# bid branch id (root = SHA-256 of agent 0x11 x32)\n", 241 ); 242 t.push_str( 243 "# vec canonical bytes, logical ObjectId (store v1)\n", 244 ); 245 t.push_str("# deferred recovery challenge / HMAC response: C does not\n"); 246 t.push_str("# implement these yet (resolve cut), not checked\n"); 247 let rb = root_branch_id(&AGENT); 248 t.push_str(&format!("bid root {}\n", hex(&rb))); 249 for (name, ix) in [ 250 ("child_index_0", 0u64), 251 ("child_index_1", 1), 252 ("child_index_2p32", 1 << 32), 253 ("child_index_2p64m1", u64::MAX), 254 ] { 255 t.push_str(&format!("bid {name} {}\n", hex(&child_branch_id(&rb, ix)))); 256 } 257 let vs = vectors(); 258 for (name, kind, bytes) in &vs { 259 let id = ObjectId::calculate(*kind, STORE_OBJECT_VERSION, bytes).unwrap(); 260 t.push_str(&format!( 261 "vec {name} {kind} {} {}\n", 262 hex(&id.0), 263 hex(bytes) 264 )); 265 } 266 let rec = system_record(); 267 for (name, a) in [ 268 ("repair_degraded_peer", Action::RepairDegradedPeer), 269 ("provision_identity", Action::ProvisionIdentity), 270 ] { 271 let ch = rec.challenge(a).unwrap(); 272 t.push_str(&format!("deferred challenge_{name} {}\n", hex(&ch))); 273 t.push_str(&format!( 274 "deferred response_{name} {}\n", 275 hex(&OperatorAuth::expected_response(&TEST_KEY, &ch)) 276 )); 277 } 278 279 let mut d = String::new(); 280 d.push_str("# continuity decode verdicts (D-2), emitted by the Rust oracle.\n"); 281 d.push_str("# DO NOT EDIT. Regenerate: see continuity_vectors.txt.\n"); 282 d.push_str( 283 "# reason ; '.' = accept. verdict : char 0 is the\n", 284 ); 285 d.push_str( 286 "# untouched vector, char 1+i is the vector with bit (i%8) of byte (i/8) flipped.\n", 287 ); 288 for (c, cls, why) in REASONS { 289 d.push_str(&format!("reason {c} {cls} {why}\n")); 290 } 291 for (name, kind, bytes) in &vs { 292 let mut s = String::new(); 293 s.push(verdict(*kind, bytes)); 294 let mut t = bytes.clone(); 295 for i in 0..bytes.len() * 8 { 296 t[i / 8] ^= 1 << (i % 8); 297 s.push(verdict(*kind, &t)); 298 t[i / 8] ^= 1 << (i % 8); 299 } 300 d.push_str(&format!("verdict {name} {s}\n")); 301 } 302 (t, d) 303 } 304 305 fn fixture_dir() -> std::path::PathBuf { 306 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../native/kernel/tests/fixtures") 307 } 308 309 #[test] 310 fn committed_fixtures_match_the_oracle() { 311 let (vecs, verds) = emit(); 312 let dir = fixture_dir(); 313 let files = [ 314 ("continuity_vectors.txt", vecs), 315 ("continuity_verdicts.txt", verds), 316 ]; 317 if std::env::var_os("AIENOS_CONTINUITY_VECTORS_REGEN").is_some() { 318 for (n, c) in &files { 319 std::fs::write(dir.join(n), c).unwrap(); 320 } 321 return; 322 } 323 for (n, c) in &files { 324 let have = std::fs::read_to_string(dir.join(n)).unwrap_or_default(); 325 assert!( 326 have == *c, 327 "{n} differs from freshly emitted bytes; regenerate with \ 328 AIENOS_CONTINUITY_VECTORS_REGEN=1 cargo test -p aienos-kernel --lib continuity_vectors" 329 ); 330 } 331 } 332 333 #[test] 334 fn emitted_vectors_are_canonical() { 335 for (name, kind, bytes) in vectors() { 336 let v = verdict(kind, &bytes); 337 if name == "state_forksum_overflow" { 338 assert_eq!(v, 'r', "{name}: the overflowing fork sum must be refused"); 339 continue; 340 } 341 assert_eq!(v, '.', "{name}: must decode"); 342 let again = match kind { 343 KIND_AGENT_ROOT => AgentRoot::decode(&bytes).unwrap().encode(), 344 KIND_MANIFEST => Manifest::decode(&bytes).unwrap().encode().unwrap(), 345 KIND_AGENT_STATE => AgentState::decode(&bytes).unwrap().encode().unwrap(), 346 _ => WalSegment::decode(&bytes).unwrap().encode().unwrap(), 347 }; 348 assert_eq!(again, bytes, "{name}: decode then encode must be identical"); 349 } 350 }