aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / tools / aien-verify / src / main.rs
| 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 | //! aien-verify: the independent verifier of WHOLE-SYSTEM-E2E v1 (lane L4). |
| 17 | //! Reads a run folder (chain receipts, SHA256SUMS, output files) and writes the verdict. |
| 18 | //! Standard library only; own sha256; shares no code with the executor or the harness. |
| 19 | //! Rules: docs/campaigns/whole-system-e2e/VERIFIER-v1.md. |
| 20 | |
| 21 | use std::collections::BTreeMap; |
| 22 | use std::fs; |
| 23 | use std::path::{Path, PathBuf}; |
| 24 | use std::process::ExitCode; |
| 25 | |
| 26 | // ---------------------------------------------------------------- sha256 |
| 27 | |
| 28 | const K: [u32; 64] = [ |
| 29 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, |
| 30 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, |
| 31 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, |
| 32 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, |
| 33 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, |
| 34 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, |
| 35 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, |
| 36 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, |
| 37 | ]; |
| 38 | |
| 39 | struct Sha256 { |
| 40 | h: [u32; 8], |
| 41 | buf: Vec<u8>, |
| 42 | len: u64, |
| 43 | } |
| 44 | |
| 45 | impl Sha256 { |
| 46 | fn new() -> Self { |
| 47 | Sha256 { |
| 48 | h: [ |
| 49 | 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, |
| 50 | ], |
| 51 | buf: Vec::with_capacity(64), |
| 52 | len: 0, |
| 53 | } |
| 54 | } |
| 55 | fn block(h: &mut [u32; 8], b: &[u8]) { |
| 56 | let mut w = [0u32; 64]; |
| 57 | for i in 0..16 { |
| 58 | w[i] = u32::from_be_bytes([b[4 * i], b[4 * i + 1], b[4 * i + 2], b[4 * i + 3]]); |
| 59 | } |
| 60 | for i in 16..64 { |
| 61 | let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); |
| 62 | let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); |
| 63 | w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1); |
| 64 | } |
| 65 | let [mut a, mut b_, mut c, mut d, mut e, mut f, mut g, mut hh] = *h; |
| 66 | for i in 0..64 { |
| 67 | let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); |
| 68 | let ch = (e & f) ^ (!e & g); |
| 69 | let t1 = hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]); |
| 70 | let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); |
| 71 | let maj = (a & b_) ^ (a & c) ^ (b_ & c); |
| 72 | let t2 = s0.wrapping_add(maj); |
| 73 | hh = g; |
| 74 | g = f; |
| 75 | f = e; |
| 76 | e = d.wrapping_add(t1); |
| 77 | d = c; |
| 78 | c = b_; |
| 79 | b_ = a; |
| 80 | a = t1.wrapping_add(t2); |
| 81 | } |
| 82 | for (x, y) in h.iter_mut().zip([a, b_, c, d, e, f, g, hh]) { |
| 83 | *x = x.wrapping_add(y); |
| 84 | } |
| 85 | } |
| 86 | fn update(&mut self, mut data: &[u8]) { |
| 87 | self.len += data.len() as u64; |
| 88 | if !self.buf.is_empty() { |
| 89 | let need = 64 - self.buf.len(); |
| 90 | let take = need.min(data.len()); |
| 91 | self.buf.extend_from_slice(&data[..take]); |
| 92 | data = &data[take..]; |
| 93 | if self.buf.len() == 64 { |
| 94 | let b = std::mem::take(&mut self.buf); |
| 95 | Self::block(&mut self.h, &b); |
| 96 | } |
| 97 | } |
| 98 | while data.len() >= 64 { |
| 99 | Self::block(&mut self.h, &data[..64]); |
| 100 | data = &data[64..]; |
| 101 | } |
| 102 | self.buf.extend_from_slice(data); |
| 103 | } |
| 104 | fn finish(mut self) -> String { |
| 105 | let bits = self.len.wrapping_mul(8); |
| 106 | let mut pad = vec![0x80u8]; |
| 107 | while (self.buf.len() + pad.len()) % 64 != 56 { |
| 108 | pad.push(0); |
| 109 | } |
| 110 | pad.extend_from_slice(&bits.to_be_bytes()); |
| 111 | let saved = self.len; |
| 112 | self.update(&pad); |
| 113 | self.len = saved; |
| 114 | self.h.iter().map(|x| format!("{:08x}", x)).collect() |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | fn sha256_bytes(d: &[u8]) -> String { |
| 119 | let mut s = Sha256::new(); |
| 120 | s.update(d); |
| 121 | s.finish() |
| 122 | } |
| 123 | |
| 124 | fn sha256_file(p: &Path) -> Result<String, String> { |
| 125 | fs::read(p).map(|d| sha256_bytes(&d)).map_err(|e| format!("{}: {}", p.display(), e)) |
| 126 | } |
| 127 | |
| 128 | fn selftest() -> Result<(), String> { |
| 129 | let vecs: [(&[u8], &str); 4] = [ |
| 130 | (b"", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"), |
| 131 | (b"abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"), |
| 132 | ( |
| 133 | b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", |
| 134 | "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", |
| 135 | ), |
| 136 | ( |
| 137 | b"The quick brown fox jumps over the lazy dog", |
| 138 | "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592", |
| 139 | ), |
| 140 | ]; |
| 141 | for (i, (m, want)) in vecs.iter().enumerate() { |
| 142 | let got = sha256_bytes(m); |
| 143 | if got != *want { |
| 144 | return Err(format!("sha256 vector {} wrong: {}", i, got)); |
| 145 | } |
| 146 | } |
| 147 | let million = vec![b'a'; 1_000_000]; |
| 148 | let got = sha256_bytes(&million); |
| 149 | if got != "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0" { |
| 150 | return Err(format!("sha256 million-a wrong: {}", got)); |
| 151 | } |
| 152 | // chunked update must equal one-shot |
| 153 | let mut s = Sha256::new(); |
| 154 | for c in million.chunks(37) { |
| 155 | s.update(c); |
| 156 | } |
| 157 | if s.finish() != got { |
| 158 | return Err("chunked sha256 differs".into()); |
| 159 | } |
| 160 | Ok(()) |
| 161 | } |
| 162 | |
| 163 | // ---------------------------------------------------------------- minimal JSON |
| 164 | |
| 165 | #[derive(Debug, Clone)] |
| 166 | enum J { |
| 167 | Null, |
| 168 | Bool(bool), |
| 169 | Num(f64), |
| 170 | Str(String), |
| 171 | Arr(Vec<J>), |
| 172 | Obj(Vec<(String, J)>), |
| 173 | } |
| 174 | |
| 175 | impl J { |
| 176 | fn get(&self, k: &str) -> Option<&J> { |
| 177 | match self { |
| 178 | J::Obj(v) => v.iter().find(|(n, _)| n == k).map(|(_, x)| x), |
| 179 | _ => None, |
| 180 | } |
| 181 | } |
| 182 | fn s(&self, k: &str) -> Option<&str> { |
| 183 | match self.get(k) { |
| 184 | Some(J::Str(s)) => Some(s), |
| 185 | _ => None, |
| 186 | } |
| 187 | } |
| 188 | fn b(&self, k: &str) -> Option<bool> { |
| 189 | match self.get(k) { |
| 190 | Some(J::Bool(b)) => Some(*b), |
| 191 | _ => None, |
| 192 | } |
| 193 | } |
| 194 | fn n(&self, k: &str) -> Option<f64> { |
| 195 | match self.get(k) { |
| 196 | Some(J::Num(n)) => Some(*n), |
| 197 | _ => None, |
| 198 | } |
| 199 | } |
| 200 | fn present_non_null(&self, k: &str) -> bool { |
| 201 | !matches!(self.get(k), None | Some(J::Null)) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | struct P<'a> { |
| 206 | b: &'a [u8], |
| 207 | i: usize, |
| 208 | } |
| 209 | |
| 210 | impl<'a> P<'a> { |
| 211 | fn ws(&mut self) { |
| 212 | while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\r' | b'\t') { |
| 213 | self.i += 1; |
| 214 | } |
| 215 | } |
| 216 | fn lit(&mut self, s: &str, v: J) -> Result<J, String> { |
| 217 | if self.b[self.i..].starts_with(s.as_bytes()) { |
| 218 | self.i += s.len(); |
| 219 | Ok(v) |
| 220 | } else { |
| 221 | Err(format!("bad literal at {}", self.i)) |
| 222 | } |
| 223 | } |
| 224 | fn hex4(&mut self) -> Result<u32, String> { |
| 225 | if self.i + 4 > self.b.len() { |
| 226 | return Err("short \\u escape".into()); |
| 227 | } |
| 228 | let t = std::str::from_utf8(&self.b[self.i..self.i + 4]).map_err(|e| e.to_string())?; |
| 229 | self.i += 4; |
| 230 | u32::from_str_radix(t, 16).map_err(|e| e.to_string()) |
| 231 | } |
| 232 | fn string(&mut self) -> Result<String, String> { |
| 233 | self.i += 1; |
| 234 | let mut out: Vec<u8> = Vec::new(); |
| 235 | loop { |
| 236 | let c = *self.b.get(self.i).ok_or("unterminated string")?; |
| 237 | self.i += 1; |
| 238 | match c { |
| 239 | b'"' => break, |
| 240 | b'\\' => { |
| 241 | let e = *self.b.get(self.i).ok_or("bad escape")?; |
| 242 | self.i += 1; |
| 243 | let ch = match e { |
| 244 | b'"' => '"', |
| 245 | b'\\' => '\\', |
| 246 | b'/' => '/', |
| 247 | b'b' => '\u{8}', |
| 248 | b'f' => '\u{c}', |
| 249 | b'n' => '\n', |
| 250 | b'r' => '\r', |
| 251 | b't' => '\t', |
| 252 | b'u' => { |
| 253 | let mut cp = self.hex4()?; |
| 254 | if (0xD800..0xDC00).contains(&cp) && self.b[self.i..].starts_with(b"\\u") { |
| 255 | self.i += 2; |
| 256 | let lo = self.hex4()?; |
| 257 | cp = 0x10000 + ((cp - 0xD800) << 10) + (lo.wrapping_sub(0xDC00) & 0x3ff); |
| 258 | } |
| 259 | char::from_u32(cp).unwrap_or('\u{fffd}') |
| 260 | } |
| 261 | _ => return Err("unknown escape".into()), |
| 262 | }; |
| 263 | let mut tmp = [0u8; 4]; |
| 264 | out.extend_from_slice(ch.encode_utf8(&mut tmp).as_bytes()); |
| 265 | } |
| 266 | _ => out.push(c), |
| 267 | } |
| 268 | } |
| 269 | String::from_utf8(out).map_err(|_| "invalid UTF-8 in string".to_string()) |
| 270 | } |
| 271 | fn val(&mut self) -> Result<J, String> { |
| 272 | self.ws(); |
| 273 | match self.b.get(self.i).ok_or("unexpected end")? { |
| 274 | b'{' => { |
| 275 | self.i += 1; |
| 276 | let mut v = Vec::new(); |
| 277 | loop { |
| 278 | self.ws(); |
| 279 | if self.b.get(self.i) == Some(&b'}') { |
| 280 | self.i += 1; |
| 281 | break; |
| 282 | } |
| 283 | if self.b.get(self.i) != Some(&b'"') { |
| 284 | return Err(format!("expected key at {}", self.i)); |
| 285 | } |
| 286 | let k = self.string()?; |
| 287 | self.ws(); |
| 288 | if self.b.get(self.i) != Some(&b':') { |
| 289 | return Err(format!("expected ':' at {}", self.i)); |
| 290 | } |
| 291 | self.i += 1; |
| 292 | let x = self.val()?; |
| 293 | v.push((k, x)); |
| 294 | self.ws(); |
| 295 | match self.b.get(self.i) { |
| 296 | Some(b',') => self.i += 1, |
| 297 | Some(b'}') => {} |
| 298 | _ => return Err(format!("expected ',' or '}}' at {}", self.i)), |
| 299 | } |
| 300 | } |
| 301 | Ok(J::Obj(v)) |
| 302 | } |
| 303 | b'[' => { |
| 304 | self.i += 1; |
| 305 | let mut v = Vec::new(); |
| 306 | loop { |
| 307 | self.ws(); |
| 308 | if self.b.get(self.i) == Some(&b']') { |
| 309 | self.i += 1; |
| 310 | break; |
| 311 | } |
| 312 | v.push(self.val()?); |
| 313 | self.ws(); |
| 314 | match self.b.get(self.i) { |
| 315 | Some(b',') => self.i += 1, |
| 316 | Some(b']') => {} |
| 317 | _ => return Err(format!("expected ',' or ']' at {}", self.i)), |
| 318 | } |
| 319 | } |
| 320 | Ok(J::Arr(v)) |
| 321 | } |
| 322 | b'"' => Ok(J::Str(self.string()?)), |
| 323 | b't' => self.lit("true", J::Bool(true)), |
| 324 | b'f' => self.lit("false", J::Bool(false)), |
| 325 | b'n' => self.lit("null", J::Null), |
| 326 | _ => { |
| 327 | let st = self.i; |
| 328 | while self.i < self.b.len() && matches!(self.b[self.i], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') { |
| 329 | self.i += 1; |
| 330 | } |
| 331 | let t = std::str::from_utf8(&self.b[st..self.i]).map_err(|e| e.to_string())?; |
| 332 | t.parse::<f64>().map(J::Num).map_err(|_| format!("bad number at {}", st)) |
| 333 | } |
| 334 | } |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | fn parse_json(b: &[u8]) -> Result<J, String> { |
| 339 | let mut p = P { b, i: 0 }; |
| 340 | let v = p.val()?; |
| 341 | p.ws(); |
| 342 | if p.i != b.len() { |
| 343 | return Err(format!("trailing bytes at {}", p.i)); |
| 344 | } |
| 345 | Ok(v) |
| 346 | } |
| 347 | |
| 348 | fn jesc(s: &str) -> String { |
| 349 | let mut o = String::from("\""); |
| 350 | for c in s.chars() { |
| 351 | match c { |
| 352 | '"' => o.push_str("\\\""), |
| 353 | '\\' => o.push_str("\\\\"), |
| 354 | '\n' => o.push_str("\\n"), |
| 355 | '\r' => o.push_str("\\r"), |
| 356 | '\t' => o.push_str("\\t"), |
| 357 | c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)), |
| 358 | c => o.push(c), |
| 359 | } |
| 360 | } |
| 361 | o.push('"'); |
| 362 | o |
| 363 | } |
| 364 | |
| 365 | // ---------------------------------------------------------------- model |
| 366 | |
| 367 | fn is_hex64(s: &str) -> bool { |
| 368 | s.len() == 64 && s.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f')) |
| 369 | } |
| 370 | |
| 371 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 372 | enum V { |
| 373 | Pass, |
| 374 | Fail, |
| 375 | NotRun, |
| 376 | } |
| 377 | |
| 378 | impl V { |
| 379 | fn word(self) -> &'static str { |
| 380 | match self { |
| 381 | V::Pass => "PASS", |
| 382 | V::Fail => "FAIL", |
| 383 | V::NotRun => "NOT_RUN", |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | #[derive(Clone)] |
| 389 | struct Row { |
| 390 | name: String, |
| 391 | v: V, |
| 392 | reason: String, |
| 393 | } |
| 394 | |
| 395 | fn row(name: &str, v: V, reason: impl Into<String>) -> Row { |
| 396 | Row { name: name.to_string(), v, reason: reason.into() } |
| 397 | } |
| 398 | |
| 399 | struct Rec { |
| 400 | step: String, |
| 401 | j: J, |
| 402 | } |
| 403 | |
| 404 | struct Ctx { |
| 405 | dir: PathBuf, |
| 406 | recs: Vec<Rec>, |
| 407 | } |
| 408 | |
| 409 | impl Ctx { |
| 410 | fn rec(&self, step: &str) -> Option<&Rec> { |
| 411 | self.recs.iter().find(|r| r.step == step) |
| 412 | } |
| 413 | fn index(&self, step: &str) -> Option<usize> { |
| 414 | self.recs.iter().position(|r| r.step == step) |
| 415 | } |
| 416 | fn artifact(&self, name: &str) -> PathBuf { |
| 417 | self.dir.join("artifacts").join(name) |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | // ---------------------------------------------------------------- chain checks |
| 422 | |
| 423 | struct Chain { |
| 424 | problems: Vec<String>, |
| 425 | notes: Vec<String>, |
| 426 | objective_id: String, |
| 427 | run_id: String, |
| 428 | status_words: BTreeMap<String, String>, |
| 429 | } |
| 430 | |
| 431 | fn walk(dir: &Path, base: &Path, out: &mut Vec<String>, problems: &mut Vec<String>) { |
| 432 | let rd = match fs::read_dir(dir) { |
| 433 | Ok(r) => r, |
| 434 | Err(e) => { |
| 435 | problems.push(format!("UNREADABLE_DIR: {}: {}", dir.display(), e)); |
| 436 | return; |
| 437 | } |
| 438 | }; |
| 439 | for e in rd.flatten() { |
| 440 | let p = e.path(); |
| 441 | let rel = p.strip_prefix(base).unwrap().to_string_lossy().to_string(); |
| 442 | match fs::symlink_metadata(&p) { |
| 443 | Ok(m) if m.file_type().is_symlink() => problems.push(format!("SYMLINK: {}", rel)), |
| 444 | Ok(m) if m.is_dir() => walk(&p, base, out, problems), |
| 445 | Ok(_) => out.push(rel), |
| 446 | Err(e) => problems.push(format!("UNREADABLE: {}: {}", rel, e)), |
| 447 | } |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | fn load_chain(dir: &Path, objective_arg: Option<&str>) -> (Ctx, Chain) { |
| 452 | let mut ch = Chain { |
| 453 | problems: vec![], |
| 454 | notes: vec![], |
| 455 | objective_id: String::new(), |
| 456 | run_id: String::new(), |
| 457 | status_words: BTreeMap::new(), |
| 458 | }; |
| 459 | let mut ctx = Ctx { dir: dir.to_path_buf(), recs: vec![] }; |
| 460 | let cdir = dir.join("chain"); |
| 461 | let mut names: Vec<String> = match fs::read_dir(&cdir) { |
| 462 | Ok(r) => r |
| 463 | .flatten() |
| 464 | .map(|e| e.file_name().to_string_lossy().to_string()) |
| 465 | .filter(|n| n.len() > 9 && n.ends_with(".json") && n.as_bytes()[..3].iter().all(|c| c.is_ascii_digit()) && n.as_bytes()[3] == b'-') |
| 466 | .collect(), |
| 467 | Err(e) => { |
| 468 | ch.problems.push(format!("NO_CHAIN: cannot read {}: {}", cdir.display(), e)); |
| 469 | return (ctx, ch); |
| 470 | } |
| 471 | }; |
| 472 | names.sort(); |
| 473 | if names.is_empty() { |
| 474 | ch.problems.push("NO_CHAIN: no chain/NNN-*.json receipts".into()); |
| 475 | } |
| 476 | let mut prev = "0".repeat(64); |
| 477 | for (i, n) in names.iter().enumerate() { |
| 478 | let want_no = format!("{:03}", i + 1); |
| 479 | if !n.starts_with(&want_no) { |
| 480 | ch.problems.push(format!("SEQUENCE_GAP: expected a receipt numbered {} but found {}", want_no, n)); |
| 481 | } |
| 482 | let bytes = match fs::read(cdir.join(n)) { |
| 483 | Ok(b) => b, |
| 484 | Err(e) => { |
| 485 | ch.problems.push(format!("UNREADABLE: chain/{}: {}", n, e)); |
| 486 | continue; |
| 487 | } |
| 488 | }; |
| 489 | let sha = sha256_bytes(&bytes); |
| 490 | let j = match parse_json(&bytes) { |
| 491 | Ok(j) => j, |
| 492 | Err(e) => { |
| 493 | ch.problems.push(format!("BAD_JSON: chain/{}: {}", n, e)); |
| 494 | prev = sha; |
| 495 | continue; |
| 496 | } |
| 497 | }; |
| 498 | let step = j.s("step").unwrap_or("").to_string(); |
| 499 | let fname_step = n[4..n.len() - 5].to_string(); |
| 500 | if step != fname_step { |
| 501 | ch.problems.push(format!("STEP_NAME: chain/{} carries step {:?}", n, step)); |
| 502 | } |
| 503 | match j.s("prev_receipt_sha256") { |
| 504 | Some(p) if p == prev => {} |
| 505 | Some(p) => ch.problems.push(format!( |
| 506 | "LINK_BROKEN: chain/{} prev_receipt_sha256 {} but the previous file hashes to {}", |
| 507 | n, p, prev |
| 508 | )), |
| 509 | None => ch.problems.push(format!("LINK_BROKEN: chain/{} has no prev_receipt_sha256", n)), |
| 510 | } |
| 511 | for (field, slot) in [("objective_id", 0), ("run_id", 1)] { |
| 512 | let cur = if slot == 0 { &mut ch.objective_id } else { &mut ch.run_id }; |
| 513 | match j.s(field) { |
| 514 | Some(v) if cur.is_empty() => *cur = v.to_string(), |
| 515 | Some(v) if v == cur => {} |
| 516 | Some(v) => ch.problems.push(format!("ID_MISMATCH: chain/{} {} {} differs from {}", n, field, v, cur)), |
| 517 | None => ch.problems.push(format!("ID_MISMATCH: chain/{} has no {}", n, field)), |
| 518 | } |
| 519 | } |
| 520 | if let Some(st) = j.s("status") { |
| 521 | ch.status_words.insert(step.clone(), st.to_string()); |
| 522 | } |
| 523 | ctx.recs.push(Rec { step, j }); |
| 524 | prev = sha; |
| 525 | } |
| 526 | // manifest |
| 527 | let mpath = cdir.join("SHA256SUMS"); |
| 528 | let mut listed: BTreeMap<String, String> = BTreeMap::new(); |
| 529 | match fs::read_to_string(&mpath) { |
| 530 | Err(e) => ch.problems.push(format!("MANIFEST_MISSING: chain/SHA256SUMS: {}", e)), |
| 531 | Ok(t) => { |
| 532 | for (ln, line) in t.lines().enumerate() { |
| 533 | if line.trim().is_empty() { |
| 534 | continue; |
| 535 | } |
| 536 | if line.len() > 66 && is_hex64(&line[..64]) && &line[64..66] == " " { |
| 537 | let p = line[66..].trim_start_matches("./").to_string(); |
| 538 | if listed.insert(p.clone(), line[..64].to_string()).is_some() { |
| 539 | ch.problems.push(format!("MANIFEST_DUPLICATE: {} listed twice", p)); |
| 540 | } |
| 541 | } else { |
| 542 | ch.problems.push(format!("MANIFEST_SYNTAX: SHA256SUMS line {}", ln + 1)); |
| 543 | } |
| 544 | } |
| 545 | } |
| 546 | } |
| 547 | let mut files = vec![]; |
| 548 | walk(dir, dir, &mut files, &mut ch.problems); |
| 549 | files.sort(); |
| 550 | const SELF_OUT: [&str; 3] = ["chain/SHA256SUMS", "VERIFIER_VERDICT.txt", "VERIFIER_RECEIPT.json"]; |
| 551 | for f in &files { |
| 552 | if SELF_OUT.contains(&f.as_str()) { |
| 553 | continue; |
| 554 | } |
| 555 | match listed.get(f) { |
| 556 | None => ch.problems.push(format!("MANIFEST_UNLISTED: {} is in the run folder but not in chain/SHA256SUMS", f)), |
| 557 | Some(want) => match sha256_file(&dir.join(f)) { |
| 558 | Ok(got) if &got == want => {} |
| 559 | Ok(got) => ch.problems.push(format!("MANIFEST_DIGEST: {} hashes to {} but the manifest says {}", f, got, want)), |
| 560 | Err(e) => ch.problems.push(format!("UNREADABLE: {}", e)), |
| 561 | }, |
| 562 | } |
| 563 | } |
| 564 | for (p, _) in &listed { |
| 565 | if !files.contains(p) { |
| 566 | if p.ends_with(".log") { |
| 567 | ch.notes.push(format!("manifest lists {} which is absent from the folder (logs are never an input to a row)", p)); |
| 568 | } else { |
| 569 | ch.problems.push(format!("MANIFEST_ABSENT: {} is listed in chain/SHA256SUMS but missing from the run folder", p)); |
| 570 | } |
| 571 | } |
| 572 | } |
| 573 | // objective id and run id recomputation |
| 574 | if let Some(txt) = ctx.rec("E2").and_then(|r| r.j.s("objective_text")) { |
| 575 | let want = sha256_bytes(format!("AIEN_E2E_OBJECTIVE_V1\n{}", txt).as_bytes()); |
| 576 | if want != ch.objective_id { |
| 577 | ch.problems.push(format!("OBJECTIVE_ID: text in the E2 receipt hashes to {} but the chain says {}", want, ch.objective_id)); |
| 578 | } |
| 579 | if let Some(a) = objective_arg { |
| 580 | if a != want { |
| 581 | ch.problems.push(format!("OBJECTIVE_ID: --objective-id {} differs from the recomputed {}", a, want)); |
| 582 | } |
| 583 | } |
| 584 | } else { |
| 585 | ch.notes.push("no objective text in an E2 receipt: objective_id not recomputed".into()); |
| 586 | if let Some(a) = objective_arg { |
| 587 | if a != ch.objective_id { |
| 588 | ch.problems.push(format!("OBJECTIVE_ID: --objective-id {} differs from the chain's {}", a, ch.objective_id)); |
| 589 | } |
| 590 | } |
| 591 | } |
| 592 | if let Some(pre) = ctx.rec("PRE") { |
| 593 | if let (Some(d), Some(w), Some(h)) = (pre.j.s("daemon_sha256"), pre.j.s("model_weights_digest"), pre.j.s("host")) { |
| 594 | let want = sha256_bytes(format!("{}\n{}\n{}\n{}", ch.objective_id, d, w, h).as_bytes()); |
| 595 | if want != ch.run_id { |
| 596 | ch.problems.push(format!("RUN_ID: recomputed {} but the chain says {}", want, ch.run_id)); |
| 597 | } |
| 598 | } else { |
| 599 | ch.notes.push("PRE receipt lacks daemon, weights or host: run_id not recomputed".into()); |
| 600 | } |
| 601 | } |
| 602 | (ctx, ch) |
| 603 | } |
| 604 | |
| 605 | // ---------------------------------------------------------------- row derivation |
| 606 | |
| 607 | fn word_count(s: &str) -> usize { |
| 608 | s.split_whitespace().count() |
| 609 | } |
| 610 | |
| 611 | fn topics_from(obj: &str) -> Vec<String> { |
| 612 | let Some(p) = obj.find("Mention ") else { return vec![] }; |
| 613 | let rest = &obj[p + 8..]; |
| 614 | let end = rest.rfind('.').unwrap_or(rest.len()); |
| 615 | rest[..end] |
| 616 | .replace(" and ", ", ") |
| 617 | .split(", ") |
| 618 | .map(|t| t.trim().trim_start_matches("the ").to_string()) |
| 619 | .filter(|t| !t.is_empty()) |
| 620 | .collect() |
| 621 | } |
| 622 | |
| 623 | fn required_names(ctx: &Ctx, step: &str) -> Vec<String> { |
| 624 | let r = match ctx.rec(step) { |
| 625 | Some(r) => r, |
| 626 | None => return vec![], |
| 627 | }; |
| 628 | if let Some(J::Arr(a)) = r.j.get("required_names") { |
| 629 | return a.iter().filter_map(|x| if let J::Str(s) = x { Some(s.clone()) } else { None }).collect(); |
| 630 | } |
| 631 | if step == "E3m" { |
| 632 | return r.j.s("objective_text").map(topics_from).unwrap_or_default(); |
| 633 | } |
| 634 | match ctx.rec("PRE").and_then(|p| p.j.get("inbox_files")) { |
| 635 | Some(J::Arr(a)) => a.iter().filter_map(|f| f.s("name").map(String::from)).collect(), |
| 636 | _ => vec![], |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | /// The E3m D4 rule of ACCEPTANCE-v1.3.1-e3m.md, as the harness writes it into the E3m receipt's `d4_rule`. |
| 641 | const D4_RULE_V131: &str = "case-insensitive whole word: LC_ALL=C grep -q -i -w (ACCEPTANCE-v1.3.1-e3m.md)"; |
| 642 | |
| 643 | /// GNU `grep -i -w` under `LC_ALL=C`: `word` occurs in `text` in any ASCII letter case with no ASCII letter, digit or |
| 644 | /// underscore directly before or after that occurrence (VERIFIER-v1.1-e3m.md). |
| 645 | fn contains_word_ci(text: &str, word: &str) -> bool { |
| 646 | let (t, w) = (text.as_bytes(), word.as_bytes()); |
| 647 | if w.is_empty() || w.len() > t.len() { |
| 648 | return false; |
| 649 | } |
| 650 | let wc = |c: u8| c.is_ascii_alphanumeric() || c == b'_'; |
| 651 | (0..=t.len() - w.len()).any(|i| { |
| 652 | t[i..i + w.len()].eq_ignore_ascii_case(w) && (i == 0 || !wc(t[i - 1])) && (i + w.len() == t.len() || !wc(t[i + w.len()])) |
| 653 | }) |
| 654 | } |
| 655 | |
| 656 | fn base(p: &str) -> &str { |
| 657 | p.rsplit('/').next().unwrap_or(p) |
| 658 | } |
| 659 | |
| 660 | fn doc_row(ctx: &Ctx, step: &str) -> Row { |
| 661 | let r = match ctx.rec(step) { |
| 662 | Some(r) => r, |
| 663 | None => return row(step, V::NotRun, "no receipt for this step in the chain"), |
| 664 | }; |
| 665 | let j = &r.j; |
| 666 | let Some(state) = j.s("effect_state") else { |
| 667 | return row(step, V::NotRun, "receipt has no effect_state fact"); |
| 668 | }; |
| 669 | if state != "DONE" { |
| 670 | return row(step, V::Fail, format!("effect_state {:?}: the file-writing effect did not happen", state)); |
| 671 | } |
| 672 | let (Some(wp), Some(cs)) = (j.s("written_path"), j.s("content_sha256")) else { |
| 673 | return row(step, V::NotRun, "effect_state DONE but no written_path or content_sha256 in the receipt"); |
| 674 | }; |
| 675 | if !is_hex64(cs) { |
| 676 | return row(step, V::NotRun, "content_sha256 is not a sha256"); |
| 677 | } |
| 678 | let rel = format!("{}-{}", step, base(wp)); |
| 679 | let path = ctx.artifact(&rel); |
| 680 | let bytes = match fs::read(&path) { |
| 681 | Ok(b) => b, |
| 682 | Err(_) => return row(step, V::Fail, format!("OUTPUT_ABSENT: artifacts/{} is not in the run folder", rel)), |
| 683 | }; |
| 684 | let got = sha256_bytes(&bytes); |
| 685 | if got != cs { |
| 686 | return row(step, V::Fail, format!("DIGEST_MISMATCH: artifacts/{} hashes to {} but the receipt content_sha256 is {}", rel, got, cs)); |
| 687 | } |
| 688 | if let Some(d) = j.s("disk_sha256") { |
| 689 | if d != cs { |
| 690 | return row(step, V::Fail, format!("DIGEST_MISMATCH: disk_sha256 {} differs from content_sha256 {}", d, cs)); |
| 691 | } |
| 692 | } |
| 693 | let text = match String::from_utf8(bytes) { |
| 694 | Ok(t) => t, |
| 695 | Err(_) => return row(step, V::Fail, "D1: output is not valid UTF-8"), |
| 696 | }; |
| 697 | let mut failed = vec![]; |
| 698 | if !text.starts_with("# ") { |
| 699 | failed.push("D2 first line does not start with \"# \"".to_string()); |
| 700 | } |
| 701 | let wc = word_count(&text); |
| 702 | if wc > 200 { |
| 703 | failed.push(format!("D3 {} words, at most 200 allowed", wc)); |
| 704 | } |
| 705 | let names = required_names(ctx, step); |
| 706 | if names.is_empty() { |
| 707 | return row(step, V::NotRun, "no required names or topics can be read from the receipts"); |
| 708 | } |
| 709 | // D4: E3m topic words follow the rule its receipt was judged under (VERIFIER-v1.1-e3m.md); E3 file names stay exact. |
| 710 | let whole_word = match (step, j.s("d4_rule")) { |
| 711 | ("E3m", Some(D4_RULE_V131)) => true, |
| 712 | ("E3m", Some(other)) => return row(step, V::NotRun, format!("unknown d4_rule {:?} in the receipt", other)), |
| 713 | _ => false, |
| 714 | }; |
| 715 | let missing: Vec<&String> = |
| 716 | names.iter().filter(|n| if whole_word { !contains_word_ci(&text, n) } else { !text.contains(n.as_str()) }).collect(); |
| 717 | if !missing.is_empty() { |
| 718 | failed.push(format!("D4 required name(s) missing: {:?}", missing)); |
| 719 | } |
| 720 | if !failed.is_empty() { |
| 721 | return row(step, V::Fail, format!("document rules: {}", failed.join("; "))); |
| 722 | } |
| 723 | if j.s("desk") != Some("required") { |
| 724 | return row(step, V::Fail, "desk is not 'required'"); |
| 725 | } |
| 726 | if j.n("grant_id").is_none() { |
| 727 | return row(step, V::Fail, "no grant_id: no grant was spent"); |
| 728 | } |
| 729 | match j.s("second_execute_refusal") { |
| 730 | None => return row(step, V::NotRun, "no second_execute_refusal fact (spent-once not shown)"), |
| 731 | Some("AlreadySpent") => {} |
| 732 | Some(o) => return row(step, V::Fail, format!("second execute gave {:?}, not AlreadySpent", o)), |
| 733 | } |
| 734 | if let Some(cr) = j.get("compose_receipt") { |
| 735 | if matches!(cr, J::Obj(_)) && cr.b("success") != Some(true) { |
| 736 | return row(step, V::Fail, "compose_receipt does not record success true"); |
| 737 | } |
| 738 | } |
| 739 | row(step, V::Pass, format!("DONE, digest matches, {} words, names present, grant spent once", wc)) |
| 740 | } |
| 741 | |
| 742 | fn e1_row(ctx: &Ctx) -> Row { |
| 743 | let Some(r) = ctx.rec("E1") else { return row("E1", V::NotRun, "no receipt for this step in the chain") }; |
| 744 | let j = &r.j; |
| 745 | let sig = j.s("signature_check").unwrap_or("none"); |
| 746 | if sig == "none" || !j.present_non_null("artifact_sha256") { |
| 747 | return row("E1", V::NotRun, "no release artifact or signature check in the receipt"); |
| 748 | } |
| 749 | if sig != "verified" && sig != "dry-run-key" { |
| 750 | return row("E1", V::Fail, format!("signature_check {:?}", sig)); |
| 751 | } |
| 752 | let art_ok = j.s("artifact_sha256").map(is_hex64).unwrap_or(false); |
| 753 | let files_ok = j.n("files_verified").map(|n| n > 0.0).unwrap_or(false); |
| 754 | let bins_ok = j.s("daemon_sha256").map(is_hex64).unwrap_or(false) && j.s("cli_sha256").map(is_hex64).unwrap_or(false); |
| 755 | if art_ok && files_ok && bins_ok { |
| 756 | row("E1", V::Pass, format!("signature_check {}, artifact and binaries hashed, files verified", sig)) |
| 757 | } else { |
| 758 | row("E1", V::NotRun, "artifact_sha256, files_verified, daemon_sha256 or cli_sha256 missing or malformed") |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | fn e2_row(ctx: &Ctx) -> Row { |
| 763 | let Some(r) = ctx.rec("E2") else { return row("E2", V::NotRun, "no receipt for this step in the chain") }; |
| 764 | let j = &r.j; |
| 765 | let (Some(t), Some(h)) = (j.s("objective_text"), j.s("objective_text_sha256")) else { |
| 766 | return row("E2", V::NotRun, "no objective text or text digest in the receipt"); |
| 767 | }; |
| 768 | if sha256_bytes(t.as_bytes()) != h { |
| 769 | return row("E2", V::Fail, "objective_text_sha256 does not match the objective text"); |
| 770 | } |
| 771 | if j.s("operator_surface") != Some("aien-cli") { |
| 772 | return row("E2", V::NotRun, format!("operator_surface {:?} is not aien-cli", j.s("operator_surface").unwrap_or(""))); |
| 773 | } |
| 774 | let inst = j.s("installation_record").unwrap_or("NOT_RUN"); |
| 775 | if inst.starts_with("NOT_RUN") { |
| 776 | return row("E2", V::NotRun, "no installation-side record of the objective (harness-side only)"); |
| 777 | } |
| 778 | if j.b("recorded_before_work") != Some(true) { |
| 779 | return row("E2", V::Fail, "recorded_before_work is not true"); |
| 780 | } |
| 781 | let me = ctx.index("E2").unwrap(); |
| 782 | for s in ["E3", "E3m", "E4", "E6"] { |
| 783 | if let Some(i) = ctx.index(s) { |
| 784 | if i < me { |
| 785 | return row("E2", V::Fail, format!("effect receipt {} predates the objective record", s)); |
| 786 | } |
| 787 | } |
| 788 | } |
| 789 | row("E2", V::Pass, "objective recorded through aien-cli before any effect receipt") |
| 790 | } |
| 791 | |
| 792 | fn e4_row(ctx: &Ctx, e4_recalled: &mut bool) -> Row { |
| 793 | let Some(r) = ctx.rec("E4") else { return row("E4", V::NotRun, "no receipt for this step in the chain") }; |
| 794 | let j = &r.j; |
| 795 | let Some(rk) = j.s("restart_kind") else { return row("E4", V::NotRun, "receipt carries no restart facts") }; |
| 796 | if rk != "graceful" && rk != "sigkill" { |
| 797 | return row("E4", V::Fail, format!("restart_kind {:?}", rk)); |
| 798 | } |
| 799 | if let Some(st) = j.s("effect_state") { |
| 800 | if st != "DONE" { |
| 801 | return row("E4", V::Fail, format!("second objective produced no effect (effect_state {:?}); recall after restart not shown", st)); |
| 802 | } |
| 803 | } |
| 804 | match j.b("recall_after_restart") { |
| 805 | None => return row("E4", V::NotRun, "no recall_after_restart fact"), |
| 806 | Some(false) => return row("E4", V::Fail, "recall_after_restart is false"), |
| 807 | Some(true) => {} |
| 808 | } |
| 809 | let (Some(_store), Some(item)) = (j.s("memory_store"), j.s("item_sha256")) else { |
| 810 | return row("E4", V::NotRun, "memory_store or item_sha256 missing"); |
| 811 | }; |
| 812 | if !is_hex64(item) { |
| 813 | return row("E4", V::NotRun, "item_sha256 is not a sha256"); |
| 814 | } |
| 815 | if let Ok(got) = sha256_file(&ctx.artifact("E4-remember.json")) { |
| 816 | if got != item { |
| 817 | return row("E4", V::Fail, "DIGEST_MISMATCH: item_sha256 differs from artifacts/E4-remember.json"); |
| 818 | } |
| 819 | } |
| 820 | let (Some(ru), Some(cu)) = (j.s("restart_utc"), j.s("recall_utc")) else { |
| 821 | return row("E4", V::NotRun, "restart_utc or recall_utc missing"); |
| 822 | }; |
| 823 | if cu < ru { |
| 824 | return row("E4", V::Fail, "the recall receipt predates the restart"); |
| 825 | } |
| 826 | let (base_step, first) = if ctx.rec("E3m").is_some() { ("E3m", required_names(ctx, "E3m")) } else { ("E3", required_names(ctx, "E3")) }; |
| 827 | let Some(first) = first.first().cloned() else { return row("E4", V::NotRun, "no first required name to look for") }; |
| 828 | let before_rel = format!("{}-report.md", base_step); |
| 829 | let (Ok(before), Ok(after)) = (fs::read_to_string(ctx.artifact(&before_rel)), fs::read_to_string(ctx.artifact("E4-report.md"))) else { |
| 830 | return row("E4", V::Fail, format!("OUTPUT_ABSENT: artifacts/{} or artifacts/E4-report.md missing", before_rel)); |
| 831 | }; |
| 832 | let nl = |s: &str| s.bytes().filter(|&c| c == b'\n').count(); |
| 833 | if !after.starts_with(&before) || nl(&after) != nl(&before) + 1 { |
| 834 | return row("E4", V::Fail, "the report after the second objective is not the earlier report plus exactly one line"); |
| 835 | } |
| 836 | let last = after.trim_end_matches('\n').rsplit('\n').next().unwrap_or(""); |
| 837 | if !last.to_lowercase().contains(&first.to_lowercase()) { |
| 838 | return row("E4", V::Fail, format!("the appended line does not name {:?}", first)); |
| 839 | } |
| 840 | *e4_recalled = true; |
| 841 | row("E4", V::Pass, format!("{} restart, recall after restart, one line appended naming {:?}", rk, first)) |
| 842 | } |
| 843 | |
| 844 | fn e6_row(ctx: &Ctx) -> Row { |
| 845 | let Some(r) = ctx.rec("E6") else { return row("E6", V::NotRun, "no receipt for this step in the chain") }; |
| 846 | let j = &r.j; |
| 847 | let (Some(kp), Some(rc), Some(eb), Some(ea), Some(dup)) = ( |
| 848 | j.s("kill_point"), |
| 849 | j.n("restart_count"), |
| 850 | j.n("effects_before_kill"), |
| 851 | j.n("effects_after_restart"), |
| 852 | j.n("duplicates"), |
| 853 | ) else { |
| 854 | return row("E6", V::NotRun, "kill_point, restart_count, effects_before_kill, effects_after_restart or duplicates missing"); |
| 855 | }; |
| 856 | let Some(tr) = j.s("third_execute_refusal") else { return row("E6", V::NotRun, "no third_execute_refusal fact") }; |
| 857 | let mut bad = vec![]; |
| 858 | if kp.is_empty() { |
| 859 | bad.push("empty kill_point".to_string()); |
| 860 | } |
| 861 | if rc < 1.0 { |
| 862 | bad.push(format!("restart_count {}", rc)); |
| 863 | } |
| 864 | if eb != 0.0 { |
| 865 | bad.push(format!("effects_before_kill {}", eb)); |
| 866 | } |
| 867 | if ea != 1.0 { |
| 868 | bad.push(format!("effects_after_restart {}", ea)); |
| 869 | } |
| 870 | if dup != 0.0 { |
| 871 | bad.push(format!("duplicates {}", dup)); |
| 872 | } |
| 873 | if j.n("grant_id").is_none() { |
| 874 | bad.push("no grant_id".into()); |
| 875 | } |
| 876 | if tr != "AlreadySpent" { |
| 877 | bad.push(format!("third execute gave {:?}", tr)); |
| 878 | } |
| 879 | if bad.is_empty() { |
| 880 | row("E6", V::Pass, format!("killed at {}, restarted, effect once, duplicates 0, third execute AlreadySpent", kp)) |
| 881 | } else { |
| 882 | row("E6", V::Fail, bad.join("; ")) |
| 883 | } |
| 884 | } |
| 885 | |
| 886 | fn ctrl_simple(ctx: &Ctx, step: &str, check: impl Fn(&J) -> Option<Result<String, String>>) -> Row { |
| 887 | let Some(r) = ctx.rec(step) else { return row(step, V::NotRun, "no receipt for this step in the chain") }; |
| 888 | match check(&r.j) { |
| 889 | None => row(step, V::NotRun, "receipt lacks the facts this control needs"), |
| 890 | Some(Ok(m)) => row(step, V::Pass, m), |
| 891 | Some(Err(m)) => row(step, V::Fail, m), |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | fn contains_ci(h: Option<&str>, n: &str) -> bool { |
| 896 | h.map(|h| h.to_lowercase().contains(&n.to_lowercase())).unwrap_or(false) |
| 897 | } |
| 898 | |
| 899 | fn ctrl_e3a(ctx: &Ctx) -> Row { |
| 900 | ctrl_simple(ctx, "CTRL-E3a", |j| { |
| 901 | let ex = j.s("exit")?.trim().parse::<i64>().ok()?; |
| 902 | let log = j.s("log_line")?; |
| 903 | Some(if ex != 0 && contains_ci(Some(log), "NoDesk") { |
| 904 | Ok(format!("daemon exited {} before serving and names NoDesk", ex)) |
| 905 | } else { |
| 906 | Err(format!("exit {} and log does not name NoDesk", ex)) |
| 907 | }) |
| 908 | }) |
| 909 | } |
| 910 | |
| 911 | fn ctrl_e3b(ctx: &Ctx) -> Row { |
| 912 | ctrl_simple(ctx, "CTRL-E3b", |j| { |
| 913 | let r = j.s("refusal")?; |
| 914 | let a = j.s("file_absent")?; |
| 915 | Some(if r == "Revoked" && a == "yes" { Ok("grant revoked before spend: refused Revoked, no file".into()) } else { Err(format!("refusal {:?}, file_absent {:?}", r, a)) }) |
| 916 | }) |
| 917 | } |
| 918 | |
| 919 | fn ctrl_e4(ctx: &Ctx, e4_recalled: bool) -> Row { |
| 920 | let Some(r) = ctx.rec("CTRL-E4") else { return row("CTRL-E4", V::NotRun, "no receipt for this step in the chain") }; |
| 921 | let j = &r.j; |
| 922 | let (Some(st), Some(ch)) = (j.s("effect_state"), j.s("report_changed")) else { |
| 923 | return row("CTRL-E4", V::NotRun, "receipt lacks effect_state or report_changed"); |
| 924 | }; |
| 925 | if st == "DONE" || ch != "no" { |
| 926 | return row("CTRL-E4", V::Fail, format!("store removed yet effect_state {:?}, report_changed {:?}", st, ch)); |
| 927 | } |
| 928 | let named = match fs::read(ctx.artifact("CTRL-E4-propose.json")).ok().and_then(|b| parse_json(&b).ok()) { |
| 929 | Some(a) => a.s("error").map(|e| e.contains("E_") || e.contains("refused")).unwrap_or(false), |
| 930 | None => contains_ci(j.s("evidence"), "refused"), |
| 931 | }; |
| 932 | if !named { |
| 933 | return row("CTRL-E4", V::Fail, "no named refusal for the removed store"); |
| 934 | } |
| 935 | if !e4_recalled { |
| 936 | return row("CTRL-E4", V::NotRun, "refusal named, but E4 did not show a recall, so the control tests store loss only, not memory loss"); |
| 937 | } |
| 938 | row("CTRL-E4", V::Pass, "store removed: named refusal, report unchanged") |
| 939 | } |
| 940 | |
| 941 | fn ctrl_e1(ctx: &Ctx) -> Row { |
| 942 | ctrl_simple(ctx, "CTRL-E1", |j| { |
| 943 | let ir = j.b("install_refused")?; |
| 944 | let why = j.s("refusal_reason")?; |
| 945 | Some(if ir && (contains_ci(Some(why), "checksum") || contains_ci(Some(why), "signature")) { |
| 946 | Ok("mutated artifact refused, reason names checksum or signature".into()) |
| 947 | } else { |
| 948 | Err(format!("install_refused {}, reason {:?}", ir, why)) |
| 949 | }) |
| 950 | }) |
| 951 | } |
| 952 | |
| 953 | fn ctrl_e2(ctx: &Ctx) -> Row { |
| 954 | ctrl_simple(ctx, "CTRL-E2", |j| { |
| 955 | let rb = j.b("refused_before_execution")?; |
| 956 | let nm = j.s("refusal_name")?; |
| 957 | Some(if rb && !nm.is_empty() { Ok(format!("refused before execution: {}", nm)) } else { Err(format!("refused_before_execution {}, refusal_name {:?}", rb, nm)) }) |
| 958 | }) |
| 959 | } |
| 960 | |
| 961 | // CTRL-E5 (v1.3-ctrl-e5): judged from the LAST CTRL-E5 receipt's facts. `pre_id` is the verdict id this verifier computes |
| 962 | // from the folder with CTRL-E5 and E5 forced to NOT_RUN; the receipt's original_verdict_id must equal it. |
| 963 | fn ctrl_e5(ctx: &Ctx, pre_id: &str) -> Row { |
| 964 | let Some(r) = ctx.recs.iter().rev().find(|r| r.step == "CTRL-E5") else { return row("CTRL-E5", V::NotRun, "no receipt for this step in the chain") }; |
| 965 | let j = &r.j; |
| 966 | let (Some(rej), Some(mcu), Some(orig), Some(mutd), Some(why)) = |
| 967 | (j.b("mutated_output_rejected"), j.b("mutated_chain_unbroken"), j.s("original_verdict_id"), j.s("mutated_verdict_id"), j.s("verifier_reason")) |
| 968 | else { |
| 969 | return row("CTRL-E5", V::NotRun, "receipt lacks the facts this control needs"); |
| 970 | }; |
| 971 | let mut bad = vec![]; |
| 972 | if !rej { |
| 973 | bad.push("mutated_output_rejected false".to_string()); |
| 974 | } |
| 975 | if mcu { |
| 976 | bad.push("mutated copy's chain still unbroken".into()); |
| 977 | } |
| 978 | if !why.contains("DIGEST_MISMATCH") { |
| 979 | bad.push(format!("reason {:?} does not name DIGEST_MISMATCH", why)); |
| 980 | } |
| 981 | if !is_hex64(orig) || !is_hex64(mutd) || orig == mutd { |
| 982 | bad.push("mutated verdict id is not a different, well-formed id".into()); |
| 983 | } |
| 984 | if orig != pre_id { |
| 985 | bad.push(format!("original_verdict_id {} is not the pre-CTRL-E5 id {} this verifier derives", orig, pre_id)); |
| 986 | } |
| 987 | if bad.is_empty() { |
| 988 | row("CTRL-E5", V::Pass, "one byte of an output changed on a copy: rejected on DIGEST_MISMATCH, chain broken, verdict id changed") |
| 989 | } else { |
| 990 | row("CTRL-E5", V::Fail, bad.join("; ")) |
| 991 | } |
| 992 | } |
| 993 | |
| 994 | fn ctrl_e6(ctx: &Ctx) -> Row { |
| 995 | ctrl_simple(ctx, "CTRL-E6", |j| { |
| 996 | let nm = j.s("refusal_name")?; |
| 997 | let ea = j.n("effects_after_restart")?; |
| 998 | Some(if !nm.is_empty() && ea == 0.0 { Ok(format!("durable state removed: refused {}, no second effect", nm)) } else { Err(format!("refusal_name {:?}, effects_after_restart {}", nm, ea)) }) |
| 999 | }) |
| 1000 | } |
| 1001 | |
| 1002 | fn net_row(ctx: &Ctx) -> Row { |
| 1003 | ctrl_simple(ctx, "NET", |j| { |
| 1004 | let n = j.n("daemon_established_tcp")?; |
| 1005 | Some(if n == 0.0 { Ok("daemon held no established TCP socket".into()) } else { Err(format!("{} established TCP socket(s)", n)) }) |
| 1006 | }) |
| 1007 | } |
| 1008 | |
| 1009 | fn pre_row(ctx: &Ctx) -> Row { |
| 1010 | ctrl_simple(ctx, "PRE", |j| { |
| 1011 | let w = j.s("model_weights_digest")?; |
| 1012 | let cw = j.s("candidate_weights_sha256")?; |
| 1013 | let t = j.s("tokenizer_sha256")?; |
| 1014 | let ct = j.s("candidate_tokenizer_sha256")?; |
| 1015 | let bl = j.s("backend_line")?; |
| 1016 | let h = j.s("host")?; |
| 1017 | Some(if is_hex64(w) && w == cw && t == ct && !bl.is_empty() && !h.is_empty() { |
| 1018 | Ok("model digests equal the candidate record; backend line and host present".into()) |
| 1019 | } else { |
| 1020 | Err("model digests differ from the candidate record or backend line missing".into()) |
| 1021 | }) |
| 1022 | }) |
| 1023 | } |
| 1024 | |
| 1025 | // ---------------------------------------------------------------- verdict |
| 1026 | |
| 1027 | fn verdict_id(objective: &str, contract: &str, rows: &BTreeMap<String, V>) -> String { |
| 1028 | let mut lines = vec![format!("objective_id {}", objective), format!("contract_sha256 {}", contract)]; |
| 1029 | for i in 1..=6 { |
| 1030 | let k = format!("E{}", i); |
| 1031 | lines.push(format!("{} {}", k, rows.get(&k).copied().unwrap_or(V::NotRun).word())); |
| 1032 | } |
| 1033 | for i in 1..=6 { |
| 1034 | let k = format!("CTRL-E{}", i); |
| 1035 | lines.push(format!("{} {}", k, rows.get(&k).copied().unwrap_or(V::NotRun).word())); |
| 1036 | } |
| 1037 | sha256_bytes(format!("AIEN_E2E_VERDICT_V1\n{}", lines.join("\n")).as_bytes()) |
| 1038 | } |
| 1039 | |
| 1040 | struct Opts { |
| 1041 | dir: PathBuf, |
| 1042 | contract: String, |
| 1043 | objective: Option<String>, |
| 1044 | peer: Option<String>, |
| 1045 | write: bool, |
| 1046 | } |
| 1047 | |
| 1048 | fn parse_args(a: &[String]) -> Result<Opts, String> { |
| 1049 | let mut dir = None; |
| 1050 | let (mut contract, mut objective, mut peer) = (None, None, None); |
| 1051 | let mut write = false; |
| 1052 | let mut i = 1; |
| 1053 | while i < a.len() { |
| 1054 | match a[i].as_str() { |
| 1055 | "--contract-sha256" | "--objective-id" | "--peer-verdict-id" => { |
| 1056 | let v = a.get(i + 1).ok_or(format!("{} needs a value", a[i]))?.clone(); |
| 1057 | if !is_hex64(&v) { |
| 1058 | return Err(format!("{} must be 64 lowercase hex characters", a[i])); |
| 1059 | } |
| 1060 | match a[i].as_str() { |
| 1061 | "--contract-sha256" => contract = Some(v), |
| 1062 | "--objective-id" => objective = Some(v), |
| 1063 | _ => peer = Some(v), |
| 1064 | } |
| 1065 | i += 2; |
| 1066 | } |
| 1067 | "--write" => { |
| 1068 | write = true; |
| 1069 | i += 1; |
| 1070 | } |
| 1071 | s if !s.starts_with("--") && dir.is_none() => { |
| 1072 | dir = Some(PathBuf::from(s)); |
| 1073 | i += 1; |
| 1074 | } |
| 1075 | s => return Err(format!("unknown argument {}", s)), |
| 1076 | } |
| 1077 | } |
| 1078 | Ok(Opts { |
| 1079 | dir: dir.ok_or("usage: aien-verify RUN_DIR --contract-sha256 HEX [--objective-id HEX] [--peer-verdict-id HEX] [--write]")?, |
| 1080 | contract: contract.ok_or("--contract-sha256 is required (the frozen contract digest, never compiled in)")?, |
| 1081 | objective, |
| 1082 | peer, |
| 1083 | write, |
| 1084 | }) |
| 1085 | } |
| 1086 | |
| 1087 | fn build_host() -> String { |
| 1088 | fs::read_to_string("/proc/sys/kernel/hostname") |
| 1089 | .ok() |
| 1090 | .map(|s| s.trim().to_string()) |
| 1091 | .filter(|s| !s.is_empty()) |
| 1092 | .or_else(|| std::env::var("HOSTNAME").ok()) |
| 1093 | .unwrap_or_else(|| "unknown".into()) |
| 1094 | } |
| 1095 | |
| 1096 | fn main() -> ExitCode { |
| 1097 | let args: Vec<String> = std::env::args().collect(); |
| 1098 | if args.get(1).map(|s| s.as_str()) == Some("--selftest") { |
| 1099 | return match selftest() { |
| 1100 | Ok(()) => { |
| 1101 | println!("selftest ok: sha256 vectors (empty, abc, two-block, fox, million a)"); |
| 1102 | ExitCode::SUCCESS |
| 1103 | } |
| 1104 | Err(e) => { |
| 1105 | eprintln!("selftest FAILED: {}", e); |
| 1106 | ExitCode::from(3) |
| 1107 | } |
| 1108 | }; |
| 1109 | } |
| 1110 | let o = match parse_args(&args) { |
| 1111 | Ok(o) => o, |
| 1112 | Err(e) => { |
| 1113 | eprintln!("aien-verify: {}", e); |
| 1114 | return ExitCode::from(2); |
| 1115 | } |
| 1116 | }; |
| 1117 | let (ctx, chain) = load_chain(&o.dir, o.objective.as_deref()); |
| 1118 | let chain_unbroken = chain.problems.is_empty(); |
| 1119 | |
| 1120 | let mut e4_recalled = false; |
| 1121 | let mut rows: Vec<Row> = vec![]; |
| 1122 | rows.push(e1_row(&ctx)); |
| 1123 | rows.push(e2_row(&ctx)); |
| 1124 | rows.push(doc_row(&ctx, "E3")); |
| 1125 | rows.push(e4_row(&ctx, &mut e4_recalled)); |
| 1126 | let e5_idx = rows.len(); |
| 1127 | rows.push(row("E5", V::NotRun, "placeholder")); |
| 1128 | rows.push(e6_row(&ctx)); |
| 1129 | rows.push(ctrl_e1(&ctx)); |
| 1130 | rows.push(ctrl_e2(&ctx)); |
| 1131 | let a = ctrl_e3a(&ctx); |
| 1132 | let b = ctrl_e3b(&ctx); |
| 1133 | let c3 = match (a.v, b.v) { |
| 1134 | (V::Pass, V::Pass) => row("CTRL-E3", V::Pass, "CTRL-E3a and CTRL-E3b both PASS"), |
| 1135 | (V::Fail, _) | (_, V::Fail) => row("CTRL-E3", V::Fail, format!("CTRL-E3a {}, CTRL-E3b {}", a.v.word(), b.v.word())), |
| 1136 | _ => row("CTRL-E3", V::NotRun, format!("CTRL-E3a {} ({}); CTRL-E3b {} ({})", a.v.word(), a.reason, b.v.word(), b.reason)), |
| 1137 | }; |
| 1138 | rows.push(c3); |
| 1139 | rows.push(ctrl_e4(&ctx, e4_recalled)); |
| 1140 | let c5_idx = rows.len(); |
| 1141 | rows.push(row("CTRL-E5", V::NotRun, "placeholder")); |
| 1142 | rows.push(ctrl_e6(&ctx)); |
| 1143 | let mut supp = vec![pre_row(&ctx), doc_row(&ctx, "E3m"), a, b, net_row(&ctx)]; |
| 1144 | |
| 1145 | // E5: base verdict id with E5 NOT_RUN, then the peer comparison |
| 1146 | let map = |rows: &Vec<Row>| rows.iter().map(|r| (r.name.clone(), r.v)).collect::<BTreeMap<_, _>>(); |
| 1147 | let pre_id = verdict_id(&chain.objective_id, &o.contract, &map(&rows)); |
| 1148 | rows[c5_idx] = ctrl_e5(&ctx, &pre_id); |
| 1149 | let base_id = verdict_id(&chain.objective_id, &o.contract, &map(&rows)); |
| 1150 | rows[e5_idx] = match (&o.peer, chain_unbroken) { |
| 1151 | (None, _) => row("E5", V::NotRun, "no --peer-verdict-id: cross-machine agreement not shown"), |
| 1152 | (Some(_), false) => row("E5", V::Fail, "chain is not unbroken"), |
| 1153 | (Some(p), true) if *p == base_id => row("E5", V::Pass, "chain unbroken and the peer machine's base verdict id equals this machine's"), |
| 1154 | (Some(p), true) => row("E5", V::Fail, format!("peer base verdict id {} differs from this machine's {}", p, base_id)), |
| 1155 | }; |
| 1156 | let vid = verdict_id(&chain.objective_id, &o.contract, &map(&rows)); |
| 1157 | |
| 1158 | // status words in receipts that contradict the derived rows (never copied, only reported) |
| 1159 | let mut disagreements = vec![]; |
| 1160 | let derived: BTreeMap<String, V> = rows.iter().chain(supp.iter()).map(|r| (r.name.clone(), r.v)).collect(); |
| 1161 | for (step, st) in &chain.status_words { |
| 1162 | if let Some(v) = derived.get(step) { |
| 1163 | if v.word() != st && ["PASS", "FAIL", "NOT_RUN"].contains(&st.as_str()) && step != "E5" { |
| 1164 | disagreements.push(format!("status_disagreement: {} receipt says {} but the facts derive {}", step, st, v.word())); |
| 1165 | } |
| 1166 | } |
| 1167 | } |
| 1168 | |
| 1169 | let any_fail = rows.iter().chain(supp.iter()).any(|r| r.v == V::Fail); |
| 1170 | let ok = chain_unbroken && !any_fail; |
| 1171 | |
| 1172 | let mut verdict = String::from("AIEN_E2E_VERDICT_V1\n"); |
| 1173 | verdict.push_str(&format!("objective_id {}\ncontract_sha256 {}\n", chain.objective_id, o.contract)); |
| 1174 | for r in rows.iter().filter(|r| r.name != "CTRL-E3").filter(|r| r.name.starts_with('E')) { |
| 1175 | verdict.push_str(&format!("{} {}\n", r.name, r.v.word())); |
| 1176 | } |
| 1177 | for r in rows.iter().filter(|r| r.name.starts_with("CTRL-E")) { |
| 1178 | verdict.push_str(&format!("{} {}\n", r.name, r.v.word())); |
| 1179 | } |
| 1180 | verdict.push_str(&format!("verdict_id {}\nchain_unbroken {}\nbase_verdict_id {}\n", vid, chain_unbroken, base_id)); |
| 1181 | for r in rows.iter() { |
| 1182 | verdict.push_str(&format!("# {} {}: {}\n", r.name, r.v.word(), r.reason)); |
| 1183 | } |
| 1184 | for r in supp.drain(..) { |
| 1185 | verdict.push_str(&format!("# (supplementary) {} {}: {}\n", r.name, r.v.word(), r.reason)); |
| 1186 | rows.push(Row { name: format!("supp:{}", r.name), ..r }); |
| 1187 | } |
| 1188 | for p in &chain.problems { |
| 1189 | verdict.push_str(&format!("# CHAIN_PROBLEM {}\n", p)); |
| 1190 | } |
| 1191 | for d in &disagreements { |
| 1192 | verdict.push_str(&format!("# {}\n", d)); |
| 1193 | } |
| 1194 | for n in &chain.notes { |
| 1195 | verdict.push_str(&format!("# note: {}\n", n)); |
| 1196 | } |
| 1197 | print!("{}", verdict); |
| 1198 | |
| 1199 | if o.write { |
| 1200 | let exe = std::env::current_exe().ok().or_else(|| args.first().map(PathBuf::from)); |
| 1201 | let vsha = exe.and_then(|p| sha256_file(&p).ok()); |
| 1202 | let mut j = String::from("{\n"); |
| 1203 | j.push_str(&format!(" \"verifier_sha256\": {},\n", vsha.map(|s| jesc(&s)).unwrap_or("null".into()))); |
| 1204 | j.push_str(&format!(" \"verifier_build_host\": {},\n", jesc(&build_host()))); |
| 1205 | j.push_str(&format!(" \"chain_unbroken\": {},\n", chain_unbroken)); |
| 1206 | j.push_str(&format!(" \"objective_id\": {},\n \"contract_sha256\": {},\n", jesc(&chain.objective_id), jesc(&o.contract))); |
| 1207 | j.push_str(" \"rows\": [\n"); |
| 1208 | let n = rows.len(); |
| 1209 | for (i, r) in rows.iter().enumerate() { |
| 1210 | j.push_str(&format!( |
| 1211 | " {{\"row\": {}, \"verdict\": {}, \"reason\": {}}}{}\n", |
| 1212 | jesc(&r.name), |
| 1213 | jesc(r.v.word()), |
| 1214 | jesc(&r.reason), |
| 1215 | if i + 1 < n { "," } else { "" } |
| 1216 | )); |
| 1217 | } |
| 1218 | j.push_str(" ],\n \"chain_problems\": ["); |
| 1219 | j.push_str(&chain.problems.iter().map(|p| jesc(p)).collect::<Vec<_>>().join(", ")); |
| 1220 | j.push_str("],\n \"status_disagreements\": ["); |
| 1221 | j.push_str(&disagreements.iter().map(|p| jesc(p)).collect::<Vec<_>>().join(", ")); |
| 1222 | j.push_str(&format!("],\n \"base_verdict_id\": {},\n \"verdict_id\": {}\n}}\n", jesc(&base_id), jesc(&vid))); |
| 1223 | if let Err(e) = fs::write(o.dir.join("VERIFIER_VERDICT.txt"), &verdict).and_then(|_| fs::write(o.dir.join("VERIFIER_RECEIPT.json"), &j)) { |
| 1224 | eprintln!("aien-verify: cannot write into the run folder: {}", e); |
| 1225 | return ExitCode::from(2); |
| 1226 | } |
| 1227 | } |
| 1228 | if ok { |
| 1229 | ExitCode::SUCCESS |
| 1230 | } else { |
| 1231 | eprintln!("aien-verify: NOT OK (chain_unbroken {}, FAIL rows: {})", chain_unbroken, rows.iter().filter(|r| r.v == V::Fail).count()); |
| 1232 | ExitCode::from(1) |
| 1233 | } |
| 1234 | } |
| 1235 | |
| 1236 | #[cfg(test)] |
| 1237 | mod tests { |
| 1238 | use super::*; |
| 1239 | #[test] |
| 1240 | fn sha256_vectors() { |
| 1241 | selftest().unwrap(); |
| 1242 | } |
| 1243 | #[test] |
| 1244 | fn whole_word_ci_is_grep_i_w() { |
| 1245 | for yes in ["# Windmill\n", "WINDMILL", "the windmill.", "windmill,", "windmill's", "a windmill", "x-windmill"] { |
| 1246 | assert!(contains_word_ci(yes, "windmill"), "{yes:?}"); |
| 1247 | } |
| 1248 | for no in ["windmills", "windmill_x", "wind-mill", "awindmill", "windmill9", "", "windmil"] { |
| 1249 | assert!(!contains_word_ci(no, "windmill"), "{no:?}"); |
| 1250 | } |
| 1251 | assert!(contains_word_ci("windmills and a Windmill", "windmill"), "a later occurrence counts"); |
| 1252 | assert!(contains_word_ci("caf\u{e9} windmill", "windmill")); |
| 1253 | } |
| 1254 | #[test] |
| 1255 | fn topics() { |
| 1256 | assert_eq!( |
| 1257 | topics_from("Write x. Mention the harbour, the orchard and the windmill."), |
| 1258 | vec!["harbour", "orchard", "windmill"] |
| 1259 | ); |
| 1260 | } |
| 1261 | } |