Skip to main content

proof_core/
model.rs

1// Copyright 2026 Proof Engine Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//! Minimal domain model (V1.0 NEUTRAL). Open vocabularies; policy controls acceptance.
4//!
5//! DESIGN: EventType, EvidenceKind, and RelType are opaque string wrappers.
6//! The core provides well-known constants for convenience, but accepts ANY string.
7//! Unknown types are NOT rejected at schema stage—validation is the policy's job.
8//!
9//! This achieves true neutrality: healthcare, logistics, AI, and 100 other domains
10//! can extend the vocabulary without modifying proof-core.
11
12use crate::HashRef;
13use std::hash::{Hash, Hasher};
14
15/// Event type (open vocabulary). The core transports any string; policy decides
16/// which types are acceptable. Well-known V1 types provided as constants.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct EventType(String);
19
20impl EventType {
21    // Well-known V1 types (for convenience, NOT exhaustive)
22    pub const PAYMENT_CREATED: &'static str = "payment.created";
23    pub const PAYMENT_COMPLETED: &'static str = "payment.completed";
24    pub const INVOICE_ISSUED: &'static str = "invoice.issued";
25    pub const DOCUMENT_SIGNED: &'static str = "document.signed";
26    pub const PACKAGE_SHIPPED: &'static str = "package.shipped";
27    pub const SENSOR_MEASUREMENT_RECORDED: &'static str = "sensor.measurement.recorded";
28    pub const AI_ACTION_EXECUTED: &'static str = "ai.action.executed";
29
30    /// Create from any string. No validation at this layer—policy decides acceptance.
31    pub fn new(s: impl Into<String>) -> Self {
32        Self(s.into())
33    }
34
35    /// Get the underlying string value.
36    pub fn as_str(&self) -> &str {
37        &self.0
38    }
39
40    /// Check if this is a well-known V1 type (for monitoring/telemetry, not validation).
41    pub fn is_well_known(&self) -> bool {
42        matches!(
43            self.0.as_str(),
44            Self::PAYMENT_CREATED
45                | Self::PAYMENT_COMPLETED
46                | Self::INVOICE_ISSUED
47                | Self::DOCUMENT_SIGNED
48                | Self::PACKAGE_SHIPPED
49                | Self::SENSOR_MEASUREMENT_RECORDED
50                | Self::AI_ACTION_EXECUTED
51        )
52    }
53}
54
55impl From<&str> for EventType {
56    fn from(s: &str) -> Self {
57        Self(s.to_string())
58    }
59}
60
61impl From<String> for EventType {
62    fn from(s: String) -> Self {
63        Self(s)
64    }
65}
66
67impl AsRef<str> for EventType {
68    fn as_ref(&self) -> &str {
69        &self.0
70    }
71}
72
73impl Hash for EventType {
74    fn hash<H: Hasher>(&self, state: &mut H) {
75        self.0.hash(state);
76    }
77}
78
79/// Evidence kind (open vocabulary). Policy controls which kinds are acceptable.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct EvidenceKind(String);
82
83impl EvidenceKind {
84    // Well-known V1 kinds
85    pub const SIGNED_EVENT: &'static str = "signed_event";
86    pub const SIGNED_DOCUMENT: &'static str = "signed_document";
87    pub const RECEIPT: &'static str = "receipt";
88    pub const CREDENTIAL: &'static str = "credential";
89    pub const MEASUREMENT: &'static str = "measurement";
90    pub const TRANSACTION_RECORD: &'static str = "transaction_record";
91    pub const TRANSPARENCY_RECEIPT: &'static str = "transparency_receipt";
92    pub const DEVICE_ATTESTATION: &'static str = "device_attestation";
93    pub const EXTERNAL_REFERENCE: &'static str = "external_reference";
94
95    pub fn new(s: impl Into<String>) -> Self {
96        Self(s.into())
97    }
98
99    pub fn as_str(&self) -> &str {
100        &self.0
101    }
102
103    pub fn is_well_known(&self) -> bool {
104        matches!(
105            self.0.as_str(),
106            Self::SIGNED_EVENT
107                | Self::SIGNED_DOCUMENT
108                | Self::RECEIPT
109                | Self::CREDENTIAL
110                | Self::MEASUREMENT
111                | Self::TRANSACTION_RECORD
112                | Self::TRANSPARENCY_RECEIPT
113                | Self::DEVICE_ATTESTATION
114                | Self::EXTERNAL_REFERENCE
115        )
116    }
117}
118
119impl From<&str> for EvidenceKind {
120    fn from(s: &str) -> Self {
121        Self(s.to_string())
122    }
123}
124
125impl From<String> for EvidenceKind {
126    fn from(s: String) -> Self {
127        Self(s)
128    }
129}
130
131impl AsRef<str> for EvidenceKind {
132    fn as_ref(&self) -> &str {
133        &self.0
134    }
135}
136
137impl Hash for EvidenceKind {
138    fn hash<H: Hasher>(&self, state: &mut H) {
139        self.0.hash(state);
140    }
141}
142
143/// Relationship type (open vocabulary). Policy controls which types are acceptable.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct RelType(String);
146
147impl RelType {
148    // Well-known V1 types
149    pub const OWNS: &'static str = "OWNS";
150    pub const CREATED: &'static str = "CREATED";
151    pub const SETTLES: &'static str = "SETTLES";
152    pub const REFERENCES: &'static str = "REFERENCES";
153    pub const CONTAINS: &'static str = "CONTAINS";
154    pub const PRODUCED: &'static str = "PRODUCED";
155    pub const EXECUTED: &'static str = "EXECUTED";
156    pub const ISSUED: &'static str = "ISSUED";
157    pub const SUPERSEDES: &'static str = "SUPERSEDES";
158    pub const REVOKES: &'static str = "REVOKES";
159
160    pub fn new(s: impl Into<String>) -> Self {
161        Self(s.into())
162    }
163
164    pub fn as_str(&self) -> &str {
165        &self.0
166    }
167
168    /// Trust-relevant edges MUST carry backing evidence.
169    /// This list is part of V1 semantics and frozen for well-known types.
170    pub fn requires_grounding(&self) -> bool {
171        matches!(
172            self.0.as_str(),
173            Self::OWNS | Self::CREATED | Self::SETTLES | Self::EXECUTED
174        )
175    }
176
177    pub fn is_well_known(&self) -> bool {
178        matches!(
179            self.0.as_str(),
180            Self::OWNS
181                | Self::CREATED
182                | Self::SETTLES
183                | Self::REFERENCES
184                | Self::CONTAINS
185                | Self::PRODUCED
186                | Self::EXECUTED
187                | Self::ISSUED
188                | Self::SUPERSEDES
189                | Self::REVOKES
190        )
191    }
192}
193
194impl From<&str> for RelType {
195    fn from(s: &str) -> Self {
196        Self(s.to_string())
197    }
198}
199
200impl From<String> for RelType {
201    fn from(s: String) -> Self {
202        Self(s)
203    }
204}
205
206impl AsRef<str> for RelType {
207    fn as_ref(&self) -> &str {
208        &self.0
209    }
210}
211
212impl Hash for RelType {
213    fn hash<H: Hasher>(&self, state: &mut H) {
214        self.0.hash(state);
215    }
216}
217
218/// Event content (without id). `metadata` is flat string→scalar, max 16 entries.
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub struct EventContent {
221    pub v: u8,
222    pub event_type: EventType,
223    pub subject: String,
224    pub effective_at: u64,
225    pub payload_ref: HashRef,
226    pub metadata: Vec<(String, MetaValue)>,
227}
228
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub enum MetaValue {
231    Text(String),
232    Uint(u64),
233    Bool(bool),
234}
235
236/// Attestation content (without id and signature).
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub struct AttestationContent {
239    pub v: u8,
240    pub issuer: String,
241    pub subject: String,
242    pub claim: Claim,
243    pub issued_at: u64,
244    pub expires_at: Option<u64>,
245    pub evidence_ref: Option<String>,
246}
247
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub struct Claim {
250    pub claim_type: String,
251    pub fields: Vec<(String, MetaValue)>,
252}
253
254/// Evidence (without id). `digest` binds the material; `attestation_ref`
255/// and `hint` are optional references. IDs are derived, never stored.
256#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct Evidence {
258    pub v: u8,
259    pub kind: EvidenceKind,
260    pub digest: HashRef,
261    pub attestation_ref: Option<String>,
262    pub hint: Option<String>,
263}
264
265/// Relationship (without id): typed directed edge between object ids.
266/// `from`/`to` reference verified artifact ids (events, attestations, evidence,
267/// or external object ids known to the verifier). Trust-relevant types MUST
268/// carry `evidence_ref` or `attestation_ref` (enforced in `proof-graph`).
269#[derive(Debug, Clone, PartialEq, Eq)]
270pub struct Relationship {
271    pub v: u8,
272    pub from: String,
273    pub rel_type: RelType,
274    pub to: String,
275    pub evidence_ref: Option<String>,
276    pub attestation_ref: Option<String>,
277}
278
279/// Machine-readable proposition: what the proof attempts to establish.
280/// `description` (human text) is never authoritative and is not stored here.
281#[derive(Debug, Clone, PartialEq, Eq)]
282pub struct Proposition {
283    pub v: u8,
284    pub kind: String,
285    pub subject: String,
286    pub predicate: String,
287    pub object: Option<String>,
288    pub at_time: Option<u64>,
289    pub context: Vec<(String, MetaValue)>,
290}
291
292/// A stored attestation inside a Proof: content plus its COSE_Sign1 envelope.
293#[derive(Debug, Clone, PartialEq, Eq)]
294pub struct StoredAttestation {
295    pub content: AttestationContent,
296    pub sign1: Vec<u8>,
297}
298
299/// Portable proof package (without canonical bytes). `proof_id` binds the
300/// proposition plus the exact member id sets (see `proof-crypto::id`).
301/// `created_at` is informational only and is NOT covered by the id.
302#[derive(Debug, Clone, PartialEq, Eq)]
303pub struct Proof {
304    pub v: u8,
305    pub proof_id: String,
306    pub proposition: Proposition,
307    pub events: Vec<EventContent>,
308    pub attestations: Vec<StoredAttestation>,
309    pub evidence: Vec<Evidence>,
310    pub relationships: Vec<Relationship>,
311    pub created_at: u64,
312}
313
314/// Per-attestation lifecycle state, computed by verification stages TIME and
315/// REVOCATION (ARCHITECTURE §4, stages 7–8). Authority: the pipeline only.
316/// `SUPERSEDED` keeps evidence validity (historical record preserved); every
317/// other non-`ACTIVE` state fails closed.
318#[derive(Debug, Clone, Copy, PartialEq, Eq)]
319// PE-LIFE-001.
320pub enum LifecycleStatus {
321    /// Within validity and no valid revocation/supersession applies.
322    Active,
323    /// Outside its validity window at the verifier clock.
324    Expired,
325    /// Covered by a valid signed revocation.
326    Revoked,
327    /// Replaced by a newer attestation via a valid signed supersession.
328    Superseded,
329    /// Revocation information missing or stale — fail closed.
330    Unknown,
331}
332
333impl LifecycleStatus {
334    pub fn as_str(self) -> &'static str {
335        match self {
336            Self::Active => "ACTIVE",
337            Self::Expired => "EXPIRED",
338            Self::Revoked => "REVOKED",
339            Self::Superseded => "SUPERSEDED",
340            Self::Unknown => "UNKNOWN",
341        }
342    }
343
344    pub fn parse(s: &str) -> Option<Self> {
345        match s {
346            "ACTIVE" => Some(Self::Active),
347            "EXPIRED" => Some(Self::Expired),
348            "REVOKED" => Some(Self::Revoked),
349            "SUPERSEDED" => Some(Self::Superseded),
350            "UNKNOWN" => Some(Self::Unknown),
351            _ => None,
352        }
353    }
354}
355
356/// ID prefixes (wire format `<prefix>:v1:<b64uNoPad(sha256)>`).
357pub mod id_prefix {
358    pub const EVENT: &str = "evt";
359    pub const ATTESTATION: &str = "att";
360    pub const EVIDENCE: &str = "evd";
361    pub const REL: &str = "rel";
362    pub const PROOF: &str = "prf";
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368
369    #[test]
370    fn open_types_accept_any_string() {
371        // Well-known types work
372        let evt = EventType::new(EventType::PAYMENT_CREATED);
373        assert_eq!(evt.as_str(), "payment.created");
374        assert!(evt.is_well_known());
375
376        // Unknown types are accepted (neutrality principle)
377        let custom = EventType::new("healthcare.patient.admitted");
378        assert_eq!(custom.as_str(), "healthcare.patient.admitted");
379        assert!(!custom.is_well_known()); // Not in V1 list, but still valid
380
381        // Evidence kinds work the same way
382        let evd = EvidenceKind::new(EvidenceKind::TRANSPARENCY_RECEIPT);
383        assert_eq!(evd.as_str(), "transparency_receipt");
384        assert!(evd.is_well_known());
385
386        let custom_evd = EvidenceKind::new("medical_record");
387        assert!(!custom_evd.is_well_known()); // Unknown but accepted
388
389        // Relationship types too
390        let rel = RelType::new(RelType::SETTLES);
391        assert_eq!(rel.as_str(), "SETTLES");
392        assert!(rel.is_well_known());
393    }
394
395    #[test]
396    fn grounding_flags_work_with_strings() {
397        assert!(RelType::new(RelType::SETTLES).requires_grounding());
398        assert!(RelType::new(RelType::OWNS).requires_grounding());
399        assert!(RelType::new(RelType::CREATED).requires_grounding());
400        assert!(RelType::new(RelType::EXECUTED).requires_grounding());
401        assert!(!RelType::new(RelType::REFERENCES).requires_grounding());
402        assert!(!RelType::new(RelType::SUPERSEDES).requires_grounding());
403
404        // Unknown types don't match well-known grounding rules
405        assert!(!RelType::new("CUSTOM_REL").requires_grounding());
406    }
407
408    #[test]
409    fn lifecycle_status_closed_and_round_trip() {
410        // LifecycleStatus remains closed (pipeline-internal state machine)
411        for (s, expected) in [
412            ("ACTIVE", LifecycleStatus::Active),
413            ("EXPIRED", LifecycleStatus::Expired),
414            ("REVOKED", LifecycleStatus::Revoked),
415            ("SUPERSEDED", LifecycleStatus::Superseded),
416            ("UNKNOWN", LifecycleStatus::Unknown),
417        ] {
418            assert_eq!(LifecycleStatus::parse(s), Some(expected));
419            assert_eq!(expected.as_str(), s);
420        }
421        assert_eq!(LifecycleStatus::parse("PENDING"), None);
422    }
423
424    #[test]
425    fn extensibility_demonstration() {
426        // Healthcare domain can add types without modifying proof-core
427        let healthcare_evt = EventType::new("healthcare.surgery.scheduled");
428        let healthcare_evd = EvidenceKind::new("medical_imaging");
429        let healthcare_rel = RelType::new("DIAGNOSED_WITH");
430
431        // Logistics domain can add types without modifying proof-core
432        let logistics_evt = EventType::new("logistics.shipment.departed");
433        let logistics_evd = EvidenceKind::new("customs_declaration");
434        let logistics_rel = RelType::new("TRANSPORTED_VIA");
435
436        // AI domain can add types without modifying proof-core
437        let ai_evt = EventType::new("ai.model.trained");
438        let ai_evd = EvidenceKind::new("training_log");
439        let ai_rel = RelType::new("TRAINED_ON");
440
441        // All accepted at core layer; policy decides if they're valid
442        assert_eq!(healthcare_evt.as_str(), "healthcare.surgery.scheduled");
443        assert_eq!(healthcare_evd.as_str(), "medical_imaging");
444        assert_eq!(healthcare_rel.as_str(), "DIAGNOSED_WITH");
445        assert_eq!(logistics_evt.as_str(), "logistics.shipment.departed");
446        assert_eq!(logistics_evd.as_str(), "customs_declaration");
447        assert_eq!(logistics_rel.as_str(), "TRANSPORTED_VIA");
448        assert_eq!(ai_evt.as_str(), "ai.model.trained");
449        assert_eq!(ai_evd.as_str(), "training_log");
450        assert_eq!(ai_rel.as_str(), "TRAINED_ON");
451        // None are well-known V1 labels: extension happened without
452        // modifying proof-core — the neutrality property, by construction.
453        assert!(!healthcare_evt.is_well_known());
454        assert!(!healthcare_evd.is_well_known());
455        assert!(!healthcare_rel.is_well_known());
456        assert!(!logistics_evt.is_well_known());
457        assert!(!logistics_evd.is_well_known());
458        assert!(!logistics_rel.is_well_known());
459        assert!(!ai_evt.is_well_known());
460        assert!(!ai_evd.is_well_known());
461        assert!(!ai_rel.is_well_known());
462    }
463}