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/spark-rsi-mv/blob/main/src/dual/records.rs # spark-rsi-mv Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger 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 `spark-rsi-mv / src / dual / records.rs` 819 lines ยท 23099 bytes Raw Blame History 1 //! DUAL record decoder (ADR 0031 section 4), a read-only port of the omega 2 //! C checker and codec in `src/dual/rx_dual.c` on omega branch 3 //! `dual/0a-records`, commit `f056b77f64ee94a80f4ed2899b5f9495aa3ef840`. 4 //! 5 //! Every enum value, field order, refusal and digest domain below is copied 6 //! from that commit's `rx_dual.h` / `rx_dual.c`. Encodings start with 7 //! `u8 kind, u8 version(1)`, integers are little-endian, doubles are IEEE-754 8 //! binary64 bits with `-0.0` written as `+0.0`, digests are 32 bytes. 9 //! Digest = SHA-256(domain || 0x00 || canonical encoding). 10 //! 11 //! This module only reads. It mints nothing, authorizes nothing and is never 12 //! consulted by a gate. A price is scarcity information, not permission. 13 14 use sha2::{Digest as _, Sha256}; 15 16 pub const DIGEST_SIZE: usize = 32; 17 pub const FORMAT_VERSION: u8 = 1; 18 pub const MAX_RESOURCES: u32 = 32; 19 20 pub const DOMAIN_RESOURCE: &str = "omega.dual.resource.v1"; 21 pub const DOMAIN_CONSTRAINT: &str = "omega.dual.constraint.v1"; 22 pub const DOMAIN_CONTROLLER: &str = "omega.dual.controller.v1"; 23 pub const DOMAIN_PRICE_VECTOR: &str = "omega.dual.pricevec.v1"; 24 25 /// 32-byte digest. All-zero means absent. 26 pub type Digest32 = [u8; DIGEST_SIZE]; 27 28 pub fn digest_is_zero(d: &Digest32) -> bool { 29 d.iter().all(|b| *b == 0) 30 } 31 32 /// SHA-256(domain || 0x00 || encoding), the DUAL identity rule. 33 pub fn domain_digest(domain: &str, encoding: &[u8]) -> Digest32 { 34 let mut h = Sha256::new(); 35 h.update(domain.as_bytes()); 36 h.update([0u8]); 37 h.update(encoding); 38 h.finalize().into() 39 } 40 41 /// Record kind bytes (`RxDualKind`). 42 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 43 #[repr(u8)] 44 pub enum Kind { 45 Resource = 1, 46 Constraint = 2, 47 Controller = 3, 48 PriceVector = 4, 49 } 50 51 /// Closed unit registry (`RxDualUnit`). `NONE` (0) and anything >= 16 are refused. 52 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] 53 #[repr(u32)] 54 pub enum Unit { 55 Ps = 1, 56 Pj = 2, 57 Bytes = 3, 58 BytesPerS = 4, 59 KvBlocks = 5, 60 PpmOccupancy = 6, 61 NsVerify = 7, 62 NsSynth = 8, 63 Ns = 9, 64 Watt = 10, 65 WattPerS = 11, 66 MilliCelsius = 12, 67 MilliCelsiusPerS = 13, 68 Dimensionless = 14, 69 Log2Ps = 15, 70 } 71 72 impl Unit { 73 pub fn from_u32(v: u32) -> Option { 74 Some(match v { 75 1 => Unit::Ps, 76 2 => Unit::Pj, 77 3 => Unit::Bytes, 78 4 => Unit::BytesPerS, 79 5 => Unit::KvBlocks, 80 6 => Unit::PpmOccupancy, 81 7 => Unit::NsVerify, 82 8 => Unit::NsSynth, 83 9 => Unit::Ns, 84 10 => Unit::Watt, 85 11 => Unit::WattPerS, 86 12 => Unit::MilliCelsius, 87 13 => Unit::MilliCelsiusPerS, 88 14 => Unit::Dimensionless, 89 15 => Unit::Log2Ps, 90 _ => return None, 91 }) 92 } 93 94 pub fn name(self) -> &'static str { 95 match self { 96 Unit::Ps => "PS", 97 Unit::Pj => "PJ", 98 Unit::Bytes => "BYTES", 99 Unit::BytesPerS => "BYTES_PER_S", 100 Unit::KvBlocks => "KV_BLOCKS", 101 Unit::PpmOccupancy => "PPM_OCCUPANCY", 102 Unit::NsVerify => "NS_VERIFY", 103 Unit::NsSynth => "NS_SYNTH", 104 Unit::Ns => "NS", 105 Unit::Watt => "WATT", 106 Unit::WattPerS => "WATT_PER_S", 107 Unit::MilliCelsius => "MILLI_CELSIUS", 108 Unit::MilliCelsiusPerS => "MILLI_CELSIUS_PER_S", 109 Unit::Dimensionless => "DIMENSIONLESS", 110 Unit::Log2Ps => "LOG2_PS", 111 } 112 } 113 } 114 115 /// Constraint class (`RxDualClass`). Only CAPACITY and SOFT construct; 116 /// UNDECLARED (0) and INVARIANT (1) are refused, never defaulted. 117 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] 118 #[repr(u32)] 119 pub enum Class { 120 /// Diagnostic lambda only; never relaxed. 121 Capacity = 2, 122 /// Priceable. 123 Soft = 3, 124 } 125 126 impl Class { 127 pub fn from_u32(v: u32) -> Option { 128 match v { 129 2 => Some(Class::Capacity), 130 3 => Some(Class::Soft), 131 _ => None, 132 } 133 } 134 } 135 136 /// `RxDualEstimateKind`. 137 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] 138 #[repr(u32)] 139 pub enum EstimateKind { 140 Measured = 1, 141 Estimated = 2, 142 Predicted = 3, 143 } 144 145 impl EstimateKind { 146 pub fn from_u32(v: u32) -> Option { 147 match v { 148 1 => Some(EstimateKind::Measured), 149 2 => Some(EstimateKind::Estimated), 150 3 => Some(EstimateKind::Predicted), 151 _ => None, 152 } 153 } 154 } 155 156 /// `RxDualLambdaState`. Consumers treat everything but FRESH as absent. 157 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] 158 #[repr(u32)] 159 pub enum LambdaState { 160 Fresh = 1, 161 Stale = 2, 162 Frozen = 3, 163 Uncalibrated = 4, 164 Refused = 5, 165 } 166 167 impl LambdaState { 168 pub fn from_u32(v: u32) -> Option { 169 match v { 170 1 => Some(LambdaState::Fresh), 171 2 => Some(LambdaState::Stale), 172 3 => Some(LambdaState::Frozen), 173 4 => Some(LambdaState::Uncalibrated), 174 5 => Some(LambdaState::Refused), 175 _ => None, 176 } 177 } 178 179 pub fn name(self) -> &'static str { 180 match self { 181 LambdaState::Fresh => "FRESH", 182 LambdaState::Stale => "STALE", 183 LambdaState::Frozen => "FROZEN", 184 LambdaState::Uncalibrated => "UNCALIBRATED", 185 LambdaState::Refused => "REFUSED", 186 } 187 } 188 } 189 190 /// Refusal reasons, one per `RxDualStatus` code the decoders can return. 191 /// `c_status()` gives the C code so golden statuses can be compared exactly. 192 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 193 pub enum Refusal { 194 /// NaN or Inf anywhere (-2). 195 NonFinite, 196 /// Missing, unknown unit (-3). 197 Unit, 198 /// Undeclared, INVARIANT or unknown class (-4). 199 Class, 200 /// Scale not strictly positive (-5). 201 Scale, 202 /// Negative uncertainty/lambda, bad enum, bad count (-6). 203 Range, 204 /// Wrong record kind byte or bad estimate kind (-7). 205 Kind, 206 /// Truncated, trailing bytes, bad version (-8). 207 Encoding, 208 /// Duplicate or unordered resource id (-9). 209 Resource, 210 /// Required digest absent, or parent/tick linkage broken (-10). 211 Digest, 212 /// Generation inconsistent across a vector (-11). 213 Generation, 214 /// FRESH claimed without a calibration receipt (-17). 215 Calibration, 216 } 217 218 impl Refusal { 219 pub fn c_status(self) -> i32 { 220 match self { 221 Refusal::NonFinite => -2, 222 Refusal::Unit => -3, 223 Refusal::Class => -4, 224 Refusal::Scale => -5, 225 Refusal::Range => -6, 226 Refusal::Kind => -7, 227 Refusal::Encoding => -8, 228 Refusal::Resource => -9, 229 Refusal::Digest => -10, 230 Refusal::Generation => -11, 231 Refusal::Calibration => -17, 232 } 233 } 234 } 235 236 impl std::fmt::Display for Refusal { 237 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 238 write!(f, "{:?} (RxDualStatus {})", self, self.c_status()) 239 } 240 } 241 242 /// `RxDualResource` (4.1 registry entry). 243 #[derive(Debug, Clone, PartialEq)] 244 pub struct Resource { 245 pub resource_id: u32, 246 pub unit: Unit, 247 pub scale: f64, 248 pub contract: Digest32, 249 } 250 251 /// `RxDualConstraintState` (4.2). 252 #[derive(Debug, Clone, PartialEq)] 253 pub struct ConstraintState { 254 pub resource_id: u32, 255 pub unit: Unit, 256 pub class: Class, 257 pub budget: f64, 258 pub budget_contract: Digest32, 259 pub observation_ref: Digest32, 260 pub estimate_ref: Digest32, 261 pub estimate_kind: EstimateKind, 262 pub estimate: f64, 263 pub uncertainty: f64, 264 pub calibration_ref: Digest32, 265 pub lambda: f64, 266 pub lambda_state: LambdaState, 267 pub controller_id: Digest32, 268 pub generation: u64, 269 pub tick: u64, 270 pub evidence_root: Digest32, 271 pub parent: Digest32, 272 } 273 274 impl ConstraintState { 275 /// FRESH and carrying a calibration receipt. The checker already refuses 276 /// FRESH without one; this is the consumer-side restatement. 277 pub fn is_fresh_calibrated(&self) -> bool { 278 self.lambda_state == LambdaState::Fresh && !digest_is_zero(&self.calibration_ref) 279 } 280 } 281 282 /// `RxDualController` (section 5.1); its digest is `controller_id`. 283 #[derive(Debug, Clone, PartialEq)] 284 pub struct Controller { 285 pub eta: f64, 286 pub rho: f64, 287 pub k_sigma: f64, 288 pub max_age: u64, 289 pub cadence: u64, 290 /// (resource_id, lambda_max), strictly ascending ids. 291 pub entries: Vec<(u32, f64)>, 292 } 293 294 /// `RxDualPriceVector` (4.3): one decision context, one generation. 295 #[derive(Debug, Clone, PartialEq)] 296 pub struct PriceVector { 297 pub generation: u64, 298 pub context: Digest32, 299 /// (resource_id, constraint state digest), strictly ascending ids. 300 pub entries: Vec<(u32, Digest32)>, 301 } 302 303 // ---------------------------------------------------------------- reader 304 305 struct Reader<'a> { 306 p: &'a [u8], 307 pos: usize, 308 st: Option, 309 } 310 311 impl<'a> Reader<'a> { 312 fn new(p: &'a [u8]) -> Self { 313 Reader { 314 p, 315 pos: 0, 316 st: None, 317 } 318 } 319 fn fail(&mut self, r: Refusal) { 320 if self.st.is_none() { 321 self.st = Some(r); 322 } 323 } 324 fn need(&mut self, n: usize) -> bool { 325 if self.st.is_some() { 326 return false; 327 } 328 if self.pos + n > self.p.len() { 329 self.fail(Refusal::Encoding); 330 return false; 331 } 332 true 333 } 334 fn u8(&mut self) -> u8 { 335 if !self.need(1) { 336 return 0; 337 } 338 let v = self.p[self.pos]; 339 self.pos += 1; 340 v 341 } 342 fn u32(&mut self) -> u32 { 343 if !self.need(4) { 344 return 0; 345 } 346 let mut b = [0u8; 4]; 347 b.copy_from_slice(&self.p[self.pos..self.pos + 4]); 348 self.pos += 4; 349 u32::from_le_bytes(b) 350 } 351 fn u64(&mut self) -> u64 { 352 if !self.need(8) { 353 return 0; 354 } 355 let mut b = [0u8; 8]; 356 b.copy_from_slice(&self.p[self.pos..self.pos + 8]); 357 self.pos += 8; 358 u64::from_le_bytes(b) 359 } 360 fn f64(&mut self) -> f64 { 361 f64::from_bits(self.u64()) 362 } 363 fn dig(&mut self) -> Digest32 { 364 let mut d = [0u8; DIGEST_SIZE]; 365 if !self.need(DIGEST_SIZE) { 366 return d; 367 } 368 d.copy_from_slice(&self.p[self.pos..self.pos + DIGEST_SIZE]); 369 self.pos += DIGEST_SIZE; 370 d 371 } 372 /// Mirrors `r_hdr`: a short header is ENCODING, a wrong kind is KIND, 373 /// a wrong version is ENCODING. 374 fn hdr(&mut self, want: Kind) { 375 let k = self.u8(); 376 let v = self.u8(); 377 if self.st.is_some() { 378 return; 379 } 380 if k != want as u8 { 381 self.fail(Refusal::Kind); 382 return; 383 } 384 if v != FORMAT_VERSION { 385 self.fail(Refusal::Encoding); 386 } 387 } 388 /// Mirrors `r_end`: earlier failure first, then trailing bytes. 389 fn end(&self) -> Result<(), Refusal> { 390 if let Some(r) = self.st { 391 return Err(r); 392 } 393 if self.pos != self.p.len() { 394 return Err(Refusal::Encoding); 395 } 396 Ok(()) 397 } 398 } 399 400 // ---------------------------------------------------------------- writer 401 402 struct Writer { 403 buf: Vec, 404 } 405 406 impl Writer { 407 fn new() -> Self { 408 Writer { buf: Vec::new() } 409 } 410 fn u8(&mut self, v: u8) { 411 self.buf.push(v); 412 } 413 fn u32(&mut self, v: u32) { 414 self.buf.extend_from_slice(&v.to_le_bytes()); 415 } 416 fn u64(&mut self, v: u64) { 417 self.buf.extend_from_slice(&v.to_le_bytes()); 418 } 419 /// Mirrors `w_f64`: +0.0 and -0.0 both encode as all-zero bits. 420 fn f64(&mut self, d: f64) { 421 let bits = if d != 0.0 { d.to_bits() } else { 0 }; 422 self.u64(bits); 423 } 424 fn dig(&mut self, d: &Digest32) { 425 self.buf.extend_from_slice(d); 426 } 427 fn hdr(&mut self, k: Kind) { 428 self.u8(k as u8); 429 self.u8(FORMAT_VERSION); 430 } 431 } 432 433 fn ids_ascending(entries: &[(u32, T)]) -> bool { 434 entries.windows(2).all(|w| w[1].0 > w[0].0) 435 } 436 437 // ------------------------------------------------------------ validation 438 439 /// Raw constraint as read off the wire, before enum conversion. The check 440 /// runs on raw values in the exact order of `rx_dual_check_constraint`. 441 struct RawConstraint { 442 resource_id: u32, 443 unit: u32, 444 cls: u32, 445 budget: f64, 446 budget_contract: Digest32, 447 observation_ref: Digest32, 448 estimate_ref: Digest32, 449 estimate_kind: u32, 450 estimate: f64, 451 uncertainty: f64, 452 calibration_ref: Digest32, 453 lambda: f64, 454 lambda_state: u32, 455 controller_id: Digest32, 456 generation: u64, 457 tick: u64, 458 evidence_root: Digest32, 459 parent: Digest32, 460 } 461 462 impl RawConstraint { 463 fn check(self) -> Result { 464 let unit = Unit::from_u32(self.unit).ok_or(Refusal::Unit)?; 465 // INVARIANT is unconstructible; UNDECLARED is never defaulted. 466 let class = Class::from_u32(self.cls).ok_or(Refusal::Class)?; 467 if !(self.budget.is_finite() 468 && self.estimate.is_finite() 469 && self.uncertainty.is_finite() 470 && self.lambda.is_finite()) 471 { 472 return Err(Refusal::NonFinite); 473 } 474 if self.uncertainty < 0.0 || self.lambda < 0.0 { 475 return Err(Refusal::Range); 476 } 477 let estimate_kind = EstimateKind::from_u32(self.estimate_kind).ok_or(Refusal::Kind)?; 478 let lambda_state = LambdaState::from_u32(self.lambda_state).ok_or(Refusal::Range)?; 479 if digest_is_zero(&self.budget_contract) 480 || digest_is_zero(&self.estimate_ref) 481 || digest_is_zero(&self.controller_id) 482 || digest_is_zero(&self.evidence_root) 483 { 484 return Err(Refusal::Digest); 485 } 486 if estimate_kind == EstimateKind::Measured && digest_is_zero(&self.observation_ref) { 487 return Err(Refusal::Digest); 488 } 489 if digest_is_zero(&self.calibration_ref) && lambda_state == LambdaState::Fresh { 490 return Err(Refusal::Calibration); 491 } 492 if (self.tick == 0) != digest_is_zero(&self.parent) { 493 return Err(Refusal::Digest); 494 } 495 Ok(ConstraintState { 496 resource_id: self.resource_id, 497 unit, 498 class, 499 budget: self.budget, 500 budget_contract: self.budget_contract, 501 observation_ref: self.observation_ref, 502 estimate_ref: self.estimate_ref, 503 estimate_kind, 504 estimate: self.estimate, 505 uncertainty: self.uncertainty, 506 calibration_ref: self.calibration_ref, 507 lambda: self.lambda, 508 lambda_state, 509 controller_id: self.controller_id, 510 generation: self.generation, 511 tick: self.tick, 512 evidence_root: self.evidence_root, 513 parent: self.parent, 514 }) 515 } 516 } 517 518 fn check_resource( 519 resource_id: u32, 520 unit: u32, 521 scale: f64, 522 contract: Digest32, 523 ) -> Result { 524 let unit = Unit::from_u32(unit).ok_or(Refusal::Unit)?; 525 if !scale.is_finite() { 526 return Err(Refusal::NonFinite); 527 } 528 if scale <= 0.0 { 529 return Err(Refusal::Scale); 530 } 531 if digest_is_zero(&contract) { 532 return Err(Refusal::Digest); 533 } 534 Ok(Resource { 535 resource_id, 536 unit, 537 scale, 538 contract, 539 }) 540 } 541 542 fn check_controller(c: &Controller) -> Result<(), Refusal> { 543 if !(c.eta.is_finite() && c.rho.is_finite() && c.k_sigma.is_finite()) { 544 return Err(Refusal::NonFinite); 545 } 546 if c.eta < 0.0 || c.rho < 0.0 || c.rho > 1.0 || c.k_sigma < 0.0 { 547 return Err(Refusal::Range); 548 } 549 if c.max_age == 0 || c.cadence == 0 { 550 return Err(Refusal::Range); 551 } 552 if c.entries.is_empty() || c.entries.len() > MAX_RESOURCES as usize { 553 return Err(Refusal::Range); 554 } 555 if !ids_ascending(&c.entries) { 556 return Err(Refusal::Resource); 557 } 558 for (_, lambda_max) in &c.entries { 559 if !lambda_max.is_finite() { 560 return Err(Refusal::NonFinite); 561 } 562 if *lambda_max <= 0.0 { 563 return Err(Refusal::Range); 564 } 565 } 566 Ok(()) 567 } 568 569 fn check_price_vector(v: &PriceVector) -> Result<(), Refusal> { 570 if digest_is_zero(&v.context) { 571 return Err(Refusal::Digest); 572 } 573 if v.entries.is_empty() || v.entries.len() > MAX_RESOURCES as usize { 574 return Err(Refusal::Range); 575 } 576 if !ids_ascending(&v.entries) { 577 return Err(Refusal::Resource); 578 } 579 for (_, state) in &v.entries { 580 if digest_is_zero(state) { 581 return Err(Refusal::Digest); 582 } 583 } 584 Ok(()) 585 } 586 587 // --------------------------------------------------------- decode / encode 588 589 pub fn decode_resource(buf: &[u8]) -> Result { 590 let mut r = Reader::new(buf); 591 r.hdr(Kind::Resource); 592 let resource_id = r.u32(); 593 let unit = r.u32(); 594 let scale = r.f64(); 595 let contract = r.dig(); 596 r.end()?; 597 check_resource(resource_id, unit, scale, contract) 598 } 599 600 pub fn encode_resource(x: &Resource) -> Vec { 601 let mut w = Writer::new(); 602 w.hdr(Kind::Resource); 603 w.u32(x.resource_id); 604 w.u32(x.unit as u32); 605 w.f64(x.scale); 606 w.dig(&x.contract); 607 w.buf 608 } 609 610 pub fn decode_constraint(buf: &[u8]) -> Result { 611 let mut r = Reader::new(buf); 612 r.hdr(Kind::Constraint); 613 let raw = RawConstraint { 614 resource_id: r.u32(), 615 unit: r.u32(), 616 cls: r.u32(), 617 budget: r.f64(), 618 budget_contract: r.dig(), 619 observation_ref: r.dig(), 620 estimate_ref: r.dig(), 621 estimate_kind: r.u32(), 622 estimate: r.f64(), 623 uncertainty: r.f64(), 624 calibration_ref: r.dig(), 625 lambda: r.f64(), 626 lambda_state: r.u32(), 627 controller_id: r.dig(), 628 generation: r.u64(), 629 tick: r.u64(), 630 evidence_root: r.dig(), 631 parent: r.dig(), 632 }; 633 r.end()?; 634 raw.check() 635 } 636 637 pub fn encode_constraint(s: &ConstraintState) -> Vec { 638 let mut w = Writer::new(); 639 w.hdr(Kind::Constraint); 640 w.u32(s.resource_id); 641 w.u32(s.unit as u32); 642 w.u32(s.class as u32); 643 w.f64(s.budget); 644 w.dig(&s.budget_contract); 645 w.dig(&s.observation_ref); 646 w.dig(&s.estimate_ref); 647 w.u32(s.estimate_kind as u32); 648 w.f64(s.estimate); 649 w.f64(s.uncertainty); 650 w.dig(&s.calibration_ref); 651 w.f64(s.lambda); 652 w.u32(s.lambda_state as u32); 653 w.dig(&s.controller_id); 654 w.u64(s.generation); 655 w.u64(s.tick); 656 w.dig(&s.evidence_root); 657 w.dig(&s.parent); 658 w.buf 659 } 660 661 pub fn decode_controller(buf: &[u8]) -> Result { 662 let mut r = Reader::new(buf); 663 r.hdr(Kind::Controller); 664 let eta = r.f64(); 665 let rho = r.f64(); 666 let k_sigma = r.f64(); 667 let max_age = r.u64(); 668 let cadence = r.u64(); 669 let n = r.u32(); 670 if let Some(st) = r.st { 671 return Err(st); 672 } 673 if n == 0 || n > MAX_RESOURCES { 674 return Err(Refusal::Range); 675 } 676 let mut entries = Vec::with_capacity(n as usize); 677 for _ in 0..n { 678 let id = r.u32(); 679 let lambda_max = r.f64(); 680 entries.push((id, lambda_max)); 681 } 682 r.end()?; 683 let c = Controller { 684 eta, 685 rho, 686 k_sigma, 687 max_age, 688 cadence, 689 entries, 690 }; 691 check_controller(&c)?; 692 Ok(c) 693 } 694 695 pub fn encode_controller(c: &Controller) -> Vec { 696 let mut w = Writer::new(); 697 w.hdr(Kind::Controller); 698 w.f64(c.eta); 699 w.f64(c.rho); 700 w.f64(c.k_sigma); 701 w.u64(c.max_age); 702 w.u64(c.cadence); 703 w.u32(c.entries.len() as u32); 704 for (id, lambda_max) in &c.entries { 705 w.u32(*id); 706 w.f64(*lambda_max); 707 } 708 w.buf 709 } 710 711 pub fn decode_price_vector(buf: &[u8]) -> Result { 712 let mut r = Reader::new(buf); 713 r.hdr(Kind::PriceVector); 714 let generation = r.u64(); 715 let context = r.dig(); 716 let n = r.u32(); 717 if let Some(st) = r.st { 718 return Err(st); 719 } 720 if n == 0 || n > MAX_RESOURCES { 721 return Err(Refusal::Range); 722 } 723 let mut entries = Vec::with_capacity(n as usize); 724 for _ in 0..n { 725 let id = r.u32(); 726 let state = r.dig(); 727 entries.push((id, state)); 728 } 729 r.end()?; 730 let v = PriceVector { 731 generation, 732 context, 733 entries, 734 }; 735 check_price_vector(&v)?; 736 Ok(v) 737 } 738 739 pub fn encode_price_vector(v: &PriceVector) -> Vec { 740 let mut w = Writer::new(); 741 w.hdr(Kind::PriceVector); 742 w.u64(v.generation); 743 w.dig(&v.context); 744 w.u32(v.entries.len() as u32); 745 for (id, state) in &v.entries { 746 w.u32(*id); 747 w.dig(state); 748 } 749 w.buf 750 } 751 752 // --------------------------------------------------------------- identity 753 754 /// Digests are taken over the canonical re-encoding of a validated record, 755 /// exactly as `rx_dual_digest_*` do (so a non-canonical `-0.0` on the wire 756 /// still yields the canonical digest). 757 pub fn digest_resource(x: &Resource) -> Digest32 { 758 domain_digest(DOMAIN_RESOURCE, &encode_resource(x)) 759 } 760 761 pub fn digest_constraint(s: &ConstraintState) -> Digest32 { 762 domain_digest(DOMAIN_CONSTRAINT, &encode_constraint(s)) 763 } 764 765 pub fn digest_controller(c: &Controller) -> Digest32 { 766 domain_digest(DOMAIN_CONTROLLER, &encode_controller(c)) 767 } 768 769 pub fn digest_price_vector(v: &PriceVector) -> Digest32 { 770 domain_digest(DOMAIN_PRICE_VECTOR, &encode_price_vector(v)) 771 } 772 773 /// Decode a record of the given kind from `bytes` and compare its canonical 774 /// digest with `expected`. Any refusal or mismatch is an `Err`. 775 pub fn verify_digest(kind: Kind, bytes: &[u8], expected: &Digest32) -> Result<(), VerifyError> { 776 let actual = match kind { 777 Kind::Resource => digest_resource(&decode_resource(bytes)?), 778 Kind::Constraint => digest_constraint(&decode_constraint(bytes)?), 779 Kind::Controller => digest_controller(&decode_controller(bytes)?), 780 Kind::PriceVector => digest_price_vector(&decode_price_vector(bytes)?), 781 }; 782 if &actual == expected { 783 Ok(()) 784 } else { 785 Err(VerifyError::DigestMismatch { 786 expected: *expected, 787 actual, 788 }) 789 } 790 } 791 792 #[derive(Debug, Clone, PartialEq, Eq)] 793 pub enum VerifyError { 794 Refused(Refusal), 795 DigestMismatch { 796 expected: Digest32, 797 actual: Digest32, 798 }, 799 } 800 801 impl From for VerifyError { 802 fn from(r: Refusal) -> Self { 803 VerifyError::Refused(r) 804 } 805 } 806 807 impl std::fmt::Display for VerifyError { 808 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 809 match self { 810 VerifyError::Refused(r) => write!(f, "refused: {}", r), 811 VerifyError::DigestMismatch { expected, actual } => write!( 812 f, 813 "digest mismatch: expected {} got {}", 814 hex::encode(expected), 815 hex::encode(actual) 816 ), 817 } 818 } 819 }