use serde::Deserialize; use serde_json::Value; use sha2::{Digest, Sha256}; use crate::{record_cid, Error, Io, StrongRef}; pub const ACCEPT_NSID: &str = "com.publicdomainrelay.temp.market.accept"; pub const RECEIPT_NSID: &str = "com.publicdomainrelay.temp.market.receipt"; pub const VM_DELETE_NSID: &str = "com.publicdomainrelay.temp.compute.events.vm.delete"; pub const VM_TERMINATED_NSID: &str = "com.publicdomainrelay.temp.compute.events.vm.terminated"; fn hex16(b: &[u8]) -> String { b[..16].iter().map(|b| format!("{b:02x}")).collect() } pub fn receipt_rkey(accept_uri: &str, accept_cid: &str) -> String { format!("receipt-{}", hex16(&Sha256::digest(format!("{}\n{}", accept_uri.trim(), accept_cid.trim())))) } pub fn release_rkey(receipt_uri: &str) -> String { const ALPHABET: &[u8] = b"234567abcdefghijklmnopqrstuvwxyz"; let sum = Sha256::digest(format!("delete\0{receipt_uri}")); sum[..13].iter().map(|b| ALPHABET[usize::from(*b) % ALPHABET.len()] as char).collect() } pub fn termination_rkey(receipt_uri: &str) -> String { format!("termination-payload-{}", hex16(&Sha256::digest(format!("terminated:{receipt_uri}")))) } fn split(uri: &str) -> Option<(&str, &str, &str)> { let mut parts = uri.strip_prefix("at://")?.split('/'); let out = (parts.next()?, parts.next()?, parts.next()?); parts.next().is_none().then_some(out) } fn strong_ref(v: Option<&Value>) -> Option { let r = StrongRef::deserialize(v?).ok()?; (r.uri.starts_with("at://") && !r.cid.is_empty()).then_some(r) } pub async fn market_contract_held(io: &I, contract: &StrongRef, authorities: &[String]) -> Result { let Some((repo, ACCEPT_NSID, rkey)) = split(&contract.uri) else { return Ok(false); }; if !authorities.iter().any(|a| a == repo) { return Ok(false); } let Some(accept) = io.get_record(repo, ACCEPT_NSID, rkey).await? else { return Ok(false); }; if record_cid(&accept).ok().as_deref() != Some(contract.cid.as_str()) { return Ok(false); } let Some(bid) = strong_ref(accept.get("bid")) else { return Ok(false); }; let bidder = bid.uri["at://".len()..].split('/').next().unwrap_or_default().to_string(); if !bidder.starts_with("did:") { return Ok(false); } let receipt_rkey = receipt_rkey(&contract.uri, &contract.cid); let receipt_uri = format!("at://{bidder}/{RECEIPT_NSID}/{receipt_rkey}"); let Some(receipt) = io.get_record(&bidder, RECEIPT_NSID, &receipt_rkey).await? else { return Ok(false); }; if strong_ref(receipt.get("accept")).as_ref() != Some(contract) { return Ok(false); } if io.get_record(repo, VM_DELETE_NSID, &release_rkey(&receipt_uri)).await?.is_some() { return Ok(false); } Ok(io.get_record(&bidder, VM_TERMINATED_NSID, &termination_rkey(&receipt_uri)).await?.is_none()) }