|
| 1 | +use crate::credential::rdf_marker::IRI_VC_TYPE; |
| 2 | +use crate::credential::vc::VerifiableCredential; |
| 3 | +use crate::ContractError; |
| 4 | +use cosmwasm_std::Addr; |
| 5 | +use itertools::Itertools; |
| 6 | +use okp4_rdf::dataset::Dataset; |
| 7 | + |
| 8 | +#[derive(Debug, PartialEq)] |
| 9 | +pub struct DataverseCredential<'a> { |
| 10 | + pub submitter_addr: Addr, |
| 11 | + pub id: &'a str, |
| 12 | + pub issuer: &'a str, |
| 13 | + pub r#type: &'a str, |
| 14 | + pub valid_from: &'a str, |
| 15 | + pub valid_until: Option<&'a str>, |
| 16 | + pub subject: &'a str, |
| 17 | + pub claim: &'a Dataset<'a>, |
| 18 | +} |
| 19 | + |
| 20 | +impl<'a> DataverseCredential<'a> { |
| 21 | + fn extract_vc_type(vc: &'a VerifiableCredential<'a>) -> Result<&'a str, ContractError> { |
| 22 | + vc.types |
| 23 | + .iter() |
| 24 | + .filter(|t| *t != &IRI_VC_TYPE) |
| 25 | + .exactly_one() |
| 26 | + .map_err(|_| { |
| 27 | + ContractError::UnsupportedCredential( |
| 28 | + "credential is expected to have exactly one type".to_string(), |
| 29 | + ) |
| 30 | + }) |
| 31 | + .map(|t| *t) |
| 32 | + } |
| 33 | + |
| 34 | + fn extract_vc_claim( |
| 35 | + vc: &'a VerifiableCredential<'a>, |
| 36 | + ) -> Result<(&'a str, &'a Dataset<'a>), ContractError> { |
| 37 | + vc.claims |
| 38 | + .iter() |
| 39 | + .exactly_one() |
| 40 | + .map(|claim| (claim.id, &(claim.content))) |
| 41 | + .map_err(|_| { |
| 42 | + ContractError::UnsupportedCredential( |
| 43 | + "credential is expected to contain exactly one claim".to_string(), |
| 44 | + ) |
| 45 | + }) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl<'a> TryFrom<(Addr, &'a VerifiableCredential<'a>)> for DataverseCredential<'a> { |
| 50 | + type Error = ContractError; |
| 51 | + |
| 52 | + fn try_from( |
| 53 | + (submitter_addr, vc): (Addr, &'a VerifiableCredential<'a>), |
| 54 | + ) -> Result<Self, Self::Error> { |
| 55 | + let (subject, claim) = DataverseCredential::extract_vc_claim(vc)?; |
| 56 | + Ok(DataverseCredential { |
| 57 | + submitter_addr, |
| 58 | + id: vc.id, |
| 59 | + issuer: vc.issuer, |
| 60 | + r#type: DataverseCredential::extract_vc_type(vc)?, |
| 61 | + valid_from: vc.issuance_date, |
| 62 | + valid_until: vc.expiration_date, |
| 63 | + subject, |
| 64 | + claim, |
| 65 | + }) |
| 66 | + } |
| 67 | +} |
0 commit comments