qualia_core_db/sensing/authority/
certificates.rs1use core::cmp::Ordering;
6use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
7
8use crate::audio::qac::signal::{ExactTime, Rate};
9use crate::sensing::acquisition::Clock;
10use crate::sensing::SemanticId;
11
12pub const CALIBRATION_CERT_DOMAIN: &[u8] = b"QUALIA-CALIBRATION-CERT-v1\0";
14pub const CALIBRATION_SIG_DOMAIN: &[u8] = b"QUALIA-CALIBRATION-SIG-v1\0";
16pub const MAX_CALIBRATION_CHAIN_LEN: usize = 8;
18pub const MAX_CALIBRATION_BATCH_SAMPLES: usize = 4096;
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23#[repr(u16)]
24pub enum CalibrationSchemaFamily {
25 EmfSchema107 = 107,
27 QacSchema202 = 202,
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum SignalStageRelation {
34 DigitalUnrelatedToPressure,
36 RawCounts,
38 PhysicalBaseUnits,
41}
42
43impl SignalStageRelation {
44 pub fn from_wire_str(label: &str) -> Result<Self, CalibrationError> {
45 match label {
46 "digital-unrelated-to-pressure" => Ok(Self::DigitalUnrelatedToPressure),
47 "raw-counts" => Ok(Self::RawCounts),
48 "physical-base-units" => Ok(Self::PhysicalBaseUnits),
49 _ => Err(CalibrationError::InvalidStageRelation),
50 }
51 }
52
53 pub const fn as_wire_str(self) -> &'static str {
54 match self {
55 Self::DigitalUnrelatedToPressure => "digital-unrelated-to-pressure",
56 Self::RawCounts => "raw-counts",
57 Self::PhysicalBaseUnits => "physical-base-units",
58 }
59 }
60}
61
62#[derive(Clone, Copy, Debug, PartialEq)]
64pub enum UncertaintyKind {
65 StandardAbsolute,
67 ExpandedAbsolute {
69 coverage_factor_k: f64,
70 confidence_probability: f64,
71 },
72 Relative,
74}
75
76impl UncertaintyKind {
77 pub fn validate(self) -> Result<(), CalibrationError> {
78 match self {
79 Self::StandardAbsolute | Self::Relative => Ok(()),
80 Self::ExpandedAbsolute {
81 coverage_factor_k,
82 confidence_probability,
83 } => {
84 if !coverage_factor_k.is_finite()
85 || coverage_factor_k <= 0.0
86 || !confidence_probability.is_finite()
87 || confidence_probability <= 0.0
88 || confidence_probability >= 1.0
89 {
90 return Err(CalibrationError::InvalidUncertaintyKind);
91 }
92 Ok(())
93 }
94 }
95 }
96}
97
98#[derive(Clone, Copy, Debug, PartialEq)]
101pub struct QualifiedUncertainty {
102 pub value: f64,
103 pub target_quantity: SemanticId,
104 pub target_unit: SemanticId,
105 pub kind: UncertaintyKind,
106 pub estimator_id: SemanticId,
107}
108
109impl QualifiedUncertainty {
110 pub fn validate(&self) -> Result<(), CalibrationError> {
111 if !self.value.is_finite() || self.value < 0.0 {
112 return Err(CalibrationError::InvalidUncertaintyValue);
113 }
114 self.kind.validate()?;
115 if self.target_quantity.value().is_none() || self.target_unit.value().is_none() {
116 return Err(CalibrationError::UnlabeledUncertaintyRejected);
117 }
118 if self.estimator_id.value().is_none() {
119 return Err(CalibrationError::InvalidIdentifier);
120 }
121 Ok(())
122 }
123
124 pub fn verify_against_mixed_record_components(
129 &self,
130 admitted_components: &[(SemanticId, SemanticId)],
131 ) -> Result<(), CalibrationError> {
132 self.validate()?;
133 if admitted_components.is_empty() {
134 return Err(CalibrationError::UnlabeledUncertaintyRejected);
135 }
136 let found = admitted_components.iter().any(|&(q, u)| {
137 q == self.target_quantity
138 && u == self.target_unit
139 && q.value().is_some()
140 && u.value().is_some()
141 });
142 if !found {
143 return Err(CalibrationError::UncertaintyTargetMismatch);
144 }
145 Ok(())
146 }
147}
148
149#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152pub struct RationalInstant {
153 clock_origin: SemanticId,
154 restart_epoch: u64,
155 scale: u32,
156 numerator: i128,
157 denominator: i128,
158}
159
160impl RationalInstant {
161 pub fn new(
164 clock_origin: SemanticId,
165 restart_epoch: u64,
166 scale: u32,
167 numerator: i128,
168 denominator: i128,
169 ) -> Result<Self, CalibrationError> {
170 if clock_origin.value().is_none() {
171 return Err(CalibrationError::InvalidIdentifier);
172 }
173 if scale > 2 || denominator <= 0 {
174 return Err(CalibrationError::InvalidClockInstant);
175 }
176 let abs_num = numerator
177 .checked_abs()
178 .ok_or(CalibrationError::RationalOverflow)? as u128;
179 let g = gcd_u128(abs_num, denominator as u128) as i128;
180 Ok(Self {
181 clock_origin,
182 restart_epoch,
183 scale,
184 numerator: numerator / g,
185 denominator: denominator / g,
186 })
187 }
188
189 pub fn from_clock_tick_subtick(
192 clock: Clock,
193 tick: i64,
194 subtick_num: u64,
195 subtick_den: u64,
196 ) -> Result<Self, CalibrationError> {
197 if subtick_den == 0 || subtick_num >= subtick_den {
198 return Err(CalibrationError::InvalidClockInstant);
199 }
200 let base: ExactTime = clock
201 .tick_time(tick)
202 .map_err(|_| CalibrationError::InvalidClockInstant)?;
203 let base_instant = Self::new(
204 clock.origin(),
205 clock.restart(),
206 clock.timing().scale,
207 base.numerator,
208 base.denominator,
209 )?;
210 if subtick_num == 0 {
211 return Ok(base_instant);
212 }
213 let ticks_rate: Rate = clock.timing().ticks;
214 let sub_sec_num = i128::from(subtick_num)
215 .checked_mul(i128::from(ticks_rate.denominator))
216 .ok_or(CalibrationError::RationalOverflow)?;
217 let sub_sec_den = i128::from(subtick_den)
218 .checked_mul(i128::from(ticks_rate.numerator))
219 .ok_or(CalibrationError::RationalOverflow)?;
220 base_instant.add_rational_seconds(sub_sec_num, sub_sec_den)
221 }
222
223 pub const fn clock_origin(self) -> SemanticId {
224 self.clock_origin
225 }
226 pub const fn restart_epoch(self) -> u64 {
227 self.restart_epoch
228 }
229 pub const fn scale(self) -> u32 {
230 self.scale
231 }
232 pub const fn numerator(self) -> i128 {
233 self.numerator
234 }
235 pub const fn denominator(self) -> i128 {
236 self.denominator
237 }
238
239 pub fn same_clock_domain(self, other: Self) -> bool {
240 self.clock_origin == other.clock_origin
241 && self.restart_epoch == other.restart_epoch
242 && self.scale == other.scale
243 && self.clock_origin.value().is_some()
244 }
245
246 pub fn add_rational_seconds(
248 self,
249 delta_num: i128,
250 delta_den: i128,
251 ) -> Result<Self, CalibrationError> {
252 if delta_den <= 0 {
253 return Err(CalibrationError::InvalidClockInstant);
254 }
255 let g = gcd_u128(self.denominator as u128, delta_den as u128) as i128;
256 let a = delta_den / g;
257 let b = self.denominator / g;
258 let left = self
259 .numerator
260 .checked_mul(a)
261 .ok_or(CalibrationError::RationalOverflow)?;
262 let right = delta_num
263 .checked_mul(b)
264 .ok_or(CalibrationError::RationalOverflow)?;
265 let sum_num = left
266 .checked_add(right)
267 .ok_or(CalibrationError::RationalOverflow)?;
268 let lcm_den = self
269 .denominator
270 .checked_mul(a)
271 .ok_or(CalibrationError::RationalOverflow)?;
272 Self::new(
273 self.clock_origin,
274 self.restart_epoch,
275 self.scale,
276 sum_num,
277 lcm_den,
278 )
279 }
280
281 pub fn checked_cmp(self, other: Self) -> Result<Ordering, CalibrationError> {
283 if !self.same_clock_domain(other) {
284 return Err(CalibrationError::ClockDomainMismatch);
285 }
286 if self.denominator == other.denominator {
287 return Ok(self.numerator.cmp(&other.numerator));
288 }
289 let g = gcd_u128(self.denominator as u128, other.denominator as u128) as i128;
290 let lhs = self
291 .numerator
292 .checked_mul(other.denominator / g)
293 .ok_or(CalibrationError::RationalOverflow)?;
294 let rhs = other
295 .numerator
296 .checked_mul(self.denominator / g)
297 .ok_or(CalibrationError::RationalOverflow)?;
298 Ok(lhs.cmp(&rhs))
299 }
300}
301
302#[derive(Clone, Copy, Debug, PartialEq, Eq)]
304pub struct CalibrationValidityWindow {
305 valid_from: RationalInstant,
306 valid_until: RationalInstant,
307}
308
309impl CalibrationValidityWindow {
310 pub fn new(
312 valid_from: RationalInstant,
313 valid_until: RationalInstant,
314 ) -> Result<Self, CalibrationError> {
315 if valid_from.checked_cmp(valid_until)? != Ordering::Less {
316 return Err(CalibrationError::InvalidValidityInterval);
317 }
318 Ok(Self {
319 valid_from,
320 valid_until,
321 })
322 }
323
324 pub const fn valid_from(self) -> RationalInstant {
325 self.valid_from
326 }
327 pub const fn valid_until(self) -> RationalInstant {
328 self.valid_until
329 }
330
331 pub fn verify_contains(self, instant: RationalInstant) -> Result<(), CalibrationError> {
334 if instant.checked_cmp(self.valid_from)? == Ordering::Less {
335 return Err(CalibrationError::CalibrationNotYetValid);
336 }
337 if instant.checked_cmp(self.valid_until)? != Ordering::Less {
338 return Err(CalibrationError::CalibrationExpiredAtOrAfterUntil);
339 }
340 Ok(())
341 }
342
343 pub fn verify_subinterval_of(self, parent: Self) -> Result<(), CalibrationError> {
345 if self.valid_from.checked_cmp(parent.valid_from)? == Ordering::Less
346 || self.valid_until.checked_cmp(parent.valid_until)? == Ordering::Greater
347 {
348 return Err(CalibrationError::ChildWindowExceedsIssuer);
349 }
350 Ok(())
351 }
352}
353
354#[derive(Clone, Copy, Debug, PartialEq)]
356pub struct CalibrationCertificate {
357 pub schema_family: CalibrationSchemaFamily,
358 pub certificate_id: [u8; 32],
359 pub parent_certificate_digest: Option<[u8; 32]>,
360 pub instrument_id: SemanticId,
361 pub channel_index: u32,
362 pub input_quantity: SemanticId,
363 pub output_quantity: SemanticId,
364 pub output_unit: SemanticId,
365 pub affine_scale: f64,
366 pub affine_offset: f64,
367 pub reference_level: Option<f64>,
368 pub frequency_band_hz: Option<[f64; 2]>,
369 pub validity_window: CalibrationValidityWindow,
370 pub uncertainty: QualifiedUncertainty,
371 pub issuer_public_key: [u8; 32],
372 pub subject_public_key: [u8; 32],
373 pub signature: [u8; 64],
374}
375
376impl CalibrationCertificate {
377 pub fn validate_fields(&self) -> Result<(), CalibrationError> {
378 if self.certificate_id == [0u8; 32]
379 || self.issuer_public_key == [0u8; 32]
380 || self.subject_public_key == [0u8; 32]
381 || self.instrument_id.value().is_none()
382 || self.input_quantity.value().is_none()
383 || self.output_quantity.value().is_none()
384 || self.output_unit.value().is_none()
385 {
386 return Err(CalibrationError::InvalidIdentifier);
387 }
388 if self.parent_certificate_digest.is_some_and(|p| p == [0u8; 32]) {
389 return Err(CalibrationError::InvalidIdentifier);
390 }
391 if !self.affine_scale.is_finite()
392 || self.affine_scale <= 0.0
393 || !self.affine_offset.is_finite()
394 {
395 return Err(CalibrationError::InvalidAffineParameters);
396 }
397 if self.reference_level.is_some_and(|r| !r.is_finite() || r <= 0.0) {
398 return Err(CalibrationError::InvalidReferenceLevel);
399 }
400 if let Some([f_lo, f_hi]) = self.frequency_band_hz {
401 if !f_lo.is_finite() || !f_hi.is_finite() || f_lo < 0.0 || f_lo >= f_hi {
402 return Err(CalibrationError::InvalidFrequencyBand);
403 }
404 }
405 self.uncertainty.validate()?;
406 if self.uncertainty.target_quantity != self.output_quantity
407 || self.uncertainty.target_unit != self.output_unit
408 {
409 return Err(CalibrationError::UncertaintyTargetMismatch);
410 }
411 Ok(())
412 }
413
414 pub fn sign(mut self, issuer_signing_key: &SigningKey) -> Result<Self, CalibrationError> {
415 self.issuer_public_key = issuer_signing_key.verifying_key().to_bytes();
416 self.validate_fields()?;
417 let preimage = self.signing_preimage();
418 self.signature = issuer_signing_key.sign(&preimage).to_bytes();
419 Ok(self)
420 }
421
422 pub fn certificate_digest(&self) -> [u8; 32] {
423 let mut hasher = blake3::Hasher::new();
424 hasher.update(CALIBRATION_CERT_DOMAIN);
425 self.hash_body(&mut hasher);
426 hasher.update(&self.signature);
427 *hasher.finalize().as_bytes()
428 }
429
430 pub fn verify_signature(&self) -> Result<(), CalibrationError> {
431 self.validate_fields()?;
432 let vk = VerifyingKey::from_bytes(&self.issuer_public_key)
433 .map_err(|_| CalibrationError::InvalidSignature)?;
434 let sig = Signature::from_bytes(&self.signature);
435 vk.verify_strict(&self.signing_preimage(), &sig)
436 .map_err(|_| CalibrationError::InvalidSignature)
437 }
438
439 pub fn verify_applicable_at(
440 &self,
441 instant: RationalInstant,
442 frequency_hz: Option<f64>,
443 ) -> Result<(), CalibrationError> {
444 self.verify_signature()?;
445 self.validity_window.verify_contains(instant)?;
446 if let (Some([f_lo, f_hi]), Some(f)) = (self.frequency_band_hz, frequency_hz) {
447 if !f.is_finite() || f < f_lo || f > f_hi {
448 return Err(CalibrationError::FrequencyOutOfCalibrationBand);
449 }
450 }
451 Ok(())
452 }
453
454 fn signing_preimage(&self) -> [u8; 32] {
455 let mut hasher = blake3::Hasher::new();
456 hasher.update(CALIBRATION_SIG_DOMAIN);
457 self.hash_body(&mut hasher);
458 *hasher.finalize().as_bytes()
459 }
460
461 fn hash_body(&self, hasher: &mut blake3::Hasher) {
462 hasher.update(&(self.schema_family as u16).to_le_bytes());
463 hasher.update(&self.certificate_id);
464 match self.parent_certificate_digest {
465 Some(parent) => {
466 hasher.update(&[1]);
467 hasher.update(&parent);
468 }
469 None => {
470 hasher.update(&[0; 33]);
471 }
472 }
473 hasher.update(&self.instrument_id.value().unwrap_or(0).to_le_bytes());
474 hasher.update(&self.channel_index.to_le_bytes());
475 hasher.update(&self.input_quantity.value().unwrap_or(0).to_le_bytes());
476 hasher.update(&self.output_quantity.value().unwrap_or(0).to_le_bytes());
477 hasher.update(&self.output_unit.value().unwrap_or(0).to_le_bytes());
478 hasher.update(&self.affine_scale.to_bits().to_le_bytes());
479 hasher.update(&self.affine_offset.to_bits().to_le_bytes());
480 match self.reference_level {
481 Some(r) => {
482 hasher.update(&[1]);
483 hasher.update(&r.to_bits().to_le_bytes());
484 }
485 None => {
486 hasher.update(&[0; 9]);
487 }
488 }
489 match self.frequency_band_hz {
490 Some([lo, hi]) => {
491 hasher.update(&[1]);
492 hasher.update(&lo.to_bits().to_le_bytes());
493 hasher.update(&hi.to_bits().to_le_bytes());
494 }
495 None => {
496 hasher.update(&[0; 17]);
497 }
498 }
499 hash_instant(hasher, self.validity_window.valid_from);
500 hash_instant(hasher, self.validity_window.valid_until);
501 hasher.update(&self.uncertainty.value.to_bits().to_le_bytes());
502 hasher.update(&self.uncertainty.target_quantity.value().unwrap_or(0).to_le_bytes());
503 hasher.update(&self.uncertainty.target_unit.value().unwrap_or(0).to_le_bytes());
504 hasher.update(&self.uncertainty.estimator_id.value().unwrap_or(0).to_le_bytes());
505 match self.uncertainty.kind {
506 UncertaintyKind::StandardAbsolute => {
507 hasher.update(&[1]);
508 }
509 UncertaintyKind::ExpandedAbsolute {
510 coverage_factor_k,
511 confidence_probability,
512 } => {
513 hasher.update(&[2]);
514 hasher.update(&coverage_factor_k.to_bits().to_le_bytes());
515 hasher.update(&confidence_probability.to_bits().to_le_bytes());
516 }
517 UncertaintyKind::Relative => {
518 hasher.update(&[3]);
519 }
520 }
521 hasher.update(&self.issuer_public_key);
522 hasher.update(&self.subject_public_key);
523 }
524}
525
526pub fn verify_calibration_certificate_chain(
529 chain: &[CalibrationCertificate],
530 trusted_root_public_key: &[u8; 32],
531 observation_instant: RationalInstant,
532 frequency_hz: Option<f64>,
533) -> Result<[u8; 32], CalibrationError> {
534 if chain.is_empty() || chain.len() > MAX_CALIBRATION_CHAIN_LEN {
535 return Err(CalibrationError::InvalidChainLength);
536 }
537 let root = &chain[0];
538 if &root.issuer_public_key != trusted_root_public_key || root.parent_certificate_digest.is_some()
539 {
540 return Err(CalibrationError::UntrustedRootAuthority);
541 }
542 root.verify_signature()?;
543 root.validity_window.verify_contains(observation_instant)?;
544
545 let mut prev_digest = root.certificate_digest();
546 let mut prev_subject_key = root.subject_public_key;
547 let mut prev_window = root.validity_window;
548
549 for cert in &chain[1..] {
550 cert.verify_signature()?;
551 if cert.parent_certificate_digest != Some(prev_digest) {
552 return Err(CalibrationError::BrokenParentDigestLink);
553 }
554 if cert.issuer_public_key != prev_subject_key {
555 return Err(CalibrationError::BrokenIssuerSubjectLink);
556 }
557 cert.validity_window.verify_subinterval_of(prev_window)?;
558 cert.validity_window.verify_contains(observation_instant)?;
559 prev_digest = cert.certificate_digest();
560 prev_subject_key = cert.subject_public_key;
561 prev_window = cert.validity_window;
562 }
563
564 chain[chain.len() - 1].verify_applicable_at(observation_instant, frequency_hz)?;
565 Ok(prev_digest)
566}
567
568#[path = "certificates_calibration.rs"]
569mod certificates_calibration;
570pub use certificates_calibration::*;
571
572
573fn hash_instant(hasher: &mut blake3::Hasher, instant: RationalInstant) {
574 hasher.update(&instant.clock_origin.value().unwrap_or(0).to_le_bytes());
575 hasher.update(&instant.restart_epoch.to_le_bytes());
576 hasher.update(&instant.scale.to_le_bytes());
577 hasher.update(&instant.numerator.to_le_bytes());
578 hasher.update(&instant.denominator.to_le_bytes());
579}
580
581const fn gcd_u128(mut a: u128, mut b: u128) -> u128 {
582 while b != 0 {
583 let r = a % b;
584 a = b;
585 b = r;
586 }
587 if a == 0 {
588 1
589 } else {
590 a
591 }
592}