aien-protocols-mv
Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem
Brought by drakestapleton
aien-protocols-mv / crates / aien-microjob / src / lib.rs
| 1 | //! MJB1, the typed bounded microjob DAG, and MJR1, its receipt. |
| 2 | //! |
| 3 | //! Spec: `specs/microjob/SPEC.md` (Draft v0.1, contract 0.1.0, wire version |
| 4 | //! 1). The C reference checker is `specs/microjob/tools/mjb_verify.c`; this |
| 5 | //! crate gives the same verdict on the same document bytes (the test in |
| 6 | //! `tests/vectors.rs` walks the shared vectors). |
| 7 | //! |
| 8 | //! A valid document is a proposal, not an authorization, and a node is not a |
| 9 | //! receipt. [`DagRun`] is the receipt ledger of section 5: it derives node |
| 10 | //! state from accepted bytes and chooses nothing (it is not a scheduler). |
| 11 | #![forbid(unsafe_code)] |
| 12 | |
| 13 | pub mod aienet0; |
| 14 | |
| 15 | use aien_provenance::{p256_compressed_key, p256_sign_low_s, p256_verify_low_s}; |
| 16 | use p256::ecdsa::SigningKey; |
| 17 | use sha2::{Digest, Sha256}; |
| 18 | |
| 19 | /// Bytes in the document header. |
| 20 | pub const HEADER_LEN: usize = 192; |
| 21 | /// Bytes in one node record. |
| 22 | pub const NODE_LEN: usize = 448; |
| 23 | /// Most nodes in one document. |
| 24 | pub const MAX_NODES: usize = 64; |
| 25 | /// Dependency slots per node. |
| 26 | pub const MAX_DEPS: usize = 8; |
| 27 | /// Operand slots per node. |
| 28 | pub const MAX_OPERANDS: usize = 4; |
| 29 | /// Largest document. |
| 30 | pub const MAX_DOCUMENT: usize = HEADER_LEN + MAX_NODES * NODE_LEN; |
| 31 | /// The four bytes that open a document. |
| 32 | pub const MAGIC: [u8; 4] = *b"MJB1"; |
| 33 | /// The four bytes that open a receipt. |
| 34 | pub const RECEIPT_MAGIC: [u8; 4] = *b"MJR1"; |
| 35 | /// The only wire version. |
| 36 | pub const VERSION: u8 = 1; |
| 37 | /// Bytes in one receipt. |
| 38 | pub const RECEIPT_LEN: usize = 404; |
| 39 | /// Bytes of a receipt covered by its signature and its digest. |
| 40 | pub const RECEIPT_SIGNED_LEN: usize = 340; |
| 41 | |
| 42 | /// Node `kind` values. |
| 43 | pub mod kind { |
| 44 | pub const COMPUTE: u8 = 1; |
| 45 | pub const NEURAL: u8 = 2; |
| 46 | } |
| 47 | /// COMPUTE `op` values. |
| 48 | pub mod compute_op { |
| 49 | pub const ARITH: u8 = 1; |
| 50 | pub const MATMUL: u8 = 2; |
| 51 | pub const REDUCE: u8 = 3; |
| 52 | pub const COMPARE: u8 = 4; |
| 53 | pub const COMPILE: u8 = 5; |
| 54 | pub const VERIFY: u8 = 6; |
| 55 | } |
| 56 | /// NEURAL `op` values. |
| 57 | pub mod neural_op { |
| 58 | pub const ROUTE: u8 = 1; |
| 59 | pub const EXTRACT: u8 = 2; |
| 60 | pub const PROPOSE: u8 = 3; |
| 61 | pub const SUMMARIZE: u8 = 4; |
| 62 | } |
| 63 | /// Token `profile` values (section 4.3). |
| 64 | pub mod profile { |
| 65 | pub const ZERO: u8 = 0; |
| 66 | pub const MINIMAL: u8 = 1; |
| 67 | pub const DEFAULT: u8 = 2; |
| 68 | pub const LARGE: u8 = 3; |
| 69 | pub const SPECIALIST: u8 = 4; |
| 70 | } |
| 71 | /// `effect_class` and `effect_ceiling` values (same as PST1). |
| 72 | pub mod effect { |
| 73 | pub const NONE: u8 = 0; |
| 74 | pub const COMPUTE: u8 = 1; |
| 75 | pub const EFFECT: u8 = 2; |
| 76 | } |
| 77 | /// `verifier_kind` values. |
| 78 | pub mod verifier { |
| 79 | pub const RECOMPUTE: u8 = 1; |
| 80 | pub const CHECKER: u8 = 2; |
| 81 | pub const JUDGE: u8 = 3; |
| 82 | } |
| 83 | /// `retry_class` values. |
| 84 | pub mod retry { |
| 85 | pub const NEVER: u8 = 1; |
| 86 | pub const IDEMPOTENT: u8 = 2; |
| 87 | pub const RECONCILE_FIRST: u8 = 3; |
| 88 | } |
| 89 | /// `cancel_mode` values. |
| 90 | pub mod cancel { |
| 91 | pub const DISCARD: u8 = 1; |
| 92 | pub const CHECKPOINT: u8 = 2; |
| 93 | } |
| 94 | /// Operand `kind` values. |
| 95 | pub mod operand { |
| 96 | pub const CORTEX_STATE: u8 = 1; |
| 97 | pub const WORLD_STATE: u8 = 2; |
| 98 | pub const CONTENT: u8 = 3; |
| 99 | pub const CAPSULE: u8 = 4; |
| 100 | pub const EXPERIENCE: u8 = 5; |
| 101 | } |
| 102 | /// Receipt `outcome` values. |
| 103 | pub mod outcome { |
| 104 | pub const COMPLETED: u8 = 1; |
| 105 | pub const REFUSED: u8 = 2; |
| 106 | pub const FAILED: u8 = 3; |
| 107 | pub const CANCELLED: u8 = 4; |
| 108 | pub const UNCERTAIN: u8 = 5; |
| 109 | } |
| 110 | |
| 111 | /// Input and output token caps of a profile, `None` for an unknown profile. |
| 112 | pub fn profile_caps(p: u8) -> Option<(u16, u16)> { |
| 113 | match p { |
| 114 | profile::ZERO => Some((0, 0)), |
| 115 | profile::MINIMAL => Some((64, 16)), |
| 116 | profile::DEFAULT => Some((128, 32)), |
| 117 | profile::LARGE => Some((256, 64)), |
| 118 | profile::SPECIALIST => Some((512, 128)), |
| 119 | _ => None, |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | /// A refusal code from SPEC.md section 6. |
| 124 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 125 | pub enum Refusal { |
| 126 | BadLength, |
| 127 | BadMagic, |
| 128 | Downgrade, |
| 129 | BadVersion, |
| 130 | BadCount, |
| 131 | ReservedNonzero, |
| 132 | BadEnum, |
| 133 | NoObjective, |
| 134 | NoTenant, |
| 135 | NoSubject, |
| 136 | NoApproval, |
| 137 | BadExpiry, |
| 138 | NoJob, |
| 139 | CrossTenant, |
| 140 | NoCapability, |
| 141 | UnauthorizedEffect, |
| 142 | NoVerifier, |
| 143 | Impure, |
| 144 | TokenProfile, |
| 145 | NeedsExpansion, |
| 146 | BadRetry, |
| 147 | ZeroCap, |
| 148 | MissingOperand, |
| 149 | DuplicateJob, |
| 150 | MissingDep, |
| 151 | StaleGeneration, |
| 152 | Cycle, |
| 153 | OverBudget, |
| 154 | BadReceipt, |
| 155 | ForgedReceipt, |
| 156 | WrongDag, |
| 157 | UnknownJob, |
| 158 | ModelMismatch, |
| 159 | ReceiptOverBudget, |
| 160 | DepNotDone, |
| 161 | BindingMismatch, |
| 162 | DoubleCommit, |
| 163 | Cancelled, |
| 164 | } |
| 165 | |
| 166 | impl Refusal { |
| 167 | /// The code name as written in SPEC.md and printed by the C checker. |
| 168 | pub fn name(self) -> &'static str { |
| 169 | match self { |
| 170 | Refusal::BadLength => "MJB_BAD_LENGTH", |
| 171 | Refusal::BadMagic => "MJB_BAD_MAGIC", |
| 172 | Refusal::Downgrade => "MJB_DOWNGRADE", |
| 173 | Refusal::BadVersion => "MJB_BAD_VERSION", |
| 174 | Refusal::BadCount => "MJB_BAD_COUNT", |
| 175 | Refusal::ReservedNonzero => "MJB_RESERVED_NONZERO", |
| 176 | Refusal::BadEnum => "MJB_BAD_ENUM", |
| 177 | Refusal::NoObjective => "MJB_NO_OBJECTIVE", |
| 178 | Refusal::NoTenant => "MJB_NO_TENANT", |
| 179 | Refusal::NoSubject => "MJB_NO_SUBJECT", |
| 180 | Refusal::NoApproval => "MJB_NO_APPROVAL", |
| 181 | Refusal::BadExpiry => "MJB_BAD_EXPIRY", |
| 182 | Refusal::NoJob => "MJB_NO_JOB", |
| 183 | Refusal::CrossTenant => "MJB_CROSS_TENANT", |
| 184 | Refusal::NoCapability => "MJB_NO_CAPABILITY", |
| 185 | Refusal::UnauthorizedEffect => "MJB_UNAUTHORIZED_EFFECT", |
| 186 | Refusal::NoVerifier => "MJB_NO_VERIFIER", |
| 187 | Refusal::Impure => "MJB_IMPURE", |
| 188 | Refusal::TokenProfile => "MJB_TOKEN_PROFILE", |
| 189 | Refusal::NeedsExpansion => "MJB_NEEDS_EXPANSION", |
| 190 | Refusal::BadRetry => "MJB_BAD_RETRY", |
| 191 | Refusal::ZeroCap => "MJB_ZERO_CAP", |
| 192 | Refusal::MissingOperand => "MJB_MISSING_OPERAND", |
| 193 | Refusal::DuplicateJob => "MJB_DUPLICATE_JOB", |
| 194 | Refusal::MissingDep => "MJB_MISSING_DEP", |
| 195 | Refusal::StaleGeneration => "MJB_STALE_GENERATION", |
| 196 | Refusal::Cycle => "MJB_CYCLE", |
| 197 | Refusal::OverBudget => "MJB_OVER_BUDGET", |
| 198 | Refusal::BadReceipt => "MJB_BAD_RECEIPT", |
| 199 | Refusal::ForgedReceipt => "MJB_FORGED_RECEIPT", |
| 200 | Refusal::WrongDag => "MJB_WRONG_DAG", |
| 201 | Refusal::UnknownJob => "MJB_UNKNOWN_JOB", |
| 202 | Refusal::ModelMismatch => "MJB_MODEL_MISMATCH", |
| 203 | Refusal::ReceiptOverBudget => "MJB_RECEIPT_OVER_BUDGET", |
| 204 | Refusal::DepNotDone => "MJB_DEP_NOT_DONE", |
| 205 | Refusal::BindingMismatch => "MJB_BINDING_MISMATCH", |
| 206 | Refusal::DoubleCommit => "MJB_DOUBLE_COMMIT", |
| 207 | Refusal::Cancelled => "MJB_CANCELLED", |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | /// The document header (section 4.1). |
| 213 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 214 | pub struct Header { |
| 215 | pub effect_ceiling: u8, |
| 216 | pub objective_id: [u8; 32], |
| 217 | pub tenant_id: [u8; 32], |
| 218 | pub subject_id: [u8; 32], |
| 219 | pub approval_ref: [u8; 32], |
| 220 | pub incarnation: u32, |
| 221 | pub expires_at: u64, |
| 222 | pub budget_time_ms: u64, |
| 223 | pub budget_fuel: u64, |
| 224 | pub budget_memory: u64, |
| 225 | pub budget_work: u64, |
| 226 | pub budget_input_tokens: u32, |
| 227 | pub budget_output_tokens: u32, |
| 228 | } |
| 229 | |
| 230 | /// One dependency slot: a node of the same document and the generation of |
| 231 | /// that node this node was planned against. |
| 232 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 233 | pub struct Dep { |
| 234 | pub index: u16, |
| 235 | pub generation: u32, |
| 236 | } |
| 237 | |
| 238 | /// One typed operand reference. |
| 239 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 240 | pub struct Operand { |
| 241 | pub kind: u8, |
| 242 | pub generation: u32, |
| 243 | pub digest: [u8; 32], |
| 244 | } |
| 245 | |
| 246 | /// One node record (section 4.2). `deps` and `operands` hold the used slots. |
| 247 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 248 | pub struct Node { |
| 249 | pub job_id: [u8; 16], |
| 250 | pub idempotence_key: [u8; 16], |
| 251 | pub generation: u32, |
| 252 | pub kind: u8, |
| 253 | pub op: u8, |
| 254 | pub profile: u8, |
| 255 | pub effect_class: u8, |
| 256 | pub input_tokens: u16, |
| 257 | pub output_tokens: u16, |
| 258 | pub required_input_tokens: u16, |
| 259 | pub required_output_tokens: u16, |
| 260 | pub verifier_kind: u8, |
| 261 | pub retry_class: u8, |
| 262 | pub max_attempts: u8, |
| 263 | pub cancel_mode: u8, |
| 264 | pub precision: u8, |
| 265 | pub substrate_mask: u8, |
| 266 | pub result_type: u8, |
| 267 | pub result_rank: u8, |
| 268 | pub pure: bool, |
| 269 | pub time_ms: u32, |
| 270 | pub fuel: u64, |
| 271 | pub memory: u64, |
| 272 | pub work: u64, |
| 273 | pub expires_at: u64, |
| 274 | pub result_dims: [u32; 4], |
| 275 | pub capability_ref: [u8; 32], |
| 276 | pub tenant_id: [u8; 32], |
| 277 | pub model_ref: [u8; 32], |
| 278 | pub verifier_ref: [u8; 32], |
| 279 | pub deps: Vec<Dep>, |
| 280 | pub operands: Vec<Operand>, |
| 281 | } |
| 282 | |
| 283 | /// One accepted document. |
| 284 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 285 | pub struct Dag { |
| 286 | pub header: Header, |
| 287 | pub nodes: Vec<Node>, |
| 288 | } |
| 289 | |
| 290 | /// Why [`encode`] could not write a document. |
| 291 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 292 | pub enum EncodeError { |
| 293 | TooManyNodes, |
| 294 | TooManyDeps, |
| 295 | TooManyOperands, |
| 296 | } |
| 297 | |
| 298 | fn u16_at(b: &[u8], at: usize) -> u16 { |
| 299 | u16::from_be_bytes([b[at], b[at + 1]]) |
| 300 | } |
| 301 | fn u32_at(b: &[u8], at: usize) -> u32 { |
| 302 | u32::from_be_bytes(arr(b, at)) |
| 303 | } |
| 304 | fn u64_at(b: &[u8], at: usize) -> u64 { |
| 305 | u64::from_be_bytes(arr(b, at)) |
| 306 | } |
| 307 | fn arr<const N: usize>(b: &[u8], at: usize) -> [u8; N] { |
| 308 | let mut out = [0u8; N]; |
| 309 | out.copy_from_slice(&b[at..at + N]); |
| 310 | out |
| 311 | } |
| 312 | fn all_zero(b: &[u8]) -> bool { |
| 313 | b.iter().all(|&x| x == 0) |
| 314 | } |
| 315 | |
| 316 | const H_MAGIC: usize = 0; |
| 317 | const H_VERSION: usize = 4; |
| 318 | const H_CEILING: usize = 5; |
| 319 | const H_COUNT: usize = 6; |
| 320 | const H_OBJECTIVE: usize = 8; |
| 321 | const H_TENANT: usize = 40; |
| 322 | const H_SUBJECT: usize = 72; |
| 323 | const H_APPROVAL: usize = 104; |
| 324 | const H_INCARNATION: usize = 136; |
| 325 | const H_RES0: usize = 140; |
| 326 | const H_EXPIRES: usize = 144; |
| 327 | const H_B_TIME: usize = 152; |
| 328 | const H_B_FUEL: usize = 160; |
| 329 | const H_B_MEMORY: usize = 168; |
| 330 | const H_B_WORK: usize = 176; |
| 331 | const H_B_IN: usize = 184; |
| 332 | const H_B_OUT: usize = 188; |
| 333 | |
| 334 | const N_JOB: usize = 0; |
| 335 | const N_IDEM: usize = 16; |
| 336 | const N_GEN: usize = 32; |
| 337 | const N_KIND: usize = 36; |
| 338 | const N_OP: usize = 37; |
| 339 | const N_PROFILE: usize = 38; |
| 340 | const N_EFFECT: usize = 39; |
| 341 | const N_IN: usize = 40; |
| 342 | const N_OUT: usize = 42; |
| 343 | const N_REQ_IN: usize = 44; |
| 344 | const N_REQ_OUT: usize = 46; |
| 345 | const N_VERIFIER: usize = 48; |
| 346 | const N_RETRY: usize = 49; |
| 347 | const N_ATTEMPTS: usize = 50; |
| 348 | const N_CANCEL: usize = 51; |
| 349 | const N_PRECISION: usize = 52; |
| 350 | const N_SUBSTRATE: usize = 53; |
| 351 | const N_DEPS_N: usize = 54; |
| 352 | const N_OPS_N: usize = 55; |
| 353 | const N_RTYPE: usize = 56; |
| 354 | const N_RANK: usize = 57; |
| 355 | const N_PURE: usize = 58; |
| 356 | const N_RES1: usize = 59; |
| 357 | const N_TIME: usize = 60; |
| 358 | const N_FUEL: usize = 64; |
| 359 | const N_MEMORY: usize = 72; |
| 360 | const N_WORK: usize = 80; |
| 361 | const N_EXPIRES: usize = 88; |
| 362 | const N_DIMS: usize = 96; |
| 363 | const N_CAP: usize = 112; |
| 364 | const N_TENANT: usize = 144; |
| 365 | const N_MODEL: usize = 176; |
| 366 | const N_VREF: usize = 208; |
| 367 | const N_DEPS: usize = 240; |
| 368 | const DEP_LEN: usize = 6; |
| 369 | const N_OPERANDS: usize = 288; |
| 370 | const OPERAND_LEN: usize = 40; |
| 371 | |
| 372 | /// Static per-node checks (section 4.4 rules 10 to 23) on the raw record. |
| 373 | fn check_node(n: &[u8], h: &[u8]) -> Result<(), Refusal> { |
| 374 | // Rule 10. |
| 375 | if all_zero(&n[N_JOB..N_JOB + 16]) || all_zero(&n[N_IDEM..N_IDEM + 16]) || u32_at(n, N_GEN) == 0 |
| 376 | { |
| 377 | return Err(Refusal::NoJob); |
| 378 | } |
| 379 | let dep_count = n[N_DEPS_N] as usize; |
| 380 | let op_count = n[N_OPS_N] as usize; |
| 381 | let rank = n[N_RANK] as usize; |
| 382 | // Rule 11. |
| 383 | let mut reserved_bad = n[N_RES1] != 0; |
| 384 | for s in dep_count.min(MAX_DEPS)..MAX_DEPS { |
| 385 | let at = N_DEPS + s * DEP_LEN; |
| 386 | reserved_bad |= !all_zero(&n[at..at + DEP_LEN]); |
| 387 | } |
| 388 | for s in 0..MAX_OPERANDS { |
| 389 | let at = N_OPERANDS + s * OPERAND_LEN; |
| 390 | if s < op_count { |
| 391 | reserved_bad |= !all_zero(&n[at + 1..at + 4]); |
| 392 | } else { |
| 393 | reserved_bad |= !all_zero(&n[at..at + OPERAND_LEN]); |
| 394 | } |
| 395 | } |
| 396 | for d in rank.min(4)..4 { |
| 397 | reserved_bad |= u32_at(n, N_DIMS + 4 * d) != 0; |
| 398 | } |
| 399 | if reserved_bad { |
| 400 | return Err(Refusal::ReservedNonzero); |
| 401 | } |
| 402 | // Rule 12. |
| 403 | let k = n[N_KIND]; |
| 404 | let op = n[N_OP]; |
| 405 | let op_ok = match k { |
| 406 | kind::COMPUTE => (1..=6).contains(&op), |
| 407 | kind::NEURAL => (1..=4).contains(&op), |
| 408 | _ => false, |
| 409 | }; |
| 410 | let operand_kinds_ok = |
| 411 | (0..op_count.min(MAX_OPERANDS)).all(|s| (1..=5).contains(&n[N_OPERANDS + s * OPERAND_LEN])); |
| 412 | if !op_ok |
| 413 | || n[N_PROFILE] > profile::SPECIALIST |
| 414 | || n[N_EFFECT] > effect::EFFECT |
| 415 | || n[N_VERIFIER] > verifier::JUDGE |
| 416 | || !(1..=3).contains(&n[N_RETRY]) |
| 417 | || !(1..=8).contains(&n[N_ATTEMPTS]) |
| 418 | || !(1..=2).contains(&n[N_CANCEL]) |
| 419 | || n[N_PRECISION] > 6 |
| 420 | || n[N_SUBSTRATE] == 0 |
| 421 | || n[N_SUBSTRATE] & 0xF8 != 0 |
| 422 | || dep_count > MAX_DEPS |
| 423 | || op_count > MAX_OPERANDS |
| 424 | || !(1..=7).contains(&n[N_RTYPE]) |
| 425 | || rank > 4 |
| 426 | || n[N_PURE] > 1 |
| 427 | || !operand_kinds_ok |
| 428 | { |
| 429 | return Err(Refusal::BadEnum); |
| 430 | } |
| 431 | // Rule 13. |
| 432 | if n[N_TENANT..N_TENANT + 32] != h[H_TENANT..H_TENANT + 32] { |
| 433 | return Err(Refusal::CrossTenant); |
| 434 | } |
| 435 | // Rule 14. |
| 436 | if all_zero(&n[N_CAP..N_CAP + 32]) { |
| 437 | return Err(Refusal::NoCapability); |
| 438 | } |
| 439 | // Rule 15. |
| 440 | if n[N_EFFECT] > h[H_CEILING] { |
| 441 | return Err(Refusal::UnauthorizedEffect); |
| 442 | } |
| 443 | // Rule 16. |
| 444 | let vk = n[N_VERIFIER]; |
| 445 | let vref_zero = all_zero(&n[N_VREF..N_VREF + 32]); |
| 446 | let pure = n[N_PURE] == 1; |
| 447 | if vk == 0 |
| 448 | || (vk != verifier::RECOMPUTE && vref_zero) |
| 449 | || (vk == verifier::RECOMPUTE && (!vref_zero || !pure)) |
| 450 | { |
| 451 | return Err(Refusal::NoVerifier); |
| 452 | } |
| 453 | // Rule 17. |
| 454 | if pure && (k == kind::NEURAL || n[N_EFFECT] == effect::EFFECT) { |
| 455 | return Err(Refusal::Impure); |
| 456 | } |
| 457 | // Rule 18. |
| 458 | let (cap_in, cap_out) = profile_caps(n[N_PROFILE]).unwrap_or((0, 0)); |
| 459 | let tin = u16_at(n, N_IN); |
| 460 | let tout = u16_at(n, N_OUT); |
| 461 | let rin = u16_at(n, N_REQ_IN); |
| 462 | let rout = u16_at(n, N_REQ_OUT); |
| 463 | let model_zero = all_zero(&n[N_MODEL..N_MODEL + 32]); |
| 464 | let profile_bad = if k == kind::COMPUTE { |
| 465 | n[N_PROFILE] != profile::ZERO |
| 466 | || tin != 0 |
| 467 | || tout != 0 |
| 468 | || rin != 0 |
| 469 | || rout != 0 |
| 470 | || !model_zero |
| 471 | } else { |
| 472 | n[N_PROFILE] == profile::ZERO |
| 473 | || tin == 0 |
| 474 | || tout == 0 |
| 475 | || tin > cap_in |
| 476 | || tout > cap_out |
| 477 | || model_zero |
| 478 | }; |
| 479 | if profile_bad { |
| 480 | return Err(Refusal::TokenProfile); |
| 481 | } |
| 482 | // Rule 19. |
| 483 | if rin > tin || rout > tout { |
| 484 | return Err(Refusal::NeedsExpansion); |
| 485 | } |
| 486 | // Rule 20. |
| 487 | if (n[N_RETRY] == retry::NEVER && n[N_ATTEMPTS] > 1) |
| 488 | || (n[N_EFFECT] == effect::EFFECT && n[N_RETRY] == retry::IDEMPOTENT) |
| 489 | { |
| 490 | return Err(Refusal::BadRetry); |
| 491 | } |
| 492 | // Rule 21. |
| 493 | if u32_at(n, N_TIME) == 0 |
| 494 | || u64_at(n, N_FUEL) == 0 |
| 495 | || u64_at(n, N_MEMORY) == 0 |
| 496 | || u64_at(n, N_WORK) == 0 |
| 497 | { |
| 498 | return Err(Refusal::ZeroCap); |
| 499 | } |
| 500 | // Rule 22. |
| 501 | let exp = u64_at(n, N_EXPIRES); |
| 502 | if exp == 0 || exp > u64_at(h, H_EXPIRES) { |
| 503 | return Err(Refusal::BadExpiry); |
| 504 | } |
| 505 | // Rule 23. |
| 506 | for s in 0..op_count { |
| 507 | let at = N_OPERANDS + s * OPERAND_LEN; |
| 508 | if u32_at(n, at + 4) == 0 || all_zero(&n[at + 8..at + 40]) { |
| 509 | return Err(Refusal::MissingOperand); |
| 510 | } |
| 511 | } |
| 512 | Ok(()) |
| 513 | } |
| 514 | |
| 515 | fn parse_node(n: &[u8]) -> Node { |
| 516 | let deps = (0..n[N_DEPS_N] as usize) |
| 517 | .map(|s| { |
| 518 | let at = N_DEPS + s * DEP_LEN; |
| 519 | Dep { |
| 520 | index: u16_at(n, at), |
| 521 | generation: u32_at(n, at + 2), |
| 522 | } |
| 523 | }) |
| 524 | .collect(); |
| 525 | let operands = (0..n[N_OPS_N] as usize) |
| 526 | .map(|s| { |
| 527 | let at = N_OPERANDS + s * OPERAND_LEN; |
| 528 | Operand { |
| 529 | kind: n[at], |
| 530 | generation: u32_at(n, at + 4), |
| 531 | digest: arr(n, at + 8), |
| 532 | } |
| 533 | }) |
| 534 | .collect(); |
| 535 | Node { |
| 536 | job_id: arr(n, N_JOB), |
| 537 | idempotence_key: arr(n, N_IDEM), |
| 538 | generation: u32_at(n, N_GEN), |
| 539 | kind: n[N_KIND], |
| 540 | op: n[N_OP], |
| 541 | profile: n[N_PROFILE], |
| 542 | effect_class: n[N_EFFECT], |
| 543 | input_tokens: u16_at(n, N_IN), |
| 544 | output_tokens: u16_at(n, N_OUT), |
| 545 | required_input_tokens: u16_at(n, N_REQ_IN), |
| 546 | required_output_tokens: u16_at(n, N_REQ_OUT), |
| 547 | verifier_kind: n[N_VERIFIER], |
| 548 | retry_class: n[N_RETRY], |
| 549 | max_attempts: n[N_ATTEMPTS], |
| 550 | cancel_mode: n[N_CANCEL], |
| 551 | precision: n[N_PRECISION], |
| 552 | substrate_mask: n[N_SUBSTRATE], |
| 553 | result_type: n[N_RTYPE], |
| 554 | result_rank: n[N_RANK], |
| 555 | pure: n[N_PURE] == 1, |
| 556 | time_ms: u32_at(n, N_TIME), |
| 557 | fuel: u64_at(n, N_FUEL), |
| 558 | memory: u64_at(n, N_MEMORY), |
| 559 | work: u64_at(n, N_WORK), |
| 560 | expires_at: u64_at(n, N_EXPIRES), |
| 561 | result_dims: [ |
| 562 | u32_at(n, N_DIMS), |
| 563 | u32_at(n, N_DIMS + 4), |
| 564 | u32_at(n, N_DIMS + 8), |
| 565 | u32_at(n, N_DIMS + 12), |
| 566 | ], |
| 567 | capability_ref: arr(n, N_CAP), |
| 568 | tenant_id: arr(n, N_TENANT), |
| 569 | model_ref: arr(n, N_MODEL), |
| 570 | verifier_ref: arr(n, N_VREF), |
| 571 | deps, |
| 572 | operands, |
| 573 | } |
| 574 | } |
| 575 | |
| 576 | /// The canonical execution order: Kahn's algorithm taking the lowest-index |
| 577 | /// ready node first. `None` when the graph has a cycle. Dependency indexes |
| 578 | /// must already be in range. |
| 579 | pub fn canonical_order(nodes: &[Node]) -> Option<Vec<usize>> { |
| 580 | let n = nodes.len(); |
| 581 | let mut indeg: Vec<usize> = nodes.iter().map(|x| x.deps.len()).collect(); |
| 582 | let mut emitted = vec![false; n]; |
| 583 | let mut order = Vec::with_capacity(n); |
| 584 | while order.len() < n { |
| 585 | let next = (0..n).find(|&i| !emitted[i] && indeg[i] == 0)?; |
| 586 | emitted[next] = true; |
| 587 | order.push(next); |
| 588 | for (i, node) in nodes.iter().enumerate() { |
| 589 | for d in &node.deps { |
| 590 | if d.index as usize == next { |
| 591 | indeg[i] -= 1; |
| 592 | } |
| 593 | } |
| 594 | } |
| 595 | } |
| 596 | Some(order) |
| 597 | } |
| 598 | |
| 599 | /// Decode and check one document in the order of SPEC.md section 4.4, the |
| 600 | /// same order as the C checker, so the same bytes give the same code. |
| 601 | pub fn decode(b: &[u8]) -> Result<Dag, Refusal> { |
| 602 | if b.len() < HEADER_LEN { |
| 603 | return Err(Refusal::BadLength); |
| 604 | } |
| 605 | if b[H_MAGIC..H_MAGIC + 4] != MAGIC { |
| 606 | return Err(Refusal::BadMagic); |
| 607 | } |
| 608 | if b[H_VERSION] == 0 { |
| 609 | return Err(Refusal::Downgrade); |
| 610 | } |
| 611 | if b[H_VERSION] > VERSION { |
| 612 | return Err(Refusal::BadVersion); |
| 613 | } |
| 614 | let count = u16_at(b, H_COUNT) as usize; |
| 615 | if count == 0 || count > MAX_NODES { |
| 616 | return Err(Refusal::BadCount); |
| 617 | } |
| 618 | if b.len() != HEADER_LEN + count * NODE_LEN { |
| 619 | return Err(Refusal::BadLength); |
| 620 | } |
| 621 | if !all_zero(&b[H_RES0..H_RES0 + 4]) { |
| 622 | return Err(Refusal::ReservedNonzero); |
| 623 | } |
| 624 | if b[H_CEILING] > effect::EFFECT { |
| 625 | return Err(Refusal::BadEnum); |
| 626 | } |
| 627 | if all_zero(&b[H_OBJECTIVE..H_OBJECTIVE + 32]) { |
| 628 | return Err(Refusal::NoObjective); |
| 629 | } |
| 630 | if all_zero(&b[H_TENANT..H_TENANT + 32]) { |
| 631 | return Err(Refusal::NoTenant); |
| 632 | } |
| 633 | if all_zero(&b[H_SUBJECT..H_SUBJECT + 32]) { |
| 634 | return Err(Refusal::NoSubject); |
| 635 | } |
| 636 | if all_zero(&b[H_APPROVAL..H_APPROVAL + 32]) { |
| 637 | return Err(Refusal::NoApproval); |
| 638 | } |
| 639 | if u32_at(b, H_INCARNATION) == 0 { |
| 640 | return Err(Refusal::NoObjective); |
| 641 | } |
| 642 | let h = &b[..HEADER_LEN]; |
| 643 | let mut nodes = Vec::with_capacity(count); |
| 644 | for i in 0..count { |
| 645 | let rec = &b[HEADER_LEN + i * NODE_LEN..HEADER_LEN + (i + 1) * NODE_LEN]; |
| 646 | check_node(rec, h)?; |
| 647 | nodes.push(parse_node(rec)); |
| 648 | } |
| 649 | // Rule 24. |
| 650 | for i in 0..count { |
| 651 | for j in i + 1..count { |
| 652 | if nodes[i].job_id == nodes[j].job_id |
| 653 | || nodes[i].idempotence_key == nodes[j].idempotence_key |
| 654 | { |
| 655 | return Err(Refusal::DuplicateJob); |
| 656 | } |
| 657 | } |
| 658 | } |
| 659 | // Rule 25. |
| 660 | for (i, node) in nodes.iter().enumerate() { |
| 661 | if node |
| 662 | .deps |
| 663 | .iter() |
| 664 | .any(|d| d.index as usize == i || d.index as usize >= count) |
| 665 | { |
| 666 | return Err(Refusal::MissingDep); |
| 667 | } |
| 668 | } |
| 669 | // Rule 26. |
| 670 | for node in &nodes { |
| 671 | if node |
| 672 | .deps |
| 673 | .iter() |
| 674 | .any(|d| d.generation != nodes[d.index as usize].generation) |
| 675 | { |
| 676 | return Err(Refusal::StaleGeneration); |
| 677 | } |
| 678 | } |
| 679 | // Rule 27. |
| 680 | if canonical_order(&nodes).is_none() { |
| 681 | return Err(Refusal::Cycle); |
| 682 | } |
| 683 | // Rule 28. |
| 684 | let sum = |f: &dyn Fn(&Node) -> u128| nodes.iter().map(f).sum::<u128>(); |
| 685 | let header = Header { |
| 686 | effect_ceiling: b[H_CEILING], |
| 687 | objective_id: arr(b, H_OBJECTIVE), |
| 688 | tenant_id: arr(b, H_TENANT), |
| 689 | subject_id: arr(b, H_SUBJECT), |
| 690 | approval_ref: arr(b, H_APPROVAL), |
| 691 | incarnation: u32_at(b, H_INCARNATION), |
| 692 | expires_at: u64_at(b, H_EXPIRES), |
| 693 | budget_time_ms: u64_at(b, H_B_TIME), |
| 694 | budget_fuel: u64_at(b, H_B_FUEL), |
| 695 | budget_memory: u64_at(b, H_B_MEMORY), |
| 696 | budget_work: u64_at(b, H_B_WORK), |
| 697 | budget_input_tokens: u32_at(b, H_B_IN), |
| 698 | budget_output_tokens: u32_at(b, H_B_OUT), |
| 699 | }; |
| 700 | if sum(&|x| x.time_ms as u128) > header.budget_time_ms as u128 |
| 701 | || sum(&|x| x.fuel as u128) > header.budget_fuel as u128 |
| 702 | || sum(&|x| x.work as u128) > header.budget_work as u128 |
| 703 | || sum(&|x| x.input_tokens as u128) > header.budget_input_tokens as u128 |
| 704 | || sum(&|x| x.output_tokens as u128) > header.budget_output_tokens as u128 |
| 705 | || nodes.iter().any(|x| x.memory > header.budget_memory) |
| 706 | { |
| 707 | return Err(Refusal::OverBudget); |
| 708 | } |
| 709 | Ok(Dag { header, nodes }) |
| 710 | } |
| 711 | |
| 712 | /// Write one document. Fields are written exactly as given; nothing is |
| 713 | /// checked beyond the slot counts (use [`decode`] to check). |
| 714 | pub fn encode(d: &Dag) -> Result<Vec<u8>, EncodeError> { |
| 715 | if d.nodes.len() > MAX_NODES { |
| 716 | return Err(EncodeError::TooManyNodes); |
| 717 | } |
| 718 | let mut b = vec![0u8; HEADER_LEN + d.nodes.len() * NODE_LEN]; |
| 719 | let h = &d.header; |
| 720 | b[H_MAGIC..H_MAGIC + 4].copy_from_slice(&MAGIC); |
| 721 | b[H_VERSION] = VERSION; |
| 722 | b[H_CEILING] = h.effect_ceiling; |
| 723 | b[H_COUNT..H_COUNT + 2].copy_from_slice(&(d.nodes.len() as u16).to_be_bytes()); |
| 724 | b[H_OBJECTIVE..H_OBJECTIVE + 32].copy_from_slice(&h.objective_id); |
| 725 | b[H_TENANT..H_TENANT + 32].copy_from_slice(&h.tenant_id); |
| 726 | b[H_SUBJECT..H_SUBJECT + 32].copy_from_slice(&h.subject_id); |
| 727 | b[H_APPROVAL..H_APPROVAL + 32].copy_from_slice(&h.approval_ref); |
| 728 | b[H_INCARNATION..H_INCARNATION + 4].copy_from_slice(&h.incarnation.to_be_bytes()); |
| 729 | b[H_EXPIRES..H_EXPIRES + 8].copy_from_slice(&h.expires_at.to_be_bytes()); |
| 730 | b[H_B_TIME..H_B_TIME + 8].copy_from_slice(&h.budget_time_ms.to_be_bytes()); |
| 731 | b[H_B_FUEL..H_B_FUEL + 8].copy_from_slice(&h.budget_fuel.to_be_bytes()); |
| 732 | b[H_B_MEMORY..H_B_MEMORY + 8].copy_from_slice(&h.budget_memory.to_be_bytes()); |
| 733 | b[H_B_WORK..H_B_WORK + 8].copy_from_slice(&h.budget_work.to_be_bytes()); |
| 734 | b[H_B_IN..H_B_IN + 4].copy_from_slice(&h.budget_input_tokens.to_be_bytes()); |
| 735 | b[H_B_OUT..H_B_OUT + 4].copy_from_slice(&h.budget_output_tokens.to_be_bytes()); |
| 736 | for (i, x) in d.nodes.iter().enumerate() { |
| 737 | if x.deps.len() > MAX_DEPS { |
| 738 | return Err(EncodeError::TooManyDeps); |
| 739 | } |
| 740 | if x.operands.len() > MAX_OPERANDS { |
| 741 | return Err(EncodeError::TooManyOperands); |
| 742 | } |
| 743 | let n = &mut b[HEADER_LEN + i * NODE_LEN..HEADER_LEN + (i + 1) * NODE_LEN]; |
| 744 | n[N_JOB..N_JOB + 16].copy_from_slice(&x.job_id); |
| 745 | n[N_IDEM..N_IDEM + 16].copy_from_slice(&x.idempotence_key); |
| 746 | n[N_GEN..N_GEN + 4].copy_from_slice(&x.generation.to_be_bytes()); |
| 747 | n[N_KIND] = x.kind; |
| 748 | n[N_OP] = x.op; |
| 749 | n[N_PROFILE] = x.profile; |
| 750 | n[N_EFFECT] = x.effect_class; |
| 751 | n[N_IN..N_IN + 2].copy_from_slice(&x.input_tokens.to_be_bytes()); |
| 752 | n[N_OUT..N_OUT + 2].copy_from_slice(&x.output_tokens.to_be_bytes()); |
| 753 | n[N_REQ_IN..N_REQ_IN + 2].copy_from_slice(&x.required_input_tokens.to_be_bytes()); |
| 754 | n[N_REQ_OUT..N_REQ_OUT + 2].copy_from_slice(&x.required_output_tokens.to_be_bytes()); |
| 755 | n[N_VERIFIER] = x.verifier_kind; |
| 756 | n[N_RETRY] = x.retry_class; |
| 757 | n[N_ATTEMPTS] = x.max_attempts; |
| 758 | n[N_CANCEL] = x.cancel_mode; |
| 759 | n[N_PRECISION] = x.precision; |
| 760 | n[N_SUBSTRATE] = x.substrate_mask; |
| 761 | n[N_DEPS_N] = x.deps.len() as u8; |
| 762 | n[N_OPS_N] = x.operands.len() as u8; |
| 763 | n[N_RTYPE] = x.result_type; |
| 764 | n[N_RANK] = x.result_rank; |
| 765 | n[N_PURE] = x.pure as u8; |
| 766 | n[N_TIME..N_TIME + 4].copy_from_slice(&x.time_ms.to_be_bytes()); |
| 767 | n[N_FUEL..N_FUEL + 8].copy_from_slice(&x.fuel.to_be_bytes()); |
| 768 | n[N_MEMORY..N_MEMORY + 8].copy_from_slice(&x.memory.to_be_bytes()); |
| 769 | n[N_WORK..N_WORK + 8].copy_from_slice(&x.work.to_be_bytes()); |
| 770 | n[N_EXPIRES..N_EXPIRES + 8].copy_from_slice(&x.expires_at.to_be_bytes()); |
| 771 | for (k, dim) in x.result_dims.iter().enumerate() { |
| 772 | n[N_DIMS + 4 * k..N_DIMS + 4 * k + 4].copy_from_slice(&dim.to_be_bytes()); |
| 773 | } |
| 774 | n[N_CAP..N_CAP + 32].copy_from_slice(&x.capability_ref); |
| 775 | n[N_TENANT..N_TENANT + 32].copy_from_slice(&x.tenant_id); |
| 776 | n[N_MODEL..N_MODEL + 32].copy_from_slice(&x.model_ref); |
| 777 | n[N_VREF..N_VREF + 32].copy_from_slice(&x.verifier_ref); |
| 778 | for (s, dep) in x.deps.iter().enumerate() { |
| 779 | let at = N_DEPS + s * DEP_LEN; |
| 780 | n[at..at + 2].copy_from_slice(&dep.index.to_be_bytes()); |
| 781 | n[at + 2..at + 6].copy_from_slice(&dep.generation.to_be_bytes()); |
| 782 | } |
| 783 | for (s, op) in x.operands.iter().enumerate() { |
| 784 | let at = N_OPERANDS + s * OPERAND_LEN; |
| 785 | n[at] = op.kind; |
| 786 | n[at + 4..at + 8].copy_from_slice(&op.generation.to_be_bytes()); |
| 787 | n[at + 8..at + 40].copy_from_slice(&op.digest); |
| 788 | } |
| 789 | } |
| 790 | Ok(b) |
| 791 | } |
| 792 | |
| 793 | /// `dag_digest`: SHA-256 of the document bytes (section 3, rule 4). |
| 794 | pub fn dag_digest(document: &[u8]) -> [u8; 32] { |
| 795 | Sha256::digest(document).into() |
| 796 | } |
| 797 | |
| 798 | fn hex(out: &mut String, bytes: &[u8]) { |
| 799 | const H: &[u8; 16] = b"0123456789abcdef"; |
| 800 | for &x in bytes { |
| 801 | out.push(H[(x >> 4) as usize] as char); |
| 802 | out.push(H[(x & 15) as usize] as char); |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | /// The verdict line in the exact format of `mjb_verify FILE` and |
| 807 | /// `vectors/expected.txt`. |
| 808 | pub fn verdict_line(document: &[u8]) -> String { |
| 809 | match decode(document) { |
| 810 | Err(r) => format!("refuse {}", r.name()), |
| 811 | Ok(d) => { |
| 812 | let mut s = format!( |
| 813 | "ok nodes={} incarnation={} ceiling={} objective=", |
| 814 | d.nodes.len(), |
| 815 | d.header.incarnation, |
| 816 | d.header.effect_ceiling |
| 817 | ); |
| 818 | hex(&mut s, &d.header.objective_id); |
| 819 | s.push_str(" tenant="); |
| 820 | hex(&mut s, &d.header.tenant_id); |
| 821 | s.push_str(" digest="); |
| 822 | hex(&mut s, &dag_digest(document)); |
| 823 | s.push_str(" order="); |
| 824 | let order = canonical_order(&d.nodes).expect("decode checked acyclic"); |
| 825 | let parts: Vec<String> = order.iter().map(|i| i.to_string()).collect(); |
| 826 | s.push_str(&parts.join(",")); |
| 827 | s |
| 828 | } |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | /// One MJR1 receipt (section 5). |
| 833 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 834 | pub struct Receipt { |
| 835 | pub outcome: u8, |
| 836 | pub attempt: u8, |
| 837 | pub dag_digest: [u8; 32], |
| 838 | pub job_id: [u8; 16], |
| 839 | pub idempotence_key: [u8; 16], |
| 840 | pub generation: u32, |
| 841 | pub used_time_ms: u32, |
| 842 | pub used_input_tokens: u16, |
| 843 | pub used_output_tokens: u16, |
| 844 | pub used_fuel: u64, |
| 845 | pub used_memory: u64, |
| 846 | pub used_work: u64, |
| 847 | pub input_binding: [u8; 32], |
| 848 | pub output_digest: [u8; 32], |
| 849 | pub source_hash: [u8; 32], |
| 850 | pub model_hash: [u8; 32], |
| 851 | pub policy_hash: [u8; 32], |
| 852 | pub verifier_verdict: [u8; 32], |
| 853 | pub signer_key: [u8; 33], |
| 854 | pub signature: [u8; 64], |
| 855 | } |
| 856 | |
| 857 | /// Write one receipt. |
| 858 | pub fn encode_receipt(r: &Receipt) -> [u8; RECEIPT_LEN] { |
| 859 | let mut b = [0u8; RECEIPT_LEN]; |
| 860 | b[0..4].copy_from_slice(&RECEIPT_MAGIC); |
| 861 | b[4] = VERSION; |
| 862 | b[5] = r.outcome; |
| 863 | b[6] = r.attempt; |
| 864 | b[8..40].copy_from_slice(&r.dag_digest); |
| 865 | b[40..56].copy_from_slice(&r.job_id); |
| 866 | b[56..72].copy_from_slice(&r.idempotence_key); |
| 867 | b[72..76].copy_from_slice(&r.generation.to_be_bytes()); |
| 868 | b[76..80].copy_from_slice(&r.used_time_ms.to_be_bytes()); |
| 869 | b[80..82].copy_from_slice(&r.used_input_tokens.to_be_bytes()); |
| 870 | b[82..84].copy_from_slice(&r.used_output_tokens.to_be_bytes()); |
| 871 | b[88..96].copy_from_slice(&r.used_fuel.to_be_bytes()); |
| 872 | b[96..104].copy_from_slice(&r.used_memory.to_be_bytes()); |
| 873 | b[104..112].copy_from_slice(&r.used_work.to_be_bytes()); |
| 874 | b[112..144].copy_from_slice(&r.input_binding); |
| 875 | b[144..176].copy_from_slice(&r.output_digest); |
| 876 | b[176..208].copy_from_slice(&r.source_hash); |
| 877 | b[208..240].copy_from_slice(&r.model_hash); |
| 878 | b[240..272].copy_from_slice(&r.policy_hash); |
| 879 | b[272..304].copy_from_slice(&r.verifier_verdict); |
| 880 | b[304..337].copy_from_slice(&r.signer_key); |
| 881 | b[340..404].copy_from_slice(&r.signature); |
| 882 | b |
| 883 | } |
| 884 | |
| 885 | /// Decode one receipt and apply the static rules of section 5.2 |
| 886 | /// (`MJB_BAD_RECEIPT`). The signature is not checked here. |
| 887 | pub fn decode_receipt(b: &[u8]) -> Result<Receipt, Refusal> { |
| 888 | if b.len() != RECEIPT_LEN |
| 889 | || b[0..4] != RECEIPT_MAGIC |
| 890 | || b[4] != VERSION |
| 891 | || b[7] != 0 |
| 892 | || !all_zero(&b[84..88]) |
| 893 | || !all_zero(&b[337..340]) |
| 894 | || !(outcome::COMPLETED..=outcome::UNCERTAIN).contains(&b[5]) |
| 895 | || b[6] == 0 |
| 896 | || (b[304] != 0x02 && b[304] != 0x03) |
| 897 | || all_zero(&b[176..208]) |
| 898 | || all_zero(&b[240..272]) |
| 899 | { |
| 900 | return Err(Refusal::BadReceipt); |
| 901 | } |
| 902 | let completed = b[5] == outcome::COMPLETED; |
| 903 | if completed == all_zero(&b[144..176]) || (completed && all_zero(&b[272..304])) { |
| 904 | return Err(Refusal::BadReceipt); |
| 905 | } |
| 906 | Ok(Receipt { |
| 907 | outcome: b[5], |
| 908 | attempt: b[6], |
| 909 | dag_digest: arr(b, 8), |
| 910 | job_id: arr(b, 40), |
| 911 | idempotence_key: arr(b, 56), |
| 912 | generation: u32_at(b, 72), |
| 913 | used_time_ms: u32_at(b, 76), |
| 914 | used_input_tokens: u16_at(b, 80), |
| 915 | used_output_tokens: u16_at(b, 82), |
| 916 | used_fuel: u64_at(b, 88), |
| 917 | used_memory: u64_at(b, 96), |
| 918 | used_work: u64_at(b, 104), |
| 919 | input_binding: arr(b, 112), |
| 920 | output_digest: arr(b, 144), |
| 921 | source_hash: arr(b, 176), |
| 922 | model_hash: arr(b, 208), |
| 923 | policy_hash: arr(b, 240), |
| 924 | verifier_verdict: arr(b, 272), |
| 925 | signer_key: arr(b, 304), |
| 926 | signature: arr(b, 340), |
| 927 | }) |
| 928 | } |
| 929 | |
| 930 | /// `receipt_digest`: SHA-256 of the signed region (the signature excluded). |
| 931 | pub fn receipt_digest(r: &Receipt) -> [u8; 32] { |
| 932 | Sha256::digest(&encode_receipt(r)[..RECEIPT_SIGNED_LEN]).into() |
| 933 | } |
| 934 | |
| 935 | /// Fill `signer_key` from `key` and sign the receipt. |
| 936 | pub fn sign_receipt(r: &mut Receipt, key: &SigningKey) { |
| 937 | r.signer_key = p256_compressed_key(key); |
| 938 | let bytes = encode_receipt(r); |
| 939 | r.signature = p256_sign_low_s(key, &bytes[..RECEIPT_SIGNED_LEN]); |
| 940 | } |
| 941 | |
| 942 | /// The input binding of section 5.1 from dependency receipt digests (in slot |
| 943 | /// order) and the node's operands. |
| 944 | pub fn input_binding(dep_receipt_digests: &[[u8; 32]], operands: &[Operand]) -> [u8; 32] { |
| 945 | let mut h = Sha256::new(); |
| 946 | h.update(b"MJR1-BIND"); |
| 947 | for d in dep_receipt_digests { |
| 948 | h.update(d); |
| 949 | } |
| 950 | for op in operands { |
| 951 | h.update([op.kind]); |
| 952 | h.update(op.generation.to_be_bytes()); |
| 953 | h.update(op.digest); |
| 954 | } |
| 955 | h.finalize().into() |
| 956 | } |
| 957 | |
| 958 | /// Derived node state (section 5.3). |
| 959 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 960 | pub enum NodeState { |
| 961 | /// Some dependency is not yet DONE. |
| 962 | Waiting, |
| 963 | /// Every dependency is DONE and no terminal receipt exists. |
| 964 | Ready, |
| 965 | /// A COMPLETED receipt was applied. |
| 966 | Done, |
| 967 | /// A REFUSED receipt was applied. |
| 968 | Refused, |
| 969 | /// A CANCELLED receipt was applied, or the objective was cancelled. |
| 970 | Cancelled, |
| 971 | /// FAILED or UNCERTAIN on the last allowed attempt. |
| 972 | Exhausted, |
| 973 | /// The last attempt is UNCERTAIN and another is allowed after |
| 974 | /// reconciliation against the effect ledger. |
| 975 | Uncertain, |
| 976 | /// A dependency is REFUSED, CANCELLED, EXHAUSTED or BLOCKED. |
| 977 | Blocked, |
| 978 | } |
| 979 | |
| 980 | /// Whether [`DagRun::apply`] changed state. |
| 981 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 982 | pub enum Applied { |
| 983 | New, |
| 984 | Replay, |
| 985 | } |
| 986 | |
| 987 | /// Receiver-local persistence event, not a wire record or remote authority. |
| 988 | /// Store events durably, in order, bound to the accepted document. |
| 989 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 990 | // Keep the fixed receipt inline: boxing would allocate per persisted receipt. |
| 991 | // Cancellation appears at most once in the canonical exported log. |
| 992 | #[allow(clippy::large_enum_variant)] |
| 993 | pub enum LedgerEvent { |
| 994 | Receipt([u8; RECEIPT_LEN]), |
| 995 | Cancelled, |
| 996 | } |
| 997 | |
| 998 | #[derive(Debug, Clone, Default)] |
| 999 | struct Slot { |
| 1000 | /// Every receipt applied to this node, in order. |
| 1001 | applied: Vec<[u8; RECEIPT_LEN]>, |
| 1002 | last_outcome: u8, |
| 1003 | last_attempt: u8, |
| 1004 | /// Digest of the COMPLETED receipt. |
| 1005 | done: Option<[u8; 32]>, |
| 1006 | output: Option<[u8; 32]>, |
| 1007 | } |
| 1008 | |
| 1009 | /// The receipt ledger of one accepted document (section 5.2). |
| 1010 | #[derive(Debug, Clone)] |
| 1011 | pub struct DagRun { |
| 1012 | dag: Dag, |
| 1013 | digest: [u8; 32], |
| 1014 | trusted: Vec<[u8; 33]>, |
| 1015 | slots: Vec<Slot>, |
| 1016 | cancelled: bool, |
| 1017 | log: Vec<LedgerEvent>, |
| 1018 | } |
| 1019 | |
| 1020 | impl DagRun { |
| 1021 | /// Admit a document at the receiver's clock `now` (Unix seconds) with the |
| 1022 | /// receiver's own trusted executor keys. Expired documents are refused. |
| 1023 | pub fn admit(document: &[u8], trusted: Vec<[u8; 33]>, now: u64) -> Result<Self, Refusal> { |
| 1024 | let dag = decode(document)?; |
| 1025 | if dag.header.expires_at < now || dag.nodes.iter().any(|node| node.expires_at < now) { |
| 1026 | return Err(Refusal::BadExpiry); |
| 1027 | } |
| 1028 | let n = dag.nodes.len(); |
| 1029 | Ok(DagRun { |
| 1030 | dag, |
| 1031 | digest: dag_digest(document), |
| 1032 | trusted, |
| 1033 | slots: vec![Slot::default(); n], |
| 1034 | cancelled: false, |
| 1035 | log: Vec::new(), |
| 1036 | }) |
| 1037 | } |
| 1038 | |
| 1039 | /// Rebuild from the receiver's ordered receipt and cancellation events. |
| 1040 | /// Receipt-only historical logs cannot establish cancellation history; |
| 1041 | /// migration requires independently trusted receiver state. |
| 1042 | pub fn restore( |
| 1043 | document: &[u8], |
| 1044 | trusted: Vec<[u8; 33]>, |
| 1045 | now: u64, |
| 1046 | log: &[LedgerEvent], |
| 1047 | ) -> Result<Self, Refusal> { |
| 1048 | let mut run = Self::admit(document, trusted, now)?; |
| 1049 | for event in log { |
| 1050 | match event { |
| 1051 | LedgerEvent::Receipt(receipt) => { |
| 1052 | run.apply(receipt)?; |
| 1053 | } |
| 1054 | LedgerEvent::Cancelled => run.cancel(), |
| 1055 | } |
| 1056 | } |
| 1057 | Ok(run) |
| 1058 | } |
| 1059 | |
| 1060 | /// The accepted document. |
| 1061 | pub fn dag(&self) -> &Dag { |
| 1062 | &self.dag |
| 1063 | } |
| 1064 | |
| 1065 | /// The `dag_digest` receipts must name. |
| 1066 | pub fn digest(&self) -> [u8; 32] { |
| 1067 | self.digest |
| 1068 | } |
| 1069 | |
| 1070 | /// Every newly applied receipt and first cancellation, in order. |
| 1071 | /// The caller must durably store events before acknowledging their effects. |
| 1072 | pub fn log(&self) -> &[LedgerEvent] { |
| 1073 | &self.log |
| 1074 | } |
| 1075 | |
| 1076 | /// The `output_digest` of a DONE node. |
| 1077 | pub fn output(&self, i: usize) -> Option<[u8; 32]> { |
| 1078 | self.slots[i].output |
| 1079 | } |
| 1080 | |
| 1081 | /// The binding a receipt for node `i` must carry, once every dependency |
| 1082 | /// is DONE. |
| 1083 | pub fn expected_binding(&self, i: usize) -> Option<[u8; 32]> { |
| 1084 | let node = &self.dag.nodes[i]; |
| 1085 | let mut deps = Vec::with_capacity(node.deps.len()); |
| 1086 | for d in &node.deps { |
| 1087 | deps.push(self.slots[d.index as usize].done?); |
| 1088 | } |
| 1089 | Some(input_binding(&deps, &node.operands)) |
| 1090 | } |
| 1091 | |
| 1092 | /// Cancel the objective: every receipt applied so far stands, every later |
| 1093 | /// receipt is refused, every non-terminal node becomes CANCELLED. |
| 1094 | pub fn cancel(&mut self) { |
| 1095 | if !self.cancelled { |
| 1096 | self.log.push(LedgerEvent::Cancelled); |
| 1097 | self.cancelled = true; |
| 1098 | } |
| 1099 | } |
| 1100 | |
| 1101 | /// Apply one receipt (section 5.2). A refusal changes nothing. |
| 1102 | pub fn apply(&mut self, bytes: &[u8]) -> Result<Applied, Refusal> { |
| 1103 | let r = decode_receipt(bytes)?; |
| 1104 | if !self.trusted.contains(&r.signer_key) |
| 1105 | || p256_verify_low_s(&r.signer_key, &bytes[..RECEIPT_SIGNED_LEN], &r.signature).is_err() |
| 1106 | { |
| 1107 | return Err(Refusal::ForgedReceipt); |
| 1108 | } |
| 1109 | if r.dag_digest != self.digest { |
| 1110 | return Err(Refusal::WrongDag); |
| 1111 | } |
| 1112 | let i = self |
| 1113 | .dag |
| 1114 | .nodes |
| 1115 | .iter() |
| 1116 | .position(|n| n.job_id == r.job_id) |
| 1117 | .ok_or(Refusal::UnknownJob)?; |
| 1118 | let node = &self.dag.nodes[i]; |
| 1119 | if node.idempotence_key != r.idempotence_key { |
| 1120 | return Err(Refusal::UnknownJob); |
| 1121 | } |
| 1122 | if node.generation != r.generation { |
| 1123 | return Err(Refusal::StaleGeneration); |
| 1124 | } |
| 1125 | if node.model_ref != r.model_hash { |
| 1126 | return Err(Refusal::ModelMismatch); |
| 1127 | } |
| 1128 | let slot = &self.slots[i]; |
| 1129 | if slot.applied.iter().any(|a| a[..] == bytes[..]) { |
| 1130 | return Ok(Applied::Replay); |
| 1131 | } |
| 1132 | if self.cancelled { |
| 1133 | return Err(Refusal::Cancelled); |
| 1134 | } |
| 1135 | if is_terminal(slot.last_outcome) { |
| 1136 | return Err(Refusal::DoubleCommit); |
| 1137 | } |
| 1138 | if r.attempt != slot.last_attempt.saturating_add(1) || r.attempt > node.max_attempts { |
| 1139 | return Err(Refusal::BadRetry); |
| 1140 | } |
| 1141 | if r.used_time_ms > node.time_ms |
| 1142 | || r.used_input_tokens > node.input_tokens |
| 1143 | || r.used_output_tokens > node.output_tokens |
| 1144 | || r.used_fuel > node.fuel |
| 1145 | || r.used_memory > node.memory |
| 1146 | || r.used_work > node.work |
| 1147 | { |
| 1148 | return Err(Refusal::ReceiptOverBudget); |
| 1149 | } |
| 1150 | match self.expected_binding(i) { |
| 1151 | Some(b) if b != r.input_binding => return Err(Refusal::BindingMismatch), |
| 1152 | None if r.outcome == outcome::COMPLETED => return Err(Refusal::DepNotDone), |
| 1153 | _ => {} |
| 1154 | } |
| 1155 | let mut stored = [0u8; RECEIPT_LEN]; |
| 1156 | stored.copy_from_slice(bytes); |
| 1157 | let slot = &mut self.slots[i]; |
| 1158 | slot.applied.push(stored); |
| 1159 | slot.last_outcome = r.outcome; |
| 1160 | slot.last_attempt = r.attempt; |
| 1161 | if r.outcome == outcome::COMPLETED { |
| 1162 | slot.done = Some(receipt_digest(&r)); |
| 1163 | slot.output = Some(r.output_digest); |
| 1164 | } |
| 1165 | self.log.push(LedgerEvent::Receipt(stored)); |
| 1166 | Ok(Applied::New) |
| 1167 | } |
| 1168 | |
| 1169 | /// The derived state of node `i` (section 5.3). |
| 1170 | pub fn state(&self, i: usize) -> NodeState { |
| 1171 | let order = canonical_order(&self.dag.nodes).expect("admitted documents are acyclic"); |
| 1172 | let mut states = vec![NodeState::Waiting; self.dag.nodes.len()]; |
| 1173 | for &k in &order { |
| 1174 | states[k] = self.own_state(k, &states); |
| 1175 | } |
| 1176 | states[i] |
| 1177 | } |
| 1178 | |
| 1179 | /// The derived state of every node, by index. |
| 1180 | pub fn states(&self) -> Vec<NodeState> { |
| 1181 | (0..self.dag.nodes.len()).map(|i| self.state(i)).collect() |
| 1182 | } |
| 1183 | |
| 1184 | fn own_state(&self, k: usize, states: &[NodeState]) -> NodeState { |
| 1185 | let slot = &self.slots[k]; |
| 1186 | let node = &self.dag.nodes[k]; |
| 1187 | match slot.last_outcome { |
| 1188 | outcome::COMPLETED => return NodeState::Done, |
| 1189 | outcome::REFUSED => return NodeState::Refused, |
| 1190 | outcome::CANCELLED => return NodeState::Cancelled, |
| 1191 | _ => {} |
| 1192 | } |
| 1193 | let out_of_attempts = slot.last_attempt >= node.max_attempts |
| 1194 | && matches!(slot.last_outcome, outcome::FAILED | outcome::UNCERTAIN); |
| 1195 | if out_of_attempts { |
| 1196 | return NodeState::Exhausted; |
| 1197 | } |
| 1198 | if self.cancelled { |
| 1199 | return NodeState::Cancelled; |
| 1200 | } |
| 1201 | let dep_states = node.deps.iter().map(|d| states[d.index as usize]); |
| 1202 | if dep_states.clone().any(|s| { |
| 1203 | matches!( |
| 1204 | s, |
| 1205 | NodeState::Refused |
| 1206 | | NodeState::Cancelled |
| 1207 | | NodeState::Exhausted |
| 1208 | | NodeState::Blocked |
| 1209 | ) |
| 1210 | }) { |
| 1211 | return NodeState::Blocked; |
| 1212 | } |
| 1213 | if slot.last_outcome == outcome::UNCERTAIN { |
| 1214 | return NodeState::Uncertain; |
| 1215 | } |
| 1216 | if dep_states.clone().all(|s| s == NodeState::Done) { |
| 1217 | NodeState::Ready |
| 1218 | } else { |
| 1219 | NodeState::Waiting |
| 1220 | } |
| 1221 | } |
| 1222 | } |
| 1223 | |
| 1224 | fn is_terminal(o: u8) -> bool { |
| 1225 | matches!( |
| 1226 | o, |
| 1227 | outcome::COMPLETED | outcome::REFUSED | outcome::CANCELLED |
| 1228 | ) |
| 1229 | } |
| 1230 | |
| 1231 | #[cfg(test)] |
| 1232 | mod tests { |
| 1233 | use super::*; |
| 1234 | |
| 1235 | #[test] |
| 1236 | fn profile_table_matches_the_issue() { |
| 1237 | assert_eq!(profile_caps(profile::ZERO), Some((0, 0))); |
| 1238 | assert_eq!(profile_caps(profile::MINIMAL), Some((64, 16))); |
| 1239 | assert_eq!(profile_caps(profile::DEFAULT), Some((128, 32))); |
| 1240 | assert_eq!(profile_caps(profile::LARGE), Some((256, 64))); |
| 1241 | assert_eq!(profile_caps(profile::SPECIALIST), Some((512, 128))); |
| 1242 | assert_eq!(profile_caps(5), None); |
| 1243 | } |
| 1244 | |
| 1245 | #[test] |
| 1246 | fn layout_constants() { |
| 1247 | assert_eq!(N_OPERANDS + MAX_OPERANDS * OPERAND_LEN, NODE_LEN); |
| 1248 | assert_eq!(N_DEPS + MAX_DEPS * DEP_LEN, N_OPERANDS); |
| 1249 | assert_eq!(H_B_OUT + 4, HEADER_LEN); |
| 1250 | assert_eq!(MAX_DOCUMENT, 28864); |
| 1251 | } |
| 1252 | } |