1use ciborium::value::Value;
65use serde::{Deserialize, Serialize};
66
67use crate::{PayError, UnitRef};
68
69pub const ATTESTATION_V1_TAG: &str = "hs-pay-settlement-attestation-v1";
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76pub struct SettlementAttestation {
77 pub issuer_did: String,
81 pub settlement_id: String,
84 pub unit: UnitRef,
86 pub destination_did: String,
88 pub amount_minor: u128,
90 pub grant_cid: Option<Vec<u8>>,
92 pub settled_at: u64,
94 pub signature: Vec<u8>,
96}
97
98impl SettlementAttestation {
99 pub fn signing_input(&self) -> Result<Vec<u8>, PayError> {
102 encode_canonical(&self.body_fields())
103 }
104
105 pub fn encode(&self) -> Result<Vec<u8>, PayError> {
109 let mut fields = self.body_fields();
110 fields.push(Value::Bytes(self.signature.clone()));
111 encode_canonical(&fields)
112 }
113
114 pub fn decode(bytes: &[u8]) -> Result<Self, PayError> {
120 let value: Value = ciborium::from_reader(bytes)
121 .map_err(|e| PayError::AttestationInvalid(format!("attestation is not CBOR: {e}")))?;
122 let items = match value {
123 Value::Array(items) => items,
124 _ => {
125 return Err(PayError::AttestationInvalid(
126 "attestation must be a CBOR array".to_owned(),
127 ))
128 }
129 };
130 if items.len() != 10 {
131 return Err(PayError::AttestationInvalid(format!(
132 "attestation must have 10 fields, found {}",
133 items.len()
134 )));
135 }
136 if text(&items[0])? != ATTESTATION_V1_TAG {
137 return Err(PayError::AttestationInvalid(
138 "attestation is not a hs-pay-settlement-attestation-v1 record".to_owned(),
139 ));
140 }
141
142 let parsed = SettlementAttestation {
143 issuer_did: text(&items[1])?.to_owned(),
144 settlement_id: text(&items[2])?.to_owned(),
145 unit: UnitRef {
146 issuer_did: text(&items[3])?.to_owned(),
147 resource_class: text(&items[4])?.to_owned(),
148 },
149 destination_did: text(&items[5])?.to_owned(),
150 amount_minor: amount(&items[6])?,
151 grant_cid: {
152 let g = bytes_of(&items[7])?;
153 if g.is_empty() {
154 None
155 } else {
156 Some(g.to_vec())
157 }
158 },
159 settled_at: uint(&items[8])?,
160 signature: bytes_of(&items[9])?.to_vec(),
161 };
162
163 let reencoded = parsed.encode()?;
166 if reencoded != bytes {
167 return Err(PayError::AttestationInvalid(
168 "attestation bytes are not canonical (re-encoding differs); refusing to \
169 normalize, because that would change the content address"
170 .to_owned(),
171 ));
172 }
173 Ok(parsed)
174 }
175
176 pub fn cid(&self) -> Result<[u8; 32], PayError> {
182 Ok(*blake3::hash(&self.encode()?).as_bytes())
183 }
184
185 fn body_fields(&self) -> Vec<Value> {
187 vec![
188 Value::Text(ATTESTATION_V1_TAG.to_owned()),
189 Value::Text(self.issuer_did.clone()),
190 Value::Text(self.settlement_id.clone()),
191 Value::Text(self.unit.issuer_did.clone()),
192 Value::Text(self.unit.resource_class.clone()),
193 Value::Text(self.destination_did.clone()),
194 Value::Bytes(self.amount_minor.to_be_bytes().to_vec()),
195 Value::Bytes(self.grant_cid.clone().unwrap_or_default()),
196 Value::Integer(self.settled_at.into()),
197 ]
198 }
199}
200
201fn encode_canonical(fields: &[Value]) -> Result<Vec<u8>, PayError> {
202 let mut buf = Vec::new();
203 ciborium::into_writer(&Value::Array(fields.to_vec()), &mut buf)
204 .map_err(|e| PayError::Internal(format!("attestation encode failed: {e}")))?;
205 Ok(buf)
206}
207
208fn text(v: &Value) -> Result<&str, PayError> {
209 v.as_text()
210 .ok_or_else(|| PayError::AttestationInvalid("expected a text field".to_owned()))
211}
212
213fn bytes_of(v: &Value) -> Result<&[u8], PayError> {
214 v.as_bytes()
215 .map(Vec::as_slice)
216 .ok_or_else(|| PayError::AttestationInvalid("expected a byte-string field".to_owned()))
217}
218
219fn uint(v: &Value) -> Result<u64, PayError> {
220 let i = v
221 .as_integer()
222 .ok_or_else(|| PayError::AttestationInvalid("expected an integer field".to_owned()))?;
223 u64::try_from(i)
224 .map_err(|_| PayError::AttestationInvalid("integer field out of range".to_owned()))
225}
226
227fn amount(v: &Value) -> Result<u128, PayError> {
230 let b = bytes_of(v)?;
231 if b.len() != 16 {
232 return Err(PayError::AttestationInvalid(format!(
233 "amount must be exactly 16 bytes, found {}",
234 b.len()
235 )));
236 }
237 let mut arr = [0u8; 16];
238 arr.copy_from_slice(b);
239 Ok(u128::from_be_bytes(arr))
240}
241
242#[cfg(test)]
243mod tests {
244 #![allow(clippy::unwrap_used, clippy::expect_used)]
246
247 use super::*;
248
249 fn sample() -> SettlementAttestation {
250 SettlementAttestation {
251 issuer_did: "did:web:settlement.test".to_owned(),
252 settlement_id: "stl_01HQ".to_owned(),
253 unit: UnitRef {
254 issuer_did: "did:web:issuer.test".to_owned(),
255 resource_class: "gpu.h100.seconds".to_owned(),
256 },
257 destination_did: "did:key:zPurchaser".to_owned(),
258 amount_minor: 12_345_678_901_234_567_890_123_456_789,
259 grant_cid: Some(vec![0xde, 0xad, 0xbe, 0xef]),
260 settled_at: 1_753_600_000,
261 signature: vec![7u8; 96],
262 }
263 }
264
265 #[test]
266 fn encode_is_deterministic() {
267 assert_eq!(sample().encode().unwrap(), sample().encode().unwrap());
268 }
269
270 #[test]
271 fn roundtrips_through_the_wire_form() {
272 let a = sample();
273 let bytes = a.encode().unwrap();
274 assert_eq!(SettlementAttestation::decode(&bytes).unwrap(), a);
275 }
276
277 #[test]
278 fn a_large_u128_amount_survives_exactly() {
279 let a = sample();
280 let decoded = SettlementAttestation::decode(&a.encode().unwrap()).unwrap();
281 assert_eq!(
282 decoded.amount_minor, a.amount_minor,
283 "a u128 amount beyond the CBOR integer range must not be truncated"
284 );
285 }
286
287 #[test]
288 fn the_cid_is_stable_across_a_roundtrip() {
289 let a = sample();
290 let bytes = a.encode().unwrap();
291 let decoded = SettlementAttestation::decode(&bytes).unwrap();
292 assert_eq!(
293 a.cid().unwrap(),
294 decoded.cid().unwrap(),
295 "an embedded attestation must content-address identically after a roundtrip"
296 );
297 assert_eq!(decoded.encode().unwrap(), bytes);
300 }
301
302 #[test]
303 fn the_cid_changes_when_any_signed_field_changes() {
304 let base = sample().cid().unwrap();
305 let mut other = sample();
306 other.amount_minor += 1;
307 assert_ne!(base, other.cid().unwrap());
308 let mut other = sample();
309 other.destination_did = "did:key:zSomeoneElse".to_owned();
310 assert_ne!(base, other.cid().unwrap());
311 let mut other = sample();
312 other.settlement_id = "stl_other".to_owned();
313 assert_ne!(base, other.cid().unwrap());
314 }
315
316 #[test]
317 fn the_signing_input_excludes_the_signature() {
318 let mut a = sample();
319 let input = a.signing_input().unwrap();
320 a.signature = vec![9u8; 96];
321 assert_eq!(
322 input,
323 a.signing_input().unwrap(),
324 "changing the signature must not change what was signed"
325 );
326 assert_ne!(
327 input,
328 a.encode().unwrap(),
329 "the signing input must not be the full record"
330 );
331 }
332
333 #[test]
334 fn the_signing_input_covers_every_semantic_field() {
335 let base = sample().signing_input().unwrap();
336 for mutate in [
337 (|a: &mut SettlementAttestation| a.issuer_did.push('x'))
338 as fn(&mut SettlementAttestation),
339 |a| a.settlement_id.push('x'),
340 |a| a.unit.issuer_did.push('x'),
341 |a| a.unit.resource_class.push('x'),
342 |a| a.destination_did.push('x'),
343 |a| a.amount_minor += 1,
344 |a| a.settled_at += 1,
345 |a| a.grant_cid = Some(vec![1, 2, 3]),
346 ] {
347 let mut a = sample();
348 mutate(&mut a);
349 assert_ne!(
350 base,
351 a.signing_input().unwrap(),
352 "a semantic field is not covered by the signature"
353 );
354 }
355 }
356
357 #[test]
358 fn a_non_canonical_encoding_is_refused() {
359 let mut noncanonical = vec![0x9fu8]; let canonical = sample().encode().unwrap();
363 noncanonical.extend_from_slice(&canonical[1..]);
365 noncanonical.push(0xff); let err = SettlementAttestation::decode(&noncanonical).unwrap_err();
368 assert!(
369 matches!(err, PayError::AttestationInvalid(_)),
370 "a non-canonical encoding must be refused, got {err:?}"
371 );
372 }
373
374 #[test]
375 fn a_record_with_the_wrong_domain_tag_is_refused() {
376 let mut fields = sample().body_fields();
377 fields[0] = Value::Text("hs-pay-something-else-v1".to_owned());
378 fields.push(Value::Bytes(vec![7u8; 96]));
379 let bytes = encode_canonical(&fields).unwrap();
380 assert!(SettlementAttestation::decode(&bytes).is_err());
381 }
382
383 #[test]
384 fn a_truncated_amount_is_refused() {
385 let mut fields = sample().body_fields();
386 fields[6] = Value::Bytes(vec![0u8; 8]);
387 fields.push(Value::Bytes(vec![7u8; 96]));
388 let bytes = encode_canonical(&fields).unwrap();
389 let err = SettlementAttestation::decode(&bytes).unwrap_err();
390 assert!(matches!(err, PayError::AttestationInvalid(_)));
391 }
392}