Skip to main content

qualia_core_db/sensing/
signed_evidence.rs

1//! Fixed-field signed envelope for caller-owned sensing evidence.
2//!
3//! The envelope signs a versioned, domain-separated SHA-256 commitment. A valid
4//! signature authenticates the signed declaration only; trusted policy must
5//! separately authorize the source/adapter, consent decision and revocation
6//! state, and calibration artifact. Neither signature nor policy proves that a
7//! physical measurement is scientifically true.
8
9use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
10use sha2::{Digest, Sha256};
11
12use super::grounding::{EvidenceUncertainty, SensingEvidence, SensingEvidenceAuthenticator};
13use super::record::{CalibrationArtifactReference, CalibrationDeclaration};
14
15#[path = "signed_evidence_wire.rs"]
16mod wire;
17
18pub const SIGNED_SENSING_EVIDENCE_VERSION: u16 = 1;
19pub const SIGNED_SENSING_EVIDENCE_WIRE_SIZE: usize = 398;
20const SIGNING_DOMAIN: &[u8] = b"qualia:sensing:evidence:v1";
21const PAYLOAD_DOMAIN: &[u8] = b"qualia:sensing:payload:v1";
22const CALIBRATION_DOMAIN: &[u8] = b"qualia:sensing:calibration-artifact:v1";
23const WIRE_MAGIC: [u8; 4] = *b"SSE1";
24
25/// Domain-separated digest for raw payload bytes. This helper allocates no
26/// memory; callers must hash the exact immutable payload that the envelope
27/// references, and the evidence policy must bind that digest to its record.
28pub fn digest_payload(payload: &[u8]) -> [u8; 32] {
29    let mut hash = Sha256::new();
30    hash.update(PAYLOAD_DOMAIN);
31    hash.update((payload.len() as u64).to_le_bytes());
32    hash.update(payload);
33    hash.finalize().into()
34}
35
36/// Domain-separated digest for calibration artifact bytes. A policy resolver
37/// must confirm that this digest names the artifact in `SensingEvidence`;
38/// signing the digest alone is not calibration validation.
39pub fn digest_calibration_artifact(artifact: &[u8]) -> [u8; 32] {
40    let mut hash = Sha256::new();
41    hash.update(CALIBRATION_DOMAIN);
42    hash.update((artifact.len() as u64).to_le_bytes());
43    hash.update(artifact);
44    hash.finalize().into()
45}
46
47/// Capture time in an explicit monotonic clock domain. This is not UTC; the
48/// grant policy must not compare it to a wall-clock expiry without an explicit
49/// authenticated clock conversion.
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub struct CaptureTimestamp {
52    clock_domain_id: u64,
53    restart_epoch: u32,
54    ticks_ns: u64,
55    uncertainty_ns: u64,
56}
57
58impl CaptureTimestamp {
59    pub const fn new(
60        clock_domain_id: u64,
61        restart_epoch: u32,
62        ticks_ns: u64,
63        uncertainty_ns: u64,
64    ) -> Result<Self, SignedEvidenceError> {
65        if clock_domain_id == 0 {
66            return Err(SignedEvidenceError::InvalidIdentifier);
67        }
68        if ticks_ns.checked_add(uncertainty_ns).is_none() {
69            return Err(SignedEvidenceError::InvalidTimestamp);
70        }
71        Ok(Self {
72            clock_domain_id,
73            restart_epoch,
74            ticks_ns,
75            uncertainty_ns,
76        })
77    }
78
79    pub const fn clock_domain_id(self) -> u64 {
80        self.clock_domain_id
81    }
82
83    pub const fn restart_epoch(self) -> u32 {
84        self.restart_epoch
85    }
86
87    pub const fn ticks_ns(self) -> u64 {
88        self.ticks_ns
89    }
90
91    pub const fn uncertainty_ns(self) -> u64 {
92        self.uncertainty_ns
93    }
94}
95
96/// Versioned signed evidence record. Fields are private to prevent post-signing
97/// mutation outside the module; use `verify` before consuming it.
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub struct SignedSensingEvidence {
100    version: u16,
101    evidence: SensingEvidence,
102    grant_id: [u8; 32],
103    grant_digest: [u8; 32],
104    decision_commitment: [u8; 32],
105    adapter_id: u64,
106    adapter_epoch: u32,
107    capture_time: CaptureTimestamp,
108    calibration_reference_id: [u8; 32],
109    calibration_artifact_commitment: [u8; 32],
110    payload_digest: [u8; 32],
111    signature: [u8; 64],
112}
113
114impl SignedSensingEvidence {
115    #[allow(clippy::too_many_arguments)]
116    pub fn sign(
117        evidence: SensingEvidence,
118        grant_id: [u8; 32],
119        grant_digest: [u8; 32],
120        decision_commitment: [u8; 32],
121        adapter_id: u64,
122        adapter_epoch: u32,
123        capture_time: CaptureTimestamp,
124        calibration_reference_id: [u8; 32],
125        calibration_artifact_commitment: [u8; 32],
126        payload_digest: [u8; 32],
127        signing_key: &SigningKey,
128    ) -> Result<Self, SignedEvidenceError> {
129        if all_zero(&grant_id)
130            || all_zero(&grant_digest)
131            || all_zero(&decision_commitment)
132            || adapter_id == 0
133        {
134            return Err(SignedEvidenceError::InvalidIdentifier);
135        }
136        if all_zero(&payload_digest) {
137            return Err(SignedEvidenceError::InvalidPayloadDigest);
138        }
139        let calibrated = matches!(
140            evidence.calibration(),
141            CalibrationDeclaration::Calibrated(_)
142        );
143        if calibrated != !all_zero(&calibration_artifact_commitment) {
144            return Err(SignedEvidenceError::InvalidCalibrationCommitment);
145        }
146        if !calibration_reference_matches(&evidence, &calibration_reference_id) {
147            return Err(SignedEvidenceError::InvalidCalibrationReference);
148        }
149        if let EvidenceUncertainty::RelativeMillionths(value) = evidence.uncertainty() {
150            if value > super::grounding::UNCERTAINTY_SCALE {
151                return Err(SignedEvidenceError::InvalidEvidence);
152            }
153        }
154
155        let mut envelope = Self {
156            version: SIGNED_SENSING_EVIDENCE_VERSION,
157            evidence,
158            grant_id,
159            grant_digest,
160            decision_commitment,
161            adapter_id,
162            adapter_epoch,
163            capture_time,
164            calibration_reference_id,
165            calibration_artifact_commitment,
166            payload_digest,
167            signature: [0; 64],
168        };
169        envelope.signature = signing_key.sign(&envelope.canonical_digest()).to_bytes();
170        Ok(envelope)
171    }
172
173    pub const fn version(self) -> u16 {
174        self.version
175    }
176
177    pub const fn evidence(self) -> SensingEvidence {
178        self.evidence
179    }
180
181    pub const fn grant_id(self) -> [u8; 32] {
182        self.grant_id
183    }
184
185    pub const fn grant_digest(self) -> [u8; 32] {
186        self.grant_digest
187    }
188
189    pub const fn decision_commitment(self) -> [u8; 32] {
190        self.decision_commitment
191    }
192
193    pub const fn adapter_id(self) -> u64 {
194        self.adapter_id
195    }
196
197    pub const fn adapter_epoch(self) -> u32 {
198        self.adapter_epoch
199    }
200
201    pub const fn capture_time(self) -> CaptureTimestamp {
202        self.capture_time
203    }
204
205    pub const fn calibration_artifact_commitment(self) -> [u8; 32] {
206        self.calibration_artifact_commitment
207    }
208
209    pub const fn calibration_reference_id(self) -> [u8; 32] {
210        self.calibration_reference_id
211    }
212
213    pub const fn payload_digest(self) -> [u8; 32] {
214        self.payload_digest
215    }
216
217    pub const fn signature(self) -> [u8; 64] {
218        self.signature
219    }
220
221    /// Encode the fixed v1 transport record into caller storage. Insufficient
222    /// output leaves the buffer untouched. Parsing does not imply trust.
223    pub fn encode_to(&self, out: &mut [u8]) -> Result<usize, SignedEvidenceError> {
224        wire::encode(self, out)
225    }
226
227    /// Parse an exact v1 transport record into an unverified envelope.
228    pub fn decode_from(input: &[u8]) -> Result<Self, SignedEvidenceError> {
229        wire::decode(input)
230    }
231
232    /// Canonical digest with a versioned domain separator and explicit
233    /// little-endian field encodings. The raw NQuin parity word is bound exactly
234    /// as stored; this does not select either conflicting parity convention.
235    pub fn canonical_digest(&self) -> [u8; 32] {
236        let e = self.evidence;
237        let q = e.assertion();
238        let mut hash = Sha256::new();
239        hash.update(SIGNING_DOMAIN);
240        hash.update(WIRE_MAGIC);
241        hash.update(self.version.to_le_bytes());
242        hash.update((SIGNED_SENSING_EVIDENCE_WIRE_SIZE as u16).to_le_bytes());
243        hash.update(e.citation_id().to_le_bytes());
244        hash.update(e.source_id().to_le_bytes());
245        hash.update(e.sample_id().to_le_bytes());
246        hash.update(q.subject.to_le_bytes());
247        hash.update(q.predicate.to_le_bytes());
248        hash.update(q.object.to_le_bytes());
249        hash.update(q.context.to_le_bytes());
250        hash.update(q.metadata.to_le_bytes());
251        hash.update(q.parity.to_le_bytes());
252        hash.update(e.physical_quantity_id().to_le_bytes());
253        hash.update(e.unit_id().to_le_bytes());
254        match e.uncertainty() {
255            EvidenceUncertainty::Unknown => hash.update([0]),
256            EvidenceUncertainty::RelativeMillionths(value) => {
257                hash.update([1]);
258                hash.update(value.to_le_bytes());
259            }
260        }
261        hash.update([calibration_tag(e.calibration())]);
262        hash.update(self.calibration_reference_id);
263        hash.update(self.grant_id);
264        hash.update(self.grant_digest);
265        hash.update(self.decision_commitment);
266        hash.update(self.adapter_id.to_le_bytes());
267        hash.update(self.adapter_epoch.to_le_bytes());
268        hash.update(self.capture_time.clock_domain_id.to_le_bytes());
269        hash.update(self.capture_time.restart_epoch.to_le_bytes());
270        hash.update(self.capture_time.ticks_ns.to_le_bytes());
271        hash.update(self.capture_time.uncertainty_ns.to_le_bytes());
272        hash.update(self.calibration_artifact_commitment);
273        hash.update(self.payload_digest);
274        hash.finalize().into()
275    }
276
277    /// Verify signature and policy using a fresh reading from the trusted clock.
278    /// This authenticates origin and authorized use only; it does not establish
279    /// truth. Implementations must fail closed when current UTC is unavailable.
280    pub fn verify(
281        &self,
282        evidence: &SensingEvidence,
283        policy: &dyn SignedEvidencePolicy,
284        clock: &dyn TrustedEvidenceClock,
285    ) -> Result<(), SignedEvidenceError> {
286        let now_unix_seconds = clock
287            .now_unix_seconds()
288            .ok_or(SignedEvidenceError::ClockUnavailable)?;
289        self.verify_at(evidence, policy, now_unix_seconds)
290    }
291
292    fn verify_at(
293        &self,
294        evidence: &SensingEvidence,
295        policy: &dyn SignedEvidencePolicy,
296        now_unix_seconds: u64,
297    ) -> Result<(), SignedEvidenceError> {
298        if self.version != SIGNED_SENSING_EVIDENCE_VERSION || &self.evidence != evidence {
299            return Err(SignedEvidenceError::EvidenceMismatch);
300        }
301        if !calibration_reference_matches(evidence, &self.calibration_reference_id) {
302            return Err(SignedEvidenceError::InvalidCalibrationReference);
303        }
304        if !policy.calibration_commitment_matches(
305            evidence,
306            &self.calibration_reference_id,
307            &self.calibration_artifact_commitment,
308        ) {
309            return Err(SignedEvidenceError::InvalidCalibrationCommitment);
310        }
311        if !policy.payload_digest_matches(evidence, &self.payload_digest) {
312            return Err(SignedEvidenceError::InvalidPayloadDigest);
313        }
314        let key = policy
315            .authorized_source_key(evidence.source_id(), self.adapter_id, self.adapter_epoch)
316            .ok_or(SignedEvidenceError::UnauthorizedSource)?;
317        let signature = Signature::from_bytes(&self.signature);
318        key.verify_strict(&self.canonical_digest(), &signature)
319            .map_err(|_| SignedEvidenceError::InvalidSignature)?;
320        if !policy.grant_and_decision_valid(
321            self,
322            evidence,
323            &self.grant_id,
324            &self.grant_digest,
325            &self.decision_commitment,
326            now_unix_seconds,
327        ) {
328            return Err(SignedEvidenceError::GrantOrRevocationDenied);
329        }
330        Ok(())
331    }
332}
333
334/// Trusted caller policy. Implementations must verify exact grant/decision
335/// binding and current revocation state, source-key authorization for this
336/// source/adapter/epoch tuple, and calibration reference-to-digest identity.
337/// These hooks do not assert that a correctly signed sensor statement is
338/// physically true.
339pub trait SignedSensingEvidencePolicy {
340    fn authorized_source_key(
341        &self,
342        source_id: u64,
343        adapter_id: u64,
344        adapter_epoch: u32,
345    ) -> Option<VerifyingKey>;
346
347    fn grant_and_decision_valid(
348        &self,
349        envelope: &SignedSensingEvidence,
350        evidence: &SensingEvidence,
351        grant_id: &[u8; 32],
352        grant_digest: &[u8; 32],
353        decision_commitment: &[u8; 32],
354        now_unix_seconds: u64,
355    ) -> bool;
356
357    fn calibration_commitment_matches(
358        &self,
359        evidence: &SensingEvidence,
360        calibration_reference_id: &[u8; 32],
361        calibration_artifact_commitment: &[u8; 32],
362    ) -> bool;
363
364    /// Verify this digest against the exact immutable payload bytes referenced
365    /// by the evidence. A signature over a caller-asserted digest is not enough.
366    fn payload_digest_matches(&self, evidence: &SensingEvidence, payload_digest: &[u8; 32])
367        -> bool;
368
369    fn calibration_artifact_verified(
370        &self,
371        envelope: &SignedSensingEvidence,
372        evidence: &SensingEvidence,
373        now_unix_seconds: u64,
374    ) -> bool;
375}
376
377/// Alias retained for the narrower verification contract named in the task.
378pub use SignedSensingEvidencePolicy as SignedEvidencePolicy;
379
380/// Trusted current UTC source used for grant expiry checks.
381///
382/// Implementations must return `None` when UTC cannot be established. The
383/// value is sampled once for each verification call, never cached by the
384/// authenticator. It is distinct from the signed monotonic capture clock.
385pub trait TrustedEvidenceClock {
386    fn now_unix_seconds(&self) -> Option<u64>;
387}
388
389/// Binds one signed envelope to trusted policy and samples trusted time on each
390/// authentication or calibration check.
391pub struct SignedEvidenceAuthenticator<'a> {
392    envelope: &'a SignedSensingEvidence,
393    policy: &'a dyn SignedEvidencePolicy,
394    clock: &'a dyn TrustedEvidenceClock,
395}
396
397impl<'a> SignedEvidenceAuthenticator<'a> {
398    pub const fn new(
399        envelope: &'a SignedSensingEvidence,
400        policy: &'a dyn SignedEvidencePolicy,
401        clock: &'a dyn TrustedEvidenceClock,
402    ) -> Self {
403        Self {
404            envelope,
405            policy,
406            clock,
407        }
408    }
409}
410
411impl SensingEvidenceAuthenticator for SignedEvidenceAuthenticator<'_> {
412    fn authenticates(&self, evidence: &SensingEvidence) -> bool {
413        self.envelope
414            .verify(evidence, self.policy, self.clock)
415            .is_ok()
416    }
417
418    fn calibration_verified(&self, evidence: &SensingEvidence) -> bool {
419        let Some(now_unix_seconds) = self.clock.now_unix_seconds() else {
420            return false;
421        };
422        self.envelope
423            .verify_at(evidence, self.policy, now_unix_seconds)
424            .is_ok()
425            && matches!(
426                evidence.calibration(),
427                CalibrationDeclaration::Calibrated(_)
428            )
429            && self
430                .policy
431                .calibration_artifact_verified(self.envelope, evidence, now_unix_seconds)
432    }
433}
434
435fn calibration_tag(calibration: CalibrationDeclaration) -> u8 {
436    match calibration {
437        CalibrationDeclaration::Unknown => 0,
438        CalibrationDeclaration::Missing => 1,
439        CalibrationDeclaration::Expired => 2,
440        CalibrationDeclaration::OutOfRange => 3,
441        CalibrationDeclaration::Uncalibrated => 4,
442        CalibrationDeclaration::Calibrated(_) => 5,
443    }
444}
445
446fn calibration_reference_matches(evidence: &SensingEvidence, reference_id: &[u8; 32]) -> bool {
447    match evidence.calibration() {
448        CalibrationDeclaration::Calibrated(reference) => {
449            CalibrationArtifactReference::new(*reference_id) == Ok(reference)
450        }
451        _ => all_zero(reference_id),
452    }
453}
454
455fn all_zero(bytes: &[u8; 32]) -> bool {
456    bytes.iter().all(|&byte| byte == 0)
457}
458
459#[derive(Clone, Copy, Debug, PartialEq, Eq)]
460pub enum SignedEvidenceError {
461    InvalidIdentifier,
462    InvalidTimestamp,
463    InvalidPayloadDigest,
464    InvalidCalibrationCommitment,
465    InvalidCalibrationReference,
466    InvalidEvidence,
467    EvidenceMismatch,
468    UnauthorizedSource,
469    InvalidSignature,
470    GrantOrRevocationDenied,
471    OutputTooSmall,
472    InvalidWireLength,
473    InvalidWireHeader,
474    UnsupportedVersion,
475    ClockUnavailable,
476}