examples/tamper_detection.py
2.6 KB · 71 lines · python Raw
1 """Tamper-detection demo: build a trace, seal, tamper, show verification fails."""
2
3 from __future__ import annotations
4
5 from quantumshield.identity.agent import AgentIdentity
6
7 from pqc_reasoning_ledger import ReasoningRecorder, TraceVerifier
8
9
10 def main() -> None:
11 print("=" * 72)
12 print("PQC Reasoning Ledger - Tamper Detection Demo")
13 print("=" * 72)
14
15 identity = AgentIdentity.create("demo-signer")
16 rec = ReasoningRecorder(identity)
17 rec.begin_trace(
18 model_did="did:pqaid:demo-model",
19 model_version="1.0.0",
20 task="loan-underwriting",
21 domain="finance",
22 )
23
24 rec.record_observation("Applicant FICO score: 742; DTI ratio: 0.31")
25 rec.record_retrieval("Underwriting guideline v2.8, section 3.2 (prime credit)")
26 rec.record_hypothesis(
27 "Applicant meets prime-credit thresholds for the 30-year fixed product"
28 )
29 tampered_target = rec.record_deduction(
30 "FICO 742 >= 740 prime cutoff, DTI 0.31 < 0.36 cap -> prime eligible",
31 confidence=0.93,
32 )
33 rec.record_decision("APPROVE at posted prime rate")
34
35 print(f"\n[1] Built 5-step trace; target step_id = {tampered_target.step_id[-16:]}")
36
37 sealed = rec.seal()
38
39 print("\n[2] Verifying sealed trace as-delivered...\n")
40 pristine = TraceVerifier.verify(sealed)
41 print(f" signature_valid: {pristine.signature_valid}")
42 print(f" chain_intact: {pristine.chain_intact}")
43 print(f" merkle_root_valid: {pristine.merkle_root_valid}")
44 print(f" fully_verified: {pristine.fully_verified} <-- should be True")
45
46 print("\n[3] Adversary flips a single byte in step 4 content_hash...\n")
47 step_idx = 3 # zero-based index of the deduction step
48 original = sealed.steps[step_idx].content_hash
49 flipped = ("0" if original[0] != "0" else "f") + original[1:]
50 sealed.steps[step_idx].content_hash = flipped
51 print(f" before: {original[:32]}...")
52 print(f" after: {flipped[:32]}...")
53
54 print("\n[4] Verifying tampered trace...\n")
55 tampered = TraceVerifier.verify(sealed)
56 print(f" signature_valid: {tampered.signature_valid}")
57 print(f" chain_intact: {tampered.chain_intact} <-- now False")
58 print(f" merkle_root_valid: {tampered.merkle_root_valid}")
59 print(f" fully_verified: {tampered.fully_verified} <-- should be False")
60 print(f" error: {tampered.error}")
61
62 if not tampered.fully_verified:
63 print("\n [OK] a single flipped byte broke the chain -- tamper detected.")
64 else:
65 print("\n [FAIL] unexpected: tamper went undetected")
66 raise SystemExit(1)
67
68
69 if __name__ == "__main__":
70 main()
71