1use anyhow::Result;
37
38use super::{
39 map_get_str, map_get_uint, reject_unknown_fields, validate_cid_string, validate_subject_id,
40 validate_token,
41};
42use crate::cid::Cid;
43use crate::dag_cbor::DagCbor;
44
45pub const COLLECTION_NSID: &str = "ai.hyprstream.ledger.receipt";
47
48#[derive(Clone, Debug, Eq, PartialEq)]
50pub struct ReceiptRecord {
51 pub allocation: String,
53 pub spender: String,
55 pub host: String,
57 pub transfer_id: String,
59 pub quantum: u64,
61}
62
63impl ReceiptRecord {
64 pub fn new(
66 allocation: impl Into<String>,
67 spender: impl Into<String>,
68 host: impl Into<String>,
69 transfer_id: impl Into<String>,
70 quantum: u64,
71 ) -> Result<Self> {
72 let allocation = allocation.into();
73 let spender = spender.into();
74 let host = host.into();
75 let transfer_id = transfer_id.into();
76 validate_cid_string(&allocation, "allocation")?;
77 validate_subject_id(&spender, "spender")?;
78 validate_subject_id(&host, "host")?;
79 validate_token(&transfer_id, "transferId")?;
80 Ok(ReceiptRecord {
81 allocation,
82 spender,
83 host,
84 transfer_id,
85 quantum,
86 })
87 }
88
89 pub fn to_dag_cbor(&self) -> Vec<u8> {
91 self.to_value().encode()
92 }
93
94 pub fn cid(&self) -> Cid {
96 Cid::from_dag_cbor(&self.to_dag_cbor())
97 }
98
99 pub fn to_value(&self) -> DagCbor {
101 DagCbor::str_map([
102 ("allocation", DagCbor::Text(self.allocation.clone())),
103 ("spender", DagCbor::Text(self.spender.clone())),
104 ("host", DagCbor::Text(self.host.clone())),
105 ("transferId", DagCbor::Text(self.transfer_id.clone())),
106 ("quantum", DagCbor::Unsigned(self.quantum)),
107 ])
108 }
109
110 pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
112 let value = DagCbor::decode(bytes)?;
113 Self::from_value(&value)
114 }
115
116 pub fn from_value(value: &DagCbor) -> Result<Self> {
117 reject_unknown_fields(
118 value,
119 &["allocation", "spender", "host", "transferId", "quantum"],
120 COLLECTION_NSID,
121 )?;
122 let allocation = map_get_str(value, "allocation", COLLECTION_NSID)?.to_owned();
123 let spender = map_get_str(value, "spender", COLLECTION_NSID)?.to_owned();
124 let host = map_get_str(value, "host", COLLECTION_NSID)?.to_owned();
125 let transfer_id = map_get_str(value, "transferId", COLLECTION_NSID)?.to_owned();
126 let quantum = map_get_uint(value, "quantum", COLLECTION_NSID)?;
127 Self::new(allocation, spender, host, transfer_id, quantum)
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 #![allow(
134 clippy::unwrap_used,
135 clippy::expect_used,
136 clippy::indexing_slicing,
137 clippy::panic
138 )]
139 use super::*;
140
141 fn sample() -> ReceiptRecord {
142 ReceiptRecord::new(
143 "bafyreiexamplealloccid1234567890abcdef",
144 "pairwise:cell42:8f3ad9c0e1",
145 "did:key:zHostNode",
146 "transfer-01HXYZ",
147 25,
148 )
149 .expect("valid sample")
150 }
151
152 #[test]
153 fn record_round_trip_same_cid() {
154 let r = sample();
155 let bytes = r.to_dag_cbor();
156 let back = ReceiptRecord::from_dag_cbor(&bytes).expect("round-trip");
157 assert_eq!(r, back);
158 assert_eq!(r.cid(), back.cid());
159 assert_eq!(back.to_dag_cbor(), bytes);
160 }
161
162 #[test]
163 fn record_fields_canonical_order() {
164 let r = sample();
165 let v = DagCbor::decode(&r.to_dag_cbor()).expect("decode");
166 let map = v.as_map().expect("map");
167 let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
168 assert_eq!(
169 keys,
170 vec!["allocation", "host", "quantum", "spender", "transferId"]
171 );
172 }
173
174 #[test]
175 fn pairwise_spender_accepted() {
176 let r = sample();
179 assert!(!r.spender.starts_with("did:"));
180 assert_eq!(
181 ReceiptRecord::from_dag_cbor(&r.to_dag_cbor()).expect("round-trip"),
182 r
183 );
184 }
185
186 #[test]
187 fn no_legal_identity_field_is_representable() {
188 let mut v = sample().to_value();
189 if let DagCbor::Map(ref mut pairs) = v {
190 pairs.push((
191 DagCbor::Text("payerLegalId".into()),
192 DagCbor::Text("SSN".into()),
193 ));
194 pairs.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
195 }
196 assert!(ReceiptRecord::from_value(&v).is_err());
197 }
198
199 #[test]
200 fn record_validates_formats() {
201 assert!(ReceiptRecord::new("x", "did:key:z", "did:key:h", "t", 1).is_err());
203 assert!(ReceiptRecord::new(
205 "bafyreiexamplealloccid1234567890abcdef",
206 "",
207 "did:key:h",
208 "t",
209 1
210 )
211 .is_err());
212 assert!(ReceiptRecord::new(
214 "bafyreiexamplealloccid1234567890abcdef",
215 "did:key:z",
216 "did:key:h",
217 "",
218 1
219 )
220 .is_err());
221 }
222}