1use proof_core::model::{
10 AttestationContent, Claim, EventContent, EventType, EvidenceKind, MetaValue, Proposition,
11 RelType, Relationship,
12};
13use proof_core::{HashAlgorithm, HashRef, LifecycleStatus, Limits};
14use proof_crypto::build::{
15 attest, create_event, fixtures, make_evidence, make_relationship, revoke_attestation,
16};
17use proof_crypto::SignedStatus;
18use proof_policy::explain_report;
19use proof_verify::{verify_proof, BuiltProof, ProofBuilder, Validity, VerifyCtx};
20
21const T_EVENT: u64 = 1_700_000_000;
22const T_ATTEST: u64 = 1_700_000_150;
23const T_BUILT: u64 = 1_700_000_200;
24const T_FRESH: u64 = 1_700_000_300;
25const T_REVOKED: u64 = 1_700_000_400;
26const T_AFTER: u64 = 1_700_000_500;
27
28fn write_json(path: &str, v: serde_json::Value) -> Result<(), String> {
29 std::fs::write(
30 path,
31 serde_json::to_string_pretty(&v).map_err(|e| e.to_string())?
32 + "
33",
34 )
35 .map_err(|e| format!("write {path}: {e}"))
36}
37
38pub fn run(out_dir: &str) -> Result<i32, String> {
40 let lim = Limits::default();
41 std::fs::create_dir_all(out_dir).map_err(|e| format!("mkdir {out_dir}: {e}"))?;
42 let key = fixtures::test_key();
43
44 println!("== Proof Engine demo: a proof that dies (ARCHITECTURE §8) ==");
45 println!("[1] creating payment + invoice events (t={T_EVENT})");
46 let event = |t: EventType, subject: &str| -> Result<EventContent, String> {
47 Ok(EventContent {
48 v: 1,
49 event_type: t,
50 subject: subject.into(),
51 effective_at: T_EVENT,
52 payload_ref: HashRef::new(HashAlgorithm::Sha256, vec![0x5Eu8; 32])
53 .map_err(|e| e.to_string())?,
54 metadata: vec![("order".into(), MetaValue::Text("ord-demo-1".into()))],
55 })
56 };
57 let pay = create_event(
58 event(EventType::new(EventType::PAYMENT_CREATED), "payment:p-demo")?,
59 &lim,
60 )
61 .map_err(|e| e.to_string())?;
62 let inv = create_event(
63 event(EventType::new(EventType::INVOICE_ISSUED), "invoice:i-demo")?,
64 &lim,
65 )
66 .map_err(|e| e.to_string())?;
67
68 println!(
69 "[2] merchant attests `payment.settled` over {} (t={T_ATTEST})",
70 pay.id
71 );
72 let att = attest(
73 AttestationContent {
74 v: 1,
75 issuer: key.key_ref(),
76 subject: "payment:p-demo".into(),
77 claim: Claim {
78 claim_type: "payment.settled".into(),
79 fields: vec![
80 ("amount".into(), MetaValue::Uint(4200)),
81 ("currency".into(), MetaValue::Text("EUR".into())),
82 ],
83 },
84 issued_at: T_ATTEST,
85 expires_at: None,
86 evidence_ref: None,
87 },
88 &key,
89 &lim,
90 )
91 .map_err(|e| e.to_string())?;
92
93 println!("[3] grounding evidence + SETTLES edge");
94 let evd = make_evidence(
95 EvidenceKind::new(EvidenceKind::TRANSACTION_RECORD),
96 HashRef::new(HashAlgorithm::Sha256, vec![0xE1u8; 32]).map_err(|e| e.to_string())?,
97 Some(att.id.clone()),
98 Some("acquirer:receipt:demo".into()),
99 &lim,
100 )
101 .map_err(|e| e.to_string())?;
102 let edge = make_relationship(
103 Relationship {
104 v: 1,
105 rel_type: RelType::new(RelType::SETTLES),
106 from: pay.id.clone(),
107 to: inv.id.clone(),
108 evidence_ref: Some(evd.id.clone()),
109 attestation_ref: None,
110 },
111 &lim,
112 )
113 .map_err(|e| e.to_string())?;
114
115 let build_once = || -> Result<BuiltProof, String> {
116 let mut b = ProofBuilder::new(
117 Proposition {
118 v: 1,
119 kind: "payment.settles-invoice".into(),
120 subject: "payment:p-demo".into(),
121 predicate: "settles".into(),
122 object: Some("invoice:i-demo".into()),
123 at_time: Some(T_ATTEST),
124 context: vec![],
125 },
126 T_BUILT,
127 );
128 b.add_event(pay.clone());
129 b.add_event(inv.clone());
130 b.add_attestation(att.clone());
131 b.add_evidence(evd.clone());
132 b.add_relationship(edge.clone());
133 b.build(&lim).map_err(|e| e.to_string())
134 };
135 let built = build_once()?;
136
137 println!("[4] determinism: rebuilding from scratch must reproduce identical bytes");
138 let rebuilt = build_once()?;
139 assert_eq!(built.id, rebuilt.id, "proof id must be deterministic");
140 assert_eq!(
141 built.canonical, rebuilt.canonical,
142 "proof bytes must be deterministic"
143 );
144 println!(" proof {} — identical on rebuild ✓", built.id);
145
146 let proof_path = format!("{out_dir}/proof.cbor.json");
147 crate::artifact::write_proof_file(&proof_path, &built.id, &built.canonical)?;
148 println!(" wrote {proof_path}");
149
150 println!("[5] fresh verification (clock={T_FRESH}, revocations known to {T_FRESH})");
151 let fresh = verify_proof(
152 &built.canonical,
153 &VerifyCtx {
154 verified_at: T_FRESH,
155 clock_skew_leeway: 300,
156 revocations_known_at: Some(T_FRESH),
157 ..VerifyCtx::default()
158 },
159 )
160 .map_err(|e| e.to_string())?;
161 assert_eq!(fresh.cryptographic_validity, Validity::Valid);
162 assert_eq!(fresh.evidence_validity, Validity::Valid);
163 assert!(fresh
164 .lifecycle
165 .iter()
166 .all(|l| l.status == LifecycleStatus::Active));
167 println!(" verdict: PASS (exit 0) — crypto valid, evidence valid, attestation ACTIVE");
168 write_json(
169 &format!("{out_dir}/report-fresh.json"),
170 serde_json::json!({
171 "when": T_FRESH,
172 "cryptographic_validity": "valid",
173 "evidence_validity": "valid",
174 "policy_decision": fresh.policy_decision.as_str(),
175 "lifecycle": fresh.lifecycle.iter().map(|l| l.status.as_str()).collect::<Vec<_>>(),
176 }),
177 )?;
178
179 println!("[6] tamper: flip one byte of the attested subject, re-verify the same way");
180 let needle = b"invoice:i-demo";
181 let pos = built
182 .canonical
183 .windows(needle.len())
184 .position(|w| w == needle)
185 .expect("subject bytes present in canonical proof");
186 let mut tampered = built.canonical.clone();
187 tampered[pos] ^= 0x01;
188 let bad = verify_proof(
189 &tampered,
190 &VerifyCtx {
191 verified_at: T_FRESH,
192 clock_skew_leeway: 300,
193 revocations_known_at: Some(T_FRESH),
194 ..VerifyCtx::default()
195 },
196 )
197 .map_err(|e| e.to_string())?;
198 assert_eq!(
199 bad.cryptographic_validity,
200 Validity::Invalid,
201 "tamper must break crypto"
202 );
203 assert!(bad
204 .failure_codes()
205 .contains(&proof_core::ErrorCode::IdMismatch));
206 println!(
207 " verdict: FAIL (exit 1) — proof id no longer binds the bytes: {:?}",
208 bad.failure_codes()
209 );
210
211 println!("[7] merchant revokes their own attestation (t={T_REVOKED})");
212 let rev = revoke_attestation(
213 &att.id,
214 Some("chargeback: order cancelled"),
215 &key,
216 T_REVOKED,
217 &lim,
218 )
219 .map_err(|e| e.to_string())?;
220 let status_path = format!("{out_dir}/status-revoke.json");
221 write_json(
222 &status_path,
223 serde_json::json!({
224 "kind": "status",
225 "id": rev.id,
226 "issuer": rev.content.issuer,
227 "claim_type": rev.content.claim.claim_type,
228 "cbor": hex::encode(&rev.canonical),
229 "sign1_b64": proof_crypto::id::b64u_nopad(&rev.sign1),
230 }),
231 )?;
232 println!(" wrote {status_path}");
233
234 println!("[8] re-verification after revocation (clock={T_AFTER}, status object supplied)");
235 let dead = verify_proof(
236 &built.canonical,
237 &VerifyCtx {
238 verified_at: T_AFTER,
239 clock_skew_leeway: 300,
240 status_objects: vec![SignedStatus {
241 content: rev.content.clone(),
242 sign1: rev.sign1.clone(),
243 }],
244 revocations_known_at: Some(T_AFTER),
245 ..VerifyCtx::default()
246 },
247 )
248 .map_err(|e| e.to_string())?;
249 assert_eq!(
250 dead.cryptographic_validity,
251 Validity::Valid,
252 "crypto must stay valid"
253 );
254 assert_eq!(
255 dead.evidence_validity,
256 Validity::Invalid,
257 "revocation kills the proof"
258 );
259 assert!(dead
260 .failure_codes()
261 .contains(&proof_core::ErrorCode::Revoked));
262 println!(
263 " verdict: FAIL (exit 1) — same bytes, crypto still valid, attestation REVOKED: {:?}",
264 dead.failure_codes()
265 );
266 write_json(
267 &format!("{out_dir}/report.json"),
268 serde_json::json!({
269 "when": T_AFTER,
270 "cryptographic_validity": "valid",
271 "evidence_validity": "invalid",
272 "policy_decision": dead.policy_decision.as_str(),
273 "lifecycle": dead.lifecycle.iter().map(|l| l.status.as_str()).collect::<Vec<_>>(),
274 "failure_codes": dead.failure_codes().iter().map(|c| c.as_str()).collect::<Vec<_>>(),
275 }),
276 )?;
277
278 let explanation = format!(
279 "== fresh (t={T_FRESH}) ==
280{}
281== after revocation (t={T_AFTER}) ==
282{}
283",
284 explain_report(&fresh),
285 explain_report(&dead),
286 );
287 std::fs::write(format!("{out_dir}/explanation.txt"), explanation)
288 .map_err(|e| format!("write explanation: {e}"))?;
289 std::fs::write(format!("{out_dir}/proof.cbor"), &built.canonical)
293 .map_err(|e| format!("write proof.cbor: {e}"))?;
294 println!(
295 "[9] artifacts in {out_dir}: proof.cbor, report.json, explanation.txt (+ CLI wrappers)"
296 );
297 println!("demo complete: one signing event turned PASS into REVOKED. Deterministic: rerun reproduces every byte.");
298 Ok(crate::EXIT_OK)
299}