a2a_protocol_types/audit/
chain.rs1use super::checkpoint::{Checkpoint, TrustedKey, verify_checkpoint};
9use super::record::{AuditRecord, SCHEMA};
10
11#[derive(Debug, Clone, PartialEq, Eq)]
13#[non_exhaustive]
14pub struct ChainReport {
15 pub chain: String,
17 pub records: usize,
19 pub range: Option<(u64, u64)>,
21 pub anchored_at: Option<u64>,
24 pub checkpoints_verified: usize,
26 pub signed_through: Option<u64>,
29 pub failure: Option<ChainFailure>,
31}
32
33impl ChainReport {
34 #[must_use]
36 pub const fn is_intact(&self) -> bool {
37 self.failure.is_none()
38 }
39
40 #[must_use]
42 pub const fn unsigned_tail(&self) -> u64 {
43 match (self.range, self.signed_through) {
44 (Some((_, last)), Some(signed)) => last.saturating_sub(signed),
45 (Some((first, last)), None) => last - first + 1,
46 (None, _) => 0,
47 }
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53#[non_exhaustive]
54pub struct ChainFailure {
55 pub seq: u64,
57 pub reason: String,
59}
60
61#[must_use]
81pub fn verify_chain(
82 records: &[AuditRecord],
83 checkpoints: &[Checkpoint],
84 keys: &[TrustedKey],
85) -> ChainReport {
86 let chain = records
87 .first()
88 .map_or_else(String::new, |r| r.chain.clone());
89 let mut report = ChainReport {
90 chain,
91 records: records.len(),
92 range: records
93 .first()
94 .zip(records.last())
95 .map(|(a, b)| (a.seq, b.seq)),
96 anchored_at: None,
97 checkpoints_verified: 0,
98 signed_through: None,
99 failure: None,
100 };
101 report.failure = check_records(records, checkpoints, keys, &mut report)
102 .or_else(|| check_checkpoints(records, checkpoints, keys, &mut report));
103 report
104}
105
106fn failure(seq: u64, reason: impl Into<String>) -> ChainFailure {
107 ChainFailure {
108 seq,
109 reason: reason.into(),
110 }
111}
112
113fn check_records(
115 records: &[AuditRecord],
116 checkpoints: &[Checkpoint],
117 keys: &[TrustedKey],
118 report: &mut ChainReport,
119) -> Option<ChainFailure> {
120 let chain = report.chain.clone();
121 for (i, r) in records.iter().enumerate() {
122 if r.schema != SCHEMA {
123 return Some(failure(r.seq, format!("unknown schema {:?}", r.schema)));
124 }
125 if r.chain != chain {
126 return Some(failure(
127 r.seq,
128 format!("record of chain {:?} in chain {chain:?}", r.chain),
129 ));
130 }
131 match r.compute_hash() {
132 Ok(h) if h == r.hash => {}
133 Ok(_) => return Some(failure(r.seq, "content does not match its hash")),
134 Err(e) => return Some(failure(r.seq, format!("cannot be hashed: {e}"))),
135 }
136 if i == 0 {
137 let expected = if r.seq == 1 {
138 None
139 } else {
140 let anchor = checkpoints
141 .iter()
142 .find(|c| c.kind == "anchor" && c.chain == chain && c.seq == r.seq - 1);
143 let Some(anchor) = anchor else {
144 return Some(failure(
145 r.seq,
146 format!("chain starts at {} with no anchor for {}", r.seq, r.seq - 1),
147 ));
148 };
149 if let Err(e) = verify_checkpoint(anchor, keys) {
150 return Some(failure(anchor.seq, format!("anchor: {e}")));
151 }
152 report.anchored_at = Some(anchor.seq);
153 Some(anchor.hash.clone())
154 };
155 if r.prev != expected {
156 return Some(failure(r.seq, "prev does not match the chain's start"));
157 }
158 } else {
159 let before = &records[i - 1];
160 if r.seq != before.seq + 1 {
161 return Some(failure(
162 r.seq,
163 format!("follows {} — records are missing or reordered", before.seq),
164 ));
165 }
166 if r.prev.as_deref() != Some(before.hash.as_str()) {
167 return Some(failure(r.seq, "prev is not the hash of the record before"));
168 }
169 }
170 }
171 None
172}
173
174fn check_checkpoints(
176 records: &[AuditRecord],
177 checkpoints: &[Checkpoint],
178 keys: &[TrustedKey],
179 report: &mut ChainReport,
180) -> Option<ChainFailure> {
181 let (first, last) = report.range.unwrap_or((1, 0));
182 for c in checkpoints
183 .iter()
184 .filter(|c| c.chain == report.chain && c.kind != "anchor")
185 {
186 if c.seq > last {
187 return Some(failure(
188 c.seq,
189 format!(
190 "a checkpoint vouches for seq {} but the records end at {last}: the tail was removed",
191 c.seq
192 ),
193 ));
194 }
195 if c.seq < first {
196 continue;
197 }
198 #[allow(clippy::cast_possible_truncation)]
199 let at = &records[(c.seq - first) as usize];
200 if at.hash != c.hash {
201 return Some(failure(
202 c.seq,
203 "checkpoint names a different hash than the record has",
204 ));
205 }
206 if let Err(e) = verify_checkpoint(c, keys) {
207 return Some(failure(c.seq, format!("checkpoint: {e}")));
208 }
209 report.checkpoints_verified += 1;
210 report.signed_through = Some(report.signed_through.map_or(c.seq, |s| s.max(c.seq)));
211 }
212 None
213}