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/aien-protocols-mv/blob/main/crates/aien-microjob/src/aienet0.rs # aien-protocols-mv Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem 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 `aien-protocols-mv / crates / aien-microjob / src / aienet0.rs` 1002 lines ยท 34054 bytes Raw Blame History 1 //! Aienet-0 P0 job path profile over MJB1/MJR1 2 //! (`specs/aienet/jobpath/PROFILE.md`). 3 //! 4 //! The profile carries exactly one allowlisted job kind, `matmul_u32` 5 //! (payload layout and digest of Core PR #662, 6 //! `crates/aien-hetjob/src/task.rs`), in a one-node MJB1 document. MJB1 has 7 //! no submitter signature and MJR1 has one signature, so the profile adds two 8 //! detached records: the submitter's signature inside the `AN0B` bundle and 9 //! the verifier's countersignature `AN0V`. Neither record grants anything; a 10 //! receiver checks each against a key it pinned out of band. 11 //! 12 //! Every guard in this file is a single statement tagged `AN0-GUARD `; 13 //! `specs/aienet/jobpath/mutants.sh` removes each one and requires the unit 14 //! tests below to fail. 15 16 use crate::{ 17 cancel, compute_op, dag_digest, decode, decode_receipt, effect, encode, encode_receipt, 18 input_binding, kind, operand, outcome, profile, retry, sign_receipt, verifier, Applied, Dag, 19 DagRun, Header, Node, NodeState, Operand, Receipt, Refusal, MAX_DOCUMENT, RECEIPT_LEN, 20 }; 21 use aien_provenance::{p256_compressed_key, p256_sign_low_s, p256_verify_low_s}; 22 use p256::ecdsa::SigningKey; 23 use sha2::{Digest, Sha256}; 24 25 /// The four bytes that open a bundle. 26 pub const BUNDLE_MAGIC: [u8; 4] = *b"AN0B"; 27 /// The four bytes that open a verifier countersignature. 28 pub const VERDICT_MAGIC: [u8; 4] = *b"AN0V"; 29 /// The only profile version. 30 pub const PROFILE_VERSION: u8 = 1; 31 /// Payload `kind` byte of `matmul_u32` (Core #662 `KIND_MATMUL_U32`). 32 pub const KIND_MATMUL_U32: u8 = 1; 33 /// Bytes in a `matmul_u32` payload. 34 pub const PAYLOAD_LEN: usize = 15; 35 /// Largest payload a bundle may carry (any kind). 36 pub const MAX_PAYLOAD: usize = 256; 37 /// Largest `m`, `k` or `n` the worker admits. 38 pub const MAX_DIM: u16 = 256; 39 /// Digest domain of Core #662 `MATMUL_DOMAIN`. 40 pub const MATMUL_DOMAIN: &[u8] = b"AIEN-HETJOB-MATMUL-U32-V1"; 41 /// Bytes before the payload in a bundle. 42 pub const BUNDLE_HEAD: usize = 4 + 1 + 1 + 2 + 4 + 33 + 64; 43 /// Largest bundle. 44 pub const MAX_BUNDLE: usize = BUNDLE_HEAD + MAX_PAYLOAD + MAX_DOCUMENT; 45 /// Bytes of a countersignature covered by its signature. 46 pub const VERDICT_SIGNED_LEN: usize = 4 + 4 + 32 * 4 + 33 + 3; 47 /// Bytes in a countersignature. 48 pub const VERDICT_LEN: usize = VERDICT_SIGNED_LEN + 64; 49 /// Seconds a built document stays admissible. 50 pub const DOCUMENT_TTL: u64 = 3600; 51 /// Per-node time cap written into built documents. 52 pub const NODE_TIME_MS: u32 = 120_000; 53 54 const SUBMIT_DOMAIN: &[u8] = b"AIENET0-MJB1-SUBMIT-V1\0"; 55 const VERIFY_DOMAIN: &[u8] = b"AIENET0-MJR1-VERIFY-V1\0"; 56 const VERDICT_DOMAIN: &[u8] = b"AIENET0-RECOMPUTE-MATCH-V1\0"; 57 58 /// Why the profile refused a bundle, a receipt or a countersignature. 59 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 60 pub enum An0Refusal { 61 /// Bundle or countersignature framing is malformed. 62 BadBundle, 63 /// The submitter key is not the pinned one, the signature does not 64 /// verify, or `approval_ref` does not name that key. 65 BadSubmitter, 66 /// The MJB1/MJR1 validator refused. 67 Mjb(Refusal), 68 /// Not the one allowlisted job shape. 69 NotAllowlisted, 70 /// Dimensions or caps outside the worker's bounds. 71 OverBudget, 72 /// The operand digest does not name the carried payload. 73 PayloadMismatch, 74 /// A receipt that the ledger had already applied. 75 ReplayedReceipt, 76 /// The receipt's output digest differs from the verifier's recompute. 77 RecomputeMismatch, 78 /// The receipt's verdict commitment does not match the recompute. 79 VerdictMismatch, 80 /// The countersignature does not verify against the pinned verifier key. 81 BadCountersign, 82 } 83 84 impl An0Refusal { 85 /// Stable refusal code printed by the job path. 86 pub fn name(self) -> &'static str { 87 match self { 88 An0Refusal::BadBundle => "AN0_BAD_BUNDLE", 89 An0Refusal::BadSubmitter => "AN0_BAD_SUBMITTER", 90 An0Refusal::Mjb(r) => r.name(), 91 An0Refusal::NotAllowlisted => "AN0_NOT_ALLOWLISTED", 92 An0Refusal::OverBudget => "AN0_OVER_BUDGET", 93 An0Refusal::PayloadMismatch => "AN0_PAYLOAD_MISMATCH", 94 An0Refusal::ReplayedReceipt => "AN0_REPLAYED_RECEIPT", 95 An0Refusal::RecomputeMismatch => "AN0_RECOMPUTE_MISMATCH", 96 An0Refusal::VerdictMismatch => "AN0_VERDICT_MISMATCH", 97 An0Refusal::BadCountersign => "AN0_BAD_COUNTERSIGN", 98 } 99 } 100 } 101 102 impl From for An0Refusal { 103 fn from(r: Refusal) -> Self { 104 An0Refusal::Mjb(r) 105 } 106 } 107 108 fn guard(ok: bool, r: An0Refusal) -> Result<(), An0Refusal> { 109 if ok { 110 Ok(()) 111 } else { 112 Err(r) 113 } 114 } 115 116 fn sha(parts: &[&[u8]]) -> [u8; 32] { 117 let mut h = Sha256::new(); 118 for p in parts { 119 h.update(p); 120 } 121 h.finalize().into() 122 } 123 124 fn id16(parts: &[&[u8]]) -> [u8; 16] { 125 let d = sha(parts); 126 let mut out = [0u8; 16]; 127 out.copy_from_slice(&d[..16]); 128 out 129 } 130 131 /// One `matmul_u32` job: `C = A x B`, `A` is `m x k`, `B` is `k x n`, all 132 /// entries drawn from splitmix64(`seed`) truncated to u32, arithmetic mod 2^32. 133 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 134 pub struct MatmulU32 { 135 pub m: u16, 136 pub k: u16, 137 pub n: u16, 138 pub seed: u64, 139 } 140 141 impl MatmulU32 { 142 /// The 15-byte payload: kind, m, k, n (u16 BE), seed (u64 BE). 143 pub fn encode(&self) -> [u8; PAYLOAD_LEN] { 144 let mut p = [0u8; PAYLOAD_LEN]; 145 p[0] = KIND_MATMUL_U32; 146 p[1..3].copy_from_slice(&self.m.to_be_bytes()); 147 p[3..5].copy_from_slice(&self.k.to_be_bytes()); 148 p[5..7].copy_from_slice(&self.n.to_be_bytes()); 149 p[7..15].copy_from_slice(&self.seed.to_be_bytes()); 150 p 151 } 152 153 /// Parse a payload. Any kind byte other than `matmul_u32` is not on the 154 /// allowlist. 155 pub fn decode(p: &[u8]) -> Result { 156 guard( 157 p.first() == Some(&KIND_MATMUL_U32), 158 An0Refusal::NotAllowlisted, 159 )?; // AN0-GUARD payload-kind 160 guard(p.len() == PAYLOAD_LEN, An0Refusal::BadBundle)?; 161 let u16_at = |i: usize| u16::from_be_bytes([p[i], p[i + 1]]); 162 let mut seed = [0u8; 8]; 163 seed.copy_from_slice(&p[7..15]); 164 Ok(MatmulU32 { 165 m: u16_at(1), 166 k: u16_at(3), 167 n: u16_at(5), 168 seed: u64::from_be_bytes(seed), 169 }) 170 } 171 172 /// Multiply-adds the job performs. 173 pub fn work(&self) -> u64 { 174 self.m as u64 * self.k as u64 * self.n as u64 175 } 176 177 /// Bytes of A, B and C. 178 pub fn memory(&self) -> u64 { 179 let (m, k, n) = (self.m as u64, self.k as u64, self.n as u64); 180 4 * (m * k + k * n + m * n) 181 } 182 183 /// Every dimension in `1..=MAX_DIM`. 184 pub fn in_bounds(&self) -> bool { 185 [self.m, self.k, self.n] 186 .iter() 187 .all(|&d| (1..=MAX_DIM).contains(&d)) 188 } 189 } 190 191 fn splitmix64(state: &mut u64) -> u64 { 192 *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); 193 let mut z = *state; 194 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); 195 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); 196 z ^ (z >> 31) 197 } 198 199 /// The worker kernel (i-k-j loop order, as Core #662's worker). Returns the 200 /// output digest: SHA-256(domain || m || k || n || seed || C as u32 BE). 201 pub fn matmul_u32_digest(j: &MatmulU32) -> [u8; 32] { 202 let (m, k, n) = (j.m as usize, j.k as usize, j.n as usize); 203 let mut s = j.seed; 204 let a: Vec = (0..m * k).map(|_| splitmix64(&mut s) as u32).collect(); 205 let b: Vec = (0..k * n).map(|_| splitmix64(&mut s) as u32).collect(); 206 let mut c = vec![0u32; m * n]; 207 for i in 0..m { 208 for p in 0..k { 209 let x = a[i * k + p]; 210 for q in 0..n { 211 c[i * n + q] = c[i * n + q].wrapping_add(x.wrapping_mul(b[p * n + q])); 212 } 213 } 214 } 215 let mut h = Sha256::new(); 216 h.update(MATMUL_DOMAIN); 217 h.update(j.m.to_be_bytes()); 218 h.update(j.k.to_be_bytes()); 219 h.update(j.n.to_be_bytes()); 220 h.update(j.seed.to_be_bytes()); 221 for v in &c { 222 h.update(v.to_be_bytes()); 223 } 224 h.finalize().into() 225 } 226 227 /// `approval_ref` of a profile document: names the submitter key and nonce. 228 pub fn approval_ref(submitter: &[u8; 33], nonce: &[u8; 16]) -> [u8; 32] { 229 sha(&[b"AIENET0-APPROVAL-V1\0", submitter, nonce]) 230 } 231 232 /// The tenant every Aienet-0 test document runs under (prefunded TUR test 233 /// credits, no wallet). 234 pub fn tenant() -> [u8; 32] { 235 sha(&[b"AIENET0-TENANT-TUR-TEST-V1"]) 236 } 237 238 /// The capability the single allowlisted job runs under. 239 pub fn capability() -> [u8; 32] { 240 sha(&[b"AIENET0-CAPABILITY-MATMUL-U32-V1"]) 241 } 242 243 /// Build the one-node MJB1 document for `payload`. `op` is the MJB1 compute 244 /// op; only `compute_op::MATMUL` is admitted by a worker, other values exist 245 /// for the negative control. Caps come from the payload when it parses as 246 /// `matmul_u32`, else 1. 247 pub fn build_document( 248 payload: &[u8], 249 op: u8, 250 nonce: [u8; 16], 251 submitter: &[u8; 33], 252 now: u64, 253 ) -> Vec { 254 let (work, memory) = match MatmulU32::decode(payload) { 255 Ok(j) => (j.work().max(1), j.memory().max(1)), 256 Err(_) => (1, 1), 257 }; 258 let expires_at = now + DOCUMENT_TTL; 259 let header = Header { 260 effect_ceiling: effect::COMPUTE, 261 objective_id: sha(&[b"AIENET0-OBJECTIVE-V1\0", &nonce]), 262 tenant_id: tenant(), 263 subject_id: sha(&[b"AIENET0-SUBJECT-V1\0", payload]), 264 approval_ref: approval_ref(submitter, &nonce), 265 incarnation: 1, 266 expires_at, 267 budget_time_ms: NODE_TIME_MS as u64, 268 budget_fuel: work, 269 budget_memory: memory, 270 budget_work: work, 271 budget_input_tokens: 0, 272 budget_output_tokens: 0, 273 }; 274 let node = Node { 275 job_id: id16(&[b"AIENET0-JOB-V1\0", &nonce]), 276 idempotence_key: id16(&[b"AIENET0-IDEM-V1\0", &nonce]), 277 generation: 1, 278 kind: kind::COMPUTE, 279 op, 280 profile: profile::ZERO, 281 effect_class: effect::COMPUTE, 282 input_tokens: 0, 283 output_tokens: 0, 284 required_input_tokens: 0, 285 required_output_tokens: 0, 286 verifier_kind: verifier::RECOMPUTE, 287 retry_class: retry::NEVER, 288 max_attempts: 1, 289 cancel_mode: cancel::DISCARD, 290 precision: 0, 291 substrate_mask: 1, 292 result_type: 7, 293 result_rank: 0, 294 pure: true, 295 time_ms: NODE_TIME_MS, 296 fuel: work, 297 memory, 298 work, 299 expires_at, 300 result_dims: [0; 4], 301 capability_ref: capability(), 302 tenant_id: tenant(), 303 model_ref: [0; 32], 304 verifier_ref: [0; 32], 305 deps: Vec::new(), 306 operands: vec![Operand { 307 kind: operand::CONTENT, 308 generation: 1, 309 digest: sha(&[payload]), 310 }], 311 }; 312 encode(&Dag { 313 header, 314 nodes: vec![node], 315 }) 316 .expect("one node fits") 317 } 318 319 fn submit_message(digest: &[u8; 32], payload: &[u8]) -> Vec { 320 let mut m = SUBMIT_DOMAIN.to_vec(); 321 m.extend_from_slice(digest); 322 m.extend_from_slice(&sha(&[payload])); 323 m 324 } 325 326 /// Seal a bundle: `AN0B`, version, reserved, payload length (u16 BE), 327 /// document length (u32 BE), submitter key (33), submitter signature (64), 328 /// payload, document. The signature covers the domain, `dag_digest` and 329 /// SHA-256(payload). 330 pub fn seal_bundle(document: &[u8], payload: &[u8], key: &SigningKey) -> Vec { 331 assert!(payload.len() <= MAX_PAYLOAD && document.len() <= MAX_DOCUMENT); 332 let sig = p256_sign_low_s(key, &submit_message(&dag_digest(document), payload)); 333 let mut b = Vec::with_capacity(BUNDLE_HEAD + payload.len() + document.len()); 334 b.extend_from_slice(&BUNDLE_MAGIC); 335 b.push(PROFILE_VERSION); 336 b.push(0); 337 b.extend_from_slice(&(payload.len() as u16).to_be_bytes()); 338 b.extend_from_slice(&(document.len() as u32).to_be_bytes()); 339 b.extend_from_slice(&p256_compressed_key(key)); 340 b.extend_from_slice(&sig); 341 b.extend_from_slice(payload); 342 b.extend_from_slice(document); 343 b 344 } 345 346 /// A bundle the worker admitted. 347 #[derive(Debug, Clone)] 348 pub struct Admitted { 349 pub document: Vec, 350 pub payload: Vec, 351 pub dag: Dag, 352 pub digest: [u8; 32], 353 pub job: MatmulU32, 354 } 355 356 /// Parsed bundle fields: submitter key, signature, borrowed payload and document. 357 pub type BundleParts<'a> = ([u8; 33], [u8; 64], &'a [u8], &'a [u8]); 358 359 /// Split a bundle into (submitter key, signature, payload, document). 360 pub fn split_bundle(b: &[u8]) -> Result, An0Refusal> { 361 guard( 362 b.len() >= BUNDLE_HEAD && b.len() <= MAX_BUNDLE && b[..4] == BUNDLE_MAGIC, 363 An0Refusal::BadBundle, 364 )?; 365 guard(b[4] == PROFILE_VERSION && b[5] == 0, An0Refusal::BadBundle)?; 366 let plen = u16::from_be_bytes([b[6], b[7]]) as usize; 367 let dlen = u32::from_be_bytes([b[8], b[9], b[10], b[11]]) as usize; 368 guard( 369 plen <= MAX_PAYLOAD && BUNDLE_HEAD + plen + dlen == b.len(), 370 An0Refusal::BadBundle, 371 )?; 372 let mut key = [0u8; 33]; 373 key.copy_from_slice(&b[12..45]); 374 let mut sig = [0u8; 64]; 375 sig.copy_from_slice(&b[45..109]); 376 Ok(( 377 key, 378 sig, 379 &b[BUNDLE_HEAD..BUNDLE_HEAD + plen], 380 &b[BUNDLE_HEAD + plen..], 381 )) 382 } 383 384 /// Worker admission at clock `now` (Unix seconds): submitter pinned and 385 /// signature valid, MJB1 valid and unexpired, exactly the allowlisted shape, 386 /// payload named by the operand, dimensions and caps within bounds. Replay 387 /// (a dag_digest seen before) is the caller's persistent check. 388 pub fn admit_bundle( 389 b: &[u8], 390 pinned_submitter: &[u8; 33], 391 now: u64, 392 ) -> Result { 393 let (key, sig, payload, document) = split_bundle(b)?; 394 guard(key == *pinned_submitter, An0Refusal::BadSubmitter)?; // AN0-GUARD submitter-pin 395 let digest = dag_digest(document); 396 guard( 397 p256_verify_low_s(&key, &submit_message(&digest, payload), &sig).is_ok(), 398 An0Refusal::BadSubmitter, 399 )?; // AN0-GUARD submitter-sig 400 let dag = decode(document)?; 401 guard( 402 dag.header.expires_at >= now, 403 An0Refusal::Mjb(Refusal::BadExpiry), 404 )?; 405 guard(dag.nodes.len() == 1, An0Refusal::NotAllowlisted)?; 406 let node = &dag.nodes[0]; 407 guard(node.expires_at >= now, An0Refusal::Mjb(Refusal::BadExpiry))?; // AN0-GUARD node-expiry 408 guard( 409 node.kind == kind::COMPUTE && node.op == compute_op::MATMUL, 410 An0Refusal::NotAllowlisted, 411 )?; // AN0-GUARD op-allowlist 412 guard( 413 node.verifier_kind == verifier::RECOMPUTE && node.effect_class == effect::COMPUTE, 414 An0Refusal::NotAllowlisted, 415 )?; 416 guard( 417 node.operands.len() == 1 && node.deps.is_empty(), 418 An0Refusal::NotAllowlisted, 419 )?; 420 guard( 421 node.operands[0].kind == operand::CONTENT, 422 An0Refusal::NotAllowlisted, 423 )?; 424 guard( 425 node.operands[0].digest == sha(&[payload]), 426 An0Refusal::PayloadMismatch, 427 )?; // AN0-GUARD payload-binding 428 let job = MatmulU32::decode(payload)?; 429 guard(job.in_bounds(), An0Refusal::OverBudget)?; // AN0-GUARD dim-bounds 430 guard( 431 node.work >= job.work() 432 && node.fuel >= job.work() 433 && dag.header.budget_fuel >= job.work() 434 && node.memory >= job.memory(), 435 An0Refusal::OverBudget, 436 )?; // AN0-GUARD node-caps 437 Ok(Admitted { 438 document: document.to_vec(), 439 payload: payload.to_vec(), 440 digest, 441 job, 442 dag, 443 }) 444 } 445 446 /// The verdict commitment an executor writes into `verifier_verdict` and the 447 /// verifier rebuilds from its own recompute. 448 pub fn verdict_commitment(digest: &[u8; 32], job_id: &[u8; 16], output: &[u8; 32]) -> [u8; 32] { 449 sha(&[VERDICT_DOMAIN, digest, job_id, output]) 450 } 451 452 /// Executor side: a signed COMPLETED receipt for an admitted job. 453 pub fn executor_receipt( 454 a: &Admitted, 455 output: [u8; 32], 456 used_time_ms: u32, 457 source_hash: [u8; 32], 458 policy_hash: [u8; 32], 459 key: &SigningKey, 460 ) -> [u8; RECEIPT_LEN] { 461 let node = &a.dag.nodes[0]; 462 let mut r = Receipt { 463 outcome: outcome::COMPLETED, 464 attempt: 1, 465 dag_digest: a.digest, 466 job_id: node.job_id, 467 idempotence_key: node.idempotence_key, 468 generation: node.generation, 469 used_time_ms, 470 used_input_tokens: 0, 471 used_output_tokens: 0, 472 used_fuel: a.job.work(), 473 used_memory: a.job.memory(), 474 used_work: a.job.work(), 475 input_binding: input_binding(&[], &node.operands), 476 output_digest: output, 477 source_hash, 478 model_hash: [0; 32], 479 policy_hash, 480 verifier_verdict: verdict_commitment(&a.digest, &node.job_id, &output), 481 signer_key: [0; 33], 482 signature: [0; 64], 483 }; 484 sign_receipt(&mut r, key); 485 encode_receipt(&r) 486 } 487 488 /// Verifier side, before the recompute: the receipt passes the MJR1 ledger 489 /// with only the pinned executor key trusted, is new, and leaves the node 490 /// DONE. 491 pub fn check_receipt( 492 document: &[u8], 493 receipt: &[u8], 494 pinned_executor: [u8; 33], 495 now: u64, 496 ) -> Result { 497 let trusted = vec![pinned_executor]; // AN0-GUARD executor-pin 498 let mut run = DagRun::admit(document, trusted, now)?; 499 let applied = run.apply(receipt)?; 500 guard(applied == Applied::New, An0Refusal::ReplayedReceipt)?; 501 guard( 502 run.state(0) == NodeState::Done, 503 An0Refusal::Mjb(Refusal::BadReceipt), 504 )?; 505 Ok(decode_receipt(receipt)?) 506 } 507 508 fn verdict_message(rec: &[u8]) -> Vec { 509 let mut m = VERIFY_DOMAIN.to_vec(); 510 m.extend_from_slice(&rec[..VERDICT_SIGNED_LEN]); 511 m 512 } 513 514 /// Verifier side, after the recompute: refuse unless the receipt's output 515 /// digest and verdict commitment both match `recomputed`, then countersign. 516 /// Record: `AN0V`, version, 3 reserved, SHA-256(MJR1), dag_digest, 517 /// recomputed digest, verdict commitment, verifier key (33), 3 reserved, 518 /// signature (64) over the domain and the first 172 bytes. 519 pub fn countersign( 520 receipt: &[u8], 521 recomputed: [u8; 32], 522 key: &SigningKey, 523 ) -> Result<[u8; VERDICT_LEN], An0Refusal> { 524 let r = decode_receipt(receipt)?; 525 guard(r.output_digest == recomputed, An0Refusal::RecomputeMismatch)?; // AN0-GUARD recompute-match 526 let commit = verdict_commitment(&r.dag_digest, &r.job_id, &recomputed); 527 guard(r.verifier_verdict == commit, An0Refusal::VerdictMismatch)?; // AN0-GUARD verdict-match 528 let mut rec = [0u8; VERDICT_LEN]; 529 rec[..4].copy_from_slice(&VERDICT_MAGIC); 530 rec[4] = PROFILE_VERSION; 531 rec[8..40].copy_from_slice(&sha(&[receipt])); 532 rec[40..72].copy_from_slice(&r.dag_digest); 533 rec[72..104].copy_from_slice(&recomputed); 534 rec[104..136].copy_from_slice(&commit); 535 rec[136..169].copy_from_slice(&p256_compressed_key(key)); 536 let sig = p256_sign_low_s(key, &verdict_message(&rec)); 537 rec[VERDICT_SIGNED_LEN..].copy_from_slice(&sig); 538 Ok(rec) 539 } 540 541 /// Check a countersignature against the receipt it names and the pinned 542 /// verifier key. 543 pub fn check_countersign( 544 rec: &[u8], 545 receipt: &[u8], 546 pinned_verifier: &[u8; 33], 547 ) -> Result<(), An0Refusal> { 548 guard( 549 rec.len() == VERDICT_LEN && rec[..4] == VERDICT_MAGIC, 550 An0Refusal::BadBundle, 551 )?; 552 guard( 553 rec[4] == PROFILE_VERSION && rec[5..8] == [0; 3] && rec[169..172] == [0; 3], 554 An0Refusal::BadBundle, 555 )?; 556 guard(rec[8..40] == sha(&[receipt]), An0Refusal::BadCountersign)?; 557 guard( 558 rec[136..169] == pinned_verifier[..], 559 An0Refusal::BadCountersign, 560 )?; 561 let mut sig = [0u8; 64]; 562 sig.copy_from_slice(&rec[VERDICT_SIGNED_LEN..]); 563 guard( 564 p256_verify_low_s(pinned_verifier, &verdict_message(rec), &sig).is_ok(), 565 An0Refusal::BadCountersign, 566 )?; // AN0-GUARD countersign-sig 567 let r = decode_receipt(receipt)?; 568 guard( 569 rec[40..72] == r.dag_digest && rec[72..104] == r.output_digest, 570 An0Refusal::BadCountersign, 571 )?; 572 let commit = verdict_commitment(&r.dag_digest, &r.job_id, &r.output_digest); 573 guard( 574 rec[104..136] == commit && r.verifier_verdict == commit, 575 An0Refusal::BadCountersign, 576 )?; // AN0-GUARD countersign-commitment 577 Ok(()) 578 } 579 580 /// Lowercase hex. 581 pub fn to_hex(b: &[u8]) -> String { 582 const H: &[u8; 16] = b"`0123456789abcdef`"; 583 let mut s = String::with_capacity(b.len() * 2); 584 for &x in b { 585 s.push(H[(x >> 4) as usize] as char); 586 s.push(H[(x & 15) as usize] as char); 587 } 588 s 589 } 590 591 /// Parse exactly `N` bytes of hex (surrounding whitespace ignored). 592 pub fn from_hex(s: &str) -> Option<[u8; N]> { 593 let s = s.trim().as_bytes(); 594 if s.len() != 2 * N { 595 return None; 596 } 597 let nib = |c: u8| match c { 598 b'0'..=b'9' => Some(c - b'0'), 599 b'a'..=b'f' => Some(c - b'a' + 10), 600 b'A'..=b'F' => Some(c - b'A' + 10), 601 _ => None, 602 }; 603 let mut out = [0u8; N]; 604 for i in 0..N { 605 out[i] = nib(s[2 * i])? << 4 | nib(s[2 * i + 1])?; 606 } 607 Some(out) 608 } 609 610 /// A P-256 signing key from 64 hex characters (a test identity file). 611 pub fn signing_key_from_hex(s: &str) -> Option { 612 SigningKey::from_slice(&from_hex::<32>(s)?).ok() 613 } 614 615 /// The SEC1 compressed public key of `key`. 616 pub fn public_key(key: &SigningKey) -> [u8; 33] { 617 p256_compressed_key(key) 618 } 619 620 #[cfg(test)] 621 mod tests { 622 use super::*; 623 624 const NOW: u64 = 1_800_000_000; 625 626 fn key(b: u8) -> SigningKey { 627 SigningKey::from_slice(&[b; 32]).unwrap() 628 } 629 630 /// Fresh OS-random nonce per fixture; no test depends on its value. 631 fn nonce() -> [u8; 16] { 632 let mut n = [0u8; 16]; 633 getrandom::fill(&mut n).expect("OS randomness"); 634 n 635 } 636 637 fn job() -> MatmulU32 { 638 MatmulU32 { 639 m: 7, 640 k: 5, 641 n: 3, 642 seed: 0xA1E7_0001, 643 } 644 } 645 646 fn bundle_with(payload: &[u8], op: u8, sub: &SigningKey) -> Vec { 647 let doc = build_document(payload, op, nonce(), &public_key(sub), NOW); 648 seal_bundle(&doc, payload, sub) 649 } 650 651 fn bundle() -> Vec { 652 bundle_with(&job().encode(), compute_op::MATMUL, &key(1)) 653 } 654 655 fn admitted() -> Admitted { 656 admit_bundle(&bundle(), &public_key(&key(1)), NOW).unwrap() 657 } 658 659 fn receipt_for(a: &Admitted, out: [u8; 32], exec: &SigningKey) -> [u8; RECEIPT_LEN] { 660 executor_receipt(a, out, 5, [0x5C; 32], [0x9F; 32], exec) 661 } 662 663 #[test] 664 fn payload_round_trip_and_core_662_layout() { 665 let p = job().encode(); 666 assert_eq!(p.len(), 15); 667 assert_eq!(p[0], 1); 668 assert_eq!(&p[1..7], &[0, 7, 0, 5, 0, 3]); 669 assert_eq!(MatmulU32::decode(&p).unwrap(), job()); 670 } 671 672 #[test] 673 fn kernel_matches_naive_ijk() { 674 for j in [ 675 MatmulU32 { 676 m: 1, 677 k: 1, 678 n: 1, 679 seed: 0, 680 }, 681 job(), 682 MatmulU32 { 683 m: 16, 684 k: 9, 685 n: 31, 686 seed: u64::MAX, 687 }, 688 ] { 689 let (m, k, n) = (j.m as usize, j.k as usize, j.n as usize); 690 let mut s = j.seed; 691 let a: Vec = (0..m * k).map(|_| splitmix64(&mut s) as u32).collect(); 692 let b: Vec = (0..k * n).map(|_| splitmix64(&mut s) as u32).collect(); 693 let mut h = Sha256::new(); 694 h.update(MATMUL_DOMAIN); 695 h.update(j.m.to_be_bytes()); 696 h.update(j.k.to_be_bytes()); 697 h.update(j.n.to_be_bytes()); 698 h.update(j.seed.to_be_bytes()); 699 for i in 0..m { 700 for q in 0..n { 701 let mut acc = 0u32; 702 for p in 0..k { 703 acc = acc.wrapping_add(a[i * k + p].wrapping_mul(b[p * n + q])); 704 } 705 h.update(acc.to_be_bytes()); 706 } 707 } 708 let want: [u8; 32] = h.finalize().into(); 709 assert_eq!(matmul_u32_digest(&j), want); 710 } 711 } 712 713 #[test] 714 fn built_document_is_valid_mjb1() { 715 let doc = build_document( 716 &job().encode(), 717 compute_op::MATMUL, 718 nonce(), 719 &public_key(&key(1)), 720 NOW, 721 ); 722 assert!(crate::verdict_line(&doc).starts_with("ok nodes=1 ")); 723 } 724 725 #[test] 726 fn admits_the_allowlisted_job() { 727 let a = admitted(); 728 assert_eq!(a.job, job()); 729 assert_eq!(a.payload, job().encode()); 730 } 731 732 #[test] 733 fn refuses_unpinned_submitter() { 734 let b = bundle_with(&job().encode(), compute_op::MATMUL, &key(2)); 735 assert_eq!( 736 admit_bundle(&b, &public_key(&key(1)), NOW).unwrap_err(), 737 An0Refusal::BadSubmitter 738 ); 739 } 740 741 #[test] 742 fn refuses_bad_submitter_signature() { 743 let mut b = bundle(); 744 b[50] ^= 1; 745 assert_eq!( 746 admit_bundle(&b, &public_key(&key(1)), NOW).unwrap_err(), 747 An0Refusal::BadSubmitter 748 ); 749 } 750 751 #[test] 752 fn refuses_a_changed_document() { 753 let mut b = bundle(); 754 let last = b.len() - 1; 755 b[last] ^= 1; 756 assert_eq!( 757 admit_bundle(&b, &public_key(&key(1)), NOW).unwrap_err(), 758 An0Refusal::BadSubmitter 759 ); 760 } 761 762 #[test] 763 fn refuses_op_not_on_allowlist() { 764 let b = bundle_with(&job().encode(), compute_op::COMPILE, &key(1)); 765 assert_eq!( 766 admit_bundle(&b, &public_key(&key(1)), NOW).unwrap_err(), 767 An0Refusal::NotAllowlisted 768 ); 769 } 770 771 #[test] 772 fn refuses_payload_kind_not_on_allowlist() { 773 let mut p = job().encode(); 774 p[0] = 2; 775 let b = bundle_with(&p, compute_op::MATMUL, &key(1)); 776 assert_eq!( 777 admit_bundle(&b, &public_key(&key(1)), NOW).unwrap_err(), 778 An0Refusal::NotAllowlisted 779 ); 780 } 781 782 #[test] 783 fn refuses_over_budget_dimensions() { 784 let big = MatmulU32 { 785 m: 512, 786 k: 4, 787 n: 4, 788 seed: 1, 789 }; 790 let b = bundle_with(&big.encode(), compute_op::MATMUL, &key(1)); 791 assert_eq!( 792 admit_bundle(&b, &public_key(&key(1)), NOW).unwrap_err(), 793 An0Refusal::OverBudget 794 ); 795 } 796 797 #[test] 798 fn refuses_caps_below_the_job() { 799 let p = job().encode(); 800 let sub = key(1); 801 let doc = build_document(&p, compute_op::MATMUL, nonce(), &public_key(&sub), NOW); 802 let mut d = decode(&doc).unwrap(); 803 d.nodes[0].work = 1; 804 let b = seal_bundle(&encode(&d).unwrap(), &p, &sub); 805 assert_eq!( 806 admit_bundle(&b, &public_key(&sub), NOW).unwrap_err(), 807 An0Refusal::OverBudget 808 ); 809 } 810 811 #[test] 812 fn refuses_a_payload_the_operand_does_not_name() { 813 let sub = key(1); 814 let doc = build_document( 815 &job().encode(), 816 compute_op::MATMUL, 817 nonce(), 818 &public_key(&sub), 819 NOW, 820 ); 821 let other = MatmulU32 { seed: 2, ..job() }.encode(); 822 let b = seal_bundle(&doc, &other, &sub); 823 assert_eq!( 824 admit_bundle(&b, &public_key(&sub), NOW).unwrap_err(), 825 An0Refusal::PayloadMismatch 826 ); 827 } 828 829 #[test] 830 fn refuses_an_expired_document() { 831 assert_eq!( 832 admit_bundle(&bundle(), &public_key(&key(1)), NOW + DOCUMENT_TTL + 1).unwrap_err(), 833 An0Refusal::Mjb(Refusal::BadExpiry) 834 ); 835 } 836 837 #[test] 838 fn admission_checks_fuel_and_node_expiry_boundaries() { 839 let original = admitted(); 840 for (fuel, expiry, expected) in [ 841 (job().work() - 1, NOW, Some(An0Refusal::OverBudget)), 842 ( 843 job().work(), 844 NOW - 1, 845 Some(An0Refusal::Mjb(Refusal::BadExpiry)), 846 ), 847 (job().work(), NOW, None), 848 ] { 849 let mut dag = original.dag.clone(); 850 dag.nodes[0].fuel = fuel; 851 dag.nodes[0].expires_at = expiry; 852 let document = encode(&dag).unwrap(); 853 let bundle = seal_bundle(&document, &original.payload, &key(1)); 854 let result = admit_bundle(&bundle, &public_key(&key(1)), NOW); 855 match expected { 856 Some(refusal) => assert_eq!(result.unwrap_err(), refusal), 857 None => { 858 let accepted = result.unwrap(); 859 let output = matmul_u32_digest(&accepted.job); 860 let receipt = receipt_for(&accepted, output, &key(3)); 861 check_receipt(&accepted.document, &receipt, public_key(&key(3)), NOW).unwrap(); 862 let verdict = countersign(&receipt, output, &key(4)).unwrap(); 863 check_countersign(&verdict, &receipt, &public_key(&key(4))).unwrap(); 864 } 865 } 866 } 867 } 868 869 #[test] 870 fn refuses_validly_signed_inconsistent_countersign_commitments() { 871 let admitted = admitted(); 872 let output = matmul_u32_digest(&admitted.job); 873 let receipt = receipt_for(&admitted, output, &key(3)); 874 let honest = countersign(&receipt, output, &key(4)).unwrap(); 875 check_countersign(&honest, &receipt, &public_key(&key(4))).unwrap(); 876 877 let mut verdict = honest; 878 verdict[104..136].fill(0xEE); 879 let signature = p256_sign_low_s(&key(4), &verdict_message(&verdict)); 880 verdict[VERDICT_SIGNED_LEN..].copy_from_slice(&signature); 881 assert_eq!( 882 check_countersign(&verdict, &receipt, &public_key(&key(4))), 883 Err(An0Refusal::BadCountersign) 884 ); 885 886 // Even matching receipt/verdict fields cannot replace recomputation. 887 let mut decoded = decode_receipt(&receipt).unwrap(); 888 decoded.verifier_verdict = [0xEE; 32]; 889 sign_receipt(&mut decoded, &key(3)); 890 let receipt = encode_receipt(&decoded); 891 verdict[8..40].copy_from_slice(&sha(&[&receipt])); 892 let signature = p256_sign_low_s(&key(4), &verdict_message(&verdict)); 893 verdict[VERDICT_SIGNED_LEN..].copy_from_slice(&signature); 894 assert_eq!( 895 check_countersign(&verdict, &receipt, &public_key(&key(4))), 896 Err(An0Refusal::BadCountersign) 897 ); 898 899 // A correct AN0V commitment still cannot bless a wrong MJR1 field. 900 verdict[104..136].copy_from_slice(&honest[104..136]); 901 let signature = p256_sign_low_s(&key(4), &verdict_message(&verdict)); 902 verdict[VERDICT_SIGNED_LEN..].copy_from_slice(&signature); 903 assert_eq!( 904 check_countersign(&verdict, &receipt, &public_key(&key(4))), 905 Err(An0Refusal::BadCountersign) 906 ); 907 } 908 909 #[test] 910 fn full_path_verifies_and_countersigns() { 911 let a = admitted(); 912 let out = matmul_u32_digest(&a.job); 913 let r = receipt_for(&a, out, &key(3)); 914 let got = check_receipt(&a.document, &r, public_key(&key(3)), NOW).unwrap(); 915 assert_eq!(got.output_digest, out); 916 let rec = countersign(&r, out, &key(4)).unwrap(); 917 check_countersign(&rec, &r, &public_key(&key(4))).unwrap(); 918 } 919 920 #[test] 921 fn refuses_receipt_from_unpinned_executor() { 922 let a = admitted(); 923 let r = receipt_for(&a, matmul_u32_digest(&a.job), &key(5)); 924 assert_eq!( 925 check_receipt(&a.document, &r, public_key(&key(3)), NOW).unwrap_err(), 926 An0Refusal::Mjb(Refusal::ForgedReceipt) 927 ); 928 } 929 930 #[test] 931 fn refuses_receipt_changed_after_signing() { 932 let a = admitted(); 933 let mut r = receipt_for(&a, matmul_u32_digest(&a.job), &key(3)); 934 r[150] ^= 1; 935 assert_eq!( 936 check_receipt(&a.document, &r, public_key(&key(3)), NOW).unwrap_err(), 937 An0Refusal::Mjb(Refusal::ForgedReceipt) 938 ); 939 } 940 941 #[test] 942 fn refuses_signed_wrong_output() { 943 let a = admitted(); 944 let good = matmul_u32_digest(&a.job); 945 let mut bad = good; 946 bad[0] ^= 1; 947 let r = receipt_for(&a, bad, &key(3)); 948 check_receipt(&a.document, &r, public_key(&key(3)), NOW).unwrap(); 949 assert_eq!( 950 countersign(&r, good, &key(4)).unwrap_err(), 951 An0Refusal::RecomputeMismatch 952 ); 953 } 954 955 #[test] 956 fn refuses_wrong_verdict_commitment() { 957 let a = admitted(); 958 let out = matmul_u32_digest(&a.job); 959 let mut r = decode_receipt(&receipt_for(&a, out, &key(3))).unwrap(); 960 r.verifier_verdict = [0x77; 32]; 961 sign_receipt(&mut r, &key(3)); 962 let bytes = encode_receipt(&r); 963 assert_eq!( 964 countersign(&bytes, out, &key(4)).unwrap_err(), 965 An0Refusal::VerdictMismatch 966 ); 967 } 968 969 #[test] 970 fn refuses_countersign_from_unpinned_verifier() { 971 let a = admitted(); 972 let out = matmul_u32_digest(&a.job); 973 let r = receipt_for(&a, out, &key(3)); 974 let rec = countersign(&r, out, &key(6)).unwrap(); 975 assert_eq!( 976 check_countersign(&rec, &r, &public_key(&key(4))).unwrap_err(), 977 An0Refusal::BadCountersign 978 ); 979 } 980 981 #[test] 982 fn refuses_countersign_with_forged_signature() { 983 let a = admitted(); 984 let out = matmul_u32_digest(&a.job); 985 let r = receipt_for(&a, out, &key(3)); 986 let mut rec = countersign(&r, out, &key(4)).unwrap(); 987 rec[VERDICT_SIGNED_LEN + 7] ^= 1; 988 assert_eq!( 989 check_countersign(&rec, &r, &public_key(&key(4))).unwrap_err(), 990 An0Refusal::BadCountersign 991 ); 992 } 993 994 #[test] 995 fn receipt_round_trips_through_the_ledger_once() { 996 let a = admitted(); 997 let r = receipt_for(&a, matmul_u32_digest(&a.job), &key(3)); 998 let mut run = DagRun::admit(&a.document, vec![public_key(&key(3))], NOW).unwrap(); 999 assert_eq!(run.apply(&r).unwrap(), Applied::New); 1000 assert_eq!(run.apply(&r).unwrap(), Applied::Replay); 1001 } 1002 }