1use anyhow::{bail, Result};
42
43use super::{
44 map_get_str, map_get_uint, reject_unknown_fields, validate_cid_string, validate_did,
45 validate_subject_id,
46};
47use crate::cid::Cid;
48use crate::dag_cbor::DagCbor;
49
50pub const COLLECTION_NSID: &str = "ai.hyprstream.ledger.allocation";
52
53#[derive(Clone, Debug, Eq, PartialEq)]
60pub struct Unit {
61 pub code: String,
63 pub issuer: String,
65}
66
67#[derive(Clone, Copy, Debug, Eq, PartialEq)]
69pub enum GrantClass {
70 Prepaid,
75 Underwritten,
80}
81
82impl GrantClass {
83 pub fn as_str(self) -> &'static str {
85 match self {
86 GrantClass::Prepaid => "prepaid",
87 GrantClass::Underwritten => "underwritten",
88 }
89 }
90
91 pub fn parse(s: &str) -> Result<Self> {
93 match s {
94 "prepaid" => Ok(GrantClass::Prepaid),
95 "underwritten" => Ok(GrantClass::Underwritten),
96 other => bail!("{COLLECTION_NSID}: unknown grant class {other:?}"),
97 }
98 }
99
100 pub fn detect_mode_eligible(self) -> bool {
109 matches!(self, GrantClass::Underwritten)
110 }
111}
112
113#[derive(Clone, Debug, Eq, PartialEq)]
115pub struct AllocationRecord {
116 pub grant: String,
118 pub unit: Unit,
120 pub amount: u64,
122 pub epoch: u64,
124 pub issuer: String,
126 pub holder: String,
128 pub class: GrantClass,
130}
131
132impl AllocationRecord {
133 pub fn new(
135 grant: impl Into<String>,
136 unit: Unit,
137 amount: u64,
138 epoch: u64,
139 issuer: impl Into<String>,
140 holder: impl Into<String>,
141 class: GrantClass,
142 ) -> Result<Self> {
143 let grant = grant.into();
144 let issuer = issuer.into();
145 let holder = holder.into();
146 validate_cid_string(&grant, "grant")?;
147 validate_did(&issuer)?;
148 validate_did(&unit.issuer)?;
149 if unit.code.is_empty() {
150 bail!("{COLLECTION_NSID}: unit.code must not be empty");
151 }
152 if issuer != unit.issuer {
156 bail!(
157 "{COLLECTION_NSID}: issuer {issuer:?} must equal unit.issuer {:?} \
158 (credits are the unit-issuer's liability, D8-1)",
159 unit.issuer
160 );
161 }
162 validate_subject_id(&holder, "holder")?;
163 Ok(AllocationRecord {
164 grant,
165 unit,
166 amount,
167 epoch,
168 issuer,
169 holder,
170 class,
171 })
172 }
173
174 pub fn to_dag_cbor(&self) -> Vec<u8> {
176 self.to_value().encode()
177 }
178
179 pub fn cid(&self) -> Cid {
181 Cid::from_dag_cbor(&self.to_dag_cbor())
182 }
183
184 pub fn to_value(&self) -> DagCbor {
186 let unit = DagCbor::str_map([
187 ("code", DagCbor::Text(self.unit.code.clone())),
188 ("issuer", DagCbor::Text(self.unit.issuer.clone())),
189 ]);
190 DagCbor::str_map([
191 ("grant", DagCbor::Text(self.grant.clone())),
192 ("unit", unit),
193 ("amount", DagCbor::Unsigned(self.amount)),
194 ("epoch", DagCbor::Unsigned(self.epoch)),
195 ("issuer", DagCbor::Text(self.issuer.clone())),
196 ("holder", DagCbor::Text(self.holder.clone())),
197 ("class", DagCbor::Text(self.class.as_str().to_owned())),
198 ])
199 }
200
201 pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
203 let value = DagCbor::decode(bytes)?;
204 Self::from_value(&value)
205 }
206
207 pub fn from_value(value: &DagCbor) -> Result<Self> {
208 reject_unknown_fields(
209 value,
210 &[
211 "grant", "unit", "amount", "epoch", "issuer", "holder", "class",
212 ],
213 COLLECTION_NSID,
214 )?;
215 let grant = map_get_str(value, "grant", COLLECTION_NSID)?.to_owned();
216 let unit = parse_unit(value.get("unit").ok_or_else(|| {
217 anyhow::anyhow!("{COLLECTION_NSID}: missing required field \"unit\"")
218 })?)?;
219 let amount = map_get_uint(value, "amount", COLLECTION_NSID)?;
220 let epoch = map_get_uint(value, "epoch", COLLECTION_NSID)?;
221 let issuer = map_get_str(value, "issuer", COLLECTION_NSID)?.to_owned();
222 let holder = map_get_str(value, "holder", COLLECTION_NSID)?.to_owned();
223 let class = GrantClass::parse(map_get_str(value, "class", COLLECTION_NSID)?)?;
224 Self::new(grant, unit, amount, epoch, issuer, holder, class)
225 }
226}
227
228fn parse_unit(value: &DagCbor) -> Result<Unit> {
229 reject_unknown_fields(value, &["code", "issuer"], COLLECTION_NSID)?;
230 let code = map_get_str(value, "code", COLLECTION_NSID)?.to_owned();
231 let issuer = map_get_str(value, "issuer", COLLECTION_NSID)?.to_owned();
232 Ok(Unit { code, issuer })
233}
234
235#[cfg(test)]
236mod tests {
237 #![allow(
238 clippy::unwrap_used,
239 clippy::expect_used,
240 clippy::indexing_slicing,
241 clippy::panic
242 )]
243 use super::*;
244
245 const ISSUER: &str = "did:web:issuer.example.com";
246
247 fn unit() -> Unit {
248 Unit {
249 code: "compute-second".into(),
250 issuer: ISSUER.into(),
251 }
252 }
253
254 fn sample() -> AllocationRecord {
255 AllocationRecord::new(
256 "bafyreiexamplegrantcid1234567890abcdef",
257 unit(),
258 1_000,
259 7,
260 ISSUER,
261 "did:key:zHolderSubject",
262 GrantClass::Underwritten,
263 )
264 .expect("valid sample")
265 }
266
267 #[test]
268 fn record_round_trip_same_cid() {
269 let r = sample();
270 let bytes = r.to_dag_cbor();
271 let back = AllocationRecord::from_dag_cbor(&bytes).expect("round-trip");
272 assert_eq!(r, back);
273 assert_eq!(r.cid(), back.cid());
274 assert_eq!(back.to_dag_cbor(), bytes);
276 }
277
278 #[test]
279 fn record_fields_canonical_order() {
280 let r = sample();
281 let v = DagCbor::decode(&r.to_dag_cbor()).expect("decode");
282 let map = v.as_map().expect("map");
283 let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
284 assert_eq!(
286 keys,
287 vec!["amount", "class", "epoch", "grant", "holder", "issuer", "unit"]
288 );
289 }
290
291 #[test]
292 fn no_legal_identity_field_is_representable() {
293 let mut v = sample().to_value();
296 if let DagCbor::Map(ref mut pairs) = v {
297 pairs.push((
298 DagCbor::Text("legalName".into()),
299 DagCbor::Text("Jane Doe".into()),
300 ));
301 pairs.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
302 }
303 let err =
304 AllocationRecord::from_value(&v).expect_err("legal-identity field must be rejected");
305 assert!(
306 err.to_string().contains("unknown field"),
307 "unexpected: {err:#}"
308 );
309 }
310
311 #[test]
312 fn pairwise_holder_accepted() {
313 let r = AllocationRecord::new(
315 "bafyreiexamplegrantcid1234567890abcdef",
316 unit(),
317 5,
318 1,
319 ISSUER,
320 "pairwise:cell42:8f3ad9c0e1",
321 GrantClass::Prepaid,
322 )
323 .expect("pairwise holder must be accepted");
324 assert_eq!(
325 AllocationRecord::from_dag_cbor(&r.to_dag_cbor()).expect("round-trip"),
326 r
327 );
328 }
329
330 #[test]
331 fn prepaid_issuable_to_bare_did_key() {
332 AllocationRecord::new(
334 "bafyreiexamplegrantcid1234567890abcdef",
335 unit(),
336 5,
337 1,
338 ISSUER,
339 "did:key:zBareKeyNoIdentity",
340 GrantClass::Prepaid,
341 )
342 .expect("prepaid to bare did:key must be accepted");
343 }
344
345 #[test]
346 fn class_mode_coupling() {
347 assert!(!GrantClass::Prepaid.detect_mode_eligible());
349 assert!(GrantClass::Underwritten.detect_mode_eligible());
350 }
351
352 #[test]
353 fn unit_names_its_issuer_and_binds_liability() {
354 let mismatched = AllocationRecord::new(
357 "bafyreiexamplegrantcid1234567890abcdef",
358 unit(),
359 5,
360 1,
361 "did:web:other.example.com",
362 "did:key:zHolder",
363 GrantClass::Underwritten,
364 );
365 assert!(
366 mismatched.is_err(),
367 "issuer != unit.issuer must be rejected"
368 );
369 }
370
371 #[test]
372 fn record_validates_formats() {
373 assert!(
375 AllocationRecord::new("x", unit(), 1, 1, ISSUER, "did:key:z", GrantClass::Prepaid)
376 .is_err()
377 );
378 assert!(AllocationRecord::new(
380 "bafyreiexamplegrantcid1234567890abcdef",
381 unit(),
382 1,
383 1,
384 "not-a-did",
385 "did:key:z",
386 GrantClass::Prepaid
387 )
388 .is_err());
389 assert!(AllocationRecord::new(
391 "bafyreiexamplegrantcid1234567890abcdef",
392 unit(),
393 1,
394 1,
395 ISSUER,
396 "",
397 GrantClass::Prepaid
398 )
399 .is_err());
400 let mut v = sample().to_value();
402 if let DagCbor::Map(ref mut pairs) = v {
403 for (k, val) in pairs.iter_mut() {
404 if k.as_str().ok() == Some("class") {
405 *val = DagCbor::Text("overdraft".into());
406 }
407 }
408 }
409 assert!(AllocationRecord::from_value(&v).is_err());
410 }
411
412 #[test]
413 fn grant_and_cids_are_strings_not_links() {
414 let v = sample().to_value();
415 assert!(matches!(v.get("grant"), Some(DagCbor::Text(_))));
416 }
417}