repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/connection/invitee/states/invited.rs
aries/aries_vcx/src/protocols/connection/invitee/states/invited.rs
use diddoc_legacy::aries::diddoc::AriesDidDoc; use crate::{ handlers::util::AnyInvitation, protocols::connection::trait_bounds::{BootstrapDidDoc, TheirDidDoc, ThreadId}, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Invited { pub(crate) did_doc: AriesDidDoc, pub(crate) invitation: AnyInvitation, } impl Invited { pub fn new(did_doc: AriesDidDoc, invitation: AnyInvitation) -> Self { Self { did_doc, invitation, } } } impl TheirDidDoc for Invited { fn their_did_doc(&self) -> &AriesDidDoc { &self.did_doc } } impl BootstrapDidDoc for Invited {} impl ThreadId for Invited { fn thread_id(&self) -> &str { match &self.invitation { AnyInvitation::Con(i) => i.id.as_str(), AnyInvitation::Oob(i) => i.id.as_str(), } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/connection/invitee/states/requested.rs
aries/aries_vcx/src/protocols/connection/invitee/states/requested.rs
use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::connection::request::Request; use crate::protocols::connection::trait_bounds::{ BootstrapDidDoc, HandleProblem, TheirDidDoc, ThreadId, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Requested { pub(crate) did_doc: AriesDidDoc, pub(crate) thread_id: String, pub(crate) request: Request, } impl Requested { pub fn new(did_doc: AriesDidDoc, thread_id: String, request: Request) -> Self { Self { did_doc, thread_id, request, } } } impl TheirDidDoc for Requested { fn their_did_doc(&self) -> &AriesDidDoc { &self.did_doc } } impl BootstrapDidDoc for Requested {} impl ThreadId for Requested { fn thread_id(&self) -> &str { &self.thread_id } } impl HandleProblem for Requested {}
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/connection/invitee/states/mod.rs
aries/aries_vcx/src/protocols/connection/invitee/states/mod.rs
pub mod completed; pub mod initial; pub mod invited; pub mod requested;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/connection/invitee/states/initial.rs
aries/aries_vcx/src/protocols/connection/invitee/states/initial.rs
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq)] pub struct Initial;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/oob/mod.rs
aries/aries_vcx/src/protocols/oob/mod.rs
use aries_vcx_ledger::ledger::base_ledger::IndyLedgerRead; use chrono::Utc; use diddoc_legacy::aries::{diddoc::AriesDidDoc, service::AriesService}; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::out_of_band::{ invitation::Invitation, reuse::{HandshakeReuse, HandshakeReuseDecorators}, reuse_accepted::{HandshakeReuseAccepted, HandshakeReuseAcceptedDecorators}, }, }; use uuid::Uuid; use crate::{ common::ledger::transactions::resolve_service, errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, }; const DID_KEY_PREFIX: &str = "did:key:"; const ED25519_MULTIBASE_CODEC: [u8; 2] = [0xed, 0x01]; pub fn build_handshake_reuse_msg(oob_invitation: &Invitation) -> HandshakeReuse { let id = Uuid::new_v4().to_string(); let decorators = HandshakeReuseDecorators::builder() .thread( Thread::builder() .thid(id.clone()) .pthid(oob_invitation.id.clone()) .build(), ) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); HandshakeReuse::builder() .id(id) .decorators(decorators) .build() } pub fn build_handshake_reuse_accepted_msg( handshake_reuse: &HandshakeReuse, ) -> VcxResult<HandshakeReuseAccepted> { let thread = &handshake_reuse.decorators.thread; let thread_id = thread.thid.clone(); let pthread_id = thread .pthid .as_deref() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidOption, "Parent thread id missing", ))? .to_owned(); let decorators = HandshakeReuseAcceptedDecorators::builder() .thread(Thread::builder().thid(thread_id).pthid(pthread_id).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); Ok(HandshakeReuseAccepted::builder() .id(Uuid::new_v4().to_string()) .decorators(decorators) .build()) } pub async fn oob_invitation_to_legacy_did_doc( indy_ledger: &impl IndyLedgerRead, invitation: &Invitation, ) -> VcxResult<AriesDidDoc> { let mut did_doc: AriesDidDoc = AriesDidDoc::default(); let (service_endpoint, recipient_keys, routing_keys) = { did_doc.set_id(invitation.id.clone()); let service = resolve_service(indy_ledger, &invitation.content.services[0]) .await .unwrap_or_else(|err| { error!("Failed to obtain service definition from the ledger: {err}"); AriesService::default() }); let recipient_keys = normalize_keys_as_naked(&service.recipient_keys).unwrap_or_else(|err| { error!( "Failed to normalize keys of service {} as naked keys: {err}", &service ); Vec::new() }); ( service.service_endpoint, recipient_keys, service.routing_keys, ) }; did_doc.set_service_endpoint(service_endpoint); did_doc.set_recipient_keys(recipient_keys); did_doc.set_routing_keys(routing_keys); Ok(did_doc) } fn normalize_keys_as_naked(keys_list: &Vec<String>) -> VcxResult<Vec<String>> { let mut result = Vec::new(); for key in keys_list { if let Some(stripped_didkey) = key.strip_prefix(DID_KEY_PREFIX) { let stripped = if let Some(stripped) = stripped_didkey.strip_prefix('z') { stripped } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidDid, format!("z prefix is missing: {key}"), ))? }; let decoded_value = bs58::decode(stripped).into_vec().map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidDid, format!("Could not decode base58: {stripped} as portion of {key}"), ) })?; let verkey = if let Some(public_key_bytes) = decoded_value.strip_prefix(&ED25519_MULTIBASE_CODEC) { Ok(bs58::encode(public_key_bytes).into_string()) } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidDid, format!("Only Ed25519-based did:keys are currently supported, got key: {key}"), )) }?; result.push(verkey); } else { result.push(key.clone()); } } Ok(result) } // #[cfg(test)] // mod unit_tests { // use crate::protocols::oob::{build_handshake_reuse_accepted_msg, build_handshake_reuse_msg}; // use crate::utils::devsetup::{was_in_past, SetupMocks}; // use messages::a2a::MessageId; // use messages::protocols::out_of_band::invitation::OutOfBandInvitation; // #[test] // fn test_build_handshake_reuse_msg() { // let _setup = SetupMocks::init(); // let msg_invitation = OutOfBandInvitation::default(); // let msg_reuse = build_handshake_reuse_msg(&msg_invitation); // assert_eq!(msg_reuse.id, MessageId("testid".into())); // assert_eq!(msg_reuse.id, MessageId(msg_reuse.thread.thid.unwrap())); // assert_eq!(msg_reuse.thread.pthid.unwrap(), msg_invitation.id.0); // assert!(was_in_past( // &msg_reuse.timing.unwrap().out_time.unwrap(), // chrono::Duration::milliseconds(100) // ) // .unwrap()); // } // #[test] // fn test_build_handshake_reuse_accepted_msg() { // let _setup = SetupMocks::init(); // let mut msg_invitation = OutOfBandInvitation::default(); // msg_invitation.id = MessageId("invitation-id".to_string()); // let msg_reuse = build_handshake_reuse_msg(&msg_invitation); // let msg_reuse_accepted = build_handshake_reuse_accepted_msg(&msg_reuse).unwrap(); // assert_eq!(msg_reuse_accepted.id, MessageId("testid".into())); // assert_eq!(msg_reuse_accepted.thread.thid.unwrap(), msg_reuse.id.0); // assert_eq!(msg_reuse_accepted.thread.pthid.unwrap(), msg_invitation.id.0); // assert!(was_in_past( // &msg_reuse_accepted.timing.unwrap().out_time.unwrap(), // chrono::Duration::milliseconds(100) // ) // .unwrap()); // } // }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/mod.rs
aries/aries_vcx/src/protocols/did_exchange/mod.rs
use std::sync::Arc; use did_doc::schema::{ did_doc::DidDocument, verification_method::{VerificationMethod, VerificationMethodKind}, }; use did_parser_nom::DidUrl; use did_resolver_registry::ResolverRegistry; use messages::msg_fields::protocols::out_of_band::invitation::{ Invitation as OobInvitation, OobService, }; use public_key::Key; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, utils::didcomm_utils::resolve_service_key_to_typed_key, }; pub mod state_machine; pub mod states; pub mod transition; fn resolve_verification_method( did_doc: &DidDocument, verification_method_ref: &DidUrl, ) -> Result<VerificationMethod, AriesVcxError> { let key = did_doc.verification_method().iter().find(|key_agreement| { let reference_fragment = match verification_method_ref.fragment() { None => { warn!( "Fragment not found in verification method reference {verification_method_ref}" ); return false; } Some(fragment) => fragment, }; let key_agreement_fragment = match key_agreement.id().fragment() { None => { warn!( "Fragment not found in verification method {}", key_agreement.id() ); return false; } Some(fragment) => fragment, }; reference_fragment == key_agreement_fragment }); match key { None => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!("Verification method not found in resolved did document {did_doc}"), )), Some(verification_method) => Ok(verification_method.clone()), } } fn resolve_first_key_agreement(did_document: &DidDocument) -> VcxResult<VerificationMethod> { // todo: did_document needs robust way to resolve this, I shouldn't care if there's reference or // actual key in the key_agreement Abstract the user from format/structure of the did // document let verification_method_kind = did_document.key_agreement().first().ok_or_else(|| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!("No verification method found in resolved did document {did_document}"), ) })?; let verification_method = match verification_method_kind { VerificationMethodKind::Resolved(verification_method) => verification_method.clone(), VerificationMethodKind::Resolvable(verification_method_ref) => { resolve_verification_method(did_document, verification_method_ref)? } }; Ok(verification_method) } pub async fn resolve_enc_key_from_invitation( invitation: &OobInvitation, resolver_registry: &Arc<ResolverRegistry>, ) -> Result<Key, AriesVcxError> { match invitation.content.services.first().ok_or_else(|| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidInput, "Invitation does not contain any services", ) })? { OobService::Did(did) => { info!("Invitation contains service (DID format): {did}"); let output = resolver_registry .resolve(&did.clone().try_into()?, &Default::default()) .await .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidDid, format!("DID resolution failed: {err}"), ) })?; info!( "resolve_enc_key_from_invitation >> Resolved did document {}", output.did_document ); let did_doc = output.did_document; resolve_enc_key_from_did_doc(&did_doc) } OobService::AriesService(_service) => { unimplemented!("Embedded Aries Service not yet supported by did-exchange") } } } pub async fn resolve_enc_key_from_did( did: &str, resolver_registry: &Arc<ResolverRegistry>, ) -> Result<Key, AriesVcxError> { let output = resolver_registry .resolve(&did.try_into()?, &Default::default()) .await .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidDid, format!("DID resolution failed: {err}"), ) })?; info!( "resolve_enc_key_from_did >> Resolved did document {}", output.did_document ); let did_doc = output.did_document; resolve_enc_key_from_did_doc(&did_doc) } /// Attempts to resolve a [Key] in the [DidDocument] that can be used for sending encrypted /// messages. The approach is: /// * check the service for a recipient key, /// * if there is none, use the first key agreement key in the DIDDoc, /// * else fail pub fn resolve_enc_key_from_did_doc(did_doc: &DidDocument) -> Result<Key, AriesVcxError> { // prefer first service key if available if let Some(service_recipient_key) = did_doc .service() .first() .and_then(|s| s.extra_field_recipient_keys().into_iter().flatten().next()) { return resolve_service_key_to_typed_key(&service_recipient_key, did_doc); } let key = resolve_first_key_agreement(did_doc)?; Ok(key.public_key()?) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/transition/mod.rs
aries/aries_vcx/src/protocols/did_exchange/transition/mod.rs
// TODO: Obviously move somewhere else once reused pub mod transition_error; pub mod transition_result;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/transition/transition_result.rs
aries/aries_vcx/src/protocols/did_exchange/transition/transition_result.rs
// TODO: Somehow enforce using both #[must_use] #[derive(Debug)] pub struct TransitionResult<T, U> { pub state: T, pub output: U, }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/transition/transition_error.rs
aries/aries_vcx/src/protocols/did_exchange/transition/transition_error.rs
use crate::errors::error::AriesVcxError; #[derive(Debug)] pub struct TransitionError<T> { pub state: T, pub error: AriesVcxError, } impl<T> std::fmt::Display for TransitionError<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Transition error: {}", self.error) } } impl<T: std::fmt::Debug> std::error::Error for TransitionError<T> {} impl<T> From<TransitionError<T>> for AriesVcxError { fn from(err: TransitionError<T>) -> Self { err.error } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/state_machine/helpers.rs
aries/aries_vcx/src/protocols/did_exchange/state_machine/helpers.rs
use std::collections::HashMap; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use chrono::Utc; use did_doc::schema::{ did_doc::DidDocument, service::{service_key_kind::ServiceKeyKind, typed::didcommv1::ServiceDidCommV1, Service}, types::uri::Uri, verification_method::{PublicKeyField, VerificationMethodType}, }; use did_key::DidKey; use did_parser_nom::{Did, DidUrl}; use did_peer::peer_did::{ numalgos::numalgo4::{ construction_did_doc::{DidPeer4ConstructionDidDocument, DidPeer4VerificationMethod}, Numalgo4, }, PeerDid, }; use messages::{ decorators::{ attachment::{Attachment, AttachmentData, AttachmentType}, thread::Thread, timing::Timing, }, msg_fields::protocols::did_exchange::{ v1_0::response::{Response as ResponseV1_0, ResponseContent as ResponseV1_0Content}, v1_1::response::{Response as ResponseV1_1, ResponseContent as ResponseV1_1Content}, v1_x::response::ResponseDecorators, }, }; use public_key::{Key, KeyType}; use serde_json::Value; use url::Url; use uuid::Uuid; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind}, protocols::{ did_exchange::transition::transition_error::TransitionError, mediated_connection::pairwise_info::PairwiseInfo, }, utils::base64::URL_SAFE_LENIENT, }; pub(crate) fn construct_response_v1_0( // pthid inclusion is overkill in practice, but needed. see: https://github.com/decentralized-identity/aries-rfcs/issues/817 request_pthid: Option<String>, request_id: String, did: &Did, signed_diddoc_attach: Attachment, ) -> ResponseV1_0 { let thread = match request_pthid { Some(request_pthid) => Thread::builder() .thid(request_id) .pthid(request_pthid) .build(), None => Thread::builder().thid(request_id).build(), }; let content = ResponseV1_0Content::builder() .did(did.to_string()) .did_doc(Some(signed_diddoc_attach)) .build(); let decorators = ResponseDecorators::builder() .thread(thread) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); ResponseV1_0::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build() } pub(crate) fn construct_response_v1_1( // pthid inclusion is overkill in practice, but needed. see: https://github.com/decentralized-identity/aries-rfcs/issues/817 request_pthid: Option<String>, request_id: String, did: &Did, signed_didrotate_attach: Attachment, ) -> ResponseV1_1 { let thread = match request_pthid { Some(request_pthid) => Thread::builder() .thid(request_id) .pthid(request_pthid) .build(), None => Thread::builder().thid(request_id).build(), }; let content = ResponseV1_1Content::builder() .did(did.to_string()) .did_rotate(signed_didrotate_attach) .build(); let decorators = ResponseDecorators::builder() .thread(thread) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); ResponseV1_1::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build() } async fn generate_keypair( wallet: &impl BaseWallet, key_type: KeyType, ) -> Result<Key, AriesVcxError> { let pairwise_info = PairwiseInfo::create(wallet).await?; Ok(Key::from_base58(&pairwise_info.pw_vk, key_type)?) } pub async fn create_peer_did_4( wallet: &impl BaseWallet, service_endpoint: Url, routing_keys: Vec<String>, ) -> Result<(PeerDid<Numalgo4>, Key), AriesVcxError> { let key_enc = generate_keypair(wallet, KeyType::Ed25519).await?; let vm_ka_id = DidUrl::from_fragment("key1".to_string())?; let service: Service = ServiceDidCommV1::new( Uri::new("#0")?, service_endpoint, 0, vec![ServiceKeyKind::Reference(vm_ka_id.clone())], routing_keys .into_iter() .map(ServiceKeyKind::Value) .collect(), ) .try_into()?; info!("Prepared service for peer:did:4 generation: {service} "); let vm_ka = DidPeer4VerificationMethod::builder() .id(vm_ka_id.clone()) .verification_method_type(VerificationMethodType::Ed25519VerificationKey2020) .public_key(PublicKeyField::Multibase { public_key_multibase: key_enc.fingerprint(), }) .build(); let mut construction_did_doc = DidPeer4ConstructionDidDocument::new(); construction_did_doc.add_verification_method(vm_ka); construction_did_doc.add_key_agreement_ref(vm_ka_id); construction_did_doc.add_service(service); info!("Created did document for peer:did:4 generation: {construction_did_doc} "); let peer_did = PeerDid::<Numalgo4>::new(construction_did_doc)?; info!("Created peer did: {peer_did}"); Ok((peer_did, key_enc)) } pub(crate) fn ddo_to_attach(ddo: DidDocument) -> Result<Attachment, AriesVcxError> { // Interop note: acapy accepts unsigned when using peer dids? let content_b64 = base64::engine::Engine::encode(&URL_SAFE_LENIENT, serde_json::to_string(&ddo)?); Ok(Attachment::builder() .data( AttachmentData::builder() .content(AttachmentType::Base64(content_b64)) .build(), ) .build()) } pub(crate) fn assemble_did_rotate_attachment(did: &Did) -> Attachment { let content_b64 = base64::engine::Engine::encode(&URL_SAFE_LENIENT, did.did()); Attachment::builder() .data( AttachmentData::builder() .content(AttachmentType::Base64(content_b64)) .build(), ) .build() } // TODO: if this becomes a common method, move to a shared location. /// Creates a JWS signature of the attachment with the provided verkey. The created JWS /// signature is appended to the attachment, in alignment with Aries RFC 0017: /// https://github.com/decentralized-identity/aries-rfcs/blob/main/concepts/0017-attachments/README.md#signing-attachments. pub(crate) async fn jws_sign_attach( mut attach: Attachment, verkey: Key, wallet: &impl BaseWallet, ) -> Result<Attachment, AriesVcxError> { let AttachmentType::Base64(attach_base64) = &attach.data.content else { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidInput, "Cannot sign non-base64-encoded attachment", )); }; if verkey.key_type() != &KeyType::Ed25519 { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidVerkey, "Only JWS signatures with Ed25519 based keys are currently supported.", )); } let did_key: DidKey = verkey.clone().try_into()?; let verkey_b64 = base64::engine::Engine::encode(&URL_SAFE_LENIENT, verkey.key()); let protected_header = json!({ "alg": "EdDSA", "jwk": { "kty": "OKP", "kid": did_key.to_string(), "crv": "Ed25519", "x": verkey_b64 } }); let unprotected_header = json!({ "kid": did_key.to_string(), }); let b64_protected = base64::engine::Engine::encode(&URL_SAFE_LENIENT, protected_header.to_string()); let sign_input = format!("{b64_protected}.{attach_base64}").into_bytes(); let signed: Vec<u8> = wallet.sign(&verkey, &sign_input).await?; let signature_base64 = base64::engine::Engine::encode(&URL_SAFE_LENIENT, signed); let jws = { let mut jws = HashMap::new(); jws.insert("header".to_string(), unprotected_header); jws.insert("protected".to_string(), Value::String(b64_protected)); jws.insert("signature".to_string(), Value::String(signature_base64)); jws }; attach.data.jws = Some(jws); Ok(attach) } /// Verifies that the given has a JWS signature attached, which is a valid signature given /// the expected signer key. // NOTE: Does not handle attachments with multiple signatures. // NOTE: this is the specific use case where the signer is known by the function caller. Therefore // we do not need to attempt to decode key within the protected nor unprotected header. pub(crate) async fn jws_verify_attachment( attach: &Attachment, expected_signer: &Key, wallet: &impl BaseWallet, ) -> Result<bool, AriesVcxError> { let AttachmentType::Base64(attach_base64) = &attach.data.content else { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidInput, "Cannot verify JWS of a non-base64-encoded attachment", )); }; // aries attachments do not REQUIRE that the attachment has no padding, // but JWS does, so remove it; just incase. let attach_base64 = attach_base64.replace('=', ""); let Some(ref jws) = attach.data.jws else { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidInput, "Attachment has no JWS signature attached. Cannot verify.", )); }; let (Some(b64_protected), Some(b64_signature)) = ( jws.get("protected").and_then(|s| s.as_str()), jws.get("signature").and_then(|s| s.as_str()), ) else { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidInput, "Attachment has an invalid JWS with missing fields. Cannot verify.", )); }; let sign_input = format!("{b64_protected}.{attach_base64}").into_bytes(); let signature = base64::engine::Engine::decode(&URL_SAFE_LENIENT, b64_signature).map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::EncodeError, "Attachment JWS signature was not correctly base64Url encoded.", ) })?; let res = wallet .verify(expected_signer, &sign_input, &signature) .await?; Ok(res) } // TODO - ideally this should be resilient to the case where the attachment is a legacy aries DIDDoc // structure (i.e. [diddoc_legacy::aries::diddoc::AriesDidDoc]). It should be converted to a // spec-compliant [DidDocument]. ACA-py handles this case here: https://github.com/openwallet-foundation/acapy/blob/5ad52c15d2f4f62db1678b22a7470776d78b36f5/aries_cloudagent/resolver/default/legacy_peer.py#L27 // https://github.com/openwallet-foundation/vcx/issues/1227 pub(crate) fn attachment_to_diddoc(attachment: Attachment) -> Result<DidDocument, AriesVcxError> { match attachment.data.content { AttachmentType::Json(value) => serde_json::from_value(value).map_err(Into::into), AttachmentType::Base64(ref value) => { let bytes = base64::Engine::decode(&URL_SAFE_LENIENT, value).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!( "Attachment base 64 decoding failed; attach: {attachment:?}, err: {err}" ), ) })?; serde_json::from_slice::<DidDocument>(&bytes).map_err(Into::into) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, "Attachment is not a JSON or Base64", )), } } pub(crate) fn to_transition_error<S, T>(state: S) -> impl FnOnce(T) -> TransitionError<S> where T: Into<AriesVcxError>, { move |error| TransitionError { error: error.into(), state, } } #[cfg(test)] mod tests { use std::error::Error; use aries_vcx_wallet::wallet::base_wallet::did_wallet::DidWallet; use messages::decorators::attachment::{Attachment, AttachmentData, AttachmentType}; use public_key::Key; use test_utils::devsetup::build_setup_profile; use crate::{ protocols::did_exchange::state_machine::helpers::{jws_sign_attach, jws_verify_attachment}, utils::base64::URL_SAFE_LENIENT, }; // assert self fulfilling #[tokio::test] async fn test_jws_sign_and_verify_attachment() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let wallet = &setup.wallet; let signer_did = wallet.create_and_store_my_did(None, None).await?; let signer = signer_did.verkey(); let content_b64 = base64::engine::Engine::encode(&URL_SAFE_LENIENT, "hello world"); let attach = Attachment::builder() .data( AttachmentData::builder() .content(AttachmentType::Base64(content_b64)) .build(), ) .build(); let signed_attach = jws_sign_attach(attach, signer.clone(), wallet).await?; // should contain signed JWS assert_eq!(signed_attach.data.jws.as_ref().unwrap().len(), 3); // verify assert!(jws_verify_attachment(&signed_attach, signer, wallet).await?); // verify with wrong key should be false let wrong_did = wallet.create_and_store_my_did(None, None).await?; let wrong_signer = wrong_did.verkey(); assert!(!jws_verify_attachment(&signed_attach, wrong_signer, wallet).await?); Ok(()) } // test vector taken from an ACApy 0.12.1 DIDExchange response #[tokio::test] async fn test_jws_verify_attachment_with_acapy_test_vector() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let wallet = &setup.wallet; let json = json!({ "@id": "18bec73c-c621-4ef2-b3d8-085c59ac9e2b", "mime-type": "text/string", "data": { "jws": { "signature": "QxC2oLxAYav-fPOvjkn4OpMLng9qOo2fjsy0MoQotDgyVM_PRjYlatsrw6_rADpRpWR_GMpBVlBskuKxpsJIBQ", "header": { "kid": "did:key:z6MkpNusbzt7HSBwrBiRpZmbyLiBEsNGs2fotoYhykU8Muaz" }, "protected": "eyJhbGciOiAiRWREU0EiLCAiandrIjogeyJrdHkiOiAiT0tQIiwgImNydiI6ICJFZDI1NTE5IiwgIngiOiAiazNlOHZRTHpSZlFhZFhzVDBMUkMxMWhpX09LUlR6VFphd29ocmxhaW1ETSIsICJraWQiOiAiZGlkOmtleTp6Nk1rcE51c2J6dDdIU0J3ckJpUnBabWJ5TGlCRXNOR3MyZm90b1loeWtVOE11YXoifX0" }, // NOTE: includes b64 padding, but not recommended "base64": "ZGlkOnBlZXI6NHpRbVhza2o1Sjc3NXRyWUpkaVVFZVlaUU5mYXZZQUREb25YMzJUOHF4VHJiU05oOno2MmY5VlFROER0N1VWRXJXcmp6YTd4MUVKOG50NWVxOWlaZk1BUGoyYnpyeGJycGY4VXdUTEpXVUJTV2U4dHNoRFl4ZDhlcmVSclRhOHRqVlhKNmNEOTV0Qml5dVdRVll6QzNtZWtUckJ4MzNjeXFCb2g0c3JGamdXZm1lcE5yOEZpRFI5aEoySExxMlM3VGZNWXIxNVN4UG52OExRR2lIV24zODhzVlF3ODRURVJFaTg4OXlUejZzeVVmRXhEaXdxWHZOTk05akt1eHc4NERvbmtVUDRHYkh0Q3B4R2hKYVBKWnlUWmJVaFF2SHBENGc2YzYyWTN5ZGQ0V1BQdXBYQVFISzJScFZod2hQWlVnQWQzN1lrcW1jb3FiWGFZTWFnekZZY3kxTEJ6NkdYekV5NjRrOGQ4WGhlem5vUkpIV3F4RTV1am5LYkpOM0pRR241UzREaEtRaXJTbUZINUJOYUNvRTZqaFlWc3gzWlpEM1ZWZVVxUW9ZMmVHMkNRVVRRak1zY0ozOEdqeDFiaVVlRkhZVVRrejRRVDJFWXpXRlVEbW1URHExVmVoZExtelJDWnNQUjJKR1VpVExUVkNzdUNzZ21jd1FqWHY4WmN6ejRaZUo0ODc4S3hBRm5mam1ibk1EejV5NVJOMnZtRGtkaE42dFFMZjJEWVJuSm1vSjJ5VTNheXczU2NjV0VMVzNpWEN6UFROV1F3WmFEb2d5UFVXZFBobkw0OEVpMjI2cnRBcWoySGQxcTRua1Fwb0ZWQ1B3aXJGUmtub05Zc2NGV1dxN1JEVGVMcmlKcENrUVVFblh4WVBpU1F5S0RxbVpFN0FRVjI=" } }); let mut attach: Attachment = serde_json::from_value(json)?; let signer = Key::from_fingerprint("z6MkpNusbzt7HSBwrBiRpZmbyLiBEsNGs2fotoYhykU8Muaz")?; // should verify with correct signer assert!(jws_verify_attachment(&attach, &signer, wallet).await?); // should not verify with wrong signer let wrong_signer = Key::from_fingerprint("z6Mkva1JM9mM3SMuLCtVDAXzAQTwkdtfzHXSYMKtfXK2cPye")?; assert!(!jws_verify_attachment(&attach, &wrong_signer, wallet).await?); // should not verify if wrong signature attach.data.content = AttachmentType::Base64(String::from("d3JvbmcgZGF0YQ==")); assert!(!jws_verify_attachment(&attach, &signer, wallet).await?); Ok(()) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/state_machine/mod.rs
aries/aries_vcx/src/protocols/did_exchange/state_machine/mod.rs
pub mod helpers; pub mod generic; pub mod requester; pub mod responder; use std::marker::PhantomData; use chrono::Utc; use did_doc::schema::did_doc::DidDocument; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::did_exchange::v1_x::problem_report::{ AnyProblemReport, ProblemCode, ProblemReport, ProblemReportContent, ProblemReportDecorators, }, }; use uuid::Uuid; use super::{ states::{abandoned::Abandoned, traits::ThreadId}, transition::transition_result::TransitionResult, }; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct DidExchange<I, S> { state: S, initiation_type: PhantomData<I>, our_did_document: DidDocument, their_did_document: DidDocument, } impl<I, S: ThreadId> DidExchange<I, S> { pub fn get_thread_id(&self) -> &str { self.state.thread_id() } pub fn fail( self, reason: String, problem_code: Option<ProblemCode>, ) -> TransitionResult<DidExchange<I, Abandoned>, AnyProblemReport> { let content = ProblemReportContent::builder() .problem_code(problem_code) .explain(Some(reason.clone())) .build(); let decorators = ProblemReportDecorators::builder() .thread( Thread::builder() .thid(self.state.thread_id().to_string()) .build(), ) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); let problem_report = ProblemReport::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build(); TransitionResult { state: DidExchange { state: Abandoned { reason, request_id: self.state.thread_id().to_string(), }, initiation_type: PhantomData, our_did_document: self.our_did_document, their_did_document: self.their_did_document, }, output: AnyProblemReport::V1_1(problem_report), } } pub fn receive_problem_report( self, problem_report: ProblemReport, ) -> DidExchange<I, Abandoned> { DidExchange { state: Abandoned { reason: problem_report.content.explain.unwrap_or_default(), request_id: self.state.thread_id().to_string(), }, initiation_type: PhantomData, our_did_document: self.our_did_document, their_did_document: self.their_did_document, } } } impl<I, S> DidExchange<I, S> { pub fn from_parts( state: S, their_did_document: DidDocument, our_did_document: DidDocument, ) -> Self { Self { state, initiation_type: PhantomData, our_did_document, their_did_document, } } } impl<I, S> DidExchange<I, S> { pub fn our_did_doc(&self) -> &DidDocument { &self.our_did_document } pub fn their_did_doc(&self) -> &DidDocument { &self.their_did_document } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/state_machine/generic/thin_state.rs
aries/aries_vcx/src/protocols/did_exchange/state_machine/generic/thin_state.rs
// todo: remove text representations, and should definitely not be driven by AATH expectations #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ThinState { #[serde(rename = "request-sent")] RequestSent, #[serde(rename = "response-sent")] ResponseSent, #[serde(rename = "completed")] Completed, #[serde(rename = "abandoned")] Abandoned, }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/state_machine/generic/mod.rs
aries/aries_vcx/src/protocols/did_exchange/state_machine/generic/mod.rs
use std::sync::Arc; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use did_doc::schema::did_doc::DidDocument; use did_parser_nom::Did; use did_peer::peer_did::{numalgos::numalgo4::Numalgo4, PeerDid}; use did_resolver_registry::ResolverRegistry; use messages::{ msg_fields::protocols::did_exchange::v1_x::{ complete::{AnyComplete, Complete}, problem_report::ProblemReport, request::AnyRequest, response::AnyResponse, }, msg_types::protocols::did_exchange::DidExchangeTypeV1, }; use public_key::Key; pub use thin_state::ThinState; use super::{requester::DidExchangeRequester, responder::DidExchangeResponder}; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind}, protocols::did_exchange::{ states::{ abandoned::Abandoned, completed::Completed, requester::request_sent::RequestSent, responder::response_sent::ResponseSent, }, transition::{transition_error::TransitionError, transition_result::TransitionResult}, }, }; mod conversions; mod thin_state; #[derive(Debug, Clone)] pub enum GenericDidExchange { Requester(RequesterState), Responder(ResponderState), } #[derive(Debug, Clone)] pub enum RequesterState { RequestSent(DidExchangeRequester<RequestSent>), Completed(DidExchangeRequester<Completed>), Abandoned(DidExchangeRequester<Abandoned>), } #[derive(Debug, Clone)] pub enum ResponderState { ResponseSent(DidExchangeResponder<ResponseSent>), Completed(DidExchangeResponder<Completed>), Abandoned(DidExchangeResponder<Abandoned>), } impl GenericDidExchange { pub fn our_did_document(&self) -> &DidDocument { match self { GenericDidExchange::Requester(requester_state) => match requester_state { RequesterState::RequestSent(request_sent_state) => request_sent_state.our_did_doc(), RequesterState::Completed(completed_state) => completed_state.our_did_doc(), RequesterState::Abandoned(_abandoned_state) => todo!(), }, GenericDidExchange::Responder(responder_state) => match responder_state { ResponderState::ResponseSent(response_sent_state) => { response_sent_state.our_did_doc() } ResponderState::Completed(completed_state) => completed_state.our_did_doc(), ResponderState::Abandoned(_abandoned_state) => todo!(), }, } } pub fn their_did_doc(&self) -> &DidDocument { match self { GenericDidExchange::Requester(requester_state) => match requester_state { RequesterState::RequestSent(request_sent_state) => { request_sent_state.their_did_doc() } RequesterState::Completed(completed_state) => completed_state.their_did_doc(), RequesterState::Abandoned(_abandoned_state) => todo!(), }, GenericDidExchange::Responder(responder_state) => match responder_state { ResponderState::ResponseSent(response_sent_state) => { response_sent_state.their_did_doc() } ResponderState::Completed(completed_state) => completed_state.their_did_doc(), ResponderState::Abandoned(_abandoned_state) => todo!(), }, } } pub async fn construct_request( resolver_registry: &Arc<ResolverRegistry>, invitation_id: Option<String>, their_did: &Did, our_peer_did: &PeerDid<Numalgo4>, our_label: String, version: DidExchangeTypeV1, ) -> Result<(Self, AnyRequest), AriesVcxError> { let TransitionResult { state, output } = DidExchangeRequester::<RequestSent>::construct_request( resolver_registry, invitation_id, their_did, our_peer_did, our_label, version, ) .await?; Ok(( GenericDidExchange::Requester(RequesterState::RequestSent(state)), output, )) } pub async fn handle_request( wallet: &impl BaseWallet, resolver_registry: &Arc<ResolverRegistry>, request: AnyRequest, our_peer_did: &PeerDid<Numalgo4>, invitation_key: Key, ) -> Result<(Self, AnyResponse), AriesVcxError> { let TransitionResult { state, output } = DidExchangeResponder::<ResponseSent>::receive_request( wallet, resolver_registry, request, our_peer_did, invitation_key, ) .await?; Ok(( GenericDidExchange::Responder(ResponderState::ResponseSent(state)), output, )) } pub async fn handle_response( self, wallet: &impl BaseWallet, invitation_key: &Key, response: AnyResponse, resolver_registry: &Arc<ResolverRegistry>, ) -> Result<(Self, AnyComplete), (Self, AriesVcxError)> { match self { GenericDidExchange::Requester(requester_state) => match requester_state { RequesterState::RequestSent(request_sent_state) => { match request_sent_state .receive_response(wallet, invitation_key, response, resolver_registry) .await { Ok(TransitionResult { state, output }) => Ok(( GenericDidExchange::Requester(RequesterState::Completed(state)), output, )), Err(TransitionError { state, error }) => Err(( GenericDidExchange::Requester(RequesterState::RequestSent(state)), error, )), } } RequesterState::Completed(completed_state) => Err(( GenericDidExchange::Requester(RequesterState::Completed(completed_state)), AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Attempted to handle response in completed state", ), )), RequesterState::Abandoned(abandoned_state) => Err(( GenericDidExchange::Requester(RequesterState::Abandoned(abandoned_state)), AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Attempted to handle response in abandoned state", ), )), }, GenericDidExchange::Responder(responder) => Err(( GenericDidExchange::Responder(responder), AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Attempted to handle response as a responder", ), )), } } pub fn handle_complete(self, complete: Complete) -> Result<Self, (Self, AriesVcxError)> { match self { GenericDidExchange::Responder(responder_state) => match responder_state { ResponderState::ResponseSent(response_sent_state) => { match response_sent_state.receive_complete(complete) { Ok(state) => Ok(GenericDidExchange::Responder(ResponderState::Completed( state, ))), Err(TransitionError { state, error }) => Err(( GenericDidExchange::Responder(ResponderState::ResponseSent(state)), error, )), } } ResponderState::Completed(completed_state) => Err(( GenericDidExchange::Responder(ResponderState::Completed(completed_state)), AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Attempted to handle complete in completed state", ), )), ResponderState::Abandoned(_) => Err(( GenericDidExchange::Responder(responder_state), AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Attempted to handle complete in abandoned state", ), )), }, GenericDidExchange::Requester(requester_state) => Err(( GenericDidExchange::Requester(requester_state), AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Attempted to handle complete as a requester", ), )), } } pub fn handle_problem_report( self, problem_report: ProblemReport, ) -> Result<Self, (Self, AriesVcxError)> { match self { GenericDidExchange::Requester(requester_state) => match requester_state { RequesterState::RequestSent(request_sent_state) => { Ok(GenericDidExchange::Requester(RequesterState::Abandoned( request_sent_state.receive_problem_report(problem_report), ))) } RequesterState::Completed(completed_state) => Err(( GenericDidExchange::Requester(RequesterState::Completed(completed_state)), AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Attempted to handle problem report in completed state", ), )), RequesterState::Abandoned(abandoned_state) => Ok(GenericDidExchange::Requester( RequesterState::Abandoned(abandoned_state), )), }, GenericDidExchange::Responder(responder_state) => match responder_state { ResponderState::ResponseSent(response_sent_state) => { Ok(GenericDidExchange::Responder(ResponderState::Abandoned( response_sent_state.receive_problem_report(problem_report), ))) } ResponderState::Completed(completed_state) => Err(( GenericDidExchange::Responder(ResponderState::Completed(completed_state)), AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Attempted to handle problem report in completed state", ), )), ResponderState::Abandoned(abandoned_state) => Ok(GenericDidExchange::Responder( ResponderState::Abandoned(abandoned_state), )), }, } } pub fn get_state(&self) -> ThinState { match self { GenericDidExchange::Requester(requester_state) => match requester_state { RequesterState::RequestSent(_) => ThinState::RequestSent, RequesterState::Completed(_) => ThinState::Completed, RequesterState::Abandoned(_) => ThinState::Abandoned, }, GenericDidExchange::Responder(responder_state) => match responder_state { ResponderState::ResponseSent(_) => ThinState::RequestSent, ResponderState::Completed(_) => ThinState::Completed, ResponderState::Abandoned(_) => ThinState::Abandoned, }, } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/state_machine/generic/conversions.rs
aries/aries_vcx/src/protocols/did_exchange/state_machine/generic/conversions.rs
use super::{GenericDidExchange, RequesterState, ResponderState}; use crate::protocols::did_exchange::{ state_machine::{requester::DidExchangeRequester, responder::DidExchangeResponder}, states::{ completed::Completed, requester::request_sent::RequestSent, responder::response_sent::ResponseSent, }, }; impl From<DidExchangeRequester<RequestSent>> for GenericDidExchange { fn from(state: DidExchangeRequester<RequestSent>) -> Self { Self::Requester(RequesterState::RequestSent(state)) } } impl From<DidExchangeRequester<Completed>> for GenericDidExchange { fn from(state: DidExchangeRequester<Completed>) -> Self { Self::Requester(RequesterState::Completed(state)) } } impl From<DidExchangeResponder<ResponseSent>> for GenericDidExchange { fn from(state: DidExchangeResponder<ResponseSent>) -> Self { Self::Responder(ResponderState::ResponseSent(state)) } } impl From<DidExchangeResponder<Completed>> for GenericDidExchange { fn from(state: DidExchangeResponder<Completed>) -> Self { Self::Responder(ResponderState::Completed(state)) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/state_machine/requester/helpers.rs
aries/aries_vcx/src/protocols/did_exchange/state_machine/requester/helpers.rs
use chrono::Utc; use did_parser_nom::Did; use messages::{ decorators::{ thread::{Thread, ThreadGoalCode}, timing::Timing, }, msg_fields::protocols::{ did_exchange::v1_x::{ complete::{AnyComplete, Complete, CompleteDecorators}, request::{AnyRequest, Request, RequestContent, RequestDecorators}, }, out_of_band::invitation::{Invitation, OobService}, }, msg_types::{ protocols::did_exchange::{DidExchangeType, DidExchangeTypeV1}, Protocol, }, }; use shared::maybe_known::MaybeKnown; use uuid::Uuid; use crate::errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}; pub fn construct_request( invitation_id: Option<String>, our_did: String, our_label: String, version: DidExchangeTypeV1, ) -> AnyRequest { let msg_id = Uuid::new_v4().to_string(); let thid = msg_id.clone(); let thread = match invitation_id { Some(invitation_id) => Thread::builder().thid(thid).pthid(invitation_id).build(), None => Thread::builder().thid(thid).build(), }; let decorators = RequestDecorators::builder() .thread(Some(thread)) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); let content = RequestContent::builder() .label(our_label) .did(our_did) .did_doc(None) .goal(Some("To establish a connection".into())) // Rejected if non-empty by acapy .goal_code(Some(MaybeKnown::Known(ThreadGoalCode::AriesRelBuild))) // Rejected if non-empty by acapy .build(); let req = Request::builder() .id(msg_id) .content(content) .decorators(decorators) .build(); match version { DidExchangeTypeV1::V1_1(_) => AnyRequest::V1_1(req), DidExchangeTypeV1::V1_0(_) => AnyRequest::V1_0(req), } } pub fn construct_didexchange_complete( // pthid inclusion is overkill in practice, but needed. see: https://github.com/decentralized-identity/aries-rfcs/issues/817 invitation_id: Option<String>, request_id: String, version: DidExchangeTypeV1, ) -> AnyComplete { let thread = match invitation_id { Some(invitation_id) => Thread::builder() .thid(request_id) .pthid(invitation_id) .build(), None => Thread::builder().thid(request_id).build(), }; let decorators = CompleteDecorators::builder() .thread(thread) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); let msg = Complete::builder() .id(Uuid::new_v4().to_string()) .decorators(decorators) .build(); match version { DidExchangeTypeV1::V1_1(_) => AnyComplete::V1_1(msg), DidExchangeTypeV1::V1_0(_) => AnyComplete::V1_0(msg), } } /// We are going to support only DID service values in did-exchange protocol unless there's explicit /// good reason to keep support for "embedded" type of service value. /// This function returns first found DID based service value from invitation. /// TODO: also used by harness, move this to messages crate pub fn invitation_get_first_did_service(invitation: &Invitation) -> VcxResult<Did> { for service in invitation.content.services.iter() { if let OobService::Did(did_string) = service { return Did::parse(did_string.clone()).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!("Invalid DID in invitation: {err}"), ) }); } } Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Invitation does not contain did service", )) } /// Finds the best suitable DIDExchange V1.X version specified in an invitation, or an error if /// none. pub fn invitation_get_acceptable_did_exchange_version( invitation: &Invitation, ) -> VcxResult<DidExchangeTypeV1> { // determine acceptable protocol let mut did_exch_v1_1_accepted = false; let mut did_exch_v1_0_accepted = false; for proto in invitation.content.handshake_protocols.iter().flatten() { let MaybeKnown::Known(Protocol::DidExchangeType(DidExchangeType::V1(exch_proto))) = proto else { continue; }; if matches!(exch_proto, DidExchangeTypeV1::V1_1(_)) { did_exch_v1_1_accepted = true; continue; } if matches!(exch_proto, DidExchangeTypeV1::V1_0(_)) { did_exch_v1_0_accepted = true; } } let version = match (did_exch_v1_1_accepted, did_exch_v1_0_accepted) { (true, _) => DidExchangeTypeV1::new_v1_1(), (false, true) => DidExchangeTypeV1::new_v1_0(), _ => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidInput, "OOB invitation does not have a suitable handshake protocol for DIDExchange", )) } }; Ok(version) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/state_machine/requester/mod.rs
aries/aries_vcx/src/protocols/did_exchange/state_machine/requester/mod.rs
pub mod helpers; mod request_sent; use super::DidExchange; #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)] pub struct Requester; pub type DidExchangeRequester<S> = DidExchange<Requester, S>;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/state_machine/requester/request_sent/mod.rs
aries/aries_vcx/src/protocols/did_exchange/state_machine/requester/request_sent/mod.rs
use std::sync::Arc; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use base64::Engine; use did_doc::schema::did_doc::DidDocument; use did_parser_nom::Did; use did_peer::peer_did::{numalgos::numalgo4::Numalgo4, PeerDid}; use did_resolver::traits::resolvable::resolution_output::DidResolutionOutput; use did_resolver_registry::ResolverRegistry; use messages::{ decorators::attachment::AttachmentType, msg_fields::protocols::did_exchange::{ v1_1::response::Response, v1_x::{complete::AnyComplete, request::AnyRequest, response::AnyResponse}, }, msg_types::protocols::did_exchange::DidExchangeTypeV1, }; use public_key::Key; use super::DidExchangeRequester; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind}, protocols::did_exchange::{ state_machine::{ helpers::{attachment_to_diddoc, jws_verify_attachment, to_transition_error}, requester::helpers::{construct_didexchange_complete, construct_request}, }, states::{completed::Completed, requester::request_sent::RequestSent}, transition::{transition_error::TransitionError, transition_result::TransitionResult}, }, utils::base64::URL_SAFE_LENIENT, }; impl DidExchangeRequester<RequestSent> { pub async fn construct_request( resolver_registry: &Arc<ResolverRegistry>, invitation_id: Option<String>, their_did: &Did, our_peer_did: &PeerDid<Numalgo4>, our_label: String, version: DidExchangeTypeV1, ) -> Result<TransitionResult<Self, AnyRequest>, AriesVcxError> { debug!( "DidExchangeRequester<RequestSent>::construct_request >> their_did: {their_did}, our_peer_did: \ {our_peer_did}" ); let their_did_document = resolver_registry .resolve(their_did, &Default::default()) .await? .did_document; let our_did_document = our_peer_did.resolve_did_doc()?; let request = construct_request( invitation_id.clone(), our_peer_did.to_string(), our_label, version, ); debug!( "DidExchangeRequester<RequestSent>::construct_request << prepared request: {request:?}" ); Ok(TransitionResult { state: DidExchangeRequester::from_parts( RequestSent { request_id: request.inner().id.clone(), invitation_id, }, their_did_document, our_did_document, ), output: request, }) } pub async fn receive_response( self, wallet: &impl BaseWallet, invitation_key: &Key, response: AnyResponse, resolver_registry: &Arc<ResolverRegistry>, ) -> Result<TransitionResult<DidExchangeRequester<Completed>, AnyComplete>, TransitionError<Self>> { debug!("DidExchangeRequester<RequestSent>::receive_response >> response: {response:?}"); let version = response.get_version(); let response = response.into_v1_1(); if response.decorators.thread.thid != self.state.request_id { return Err(TransitionError { error: AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Response thread ID does not match request ID", ), state: self, }); } let did_document = extract_and_verify_responder_did_doc( wallet, invitation_key, response, resolver_registry, ) .await .map_err(to_transition_error(self.clone()))?; let complete_message = construct_didexchange_complete( self.state.invitation_id, self.state.request_id.clone(), version, ); debug!( "DidExchangeRequester<RequestSent>::receive_response << complete_message: {complete_message:?}" ); Ok(TransitionResult { state: DidExchangeRequester::from_parts( Completed { request_id: self.state.request_id, }, did_document, self.our_did_document, ), output: complete_message, }) } } async fn extract_and_verify_responder_did_doc( wallet: &impl BaseWallet, invitation_key: &Key, response: Response, resolver_registry: &Arc<ResolverRegistry>, ) -> Result<DidDocument, AriesVcxError> { let their_did = response.content.did; if let Some(did_doc_attach) = response.content.did_doc { debug!( "Verifying signature of DIDDoc attached to response: {did_doc_attach:?} against \ expected key {invitation_key:?}" ); let verified_signature = jws_verify_attachment(&did_doc_attach, invitation_key, wallet).await?; if !verified_signature { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidInput, "DIDExchange response did not have a valid DIDDoc signature from the expected \ inviter", )); } let did_doc = attachment_to_diddoc(did_doc_attach)?; if did_doc.id().to_string() != their_did { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidInput, "DIDExchange response had a DIDDoc which did not match the response DID", )); } return Ok(did_doc); } if let Some(did_rotate_attach) = response.content.did_rotate { debug!( "Verifying signature of DID Rotate attached to response: {did_rotate_attach:?} \ against expected key {invitation_key:?}" ); let verified_signature = jws_verify_attachment(&did_rotate_attach, invitation_key, wallet).await?; if !verified_signature { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidInput, "DIDExchange response did not have a valid DID rotate signature from the expected \ inviter", )); } let AttachmentType::Base64(signed_did_b64) = did_rotate_attach.data.content else { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::EncodeError, "DIDExchange response did not have a valid DID rotate attachment", )); }; let did_bytes = URL_SAFE_LENIENT.decode(signed_did_b64).map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::EncodeError, "DIDExchange response did not have a valid base64 did rotate attachment", ) })?; let signed_did = String::from_utf8(did_bytes).map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::EncodeError, "DIDExchange response did not have a valid UTF8 did rotate attachment", ) })?; if signed_did != their_did { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidInput, format!( "DIDExchange response had a DID rotate which did not match the response DID. \ Wanted {their_did}, found {signed_did}" ), )); } let did = &Did::parse(their_did)?; let DidResolutionOutput { did_document: did_doc, .. } = resolver_registry.resolve(did, &Default::default()).await?; return Ok(did_doc); } // default to error Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidInput, "DIDExchange response could not be verified. No DIDDoc nor DIDRotate was attached.", )) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/state_machine/responder/mod.rs
aries/aries_vcx/src/protocols/did_exchange/state_machine/responder/mod.rs
mod response_sent; use super::DidExchange; #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)] pub struct Responder; pub type DidExchangeResponder<S> = DidExchange<Responder, S>;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/state_machine/responder/response_sent/mod.rs
aries/aries_vcx/src/protocols/did_exchange/state_machine/responder/response_sent/mod.rs
use std::sync::Arc; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use did_doc::schema::did_doc::DidDocument; use did_peer::peer_did::{numalgos::numalgo4::Numalgo4, PeerDid}; use did_resolver_registry::ResolverRegistry; use messages::{ msg_fields::protocols::did_exchange::v1_x::{ complete::Complete, request::{AnyRequest, Request}, response::AnyResponse, }, msg_types::protocols::did_exchange::DidExchangeTypeV1, }; use public_key::Key; use super::DidExchangeResponder; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind}, protocols::did_exchange::{ state_machine::helpers::{ assemble_did_rotate_attachment, attachment_to_diddoc, construct_response_v1_0, construct_response_v1_1, ddo_to_attach, jws_sign_attach, }, states::{completed::Completed, responder::response_sent::ResponseSent}, transition::{transition_error::TransitionError, transition_result::TransitionResult}, }, }; impl DidExchangeResponder<ResponseSent> { pub async fn receive_request( wallet: &impl BaseWallet, resolver_registry: &Arc<ResolverRegistry>, request: AnyRequest, our_peer_did: &PeerDid<Numalgo4>, invitation_key: Key, ) -> Result<TransitionResult<DidExchangeResponder<ResponseSent>, AnyResponse>, AriesVcxError> { debug!( "DidExchangeResponder<ResponseSent>::receive_request >> request: {request:?}, our_peer_did: \ {our_peer_did}, invitation_key: {invitation_key:?}" ); let version = request.get_version(); let request = request.into_inner(); let their_ddo = resolve_ddo_from_request(resolver_registry, &request).await?; let our_did_document = our_peer_did.resolve_did_doc()?; let unsigned_attachment = match version { DidExchangeTypeV1::V1_1(_) => assemble_did_rotate_attachment(our_peer_did.did()), DidExchangeTypeV1::V1_0(_) => ddo_to_attach(our_did_document.clone())?, }; let attachment = jws_sign_attach(unsigned_attachment, invitation_key, wallet).await?; let request_id = request.id.clone(); let request_pthid = request.decorators.thread.and_then(|thid| thid.pthid); let response = match version { DidExchangeTypeV1::V1_1(_) => AnyResponse::V1_1(construct_response_v1_1( request_pthid, request_id, our_peer_did.did(), attachment, )), DidExchangeTypeV1::V1_0(_) => AnyResponse::V1_0(construct_response_v1_0( request_pthid, request_id, our_peer_did.did(), attachment, )), }; debug!( "DidExchangeResponder<ResponseSent>::receive_request << prepared response: {response:?}" ); Ok(TransitionResult { state: DidExchangeResponder::from_parts( ResponseSent { request_id: request.id, }, their_ddo, our_did_document, ), output: response, }) } pub fn receive_complete( self, complete: Complete, ) -> Result<DidExchangeResponder<Completed>, TransitionError<Self>> { if complete.decorators.thread.thid != self.state.request_id { return Err(TransitionError { error: AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Thread ID of the complete message does not match the id of the request", ), state: self, }); } Ok(DidExchangeResponder::from_parts( Completed { request_id: self.state.request_id, }, self.their_did_document, self.our_did_document, )) } } async fn resolve_ddo_from_request( resolver_registry: &Arc<ResolverRegistry>, request: &Request, ) -> Result<DidDocument, AriesVcxError> { Ok(request .content .did_doc .clone() .map(attachment_to_diddoc) .transpose()? .unwrap_or( resolver_registry .resolve(&request.content.did.parse()?, &Default::default()) .await? .did_document, )) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/states/abandoned.rs
aries/aries_vcx/src/protocols/did_exchange/states/abandoned.rs
use super::traits::ThreadId; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Abandoned { pub reason: String, pub request_id: String, } impl ThreadId for Abandoned { fn thread_id(&self) -> &str { self.request_id.as_str() } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/states/completed.rs
aries/aries_vcx/src/protocols/did_exchange/states/completed.rs
use std::clone::Clone; use super::traits::ThreadId; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Completed { pub request_id: String, } impl ThreadId for Completed { fn thread_id(&self) -> &str { self.request_id.as_str() } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/states/mod.rs
aries/aries_vcx/src/protocols/did_exchange/states/mod.rs
pub mod abandoned; pub mod completed; pub mod requester; pub mod responder; pub mod traits;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/states/traits.rs
aries/aries_vcx/src/protocols/did_exchange/states/traits.rs
pub trait ThreadId { fn thread_id(&self) -> &str; }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/states/requester/request_sent.rs
aries/aries_vcx/src/protocols/did_exchange/states/requester/request_sent.rs
use crate::protocols::did_exchange::states::traits::ThreadId; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct RequestSent { pub request_id: String, /* Note: Historical artifact in Aries RFC, used to fill pthread * value in Complete message * See more info here: https://github.com/decentralized-identity/aries-rfcs/issues/817 */ pub invitation_id: Option<String>, } impl ThreadId for RequestSent { fn thread_id(&self) -> &str { self.request_id.as_str() } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/states/requester/mod.rs
aries/aries_vcx/src/protocols/did_exchange/states/requester/mod.rs
pub mod request_sent;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/states/responder/response_sent.rs
aries/aries_vcx/src/protocols/did_exchange/states/responder/response_sent.rs
use crate::protocols::did_exchange::states::traits::ThreadId; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct ResponseSent { pub request_id: String, } impl ThreadId for ResponseSent { fn thread_id(&self) -> &str { self.request_id.as_str() } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/did_exchange/states/responder/mod.rs
aries/aries_vcx/src/protocols/did_exchange/states/responder/mod.rs
pub mod response_sent;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/mod.rs
aries/aries_vcx/src/protocols/issuance/mod.rs
use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use crate::errors::error::prelude::*; pub mod holder; pub mod issuer; pub async fn is_cred_def_revokable( ledger: &impl AnoncredsLedgerRead, cred_def_id: &str, ) -> VcxResult<bool> { let cred_def_json = ledger .get_cred_def(&cred_def_id.to_string().try_into()?, None) .await .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidLedgerResponse, format!("Failed to obtain credential definition from ledger or cache: {err}"), ) })?; let parsed_cred_def = serde_json::to_value(&cred_def_json).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!( "Failed deserialize credential definition json {cred_def_json:?}\nError: {err}" ), ) })?; Ok(!parsed_cred_def["value"]["revocation"].is_null()) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/issuer/mod.rs
aries/aries_vcx/src/protocols/issuance/issuer/mod.rs
pub mod state_machine; pub mod states;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/issuer/state_machine.rs
aries/aries_vcx/src/protocols/issuance/issuer/state_machine.rs
use std::{fmt::Display, path::Path}; use anoncreds_types::data_types::messages::credential::Credential; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use chrono::Utc; use messages::{ decorators::{please_ack::PleaseAck, thread::Thread, timing::Timing}, msg_fields::protocols::{ cred_issuance::{ v1::{ ack::AckCredentialV1, issue_credential::{ IssueCredentialV1, IssueCredentialV1Content, IssueCredentialV1Decorators, }, offer_credential::{ OfferCredentialV1, OfferCredentialV1Content, OfferCredentialV1Decorators, }, propose_credential::ProposeCredentialV1, request_credential::RequestCredentialV1, CredentialIssuanceV1, CredentialPreviewV1, }, CredentialIssuance, }, report_problem::ProblemReport, }, AriesMessage, }; use uuid::Uuid; use crate::{ common::credentials::{encoding::encode_attributes, is_cred_revoked}, errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, handlers::util::{ get_attach_as_string, make_attach_from_str, matches_opt_thread_id, verify_thread_id, AttachmentId, OfferInfo, Status, }, protocols::{ common::build_problem_report_msg, issuance::issuer::states::{ credential_set::CredentialSetState, finished::FinishedState, initial::InitialIssuerState, offer_set::OfferSetState, proposal_received::ProposalReceivedState, requested_received::RequestReceivedState, }, }, }; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum IssuerFullState { Initial(InitialIssuerState), OfferSet(OfferSetState), ProposalReceived(ProposalReceivedState), RequestReceived(RequestReceivedState), CredentialSet(CredentialSetState), Finished(FinishedState), } #[derive(Debug, PartialEq, Eq)] pub enum IssuerState { Initial, OfferSet, ProposalReceived, RequestReceived, CredentialSet, Finished, Failed, } // todo: Use this approach for logging in other protocols as well. impl Display for IssuerFullState { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> { match *self { IssuerFullState::Initial(_) => f.write_str("Initial"), IssuerFullState::OfferSet(_) => f.write_str("OfferSet"), IssuerFullState::ProposalReceived(_) => f.write_str("ProposalReceived"), IssuerFullState::RequestReceived(_) => f.write_str("RequestReceived"), IssuerFullState::CredentialSet(_) => f.write_str("CredentialSet"), IssuerFullState::Finished(_) => f.write_str("Finished"), } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct RevocationInfoV1 { pub cred_rev_id: Option<String>, pub rev_reg_id: Option<String>, pub tails_file: Option<String>, } impl Default for IssuerFullState { fn default() -> Self { Self::Initial(InitialIssuerState::default()) } } #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct IssuerSM { pub(crate) source_id: String, pub(crate) thread_id: String, pub(crate) state: IssuerFullState, } fn build_credential_message( libindy_credential: Credential, thread_id: String, ) -> IssueCredentialV1 { let id = Uuid::new_v4().to_string(); let content = IssueCredentialV1Content::builder() .credentials_attach(vec![make_attach_from_str!( &serde_json::to_string(&libindy_credential).unwrap(), AttachmentId::Credential.as_ref().to_string() )]) .build(); let decorators = IssueCredentialV1Decorators::builder() .thread(Thread::builder().thid(thread_id).build()) .please_ack(PleaseAck::builder().on(vec![]).build()) .build(); IssueCredentialV1::builder() .id(id) .content(content) .decorators(decorators) .build() } fn build_credential_offer( thread_id: &str, credential_offer: &str, credential_preview: CredentialPreviewV1, comment: Option<String>, ) -> VcxResult<OfferCredentialV1> { let id = thread_id.to_owned(); let content = OfferCredentialV1Content::builder() .credential_preview(credential_preview) .offers_attach(vec![make_attach_from_str!( &credential_offer, AttachmentId::CredentialOffer.as_ref().to_string() )]); let content = if let Some(comment) = comment { content.comment(comment).build() } else { content.build() }; let decorators = OfferCredentialV1Decorators::builder() .timing(Timing::builder().out_time(Utc::now()).build()) .build(); Ok(OfferCredentialV1::builder() .id(id) .content(content) .decorators(decorators) .build()) } impl IssuerSM { pub fn new(source_id: &str) -> Self { Self { source_id: source_id.to_string(), thread_id: Uuid::new_v4().to_string(), state: IssuerFullState::Initial(InitialIssuerState {}), } } pub fn from_proposal(source_id: &str, credential_proposal: &ProposeCredentialV1) -> Self { Self { thread_id: credential_proposal.id.clone(), source_id: source_id.to_string(), state: IssuerFullState::ProposalReceived(ProposalReceivedState::new( credential_proposal.clone(), None, )), } } pub fn get_source_id(&self) -> String { self.source_id.clone() } pub fn step(source_id: String, thread_id: String, state: IssuerFullState) -> Self { Self { source_id, thread_id, state, } } pub fn get_revocation_info(&self) -> Option<RevocationInfoV1> { match &self.state { IssuerFullState::CredentialSet(state) => state.revocation_info_v1.clone(), IssuerFullState::Finished(state) => state.revocation_info_v1.clone(), _ => None, } } pub fn get_rev_id(&self) -> VcxResult<u32> { let err = AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "No revocation info found - is this credential revokable?", ); let rev_id = match &self.state { IssuerFullState::CredentialSet(state) => state .revocation_info_v1 .as_ref() .ok_or(err)? .cred_rev_id .to_owned(), IssuerFullState::Finished(state) => state .revocation_info_v1 .as_ref() .ok_or(err)? .cred_rev_id .to_owned(), _ => None, }; rev_id .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Revocation info does not contain rev id", )) .and_then(|s| s.parse().map_err(Into::into)) } pub fn get_rev_reg_id(&self) -> VcxResult<String> { let rev_registry = match &self.state { IssuerFullState::Initial(_state) => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "No revocation info available in the initial state", )); } IssuerFullState::OfferSet(state) => state.rev_reg_id.clone(), IssuerFullState::ProposalReceived(state) => match &state.offer_info { Some(offer_info) => offer_info.rev_reg_id.clone(), _ => None, }, IssuerFullState::RequestReceived(state) => state.rev_reg_id.clone(), IssuerFullState::CredentialSet(state) => { state .revocation_info_v1 .clone() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "No revocation info found - is this credential revokable?", ))? .rev_reg_id } IssuerFullState::Finished(state) => { state .revocation_info_v1 .clone() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "No revocation info found - is this credential revokable?", ))? .rev_reg_id } }; rev_registry.ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "No revocation registry id found on revocation info - is this credential revokable?", )) } pub fn is_revokable(&self) -> bool { fn _is_revokable(rev_info: &Option<RevocationInfoV1>) -> bool { match rev_info { Some(rev_info) => rev_info.cred_rev_id.is_some(), None => false, } } match &self.state { IssuerFullState::CredentialSet(state) => _is_revokable(&state.revocation_info_v1), IssuerFullState::Finished(state) => _is_revokable(&state.revocation_info_v1), _ => false, } } pub async fn is_revoked(&self, ledger: &impl AnoncredsLedgerRead) -> VcxResult<bool> { if self.is_revokable() { let rev_reg_id = self.get_rev_reg_id()?; let rev_id = self.get_rev_id()?; is_cred_revoked(ledger, &rev_reg_id, rev_id).await } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Unable to check revocation status - this credential is not revokable", )) } } pub fn get_state(&self) -> IssuerState { match self.state { IssuerFullState::Initial(_) => IssuerState::Initial, IssuerFullState::ProposalReceived(_) => IssuerState::ProposalReceived, IssuerFullState::OfferSet(_) => IssuerState::OfferSet, IssuerFullState::RequestReceived(_) => IssuerState::RequestReceived, IssuerFullState::CredentialSet(_) => IssuerState::CredentialSet, IssuerFullState::Finished(ref status) => match status.status { Status::Success => IssuerState::Finished, _ => IssuerState::Failed, }, } } pub fn get_proposal(&self) -> VcxResult<ProposeCredentialV1> { match &self.state { IssuerFullState::ProposalReceived(state) => Ok(state.credential_proposal.clone()), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Proposal is only available in ProposalReceived state", )), } } pub fn build_credential_offer_msg( self, credential_offer: &str, credential_preview: CredentialPreviewV1, comment: Option<String>, offer_info: &OfferInfo, ) -> VcxResult<Self> { let Self { state, source_id, thread_id, } = self; let state = match state { IssuerFullState::Initial(_) | IssuerFullState::OfferSet(_) | IssuerFullState::ProposalReceived(_) => { let cred_offer_msg = build_credential_offer( &thread_id, credential_offer, credential_preview, comment, )?; IssuerFullState::OfferSet(OfferSetState::new( cred_offer_msg, &offer_info.credential_json, offer_info.cred_def_id.clone(), offer_info.rev_reg_id.clone(), offer_info.tails_file.clone(), )) } _ => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!("Can not set_offer in current state {state}."), )); } }; Ok(Self::step(source_id, thread_id, state)) } pub fn get_credential_offer_msg(&self) -> VcxResult<OfferCredentialV1> { match &self.state { IssuerFullState::OfferSet(state) => Ok(state.offer.clone()), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!( "Can not get_credential_offer in current state {}.", self.state ), )), } } pub fn receive_proposal(self, proposal: ProposeCredentialV1) -> VcxResult<Self> { verify_thread_id( &self.thread_id, &AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::ProposeCredential(proposal.clone()), )), )?; let (state, thread_id) = match self.state { IssuerFullState::Initial(_) => { let thread_id = proposal.id.to_string(); let state = IssuerFullState::ProposalReceived(ProposalReceivedState::new(proposal, None)); (state, thread_id) } IssuerFullState::OfferSet(_) => { let state = IssuerFullState::ProposalReceived(ProposalReceivedState::new(proposal, None)); (state, self.thread_id.clone()) } s => { warn!("Unable to receive credential proposal in state {s}"); (s, self.thread_id.clone()) } }; Ok(Self { state, thread_id, ..self }) } pub fn receive_request(self, request: RequestCredentialV1) -> VcxResult<Self> { verify_thread_id( &self.thread_id, &AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::RequestCredential(request.clone()), )), )?; let state = match self.state { IssuerFullState::OfferSet(state_data) => IssuerFullState::RequestReceived( RequestReceivedState::from_offer_set_and_request(state_data, request), ), s => { warn!("Unable to receive credential request in state {s}"); s } }; Ok(Self { state, ..self }) } pub async fn build_credential( self, wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ) -> VcxResult<Self> { let state = match self.state { IssuerFullState::RequestReceived(state_data) => { match create_credential( wallet, anoncreds, &state_data.request, &state_data.rev_reg_id, &state_data.tails_file, &state_data.offer, &state_data.cred_data, self.thread_id.clone(), ) .await { Ok((msg_issue_credential, cred_rev_id)) => { // todo: have constructor for this IssuerFullState::CredentialSet(CredentialSetState { msg_issue_credential, revocation_info_v1: Some(RevocationInfoV1 { cred_rev_id: cred_rev_id.as_ref().map(ToString::to_string), rev_reg_id: state_data.rev_reg_id, tails_file: state_data.tails_file, }), }) } // todo: 1. Don't transition, throw error, add to_failed transition() api which // SM consumer can call 2. Also create separate // "Failed" state Err(err) => { let problem_report = build_problem_report_msg(Some(err.to_string()), &self.thread_id); error!( "Failed to create credential, generated problem report \ {problem_report:?}", ); IssuerFullState::Finished(FinishedState::from_request_and_error( state_data, problem_report, )) } } } _ => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Invalid action", )); } }; Ok(Self { state, ..self }) } pub fn get_msg_issue_credential(self) -> VcxResult<IssueCredentialV1> { match self.state { IssuerFullState::CredentialSet(ref state_data) => { let mut msg_issue_credential: IssueCredentialV1 = state_data.msg_issue_credential.clone(); let timing = Timing::builder().out_time(Utc::now()).build(); msg_issue_credential.decorators.timing = Some(timing); Ok(msg_issue_credential) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Invalid action", )), } } pub fn receive_ack(self, ack: AckCredentialV1) -> VcxResult<Self> { verify_thread_id( &self.thread_id, &AriesMessage::CredentialIssuance(CredentialIssuance::V1(CredentialIssuanceV1::Ack( ack, ))), )?; let state = match self.state { IssuerFullState::CredentialSet(state_data) => { IssuerFullState::Finished(FinishedState::from_credential_set_state(state_data)) } s => { warn!("Unable to receive credential ack in state {s}"); s } }; Ok(Self { state, ..self }) } pub fn receive_problem_report(self, problem_report: ProblemReport) -> VcxResult<Self> { verify_thread_id( &self.thread_id, &AriesMessage::ReportProblem(problem_report.clone()), )?; let state = match self.state { IssuerFullState::OfferSet(state_data) => IssuerFullState::Finished( FinishedState::from_offer_set_and_error(state_data, problem_report), ), IssuerFullState::CredentialSet(state_data) => { IssuerFullState::Finished(FinishedState::from_credential_set_state(state_data)) } s => { warn!("Unable to receive credential ack in state {s}"); s } }; Ok(Self { state, ..self }) } pub fn credential_status(&self) -> u32 { trace!("Issuer::credential_status >>>"); match self.state { IssuerFullState::Finished(ref state) => state.status.code(), _ => Status::Undefined.code(), } } pub fn is_terminal_state(&self) -> bool { matches!(self.state, IssuerFullState::Finished(_)) } pub fn thread_id(&self) -> VcxResult<String> { Ok(self.thread_id.clone()) } pub fn get_problem_report(&self) -> VcxResult<ProblemReport> { match self.state { IssuerFullState::Finished(ref state) => match &state.status { Status::Failed(problem_report) => Ok(problem_report.clone()), Status::Declined(problem_report) => Ok(problem_report.clone()), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "No problem report available in current state", )), }, _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "No problem report available in current state", )), } } } #[allow(clippy::too_many_arguments)] async fn create_credential( wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, request: &RequestCredentialV1, rev_reg_id: &Option<String>, tails_file: &Option<String>, offer: &OfferCredentialV1, cred_data: &str, thread_id: String, ) -> VcxResult<(IssueCredentialV1, Option<u32>)> { let offer = get_attach_as_string!(&offer.content.offers_attach); trace!( "Issuer::_create_credential >>> request: {request:?}, rev_reg_id: {rev_reg_id:?}, tails_file: {tails_file:?}, offer: \ {offer}, cred_data: {cred_data}, thread_id: {thread_id}" ); if !matches_opt_thread_id!(request, thread_id.as_str()) { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, "Cannot handle credential request: thread id does not match", )); }; let request = get_attach_as_string!(&request.content.requests_attach); let cred_data = encode_attributes(cred_data)?; let (libindy_credential, cred_rev_id) = anoncreds .issuer_create_credential( wallet, serde_json::from_str(&offer)?, serde_json::from_str(&request)?, serde_json::from_str(&cred_data)?, rev_reg_id .to_owned() .map(TryInto::try_into) .transpose()? .as_ref(), tails_file.clone().as_deref().map(Path::new), ) .await?; let msg_issue_credential = build_credential_message(libindy_credential, thread_id); Ok((msg_issue_credential, cred_rev_id)) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/issuer/states/offer_set.rs
aries/aries_vcx/src/protocols/issuance/issuer/states/offer_set.rs
use anoncreds_types::data_types::identifiers::cred_def_id::CredentialDefinitionId; use messages::msg_fields::protocols::{ cred_issuance::v1::{ offer_credential::OfferCredentialV1, request_credential::RequestCredentialV1, }, report_problem::ProblemReport, }; use crate::{ handlers::util::Status, protocols::issuance::issuer::{ state_machine::RevocationInfoV1, states::{finished::FinishedState, requested_received::RequestReceivedState}, }, }; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct OfferSetState { pub offer: OfferCredentialV1, pub credential_json: String, pub cred_def_id: CredentialDefinitionId, pub rev_reg_id: Option<String>, pub tails_file: Option<String>, } impl OfferSetState { pub fn new( cred_offer_msg: OfferCredentialV1, credential_json: &str, cred_def_id: CredentialDefinitionId, rev_reg_id: Option<String>, tails_file: Option<String>, ) -> Self { OfferSetState { offer: cred_offer_msg, credential_json: credential_json.into(), cred_def_id, rev_reg_id, tails_file, } } } impl RequestReceivedState { pub fn from_offer_set_and_request(state: OfferSetState, request: RequestCredentialV1) -> Self { trace!("SM is now in Request Received state"); RequestReceivedState { offer: state.offer, cred_data: state.credential_json, rev_reg_id: state.rev_reg_id, tails_file: state.tails_file, request, } } } impl FinishedState { pub fn from_offer_set_and_error(state: OfferSetState, err: ProblemReport) -> Self { trace!("SM is now in Finished state"); FinishedState { cred_id: None, revocation_info_v1: Some(RevocationInfoV1 { cred_rev_id: None, rev_reg_id: state.rev_reg_id, tails_file: state.tails_file, }), status: Status::Failed(err), } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/issuer/states/proposal_received.rs
aries/aries_vcx/src/protocols/issuance/issuer/states/proposal_received.rs
use messages::msg_fields::protocols::cred_issuance::v1::propose_credential::ProposeCredentialV1; use crate::handlers::util::OfferInfo; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ProposalReceivedState { pub credential_proposal: ProposeCredentialV1, pub offer_info: Option<OfferInfo>, } impl ProposalReceivedState { pub fn new(credential_proposal: ProposeCredentialV1, offer_info: Option<OfferInfo>) -> Self { Self { credential_proposal, offer_info, } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/issuer/states/finished.rs
aries/aries_vcx/src/protocols/issuance/issuer/states/finished.rs
use crate::{handlers::util::Status, protocols::issuance::issuer::state_machine::RevocationInfoV1}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct FinishedState { pub cred_id: Option<String>, pub revocation_info_v1: Option<RevocationInfoV1>, pub status: Status, }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/issuer/states/mod.rs
aries/aries_vcx/src/protocols/issuance/issuer/states/mod.rs
pub(super) mod credential_set; pub(super) mod finished; pub(super) mod initial; pub(super) mod offer_set; pub(super) mod proposal_received; pub(super) mod requested_received;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/issuer/states/initial.rs
aries/aries_vcx/src/protocols/issuance/issuer/states/initial.rs
#[derive(Serialize, Deserialize, Default, Debug, Clone, PartialEq, Eq)] pub struct InitialIssuerState {}
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/issuer/states/requested_received.rs
aries/aries_vcx/src/protocols/issuance/issuer/states/requested_received.rs
use messages::msg_fields::protocols::{ cred_issuance::v1::{ offer_credential::OfferCredentialV1, request_credential::RequestCredentialV1, }, report_problem::ProblemReport, }; use crate::{ handlers::util::Status, protocols::issuance::issuer::{ state_machine::RevocationInfoV1, states::finished::FinishedState, }, }; // TODO: Use OfferInfo instead of ind. fields #[derive(Serialize, Deserialize, Debug, Clone)] pub struct RequestReceivedState { pub offer: OfferCredentialV1, pub cred_data: String, pub rev_reg_id: Option<String>, pub tails_file: Option<String>, pub request: RequestCredentialV1, } impl FinishedState { pub fn from_request_and_error(state: RequestReceivedState, err: ProblemReport) -> Self { trace!("SM is now in Finished state"); FinishedState { cred_id: None, revocation_info_v1: Some(RevocationInfoV1 { cred_rev_id: None, rev_reg_id: state.rev_reg_id, tails_file: state.tails_file, }), status: Status::Failed(err), } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/issuer/states/credential_set.rs
aries/aries_vcx/src/protocols/issuance/issuer/states/credential_set.rs
use messages::msg_fields::protocols::cred_issuance::v1::issue_credential::IssueCredentialV1; use crate::{ handlers::util::Status, protocols::issuance::issuer::{ state_machine::RevocationInfoV1, states::finished::FinishedState, }, }; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CredentialSetState { pub revocation_info_v1: Option<RevocationInfoV1>, pub msg_issue_credential: IssueCredentialV1, } impl FinishedState { pub fn from_credential_set_state(state: CredentialSetState) -> Self { trace!("SM is now in Finished state"); FinishedState { cred_id: None, revocation_info_v1: state.revocation_info_v1, status: Status::Success, } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/holder/mod.rs
aries/aries_vcx/src/protocols/issuance/holder/mod.rs
pub mod state_machine; pub mod states;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/holder/state_machine.rs
aries/aries_vcx/src/protocols/issuance/holder/state_machine.rs
use std::fmt; use anoncreds_types::data_types::{ identifiers::schema_id::SchemaId, messages::cred_offer::CredentialOffer, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use chrono::Utc; use did_parser_nom::Did; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::{ cred_issuance::{ v1::{ issue_credential::IssueCredentialV1, offer_credential::OfferCredentialV1, propose_credential::ProposeCredentialV1, request_credential::{ RequestCredentialV1, RequestCredentialV1Content, RequestCredentialV1Decorators, }, CredentialIssuanceV1, }, CredentialIssuance, }, report_problem::ProblemReport, }, AriesMessage, }; use uuid::Uuid; use crate::{ common::credentials::{get_cred_rev_id, is_cred_revoked}, errors::error::prelude::*, global::settings, handlers::util::{ get_attach_as_string, make_attach_from_str, verify_thread_id, AttachmentId, Status, }, protocols::{ common::build_problem_report_msg, issuance::holder::states::{ finished::FinishedHolderState, initial::InitialHolderState, offer_received::OfferReceivedState, proposal_set::ProposalSetState, request_set::RequestSetState, }, }, }; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum HolderFullState { Initial(InitialHolderState), ProposalSet(ProposalSetState), OfferReceived(OfferReceivedState), RequestSet(RequestSetState), Finished(FinishedHolderState), } #[derive(Debug, PartialEq, Eq)] pub enum HolderState { Initial, ProposalSet, OfferReceived, RequestSet, Finished, Failed, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct HolderSM { pub(crate) state: HolderFullState, pub(crate) source_id: String, pub(crate) thread_id: String, } impl fmt::Display for HolderFullState { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { HolderFullState::Initial(_) => f.write_str("Initial"), HolderFullState::ProposalSet(_) => f.write_str("ProposalSet"), HolderFullState::OfferReceived(_) => f.write_str("OfferReceived"), HolderFullState::RequestSet(_) => f.write_str("RequestSet"), HolderFullState::Finished(_) => f.write_str("Finished"), } } } fn _build_credential_request_msg( credential_request_attach: String, thread_id: &str, ) -> RequestCredentialV1 { let content = RequestCredentialV1Content::builder() .requests_attach(vec![make_attach_from_str!( &credential_request_attach, AttachmentId::CredentialRequest.as_ref().to_string() )]) .build(); let decorators = RequestCredentialV1Decorators::builder() .thread(Thread::builder().thid(thread_id.to_owned()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); RequestCredentialV1::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build() } impl HolderSM { pub fn new(source_id: String) -> Self { HolderSM { thread_id: Uuid::new_v4().to_string(), state: HolderFullState::Initial(InitialHolderState), source_id, } } pub fn from_offer(offer: OfferCredentialV1, source_id: String) -> Self { HolderSM { thread_id: offer.id.clone(), state: HolderFullState::OfferReceived(OfferReceivedState::new(offer)), source_id, } } pub fn with_proposal(propose_credential: ProposeCredentialV1, source_id: String) -> Self { HolderSM { thread_id: propose_credential.id.clone(), state: HolderFullState::ProposalSet(ProposalSetState::new(propose_credential)), source_id, } } pub fn get_source_id(&self) -> String { self.source_id.clone() } pub fn get_state(&self) -> HolderState { match self.state { HolderFullState::Initial(_) => HolderState::Initial, HolderFullState::ProposalSet(_) => HolderState::ProposalSet, HolderFullState::OfferReceived(_) => HolderState::OfferReceived, HolderFullState::RequestSet(_) => HolderState::RequestSet, HolderFullState::Finished(ref status) => match status.status { Status::Success => HolderState::Finished, _ => HolderState::Failed, }, } } #[allow(dead_code)] pub fn get_proposal(&self) -> VcxResult<ProposeCredentialV1> { match &self.state { HolderFullState::ProposalSet(state) => Ok(state.credential_proposal.clone()), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Proposal not available in this state", )), } } pub fn set_proposal(self, proposal: ProposeCredentialV1) -> VcxResult<Self> { trace!("HolderSM::set_proposal >>"); verify_thread_id( &self.thread_id, &AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::ProposeCredential(proposal.clone()), )), )?; let state = match self.state { HolderFullState::Initial(_) => { let mut proposal = proposal; proposal.id.clone_from(&self.thread_id); HolderFullState::ProposalSet(ProposalSetState::new(proposal)) } HolderFullState::OfferReceived(_) => { let mut proposal = proposal; proposal.id.clone_from(&self.thread_id); HolderFullState::ProposalSet(ProposalSetState::new(proposal)) } s => { warn!("Unable to set credential proposal in state {s}"); s } }; Ok(Self { state, ..self }) } pub fn receive_offer(self, offer: OfferCredentialV1) -> VcxResult<Self> { trace!("HolderSM::receive_offer >>"); verify_thread_id( &self.thread_id, &AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::OfferCredential(offer.clone()), )), )?; let state = match self.state { HolderFullState::ProposalSet(_) => { HolderFullState::OfferReceived(OfferReceivedState::new(offer)) } s => { warn!("Unable to receive credential offer in state {s}"); s } }; Ok(Self { state, ..self }) } pub async fn prepare_credential_request<'a>( self, wallet: &impl BaseWallet, ledger: &'a impl AnoncredsLedgerRead, anoncreds: &'a impl BaseAnonCreds, my_pw_did: Did, ) -> VcxResult<Self> { trace!("HolderSM::prepare_credential_request >>"); let state = match self.state { HolderFullState::OfferReceived(state_data) => { match build_credential_request_msg( wallet, ledger, anoncreds, self.thread_id.clone(), my_pw_did, &state_data.offer, ) .await { Ok((msg_credential_request, req_meta, cred_def_json, schema_id)) => { HolderFullState::RequestSet(RequestSetState { msg_credential_request, req_meta, cred_def_json, schema_id, }) } Err(err) => { let problem_report = build_problem_report_msg(Some(err.to_string()), &self.thread_id); error!( "Failed to create credential request with error {err}, generating \ problem report: {problem_report:?}" ); HolderFullState::Finished(FinishedHolderState::new(problem_report)) } } } s => { warn!("Unable to set credential request in state {s}"); s } }; Ok(Self { state, ..self }) } pub fn decline_offer(self, comment: Option<String>) -> VcxResult<Self> { trace!("HolderSM::decline_offer >>"); let state = match self.state { HolderFullState::OfferReceived(_) => { let problem_report = build_problem_report_msg(comment, &self.thread_id); HolderFullState::Finished(FinishedHolderState::new(problem_report)) } s => { warn!("Unable to decline credential offer in state {s}"); s } }; Ok(Self { state, ..self }) } pub async fn receive_credential<'a>( self, wallet: &'a impl BaseWallet, ledger: &'a impl AnoncredsLedgerRead, anoncreds: &'a impl BaseAnonCreds, credential: IssueCredentialV1, ) -> VcxResult<Self> { trace!("HolderSM::receive_credential >>"); let state = match self.state { HolderFullState::RequestSet(state_data) => { let schema = ledger.get_schema(&state_data.schema_id, None).await?; let schema_json = serde_json::to_string(&schema)?; match _store_credential( wallet, ledger, anoncreds, &credential, &state_data.req_meta, &state_data.cred_def_json, &schema_json, ) .await { Ok((cred_id, rev_reg_def_json)) => HolderFullState::Finished( (state_data, cred_id, credential, rev_reg_def_json).into(), ), Err(err) => { let problem_report = build_problem_report_msg(Some(err.to_string()), &self.thread_id); error!("Failed to process or save received credential: {problem_report:?}"); HolderFullState::Finished(FinishedHolderState::new(problem_report)) } } } s => { warn!("Unable to receive credential offer in state {s}"); s } }; Ok(Self { state, ..self }) } pub fn receive_problem_report(self, problem_report: ProblemReport) -> VcxResult<Self> { warn!("HolderSM::receive_problem_report >> problem_report: {problem_report:?}"); let state = match self.state { HolderFullState::ProposalSet(_) | HolderFullState::RequestSet(_) => { HolderFullState::Finished(FinishedHolderState::new(problem_report)) } s => { warn!("Unable to receive problem report in state {s}"); s } }; Ok(Self { state, ..self }) } pub fn credential_status(&self) -> u32 { match self.state { HolderFullState::Finished(ref state) => state.status.code(), _ => Status::Undefined.code(), } } pub fn is_terminal_state(&self) -> bool { matches!(self.state, HolderFullState::Finished(_)) } pub fn get_credential(&self) -> VcxResult<(String, AriesMessage)> { match self.state { HolderFullState::Finished(ref state) => { let cred_id = state.cred_id.clone().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Cannot get credential: Credential Id not found", ))?; let credential = state.credential.clone().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Cannot get credential: Credential not found", ))?; Ok((cred_id, credential.into())) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot get credential: Credential Issuance is not finished yet", )), } } pub fn get_attributes(&self) -> VcxResult<String> { match self.state { HolderFullState::Finished(ref state) => state.get_attributes(), HolderFullState::OfferReceived(ref state) => state.get_attributes(), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot get credential attributes: credential offer or credential must be \ receieved first", )), } } pub fn get_attachment(&self) -> VcxResult<String> { match self.state { HolderFullState::Finished(ref state) => state.get_attachment(), HolderFullState::OfferReceived(ref state) => state.get_attachment(), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot get credential attachment: credential offer or credential must be \ receieved first", )), } } pub fn get_tails_location(&self) -> VcxResult<String> { match self.state { HolderFullState::Finished(ref state) => state.get_tails_location(), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot get tails location: credential exchange not finished yet", )), } } pub fn get_tails_hash(&self) -> VcxResult<String> { match self.state { HolderFullState::Finished(ref state) => state.get_tails_hash(), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot get tails hash: credential exchange not finished yet", )), } } pub fn get_rev_reg_id(&self) -> VcxResult<String> { match self.state { HolderFullState::Finished(ref state) => state.get_rev_reg_id(), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot get rev reg id: credential exchange not finished yet", )), } } pub fn get_cred_id(&self) -> VcxResult<String> { match self.state { HolderFullState::Finished(ref state) => state.get_cred_id(), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot get credential id: credential exchange not finished yet", )), } } pub fn get_offer(&self) -> VcxResult<OfferCredentialV1> { match self.state { HolderFullState::OfferReceived(ref state) => Ok(state.offer.clone()), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Credential offer can only be obtained from OfferReceived state", )), } } pub fn get_thread_id(&self) -> VcxResult<String> { Ok(self.thread_id.clone()) } pub async fn is_revokable(&self, ledger: &impl AnoncredsLedgerRead) -> VcxResult<bool> { match self.state { HolderFullState::Initial(ref state) => state.is_revokable(), HolderFullState::ProposalSet(ref state) => state.is_revokable(ledger).await, HolderFullState::OfferReceived(ref state) => state.is_revokable(ledger).await, HolderFullState::RequestSet(ref state) => state.is_revokable(), HolderFullState::Finished(ref state) => state.is_revokable(), } } pub async fn is_revoked( &self, wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, ) -> VcxResult<bool> { if self.is_revokable(ledger).await? { let rev_reg_id = self.get_rev_reg_id()?; let cred_id = self.get_cred_id()?; let rev_id = get_cred_rev_id(wallet, anoncreds, &cred_id).await?; is_cred_revoked(ledger, &rev_reg_id, rev_id).await } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Unable to check revocation status - this credential is not revokable", )) } } pub async fn delete_credential( &self, wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ) -> VcxResult<()> { trace!("Holder::delete_credential"); match self.state { HolderFullState::Finished(ref state) => { let cred_id = state.cred_id.clone().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Cannot get credential: credential id not found", ))?; anoncreds .prover_delete_credential(wallet, &cred_id) .await .map_err(|err| err.into()) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot delete credential: credential issuance is not finished yet", )), } } pub fn get_problem_report(&self) -> VcxResult<ProblemReport> { match self.state { HolderFullState::Finished(ref state) => match &state.status { Status::Failed(problem_report) => Ok(problem_report.clone()), Status::Declined(problem_report) => Ok(problem_report.clone()), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "No problem report available in current state", )), }, _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "No problem report available in current state", )), } } } pub fn parse_cred_def_id_from_cred_offer(cred_offer: &str) -> VcxResult<String> { trace!("Holder::parse_cred_def_id_from_cred_offer >>> cred_offer: {cred_offer:?}"); let parsed_offer: serde_json::Value = serde_json::from_str(cred_offer).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Invalid Credential Offer Json: {err:?}"), ) })?; let cred_def_id = parsed_offer["cred_def_id"].as_str().ok_or_else(|| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, "Invalid Credential Offer Json: cred_def_id not found", ) })?; Ok(cred_def_id.to_string()) } fn _parse_rev_reg_id_from_credential(credential: &str) -> VcxResult<Option<String>> { trace!("Holder::_parse_rev_reg_id_from_credential >>>"); let parsed_credential: serde_json::Value = serde_json::from_str(credential).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Invalid Credential Json: {credential}, err: {err:?}"), ) })?; let rev_reg_id = parsed_credential["rev_reg_id"].as_str().map(String::from); trace!("Holder::_parse_rev_reg_id_from_credential <<< {rev_reg_id:?}"); Ok(rev_reg_id) } async fn _store_credential( wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, credential: &IssueCredentialV1, req_meta: &str, cred_def_json: &str, schema_json: &str, ) -> VcxResult<(String, Option<String>)> { trace!( "Holder::_store_credential >>> credential: {credential:?}, req_meta: {req_meta}, cred_def_json: {cred_def_json}" ); let credential_json = get_attach_as_string!(&credential.content.credentials_attach); let rev_reg_id = _parse_rev_reg_id_from_credential(&credential_json)?; let rev_reg_def_json = if let Some(rev_reg_id) = rev_reg_id { let (json, _meta) = ledger.get_rev_reg_def_json(&rev_reg_id.try_into()?).await?; Some(json) } else { None }; let cred_id = anoncreds .prover_store_credential( wallet, serde_json::from_str(req_meta)?, serde_json::from_str(&credential_json)?, serde_json::from_str(schema_json)?, serde_json::from_str(cred_def_json)?, rev_reg_def_json.clone(), ) .await?; Ok(( cred_id, rev_reg_def_json .as_ref() .map(serde_json::to_string) .transpose()?, )) } /// On success, returns: credential request, request metadata, cred_def_id, cred def, schema_id pub async fn create_anoncreds_credential_request( wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, prover_did: &Did, cred_offer: &str, ) -> VcxResult<(String, String, String, String, SchemaId)> { let offer: CredentialOffer = serde_json::from_str(cred_offer)?; let schema_id = offer.schema_id.clone(); let cred_def_id = offer.cred_def_id.clone(); let cred_def_json = ledger.get_cred_def(&cred_def_id, None).await?; let master_secret_id = settings::DEFAULT_LINK_SECRET_ALIAS; anoncreds .prover_create_credential_req( wallet, prover_did, offer, cred_def_json.try_clone()?, &master_secret_id.to_string(), ) .await .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!("Cannot create credential request; {err}"), ) }) .map(|(s1, s2)| { ( serde_json::to_string(&s1).unwrap(), serde_json::to_string(&s2).unwrap(), cred_def_id.to_string(), serde_json::to_string(&cred_def_json).unwrap(), schema_id, ) }) } /// On success, returns: message with cred request, request metadata, cred def (for caching), /// schema_id async fn build_credential_request_msg( wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, thread_id: String, my_pw_did: Did, offer: &OfferCredentialV1, ) -> VcxResult<(RequestCredentialV1, String, String, SchemaId)> { trace!("Holder::_make_credential_request >>> my_pw_did: {my_pw_did:?}, offer: {offer:?}"); let cred_offer = get_attach_as_string!(&offer.content.offers_attach); trace!("Parsed cred offer attachment: {cred_offer}"); let (req, req_meta, _cred_def_id, cred_def_json, schema_id) = create_anoncreds_credential_request(wallet, ledger, anoncreds, &my_pw_did, &cred_offer) .await?; trace!("Created cred def json: {cred_def_json}"); let credential_request_msg = _build_credential_request_msg(req, &thread_id); Ok((credential_request_msg, req_meta, cred_def_json, schema_id)) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/holder/states/proposal_set.rs
aries/aries_vcx/src/protocols/issuance/holder/states/proposal_set.rs
use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use messages::msg_fields::protocols::cred_issuance::v1::propose_credential::ProposeCredentialV1; use crate::{errors::error::prelude::*, protocols::issuance::is_cred_def_revokable}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ProposalSetState { pub credential_proposal: ProposeCredentialV1, } impl ProposalSetState { pub fn new(credential_proposal: ProposeCredentialV1) -> Self { Self { credential_proposal, } } pub async fn is_revokable(&self, ledger: &impl AnoncredsLedgerRead) -> VcxResult<bool> { is_cred_def_revokable(ledger, &self.credential_proposal.content.cred_def_id).await } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/holder/states/request_set.rs
aries/aries_vcx/src/protocols/issuance/holder/states/request_set.rs
use anoncreds_types::data_types::identifiers::schema_id::SchemaId; use messages::msg_fields::protocols::cred_issuance::v1::{ issue_credential::IssueCredentialV1, request_credential::RequestCredentialV1, }; use crate::{ errors::error::prelude::*, handlers::util::Status, protocols::issuance::holder::states::finished::FinishedHolderState, }; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct RequestSetState { pub req_meta: String, pub cred_def_json: String, pub schema_id: SchemaId, pub msg_credential_request: RequestCredentialV1, } impl From<(RequestSetState, String, IssueCredentialV1, Option<String>)> for FinishedHolderState { fn from( (_, cred_id, credential, rev_reg_def_json): ( RequestSetState, String, IssueCredentialV1, Option<String>, ), ) -> Self { let ack_requested = credential.decorators.please_ack.is_some(); FinishedHolderState { cred_id: Some(cred_id), credential: Some(credential), status: Status::Success, rev_reg_def_json, ack_requested: Some(ack_requested), } } } impl RequestSetState { pub fn is_revokable(&self) -> VcxResult<bool> { let parsed_cred_def: serde_json::Value = serde_json::from_str(&self.cred_def_json) .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!( "Failed deserialize credential definition json {}\nError: {}", self.cred_def_json, err ), ) })?; Ok(!parsed_cred_def["value"]["revocation"].is_null()) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/holder/states/finished.rs
aries/aries_vcx/src/protocols/issuance/holder/states/finished.rs
use messages::msg_fields::protocols::{ cred_issuance::v1::issue_credential::IssueCredentialV1, report_problem::ProblemReport, }; use crate::{ errors::error::prelude::*, handlers::util::{get_attach_as_string, CredentialData, Status}, }; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct FinishedHolderState { pub cred_id: Option<String>, pub credential: Option<IssueCredentialV1>, pub status: Status, pub rev_reg_def_json: Option<String>, pub ack_requested: Option<bool>, } impl FinishedHolderState { pub fn get_attributes(&self) -> VcxResult<String> { let attach = self.get_attachment()?; let cred_data: CredentialData = serde_json::from_str(&attach).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot deserialize {attach:?}, into CredentialData, err: {err:?}"), ) })?; let mut new_map = serde_json::map::Map::new(); match cred_data.values.as_object() { Some(values) => { for (key, value) in values { let val = value["raw"] .as_str() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, "Missing raw encoding on credential value", ))? .into(); new_map.insert(key.clone(), val); } Ok(serde_json::Value::Object(new_map).to_string()) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot convert {attach:?} into object"), )), } } pub fn get_attachment(&self) -> VcxResult<String> { let credential = self.credential.as_ref().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "No credential found", ))?; Ok(get_attach_as_string!( &credential.content.credentials_attach )) } // TODO: Avoid duplication pub fn get_tails_location(&self) -> VcxResult<String> { debug!("get_tails_location >>>"); let rev_reg_def_json = self .rev_reg_def_json .as_ref() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "No revocation registry definition found - is this credential revokable?", ))?; let rev_reg_def: serde_json::Value = serde_json::from_str(rev_reg_def_json).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Cannot deserialize {rev_reg_def_json:?} into Value, err: {err:?}"), ) })?; let value = rev_reg_def["value"] .as_object() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("The field 'value' not found on rev_reg_def_json: {rev_reg_def_json:?}"), ))?; let tails_location = value["tailsLocation"] .as_str() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!( "The field 'tailsLocation' not found on rev_reg_def_json: {:?}", self.rev_reg_def_json ), ))?; trace!("get_tails_location <<< tails_location: {tails_location}"); Ok(tails_location.to_string()) } pub fn get_tails_hash(&self) -> VcxResult<String> { let rev_reg_def_json = self .rev_reg_def_json .as_ref() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "No revocation registry definition found - is this credential revokable?", ))?; let rev_reg_def: serde_json::Value = serde_json::from_str(rev_reg_def_json).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Cannot deserialize {rev_reg_def_json:?} into Value, err: {err:?}"), ) })?; let value = rev_reg_def["value"] .as_object() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("The field 'value' not found on rev_reg_def_json: {rev_reg_def_json:?}"), ))?; let tails_hash = value["tailsHash"].as_str().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!( "The field 'tailsLocation' not found on rev_reg_def_json: {:?}", self.rev_reg_def_json ), ))?; Ok(tails_hash.to_string()) } pub fn get_rev_reg_id(&self) -> VcxResult<String> { let rev_reg_def_json = self .rev_reg_def_json .as_ref() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "No revocation registry definition found - is this credential revokable?", ))?; let rev_reg_def: serde_json::Value = serde_json::from_str(rev_reg_def_json).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Cannot deserialize {rev_reg_def_json:?} into Value, err: {err:?}"), ) })?; let rev_reg_def_id = rev_reg_def["id"].as_str().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("The field 'id' not found on rev_reg_def_json: {rev_reg_def_json:?}"), ))?; Ok(rev_reg_def_id.to_string()) } pub fn get_cred_id(&self) -> VcxResult<String> { self.cred_id.clone().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, "The field 'cred_id' not found on FinishedHolderState".to_string(), )) } pub fn is_revokable(&self) -> VcxResult<bool> { Ok(self.rev_reg_def_json.is_some()) } } impl FinishedHolderState { pub fn new(problem_report: ProblemReport) -> Self { trace!("SM is now in Finished state"); FinishedHolderState { ack_requested: None, cred_id: None, credential: None, status: Status::Failed(problem_report), rev_reg_def_json: None, } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/holder/states/mod.rs
aries/aries_vcx/src/protocols/issuance/holder/states/mod.rs
pub(super) mod finished; pub(super) mod initial; pub(super) mod offer_received; pub(super) mod proposal_set; pub(super) mod request_set;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/holder/states/initial.rs
aries/aries_vcx/src/protocols/issuance/holder/states/initial.rs
use crate::errors::error::prelude::*; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct InitialHolderState; impl InitialHolderState { pub fn is_revokable(&self) -> VcxResult<bool> { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Revocation information not available in the initial state", )) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/issuance/holder/states/offer_received.rs
aries/aries_vcx/src/protocols/issuance/holder/states/offer_received.rs
use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use messages::msg_fields::protocols::cred_issuance::v1::offer_credential::OfferCredentialV1; use crate::{ errors::error::prelude::*, handlers::util::get_attach_as_string, protocols::issuance::{ holder::state_machine::parse_cred_def_id_from_cred_offer, is_cred_def_revokable, }, }; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct OfferReceivedState { pub offer: OfferCredentialV1, } impl OfferReceivedState { pub fn new(offer: OfferCredentialV1) -> Self { OfferReceivedState { offer } } pub fn get_attributes(&self) -> VcxResult<String> { let mut new_map = serde_json::map::Map::new(); self.offer .content .credential_preview .attributes .iter() .for_each(|attribute| { new_map.insert( attribute.name.clone(), serde_json::Value::String(attribute.value.clone()), ); }); Ok(serde_json::Value::Object(new_map).to_string()) } pub async fn is_revokable(&self, ledger: &impl AnoncredsLedgerRead) -> VcxResult<bool> { let offer = self.get_attachment()?; let cred_def_id = parse_cred_def_id_from_cred_offer(&offer).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Failed to parse credential definition id from credential offer: {err}"), ) })?; is_cred_def_revokable(ledger, &cred_def_id).await } pub fn get_attachment(&self) -> VcxResult<String> { Ok(get_attach_as_string!(self.offer.content.offers_attach)) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/util.rs
aries/aries_vcx/src/handlers/util.rs
use anoncreds_types::data_types::identifiers::cred_def_id::CredentialDefinitionId; use messages::{ msg_fields::protocols::{ connection::{invitation::Invitation, Connection}, coordinate_mediation::CoordinateMediation, cred_issuance::{v1::CredentialIssuanceV1, v2::CredentialIssuanceV2, CredentialIssuance}, did_exchange::{v1_0::DidExchangeV1_0, v1_1::DidExchangeV1_1, DidExchange}, discover_features::DiscoverFeatures, notification::Notification, out_of_band::{invitation::Invitation as OobInvitation, OutOfBand}, pickup::Pickup, present_proof::{ v1::{ propose::{Predicate, PresentationAttr}, PresentProofV1, }, v2::PresentProofV2, PresentProof, }, report_problem::ProblemReport, revocation::Revocation, trust_ping::TrustPing, }, AriesMessage, }; use strum_macros::{AsRefStr, EnumString}; use crate::errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}; #[macro_export] macro_rules! matches_thread_id { ($msg:expr, $id:expr) => { $msg.decorators.thread.thid == $id || $msg.decorators.thread.pthid.as_deref() == Some($id) }; } #[macro_export] macro_rules! matches_opt_thread_id { ($msg:expr, $id:expr) => { match $msg.decorators.thread.as_ref() { Some(t) => t.thid == $id || t.pthid.as_deref() == Some($id), None => true, } }; } #[rustfmt::skip] // This macro results in some false positives and formatting makes it harder to read macro_rules! get_attach_as_string { ($attachments:expr) => {{ let __attach = $attachments.first().as_ref().map(|a| &a.data.content); let err_fn = |attach: Option<&messages::decorators::attachment::Attachment>| { Err(AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Attachment is not base 64 encoded JSON: {:?}", attach), )) }; let Some(messages::decorators::attachment::AttachmentType::Base64(encoded_attach)) = __attach else { return err_fn($attachments.first()); }; let Ok(bytes) = base64::engine::Engine::decode(&base64::engine::general_purpose::STANDARD, &encoded_attach) else { return err_fn($attachments.first()); }; let Ok(attach_string) = String::from_utf8(bytes) else { return err_fn($attachments.first()); }; attach_string }}; } macro_rules! make_attach_from_str { ($str_attach:expr, $id:expr) => {{ let attach_type = messages::decorators::attachment::AttachmentType::Base64( base64::engine::Engine::encode(&base64::engine::general_purpose::STANDARD, $str_attach), ); let attach_data = messages::decorators::attachment::AttachmentData::builder() .content(attach_type) .build(); let mut attach = messages::decorators::attachment::Attachment::builder() .data(attach_data) .build(); attach.id = Some($id); attach.mime_type = Some(shared::maybe_known::MaybeKnown::Known( messages::misc::MimeType::Json, )); attach }}; } pub(crate) use get_attach_as_string; pub(crate) use make_attach_from_str; pub use matches_opt_thread_id; pub use matches_thread_id; pub fn verify_thread_id(thread_id: &str, message: &AriesMessage) -> VcxResult<()> { let is_match = match message { AriesMessage::BasicMessage(msg) => matches_opt_thread_id!(msg, thread_id), AriesMessage::Connection(Connection::Invitation(msg)) => msg.id == thread_id, AriesMessage::Connection(Connection::ProblemReport(msg)) => { matches_thread_id!(msg, thread_id) } AriesMessage::Connection(Connection::Request(msg)) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::Connection(Connection::Response(msg)) => matches_thread_id!(msg, thread_id), AriesMessage::CredentialIssuance(CredentialIssuance::V1(CredentialIssuanceV1::Ack( msg, ))) => { matches_thread_id!(msg, thread_id) } AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::IssueCredential(msg), )) => { matches_thread_id!(msg, thread_id) } AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::OfferCredential(msg), )) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::ProposeCredential(msg), )) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::RequestCredential(msg), )) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::ProblemReport(msg), )) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::CredentialIssuance(CredentialIssuance::V2(CredentialIssuanceV2::Ack( msg, ))) => { matches_thread_id!(msg, thread_id) } AriesMessage::CredentialIssuance(CredentialIssuance::V2( CredentialIssuanceV2::IssueCredential(msg), )) => { matches_thread_id!(msg, thread_id) } AriesMessage::CredentialIssuance(CredentialIssuance::V2( CredentialIssuanceV2::OfferCredential(msg), )) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::CredentialIssuance(CredentialIssuance::V2( CredentialIssuanceV2::ProposeCredential(msg), )) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::CredentialIssuance(CredentialIssuance::V2( CredentialIssuanceV2::RequestCredential(msg), )) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::CredentialIssuance(CredentialIssuance::V2( CredentialIssuanceV2::ProblemReport(msg), )) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::DiscoverFeatures(DiscoverFeatures::Query(msg)) => msg.id == thread_id, AriesMessage::DiscoverFeatures(DiscoverFeatures::Disclose(msg)) => { matches_thread_id!(msg, thread_id) } AriesMessage::Notification(Notification::Ack(msg)) => matches_thread_id!(msg, thread_id), AriesMessage::Notification(Notification::ProblemReport(msg)) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::OutOfBand(OutOfBand::Invitation(msg)) => msg.id == thread_id, AriesMessage::OutOfBand(OutOfBand::HandshakeReuse(msg)) => { matches_thread_id!(msg, thread_id) } AriesMessage::OutOfBand(OutOfBand::HandshakeReuseAccepted(msg)) => { matches_thread_id!(msg, thread_id) } AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Ack(msg))) => { matches_thread_id!(msg, thread_id) } AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Presentation(msg))) => { matches_thread_id!(msg, thread_id) } AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::ProposePresentation(msg))) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::RequestPresentation(msg))) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::ProblemReport(msg))) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::PresentProof(PresentProof::V2(PresentProofV2::Ack(msg))) => { matches_thread_id!(msg, thread_id) } AriesMessage::PresentProof(PresentProof::V2(PresentProofV2::Presentation(msg))) => { matches_thread_id!(msg, thread_id) } AriesMessage::PresentProof(PresentProof::V2(PresentProofV2::ProposePresentation(msg))) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::PresentProof(PresentProof::V2(PresentProofV2::RequestPresentation(msg))) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::PresentProof(PresentProof::V2(PresentProofV2::ProblemReport(msg))) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::ReportProblem(msg) => matches_opt_thread_id!(msg, thread_id), AriesMessage::Revocation(Revocation::Revoke(msg)) => matches_opt_thread_id!(msg, thread_id), AriesMessage::Revocation(Revocation::Ack(msg)) => matches_thread_id!(msg, thread_id), AriesMessage::Routing(msg) => msg.id == thread_id, AriesMessage::TrustPing(TrustPing::Ping(msg)) => matches_opt_thread_id!(msg, thread_id), AriesMessage::TrustPing(TrustPing::PingResponse(msg)) => matches_thread_id!(msg, thread_id), AriesMessage::Pickup(Pickup::Status(msg)) => matches_opt_thread_id!(msg, thread_id), AriesMessage::Pickup(Pickup::StatusRequest(msg)) => matches_opt_thread_id!(msg, thread_id), AriesMessage::Pickup(Pickup::Delivery(msg)) => matches_opt_thread_id!(msg, thread_id), AriesMessage::Pickup(Pickup::DeliveryRequest(msg)) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::Pickup(Pickup::MessagesReceived(msg)) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::Pickup(Pickup::LiveDeliveryChange(msg)) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::CoordinateMediation(CoordinateMediation::MediateRequest(msg)) => { msg.id == thread_id } AriesMessage::CoordinateMediation(CoordinateMediation::MediateDeny(msg)) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::CoordinateMediation(CoordinateMediation::MediateGrant(msg)) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::CoordinateMediation(CoordinateMediation::KeylistUpdate(msg)) => { msg.id == thread_id } AriesMessage::CoordinateMediation(CoordinateMediation::KeylistUpdateResponse(msg)) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::CoordinateMediation(CoordinateMediation::KeylistQuery(msg)) => { msg.id == thread_id } AriesMessage::CoordinateMediation(CoordinateMediation::Keylist(msg)) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::DidExchange(DidExchange::V1_0(DidExchangeV1_0::Request(msg))) | AriesMessage::DidExchange(DidExchange::V1_1(DidExchangeV1_1::Request(msg))) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::DidExchange(DidExchange::V1_0(DidExchangeV1_0::Response(msg))) => { matches_thread_id!(msg, thread_id) } AriesMessage::DidExchange(DidExchange::V1_0(DidExchangeV1_0::Complete(msg))) | AriesMessage::DidExchange(DidExchange::V1_1(DidExchangeV1_1::Complete(msg))) => { matches_thread_id!(msg, thread_id) } AriesMessage::DidExchange(DidExchange::V1_0(DidExchangeV1_0::ProblemReport(msg))) | AriesMessage::DidExchange(DidExchange::V1_1(DidExchangeV1_1::ProblemReport(msg))) => { matches_thread_id!(msg, thread_id) } AriesMessage::DidExchange(DidExchange::V1_1(DidExchangeV1_1::Response(msg))) => { matches_thread_id!(msg, thread_id) } }; if !is_match { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!( "Cannot handle message {message:?}: thread id does not match, expected {thread_id:?}" ), )); }; Ok(()) } #[derive(Debug, Clone, AsRefStr, EnumString, PartialEq)] pub enum AttachmentId { #[strum(serialize = "libindy-cred-offer-0")] CredentialOffer, #[strum(serialize = "libindy-cred-request-0")] CredentialRequest, #[strum(serialize = "libindy-cred-0")] Credential, #[strum(serialize = "libindy-request-presentation-0")] PresentationRequest, #[strum(serialize = "libindy-presentation-0")] Presentation, } /// For retro-fitting the new messages. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(untagged)] pub enum AnyInvitation { Con(Invitation), Oob(OobInvitation), } impl AnyInvitation { pub fn id(&self) -> &str { match self { AnyInvitation::Con(invitation) => &invitation.id, AnyInvitation::Oob(invitation) => &invitation.id, } } } // TODO: post-rebase check if this is applicable version, else delete // impl AnyInvitation { // pub fn get_id(&self) -> &str { // match self { // AnyInvitation::Con(Invitation::Public(msg)) => &msg.id, // AnyInvitation::Con(Invitation::Pairwise(msg)) => &msg.id, // AnyInvitation::Con(Invitation::PairwiseDID(msg)) => &msg.id, // AnyInvitation::Oob(msg) => &msg.id, // } // } // } // todo: this is shared by multiple protocols to express different things - needs to be split #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum Status { Undefined, Success, Failed(ProblemReport), Declined(ProblemReport), } impl Status { pub fn code(&self) -> u32 { match self { Status::Undefined => 0, Status::Success => 1, Status::Failed(_) => 2, Status::Declined(_) => 3, } } } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Default)] pub struct CredentialData { pub schema_id: String, pub cred_def_id: String, #[serde(skip_serializing_if = "Option::is_none")] pub rev_reg_id: Option<String>, pub values: serde_json::Value, pub signature: serde_json::Value, pub signature_correctness_proof: serde_json::Value, #[serde(skip_serializing_if = "Option::is_none")] pub rev_reg: Option<serde_json::Value>, #[serde(skip_serializing_if = "Option::is_none")] pub witness: Option<serde_json::Value>, } #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct OfferInfo { pub credential_json: String, pub cred_def_id: CredentialDefinitionId, pub rev_reg_id: Option<String>, pub tails_file: Option<String>, } impl OfferInfo { pub fn new( credential_json: String, cred_def_id: CredentialDefinitionId, rev_reg_id: Option<String>, tails_file: Option<String>, ) -> Self { Self { credential_json, cred_def_id, rev_reg_id, tails_file, } } } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Default)] pub struct PresentationProposalData { pub attributes: Vec<PresentationAttr>, pub predicates: Vec<Predicate>, pub comment: Option<String>, }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/mod.rs
aries/aries_vcx/src/handlers/mod.rs
pub mod issuance; pub mod out_of_band; pub mod proof_presentation; pub mod revocation_notification; pub mod trust_ping; pub mod util;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/trust_ping/mod.rs
aries/aries_vcx/src/handlers/trust_ping/mod.rs
use messages::msg_fields::protocols::trust_ping::{ping::Ping, ping_response::PingResponse}; use super::util::matches_thread_id; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, protocols::{trustping::build_ping, SendClosure}, }; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct TrustPingSender { ping: Ping, ping_sent: bool, response_received: bool, } impl TrustPingSender { pub fn build(request_response: bool, comment: Option<String>) -> TrustPingSender { let ping = build_ping(request_response, comment); Self { ping, ping_sent: false, response_received: false, } } pub fn get_ping(&self) -> &Ping { &self.ping } pub fn get_thread_id(&self) -> &str { self.ping .decorators .thread .as_ref() .map(|t| t.thid.as_str()) .unwrap_or(self.ping.id.as_str()) } pub async fn send_ping(&mut self, send_message: SendClosure<'_>) -> VcxResult<()> { if self.ping_sent { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Ping message has already been sent", )); } send_message(self.ping.clone().into()).await?; self.ping_sent = true; Ok(()) } pub fn handle_ping_response(&mut self, ping: &PingResponse) -> VcxResult<()> { if !matches_thread_id!(ping, self.get_thread_id()) { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Thread ID mismatch", )); } if !self.ping.content.response_requested { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Message was not expected", )); } else { self.response_received = true } Ok(()) } } #[cfg(test)] mod unit_tests { use messages::AriesMessage; use test_utils::devsetup::SetupMocks; use crate::{ errors::error::VcxResult, handlers::trust_ping::TrustPingSender, protocols::{trustping::build_ping_response, SendClosure}, }; pub fn _send_message() -> SendClosure<'static> { Box::new(|_: AriesMessage| Box::pin(async { VcxResult::Ok(()) })) } #[tokio::test] async fn test_build_send_ping_process_response() { let _setup = SetupMocks::init(); let mut sender = TrustPingSender::build(true, None); sender.send_ping(_send_message()).await.unwrap(); let ping_response = build_ping_response(&sender.ping); sender.handle_ping_response(&ping_response).unwrap(); } #[tokio::test] async fn test_should_fail_on_thread_id_mismatch() { let _setup = SetupMocks::init(); let mut sender1 = TrustPingSender::build(true, None); let sender2 = TrustPingSender::build(true, None); sender1.send_ping(_send_message()).await.unwrap(); let ping_response = build_ping_response(&sender2.ping); sender1.handle_ping_response(&ping_response).unwrap_err(); } #[tokio::test] async fn test_should_fail_if_response_was_not_expected() { let _setup = SetupMocks::init(); let mut sender1 = TrustPingSender::build(false, None); sender1.send_ping(_send_message()).await.unwrap(); let ping_response = build_ping_response(&sender1.ping); sender1.handle_ping_response(&ping_response).unwrap_err(); } #[test] fn test_should_build_ping_with_comment() { let _setup = SetupMocks::init(); let sender1 = TrustPingSender::build(false, Some("hello".to_string())); assert_eq!( sender1.get_ping().content.comment, Some("hello".to_string()) ) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/revocation_notification/sender.rs
aries/aries_vcx/src/handlers/revocation_notification/sender.rs
use messages::msg_fields::protocols::revocation::ack::AckRevoke; use crate::{ errors::error::prelude::*, protocols::{ revocation_notification::sender::state_machine::{ RevocationNotificationSenderSM, SenderConfig, }, SendClosure, }, }; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct RevocationNotificationSender { sender_sm: RevocationNotificationSenderSM, } impl RevocationNotificationSender { pub fn build() -> Self { Self { sender_sm: RevocationNotificationSenderSM::create(), } } pub async fn send_revocation_notification( self, config: SenderConfig, send_message: SendClosure<'_>, ) -> VcxResult<Self> { let sender_sm = self.sender_sm.send(config, send_message).await?; Ok(Self { sender_sm }) } pub async fn handle_revocation_notification_ack(self, ack: AckRevoke) -> VcxResult<Self> { let sender_sm = self.sender_sm.handle_ack(ack)?; Ok(Self { sender_sm }) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/revocation_notification/mod.rs
aries/aries_vcx/src/handlers/revocation_notification/mod.rs
use messages::decorators::please_ack::AckOn; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, handlers::{ issuance::issuer::Issuer, revocation_notification::sender::RevocationNotificationSender, }, protocols::{revocation_notification::sender::state_machine::SenderConfigBuilder, SendClosure}, }; pub mod receiver; pub mod sender; pub async fn send_revocation_notification( issuer: &Issuer, ack_on: Vec<AckOn>, comment: Option<String>, send_message: SendClosure<'_>, ) -> VcxResult<()> { // TODO: Check if actually revoked if issuer.is_revokable() { // TODO: Store to allow checking not. status (sent, acked) let config = SenderConfigBuilder::default() .rev_reg_id(issuer.get_rev_reg_id()?) .cred_rev_id(issuer.get_rev_id()?) .comment(comment) .ack_on(ack_on) .build()?; RevocationNotificationSender::build() .send_revocation_notification(config, send_message) .await?; Ok(()) } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!( "Can't send revocation notification in state {:?}, credential is not revokable", issuer.get_state() ), )) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/revocation_notification/receiver.rs
aries/aries_vcx/src/handlers/revocation_notification/receiver.rs
use messages::msg_fields::protocols::revocation::revoke::Revoke; use crate::{ errors::error::prelude::*, protocols::{ revocation_notification::receiver::state_machine::RevocationNotificationReceiverSM, SendClosure, }, }; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct RevocationNotificationReceiver { receiver_sm: RevocationNotificationReceiverSM, } impl RevocationNotificationReceiver { pub fn build(rev_reg_id: String, cred_rev_id: u32) -> Self { Self { receiver_sm: RevocationNotificationReceiverSM::create(rev_reg_id, cred_rev_id), } } pub fn get_thread_id(&self) -> VcxResult<String> { self.receiver_sm.get_thread_id() } pub async fn handle_revocation_notification(self, notification: Revoke) -> VcxResult<Self> { let receiver_sm = self .receiver_sm .handle_revocation_notification(notification) .await?; Ok(Self { receiver_sm }) } pub async fn send_ack(self, send_message: SendClosure<'_>) -> VcxResult<Self> { let receiver_sm = self.receiver_sm.send_ack(send_message).await?; Ok(Self { receiver_sm }) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/proof_presentation/prover.rs
aries/aries_vcx/src/handlers/proof_presentation/prover.rs
use std::collections::HashMap; use anoncreds_types::data_types::messages::cred_selection::{ RetrievedCredentials, SelectedCredentials, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use chrono::Utc; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::{ notification::Notification, present_proof::{ v1::{ ack::AckPresentationV1, present::PresentationV1, propose::{ PresentationPreview, ProposePresentationV1, ProposePresentationV1Content, ProposePresentationV1Decorators, }, request::RequestPresentationV1, PresentProofV1, }, PresentProof, }, }, AriesMessage, }; use uuid::Uuid; use crate::{ errors::error::prelude::*, handlers::util::{get_attach_as_string, PresentationProposalData}, protocols::{ common::build_problem_report_msg, proof_presentation::prover::state_machine::{ProverSM, ProverState}, }, }; #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct Prover { prover_sm: ProverSM, } impl Prover { pub fn create(source_id: &str) -> VcxResult<Prover> { trace!("Prover::create >>> source_id: {source_id}"); Ok(Prover { prover_sm: ProverSM::new(source_id.to_string()), }) } pub fn create_from_request( source_id: &str, presentation_request: RequestPresentationV1, ) -> VcxResult<Prover> { trace!( "Prover::create_from_request >>> source_id: {source_id}, presentation_request: {presentation_request:?}" ); Ok(Prover { prover_sm: ProverSM::from_request(presentation_request, source_id.to_string()), }) } pub fn get_state(&self) -> ProverState { self.prover_sm.get_state() } pub fn presentation_status(&self) -> u32 { self.prover_sm.get_presentation_status() } pub async fn retrieve_credentials( &self, wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ) -> VcxResult<RetrievedCredentials> { trace!("Prover::retrieve_credentials >>>"); let presentation_request = self.presentation_request_data()?; let json_retrieved_credentials = anoncreds .prover_get_credentials_for_proof_req( wallet, serde_json::from_str(&presentation_request)?, ) .await?; trace!( "Prover::retrieve_credentials >>> presentation_request: {presentation_request}, \ json_retrieved_credentials: {json_retrieved_credentials:?}" ); Ok(json_retrieved_credentials) } pub async fn generate_presentation( &mut self, wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, credentials: SelectedCredentials, self_attested_attrs: HashMap<String, String>, ) -> VcxResult<()> { trace!( "Prover::generate_presentation >>> credentials: {credentials:?}, self_attested_attrs: {self_attested_attrs:?}" ); self.prover_sm = self .prover_sm .clone() .generate_presentation(wallet, ledger, anoncreds, credentials, self_attested_attrs) .await?; Ok(()) } pub fn get_presentation_msg(&self) -> VcxResult<PresentationV1> { Ok(self.prover_sm.get_presentation_msg()?.to_owned()) } pub async fn build_presentation_proposal( &mut self, proposal_data: PresentationProposalData, ) -> VcxResult<ProposePresentationV1> { trace!("Prover::build_presentation_proposal >>>"); self.prover_sm = self .prover_sm .clone() .build_presentation_proposal(proposal_data) .await?; self.prover_sm.get_presentation_proposal() } pub fn mark_presentation_sent(&mut self) -> VcxResult<AriesMessage> { trace!("Prover::mark_presentation_sent >>>"); self.prover_sm = self.prover_sm.clone().mark_presentation_sent()?; match self.prover_sm.get_state() { ProverState::PresentationSent => self .prover_sm .get_presentation_msg() .map(|p| p.clone().into()), ProverState::Finished => self.prover_sm.get_problem_report().map(Into::into), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot send presentation", )), } } pub fn process_presentation_ack(&mut self, ack: AckPresentationV1) -> VcxResult<()> { trace!("Prover::process_presentation_ack >>>"); self.prover_sm = self.prover_sm.clone().receive_presentation_ack(ack)?; Ok(()) } pub fn progressable_by_message(&self) -> bool { self.prover_sm.progressable_by_message() } pub fn presentation_request_data(&self) -> VcxResult<String> { Ok(get_attach_as_string!( &self .prover_sm .get_presentation_request()? .content .request_presentations_attach )) } pub fn get_proof_request_attachment(&self) -> VcxResult<String> { let data = get_attach_as_string!( &self .prover_sm .get_presentation_request()? .content .request_presentations_attach ); let proof_request_data: serde_json::Value = serde_json::from_str(&data).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot deserialize {data:?} into PresentationRequestData: {err:?}"), ) })?; Ok(proof_request_data.to_string()) } pub fn get_source_id(&self) -> String { self.prover_sm.source_id() } pub fn get_thread_id(&self) -> VcxResult<String> { self.prover_sm.get_thread_id() } pub async fn process_aries_msg(&mut self, message: AriesMessage) -> VcxResult<()> { let prover_sm = match message { AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::RequestPresentation( request, ))) => self .prover_sm .clone() .receive_presentation_request(request)?, AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Ack(ack))) => { self.prover_sm.clone().receive_presentation_ack(ack)? } AriesMessage::ReportProblem(report) => { self.prover_sm.clone().receive_presentation_reject(report)? } AriesMessage::Notification(Notification::ProblemReport(report)) => self .prover_sm .clone() .receive_presentation_reject(report.into())?, AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::ProblemReport(report))) => { self.prover_sm .clone() .receive_presentation_reject(report.into())? } _ => self.prover_sm.clone(), }; self.prover_sm = prover_sm; Ok(()) } // TODO: Can we delete this (please)? pub async fn decline_presentation_request( &mut self, reason: Option<String>, proposal: Option<String>, ) -> VcxResult<AriesMessage> { trace!( "Prover::decline_presentation_request >>> reason: {reason:?}, proposal: {proposal:?}" ); let (sm, message) = match (reason, proposal) { (Some(reason), None) => { let thread_id = self.prover_sm.get_thread_id()?; let problem_report = build_problem_report_msg(Some(reason), &thread_id); ( self.prover_sm .clone() .decline_presentation_request(problem_report.clone()) .await?, problem_report.into(), ) } (None, Some(proposal)) => { let presentation_preview: PresentationPreview = serde_json::from_str(&proposal) .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot serialize Presentation Preview: {err:?}"), ) })?; let thread_id = self.prover_sm.get_thread_id()?; let id = Uuid::new_v4().to_string(); let content = ProposePresentationV1Content::builder() .presentation_proposal(presentation_preview) .build(); let decorators = ProposePresentationV1Decorators::builder() .thread(Thread::builder().thid(thread_id.to_owned()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); let proposal = ProposePresentationV1::builder() .id(id) .content(content) .decorators(decorators) .build(); ( self.prover_sm.clone().negotiate_presentation().await?, proposal, ) } (None, None) => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidOption, "Either `reason` or `proposal` parameter must be specified.", )); } (Some(_), Some(_)) => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidOption, "Only one of `reason` or `proposal` parameters must be specified.", )); } }; self.prover_sm = sm; Ok(message) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/proof_presentation/mod.rs
aries/aries_vcx/src/handlers/proof_presentation/mod.rs
pub mod prover; pub mod verifier;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/proof_presentation/verifier.rs
aries/aries_vcx/src/handlers/proof_presentation/verifier.rs
use anoncreds_types::data_types::messages::pres_request::PresentationRequest; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use messages::{ msg_fields::protocols::{ notification::Notification, present_proof::{ v1::{ present::PresentationV1, propose::ProposePresentationV1, request::RequestPresentationV1, PresentProofV1, }, PresentProof, }, report_problem::ProblemReport, }, AriesMessage, }; use crate::{ errors::error::prelude::*, handlers::util::get_attach_as_string, protocols::{ common::build_problem_report_msg, proof_presentation::verifier::{ state_machine::{VerifierSM, VerifierState}, verification_status::PresentationVerificationStatus, }, }, }; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)] pub struct Verifier { verifier_sm: VerifierSM, } impl Verifier { pub fn create(source_id: &str) -> VcxResult<Self> { trace!("Verifier::create >>> source_id: {source_id:?}"); Ok(Self { verifier_sm: VerifierSM::new(source_id), }) } pub fn create_from_request( source_id: String, presentation_request: &PresentationRequest, ) -> VcxResult<Self> { trace!( "Verifier::create_from_request >>> source_id: {source_id:?}, presentation_request: {presentation_request:?}" ); let verifier_sm = VerifierSM::from_request(&source_id, presentation_request)?; Ok(Self { verifier_sm }) } pub fn create_from_proposal( source_id: &str, presentation_proposal: &ProposePresentationV1, ) -> VcxResult<Self> { trace!( "Issuer::create_from_proposal >>> source_id: {source_id:?}, presentation_proposal: {presentation_proposal:?}" ); Ok(Self { verifier_sm: VerifierSM::from_proposal(source_id, presentation_proposal), }) } pub fn get_source_id(&self) -> String { self.verifier_sm.source_id() } pub fn get_state(&self) -> VerifierState { self.verifier_sm.get_state() } // TODO: Find a better name for this method pub fn mark_presentation_request_sent(&mut self) -> VcxResult<RequestPresentationV1> { if self.verifier_sm.get_state() == VerifierState::PresentationRequestSet { let request = self.verifier_sm.presentation_request_msg()?; self.verifier_sm = self.verifier_sm.clone().mark_presentation_request_sent()?; Ok(request) } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot send presentation request", )) } } // todo: verification and sending ack should be separate apis pub async fn verify_presentation( &mut self, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, presentation: PresentationV1, ) -> VcxResult<AriesMessage> { trace!("Verifier::verify_presentation >>>"); self.verifier_sm = self .verifier_sm .clone() .verify_presentation(ledger, anoncreds, presentation) .await?; self.verifier_sm.get_final_message() } pub fn set_presentation_request( &mut self, presentation_request_data: PresentationRequest, comment: Option<String>, ) -> VcxResult<()> { trace!( "Verifier::set_presentation_request >>> presentation_request_data: {presentation_request_data:?}, comment: \ ${comment:?}" ); self.verifier_sm = self .verifier_sm .clone() .set_presentation_request(&presentation_request_data, comment)?; Ok(()) } pub fn get_presentation_request_msg(&self) -> VcxResult<RequestPresentationV1> { self.verifier_sm.presentation_request_msg() } pub fn get_presentation_request_attachment(&self) -> VcxResult<String> { let pres_req = &self.verifier_sm.presentation_request_msg()?; Ok(get_attach_as_string!( pres_req.content.request_presentations_attach )) } pub fn get_presentation_msg(&self) -> VcxResult<PresentationV1> { self.verifier_sm.get_presentation_msg() } pub fn get_verification_status(&self) -> PresentationVerificationStatus { self.verifier_sm.get_verification_status() } pub fn get_presentation_attachment(&self) -> VcxResult<String> { let presentation = &self.verifier_sm.get_presentation_msg()?; Ok(get_attach_as_string!( presentation.content.presentations_attach )) } pub fn get_presentation_proposal(&self) -> VcxResult<ProposePresentationV1> { self.verifier_sm.presentation_proposal() } pub fn get_thread_id(&self) -> VcxResult<String> { Ok(self.verifier_sm.thread_id()) } pub async fn process_aries_msg( &mut self, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, message: AriesMessage, ) -> VcxResult<Option<AriesMessage>> { let (verifier_sm, message) = match message { AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::ProposePresentation( proposal, ))) => ( self.verifier_sm .clone() .receive_presentation_proposal(proposal)?, None, ), AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Presentation( presentation, ))) => { let sm = self .verifier_sm .clone() .verify_presentation(ledger, anoncreds, presentation) .await?; (sm.clone(), Some(sm.get_final_message()?)) } AriesMessage::ReportProblem(report) => ( self.verifier_sm .clone() .receive_presentation_request_reject(report)?, None, ), AriesMessage::Notification(Notification::ProblemReport(report)) => ( self.verifier_sm .clone() .receive_presentation_request_reject(report.into())?, None, ), AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::ProblemReport(report))) => { ( self.verifier_sm .clone() .receive_presentation_request_reject(report.into())?, None, ) } _ => (self.verifier_sm.clone(), None), }; self.verifier_sm = verifier_sm; Ok(message) } pub fn progressable_by_message(&self) -> bool { self.verifier_sm.progressable_by_message() } pub async fn decline_presentation_proposal<'a>( &'a mut self, reason: &'a str, ) -> VcxResult<ProblemReport> { trace!("Verifier::decline_presentation_proposal >>> reason: {reason:?}"); let state = self.verifier_sm.get_state(); if state == VerifierState::PresentationProposalReceived { let proposal = self.verifier_sm.presentation_proposal()?; let thread_id = match proposal.decorators.thread { Some(thread) => thread.thid, None => proposal.id, }; let problem_report = build_problem_report_msg(Some(reason.to_string()), &thread_id); self.verifier_sm = self .verifier_sm .clone() .reject_presentation_proposal(problem_report.clone()) .await?; Ok(problem_report) } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, format!("Unable to reject presentation proposal in state {state:?}"), )) } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/issuance/mod.rs
aries/aries_vcx/src/handlers/issuance/mod.rs
pub mod holder; pub mod issuer;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/issuance/holder.rs
aries/aries_vcx/src/handlers/issuance/holder.rs
use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use chrono::Utc; use did_parser_nom::Did; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::{ cred_issuance::{ v1::{ ack::{AckCredentialV1, AckCredentialV1Content}, issue_credential::IssueCredentialV1, offer_credential::OfferCredentialV1, propose_credential::ProposeCredentialV1, request_credential::RequestCredentialV1, CredentialIssuanceV1, }, CredentialIssuance, }, notification::ack::{AckContent, AckDecorators, AckStatus}, report_problem::ProblemReport, revocation::revoke::Revoke, }, AriesMessage, }; use uuid::Uuid; use crate::{ common::credentials::get_cred_rev_id, errors::error::prelude::*, handlers::revocation_notification::receiver::RevocationNotificationReceiver, protocols::issuance::holder::state_machine::{HolderFullState, HolderSM, HolderState}, }; fn build_credential_ack(thread_id: &str) -> AckCredentialV1 { let content = AckCredentialV1Content::builder() .inner(AckContent::builder().status(AckStatus::Ok).build()) .build(); let decorators = AckDecorators::builder() .thread(Thread::builder().thid(thread_id.to_owned()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); AckCredentialV1::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build() } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Holder { holder_sm: HolderSM, } impl Holder { pub fn create(source_id: &str) -> VcxResult<Holder> { trace!("Holder::create >>> source_id: {source_id:?}"); let holder_sm = HolderSM::new(source_id.to_string()); Ok(Holder { holder_sm }) } pub fn get_proposal(&self) -> VcxResult<ProposeCredentialV1> { self.holder_sm.get_proposal() } pub fn create_with_proposal( source_id: &str, propose_credential: ProposeCredentialV1, ) -> VcxResult<Holder> { trace!( "Holder::create_with_proposal >>> source_id: {source_id:?}, propose_credential: {propose_credential:?}" ); let holder_sm = HolderSM::with_proposal(propose_credential, source_id.to_string()); Ok(Holder { holder_sm }) } pub fn create_from_offer( source_id: &str, credential_offer: OfferCredentialV1, ) -> VcxResult<Holder> { trace!( "Holder::create_from_offer >>> source_id: {source_id:?}, credential_offer: {credential_offer:?}" ); let holder_sm = HolderSM::from_offer(credential_offer, source_id.to_string()); Ok(Holder { holder_sm }) } pub fn set_proposal(&mut self, credential_proposal: ProposeCredentialV1) -> VcxResult<()> { self.holder_sm = self.holder_sm.clone().set_proposal(credential_proposal)?; Ok(()) } pub async fn prepare_credential_request( &mut self, wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, my_pw_did: Did, ) -> VcxResult<AriesMessage> { self.holder_sm = self .holder_sm .clone() .prepare_credential_request(wallet, ledger, anoncreds, my_pw_did) .await?; match self.get_state() { HolderState::Failed => Ok(self.get_problem_report()?.into()), HolderState::RequestSet => Ok(self.get_msg_credential_request()?.into()), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Holder::prepare_credential_request >> reached unexpected state after calling \ prepare_credential_request", )), } } pub fn get_msg_credential_request(&self) -> VcxResult<RequestCredentialV1> { match self.holder_sm.state { HolderFullState::RequestSet(ref state) => { let mut msg: RequestCredentialV1 = state.msg_credential_request.clone(); let timing = Timing::builder().out_time(Utc::now()).build(); msg.decorators.timing = Some(timing); Ok(msg) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Invalid action", )), } } pub fn decline_offer<'a>(&'a mut self, comment: Option<&'a str>) -> VcxResult<ProblemReport> { self.holder_sm = self .holder_sm .clone() .decline_offer(comment.map(String::from))?; self.get_problem_report() } pub async fn process_credential( &mut self, wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, credential: IssueCredentialV1, ) -> VcxResult<()> { self.holder_sm = self .holder_sm .clone() .receive_credential(wallet, ledger, anoncreds, credential) .await?; Ok(()) } pub fn is_terminal_state(&self) -> bool { self.holder_sm.is_terminal_state() } pub fn get_state(&self) -> HolderState { self.holder_sm.get_state() } pub fn get_source_id(&self) -> String { self.holder_sm.get_source_id() } pub fn get_credential(&self) -> VcxResult<(String, AriesMessage)> { self.holder_sm.get_credential() } pub fn get_attributes(&self) -> VcxResult<String> { self.holder_sm.get_attributes() } pub fn get_attachment(&self) -> VcxResult<String> { self.holder_sm.get_attachment() } pub fn get_offer(&self) -> VcxResult<OfferCredentialV1> { self.holder_sm.get_offer() } pub fn get_tails_location(&self) -> VcxResult<String> { self.holder_sm.get_tails_location() } pub fn get_tails_hash(&self) -> VcxResult<String> { self.holder_sm.get_tails_hash() } pub fn get_rev_reg_id(&self) -> VcxResult<String> { self.holder_sm.get_rev_reg_id() } pub fn get_cred_id(&self) -> VcxResult<String> { self.holder_sm.get_cred_id() } pub fn get_thread_id(&self) -> VcxResult<String> { self.holder_sm.get_thread_id() } pub async fn is_revokable(&self, ledger: &impl AnoncredsLedgerRead) -> VcxResult<bool> { self.holder_sm.is_revokable(ledger).await } pub async fn is_revoked( &self, wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, ) -> VcxResult<bool> { self.holder_sm.is_revoked(wallet, ledger, anoncreds).await } pub async fn delete_credential( &self, wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ) -> VcxResult<()> { self.holder_sm.delete_credential(wallet, anoncreds).await } pub fn get_credential_status(&self) -> VcxResult<u32> { Ok(self.holder_sm.credential_status()) } pub async fn get_cred_rev_id( &self, wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ) -> VcxResult<u32> { get_cred_rev_id(wallet, anoncreds, &self.get_cred_id()?).await } pub async fn handle_revocation_notification( &self, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, wallet: &impl BaseWallet, notification: Revoke, ) -> VcxResult<()> { if self.holder_sm.is_revokable(ledger).await? { // TODO: Store to remember notification was received along with details RevocationNotificationReceiver::build( self.get_rev_reg_id()?, self.get_cred_rev_id(wallet, anoncreds).await?, ) .handle_revocation_notification(notification) .await?; Ok(()) } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Unexpected revocation notification, credential is not revokable".to_string(), )) } } pub fn get_problem_report(&self) -> VcxResult<ProblemReport> { self.holder_sm.get_problem_report() } pub async fn process_aries_msg( &mut self, wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, message: AriesMessage, ) -> VcxResult<()> { let holder_sm = match message { AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::OfferCredential(offer), )) => self.holder_sm.clone().receive_offer(offer)?, AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::IssueCredential(credential), )) => { self.holder_sm .clone() .receive_credential(wallet, ledger, anoncreds, credential) .await? } // TODO: What about credential issuance problem report? AriesMessage::ReportProblem(report) => { self.holder_sm.clone().receive_problem_report(report)? } _ => self.holder_sm.clone(), }; self.holder_sm = holder_sm; Ok(()) } pub fn get_final_message(&self) -> VcxResult<Option<AriesMessage>> { match &self.holder_sm.state { HolderFullState::Finished(state) if Some(true) == state.ack_requested => { let ack_msg = build_credential_ack(&self.get_thread_id()?); Ok(Some(ack_msg.into())) } _ => Ok(None), } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/issuance/issuer.rs
aries/aries_vcx/src/handlers/issuance/issuer.rs
use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use messages::{ misc::MimeType, msg_fields::protocols::{ cred_issuance::{ common::CredentialAttr, v1::{ ack::AckCredentialV1, issue_credential::IssueCredentialV1, offer_credential::OfferCredentialV1, propose_credential::ProposeCredentialV1, request_credential::RequestCredentialV1, CredentialIssuanceV1, CredentialPreviewV1, }, CredentialIssuance, }, notification::Notification, report_problem::ProblemReport, }, AriesMessage, }; use crate::{ errors::error::prelude::*, handlers::util::OfferInfo, protocols::issuance::issuer::state_machine::{IssuerSM, IssuerState, RevocationInfoV1}, }; #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct Issuer { issuer_sm: IssuerSM, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct IssuerConfig { pub cred_def_id: String, pub rev_reg_id: Option<String>, pub tails_file: Option<String>, } fn _build_credential_preview(credential_json: &str) -> VcxResult<CredentialPreviewV1> { trace!( "Issuer::_build_credential_preview >>> credential_json: {:?}", secret!(credential_json) ); let cred_values: serde_json::Value = serde_json::from_str(credential_json).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!( "Can't deserialize credential preview json. credential_json: {credential_json}, error: {err:?}" ), ) })?; // todo: should throw err if cred_values is not serde_json::Value::Array or // serde_json::Value::Object let mut attributes = Vec::new(); match cred_values { serde_json::Value::Array(cred_values) => { for cred_value in cred_values.iter() { let key = cred_value.get("name").ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidAttributesStructure, format!("No 'name' field in cred_value: {cred_value:?}"), ))?; let value = cred_value.get("value").ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidAttributesStructure, format!("No 'value' field in cred_value: {cred_value:?}"), ))?; let name = key .as_str() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidOption, "Credential value names are currently only allowed to be strings", ))? .to_owned(); let value = value .as_str() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidOption, "Credential values are currently only allowed to be strings", ))? .to_owned(); let attr = CredentialAttr::builder() .name(name) .value(value) .mime_type(MimeType::Plain) .build(); attributes.push(attr); } } serde_json::Value::Object(values_map) => { for item in values_map.iter() { let (key, value) = item; let value = value .as_str() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidOption, "Credential values are currently only allowed to be strings", ))? .to_owned(); let attr = CredentialAttr::builder() .name(key.to_owned()) .value(value) .mime_type(MimeType::Plain) .build(); attributes.push(attr); } } _ => {} }; Ok(CredentialPreviewV1::new(attributes)) } impl Issuer { pub fn create(source_id: &str) -> VcxResult<Issuer> { trace!("Issuer::create >>> source_id: {source_id:?}"); let issuer_sm = IssuerSM::new(source_id); Ok(Issuer { issuer_sm }) } pub fn create_from_proposal( source_id: &str, credential_proposal: &ProposeCredentialV1, ) -> VcxResult<Issuer> { trace!( "Issuer::create_from_proposal >>> source_id: {source_id:?}, credential_proposal: {credential_proposal:?}" ); let issuer_sm = IssuerSM::from_proposal(source_id, credential_proposal); Ok(Issuer { issuer_sm }) } // todo: "build_credential_offer_msg" should take optional revReg as parameter, build OfferInfo // from that pub async fn build_credential_offer_msg( &mut self, wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, offer_info: OfferInfo, comment: Option<String>, ) -> VcxResult<()> { let credential_preview = _build_credential_preview(&offer_info.credential_json)?; let libindy_cred_offer = anoncreds .issuer_create_credential_offer(wallet, &offer_info.cred_def_id) .await?; self.issuer_sm = self.issuer_sm.clone().build_credential_offer_msg( &serde_json::to_string(&libindy_cred_offer)?, credential_preview, comment, &offer_info, )?; Ok(()) } pub fn get_credential_offer(&self) -> VcxResult<OfferCredentialV1> { self.issuer_sm.get_credential_offer_msg() } pub fn get_credential_offer_msg(&self) -> VcxResult<AriesMessage> { let offer = self.issuer_sm.get_credential_offer_msg()?; Ok(offer.into()) } pub fn process_credential_request(&mut self, request: RequestCredentialV1) -> VcxResult<()> { self.issuer_sm = self.issuer_sm.clone().receive_request(request)?; Ok(()) } pub fn process_credential_ack(&mut self, ack: AckCredentialV1) -> VcxResult<()> { self.issuer_sm = self.issuer_sm.clone().receive_ack(ack)?; Ok(()) } pub async fn build_credential( &mut self, wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ) -> VcxResult<()> { self.issuer_sm = self .issuer_sm .clone() .build_credential(wallet, anoncreds) .await?; Ok(()) } pub fn get_msg_issue_credential(&mut self) -> VcxResult<IssueCredentialV1> { self.issuer_sm.clone().get_msg_issue_credential() } pub fn get_state(&self) -> IssuerState { self.issuer_sm.get_state() } pub fn get_source_id(&self) -> VcxResult<String> { Ok(self.issuer_sm.get_source_id()) } pub fn is_terminal_state(&self) -> bool { self.issuer_sm.is_terminal_state() } pub fn get_revocation_id(&self) -> VcxResult<u32> { self.issuer_sm .get_revocation_info() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Credential has not yet been created", ))? .cred_rev_id .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Credential has not yet been created or is irrevocable", )) .and_then(|s| s.parse().map_err(Into::into)) } pub async fn revoke_credential_local( &self, wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger: &impl AnoncredsLedgerRead, ) -> VcxResult<()> { let revocation_info: RevocationInfoV1 = self.issuer_sm .get_revocation_info() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Credential is not revocable, no revocation info has been found.", ))?; if let (Some(cred_rev_id), Some(rev_reg_id), Some(_tails_file)) = ( revocation_info.cred_rev_id, revocation_info.rev_reg_id, revocation_info.tails_file, ) { #[allow(deprecated)] // TODO - https://github.com/openwallet-foundation/vcx/issues/1309 let rev_reg_delta_json = ledger .get_rev_reg_delta_json(&rev_reg_id.to_owned().try_into()?, None, None) .await? .0; anoncreds .revoke_credential_local( wallet, &rev_reg_id.try_into()?, cred_rev_id.parse()?, rev_reg_delta_json, ) .await?; } else { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Revocation info is not complete, cannot revoke credential.", )); } Ok(()) } pub fn get_rev_reg_id(&self) -> VcxResult<String> { self.issuer_sm.get_rev_reg_id() } pub fn get_rev_id(&self) -> VcxResult<u32> { self.issuer_sm.get_rev_id() } pub fn get_thread_id(&self) -> VcxResult<String> { self.issuer_sm.thread_id() } pub fn get_proposal(&self) -> VcxResult<ProposeCredentialV1> { self.issuer_sm.get_proposal() } pub fn get_credential_status(&self) -> VcxResult<u32> { Ok(self.issuer_sm.credential_status()) } pub fn is_revokable(&self) -> bool { self.issuer_sm.is_revokable() } pub async fn is_revoked(&self, ledger: &impl AnoncredsLedgerRead) -> VcxResult<bool> { self.issuer_sm.is_revoked(ledger).await } pub async fn receive_proposal(&mut self, proposal: ProposeCredentialV1) -> VcxResult<()> { self.issuer_sm = self.issuer_sm.clone().receive_proposal(proposal)?; Ok(()) } pub async fn receive_request(&mut self, request: RequestCredentialV1) -> VcxResult<()> { self.issuer_sm = self.issuer_sm.clone().receive_request(request)?; Ok(()) } pub async fn receive_ack(&mut self, ack: AckCredentialV1) -> VcxResult<()> { self.issuer_sm = self.issuer_sm.clone().receive_ack(ack)?; Ok(()) } pub async fn receive_problem_report(&mut self, problem_report: ProblemReport) -> VcxResult<()> { self.issuer_sm = self .issuer_sm .clone() .receive_problem_report(problem_report)?; Ok(()) } pub fn get_problem_report(&self) -> VcxResult<ProblemReport> { self.issuer_sm.get_problem_report() } // todo: will ultimately end up in generic SM layer pub async fn process_aries_msg(&mut self, msg: AriesMessage) -> VcxResult<()> { let issuer_sm = match msg { AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::ProposeCredential(proposal), )) => self.issuer_sm.clone().receive_proposal(proposal)?, AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::RequestCredential(request), )) => self.issuer_sm.clone().receive_request(request)?, AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::Ack(ack), )) => self.issuer_sm.clone().receive_ack(ack)?, AriesMessage::ReportProblem(report) => { self.issuer_sm.clone().receive_problem_report(report)? } AriesMessage::Notification(Notification::ProblemReport(report)) => self .issuer_sm .clone() .receive_problem_report(report.into())?, AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::ProblemReport(report), )) => self .issuer_sm .clone() .receive_problem_report(report.into())?, _ => self.issuer_sm.clone(), }; self.issuer_sm = issuer_sm; Ok(()) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/out_of_band/sender.rs
aries/aries_vcx/src/handlers/out_of_band/sender.rs
use std::fmt::Display; use base64::Engine; use messages::{ msg_fields::protocols::{ cred_issuance::{v1::CredentialIssuanceV1, CredentialIssuance}, out_of_band::{ invitation::{Invitation, InvitationContent, InvitationDecorators, OobService}, OobGoalCode, }, present_proof::{v1::PresentProofV1, PresentProof}, }, msg_types::Protocol, AriesMessage, }; use shared::maybe_known::MaybeKnown; use url::Url; use uuid::Uuid; use crate::{ errors::error::prelude::*, handlers::util::{make_attach_from_str, AttachmentId}, utils::base64::URL_SAFE_LENIENT, }; #[derive(Debug, PartialEq, Clone)] pub struct OutOfBandSender { pub oob: Invitation, } impl OutOfBandSender { pub fn create() -> Self { let id = Uuid::new_v4().to_string(); let content = InvitationContent::builder().services(Vec::new()).build(); let decorators = InvitationDecorators::default(); Self { oob: Invitation::builder() .id(id) .content(content) .decorators(decorators) .build(), } } pub fn create_from_invitation(invitation: Invitation) -> Self { Self { oob: invitation } } pub fn set_label(mut self, label: &str) -> Self { self.oob.content.label = Some(label.to_string()); self } pub fn set_goal_code(mut self, goal_code: OobGoalCode) -> Self { self.oob.content.goal_code = Some(MaybeKnown::Known(goal_code)); self } pub fn set_goal(mut self, goal: &str) -> Self { self.oob.content.goal = Some(goal.to_string()); self } pub fn append_service(mut self, service: &OobService) -> Self { self.oob.content.services.push(service.clone()); self } pub fn get_services(&self) -> Vec<OobService> { self.oob.content.services.clone() } pub fn get_id(&self) -> String { self.oob.id.clone() } pub fn append_handshake_protocol(mut self, protocol: Protocol) -> VcxResult<Self> { let new_protocol = match protocol { Protocol::ConnectionType(_) | Protocol::DidExchangeType(_) => { MaybeKnown::Known(protocol) } _ => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::ActionNotSupported, "Protocol not supported".to_string(), )) } }; match self.oob.content.handshake_protocols { Some(ref mut protocols) => { protocols.push(new_protocol); } None => { self.oob.content.handshake_protocols = Some(vec![new_protocol]); } }; Ok(self) } pub fn append_a2a_message(mut self, msg: AriesMessage) -> VcxResult<Self> { let (attach_id, attach) = match msg { a2a_msg @ AriesMessage::PresentProof(PresentProof::V1( PresentProofV1::RequestPresentation(_), )) => ( AttachmentId::PresentationRequest, json!(&a2a_msg).to_string(), ), a2a_msg @ AriesMessage::CredentialIssuance(CredentialIssuance::V1( CredentialIssuanceV1::OfferCredential(_), )) => (AttachmentId::CredentialOffer, json!(&a2a_msg).to_string()), _ => { error!("Appended message type {msg:?} is not allowed."); return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidMessageFormat, format!("Appended message type {msg:?} is not allowed."), )); } }; self.oob .content .requests_attach .get_or_insert(Vec::with_capacity(1)) .push(make_attach_from_str!( &attach, attach_id.as_ref().to_string() )); Ok(self) } pub fn invitation_to_aries_message(&self) -> AriesMessage { self.oob.clone().into() } pub fn invitation_to_json_string(&self) -> String { self.invitation_to_aries_message().to_string() } fn invitation_to_base64_url(&self) -> String { URL_SAFE_LENIENT.encode(self.invitation_to_json_string()) } pub fn invitation_to_url(&self, domain_path: &str) -> VcxResult<Url> { let oob_url = Url::parse(domain_path)? .query_pairs_mut() .append_pair("oob", &self.invitation_to_base64_url()) .finish() .to_owned(); Ok(oob_url) } } impl Display for OutOfBandSender { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", json!(AriesMessage::from(self.oob.clone()))) } } #[cfg(test)] mod tests { use messages::{ msg_fields::protocols::out_of_band::{ invitation::{Invitation, InvitationContent, InvitationDecorators, OobService}, OobGoalCode, }, msg_types::{ connection::{ConnectionType, ConnectionTypeV1}, protocols::did_exchange::{DidExchangeType, DidExchangeTypeV1}, Protocol, }, }; use shared::maybe_known::MaybeKnown; use super::*; // Example invite formats referenced (with change to use OOB 1.1) from example invite in RFC 0434 - https://github.com/decentralized-identity/aries-rfcs/tree/main/features/0434-outofband const JSON_OOB_INVITE_NO_WHITESPACE: &str = r#"{"@type":"https://didcomm.org/out-of-band/1.1/invitation","@id":"69212a3a-d068-4f9d-a2dd-4741bca89af3","label":"Faber College","goal_code":"issue-vc","goal":"To issue a Faber College Graduate credential","handshake_protocols":["https://didcomm.org/didexchange/1.0","https://didcomm.org/connections/1.0"],"services":["did:sov:LjgpST2rjsoxYegQDRm7EL"]}"#; const OOB_BASE64_URL_ENCODED: &str = "eyJAdHlwZSI6Imh0dHBzOi8vZGlkY29tbS5vcmcvb3V0LW9mLWJhbmQvMS4xL2ludml0YXRpb24iLCJAaWQiOiI2OTIxMmEzYS1kMDY4LTRmOWQtYTJkZC00NzQxYmNhODlhZjMiLCJsYWJlbCI6IkZhYmVyIENvbGxlZ2UiLCJnb2FsX2NvZGUiOiJpc3N1ZS12YyIsImdvYWwiOiJUbyBpc3N1ZSBhIEZhYmVyIENvbGxlZ2UgR3JhZHVhdGUgY3JlZGVudGlhbCIsImhhbmRzaGFrZV9wcm90b2NvbHMiOlsiaHR0cHM6Ly9kaWRjb21tLm9yZy9kaWRleGNoYW5nZS8xLjAiLCJodHRwczovL2RpZGNvbW0ub3JnL2Nvbm5lY3Rpb25zLzEuMCJdLCJzZXJ2aWNlcyI6WyJkaWQ6c292OkxqZ3BTVDJyanNveFllZ1FEUm03RUwiXX0"; const OOB_URL: &str = "http://example.com/ssi?oob=eyJAdHlwZSI6Imh0dHBzOi8vZGlkY29tbS5vcmcvb3V0LW9mLWJhbmQvMS4xL2ludml0YXRpb24iLCJAaWQiOiI2OTIxMmEzYS1kMDY4LTRmOWQtYTJkZC00NzQxYmNhODlhZjMiLCJsYWJlbCI6IkZhYmVyIENvbGxlZ2UiLCJnb2FsX2NvZGUiOiJpc3N1ZS12YyIsImdvYWwiOiJUbyBpc3N1ZSBhIEZhYmVyIENvbGxlZ2UgR3JhZHVhdGUgY3JlZGVudGlhbCIsImhhbmRzaGFrZV9wcm90b2NvbHMiOlsiaHR0cHM6Ly9kaWRjb21tLm9yZy9kaWRleGNoYW5nZS8xLjAiLCJodHRwczovL2RpZGNvbW0ub3JnL2Nvbm5lY3Rpb25zLzEuMCJdLCJzZXJ2aWNlcyI6WyJkaWQ6c292OkxqZ3BTVDJyanNveFllZ1FEUm03RUwiXX0"; // Params mimic example invitation in RFC 0434 - https://github.com/decentralized-identity/aries-rfcs/tree/main/features/0434-outofband fn _create_invitation() -> Invitation { let id = "69212a3a-d068-4f9d-a2dd-4741bca89af3"; let did = "did:sov:LjgpST2rjsoxYegQDRm7EL"; let service = OobService::Did(did.to_string()); let handshake_protocols = vec![ MaybeKnown::Known(Protocol::DidExchangeType(DidExchangeType::V1( DidExchangeTypeV1::new_v1_0(), ))), MaybeKnown::Known(Protocol::ConnectionType(ConnectionType::V1( ConnectionTypeV1::new_v1_0(), ))), ]; let content = InvitationContent::builder() .services(vec![service]) .goal("To issue a Faber College Graduate credential".to_string()) .goal_code(MaybeKnown::Known(OobGoalCode::IssueVC)) .label("Faber College".to_string()) .handshake_protocols(handshake_protocols) .build(); let decorators = InvitationDecorators::default(); let invitation: Invitation = Invitation::builder() .id(id.to_string()) .content(content) .decorators(decorators) .build(); invitation } #[test] fn invitation_to_json() { let out_of_band_sender = OutOfBandSender::create_from_invitation(_create_invitation()); let json_invite = out_of_band_sender.invitation_to_json_string(); assert_eq!(JSON_OOB_INVITE_NO_WHITESPACE, json_invite); } #[test] fn invitation_to_base64_url() { let out_of_band_sender = OutOfBandSender::create_from_invitation(_create_invitation()); let base64_url_invite = out_of_band_sender.invitation_to_base64_url(); assert_eq!(OOB_BASE64_URL_ENCODED, base64_url_invite); } #[test] fn invitation_to_url() { let out_of_band_sender = OutOfBandSender::create_from_invitation(_create_invitation()); let oob_url = out_of_band_sender .invitation_to_url("http://example.com/ssi") .unwrap() .to_string(); assert_eq!(OOB_URL, oob_url); } } // #[cfg(test)] // mod unit_tests { // use crate::utils::devsetup::SetupMocks; // use messages::diddoc::aries::service::AriesService; // use messages::protocols::connection::did::Did; // use messages::protocols::issuance::credential_offer::CredentialOffer; // // use super::*; // // fn _create_oob() -> OutOfBandSender { // OutOfBandSender::create() // .set_label("oob-label") // .set_goal("issue-vc") // .set_goal_code(&GoalCode::IssueVC) // } // // fn _create_service() -> ServiceOob { // ServiceOob::AriesService( // AriesService::create() // .set_service_endpoint("http://example.org/agent".into()) // .set_routing_keys(vec!["12345".into()]) // .set_recipient_keys(vec!["abcde".into()]), // ) // } // // #[test] // fn test_append_aries_service_object_to_oob_services() { // let _setup = SetupMocks::init(); // // let service = _create_service(); // let oob = _create_oob().append_service(&service); // let resolved_service = oob.get_services(); // // assert_eq!(resolved_service.len(), 1); // assert_eq!(service, resolved_service[0]); // } // // #[test] // fn test_append_did_service_object_to_oob_services() { // let _setup = SetupMocks::init(); // // let service = ServiceOob::Did(Did::new("V4SGRU86Z58d6TV7PBUe6f").unwrap()); // let oob = _create_oob().append_service(&service); // let resolved_service = oob.get_services(); // // assert_eq!(resolved_service.len(), 1); // assert_eq!(service, resolved_service[0]); // } // // #[test] // fn test_oob_sender_to_a2a_message() { // let _setup = SetupMocks::init(); // // let inserted_offer = CredentialOffer::create(); // let basic_msg = A2AMessage::CredentialOffer(inserted_offer.clone()); // let oob = _create_oob().append_a2a_message(basic_msg).unwrap(); // let oob_msg = oob.to_a2a_message(); // assert!(matches!(oob_msg, A2AMessage::OutOfBandInvitation(..))); // if let A2AMessage::OutOfBandInvitation(oob_msg) = oob_msg { // let attachment = oob_msg.requests_attach.content().unwrap(); // let attachment: A2AMessage = serde_json::from_str(&attachment).unwrap(); // assert!(matches!(attachment, A2AMessage::CredentialOffer(..))); // if let A2AMessage::CredentialOffer(offer) = attachment { // assert_eq!(offer, inserted_offer) // } // } // } // }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/out_of_band/mod.rs
aries/aries_vcx/src/handlers/out_of_band/mod.rs
pub mod receiver; pub mod sender; #[derive(Debug, Clone, PartialEq)] pub enum GenericOutOfBand { Receiver(receiver::OutOfBandReceiver), Sender(sender::OutOfBandSender), }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/handlers/out_of_band/receiver.rs
aries/aries_vcx/src/handlers/out_of_band/receiver.rs
use std::{clone::Clone, fmt::Display, str::FromStr}; use base64::{engine::general_purpose, Engine}; use messages::{ decorators::attachment::{Attachment, AttachmentType}, msg_fields::protocols::{ cred_issuance::v1::offer_credential::OfferCredentialV1, out_of_band::{invitation::Invitation, OutOfBand}, present_proof::v1::request::RequestPresentationV1, }, AriesMessage, }; use serde::Deserialize; use serde_json::Value; use url::Url; use crate::{ errors::error::prelude::*, handlers::util::AttachmentId, utils::base64::URL_SAFE_LENIENT, }; #[derive(Debug, PartialEq, Clone)] pub struct OutOfBandReceiver { pub oob: Invitation, } impl OutOfBandReceiver { pub fn create_from_a2a_msg(msg: &AriesMessage) -> VcxResult<Self> { trace!("OutOfBandReceiver::create_from_a2a_msg >>> msg: {msg:?}"); match msg { AriesMessage::OutOfBand(OutOfBand::Invitation(oob)) => { Ok(OutOfBandReceiver { oob: oob.clone() }) } m => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidMessageFormat, format!( "Expected OutOfBandInvitation message to create OutOfBandReceiver, but \ received message of unknown type: {m:?}" ), )), } } pub fn create_from_json_encoded_oob(oob_json: &str) -> VcxResult<Self> { Ok(Self { oob: extract_encoded_invitation_from_json_string(oob_json)?, }) } pub fn create_from_url_encoded_oob(oob_url_string: &str) -> VcxResult<Self> { // TODO - URL Shortening Ok(Self { oob: extract_encoded_invitation_from_json_string( &extract_encoded_invitation_from_base64_url(&extract_encoded_invitation_from_url( oob_url_string, )?)?, )?, }) } pub fn get_id(&self) -> String { self.oob.id.clone() } // TODO: There may be multiple A2AMessages in a single OoB msg pub fn extract_a2a_message(&self) -> VcxResult<Option<AriesMessage>> { trace!("OutOfBandReceiver::extract_a2a_message >>>"); if let Some(attach) = self .oob .content .requests_attach .as_ref() .and_then(|v| v.first()) { attachment_to_aries_message(attach) } else { Ok(None) } } pub fn invitation_to_aries_message(&self) -> AriesMessage { self.oob.clone().into() } pub fn invitation_to_json_string(&self) -> String { self.invitation_to_aries_message().to_string() } fn invitation_to_base64_url(&self) -> String { URL_SAFE_LENIENT.encode(self.invitation_to_json_string()) } pub fn invitation_to_url(&self, domain_path: &str) -> VcxResult<Url> { let oob_url = Url::parse(domain_path)? .query_pairs_mut() .append_pair("oob", &self.invitation_to_base64_url()) .finish() .to_owned(); Ok(oob_url) } } fn extract_encoded_invitation_from_json_string(oob_json: &str) -> VcxResult<Invitation> { Ok(serde_json::from_str(oob_json)?) } fn extract_encoded_invitation_from_base64_url(base64_url_encoded_oob: &str) -> VcxResult<String> { Ok(String::from_utf8( URL_SAFE_LENIENT.decode(base64_url_encoded_oob)?, )?) } fn extract_encoded_invitation_from_url(oob_url_string: &str) -> VcxResult<String> { let oob_url = Url::parse(oob_url_string)?; let (_oob_query, base64_url_encoded_oob) = oob_url .query_pairs() .find(|(name, _value)| name == "oob") .ok_or_else(|| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidInput, "OutOfBand Invitation URL is missing 'oob' query parameter", ) })?; Ok(base64_url_encoded_oob.into_owned()) } impl Display for OutOfBandReceiver { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", json!(AriesMessage::from(self.oob.clone()))) } } fn attachment_to_aries_message(attach: &Attachment) -> VcxResult<Option<AriesMessage>> { let AttachmentType::Base64(encoded_attach) = &attach.data.content else { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Attachment is not base 64 encoded JSON: {attach:?}"), )); }; let Ok(bytes) = general_purpose::STANDARD.decode(encoded_attach) else { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Attachment is not base 64 encoded JSON: {attach:?}"), )); }; let attach_json: Value = serde_json::from_slice(&bytes).map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Attachment is not base 64 encoded JSON: {attach:?}"), ) })?; let attach_id = if let Some(attach_id) = attach.id.as_deref() { AttachmentId::from_str(attach_id).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Failed to deserialize attachment ID: {err}"), ) }) } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidMessageFormat, format!("Missing attachment ID on attach: {attach:?}"), )) }?; match attach_id { AttachmentId::CredentialOffer => { let offer = OfferCredentialV1::deserialize(&attach_json).map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Failed to deserialize attachment: {attach_json:?}"), ) })?; Ok(Some(offer.into())) } AttachmentId::PresentationRequest => { let request = RequestPresentationV1::deserialize(&attach_json).map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Failed to deserialize attachment: {attach_json:?}"), ) })?; Ok(Some(request.into())) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidMessageFormat, format!("unexpected attachment type: {attach_id:?}"), )), } } #[cfg(test)] mod tests { use messages::{ msg_fields::protocols::out_of_band::{ invitation::{Invitation, InvitationContent, InvitationDecorators, OobService}, OobGoalCode, }, msg_types::{ connection::{ConnectionType, ConnectionTypeV1}, protocols::did_exchange::{DidExchangeType, DidExchangeTypeV1}, Protocol, }, }; use shared::maybe_known::MaybeKnown; use super::*; // Example invite formats referenced (with change to use OOB 1.1) from example invite in RFC 0434 - https://github.com/decentralized-identity/aries-rfcs/tree/main/features/0434-outofband const JSON_OOB_INVITE: &str = r#"{ "@type": "https://didcomm.org/out-of-band/1.1/invitation", "@id": "69212a3a-d068-4f9d-a2dd-4741bca89af3", "label": "Faber College", "goal_code": "issue-vc", "goal": "To issue a Faber College Graduate credential", "handshake_protocols": ["https://didcomm.org/didexchange/1.0", "https://didcomm.org/connections/1.0"], "services": ["did:sov:LjgpST2rjsoxYegQDRm7EL"] }"#; const JSON_OOB_INVITE_NO_WHITESPACE: &str = r#"{"@type":"https://didcomm.org/out-of-band/1.1/invitation","@id":"69212a3a-d068-4f9d-a2dd-4741bca89af3","label":"Faber College","goal_code":"issue-vc","goal":"To issue a Faber College Graduate credential","handshake_protocols":["https://didcomm.org/didexchange/1.0","https://didcomm.org/connections/1.0"],"services":["did:sov:LjgpST2rjsoxYegQDRm7EL"]}"#; const OOB_BASE64_URL_ENCODED: &str = "eyJAdHlwZSI6Imh0dHBzOi8vZGlkY29tbS5vcmcvb3V0LW9mLWJhbmQvMS4xL2ludml0YXRpb24iLCJAaWQiOiI2OTIxMmEzYS1kMDY4LTRmOWQtYTJkZC00NzQxYmNhODlhZjMiLCJsYWJlbCI6IkZhYmVyIENvbGxlZ2UiLCJnb2FsX2NvZGUiOiJpc3N1ZS12YyIsImdvYWwiOiJUbyBpc3N1ZSBhIEZhYmVyIENvbGxlZ2UgR3JhZHVhdGUgY3JlZGVudGlhbCIsImhhbmRzaGFrZV9wcm90b2NvbHMiOlsiaHR0cHM6Ly9kaWRjb21tLm9yZy9kaWRleGNoYW5nZS8xLjAiLCJodHRwczovL2RpZGNvbW0ub3JnL2Nvbm5lY3Rpb25zLzEuMCJdLCJzZXJ2aWNlcyI6WyJkaWQ6c292OkxqZ3BTVDJyanNveFllZ1FEUm03RUwiXX0"; const OOB_URL: &str = "http://example.com/ssi?oob=eyJAdHlwZSI6Imh0dHBzOi8vZGlkY29tbS5vcmcvb3V0LW9mLWJhbmQvMS4xL2ludml0YXRpb24iLCJAaWQiOiI2OTIxMmEzYS1kMDY4LTRmOWQtYTJkZC00NzQxYmNhODlhZjMiLCJsYWJlbCI6IkZhYmVyIENvbGxlZ2UiLCJnb2FsX2NvZGUiOiJpc3N1ZS12YyIsImdvYWwiOiJUbyBpc3N1ZSBhIEZhYmVyIENvbGxlZ2UgR3JhZHVhdGUgY3JlZGVudGlhbCIsImhhbmRzaGFrZV9wcm90b2NvbHMiOlsiaHR0cHM6Ly9kaWRjb21tLm9yZy9kaWRleGNoYW5nZS8xLjAiLCJodHRwczovL2RpZGNvbW0ub3JnL2Nvbm5lY3Rpb25zLzEuMCJdLCJzZXJ2aWNlcyI6WyJkaWQ6c292OkxqZ3BTVDJyanNveFllZ1FEUm03RUwiXX0"; const OOB_URL_WITH_PADDING: &str = "http://example.com/ssi?oob=eyJAdHlwZSI6Imh0dHBzOi8vZGlkY29tbS5vcmcvb3V0LW9mLWJhbmQvMS4xL2ludml0YXRpb24iLCJAaWQiOiI2OTIxMmEzYS1kMDY4LTRmOWQtYTJkZC00NzQxYmNhODlhZjMiLCJsYWJlbCI6IkZhYmVyIENvbGxlZ2UiLCJnb2FsX2NvZGUiOiJpc3N1ZS12YyIsImdvYWwiOiJUbyBpc3N1ZSBhIEZhYmVyIENvbGxlZ2UgR3JhZHVhdGUgY3JlZGVudGlhbCIsImhhbmRzaGFrZV9wcm90b2NvbHMiOlsiaHR0cHM6Ly9kaWRjb21tLm9yZy9kaWRleGNoYW5nZS8xLjAiLCJodHRwczovL2RpZGNvbW0ub3JnL2Nvbm5lY3Rpb25zLzEuMCJdLCJzZXJ2aWNlcyI6WyJkaWQ6c292OkxqZ3BTVDJyanNveFllZ1FEUm03RUwiXX0%3D"; const OOB_URL_WITH_PADDING_NOT_PERCENT_ENCODED: &str = "http://example.com/ssi?oob=eyJAdHlwZSI6Imh0dHBzOi8vZGlkY29tbS5vcmcvb3V0LW9mLWJhbmQvMS4xL2ludml0YXRpb24iLCJAaWQiOiI2OTIxMmEzYS1kMDY4LTRmOWQtYTJkZC00NzQxYmNhODlhZjMiLCJsYWJlbCI6IkZhYmVyIENvbGxlZ2UiLCJnb2FsX2NvZGUiOiJpc3N1ZS12YyIsImdvYWwiOiJUbyBpc3N1ZSBhIEZhYmVyIENvbGxlZ2UgR3JhZHVhdGUgY3JlZGVudGlhbCIsImhhbmRzaGFrZV9wcm90b2NvbHMiOlsiaHR0cHM6Ly9kaWRjb21tLm9yZy9kaWRleGNoYW5nZS8xLjAiLCJodHRwczovL2RpZGNvbW0ub3JnL2Nvbm5lY3Rpb25zLzEuMCJdLCJzZXJ2aWNlcyI6WyJkaWQ6c292OkxqZ3BTVDJyanNveFllZ1FEUm03RUwiXX0="; // Params mimic example invitation in RFC 0434 - https://github.com/decentralized-identity/aries-rfcs/tree/main/features/0434-outofband fn _create_invitation() -> Invitation { let id = "69212a3a-d068-4f9d-a2dd-4741bca89af3"; let did = "did:sov:LjgpST2rjsoxYegQDRm7EL"; let service = OobService::Did(did.to_string()); let handshake_protocols = vec![ MaybeKnown::Known(Protocol::DidExchangeType(DidExchangeType::V1( DidExchangeTypeV1::new_v1_0(), ))), MaybeKnown::Known(Protocol::ConnectionType(ConnectionType::V1( ConnectionTypeV1::new_v1_0(), ))), ]; let content = InvitationContent::builder() .services(vec![service]) .goal("To issue a Faber College Graduate credential".to_string()) .goal_code(MaybeKnown::Known(OobGoalCode::IssueVC)) .label("Faber College".to_string()) .handshake_protocols(handshake_protocols) .build(); let decorators = InvitationDecorators::default(); let invitation: Invitation = Invitation::builder() .id(id.to_string()) .content(content) .decorators(decorators) .build(); invitation } #[test] fn receive_invitation_by_json() { let base_invite = _create_invitation(); let parsed_invite = OutOfBandReceiver::create_from_json_encoded_oob(JSON_OOB_INVITE) .unwrap() .oob; assert_eq!(base_invite, parsed_invite); } #[test] fn receive_invitation_by_json_no_whitespace() { let base_invite = _create_invitation(); let parsed_invite = OutOfBandReceiver::create_from_json_encoded_oob(JSON_OOB_INVITE_NO_WHITESPACE) .unwrap() .oob; assert_eq!(base_invite, parsed_invite); } #[test] fn receive_invitation_by_url() { let base_invite = _create_invitation(); let parsed_invite = OutOfBandReceiver::create_from_url_encoded_oob(OOB_URL) .unwrap() .oob; assert_eq!(base_invite, parsed_invite); } #[test] fn receive_invitation_by_url_with_padding() { let base_invite = _create_invitation(); let parsed_invite = OutOfBandReceiver::create_from_url_encoded_oob(OOB_URL_WITH_PADDING) .unwrap() .oob; assert_eq!(base_invite, parsed_invite); } #[test] fn receive_invitation_by_url_with_padding_no_percent_encoding() { let base_invite = _create_invitation(); let parsed_invite = OutOfBandReceiver::create_from_url_encoded_oob( OOB_URL_WITH_PADDING_NOT_PERCENT_ENCODED, ) .unwrap() .oob; assert_eq!(base_invite, parsed_invite); } #[test] fn invitation_to_json() { let out_of_band_receiver = OutOfBandReceiver::create_from_json_encoded_oob(JSON_OOB_INVITE).unwrap(); let json_invite = out_of_band_receiver.invitation_to_json_string(); assert_eq!(JSON_OOB_INVITE_NO_WHITESPACE, json_invite); } #[test] fn invitation_to_base64_url() { let out_of_band_receiver = OutOfBandReceiver::create_from_json_encoded_oob(JSON_OOB_INVITE).unwrap(); let base64_url_invite = out_of_band_receiver.invitation_to_base64_url(); assert_eq!(OOB_BASE64_URL_ENCODED, base64_url_invite); } #[test] fn invitation_to_url() { let out_of_band_receiver = OutOfBandReceiver::create_from_json_encoded_oob(JSON_OOB_INVITE).unwrap(); let oob_url = out_of_band_receiver .invitation_to_url("http://example.com/ssi") .unwrap() .to_string(); assert_eq!(OOB_URL, oob_url); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/test_credential_issuance.rs
aries/aries_vcx/tests/test_credential_issuance.rs
use std::error::Error; use aries_vcx::protocols::{ issuance::issuer::state_machine::IssuerState, proof_presentation::verifier::verification_status::PresentationVerificationStatus, }; use test_utils::devsetup::*; use crate::utils::{ scenarios::{ accept_credential_proposal, accept_offer, create_address_schema_creddef_revreg, create_credential_proposal, create_holder_from_proposal, create_issuer_from_proposal, credential_data_address_1, decline_offer, exchange_credential, exchange_credential_with_proposal, exchange_proof, send_credential, }, test_agent::{create_test_agent, create_test_agent_trustee}, }; pub mod utils; #[tokio::test] #[ignore] async fn test_agency_pool_double_issuance_issuer_is_verifier() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &institution.wallet, &institution.ledger_read, &institution.ledger_write, &institution.anoncreds, &institution.institution_did, ) .await; let _credential_handle = exchange_credential( &mut consumer, &mut institution, credential_data_address_1().to_string(), &cred_def, &rev_reg, None, ) .await; let verifier = exchange_proof( &mut institution, &mut consumer, &schema.schema_id, cred_def.get_cred_def_id(), Some("request1"), ) .await; assert_eq!( verifier.get_verification_status(), PresentationVerificationStatus::Valid ); let verifier = exchange_proof( &mut institution, &mut consumer, &schema.schema_id, cred_def.get_cred_def_id(), Some("request2"), ) .await; assert_eq!( verifier.get_verification_status(), PresentationVerificationStatus::Valid ); Ok(()) } #[tokio::test] #[ignore] #[allow(unused_mut)] async fn test_agency_pool_two_creds_one_rev_reg() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut issuer = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut verifier = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &issuer.wallet, &issuer.ledger_read, &issuer.ledger_write, &issuer.anoncreds, &issuer.institution_did, ) .await; let credential_data1 = credential_data_address_1().to_string(); let _credential_handle1 = exchange_credential( &mut consumer, &mut issuer, credential_data1.clone(), &cred_def, &rev_reg, Some("request1"), ) .await; let _credential_handle2 = exchange_credential( &mut consumer, &mut issuer, credential_data_address_1().to_string(), &cred_def, &rev_reg, Some("request2"), ) .await; let verifier_handler = exchange_proof( &mut verifier, &mut consumer, &schema.schema_id, cred_def.get_cred_def_id(), Some("request1"), ) .await; assert_eq!( verifier_handler.get_verification_status(), PresentationVerificationStatus::Valid ); let verifier_handler = exchange_proof( &mut verifier, &mut consumer, &schema.schema_id, cred_def.get_cred_def_id(), Some("request2"), ) .await; assert_eq!( verifier_handler.get_verification_status(), PresentationVerificationStatus::Valid ); Ok(()) } #[tokio::test] #[ignore] #[allow(unused_mut)] async fn test_agency_pool_credential_exchange_via_proposal() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &institution.wallet, &institution.ledger_read, &institution.ledger_write, &institution.anoncreds, &institution.institution_did, ) .await; exchange_credential_with_proposal( &mut consumer, &mut institution, &schema.schema_id, cred_def.get_cred_def_id(), Some(rev_reg.rev_reg_id.clone()), Some(rev_reg.get_tails_dir()), "comment", ) .await; Ok(()) } #[tokio::test] #[ignore] #[allow(unused_mut)] async fn test_agency_pool_credential_exchange_via_proposal_failed() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &institution.wallet, &institution.ledger_read, &institution.ledger_write, &institution.anoncreds, &institution.institution_did, ) .await; let cred_proposal = create_credential_proposal(&schema.schema_id, cred_def.get_cred_def_id(), "comment"); let mut holder = create_holder_from_proposal(cred_proposal.clone()); let mut issuer = create_issuer_from_proposal(cred_proposal.clone()); let cred_offer = accept_credential_proposal( &mut institution, &mut issuer, cred_proposal, Some(rev_reg.rev_reg_id.clone()), Some(rev_reg.get_tails_dir()), ) .await; let problem_report = decline_offer(&mut consumer, cred_offer, &mut holder).await; assert_eq!(IssuerState::OfferSet, issuer.get_state()); issuer.process_aries_msg(problem_report.into()).await?; assert_eq!(IssuerState::Failed, issuer.get_state()); Ok(()) } // TODO: Maybe duplicates test_agency_pool_credential_exchange_via_proposal #[tokio::test] #[ignore] #[allow(unused_mut)] async fn test_agency_pool_credential_exchange_via_proposal_with_negotiation( ) -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &institution.wallet, &institution.ledger_read, &institution.ledger_write, &institution.anoncreds, &institution.institution_did, ) .await; let cred_proposal = create_credential_proposal(&schema.schema_id, cred_def.get_cred_def_id(), "comment"); let mut holder = create_holder_from_proposal(cred_proposal.clone()); let mut issuer = create_issuer_from_proposal(cred_proposal.clone()); let cred_proposal_1 = create_credential_proposal(&schema.schema_id, cred_def.get_cred_def_id(), "comment"); let cred_offer_1 = accept_credential_proposal( &mut institution, &mut issuer, cred_proposal_1, Some(rev_reg.rev_reg_id.clone()), Some(rev_reg.get_tails_dir()), ) .await; let cred_request = accept_offer(&mut consumer, cred_offer_1, &mut holder).await; send_credential( &mut consumer, &mut institution, &mut issuer, &mut holder, cred_request, true, ) .await; Ok(()) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/test_proof_presentation.rs
aries/aries_vcx/tests/test_proof_presentation.rs
#![allow(clippy::diverging_sub_expression)] use std::error::Error; use anoncreds_types::data_types::messages::pres_request::PresentationRequest; use aries_vcx::{ handlers::proof_presentation::{prover::Prover, verifier::Verifier}, protocols::proof_presentation::{ prover::state_machine::ProverState, verifier::{ state_machine::VerifierState, verification_status::PresentationVerificationStatus, }, }, }; use messages::{ msg_fields::protocols::present_proof::{v1::PresentProofV1, PresentProof}, AriesMessage, }; use serde_json::json; use test_utils::{ constants::DEFAULT_SCHEMA_ATTRS, devsetup::{build_setup_profile, SetupPoolDirectory}, }; use crate::utils::{ create_and_publish_test_rev_reg, create_and_write_credential, create_and_write_test_cred_def, create_and_write_test_schema, scenarios::{ accept_proof_proposal, create_address_schema_creddef_revreg, create_proof_proposal, exchange_credential_with_proposal, generate_and_send_proof, prover_select_credentials, receive_proof_proposal_rejection, reject_proof_proposal, verify_proof, }, test_agent::{create_test_agent, create_test_agent_trustee}, }; pub mod utils; #[tokio::test] #[ignore] async fn test_agency_pool_generate_proof_with_predicates() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let schema = create_and_write_test_schema( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; let cred_def = create_and_write_test_cred_def( &setup.wallet, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, &schema.schema_id, true, ) .await; let rev_reg = create_and_publish_test_rev_reg( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, cred_def.get_cred_def_id(), ) .await; let _cred_id = create_and_write_credential( &setup.wallet, &setup.wallet, &setup.anoncreds, &setup.anoncreds, &setup.institution_did, &schema, &cred_def, Some(&rev_reg), ) .await; let to = time::OffsetDateTime::now_utc().unix_timestamp() as u64; let indy_proof_req = json!({ "nonce": "123432421212", "name": "proof_req_1", "version": "1.0", "requested_attributes": { "address1_1": { "name": "address1", "restrictions": [{"issuer_did": "abcdef0000000000000000"}, {"issuer_did": setup.institution_did}], "non_revoked": {"from": 123, "to": to} }, "state_2": { "name": "state", "restrictions": { "issuer_did": setup.institution_did, "schema_id": schema.schema_id, "cred_def_id": cred_def.get_cred_def_id(), } }, "zip_self_attested_3": { "name":"zip", } }, "requested_predicates": json!({ "zip_3": {"name":"zip", "p_type":">=", "p_value":18} }), "non_revoked": {"from": 98, "to": to} }) .to_string(); let pres_req_data: PresentationRequest = serde_json::from_str(&indy_proof_req)?; let mut verifier = Verifier::create_from_request("1".to_string(), &pres_req_data)?; let proof_req = verifier.get_presentation_request_msg()?; verifier.mark_presentation_request_sent()?; let mut proof: Prover = Prover::create_from_request("1", proof_req)?; let all_creds = proof .retrieve_credentials(&setup.wallet, &setup.anoncreds) .await?; let selected_credentials: serde_json::Value = json!({ "attrs":{ "address1_1": { "credential": all_creds.credentials_by_referent["address1_1"][0], "tails_dir": rev_reg.get_tails_dir() }, "state_2": { "credential": all_creds.credentials_by_referent["state_2"][0], "tails_dir": rev_reg.get_tails_dir() }, "zip_3": { "credential": all_creds.credentials_by_referent["zip_3"][0], "tails_dir": rev_reg.get_tails_dir() }, }, }); let self_attested: serde_json::Value = json!({ "zip_self_attested_3":"attested_val" }); proof .generate_presentation( &setup.wallet, &setup.ledger_read, &setup.anoncreds, serde_json::from_value(selected_credentials)?, serde_json::from_value(self_attested)?, ) .await?; assert!(matches!( proof.get_state(), ProverState::PresentationPrepared )); let final_message = verifier .verify_presentation( &setup.ledger_read, &setup.anoncreds, proof.get_presentation_msg()?, ) .await?; if let AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Ack(_))) = final_message { assert_eq!(verifier.get_state(), VerifierState::Finished); assert_eq!( verifier.get_verification_status(), PresentationVerificationStatus::Valid ); } else { panic!("Unexpected message type {final_message:?}"); } Ok(()) } #[tokio::test] #[ignore] #[allow(unused_mut)] async fn test_agency_pool_presentation_via_proposal() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let mut institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &institution.wallet, &institution.ledger_read, &institution.ledger_write, &institution.anoncreds, &institution.institution_did, ) .await; let tails_dir = rev_reg.get_tails_dir(); exchange_credential_with_proposal( &mut consumer, &mut institution, &schema.schema_id, cred_def.get_cred_def_id(), Some(rev_reg.rev_reg_id), Some(tails_dir), "comment", ) .await; let mut prover = Prover::create("1")?; let mut verifier = Verifier::create("1")?; let presentation_proposal = create_proof_proposal(&mut prover, cred_def.get_cred_def_id()).await; let presentation_request = accept_proof_proposal(&mut institution, &mut verifier, presentation_proposal).await; let selected_credentials = prover_select_credentials(&mut prover, &mut consumer, presentation_request, None).await; let presentation = generate_and_send_proof(&mut consumer, &mut prover, selected_credentials) .await .unwrap(); verify_proof(&mut institution, &mut verifier, presentation).await; Ok(()) } #[tokio::test] #[ignore] #[allow(unused_mut)] async fn test_agency_pool_presentation_via_proposal_with_rejection() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &institution.wallet, &institution.ledger_read, &institution.ledger_write, &institution.anoncreds, &institution.institution_did, ) .await; let tails_dir = rev_reg.get_tails_dir(); exchange_credential_with_proposal( &mut consumer, &mut institution, &schema.schema_id, cred_def.get_cred_def_id(), Some(rev_reg.rev_reg_id), Some(tails_dir), "comment", ) .await; let mut prover = Prover::create("1")?; let presentation_proposal = create_proof_proposal(&mut prover, cred_def.get_cred_def_id()).await; let rejection = reject_proof_proposal(&presentation_proposal).await; receive_proof_proposal_rejection(&mut prover, rejection).await; Ok(()) } #[tokio::test] #[ignore] #[allow(unused_mut)] async fn test_agency_pool_presentation_via_proposal_with_negotiation() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &institution.wallet, &institution.ledger_read, &institution.ledger_write, &institution.anoncreds, &institution.institution_did, ) .await; let tails_dir = rev_reg.get_tails_dir(); exchange_credential_with_proposal( &mut consumer, &mut institution, &schema.schema_id, cred_def.get_cred_def_id(), Some(rev_reg.rev_reg_id), Some(tails_dir), "comment", ) .await; let mut prover = Prover::create("1")?; let mut verifier = Verifier::create("1")?; let presentation_proposal = create_proof_proposal(&mut prover, &cred_def.get_cred_def_id().to_owned()).await; let presentation_request = accept_proof_proposal(&mut institution, &mut verifier, presentation_proposal).await; let selected_credentials = prover_select_credentials(&mut prover, &mut consumer, presentation_request, None).await; let presentation = generate_and_send_proof(&mut consumer, &mut prover, selected_credentials) .await .unwrap(); verify_proof(&mut institution, &mut verifier, presentation).await; Ok(()) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/test_credential_retrieval.rs
aries/aries_vcx/tests/test_credential_retrieval.rs
#![allow(clippy::diverging_sub_expression)] use std::{collections::HashMap, error::Error}; use anoncreds_types::data_types::messages::{ cred_selection::RetrievedCredentials, nonce::Nonce, pres_request::{AttributeInfo, PresentationRequest, PresentationRequestPayload}, }; use aries_vcx::handlers::{proof_presentation::prover::Prover, util::AttachmentId}; use base64::{engine::general_purpose, Engine}; use messages::{ decorators::attachment::{Attachment, AttachmentData, AttachmentType}, misc::MimeType, msg_fields::protocols::present_proof::v1::request::{ RequestPresentationV1, RequestPresentationV1Content, }, }; use serde_json::json; use test_utils::{constants::DEFAULT_SCHEMA_ATTRS, devsetup::build_setup_profile}; use crate::utils::{ create_and_write_credential, create_and_write_test_cred_def, create_and_write_test_schema, }; pub mod utils; #[tokio::test] #[ignore] // TODO: This should be a unit test async fn test_agency_pool_retrieve_credentials_empty() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let pres_req_data = PresentationRequestPayload::builder() .name("proof_req_1".into()) .nonce(Nonce::new().unwrap()) .build(); let attach_type = AttachmentType::Base64(general_purpose::STANDARD.encode(json!(pres_req_data).to_string())); let attach_data = AttachmentData::builder().content(attach_type).build(); let attach = Attachment::builder() .data(attach_data) .id(AttachmentId::PresentationRequest.as_ref().to_owned()) .mime_type(MimeType::Json) .build(); let content = RequestPresentationV1Content::builder() .request_presentations_attach(vec![attach]) .build(); // test retrieving credentials for empty proof request returns "{}" let id = "test_id".to_owned(); let proof_req = RequestPresentationV1::builder() .id(id) .content(content) .build(); let proof: Prover = Prover::create_from_request("1", proof_req)?; let retrieved_creds = proof .retrieve_credentials(&setup.wallet, &setup.anoncreds) .await?; assert_eq!(serde_json::to_string(&retrieved_creds)?, "{}".to_string()); assert!(retrieved_creds.credentials_by_referent.is_empty()); // populate proof request with a single attribute referent request let pres_req_data = PresentationRequestPayload::builder() .name("proof_req_1".into()) .requested_attributes( vec![( "address1_1".into(), AttributeInfo { name: Some("address1".into()), ..Default::default() }, )] .into_iter() .collect(), ) .nonce(Nonce::new().unwrap()) .build(); let attach_type = AttachmentType::Base64(general_purpose::STANDARD.encode(json!(pres_req_data).to_string())); let attach_data = AttachmentData::builder().content(attach_type).build(); let attach = Attachment::builder() .data(attach_data) .id(AttachmentId::PresentationRequest.as_ref().to_owned()) .mime_type(MimeType::Json) .build(); let content = RequestPresentationV1Content::builder() .request_presentations_attach(vec![attach]) .build(); // test retrieving credentials for the proof request returns the referent with no cred // matches let id = "test_id".to_owned(); let proof_req = RequestPresentationV1::builder() .id(id) .content(content) .build(); let proof: Prover = Prover::create_from_request("2", proof_req)?; let retrieved_creds = proof .retrieve_credentials(&setup.wallet, &setup.anoncreds) .await?; assert_eq!( serde_json::to_string(&retrieved_creds)?, json!({"attrs":{"address1_1":[]}}).to_string() ); assert_eq!( retrieved_creds, RetrievedCredentials { credentials_by_referent: HashMap::from([("address1_1".to_string(), vec![])]) } ); Ok(()) } #[tokio::test] #[ignore] // TODO: This should be a unit test async fn test_agency_pool_case_for_proof_req_doesnt_matter_for_retrieve_creds( ) -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let schema = create_and_write_test_schema( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; let cred_def = create_and_write_test_cred_def( &setup.wallet, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, &schema.schema_id, true, ) .await; create_and_write_credential( &setup.wallet, &setup.wallet, &setup.anoncreds, &setup.anoncreds, &setup.institution_did, &schema, &cred_def, None, ) .await; let mut req = json!({ "nonce":"123432421212", "name":"proof_req_1", "version":"1.0", "requested_attributes": json!({ "zip_1": json!({ "name":"zip", "restrictions": [json!({ "issuer_did": setup.institution_did })] }) }), "requested_predicates": json!({}), }); let pres_req_data: PresentationRequest = serde_json::from_str(&req.to_string())?; let id = "test_id".to_owned(); let attach_type = AttachmentType::Base64(general_purpose::STANDARD.encode(json!(pres_req_data).to_string())); let attach_data = AttachmentData::builder().content(attach_type).build(); let attach = Attachment::builder() .data(attach_data) .id(AttachmentId::PresentationRequest.as_ref().to_owned()) .mime_type(MimeType::Json) .build(); let content = RequestPresentationV1Content::builder() .request_presentations_attach(vec![attach]) .build(); let proof_req = RequestPresentationV1::builder() .id(id) .content(content) .build(); let proof: Prover = Prover::create_from_request("1", proof_req)?; // All lower case let retrieved_creds = proof .retrieve_credentials(&setup.wallet, &setup.anoncreds) .await?; assert_eq!( retrieved_creds.credentials_by_referent["zip_1"][0] .cred_info .attributes["zip"], "84000" ); // First letter upper req["requested_attributes"]["zip_1"]["name"] = json!("Zip"); let pres_req_data: PresentationRequest = serde_json::from_str(&req.to_string())?; let id = "test_id".to_owned(); let attach_type = AttachmentType::Base64(general_purpose::STANDARD.encode(json!(pres_req_data).to_string())); let attach_data = AttachmentData::builder().content(attach_type).build(); let attach = Attachment::builder() .data(attach_data) .id(AttachmentId::PresentationRequest.as_ref().to_owned()) .mime_type(MimeType::Json) .build(); let content = RequestPresentationV1Content::builder() .request_presentations_attach(vec![attach]) .build(); let proof_req = RequestPresentationV1::builder() .id(id) .content(content) .build(); let proof: Prover = Prover::create_from_request("2", proof_req)?; let retrieved_creds2 = proof .retrieve_credentials(&setup.wallet, &setup.anoncreds) .await?; assert_eq!( retrieved_creds2.credentials_by_referent["zip_1"][0] .cred_info .attributes["zip"], "84000" ); // Entire word upper req["requested_attributes"]["zip_1"]["name"] = json!("ZIP"); let pres_req_data: PresentationRequest = serde_json::from_str(&req.to_string())?; let id = "test_id".to_owned(); let attach_type = AttachmentType::Base64(general_purpose::STANDARD.encode(json!(pres_req_data).to_string())); let attach_data = AttachmentData::builder().content(attach_type).build(); let attach = Attachment::builder() .data(attach_data) .id(AttachmentId::PresentationRequest.as_ref().to_owned()) .mime_type(MimeType::Json) .build(); let content = RequestPresentationV1Content::builder() .request_presentations_attach(vec![attach]) .build(); let proof_req = RequestPresentationV1::builder() .id(id) .content(content) .build(); let proof: Prover = Prover::create_from_request("1", proof_req)?; let retrieved_creds3 = proof .retrieve_credentials(&setup.wallet, &setup.anoncreds) .await?; assert_eq!( retrieved_creds3.credentials_by_referent["zip_1"][0] .cred_info .attributes["zip"], "84000" ); Ok(()) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/test_connection.rs
aries/aries_vcx/tests/test_connection.rs
use std::error::Error; use aries_vcx::{ common::ledger::transactions::write_endpoint_legacy, protocols::{connection::GenericConnection, mediated_connection::pairwise_info::PairwiseInfo}, utils::encryption_envelope::EncryptionEnvelope, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::{ AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite, }; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use chrono::Utc; use diddoc_legacy::aries::service::AriesService; use messages::{ decorators::timing::Timing, msg_fields::protocols::basic_message::{ BasicMessage, BasicMessageContent, BasicMessageDecorators, }, AriesMessage, }; use test_utils::devsetup::*; use utils::test_agent::TestAgent; use uuid::Uuid; use crate::utils::{ scenarios::{ create_connections_via_oob_invite, create_connections_via_pairwise_invite, create_connections_via_public_invite, }, test_agent::{create_test_agent, create_test_agent_endorser, create_test_agent_trustee}, }; pub mod utils; fn build_basic_message(content: String) -> BasicMessage { let now = Utc::now(); let content = BasicMessageContent::builder() .content(content) .sent_time(now) .build(); let decorators = BasicMessageDecorators::builder() .timing(Timing::builder().out_time(now).build()) .build(); BasicMessage::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build() } async fn decrypt_message( consumer: &TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, received: Vec<u8>, ) -> AriesMessage { let (message, _, _) = EncryptionEnvelope::unpack_aries_msg(&consumer.wallet, received.as_slice(), &None) .await .unwrap(); message } async fn send_and_receive_message( consumer: &TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, insitution: &TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, institution_to_consumer: &GenericConnection, message: &AriesMessage, ) -> AriesMessage { let encrypted_message = institution_to_consumer .encrypt_message(&insitution.wallet, message) .await .unwrap() .0; decrypt_message(consumer, encrypted_message).await } async fn create_service( faber: &TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, ) { let pairwise_info = PairwiseInfo::create(&faber.wallet).await.unwrap(); let service = AriesService::create() .set_service_endpoint("http://dummy.org".parse().unwrap()) .set_recipient_keys(vec![pairwise_info.pw_vk.clone()]); write_endpoint_legacy( &faber.wallet, &faber.ledger_write, &faber.institution_did, &service, ) .await .unwrap(); } #[tokio::test] #[ignore] async fn test_agency_pool_establish_connection_via_public_invite() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; create_service(&institution).await; let (_consumer_to_institution, institution_to_consumer) = create_connections_via_public_invite(&mut consumer, &mut institution).await; let basic_message = build_basic_message("Hello TestAgent".to_string()); if let AriesMessage::BasicMessage(message) = send_and_receive_message( &consumer, &institution, &institution_to_consumer, &basic_message.clone().into(), ) .await { assert_eq!(message.content.content, basic_message.content.content); } else { panic!("Unexpected message type"); } Ok(()) } #[tokio::test] #[ignore] async fn test_agency_pool_establish_connection_via_pairwise_invite() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut institution = create_test_agent(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; let (_consumer_to_institution, institution_to_consumer) = create_connections_via_pairwise_invite(&mut consumer, &mut institution).await; let basic_message = build_basic_message("Hello TestAgent".to_string()); if let AriesMessage::BasicMessage(message) = send_and_receive_message( &consumer, &institution, &institution_to_consumer, &basic_message.clone().into(), ) .await { assert_eq!(message.content.content, basic_message.content.content); } else { panic!("Unexpected message type"); } Ok(()) } #[tokio::test] #[ignore] async fn test_agency_pool_establish_connection_via_out_of_band() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut endorser = create_test_agent_endorser( institution.ledger_write, institution.wallet, &setup.genesis_file_path, &institution.institution_did, ) .await?; let mut consumer = create_test_agent(setup.genesis_file_path).await; create_service(&endorser).await; let (_consumer_to_endorser, endorser_to_consumer) = create_connections_via_oob_invite(&mut consumer, &mut endorser).await; let basic_message = build_basic_message("Hello TestAgent".to_string()); if let AriesMessage::BasicMessage(message) = send_and_receive_message( &consumer, &endorser, &endorser_to_consumer, &basic_message.clone().into(), ) .await { assert_eq!(message.content.content, basic_message.content.content); } else { panic!("Unexpected message type"); } Ok(()) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/test_did_exchange.rs
aries/aries_vcx/tests/test_did_exchange.rs
extern crate log; use std::{error::Error, sync::Arc, thread, time::Duration}; use aries_vcx::{ common::ledger::transactions::write_endpoint_from_service, errors::error::AriesVcxErrorKind, protocols::did_exchange::{ resolve_enc_key_from_invitation, state_machine::{ helpers::create_peer_did_4, requester::{helpers::invitation_get_first_did_service, DidExchangeRequester}, responder::DidExchangeResponder, }, states::{requester::request_sent::RequestSent, responder::response_sent::ResponseSent}, transition::transition_result::TransitionResult, }, utils::{ didcomm_utils::resolve_ed25519_key_agreement, encryption_envelope::EncryptionEnvelope, }, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::{ base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite}, indy_vdr_ledger::DefaultIndyLedgerRead, }; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use did_doc::schema::{ did_doc::DidDocument, service::typed::{didcommv1::ServiceDidCommV1, ServiceType}, types::uri::Uri, }; use did_parser_nom::Did; use did_peer::resolver::PeerDidResolver; use did_resolver_registry::ResolverRegistry; use did_resolver_sov::resolution::DidSovResolver; use log::info; use messages::{ msg_fields::protocols::out_of_band::invitation::{Invitation, InvitationContent, OobService}, msg_types::protocols::did_exchange::DidExchangeTypeV1, }; use pretty_assertions::assert_eq; use test_utils::devsetup::{dev_build_profile_vdr_ledger, SetupPoolDirectory}; use url::Url; use utils::test_agent::TestAgent; use crate::utils::test_agent::{ create_test_agent, create_test_agent_endorser_2, create_test_agent_trustee, }; pub mod utils; fn assert_key_agreement(a: DidDocument, b: DidDocument) { log::warn!("comparing did doc a: {a}, b: {b}"); let a_key = resolve_ed25519_key_agreement(&a).unwrap(); let b_key = resolve_ed25519_key_agreement(&b).unwrap(); assert_eq!(a_key, b_key); } async fn did_exchange_test( inviter_did: String, agent_inviter: TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, agent_invitee: TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, resolver_registry: Arc<ResolverRegistry>, ) -> Result<(), Box<dyn Error>> { let dummy_url: Url = "http://dummyurl.org".parse().unwrap(); let invitation = Invitation::builder() .id("test_invite_id".to_owned()) .content( InvitationContent::builder() .services(vec![OobService::Did(inviter_did)]) .build(), ) .build(); let invitation_key = resolve_enc_key_from_invitation(&invitation, &resolver_registry) .await .unwrap(); info!("Inviter prepares invitation and passes to invitee {invitation}"); let (requesters_peer_did, _our_verkey) = create_peer_did_4(&agent_invitee.wallet, dummy_url.clone(), vec![]).await?; let did_inviter: Did = invitation_get_first_did_service(&invitation)?; info!( "Invitee resolves Inviter's DID from invitation {did_inviter} (as a first DID service found in the \ invitation)" ); let TransitionResult { state: requester, output: request, } = DidExchangeRequester::<RequestSent>::construct_request( &resolver_registry, Some(invitation.id), &did_inviter, &requesters_peer_did, "some-label".to_owned(), DidExchangeTypeV1::new_v1_1(), ) .await .unwrap(); info!( "Invitee processes invitation, builds up request {:?}", &request ); let (responders_peer_did, _our_verkey) = create_peer_did_4(&agent_inviter.wallet, dummy_url.clone(), vec![]).await?; let responders_did_document = responders_peer_did.resolve_did_doc()?; info!("Responder prepares did document: {responders_did_document}"); let check_diddoc = responders_peer_did.resolve_did_doc()?; info!("Responder decodes constructed peer:did as did document: {check_diddoc}"); let TransitionResult { output: response, state: responder, } = DidExchangeResponder::<ResponseSent>::receive_request( &agent_inviter.wallet, &resolver_registry, request, &responders_peer_did, invitation_key.clone(), ) .await .unwrap(); let TransitionResult { state: requester, output: complete, } = requester .receive_response( &agent_invitee.wallet, &invitation_key, response, &resolver_registry, ) .await .unwrap(); let responder = responder.receive_complete(complete.into_inner()).unwrap(); info!("Asserting did document of requester"); assert_key_agreement( requester.our_did_doc().clone(), responder.their_did_doc().clone(), ); info!("Asserting did document of responder"); assert_key_agreement( responder.our_did_doc().clone(), requester.their_did_doc().clone(), ); info!( "Requesters did document (requesters view): {}", requester.our_did_doc() ); info!( "Responders did document (requesters view): {}", requester.their_did_doc() ); let data = "Hello world"; let service = requester .their_did_doc() .get_service_of_type(&ServiceType::DIDCommV1)?; let m = EncryptionEnvelope::create( &agent_invitee.wallet, data.as_bytes(), requester.our_did_doc(), requester.their_did_doc(), service.id(), ) .await?; info!("Encrypted message: {m:?}"); let requesters_peer_did = requesters_peer_did.resolve_did_doc()?; let expected_sender_vk = resolve_ed25519_key_agreement(&requesters_peer_did)?; let unpacked = EncryptionEnvelope::unpack(&agent_inviter.wallet, &m.0, &Some(expected_sender_vk)).await?; info!("Unpacked message: {unpacked:?}"); Ok(()) } #[tokio::test] #[ignore] async fn did_exchange_test_sov_inviter() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let dummy_url: Url = "http://dummyurl.org".parse().unwrap(); let agent_trustee = create_test_agent_trustee(setup.genesis_file_path.clone()).await; // todo: patrik: update create_test_agent_endorser_2 to not consume trustee agent let agent_inviter = create_test_agent_endorser_2(&setup.genesis_file_path, agent_trustee).await?; let create_service = ServiceDidCommV1::new( Uri::new("#service-0").unwrap(), dummy_url.clone(), 0, vec![], vec![], ); write_endpoint_from_service( &agent_inviter.wallet, &agent_inviter.ledger_write, &agent_inviter.institution_did, &create_service.try_into()?, ) .await?; thread::sleep(Duration::from_millis(100)); let agent_invitee = create_test_agent(setup.genesis_file_path.clone()).await; let (ledger_read_2, _) = dev_build_profile_vdr_ledger(setup.genesis_file_path); let ledger_read_2_arc = Arc::new(ledger_read_2); // if we were to use, more generally, the `dev_build_featured_indy_ledger`, we would need to // here the type based on the feature flag (indy vs proxy vdr client) which is pain // we need to improve DidSovResolver such that Rust compiler can fully infer the return type let did_sov_resolver: DidSovResolver<Arc<DefaultIndyLedgerRead>, DefaultIndyLedgerRead> = DidSovResolver::new(ledger_read_2_arc); let resolver_registry = Arc::new( ResolverRegistry::new() .register_resolver::<PeerDidResolver>("peer".into(), PeerDidResolver::new()) .register_resolver("sov".into(), did_sov_resolver), ); did_exchange_test( format!("did:sov:{}", agent_inviter.institution_did), agent_inviter, agent_invitee, resolver_registry, ) .await } #[tokio::test] #[ignore] async fn did_exchange_test_peer_to_peer() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let dummy_url: Url = "http://dummyurl.org".parse().unwrap(); let agent_inviter = create_test_agent(setup.genesis_file_path.clone()).await; let agent_invitee = create_test_agent(setup.genesis_file_path.clone()).await; let resolver_registry = Arc::new( ResolverRegistry::new() .register_resolver::<PeerDidResolver>("peer".into(), PeerDidResolver::new()), ); let (inviter_peer_did, _) = create_peer_did_4(&agent_inviter.wallet, dummy_url.clone(), vec![]).await?; did_exchange_test( inviter_peer_did.to_string(), agent_inviter, agent_invitee, resolver_registry, ) .await } #[tokio::test] #[ignore] async fn did_exchange_test_with_invalid_rotation_signature() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let dummy_url: Url = "http://dummyurl.org".parse().unwrap(); let agent_inviter = create_test_agent(setup.genesis_file_path.clone()).await; let agent_invitee = create_test_agent(setup.genesis_file_path.clone()).await; let resolver_registry = Arc::new( ResolverRegistry::new() .register_resolver::<PeerDidResolver>("peer".into(), PeerDidResolver::new()), ); let (inviter_peer_did, _) = create_peer_did_4(&agent_inviter.wallet, dummy_url.clone(), vec![]).await?; let dummy_url: Url = "http://dummyurl.org".parse().unwrap(); let invitation = Invitation::builder() .id("test_invite_id".to_owned()) .content( InvitationContent::builder() .services(vec![OobService::Did(inviter_peer_did.to_string())]) .build(), ) .build(); let real_invitation_key = resolve_enc_key_from_invitation(&invitation, &resolver_registry).await?; let (requesters_peer_did, _our_verkey) = create_peer_did_4(&agent_invitee.wallet, dummy_url.clone(), vec![]).await?; let did_inviter: Did = invitation_get_first_did_service(&invitation)?; let TransitionResult { state: requester, output: request, } = DidExchangeRequester::<RequestSent>::construct_request( &resolver_registry, Some(invitation.id), &did_inviter, &requesters_peer_did, "some-label".to_owned(), DidExchangeTypeV1::new_v1_1(), ) .await?; let (responders_peer_did, incorrect_invitation_key) = create_peer_did_4(&agent_inviter.wallet, dummy_url.clone(), vec![]).await?; // create a response with a DID Rotate signed by the wrong key (not the original invitation key) let TransitionResult { output: response, state: _, } = DidExchangeResponder::<ResponseSent>::receive_request( &agent_inviter.wallet, &resolver_registry, request, &responders_peer_did, // sign with NOT the invitation key incorrect_invitation_key, ) .await?; // receiving the response should fail when verifying the signature let res = requester .receive_response( &agent_invitee.wallet, &real_invitation_key, response, &resolver_registry, ) .await; assert_eq!( res.unwrap_err().error.kind(), AriesVcxErrorKind::InvalidInput ); Ok(()) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/test_anoncreds.rs
aries/aries_vcx/tests/test_anoncreds.rs
use std::error::Error; use aries_vcx::common::credentials::get_cred_rev_id; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use serde_json::json; use test_utils::{constants::DEFAULT_SCHEMA_ATTRS, devsetup::build_setup_profile}; use crate::utils::{ create_and_publish_test_rev_reg, create_and_write_credential, create_and_write_test_cred_def, create_and_write_test_schema, }; pub mod utils; #[tokio::test] #[ignore] async fn test_pool_prover_get_credentials() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let proof_req = json!({ "nonce":"123432421212", "name":"proof_req_1", "version":"1.0", "requested_attributes": json!({ "address1_1": json!({ "name":"address1", }), "zip_2": json!({ "name":"zip", }), }), "requested_predicates": json!({}), }) .to_string(); let anoncreds = setup.anoncreds; let _result = anoncreds .prover_get_credentials_for_proof_req(&setup.wallet, serde_json::from_str(&proof_req)?) .await?; Ok(()) } #[tokio::test] #[ignore] async fn test_pool_proof_req_attribute_names() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let proof_req = json!({ "nonce":"123432421212", "name":"proof_req_1", "version":"1.0", "requested_attributes": json!({ "multiple_attrs": { "names": ["name_1", "name_2"] }, "address1_1": json!({ "name":"address1", "restrictions": [json!({ "issuer_did": "some_did" })] }), "self_attest_3": json!({ "name":"self_attest", }), }), "requested_predicates": json!({ "zip_3": {"name":"zip", "p_type":">=", "p_value":18} }), }) .to_string(); let anoncreds = setup.anoncreds; anoncreds .prover_get_credentials_for_proof_req(&setup.wallet, serde_json::from_str(&proof_req)?) .await?; Ok(()) } #[allow(deprecated)] // TODO - https://github.com/openwallet-foundation/vcx/issues/1309 #[tokio::test] #[ignore] async fn test_pool_revoke_credential() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let schema = create_and_write_test_schema( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; let cred_def = create_and_write_test_cred_def( &setup.wallet, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, &schema.schema_id, true, ) .await; let rev_reg = create_and_publish_test_rev_reg( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, cred_def.get_cred_def_id(), ) .await; let cred_id = create_and_write_credential( &setup.wallet, &setup.wallet, &setup.anoncreds, &setup.anoncreds, &setup.institution_did, &schema, &cred_def, Some(&rev_reg), ) .await; let cred_rev_id = get_cred_rev_id(&setup.wallet, &setup.anoncreds, &cred_id).await?; let ledger = &setup.ledger_read; let (first_rev_reg_delta, first_timestamp) = ledger .get_rev_reg_delta_json(&rev_reg.rev_reg_id.to_owned().try_into()?, None, None) .await?; let (test_same_delta, test_same_timestamp) = ledger .get_rev_reg_delta_json(&rev_reg.rev_reg_id.to_owned().try_into()?, None, None) .await?; assert_eq!(first_rev_reg_delta, test_same_delta); assert_eq!(first_timestamp, test_same_timestamp); let anoncreds = &setup.anoncreds; let rev_reg_delta_json = setup .ledger_read .get_rev_reg_delta_json(&rev_reg.rev_reg_id.to_owned().try_into()?, None, None) .await? .0; anoncreds .revoke_credential_local( &setup.wallet, &rev_reg.rev_reg_id.to_owned().try_into()?, cred_rev_id, rev_reg_delta_json, ) .await?; rev_reg .publish_local_revocations( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, ) .await?; // Delta should change after revocation let (second_rev_reg_delta, _) = ledger .get_rev_reg_delta_json( &rev_reg.rev_reg_id.try_into()?, Some(first_timestamp + 1), None, ) .await?; assert_ne!(first_rev_reg_delta, second_rev_reg_delta); Ok(()) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/test_pool.rs
aries/aries_vcx/tests/test_pool.rs
#![allow(clippy::diverging_sub_expression)] use std::{error::Error, thread, time::Duration}; use anoncreds_types::data_types::identifiers::cred_def_id::CredentialDefinitionId; use aries_vcx::{ common::{ keys::{get_verkey_from_ledger, rotate_verkey}, ledger::{ service_didsov::EndpointDidSov, transactions::{ add_attr, add_new_did, clear_attr, get_attr, get_service, write_endorser_did, write_endpoint, write_endpoint_legacy, }, }, primitives::{ credential_definition::CredentialDef, credential_schema::Schema, revocation_registry::{generate_rev_reg, RevocationRegistry}, }, }, errors::error::AriesVcxErrorKind, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::{ base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerWrite}, indy::pool::test_utils::get_temp_file_path, }; use aries_vcx_wallet::wallet::base_wallet::{did_wallet::DidWallet, BaseWallet}; use did_parser_nom::Did; use diddoc_legacy::aries::service::AriesService; use serde_json::json; use test_utils::{ constants::{DEFAULT_SCHEMA_ATTRS, TEST_TAILS_URL}, devsetup::{build_setup_profile, SetupPoolDirectory}, }; use crate::utils::{ create_and_publish_test_rev_reg, create_and_write_test_cred_def, create_and_write_test_schema, scenarios::attr_names_address_list, test_agent::{create_test_agent, create_test_agent_endorser, create_test_agent_trustee}, }; pub mod utils; // TODO: Deduplicate with create_and_store_revocable_credential_def async fn create_and_store_nonrevocable_credential_def( wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger_read: &impl AnoncredsLedgerRead, ledger_write: &impl AnoncredsLedgerWrite, issuer_did: &Did, attr_list: &str, ) -> Result< ( String, String, CredentialDefinitionId, String, CredentialDef, ), Box<dyn Error>, > { let schema = create_and_write_test_schema(wallet, anoncreds, ledger_write, issuer_did, attr_list).await; let cred_def = create_and_write_test_cred_def( wallet, anoncreds, ledger_read, ledger_write, issuer_did, &schema.schema_id, false, ) .await; tokio::time::sleep(Duration::from_millis(1000)).await; let cred_def_id = cred_def.get_cred_def_id(); let cred_def_json = ledger_read .get_cred_def(&cred_def_id.to_owned(), None) .await?; Ok(( schema.schema_id.to_string(), serde_json::to_string(&schema.schema_json)?, cred_def_id.to_owned(), serde_json::to_string(&cred_def_json)?, cred_def, )) } // TODO: Deduplicate with create_and_store_nonrevocable_credential_def async fn create_and_store_revocable_credential_def( wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger_read: &impl AnoncredsLedgerRead, ledger_write: &impl AnoncredsLedgerWrite, issuer_did: &Did, attr_list: &str, ) -> Result<(Schema, CredentialDef, RevocationRegistry), Box<dyn Error>> { let schema = create_and_write_test_schema(wallet, anoncreds, ledger_write, issuer_did, attr_list).await; let cred_def = create_and_write_test_cred_def( wallet, anoncreds, ledger_read, ledger_write, issuer_did, &schema.schema_id, true, ) .await; let rev_reg = create_and_publish_test_rev_reg( wallet, anoncreds, ledger_write, issuer_did, cred_def.get_cred_def_id(), ) .await; tokio::time::sleep(Duration::from_millis(1000)).await; Ok((schema, cred_def, rev_reg)) } #[tokio::test] #[ignore] async fn test_pool_rotate_verkey() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let (did, verkey) = add_new_did( &setup.wallet, &setup.ledger_write, &setup.institution_did, None, ) .await?; rotate_verkey(&setup.wallet, &setup.ledger_write, &did).await?; tokio::time::sleep(Duration::from_millis(1000)).await; let local_verkey = setup.wallet.key_for_did(&did.to_string()).await?; let ledger_verkey = get_verkey_from_ledger(&setup.ledger_read, &did).await?; assert_ne!(verkey, ledger_verkey); assert_eq!(local_verkey.base58(), ledger_verkey); Ok(()) } #[tokio::test] #[ignore] async fn test_pool_add_get_service() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let endorser = create_test_agent_endorser( setup.ledger_write, setup.wallet, &setup.genesis_file_path, &setup.institution_did, ) .await?; let expect_service = AriesService::default(); write_endpoint_legacy( &endorser.wallet, &endorser.ledger_write, &endorser.institution_did, &expect_service, ) .await?; thread::sleep(Duration::from_millis(50)); let service = get_service(&endorser.ledger_read, &endorser.institution_did).await?; assert_eq!(expect_service, service); // clean up written legacy service clear_attr( &endorser.wallet, &endorser.ledger_write, &endorser.institution_did, "service", ) .await?; Ok(()) } #[tokio::test] #[ignore] async fn test_pool_write_new_endorser_did() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let faber = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let acme = create_test_agent(setup.genesis_file_path.clone()).await; let acme_vk = acme .wallet .key_for_did(&acme.institution_did.to_string()) .await?; let attrib_json = json!({ "attrib_name": "foo"}).to_string(); assert!(add_attr( &acme.wallet, &acme.ledger_write, &acme.institution_did, &attrib_json, ) .await .is_err()); write_endorser_did( &faber.wallet, &faber.ledger_write, &faber.institution_did, &acme.institution_did, &acme_vk.base58(), None, ) .await?; thread::sleep(Duration::from_millis(50)); add_attr( &acme.wallet, &acme.ledger_write, &acme.institution_did, &attrib_json, ) .await?; Ok(()) } #[tokio::test] #[ignore] async fn test_pool_add_get_service_public() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let endorser = create_test_agent_endorser( setup.ledger_write, setup.wallet, &setup.genesis_file_path, &setup.institution_did, ) .await?; let create_service = EndpointDidSov::create() .set_service_endpoint("https://example.org".parse()?) .set_routing_keys(Some(vec!["did:sov:456".into()])); write_endpoint( &endorser.wallet, &endorser.ledger_write, &endorser.institution_did, &create_service, ) .await?; thread::sleep(Duration::from_millis(50)); let service = get_service(&endorser.ledger_read, &endorser.institution_did).await?; let expect_recipient_key = get_verkey_from_ledger(&endorser.ledger_read, &endorser.institution_did).await?; let expect_service = AriesService::default() .set_service_endpoint("https://example.org".parse()?) .set_recipient_keys(vec![expect_recipient_key]) .set_routing_keys(vec!["did:sov:456".into()]); assert_eq!(expect_service, service); // clean up written endpoint clear_attr( &endorser.wallet, &endorser.ledger_write, &endorser.institution_did, "endpoint", ) .await?; Ok(()) } #[tokio::test] #[ignore] async fn test_pool_add_get_service_public_none_routing_keys() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let did = setup.institution_did.clone(); let create_service = EndpointDidSov::create() .set_service_endpoint("https://example.org".parse()?) .set_routing_keys(None); write_endpoint(&setup.wallet, &setup.ledger_write, &did, &create_service).await?; thread::sleep(Duration::from_millis(50)); let service = get_service(&setup.ledger_read, &did).await?; let expect_recipient_key = get_verkey_from_ledger(&setup.ledger_read, &setup.institution_did).await?; let expect_service = AriesService::default() .set_service_endpoint("https://example.org".parse()?) .set_recipient_keys(vec![expect_recipient_key]) .set_routing_keys(vec![]); assert_eq!(expect_service, service); // clean up written endpoint clear_attr( &setup.wallet, &setup.ledger_write, &setup.institution_did, "endpoint", ) .await?; Ok(()) } #[tokio::test] #[ignore] async fn test_pool_multiple_service_formats() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let did = setup.institution_did.clone(); // clear all let c = json!({ "service": serde_json::Value::Null }).to_string(); setup.ledger_write.add_attr(&setup.wallet, &did, &c).await?; let c = json!({ "endpoint": serde_json::Value::Null }).to_string(); setup.ledger_write.add_attr(&setup.wallet, &did, &c).await?; // Write legacy service format let service_1 = AriesService::create() .set_service_endpoint("https://example1.org".parse()?) .set_recipient_keys(vec!["did:sov:123".into()]) .set_routing_keys(vec!["did:sov:456".into()]); write_endpoint_legacy(&setup.wallet, &setup.ledger_write, &did, &service_1).await?; thread::sleep(Duration::from_millis(50)); // Get service and verify it is in the old format let service = get_service(&setup.ledger_read, &did).await?; assert_eq!(service_1, service); // Write new service format let endpoint_url_2 = "https://example2.org"; let routing_keys_2 = vec![]; let service_2 = EndpointDidSov::create() .set_service_endpoint(endpoint_url_2.parse()?) .set_routing_keys(Some(routing_keys_2.clone())); write_endpoint(&setup.wallet, &setup.ledger_write, &did, &service_2).await?; thread::sleep(Duration::from_millis(50)); // Get service and verify it is in the new format let service = get_service(&setup.ledger_read, &did).await?; let expect_recipient_key = get_verkey_from_ledger(&setup.ledger_read, &setup.institution_did).await?; let expect_service = AriesService::default() .set_service_endpoint(endpoint_url_2.parse()?) .set_recipient_keys(vec![expect_recipient_key]) .set_routing_keys(routing_keys_2); assert_eq!(expect_service, service); // Clear up written endpoint clear_attr( &setup.wallet, &setup.ledger_write, &setup.institution_did, "endpoint", ) .await?; thread::sleep(Duration::from_millis(50)); // Get service and verify it is in the old format let service = get_service(&setup.ledger_read, &did).await?; assert_eq!(service_1, service); Ok(()) } #[tokio::test] #[ignore] async fn test_pool_add_get_attr() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let did = setup.institution_did.clone(); let attr_json = json!({ "attr_json": { "attr_key_1": "attr_value_1", "attr_key_2": "attr_value_2", } }); add_attr( &setup.wallet, &setup.ledger_write, &did, &attr_json.to_string(), ) .await?; thread::sleep(Duration::from_millis(50)); let attr = get_attr(&setup.ledger_read, &did, "attr_json").await?; assert_eq!(attr, attr_json["attr_json"].to_string()); clear_attr(&setup.wallet, &setup.ledger_write, &did, "attr_json").await?; thread::sleep(Duration::from_millis(50)); let attr = get_attr(&setup.ledger_read, &did, "attr_json").await?; assert_eq!(attr, ""); let attr = get_attr(&setup.ledger_read, &did, "nonexistent").await?; assert_eq!(attr, ""); Ok(()) } #[tokio::test] #[ignore] async fn test_agency_pool_get_credential_def() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let (_, _, cred_def_id, cred_def_json, _) = create_and_store_nonrevocable_credential_def( &setup.wallet, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await?; let ledger = &setup.ledger_read; let r_cred_def_json = ledger.get_cred_def(&cred_def_id, None).await?; let def1: serde_json::Value = serde_json::from_str(&cred_def_json)?; let def2 = serde_json::to_value(&r_cred_def_json)?; assert_eq!(def1, def2); Ok(()) } #[tokio::test] #[ignore] async fn test_pool_rev_reg_def_fails_for_cred_def_created_without_revocation( ) -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; // Cred def is created with support_revocation=false, // revoc_reg_def will fail in libindy because cred_Def doesn't have revocation keys let (_, _, cred_def_id, _, _) = create_and_store_nonrevocable_credential_def( &setup.wallet, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await?; let rc = generate_rev_reg( &setup.wallet, &setup.anoncreds, &setup.institution_did, &cred_def_id, get_temp_file_path("path.txt").to_str().unwrap(), 2, "tag1", ) .await; assert_eq!(rc.unwrap_err().kind(), AriesVcxErrorKind::InvalidState); Ok(()) } #[tokio::test] #[ignore] async fn test_pool_get_rev_reg_def_json() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let attrs = format!("{:?}", attr_names_address_list()); let (_, _, rev_reg) = create_and_store_revocable_credential_def( &setup.wallet, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, &attrs, ) .await?; let ledger = &setup.ledger_read; let _json = ledger .get_rev_reg_def_json(&rev_reg.rev_reg_id.try_into()?) .await?; Ok(()) } #[tokio::test] #[ignore] async fn test_pool_get_rev_reg_delta_json() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let attrs = format!("{:?}", attr_names_address_list()); let (_, _, rev_reg) = create_and_store_revocable_credential_def( &setup.wallet, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, &attrs, ) .await?; let ledger = &setup.ledger_read; #[allow(deprecated)] // TODO - https://github.com/openwallet-foundation/vcx/issues/1309 let (_delta, _timestamp) = ledger .get_rev_reg_delta_json(&rev_reg.rev_reg_id.to_owned().try_into()?, None, None) .await?; Ok(()) } #[tokio::test] #[ignore] async fn test_pool_get_rev_reg() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let attrs = format!("{:?}", attr_names_address_list()); let (_, _, rev_reg) = create_and_store_revocable_credential_def( &setup.wallet, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, &attrs, ) .await?; assert_eq!( TEST_TAILS_URL, rev_reg.get_rev_reg_def().value.tails_location ); let ledger = &setup.ledger_read; let (_rev_reg, _timestamp) = ledger .get_rev_reg( &rev_reg.rev_reg_id.to_owned().try_into()?, time::OffsetDateTime::now_utc().unix_timestamp() as u64, ) .await?; Ok(()) } #[tokio::test] #[ignore] async fn test_pool_create_and_get_schema() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let schema = create_and_write_test_schema( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; let ledger = &setup.ledger_read; let retrieved_schema = serde_json::to_string(&ledger.get_schema(&schema.schema_id, None).await?).unwrap(); assert!(retrieved_schema.contains(&schema.schema_id.to_string())); Ok(()) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/test_verifier.rs
aries/aries_vcx/tests/test_verifier.rs
use std::{error::Error, time::Duration}; use anoncreds_types::{ data_types::messages::{ nonce::Nonce, pres_request::{AttributeInfo, PresentationRequest, PresentationRequestPayload}, presentation::{ Presentation, RequestedAttribute, RequestedCredentials, RequestedPredicate, }, }, utils::query::Query, }; use aries_vcx::{ common::{ primitives::{ credential_definition::CredentialDef, credential_schema::Schema as SchemaPrimitive, }, proofs::verifier::validate_indy_proof, }, errors::error::AriesVcxErrorKind, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::{ BaseAnonCreds, CredentialDefinitionsMap, SchemasMap, }; use aries_vcx_ledger::ledger::base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite}; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use did_parser_nom::Did; use serde_json::json; use test_utils::{constants::DEFAULT_SCHEMA_ATTRS, devsetup::build_setup_profile}; use crate::utils::{ create_and_write_credential, create_and_write_test_cred_def, create_and_write_test_schema, }; pub mod utils; // FUTURE - issuer and holder seperation only needed whilst modular deps not fully implemented async fn create_indy_proof( wallet_issuer: &impl BaseWallet, wallet_holder: &impl BaseWallet, anoncreds_issuer: &impl BaseAnonCreds, anoncreds_holder: &impl BaseAnonCreds, ledger_read: &impl AnoncredsLedgerRead, ledger_write: &impl AnoncredsLedgerWrite, did: &Did, ) -> Result< ( SchemasMap, CredentialDefinitionsMap, PresentationRequest, Presentation, ), Box<dyn Error>, > { let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( wallet_issuer, wallet_holder, anoncreds_issuer, anoncreds_holder, ledger_read, ledger_write, did, DEFAULT_SCHEMA_ATTRS, ) .await; let proof_req = json!({ "nonce":"123432421212", "name":"proof_req_1", "version":"1.0", "requested_attributes": json!({ "address1_1": json!({ "name":"address1", "restrictions": [json!({ "issuer_did": did })] }), "zip_2": json!({ "name":"zip", "restrictions": [json!({ "issuer_did": did })] }), "self_attest_3": json!({ "name":"self_attest", }), }), "requested_predicates": json!({}), }) .to_string(); let requested_credentials_json = RequestedCredentials { self_attested_attributes: vec![( "self_attest_3".to_string(), "my_self_attested_val".to_string(), )] .into_iter() .collect(), requested_attributes: vec![ ( "address1_1".to_string(), RequestedAttribute { cred_id: cred_id.clone(), timestamp: None, revealed: true, }, ), ( "zip_2".to_string(), RequestedAttribute { cred_id: cred_id.clone(), timestamp: None, revealed: true, }, ), ] .into_iter() .collect(), requested_predicates: Default::default(), }; let schema_id = schema.schema_id.clone(); let schemas = json!({ schema_id: schema.schema_json, }) .to_string(); let cred_def_json = serde_json::to_value(cred_def.get_cred_def_json())?; let cred_defs = json!({ cred_def.get_cred_def_id().to_string(): cred_def_json, }) .to_string(); anoncreds_holder .prover_get_credentials_for_proof_req(wallet_holder, serde_json::from_str(&proof_req)?) .await?; let proof = anoncreds_holder .prover_create_proof( wallet_holder, serde_json::from_str(&proof_req)?, requested_credentials_json, &"main".to_string(), serde_json::from_str(&schemas)?, serde_json::from_str(&cred_defs)?, None, ) .await?; Ok(( serde_json::from_str(&schemas).unwrap(), serde_json::from_str(&cred_defs).unwrap(), serde_json::from_str(&proof_req).unwrap(), proof, )) } #[allow(clippy::too_many_arguments)] async fn create_proof_with_predicate( wallet_issuer: &impl BaseWallet, wallet_holder: &impl BaseWallet, anoncreds_issuer: &impl BaseAnonCreds, anoncreds_holder: &impl BaseAnonCreds, ledger_read: &impl AnoncredsLedgerRead, ledger_write: &impl AnoncredsLedgerWrite, did: &Did, include_predicate_cred: bool, ) -> Result< ( SchemasMap, CredentialDefinitionsMap, PresentationRequest, Presentation, ), Box<dyn Error>, > { let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( wallet_issuer, wallet_holder, anoncreds_issuer, anoncreds_holder, ledger_read, ledger_write, did, DEFAULT_SCHEMA_ATTRS, ) .await; let proof_req = json!({ "nonce":"123432421212", "name":"proof_req_1", "version":"1.0", "requested_attributes": json!({ "address1_1": json!({ "name":"address1", "restrictions": [json!({ "issuer_did": did })] }), "self_attest_3": json!({ "name":"self_attest", }), }), "requested_predicates": json!({ "zip_3": {"name":"zip", "p_type":">=", "p_value":18} }), }) .to_string(); let requested_credentials_json = if include_predicate_cred { RequestedCredentials { self_attested_attributes: vec![( "self_attest_3".to_string(), "my_self_attested_val".to_string(), )] .into_iter() .collect(), requested_attributes: vec![( "address1_1".to_string(), RequestedAttribute { cred_id: cred_id.clone(), timestamp: None, revealed: true, }, )] .into_iter() .collect(), requested_predicates: vec![( "zip_3".to_string(), RequestedPredicate { cred_id: cred_id.clone(), timestamp: None, }, )] .into_iter() .collect(), } } else { RequestedCredentials { self_attested_attributes: vec![( "self_attest_3".to_string(), "my_self_attested_val".to_string(), )] .into_iter() .collect(), requested_attributes: vec![( "address1_1".to_string(), RequestedAttribute { cred_id: cred_id.clone(), timestamp: None, revealed: true, }, )] .into_iter() .collect(), requested_predicates: Default::default(), } }; let schemas = json!({ schema.schema_id: schema.schema_json, }) .to_string(); let cred_def_json = serde_json::to_value(cred_def.get_cred_def_json())?; let cred_defs = json!({ cred_def.get_cred_def_id().to_string(): cred_def_json, }) .to_string(); anoncreds_holder .prover_get_credentials_for_proof_req(wallet_holder, serde_json::from_str(&proof_req)?) .await?; let proof = anoncreds_holder .prover_create_proof( wallet_holder, serde_json::from_str(&proof_req)?, requested_credentials_json, &"main".to_string(), serde_json::from_str(&schemas)?, serde_json::from_str(&cred_defs)?, None, ) .await?; Ok(( serde_json::from_str(&schemas).unwrap(), serde_json::from_str(&cred_defs).unwrap(), serde_json::from_str(&proof_req).unwrap(), proof, )) } #[allow(clippy::too_many_arguments)] async fn create_and_store_nonrevocable_credential( wallet_issuer: &impl BaseWallet, wallet_holder: &impl BaseWallet, anoncreds_issuer: &impl BaseAnonCreds, anoncreds_holder: &impl BaseAnonCreds, ledger_read: &impl AnoncredsLedgerRead, ledger_write: &impl AnoncredsLedgerWrite, issuer_did: &Did, attr_list: &str, ) -> (SchemaPrimitive, CredentialDef, String) { let schema = create_and_write_test_schema( wallet_issuer, anoncreds_issuer, ledger_write, issuer_did, attr_list, ) .await; let cred_def = create_and_write_test_cred_def( wallet_issuer, anoncreds_issuer, ledger_read, ledger_write, issuer_did, &schema.schema_id, false, ) .await; tokio::time::sleep(Duration::from_millis(500)).await; let cred_id = create_and_write_credential( wallet_issuer, wallet_holder, anoncreds_issuer, anoncreds_holder, issuer_did, &schema, &cred_def, None, ) .await; (schema, cred_def, cred_id) } #[tokio::test] #[ignore] async fn test_pool_proof_self_attested_proof_validation() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let requested_attributes = vec![ ( "attribute_0".to_string(), AttributeInfo::builder() .name("address1".into()) .self_attest_allowed(true) .build(), ), ( "attribute_1".to_string(), AttributeInfo::builder() .name("zip".into()) .self_attest_allowed(true) .build(), ), ] .into_iter() .collect(); let name = "Optional".to_owned(); let proof_req_json = PresentationRequestPayload::builder() .requested_attributes(requested_attributes) .name(name) .nonce(Nonce::new()?) .build(); let proof_req_json_str = serde_json::to_string(&proof_req_json)?; let anoncreds = &setup.anoncreds; let prover_proof_json = anoncreds .prover_create_proof( &setup.wallet, proof_req_json.into_v1(), RequestedCredentials { self_attested_attributes: vec![ ( "attribute_0".to_string(), "my_self_attested_address".to_string(), ), ( "attribute_1".to_string(), "my_self_attested_zip".to_string(), ), ] .into_iter() .collect(), ..Default::default() }, &"main".to_string(), Default::default(), Default::default(), None, ) .await?; assert!( validate_indy_proof( &setup.ledger_read, &setup.anoncreds, &serde_json::to_string(&prover_proof_json)?, &proof_req_json_str, ) .await? ); Ok(()) } #[tokio::test] #[ignore] async fn test_pool_proof_restrictions() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let requested_attributes = vec![ ( "attribute_0".to_string(), AttributeInfo::builder() .name("address1".into()) .restrictions(Query::Eq( "issuer_did".to_string(), setup.institution_did.to_string(), )) .build(), ), ( "attribute_1".to_string(), AttributeInfo::builder().name("zip".into()).build(), ), ( "attribute_2".to_string(), AttributeInfo::builder() .name("self_attest".into()) .self_attest_allowed(true) .build(), ), ] .into_iter() .collect(); let name = "Optional".to_owned(); let proof_req_json = PresentationRequestPayload::builder() .requested_attributes(requested_attributes) .name(name) .nonce(Nonce::new()?) .build(); let proof_req_json_str = serde_json::to_string(&proof_req_json)?; let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( &setup.wallet, &setup.wallet, &setup.anoncreds, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; let cred_def_json = serde_json::to_value(cred_def.get_cred_def_json())?; let anoncreds = &setup.anoncreds; let prover_proof_json = anoncreds .prover_create_proof( &setup.wallet, proof_req_json.into_v1(), RequestedCredentials { self_attested_attributes: vec![( "attribute_2".to_string(), "my_self_attested_val".to_string(), )] .into_iter() .collect(), requested_attributes: vec![ ( "attribute_0".to_string(), RequestedAttribute { cred_id: cred_id.clone(), timestamp: None, revealed: true, }, ), ( "attribute_1".to_string(), RequestedAttribute { cred_id: cred_id.clone(), timestamp: None, revealed: true, }, ), ] .into_iter() .collect(), requested_predicates: Default::default(), }, &"main".to_string(), serde_json::from_str(&json!({ schema.schema_id: schema.schema_json }).to_string())?, serde_json::from_str( &json!({ cred_def.get_cred_def_id().to_string(): cred_def_json }).to_string(), )?, None, ) .await?; assert!( validate_indy_proof( &setup.ledger_read, &setup.anoncreds, &serde_json::to_string(&prover_proof_json)?, &proof_req_json_str, ) .await? ); Ok(()) } #[tokio::test] #[ignore] async fn test_pool_proof_validate_attribute() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let requested_attributes = vec![ ( "attribute_0".to_string(), AttributeInfo::builder() .name("address1".into()) .restrictions(Query::Eq( "issuer_did".to_string(), setup.institution_did.to_string(), )) .build(), ), ( "attribute_1".to_string(), AttributeInfo::builder() .name("zip".into()) .restrictions(Query::Eq( "issuer_did".to_string(), setup.institution_did.to_string(), )) .build(), ), ( "attribute_2".to_string(), AttributeInfo::builder() .name("self_attest".into()) .self_attest_allowed(true) .build(), ), ] .into_iter() .collect(); let name = "Optional".to_owned(); let proof_req_json = PresentationRequestPayload::builder() .requested_attributes(requested_attributes) .name(name) .nonce(Nonce::new()?) .build(); let proof_req_json_str = serde_json::to_string(&proof_req_json)?; let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( &setup.wallet, &setup.wallet, &setup.anoncreds, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; let cred_def_json = serde_json::to_value(cred_def.get_cred_def_json())?; let anoncreds = &setup.anoncreds; let prover_proof_json = anoncreds .prover_create_proof( &setup.wallet, proof_req_json.into_v1(), RequestedCredentials { self_attested_attributes: vec![( "attribute_2".to_string(), "my_self_attested_val".to_string(), )] .into_iter() .collect(), requested_attributes: vec![ ( "attribute_0".to_string(), RequestedAttribute { cred_id: cred_id.clone(), timestamp: None, revealed: true, }, ), ( "attribute_1".to_string(), RequestedAttribute { cred_id: cred_id.clone(), timestamp: None, revealed: true, }, ), ] .into_iter() .collect(), requested_predicates: Default::default(), }, &"main".to_string(), serde_json::from_str(&json!({ schema.schema_id: schema.schema_json }).to_string())?, serde_json::from_str( &json!({ cred_def.get_cred_def_id().to_string(): cred_def_json }).to_string(), )?, None, ) .await?; assert!( validate_indy_proof( &setup.ledger_read, &setup.anoncreds, &serde_json::to_string(&prover_proof_json)?, &proof_req_json_str, ) .await? ); let mut proof_obj: serde_json::Value = serde_json::to_value(&prover_proof_json)?; { proof_obj["requested_proof"]["revealed_attrs"]["address1_1"]["raw"] = json!("Other Value"); let prover_proof_json = serde_json::to_string(&proof_obj)?; assert_eq!( validate_indy_proof( &setup.ledger_read, &setup.anoncreds, &prover_proof_json, &proof_req_json_str, ) .await .unwrap_err() .kind(), AriesVcxErrorKind::InvalidProof ); } { proof_obj["requested_proof"]["revealed_attrs"]["address1_1"]["encoded"] = json!("1111111111111111111111111111111111111111111111111111111111"); let prover_proof_json = serde_json::to_string(&proof_obj).unwrap(); assert_eq!( validate_indy_proof( &setup.ledger_read, &setup.anoncreds, &prover_proof_json, &proof_req_json_str, ) .await .unwrap_err() .kind(), AriesVcxErrorKind::InvalidProof ); } Ok(()) } #[tokio::test] #[ignore] async fn test_pool_prover_verify_proof() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let (schemas, cred_defs, proof_req, proof) = create_indy_proof( &setup.wallet, &setup.wallet, &setup.anoncreds, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, ) .await?; let anoncreds = &setup.anoncreds; let proof_validation = anoncreds .verifier_verify_proof(proof_req, proof, schemas, cred_defs, None, None) .await?; assert!(proof_validation); Ok(()) } #[tokio::test] #[ignore] async fn test_pool_prover_verify_proof_with_predicate_success_case() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let (schemas, cred_defs, proof_req, proof) = create_proof_with_predicate( &setup.wallet, &setup.wallet, &setup.anoncreds, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, true, ) .await?; let anoncreds = &setup.anoncreds; let proof_validation = anoncreds .verifier_verify_proof(proof_req, proof, schemas, cred_defs, None, None) .await?; assert!(proof_validation); Ok(()) } #[tokio::test] #[ignore] async fn test_pool_prover_verify_proof_with_predicate_fail_case() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let (schemas, cred_defs, proof_req, proof) = create_proof_with_predicate( &setup.wallet, &setup.wallet, &setup.anoncreds, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, false, ) .await?; let anoncreds = &setup.anoncreds; anoncreds .verifier_verify_proof(proof_req, proof, schemas, cred_defs, None, None) .await .unwrap_err(); Ok(()) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/test_primitives.rs
aries/aries_vcx/tests/test_primitives.rs
use std::error::Error; use anoncreds_types::{ data_types::ledger::cred_def::CredentialDefinition, utils::validation::Validatable, }; use aries_vcx::common::primitives::{ credential_definition::generate_cred_def, revocation_registry::generate_rev_reg, }; use aries_vcx_ledger::ledger::{ base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite}, indy::pool::test_utils::get_temp_dir_path, }; use test_utils::{constants::DEFAULT_SCHEMA_ATTRS, devsetup::build_setup_profile}; use crate::utils::create_and_write_test_schema; pub mod utils; #[tokio::test] #[ignore] async fn test_pool_create_cred_def_real() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let schema = create_and_write_test_schema( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; let ledger_read = setup.ledger_read; let ledger_write = &setup.ledger_write; let schema_json = ledger_read.get_schema(&schema.schema_id, None).await?; let cred_def = generate_cred_def( &setup.wallet, &setup.anoncreds, &setup.institution_did, &schema.schema_id, schema_json, "tag_1", None, Some(true), ) .await?; ledger_write .publish_cred_def(&setup.wallet, cred_def.try_clone()?, &setup.institution_did) .await?; tokio::time::sleep(std::time::Duration::from_secs(2)).await; let cred_def_json_ledger = ledger_read .get_cred_def(&cred_def.id, Some(&setup.institution_did)) .await?; cred_def_json_ledger.validate()?; // same as the original generated cred def, but schema ID corrected to the qualified version let cred_def_corrected_schema_id = CredentialDefinition { schema_id: schema.schema_id, ..cred_def.try_clone().unwrap() }; // check cred def matches originally, but with corected schema ID. assert_eq!( serde_json::to_value(cred_def_json_ledger)?, serde_json::to_value(cred_def_corrected_schema_id)? ); Ok(()) } #[tokio::test] #[ignore] async fn test_pool_create_rev_reg_def() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let schema = create_and_write_test_schema( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; let ledger_read = &setup.ledger_read; let ledger_write = &setup.ledger_write; let schema_json = ledger_read.get_schema(&schema.schema_id, None).await?; let cred_def = generate_cred_def( &setup.wallet, &setup.anoncreds, &setup.institution_did, &schema.schema_id, schema_json, "tag_1", None, Some(true), ) .await?; ledger_write .publish_cred_def(&setup.wallet, cred_def.try_clone()?, &setup.institution_did) .await?; let path = get_temp_dir_path(); let (rev_reg_def_id, rev_reg_def_json, rev_reg_entry_json) = generate_rev_reg( &setup.wallet, &setup.anoncreds, &setup.institution_did, &cred_def.id, path.to_str().unwrap(), 2, "tag1", ) .await?; ledger_write .publish_rev_reg_def( &setup.wallet, serde_json::from_str(&serde_json::to_string(&rev_reg_def_json)?)?, &setup.institution_did, ) .await?; ledger_write .publish_rev_reg_delta( &setup.wallet, &rev_reg_def_id.try_into()?, serde_json::from_str(&rev_reg_entry_json)?, &setup.institution_did, ) .await?; Ok(()) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/test_revocations.rs
aries/aries_vcx/tests/test_revocations.rs
use std::{error::Error, thread, time::Duration}; use anoncreds_types::data_types::messages::pres_request::NonRevokedInterval; use aries_vcx::protocols::proof_presentation::verifier::{ state_machine::VerifierState, verification_status::PresentationVerificationStatus, }; use test_utils::devsetup::*; use crate::utils::{ scenarios::{ create_address_schema_creddef_revreg, create_proof_request_data, create_verifier_from_request_data, credential_data_address_1, credential_data_address_2, credential_data_address_3, exchange_credential, exchange_proof, issue_address_credential, prover_select_credentials_and_send_proof, publish_revocation, requested_attrs_address, revoke_credential_and_publish_accumulator, revoke_credential_local, rotate_rev_reg, verifier_create_proof_and_send_request, }, test_agent::{create_test_agent, create_test_agent_trustee}, }; pub mod utils; #[tokio::test] #[ignore] async fn test_agency_pool_basic_revocation() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; let (schema, cred_def, rev_reg, issuer) = issue_address_credential(&mut consumer, &mut institution).await; assert!(!issuer.is_revoked(&institution.ledger_read).await?); let time_before_revocation = time::OffsetDateTime::now_utc().unix_timestamp() as u64; revoke_credential_and_publish_accumulator(&mut institution, &issuer, &rev_reg).await; tokio::time::sleep(Duration::from_millis(1000)).await; let time_after_revocation = time::OffsetDateTime::now_utc().unix_timestamp() as u64; assert!(issuer.is_revoked(&institution.ledger_read).await?); let requested_attrs = requested_attrs_address( &institution.institution_did, &schema.schema_id, cred_def.get_cred_def_id(), None, Some(time_after_revocation), ); let presentation_request_data = create_proof_request_data( &mut institution, requested_attrs, Default::default(), NonRevokedInterval::new( Some(time_before_revocation - 100), Some(time_after_revocation), ), None, ) .await; let mut verifier = create_verifier_from_request_data(presentation_request_data).await; let presentation = prover_select_credentials_and_send_proof( &mut consumer, verifier.get_presentation_request_msg()?, None, ) .await; verifier .verify_presentation( &institution.ledger_read, &institution.anoncreds, presentation, ) .await?; assert_eq!(verifier.get_state(), VerifierState::Finished); assert_eq!( verifier.get_verification_status(), PresentationVerificationStatus::Invalid ); Ok(()) } #[tokio::test] #[ignore] async fn test_agency_pool_revoked_credential_might_still_work() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; let (schema, cred_def, rev_reg, issuer) = issue_address_credential(&mut consumer, &mut institution).await; assert!(!issuer.is_revoked(&institution.ledger_read).await?); tokio::time::sleep(Duration::from_millis(1000)).await; let time_before_revocation = time::OffsetDateTime::now_utc().unix_timestamp() as u64; tokio::time::sleep(Duration::from_millis(1000)).await; revoke_credential_and_publish_accumulator(&mut institution, &issuer, &rev_reg).await; tokio::time::sleep(Duration::from_millis(1000)).await; let from = time_before_revocation - 100; let to = time_before_revocation; let requested_attrs = requested_attrs_address( &institution.institution_did, &schema.schema_id, cred_def.get_cred_def_id(), Some(from), Some(to), ); let presentation_request_data = create_proof_request_data( &mut institution, requested_attrs, Default::default(), NonRevokedInterval::new(Some(from), Some(to)), None, ) .await; let mut verifier = create_verifier_from_request_data(presentation_request_data).await; let presentation = prover_select_credentials_and_send_proof( &mut consumer, verifier.get_presentation_request_msg()?, None, ) .await; verifier .verify_presentation( &institution.ledger_read, &institution.anoncreds, presentation, ) .await?; assert_eq!(verifier.get_state(), VerifierState::Finished); assert_eq!( verifier.get_verification_status(), PresentationVerificationStatus::Valid ); Ok(()) } #[tokio::test] #[ignore] async fn test_agency_pool_local_revocation() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; let (schema, cred_def, rev_reg, issuer) = issue_address_credential(&mut consumer, &mut institution).await; revoke_credential_local(&mut institution, &issuer, &rev_reg.rev_reg_id).await; assert!(!issuer.is_revoked(&institution.ledger_read).await?); let verifier_handler = exchange_proof( &mut institution, &mut consumer, &schema.schema_id, cred_def.get_cred_def_id(), Some("request1"), ) .await; assert_eq!( verifier_handler.get_verification_status(), PresentationVerificationStatus::Valid ); assert!(!issuer.is_revoked(&institution.ledger_read).await?); publish_revocation(&mut institution, &rev_reg).await; let verifier_handler = exchange_proof( &mut institution, &mut consumer, &schema.schema_id, cred_def.get_cred_def_id(), Some("request2"), ) .await; assert_eq!( verifier_handler.get_verification_status(), PresentationVerificationStatus::Invalid ); assert!(issuer.is_revoked(&institution.ledger_read).await?); Ok(()) } // TODO - re-enable after https://github.com/openwallet-foundation/vcx/issues/1309 // #[tokio::test] // #[ignore] #[allow(unused)] async fn test_agency_batch_revocation() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut institution = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer1 = create_test_agent(setup.genesis_file_path.clone()).await; let mut consumer2 = create_test_agent(setup.genesis_file_path.clone()).await; let mut consumer3 = create_test_agent(setup.genesis_file_path).await; // Issue and send three credentials of the same schema let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &institution.wallet, &institution.ledger_read, &institution.ledger_write, &institution.anoncreds, &institution.institution_did, ) .await; let issuer_credential1 = exchange_credential( &mut consumer1, &mut institution, credential_data_address_1().to_string(), &cred_def, &rev_reg, None, ) .await; let issuer_credential2 = exchange_credential( &mut consumer2, &mut institution, credential_data_address_2().to_string(), &cred_def, &rev_reg, None, ) .await; let issuer_credential3 = exchange_credential( &mut consumer3, &mut institution, credential_data_address_3().to_string(), &cred_def, &rev_reg, None, ) .await; revoke_credential_local(&mut institution, &issuer_credential1, &rev_reg.rev_reg_id).await; revoke_credential_local(&mut institution, &issuer_credential2, &rev_reg.rev_reg_id).await; assert!( !issuer_credential1 .is_revoked(&institution.ledger_read) .await? ); assert!( !issuer_credential2 .is_revoked(&institution.ledger_read) .await? ); assert!( !issuer_credential3 .is_revoked(&institution.ledger_read) .await? ); // Revoke two locally and verify their are all still valid let verifier_handler = exchange_proof( &mut institution, &mut consumer1, &schema.schema_id, cred_def.get_cred_def_id(), Some("request1"), ) .await; assert_eq!( verifier_handler.get_verification_status(), PresentationVerificationStatus::Valid ); let verifier_handler = exchange_proof( &mut institution, &mut consumer2, &schema.schema_id, cred_def.get_cred_def_id(), Some("request2"), ) .await; assert_eq!( verifier_handler.get_verification_status(), PresentationVerificationStatus::Valid ); let verifier_handler = exchange_proof( &mut institution, &mut consumer3, &schema.schema_id, cred_def.get_cred_def_id(), Some("request3"), ) .await; assert_eq!( verifier_handler.get_verification_status(), PresentationVerificationStatus::Valid ); // Publish revocations and verify the two are invalid, third still valid publish_revocation(&mut institution, &rev_reg).await; tokio::time::sleep(Duration::from_millis(1000)).await; assert!( issuer_credential1 .is_revoked(&institution.ledger_read) .await? ); assert!( issuer_credential2 .is_revoked(&institution.ledger_read) .await? ); assert!( !issuer_credential3 .is_revoked(&institution.ledger_read) .await? ); let verifier_handler = exchange_proof( &mut institution, &mut consumer1, &schema.schema_id, cred_def.get_cred_def_id(), Some("request1"), ) .await; assert_eq!( verifier_handler.get_verification_status(), PresentationVerificationStatus::Invalid ); let verifier_handler = exchange_proof( &mut institution, &mut consumer2, &schema.schema_id, cred_def.get_cred_def_id(), Some("request2"), ) .await; assert_eq!( verifier_handler.get_verification_status(), PresentationVerificationStatus::Invalid ); let verifier_handler = exchange_proof( &mut institution, &mut consumer3, &schema.schema_id, cred_def.get_cred_def_id(), Some("request3"), ) .await; assert_eq!( verifier_handler.get_verification_status(), PresentationVerificationStatus::Valid ); Ok(()) } #[tokio::test] #[ignore] #[allow(unused_mut)] async fn test_agency_pool_two_creds_one_rev_reg_revoke_first() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut issuer = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut verifier = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &issuer.wallet, &issuer.ledger_read, &issuer.ledger_write, &issuer.anoncreds, &issuer.institution_did, ) .await; let credential_data1 = credential_data_address_1().to_string(); let issuer_credential1 = exchange_credential( &mut consumer, &mut issuer, credential_data1.clone(), &cred_def, &rev_reg, Some("request1"), ) .await; let credential_data2 = credential_data_address_2().to_string(); let issuer_credential2 = exchange_credential( &mut consumer, &mut issuer, credential_data2.clone(), &cred_def, &rev_reg, Some("request2"), ) .await; assert!(!issuer_credential1.is_revoked(&issuer.ledger_read).await?); assert!(!issuer_credential2.is_revoked(&issuer.ledger_read).await?); revoke_credential_and_publish_accumulator(&mut issuer, &issuer_credential1, &rev_reg).await; let mut proof_verifier = verifier_create_proof_and_send_request( &mut verifier, &schema.schema_id, cred_def.get_cred_def_id(), Some("request1"), ) .await; let presentation_request = proof_verifier.get_presentation_request_msg()?; let presentation = prover_select_credentials_and_send_proof( &mut consumer, presentation_request, Some(&credential_data1), ) .await; proof_verifier .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await?; assert_eq!(proof_verifier.get_state(), VerifierState::Finished); assert_eq!( proof_verifier.get_verification_status(), PresentationVerificationStatus::Invalid ); let mut proof_verifier = verifier_create_proof_and_send_request( &mut verifier, &schema.schema_id, cred_def.get_cred_def_id(), Some("request2"), ) .await; let presentation_request = proof_verifier.get_presentation_request_msg()?; let presentation = prover_select_credentials_and_send_proof( &mut consumer, presentation_request, Some(&credential_data2), ) .await; proof_verifier .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await?; assert_eq!( proof_verifier.get_verification_status(), PresentationVerificationStatus::Valid ); assert!(issuer_credential1.is_revoked(&issuer.ledger_read).await?); assert!(!issuer_credential2.is_revoked(&issuer.ledger_read).await?); Ok(()) } #[tokio::test] #[ignore] #[allow(unused_mut)] async fn test_agency_pool_two_creds_one_rev_reg_revoke_second() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut issuer = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut verifier = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &issuer.wallet, &issuer.ledger_read, &issuer.ledger_write, &issuer.anoncreds, &issuer.institution_did, ) .await; let credential_data1 = credential_data_address_1().to_string(); let issuer_credential1 = exchange_credential( &mut consumer, &mut issuer, credential_data1.clone(), &cred_def, &rev_reg, Some("request1"), ) .await; let credential_data2 = credential_data_address_2().to_string(); let issuer_credential2 = exchange_credential( &mut consumer, &mut issuer, credential_data2.clone(), &cred_def, &rev_reg, Some("request2"), ) .await; assert!(!issuer_credential1.is_revoked(&issuer.ledger_read).await?); assert!(!issuer_credential2.is_revoked(&issuer.ledger_read).await?); revoke_credential_and_publish_accumulator(&mut issuer, &issuer_credential2, &rev_reg).await; let mut proof_verifier = verifier_create_proof_and_send_request( &mut verifier, &schema.schema_id, cred_def.get_cred_def_id(), Some("request1"), ) .await; let presentation = prover_select_credentials_and_send_proof( &mut consumer, proof_verifier.get_presentation_request_msg()?, Some(&credential_data1), ) .await; proof_verifier .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await?; assert_eq!(proof_verifier.get_state(), VerifierState::Finished); assert_eq!( proof_verifier.get_verification_status(), PresentationVerificationStatus::Valid ); let mut proof_verifier = verifier_create_proof_and_send_request( &mut verifier, &schema.schema_id, cred_def.get_cred_def_id(), Some("request2"), ) .await; let presentation = prover_select_credentials_and_send_proof( &mut consumer, proof_verifier.get_presentation_request_msg()?, Some(&credential_data2), ) .await; proof_verifier .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await?; assert_eq!( proof_verifier.get_verification_status(), PresentationVerificationStatus::Invalid ); assert!(!issuer_credential1.is_revoked(&issuer.ledger_read).await?); assert!(issuer_credential2.is_revoked(&issuer.ledger_read).await?); Ok(()) } #[tokio::test] #[ignore] async fn test_agency_pool_two_creds_two_rev_reg_id() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut issuer = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut verifier = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &issuer.wallet, &issuer.ledger_read, &issuer.ledger_write, &issuer.anoncreds, &issuer.institution_did, ) .await; let credential_data1 = credential_data_address_1().to_string(); let issuer_credential1 = exchange_credential( &mut consumer, &mut issuer, credential_data1.clone(), &cred_def, &rev_reg, Some("request1"), ) .await; let rev_reg_2 = rotate_rev_reg(&mut issuer, &cred_def, &rev_reg).await; let credential_data2 = credential_data_address_2().to_string(); let issuer_credential2 = exchange_credential( &mut consumer, &mut issuer, credential_data2.clone(), &cred_def, &rev_reg_2, Some("request2"), ) .await; let mut proof_verifier = verifier_create_proof_and_send_request( &mut verifier, &schema.schema_id, cred_def.get_cred_def_id(), Some("request1"), ) .await; let presentation = prover_select_credentials_and_send_proof( &mut consumer, proof_verifier.get_presentation_request_msg()?, Some(&credential_data1), ) .await; proof_verifier .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await?; assert_eq!(proof_verifier.get_state(), VerifierState::Finished); assert_eq!( proof_verifier.get_verification_status(), PresentationVerificationStatus::Valid ); let mut proof_verifier = verifier_create_proof_and_send_request( &mut verifier, &schema.schema_id, cred_def.get_cred_def_id(), Some("request2"), ) .await; let presentation = prover_select_credentials_and_send_proof( &mut consumer, proof_verifier.get_presentation_request_msg()?, Some(&credential_data2), ) .await; proof_verifier .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await?; assert_eq!(proof_verifier.get_state(), VerifierState::Finished); assert_eq!( proof_verifier.get_verification_status(), PresentationVerificationStatus::Valid ); assert!(!issuer_credential1.is_revoked(&issuer.ledger_read).await?); assert!(!issuer_credential2.is_revoked(&issuer.ledger_read).await?); Ok(()) } #[tokio::test] #[ignore] #[allow(unused_mut)] async fn test_agency_pool_two_creds_two_rev_reg_id_revoke_first() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut issuer = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut verifier = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &issuer.wallet, &issuer.ledger_read, &issuer.ledger_write, &issuer.anoncreds, &issuer.institution_did, ) .await; let credential_data1 = credential_data_address_1().to_string(); let issuer_credential1 = exchange_credential( &mut consumer, &mut issuer, credential_data1.clone(), &cred_def, &rev_reg, Some("request1"), ) .await; let rev_reg_2 = rotate_rev_reg(&mut issuer, &cred_def, &rev_reg).await; let credential_data2 = credential_data_address_2().to_string(); let issuer_credential2 = exchange_credential( &mut consumer, &mut issuer, credential_data2.clone(), &cred_def, &rev_reg_2, Some("request2"), ) .await; assert!(!issuer_credential1.is_revoked(&issuer.ledger_read).await?); assert!(!issuer_credential2.is_revoked(&issuer.ledger_read).await?); revoke_credential_and_publish_accumulator(&mut issuer, &issuer_credential1, &rev_reg).await; let mut proof_verifier = verifier_create_proof_and_send_request( &mut verifier, &schema.schema_id, cred_def.get_cred_def_id(), Some("request1"), ) .await; let presentation = prover_select_credentials_and_send_proof( &mut consumer, proof_verifier.get_presentation_request_msg()?, Some(&credential_data1), ) .await; proof_verifier .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await?; assert_eq!(proof_verifier.get_state(), VerifierState::Finished); assert_eq!( proof_verifier.get_verification_status(), PresentationVerificationStatus::Invalid ); let mut proof_verifier = verifier_create_proof_and_send_request( &mut verifier, &schema.schema_id, cred_def.get_cred_def_id(), Some("request2"), ) .await; let presentation = prover_select_credentials_and_send_proof( &mut consumer, proof_verifier.get_presentation_request_msg()?, Some(&credential_data2), ) .await; proof_verifier .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await?; assert_eq!( proof_verifier.get_verification_status(), PresentationVerificationStatus::Valid ); assert!(issuer_credential1.is_revoked(&issuer.ledger_read).await?); assert!(!issuer_credential2.is_revoked(&issuer.ledger_read).await?); Ok(()) } #[tokio::test] #[ignore] async fn test_agency_pool_two_creds_two_rev_reg_id_revoke_second() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut issuer = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut verifier = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &issuer.wallet, &issuer.ledger_read, &issuer.ledger_write, &issuer.anoncreds, &issuer.institution_did, ) .await; let credential_data1 = credential_data_address_1().to_string(); let issuer_credential1 = exchange_credential( &mut consumer, &mut issuer, credential_data1.clone(), &cred_def, &rev_reg, Some("request1"), ) .await; let rev_reg_2 = rotate_rev_reg(&mut issuer, &cred_def, &rev_reg).await; let credential_data2 = credential_data_address_2().to_string(); let issuer_credential2 = exchange_credential( &mut consumer, &mut issuer, credential_data2.clone(), &cred_def, &rev_reg_2, Some("request2"), ) .await; assert!(!issuer_credential1.is_revoked(&issuer.ledger_read).await?); assert!(!issuer_credential2.is_revoked(&issuer.ledger_read).await?); revoke_credential_and_publish_accumulator(&mut issuer, &issuer_credential2, &rev_reg_2).await; let mut proof_verifier = verifier_create_proof_and_send_request( &mut verifier, &schema.schema_id, cred_def.get_cred_def_id(), Some("request1"), ) .await; let presentation = prover_select_credentials_and_send_proof( &mut consumer, proof_verifier.get_presentation_request_msg()?, Some(&credential_data1), ) .await; proof_verifier .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await?; assert_eq!(proof_verifier.get_state(), VerifierState::Finished); assert_eq!( proof_verifier.get_verification_status(), PresentationVerificationStatus::Valid ); let mut proof_verifier = verifier_create_proof_and_send_request( &mut verifier, &schema.schema_id, cred_def.get_cred_def_id(), Some("request2"), ) .await; let presentation = prover_select_credentials_and_send_proof( &mut consumer, proof_verifier.get_presentation_request_msg()?, Some(&credential_data2), ) .await; proof_verifier .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await?; assert_eq!(proof_verifier.get_state(), VerifierState::Finished); assert_eq!( proof_verifier.get_verification_status(), PresentationVerificationStatus::Invalid ); assert!(!issuer_credential1.is_revoked(&issuer.ledger_read).await?); assert!(issuer_credential2.is_revoked(&issuer.ledger_read).await?); Ok(()) } #[tokio::test] #[ignore] async fn test_agency_pool_three_creds_one_rev_reg_revoke_all() -> Result<(), Box<dyn Error>> { let setup = SetupPoolDirectory::init().await; let mut issuer = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (_schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &issuer.wallet, &issuer.ledger_read, &issuer.ledger_write, &issuer.anoncreds, &issuer.institution_did, ) .await; let issuer_credential1 = exchange_credential( &mut consumer, &mut issuer, credential_data_address_1().to_string(), &cred_def, &rev_reg, Some("request1"), ) .await; assert!(!issuer_credential1.is_revoked(&issuer.ledger_read).await?); revoke_credential_local(&mut issuer, &issuer_credential1, &rev_reg.rev_reg_id).await; let issuer_credential2 = exchange_credential( &mut consumer, &mut issuer, credential_data_address_2().to_string(), &cred_def, &rev_reg, Some("request2"), ) .await; assert!(!issuer_credential2.is_revoked(&issuer.ledger_read).await?); revoke_credential_local(&mut issuer, &issuer_credential2, &rev_reg.rev_reg_id).await; let issuer_credential3 = exchange_credential( &mut consumer, &mut issuer, credential_data_address_3().to_string(), &cred_def, &rev_reg, Some("request3"), ) .await; revoke_credential_and_publish_accumulator(&mut issuer, &issuer_credential3, &rev_reg).await; thread::sleep(Duration::from_millis(100)); assert!(issuer_credential1.is_revoked(&issuer.ledger_read).await?); assert!(issuer_credential2.is_revoked(&issuer.ledger_read).await?); assert!(issuer_credential3.is_revoked(&issuer.ledger_read).await?); Ok(()) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/test_credentials.rs
aries/aries_vcx/tests/test_credentials.rs
use std::error::Error; use aries_vcx::common::credentials::{get_cred_rev_id, is_cred_revoked}; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use test_utils::{constants::DEFAULT_SCHEMA_ATTRS, devsetup::build_setup_profile}; use crate::utils::{ create_and_publish_test_rev_reg, create_and_write_credential, create_and_write_test_cred_def, create_and_write_test_schema, }; pub mod utils; #[tokio::test] #[ignore] async fn test_pool_prover_get_credential() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let schema = create_and_write_test_schema( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; let cred_def = create_and_write_test_cred_def( &setup.wallet, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, &schema.schema_id, true, ) .await; let rev_reg = create_and_publish_test_rev_reg( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, cred_def.get_cred_def_id(), ) .await; let cred_id = create_and_write_credential( &setup.wallet, &setup.wallet, &setup.anoncreds, &setup.anoncreds, &setup.institution_did, &schema, &cred_def, Some(&rev_reg), ) .await; let cred_rev_id = get_cred_rev_id(&setup.wallet, &setup.anoncreds, &cred_id).await?; let prover_cred = setup .anoncreds .prover_get_credential(&setup.wallet, &cred_id) .await?; assert_eq!(prover_cred.schema_id, schema.schema_id); assert_eq!(&prover_cred.cred_def_id, cred_def.get_cred_def_id()); assert_eq!(prover_cred.cred_rev_id.unwrap(), cred_rev_id); assert_eq!(prover_cred.rev_reg_id.unwrap(), rev_reg.rev_reg_id); Ok(()) } #[tokio::test] #[ignore] async fn test_pool_is_cred_revoked() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let schema = create_and_write_test_schema( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; let cred_def = create_and_write_test_cred_def( &setup.wallet, &setup.anoncreds, &setup.ledger_read, &setup.ledger_write, &setup.institution_did, &schema.schema_id, true, ) .await; let rev_reg = create_and_publish_test_rev_reg( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, cred_def.get_cred_def_id(), ) .await; let cred_id = create_and_write_credential( &setup.wallet, &setup.wallet, &setup.anoncreds, &setup.anoncreds, &setup.institution_did, &schema, &cred_def, Some(&rev_reg), ) .await; let cred_rev_id = get_cred_rev_id(&setup.wallet, &setup.anoncreds, &cred_id).await?; assert!(!is_cred_revoked(&setup.ledger_read, &rev_reg.rev_reg_id, cred_rev_id).await?); #[allow(deprecated)] // TODO - https://github.com/openwallet-foundation/vcx/issues/1309 let rev_reg_delta_json = setup .ledger_read .get_rev_reg_delta_json(&rev_reg.rev_reg_id.to_owned().try_into()?, None, None) .await? .0; setup .anoncreds .revoke_credential_local( &setup.wallet, &rev_reg.rev_reg_id.to_owned().try_into()?, cred_rev_id, rev_reg_delta_json, ) .await?; rev_reg .publish_local_revocations( &setup.wallet, &setup.anoncreds, &setup.ledger_write, &setup.institution_did, ) .await?; std::thread::sleep(std::time::Duration::from_millis(500)); assert!(is_cred_revoked(&setup.ledger_read, &rev_reg.rev_reg_id, cred_rev_id).await?); Ok(()) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/utils/test_agent.rs
aries/aries_vcx/tests/utils/test_agent.rs
#![allow(clippy::diverging_sub_expression)] use aries_vcx::{ common::ledger::transactions::write_endorser_did, global::settings::DEFAULT_LINK_SECRET_ALIAS, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::{ AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite, }; use aries_vcx_wallet::wallet::base_wallet::{did_wallet::DidWallet, BaseWallet}; use did_parser_nom::Did; use test_utils::{ constants::TRUSTEE_SEED, devsetup::{ dev_build_featured_anoncreds, dev_build_featured_indy_ledger, dev_build_featured_wallet, }, random::generate_random_seed, }; pub struct TestAgent<LR, LW, A, W> where LR: IndyLedgerRead + AnoncredsLedgerRead, LW: IndyLedgerWrite + AnoncredsLedgerWrite, A: BaseAnonCreds, W: BaseWallet, { pub ledger_read: LR, pub ledger_write: LW, pub anoncreds: A, pub wallet: W, pub institution_did: Did, pub genesis_file_path: String, } async fn create_test_agent_from_seed( seed: &str, genesis_file_path: String, ) -> TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, > { let (institution_did, wallet) = dev_build_featured_wallet(seed).await; let (ledger_read, ledger_write) = dev_build_featured_indy_ledger(genesis_file_path.clone()).await; let anoncreds = dev_build_featured_anoncreds().await; anoncreds .prover_create_link_secret(&wallet, &DEFAULT_LINK_SECRET_ALIAS.to_string()) .await .unwrap(); TestAgent { genesis_file_path, institution_did: Did::parse(institution_did).unwrap(), wallet, ledger_read, ledger_write, anoncreds, } } pub async fn create_test_agent_trustee( genesis_file_path: String, ) -> TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, > { create_test_agent_from_seed(TRUSTEE_SEED, genesis_file_path).await } pub async fn create_test_agent( genesis_file_path: String, ) -> TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, > { create_test_agent_from_seed(&generate_random_seed(), genesis_file_path).await } pub async fn create_test_agent_endorser_2( genesis_file_path: &str, test_agent_trustee: TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, ) -> Result< TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, Box<dyn std::error::Error>, > { let agent_endorser = create_test_agent_endorser( test_agent_trustee.ledger_write, test_agent_trustee.wallet, genesis_file_path, &test_agent_trustee.institution_did, ) .await?; Ok(agent_endorser) } pub async fn create_test_agent_endorser<LW, W>( ledger_write: LW, trustee_wallet: W, genesis_file_path: &str, trustee_did: &Did, ) -> Result< TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, Box<dyn std::error::Error>, > where LW: IndyLedgerWrite + AnoncredsLedgerWrite, W: BaseWallet, { let acme = create_test_agent(genesis_file_path.to_string()).await; let acme_vk = acme .wallet .key_for_did(&acme.institution_did.to_string()) .await?; write_endorser_did( &trustee_wallet, &ledger_write, trustee_did, &acme.institution_did, &acme_vk.base58(), None, ) .await?; Ok(acme) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/utils/mod.rs
aries/aries_vcx/tests/utils/mod.rs
pub mod scenarios; pub mod test_agent; use std::{path::Path, time::Duration}; use anoncreds_types::data_types::identifiers::{ cred_def_id::CredentialDefinitionId, schema_id::SchemaId, }; use aries_vcx::{ common::{ credentials::encoding::encode_attributes, primitives::{ credential_definition::CredentialDef, credential_schema::Schema, revocation_registry::RevocationRegistry, }, }, global::settings, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::{ base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite}, indy::pool::test_utils::get_temp_dir_path, }; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use did_parser_nom::Did; use test_utils::{ constants::TEST_TAILS_URL, random::{generate_random_schema_name, generate_random_schema_version}, }; pub async fn create_and_write_test_schema( wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger_write: &impl AnoncredsLedgerWrite, submitter_did: &Did, attr_list: &str, ) -> Schema { let schema = Schema::create( anoncreds, "source_id", submitter_did, &generate_random_schema_name(), &generate_random_schema_version(), serde_json::from_str::<Vec<String>>(attr_list).unwrap(), ) .await .unwrap(); let schema = schema.publish(wallet, ledger_write).await.unwrap(); std::thread::sleep(Duration::from_millis(500)); schema } pub async fn create_and_write_test_cred_def( wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger_read: &impl AnoncredsLedgerRead, ledger_write: &impl AnoncredsLedgerWrite, issuer_did: &Did, schema_id: &SchemaId, revokable: bool, ) -> CredentialDef { CredentialDef::create( wallet, ledger_read, anoncreds, "1".to_string(), issuer_did.clone(), schema_id.clone(), "1".to_string(), revokable, ) .await .unwrap() .publish_cred_def(wallet, ledger_read, ledger_write) .await .unwrap() } pub async fn create_and_publish_test_rev_reg( wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger_write: &impl AnoncredsLedgerWrite, issuer_did: &Did, cred_def_id: &CredentialDefinitionId, ) -> RevocationRegistry { let tails_dir = get_temp_dir_path().as_path().to_str().unwrap().to_string(); let mut rev_reg = RevocationRegistry::create( wallet, anoncreds, issuer_did, cred_def_id, &tails_dir, 10, 1, ) .await .unwrap(); rev_reg .publish_revocation_primitives(wallet, ledger_write, TEST_TAILS_URL) .await .unwrap(); rev_reg } #[allow(clippy::too_many_arguments)] // test util code pub async fn create_and_write_credential( wallet_issuer: &impl BaseWallet, wallet_holder: &impl BaseWallet, anoncreds_issuer: &impl BaseAnonCreds, anoncreds_holder: &impl BaseAnonCreds, institution_did: &Did, schema: &Schema, cred_def: &CredentialDef, rev_reg: Option<&RevocationRegistry>, ) -> String { // TODO: Inject credential_data from caller let credential_data = r#"{"address1": ["123 Main St"], "address2": ["Suite 3"], "city": ["Draper"], "state": ["UT"], "zip": ["84000"]}"#; let encoded_attributes = encode_attributes(credential_data).unwrap(); let offer = anoncreds_issuer .issuer_create_credential_offer(wallet_issuer, cred_def.get_cred_def_id()) .await .unwrap(); let (req, req_meta) = anoncreds_holder .prover_create_credential_req( wallet_holder, institution_did, serde_json::from_str(&serde_json::to_string(&offer).unwrap()).unwrap(), cred_def.get_cred_def_json().try_clone().unwrap(), &settings::DEFAULT_LINK_SECRET_ALIAS.to_string(), ) .await .unwrap(); let (rev_reg_def_json, rev_reg_id, tails_dir) = if let Some(rev_reg) = rev_reg { ( Some(serde_json::to_string(&rev_reg.get_rev_reg_def()).unwrap()), Some(rev_reg.rev_reg_id.clone()), Some(rev_reg.tails_dir.clone()), ) } else { (None, None, None) }; let (cred, _) = anoncreds_issuer .issuer_create_credential( wallet_issuer, offer, req, serde_json::from_str(&encoded_attributes).unwrap(), rev_reg_id .map(TryInto::try_into) .transpose() .unwrap() .as_ref(), tails_dir.as_deref().map(Path::new), ) .await .unwrap(); anoncreds_holder .prover_store_credential( wallet_holder, req_meta, cred, schema.schema_json.clone(), cred_def.get_cred_def_json().try_clone().unwrap(), rev_reg_def_json .as_deref() .map(serde_json::from_str) .transpose() .unwrap(), ) .await .unwrap() }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/utils/scenarios/proof_presentation.rs
aries/aries_vcx/tests/utils/scenarios/proof_presentation.rs
use std::collections::HashMap; use anoncreds_types::data_types::{ identifiers::{cred_def_id::CredentialDefinitionId, schema_id::SchemaId}, messages::{ cred_selection::{ RetrievedCredentialForReferent, RetrievedCredentials, SelectedCredentials, }, nonce::Nonce, pres_request::{ AttributeInfo, NonRevokedInterval, PredicateInfo, PresentationRequest, PresentationRequestPayload, }, }, }; use aries_vcx::{ common::primitives::{ credential_definition::CredentialDef, revocation_registry::RevocationRegistry, }, handlers::{ issuance::issuer::Issuer, proof_presentation::{prover::Prover, verifier::Verifier}, util::PresentationProposalData, }, protocols::proof_presentation::{ prover::state_machine::ProverState, verifier::{ state_machine::VerifierState, verification_status::PresentationVerificationStatus, }, }, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::{ base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite}, indy::pool::test_utils::get_temp_dir_path, }; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use log::info; use messages::{ msg_fields::protocols::{ present_proof::{ v1::{ ack::AckPresentationV1, present::PresentationV1, propose::ProposePresentationV1, request::RequestPresentationV1, PresentProofV1, }, PresentProof, }, report_problem::ProblemReport, }, AriesMessage, }; use serde_json::Value; use test_utils::constants::{DEFAULT_PROOF_NAME, TEST_TAILS_URL}; use super::requested_attrs_address; use crate::utils::{scenarios::requested_attr_objects, test_agent::TestAgent}; pub async fn create_proof_proposal( prover: &mut Prover, cred_def_id: &CredentialDefinitionId, ) -> ProposePresentationV1 { let attrs = requested_attr_objects(cred_def_id); let mut proposal_data = PresentationProposalData::default(); for attr in attrs.into_iter() { proposal_data.attributes.push(attr); } let proposal = prover .build_presentation_proposal(proposal_data) .await .unwrap(); assert_eq!(prover.get_state(), ProverState::PresentationProposalSent); proposal } pub async fn accept_proof_proposal( faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, verifier: &mut Verifier, presentation_proposal: ProposePresentationV1, ) -> RequestPresentationV1 { verifier .process_aries_msg( &faber.ledger_read, &faber.anoncreds, presentation_proposal.clone().into(), ) .await .unwrap(); assert_eq!( verifier.get_state(), VerifierState::PresentationProposalReceived ); let attrs = presentation_proposal .content .presentation_proposal .attributes .into_iter() .map(|attr| { ( attr.name.to_string(), AttributeInfo { name: Some(attr.name), ..AttributeInfo::default() }, ) }) .collect(); let presentation_request = PresentationRequestPayload::builder() .name("request-1".into()) .requested_attributes(attrs) .nonce(Nonce::new().unwrap()) .build(); verifier .set_presentation_request(presentation_request.into_v1(), None) .unwrap(); verifier.mark_presentation_request_sent().unwrap() } pub async fn reject_proof_proposal(presentation_proposal: &ProposePresentationV1) -> ProblemReport { let mut verifier = Verifier::create_from_proposal("1", presentation_proposal).unwrap(); assert_eq!( verifier.get_state(), VerifierState::PresentationProposalReceived ); let message = verifier .decline_presentation_proposal("I don't like Fabers") // :( .await .unwrap(); assert_eq!(verifier.get_state(), VerifierState::Failed); message } pub async fn receive_proof_proposal_rejection(prover: &mut Prover, rejection: ProblemReport) { assert_eq!(prover.get_state(), ProverState::PresentationProposalSent); prover.process_aries_msg(rejection.into()).await.unwrap(); assert_eq!(prover.get_state(), ProverState::Failed); } pub async fn create_proof_request_data( _faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, requested_attrs: HashMap<String, AttributeInfo>, requested_preds: HashMap<String, PredicateInfo>, revocation_interval: NonRevokedInterval, request_name: Option<&str>, ) -> PresentationRequest { PresentationRequestPayload::builder() .nonce(Nonce::new().unwrap()) .name(request_name.unwrap_or("name").to_string()) .requested_attributes(requested_attrs) .requested_predicates(requested_preds) .non_revoked(Some(revocation_interval)) .build() .into_v1() } pub async fn create_prover_from_request(presentation_request: RequestPresentationV1) -> Prover { Prover::create_from_request(DEFAULT_PROOF_NAME, presentation_request).unwrap() } pub async fn create_verifier_from_request_data( presentation_request_data: PresentationRequest, ) -> Verifier { let mut verifier = Verifier::create_from_request("1".to_string(), &presentation_request_data).unwrap(); verifier.mark_presentation_request_sent().unwrap(); verifier } pub async fn generate_and_send_proof( alice: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, prover: &mut Prover, selected_credentials: SelectedCredentials, ) -> Option<PresentationV1> { let thread_id = prover.get_thread_id().unwrap(); info!( "generate_and_send_proof >>> generating proof using selected credentials {selected_credentials:?}" ); prover .generate_presentation( &alice.wallet, &alice.ledger_read, &alice.anoncreds, selected_credentials, HashMap::new(), ) .await .unwrap(); assert_eq!(thread_id, prover.get_thread_id().unwrap()); if ProverState::PresentationPrepared == prover.get_state() { info!("generate_and_send_proof :: proof generated, sending proof"); let message = prover.mark_presentation_sent().unwrap(); info!("generate_and_send_proof :: proof sent"); assert_eq!(thread_id, prover.get_thread_id().unwrap()); let message = match message { AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Presentation( presentation, ))) => presentation, _ => panic!("Unexpected message type"), }; Some(message) } else { None } } pub async fn verify_proof( faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, verifier: &mut Verifier, presentation: PresentationV1, ) -> AckPresentationV1 { let msg = verifier .verify_presentation(&faber.ledger_read, &faber.anoncreds, presentation) .await .unwrap(); let msg = match msg { AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Ack(ack))) => ack, _ => panic!("Unexpected message type"), }; // TODO: Perhaps we should leave verification on the caller assert_eq!(verifier.get_state(), VerifierState::Finished); assert_eq!( verifier.get_verification_status(), PresentationVerificationStatus::Valid ); msg } pub async fn revoke_credential_and_publish_accumulator( faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, issuer_credential: &Issuer, rev_reg: &RevocationRegistry, ) { revoke_credential_local(faber, issuer_credential, &rev_reg.rev_reg_id).await; rev_reg .publish_local_revocations( &faber.wallet, &faber.anoncreds, &faber.ledger_write, &faber.institution_did, ) .await .unwrap(); } // todo: inline this pub async fn revoke_credential_local( faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, issuer_credential: &Issuer, _rev_reg_id: &str, ) { issuer_credential .revoke_credential_local(&faber.wallet, &faber.anoncreds, &faber.ledger_read) .await .unwrap(); } pub async fn rotate_rev_reg( faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, credential_def: &CredentialDef, rev_reg: &RevocationRegistry, ) -> RevocationRegistry { let mut rev_reg = RevocationRegistry::create( &faber.wallet, &faber.anoncreds, &faber.institution_did, credential_def.get_cred_def_id(), &rev_reg.get_tails_dir(), 10, 2, ) .await .unwrap(); rev_reg .publish_revocation_primitives(&faber.wallet, &faber.ledger_write, TEST_TAILS_URL) .await .unwrap(); rev_reg } pub async fn publish_revocation( institution: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, rev_reg: &RevocationRegistry, ) { rev_reg .publish_local_revocations( &institution.wallet, &institution.anoncreds, &institution.ledger_write, &institution.institution_did, ) .await .unwrap(); } pub async fn verifier_create_proof_and_send_request( institution: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, schema_id: &SchemaId, cred_def_id: &CredentialDefinitionId, request_name: Option<&str>, ) -> Verifier { let requested_attrs = requested_attrs_address( &institution.institution_did, schema_id, cred_def_id, None, None, ); let presentation_request_data = create_proof_request_data( institution, requested_attrs, Default::default(), Default::default(), request_name, ) .await; create_verifier_from_request_data(presentation_request_data).await } pub async fn prover_select_credentials( prover: &mut Prover, alice: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, presentation_request: RequestPresentationV1, preselected_credentials: Option<&str>, ) -> SelectedCredentials { prover .process_aries_msg(presentation_request.into()) .await .unwrap(); assert_eq!(prover.get_state(), ProverState::PresentationRequestReceived); let retrieved_credentials = prover .retrieve_credentials(&alice.wallet, &alice.anoncreds) .await .unwrap(); info!("prover_select_credentials >> retrieved_credentials: {retrieved_credentials:?}"); match preselected_credentials { Some(preselected_credentials) => { let credential_data = prover.presentation_request_data().unwrap(); match_preselected_credentials( &retrieved_credentials, preselected_credentials, &credential_data, true, ) } _ => retrieved_to_selected_credentials_simple(&retrieved_credentials, true), } } pub async fn prover_select_credentials_and_send_proof( alice: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, presentation_request: RequestPresentationV1, preselected_credentials: Option<&str>, ) -> PresentationV1 { let mut prover = create_prover_from_request(presentation_request.clone()).await; let selected_credentials = prover_select_credentials( &mut prover, alice, presentation_request, preselected_credentials, ) .await; info!( "Prover :: Retrieved credential converted to selected: {:?}", &selected_credentials ); let presentation = generate_and_send_proof(alice, &mut prover, selected_credentials) .await .unwrap(); assert_eq!(ProverState::PresentationSent, prover.get_state()); presentation } pub fn retrieved_to_selected_credentials_simple( retrieved_credentials: &RetrievedCredentials, with_tails: bool, ) -> SelectedCredentials { info!( "retrieved_to_selected_credentials_simple >>> retrieved matching credentials {retrieved_credentials:?}" ); let mut selected_credentials = SelectedCredentials::default(); for (referent, cred_array) in retrieved_credentials.credentials_by_referent.iter() { if !cred_array.is_empty() { let first_cred = cred_array[0].clone(); let tails_dir = with_tails.then_some(get_temp_dir_path().to_str().unwrap().to_owned()); selected_credentials.select_credential_for_referent_from_retrieved( referent.to_owned(), first_cred, tails_dir, ); } } selected_credentials } pub fn match_preselected_credentials( retrieved_credentials: &RetrievedCredentials, preselected_credentials: &str, credential_data: &str, with_tails: bool, ) -> SelectedCredentials { info!( "retrieved_to_selected_credentials_specific >>> retrieved matching credentials {retrieved_credentials:?}" ); let credential_data: Value = serde_json::from_str(credential_data).unwrap(); let preselected_credentials: Value = serde_json::from_str(preselected_credentials).unwrap(); let requested_attributes: &Value = &credential_data["requested_attributes"]; let mut selected_credentials = SelectedCredentials::default(); for (referent, cred_array) in retrieved_credentials.credentials_by_referent.iter() { let filtered: Vec<RetrievedCredentialForReferent> = cred_array .clone() .into_iter() .filter_map(|cred| { let attribute_name = requested_attributes[referent]["name"].as_str().unwrap(); let preselected_credential = preselected_credentials[attribute_name].as_str().unwrap(); if cred.cred_info.attributes[attribute_name] == preselected_credential { Some(cred) } else { None } }) .collect(); let first_cred = filtered[0].clone(); let tails_dir = with_tails.then_some(get_temp_dir_path().to_str().unwrap().to_owned()); selected_credentials.select_credential_for_referent_from_retrieved( referent.to_owned(), first_cred, tails_dir, ); } selected_credentials } pub async fn exchange_proof( institution: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, consumer: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, schema_id: &SchemaId, cred_def_id: &CredentialDefinitionId, request_name: Option<&str>, ) -> Verifier { let mut verifier = verifier_create_proof_and_send_request(institution, schema_id, cred_def_id, request_name) .await; let presentation = prover_select_credentials_and_send_proof( consumer, verifier.get_presentation_request_msg().unwrap(), None, ) .await; verifier .verify_presentation( &institution.ledger_read, &institution.anoncreds, presentation, ) .await .unwrap(); verifier }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/utils/scenarios/connection.rs
aries/aries_vcx/tests/utils/scenarios/connection.rs
use aries_vcx::{ handlers::{out_of_band::sender::OutOfBandSender, util::AnyInvitation}, protocols::{ connection::{invitee::any_invitation_into_did_doc, Connection, GenericConnection}, mediated_connection::pairwise_info::PairwiseInfo, }, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::{ AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite, }; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use messages::{ msg_fields::protocols::{ connection::invitation::{Invitation, InvitationContent}, out_of_band::{invitation::OobService, OobGoalCode}, }, msg_types::{ connection::{ConnectionType, ConnectionTypeV1}, Protocol, }, }; use uuid::Uuid; use crate::utils::test_agent::TestAgent; async fn establish_connection_from_invite( alice: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, invitation: AnyInvitation, inviter_pairwise_info: PairwiseInfo, ) -> (GenericConnection, GenericConnection) { let invitee_pairwise_info = PairwiseInfo::create(&alice.wallet).await.unwrap(); let invitee = Connection::new_invitee("".to_owned(), invitee_pairwise_info) .accept_invitation(&alice.ledger_read, invitation.clone()) .await .unwrap() .prepare_request("http://dummy.org".parse().unwrap(), vec![]) .await .unwrap(); let request = invitee.get_request().clone(); let inviter = Connection::new_inviter("".to_owned(), inviter_pairwise_info) .into_invited(invitation.id()) .handle_request( &faber.wallet, request, "http://dummy.org".parse().unwrap(), vec![], ) .await .unwrap(); let response = inviter.get_connection_response_msg(); let invitee = invitee .handle_response(&alice.wallet, response) .await .unwrap(); let ack = invitee.get_ack(); let inviter = inviter.acknowledge_connection(&ack.into()).unwrap(); (invitee.into(), inviter.into()) } pub async fn create_connections_via_oob_invite( alice: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, ) -> (GenericConnection, GenericConnection) { let oob_sender = OutOfBandSender::create() .set_label("test-label") .set_goal_code(OobGoalCode::P2PMessaging) .set_goal("To exchange message") .append_service(&OobService::Did(faber.institution_did.to_string())) .append_handshake_protocol(Protocol::ConnectionType(ConnectionType::V1( ConnectionTypeV1::new_v1_0(), ))) .unwrap(); let invitation = AnyInvitation::Oob(oob_sender.oob.clone()); let ddo = any_invitation_into_did_doc(&alice.ledger_read, &invitation) .await .unwrap(); // TODO: Create a key and write on ledger instead let inviter_pairwise_info = PairwiseInfo { pw_did: ddo.clone().id, pw_vk: ddo.recipient_keys().unwrap().first().unwrap().to_string(), }; establish_connection_from_invite(alice, faber, invitation, inviter_pairwise_info).await } pub async fn create_connections_via_public_invite( alice: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, ) -> (GenericConnection, GenericConnection) { let content = InvitationContent::builder_public() .label("faber".to_owned()) .did(faber.institution_did.to_string()) .build(); let public_invite = AnyInvitation::Con( Invitation::builder() .id("test_invite_id".to_owned()) .content(content) .build(), ); let ddo = any_invitation_into_did_doc(&alice.ledger_read, &public_invite) .await .unwrap(); // TODO: Create a key and write on ledger instead let inviter_pairwise_info = PairwiseInfo { pw_did: ddo.clone().id, pw_vk: ddo.recipient_keys().unwrap().first().unwrap().to_string(), }; establish_connection_from_invite(alice, faber, public_invite.clone(), inviter_pairwise_info) .await } pub async fn create_connections_via_pairwise_invite( alice: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, ) -> (GenericConnection, GenericConnection) { let inviter_pairwise_info = PairwiseInfo::create(&faber.wallet).await.unwrap(); let invite = { let id = Uuid::new_v4().to_string(); let content = InvitationContent::builder_pairwise() .label("".to_string()) .recipient_keys(vec![inviter_pairwise_info.pw_vk.clone()]) .service_endpoint("http://dummy.org".parse().unwrap()) .build(); let invite = Invitation::builder().id(id).content(content).build(); AnyInvitation::Con(invite) }; establish_connection_from_invite(alice, faber, invite, inviter_pairwise_info).await }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/utils/scenarios/mod.rs
aries/aries_vcx/tests/utils/scenarios/mod.rs
mod connection; mod credential_issuance; mod data; mod proof_presentation; pub use connection::*; pub use credential_issuance::*; pub use data::*; pub use proof_presentation::*;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/utils/scenarios/data.rs
aries/aries_vcx/tests/utils/scenarios/data.rs
use std::collections::HashMap; use anoncreds_types::{ data_types::{ identifiers::{cred_def_id::CredentialDefinitionId, schema_id::SchemaId}, messages::pres_request::{AttributeInfo, NonRevokedInterval}, }, utils::query::Query, }; use did_parser_nom::Did; use messages::{ misc::MimeType, msg_fields::protocols::{ cred_issuance::{ common::CredentialAttr, v1::{ propose_credential::{ProposeCredentialV1, ProposeCredentialV1Content}, CredentialPreviewV1, }, }, present_proof::v1::propose::PresentationAttr, }, }; use serde_json::{json, Value}; pub fn attr_names_address() -> (String, String, String, String, String) { let address1 = "Address1".to_string(); let address2 = "address2".to_string(); let city = "CITY".to_string(); let state = "State".to_string(); let zip = "zip".to_string(); (address1, address2, city, state, zip) } pub fn attr_names_address_list() -> Vec<String> { let (address1, address2, city, state, zip) = attr_names_address(); vec![address1, address2, city, state, zip] } pub fn requested_attrs_address( did: &Did, schema_id: &SchemaId, cred_def_id: &CredentialDefinitionId, from: Option<u64>, to: Option<u64>, ) -> HashMap<String, AttributeInfo> { let restrictions = Query::And(vec![ Query::Eq("issuer_did".to_string(), did.to_string()), Query::Eq("schema_id".to_string(), schema_id.to_string()), Query::Eq("cred_def_id".to_string(), cred_def_id.to_string()), ]); attr_names_address_list() .into_iter() .map(|name| { ( format!("{name}_1"), AttributeInfo { name: Some(name), restrictions: Some(restrictions.to_owned()), non_revoked: Some(NonRevokedInterval::new(from, to)), ..Default::default() }, ) }) .collect() } pub(super) fn requested_attr_objects( cred_def_id: &CredentialDefinitionId, ) -> Vec<PresentationAttr> { credential_data_address_1() .as_object() .unwrap() .iter() .map(|(key, value)| { PresentationAttr::builder() .name(key.to_string()) .cred_def_id(cred_def_id.to_string()) .value(value.to_string()) .build() }) .collect() } pub fn create_credential_proposal( schema_id: &SchemaId, cred_def_id: &CredentialDefinitionId, comment: &str, ) -> ProposeCredentialV1 { let attrs = credential_data_address_1() .as_object() .unwrap() .iter() .map(|(key, value)| { CredentialAttr::builder() .name(key.to_string()) .value(value.to_string()) .mime_type(MimeType::Plain) .build() }) .collect(); let content = ProposeCredentialV1Content::builder() .credential_proposal(CredentialPreviewV1::new(attrs)) .schema_id(schema_id.to_string()) .cred_def_id(cred_def_id.to_string()) .comment(comment.to_owned()) .build(); ProposeCredentialV1::builder() .id("test".to_owned()) .content(content) .build() } pub fn credential_data_address_1() -> Value { let (address1, address2, city, state, zip) = attr_names_address(); json!({address1: "123 Main St", address2: "Suite 3", city: "Draper", state: "UT", zip: "84000"}) } pub fn credential_data_address_2() -> Value { let (address1, address2, city, state, zip) = attr_names_address(); json!({address1: "321 Test St", address2: "Suite Foo", city: "Kickapoo", state: "LU", zip: "87210"}) } pub fn credential_data_address_3() -> Value { let (address1, address2, city, state, zip) = attr_names_address(); json!({address1: "007 Mock St", address2: "Yes", city: "None", state: "KO", zip: "11111"}) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/tests/utils/scenarios/credential_issuance.rs
aries/aries_vcx/tests/utils/scenarios/credential_issuance.rs
use std::{thread, time::Duration}; use anoncreds_types::data_types::identifiers::{ cred_def_id::CredentialDefinitionId, schema_id::SchemaId, }; use aries_vcx::{ common::primitives::{ credential_definition::CredentialDef, credential_schema::Schema, revocation_registry::RevocationRegistry, }, handlers::{ issuance::{holder::Holder, issuer::Issuer}, util::OfferInfo, }, protocols::{ issuance::{holder::state_machine::HolderState, issuer::state_machine::IssuerState}, mediated_connection::pairwise_info::PairwiseInfo, }, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::{ AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite, }; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use did_parser_nom::Did; use messages::msg_fields::protocols::{ cred_issuance::v1::{ offer_credential::OfferCredentialV1, propose_credential::ProposeCredentialV1, request_credential::RequestCredentialV1, }, report_problem::ProblemReport, }; use serde_json::json; use test_utils::constants::TEST_TAILS_URL; use super::{attr_names_address_list, create_credential_proposal, credential_data_address_1}; use crate::utils::{ create_and_publish_test_rev_reg, create_and_write_test_cred_def, create_and_write_test_schema, test_agent::TestAgent, }; pub async fn create_address_schema_creddef_revreg( wallet: &impl BaseWallet, ledger_read: &(impl IndyLedgerRead + AnoncredsLedgerRead), ledger_write: &(impl IndyLedgerWrite + AnoncredsLedgerWrite), anoncreds: &impl BaseAnonCreds, institution_did: &Did, ) -> (Schema, CredentialDef, RevocationRegistry) { let schema = create_and_write_test_schema( wallet, anoncreds, ledger_write, institution_did, &json!(attr_names_address_list()).to_string(), ) .await; let cred_def = create_and_write_test_cred_def( wallet, anoncreds, ledger_read, ledger_write, institution_did, &schema.schema_id, true, ) .await; let rev_reg = create_and_publish_test_rev_reg( wallet, anoncreds, ledger_write, institution_did, cred_def.get_cred_def_id(), ) .await; tokio::time::sleep(Duration::from_millis(500)).await; (schema, cred_def, rev_reg) } pub fn create_holder_from_proposal(proposal: ProposeCredentialV1) -> Holder { let holder = Holder::create_with_proposal("TEST_CREDENTIAL", proposal).unwrap(); assert_eq!(HolderState::ProposalSet, holder.get_state()); holder } pub fn create_issuer_from_proposal(proposal: ProposeCredentialV1) -> Issuer { let issuer = Issuer::create_from_proposal("TEST_CREDENTIAL", &proposal).unwrap(); assert_eq!(IssuerState::ProposalReceived, issuer.get_state()); assert_eq!(proposal, issuer.get_proposal().unwrap()); issuer } pub async fn accept_credential_proposal( faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, issuer: &mut Issuer, cred_proposal: ProposeCredentialV1, rev_reg_id: Option<String>, tails_dir: Option<String>, ) -> OfferCredentialV1 { let offer_info = OfferInfo { credential_json: json!(cred_proposal.content.credential_proposal.attributes).to_string(), cred_def_id: cred_proposal.content.cred_def_id.try_into().unwrap(), rev_reg_id, tails_file: tails_dir, }; issuer .build_credential_offer_msg( &faber.wallet, &faber.anoncreds, offer_info, Some("comment".into()), ) .await .unwrap(); issuer.get_credential_offer().unwrap() } pub async fn accept_offer( alice: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, cred_offer: OfferCredentialV1, holder: &mut Holder, ) -> RequestCredentialV1 { // TODO: Replace with message-specific handler holder .process_aries_msg( &alice.wallet, &alice.ledger_read, &alice.anoncreds, cred_offer.into(), ) .await .unwrap(); assert_eq!(HolderState::OfferReceived, holder.get_state()); assert!(holder.get_offer().is_ok()); holder .prepare_credential_request( &alice.wallet, &alice.ledger_read, &alice.anoncreds, PairwiseInfo::create(&alice.wallet) .await .unwrap() .pw_did .parse() .unwrap(), ) .await .unwrap(); assert_eq!(HolderState::RequestSet, holder.get_state()); holder.get_msg_credential_request().unwrap() } pub async fn decline_offer( alice: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, cred_offer: OfferCredentialV1, holder: &mut Holder, ) -> ProblemReport { // TODO: Replace with message-specific handler holder .process_aries_msg( &alice.wallet, &alice.ledger_read, &alice.anoncreds, cred_offer.into(), ) .await .unwrap(); assert_eq!(HolderState::OfferReceived, holder.get_state()); let problem_report = holder.decline_offer(Some("Have a nice day")).unwrap(); assert_eq!(HolderState::Failed, holder.get_state()); problem_report } pub async fn send_credential( alice: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, issuer_credential: &mut Issuer, holder_credential: &mut Holder, cred_request: RequestCredentialV1, revokable: bool, ) { let thread_id = issuer_credential.get_thread_id().unwrap(); assert_eq!(IssuerState::OfferSet, issuer_credential.get_state()); assert!(!issuer_credential.is_revokable()); issuer_credential .receive_request(cred_request) .await .unwrap(); assert_eq!(IssuerState::RequestReceived, issuer_credential.get_state()); assert!(!issuer_credential.is_revokable()); assert_eq!(thread_id, issuer_credential.get_thread_id().unwrap()); issuer_credential .build_credential(&faber.wallet, &faber.anoncreds) .await .unwrap(); let credential = issuer_credential.get_msg_issue_credential().unwrap(); assert_eq!(thread_id, issuer_credential.get_thread_id().unwrap()); assert_eq!(thread_id, holder_credential.get_thread_id().unwrap()); assert_eq!( holder_credential .is_revokable(&alice.ledger_read) .await .unwrap(), revokable ); holder_credential .process_credential( &alice.wallet, &alice.ledger_read, &alice.anoncreds, credential, ) .await .unwrap(); assert_eq!(HolderState::Finished, holder_credential.get_state()); assert_eq!( holder_credential .is_revokable(&alice.ledger_read) .await .unwrap(), revokable ); assert_eq!(thread_id, holder_credential.get_thread_id().unwrap()); if revokable { thread::sleep(Duration::from_millis(500)); assert_eq!( holder_credential.get_tails_location().unwrap(), TEST_TAILS_URL.to_string() ); } } pub async fn issue_address_credential( consumer: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, institution: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, ) -> (Schema, CredentialDef, RevocationRegistry, Issuer) { let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( &institution.wallet, &institution.ledger_read, &institution.ledger_write, &institution.anoncreds, &institution.institution_did, ) .await; let issuer = exchange_credential( consumer, institution, credential_data_address_1().to_string(), &cred_def, &rev_reg, None, ) .await; (schema, cred_def, rev_reg, issuer) } pub async fn exchange_credential( consumer: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, institution: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, credential_data: String, cred_def: &CredentialDef, rev_reg: &RevocationRegistry, comment: Option<&str>, ) -> Issuer { let mut issuer = create_credential_offer(institution, cred_def, rev_reg, &credential_data, comment).await; let mut holder_credential = create_credential_request(consumer, issuer.get_credential_offer().unwrap()).await; let cred_request = holder_credential.get_msg_credential_request().unwrap(); send_credential( consumer, institution, &mut issuer, &mut holder_credential, cred_request, true, ) .await; assert!(!holder_credential .is_revoked(&consumer.wallet, &consumer.ledger_read, &consumer.anoncreds) .await .unwrap()); issuer } pub async fn exchange_credential_with_proposal( consumer: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, institution: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, schema_id: &SchemaId, cred_def_id: &CredentialDefinitionId, rev_reg_id: Option<String>, tails_dir: Option<String>, comment: &str, ) -> (Holder, Issuer) { let cred_proposal = create_credential_proposal(schema_id, cred_def_id, comment); let mut holder = create_holder_from_proposal(cred_proposal.clone()); let mut issuer = create_issuer_from_proposal(cred_proposal.clone()); let cred_offer = accept_credential_proposal( institution, &mut issuer, cred_proposal, rev_reg_id, tails_dir, ) .await; let cred_request = accept_offer(consumer, cred_offer, &mut holder).await; send_credential( consumer, institution, &mut issuer, &mut holder, cred_request, true, ) .await; (holder, issuer) } async fn create_credential_offer( faber: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, cred_def: &CredentialDef, rev_reg: &RevocationRegistry, credential_json: &str, comment: Option<&str>, ) -> Issuer { let offer_info = OfferInfo { credential_json: credential_json.to_string(), cred_def_id: cred_def.get_cred_def_id().to_owned(), rev_reg_id: Some(rev_reg.get_rev_reg_id()), tails_file: Some(rev_reg.get_tails_dir()), }; let mut issuer = Issuer::create("1").unwrap(); issuer .build_credential_offer_msg( &faber.wallet, &faber.anoncreds, offer_info, comment.map(String::from), ) .await .unwrap(); issuer } async fn create_credential_request( alice: &mut TestAgent< impl IndyLedgerRead + AnoncredsLedgerRead, impl IndyLedgerWrite + AnoncredsLedgerWrite, impl BaseAnonCreds, impl BaseWallet, >, cred_offer: OfferCredentialV1, ) -> Holder { let mut holder = Holder::create_from_offer("TEST_CREDENTIAL", cred_offer).unwrap(); assert_eq!(HolderState::OfferReceived, holder.get_state()); holder .prepare_credential_request( &alice.wallet, &alice.ledger_read, &alice.anoncreds, PairwiseInfo::create(&alice.wallet) .await .unwrap() .pw_did .parse() .unwrap(), ) .await .unwrap(); holder }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/lib.rs
aries/messages/src/lib.rs
#![allow(clippy::or_fun_call)] #![allow(clippy::module_inception)] #![allow(clippy::derive_partial_eq_without_eq)] #![allow(clippy::new_without_default)] #![allow(clippy::inherent_to_string)] #![allow(clippy::large_enum_variant)] pub mod decorators; pub mod error; pub mod misc; pub mod msg_fields; pub mod msg_parts; pub mod msg_types; use derive_more::From; use display_as_json::Display; use misc::utils; use msg_fields::protocols::{ cred_issuance::{v1::CredentialIssuanceV1, v2::CredentialIssuanceV2, CredentialIssuance}, did_exchange::{v1_0::DidExchangeV1_0, v1_1::DidExchangeV1_1, DidExchange}, pickup::Pickup, present_proof::{v2::PresentProofV2, PresentProof}, }; use msg_types::{ cred_issuance::CredentialIssuanceType, present_proof::PresentProofType, protocols::did_exchange::{DidExchangeType, DidExchangeTypeV1}, report_problem::ReportProblemTypeV1_0, routing::RoutingTypeV1_0, MsgWithType, }; use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; use crate::{ msg_fields::{ protocols::{ basic_message::BasicMessage, connection::Connection, coordinate_mediation::CoordinateMediation, discover_features::DiscoverFeatures, notification::Notification, out_of_band::OutOfBand, present_proof::v1::PresentProofV1, report_problem::ProblemReport, revocation::Revocation, routing::Forward, trust_ping::TrustPing, }, traits::DelayedSerde, }, msg_types::{ basic_message::BasicMessageTypeV1_0, protocols::{ basic_message::{BasicMessageType, BasicMessageTypeV1}, report_problem::{ReportProblemType, ReportProblemTypeV1}, routing::{RoutingType, RoutingTypeV1}, }, MessageType, Protocol, }, }; /// Enum that can represent any message of the implemented protocols. /// /// It abstracts away the `@type` field and uses it to determine how /// to deserialize the input into the correct message type. /// /// It also automatically appends the correct `@type` field when serializing /// a message. #[derive(Clone, Debug, Display, From, PartialEq)] pub enum AriesMessage { Routing(Forward), Connection(Connection), Revocation(Revocation), CredentialIssuance(CredentialIssuance), ReportProblem(ProblemReport), PresentProof(PresentProof), TrustPing(TrustPing), DiscoverFeatures(DiscoverFeatures), BasicMessage(BasicMessage), OutOfBand(OutOfBand), Notification(Notification), Pickup(Pickup), CoordinateMediation(CoordinateMediation), DidExchange(DidExchange), } impl DelayedSerde for AriesMessage { type MsgType<'a> = MessageType<'a>; /// Match on every protocol variant and either: /// - call the equivalent type's [`DelayedSerde::delayed_deserialize`] /// - handle the message kind and directly deserialize to the proper type /// /// The second option is employed simply because some protocols only have one message /// and one version (at least right now) and there's no point in crowding the codebase /// with one variant enums or the like. fn delayed_deserialize<'de, D>( msg_type: Self::MsgType<'de>, deserializer: D, ) -> Result<Self, D::Error> where D: Deserializer<'de>, { let MessageType { protocol, kind: kind_str, } = msg_type; match protocol { Protocol::RoutingType(msg_type) => { let kind = match msg_type { RoutingType::V1(RoutingTypeV1::V1_0(kind)) => kind.kind_from_str(kind_str), }; match kind.map_err(D::Error::custom)? { RoutingTypeV1_0::Forward => Forward::deserialize(deserializer).map(From::from), } } Protocol::ConnectionType(msg_type) => { Connection::delayed_deserialize((msg_type, kind_str), deserializer).map(From::from) } Protocol::SignatureType(_) => Err(utils::not_standalone_msg::<D>(kind_str)), Protocol::RevocationType(msg_type) => { Revocation::delayed_deserialize((msg_type, kind_str), deserializer).map(From::from) } Protocol::CredentialIssuanceType(CredentialIssuanceType::V1(msg_type)) => { CredentialIssuanceV1::delayed_deserialize( (CredentialIssuanceType::V1(msg_type), kind_str), deserializer, ) .map(|x| AriesMessage::from(CredentialIssuance::V1(x))) } Protocol::CredentialIssuanceType(CredentialIssuanceType::V2(msg_type)) => { CredentialIssuanceV2::delayed_deserialize( (CredentialIssuanceType::V2(msg_type), kind_str), deserializer, ) .map(|x| AriesMessage::from(CredentialIssuance::V2(x))) } Protocol::ReportProblemType(msg_type) => { let kind = match msg_type { ReportProblemType::V1(ReportProblemTypeV1::V1_0(kind)) => { kind.kind_from_str(kind_str) } }; match kind.map_err(D::Error::custom)? { ReportProblemTypeV1_0::ProblemReport => { ProblemReport::deserialize(deserializer).map(From::from) } } } Protocol::PresentProofType(PresentProofType::V1(msg_type)) => { PresentProofV1::delayed_deserialize( (PresentProofType::V1(msg_type), kind_str), deserializer, ) .map(|x| AriesMessage::from(PresentProof::V1(x))) } Protocol::PresentProofType(PresentProofType::V2(msg_type)) => { PresentProofV2::delayed_deserialize( (PresentProofType::V2(msg_type), kind_str), deserializer, ) .map(|x| AriesMessage::from(PresentProof::V2(x))) } Protocol::TrustPingType(msg_type) => { TrustPing::delayed_deserialize((msg_type, kind_str), deserializer).map(From::from) } Protocol::DiscoverFeaturesType(msg_type) => { DiscoverFeatures::delayed_deserialize((msg_type, kind_str), deserializer) .map(From::from) } Protocol::BasicMessageType(msg_type) => { let kind = match msg_type { BasicMessageType::V1(BasicMessageTypeV1::V1_0(kind)) => { kind.kind_from_str(kind_str) } }; match kind.map_err(D::Error::custom)? { BasicMessageTypeV1_0::Message => { BasicMessage::deserialize(deserializer).map(From::from) } } } Protocol::OutOfBandType(msg_type) => { OutOfBand::delayed_deserialize((msg_type, kind_str), deserializer).map(From::from) } Protocol::NotificationType(msg_type) => { Notification::delayed_deserialize((msg_type, kind_str), deserializer) .map(From::from) } Protocol::PickupType(msg_type) => { Pickup::delayed_deserialize((msg_type, kind_str), deserializer).map(From::from) } Protocol::CoordinateMediationType(msg_type) => { CoordinateMediation::delayed_deserialize((msg_type, kind_str), deserializer) .map(From::from) } Protocol::DidExchangeType(DidExchangeType::V1(DidExchangeTypeV1::V1_0(msg_type))) => { DidExchangeV1_0::delayed_deserialize((msg_type, kind_str), deserializer) .map(|x| AriesMessage::from(DidExchange::V1_0(x))) } Protocol::DidExchangeType(DidExchangeType::V1(DidExchangeTypeV1::V1_1(msg_type))) => { DidExchangeV1_1::delayed_deserialize((msg_type, kind_str), deserializer) .map(|x| AriesMessage::from(DidExchange::V1_1(x))) } } } fn delayed_serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { Self::Routing(v) => MsgWithType::from(v).serialize(serializer), Self::Connection(v) => v.delayed_serialize(serializer), Self::Revocation(v) => v.delayed_serialize(serializer), Self::CredentialIssuance(CredentialIssuance::V1(v)) => v.delayed_serialize(serializer), Self::CredentialIssuance(CredentialIssuance::V2(v)) => v.delayed_serialize(serializer), Self::ReportProblem(v) => MsgWithType::from(v).serialize(serializer), Self::PresentProof(PresentProof::V1(v)) => v.delayed_serialize(serializer), Self::PresentProof(PresentProof::V2(v)) => v.delayed_serialize(serializer), Self::TrustPing(v) => v.delayed_serialize(serializer), Self::DiscoverFeatures(v) => v.delayed_serialize(serializer), Self::BasicMessage(v) => MsgWithType::from(v).serialize(serializer), Self::OutOfBand(v) => v.delayed_serialize(serializer), Self::Notification(v) => v.delayed_serialize(serializer), Self::Pickup(v) => v.delayed_serialize(serializer), Self::CoordinateMediation(v) => v.delayed_serialize(serializer), Self::DidExchange(DidExchange::V1_0(v)) => v.delayed_serialize(serializer), Self::DidExchange(DidExchange::V1_1(v)) => v.delayed_serialize(serializer), } } } /// Custom [`Deserialize`] impl for [`AriesMessage`] to use the `@type` as internal tag, /// but deserialize it to a [`MessageType`]. /// /// For readability, the [`MessageType`] matching is done in the /// [`DelayedSerde::delayed_deserialize`] method. impl<'de> Deserialize<'de> for AriesMessage { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { use std::borrow::Cow; /// Helper that will only deserialize the message type and buffer the /// rest of the fields (borrowing where possible). #[derive(Deserialize)] struct TypeAndContent<'a> { #[serde(rename = "@type")] #[serde(borrow)] msg_type: Cow<'a, str>, #[serde(flatten)] content: serde_value::Value, } let TypeAndContent { msg_type, content } = TypeAndContent::deserialize(deserializer)?; // Parse the message type field to get the protocol and message kind let msg_type = msg_type.as_ref().try_into().map_err(D::Error::custom)?; // The content is serde_value::Value, which can be deserialized using ValueDeserializer let deserializer = serde_value::ValueDeserializer::<D::Error>::new(content); Self::delayed_deserialize(msg_type, deserializer) } } impl Serialize for AriesMessage { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.delayed_serialize(serializer) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/error.rs
aries/messages/src/error.rs
use std::num::ParseIntError; use thiserror::Error as ThisError; pub type MsgTypeResult<T> = Result<T, MsgTypeError>; #[derive(Debug, ThisError)] pub enum MsgTypeError { #[error("Unknown message type prefix: {0}")] UnknownPrefix(String), #[error("Unknown message kind: {0}")] UnknownMsgKind(String), #[error("Unsupported protocol minor version: {0}")] UnsupportedMinorVer(u8), #[error("Unsupported protocol major version: {0}")] UnsupportedMajorVer(u8), #[error("Unknown protocol name: {0}")] UnknownProtocol(String), #[error("Error parsing version: {0}")] InvalidVersion(#[from] ParseIntError), #[error("No {0} found in the message type")] PartNotFound(&'static str), } impl MsgTypeError { pub fn unknown_prefix(prefix: String) -> Self { Self::UnknownPrefix(prefix) } pub fn unknown_kind(kind: String) -> Self { Self::UnknownMsgKind(kind) } pub fn minor_ver_err(minor: u8) -> Self { Self::UnsupportedMinorVer(minor) } pub fn major_ver_err(major: u8) -> Self { Self::UnsupportedMajorVer(major) } pub fn unknown_protocol(name: String) -> Self { Self::UnknownProtocol(name) } pub fn not_found(part: &'static str) -> Self { Self::PartNotFound(part) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/msg_parts.rs
aries/messages/src/msg_parts.rs
use display_as_json::Display; use serde::{Deserialize, Serialize}; use shared::misc::serde_ignored::SerdeIgnored as NoDecorators; use typed_builder::TypedBuilder; /// Struct representing a complete message (apart from the `@type` field) as defined in a protocol /// RFC. The purpose of this type is to allow decomposition of certain message parts so they can be /// independently processed, if needed. /// /// This allows separating, for example, the protocol specific fields from the decorators /// used in a message without decomposing the entire message into individual fields. /// /// Note that there's no hard rule about what field goes where. There are decorators, such as /// `~attach` used in some messages that are in fact part of the protocol itself and are /// instrumental to the message processing, not an appendix to the message (such as `~thread` or /// `~timing`). #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder, Display)] #[builder(build_method(vis = "", name = __build))] pub struct MsgParts<C, D = NoDecorators> { /// All standalone messages have an `id` field. #[serde(rename = "@id")] pub id: String, /// The protocol specific fields provided as a standalone type. #[serde(flatten)] pub content: C, /// The decorators this message uses, provided as a standalone type. #[serde(flatten)] pub decorators: D, } /// Allows building message without decorators being specified. #[allow(dead_code, non_camel_case_types, missing_docs)] impl<C, D> MsgPartsBuilder<C, D, ((String,), (), (D,))> where C: Default, { pub fn build<T>(self) -> T where MsgParts<C, D>: Into<T>, { self.content(Default::default()).__build().into() } } /// Allows building message without decorators being specified. #[allow(dead_code, non_camel_case_types, missing_docs)] impl<C, D> MsgPartsBuilder<C, D, ((String,), (C,), ())> where D: Default, { pub fn build<T>(self) -> T where MsgParts<C, D>: Into<T>, { self.decorators(Default::default()).__build().into() } } #[allow(dead_code, non_camel_case_types, missing_docs)] impl<C, D> MsgPartsBuilder<C, D, ((String,), (C,), (D,))> { pub fn build<T>(self) -> T where MsgParts<C, D>: Into<T>, { self.__build().into() } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/decorators/please_ack.rs
aries/messages/src/decorators/please_ack.rs
use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; /// Struct representing the `~please_ack` decorators from its [RFC](<https://github.com/decentralized-identity/aries-rfcs/blob/main/features/0317-please-ack/README.md>). #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, TypedBuilder)] pub struct PleaseAck { // This is wrong, but necessary for backwards compatibility. // Per the [RFC](<https://github.com/decentralized-identity/aries-rfcs/blob/main/features/0317-please-ack/README.md#on>) // this is a *required* array. // // However, the entire field was previously NOT serialized if it was empty, // resulting in something like '"~please_ack": null' instead of '"~please_ack": {"on": []}'. // // One could argue that the field could be treated even better, so that an empty array would be // incorrect. Perhaps using an enum altogether (if the values become somewhat stable) or // ordering the array might be of interest, so that processing happens in a specific order. #[serde(default)] pub on: Vec<AckOn>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum AckOn { Receipt, Outcome, } #[cfg(test)] #[allow(clippy::field_reassign_with_default)] pub mod tests { use serde_json::json; use super::*; use crate::misc::test_utils; pub fn make_minimal_please_ack() -> PleaseAck { let on = vec![AckOn::Receipt, AckOn::Outcome]; PleaseAck::builder().on(on).build() } #[test] fn test_minimal_please_ack() { let please_ack = make_minimal_please_ack(); let expected = json!({ "on": please_ack.on }); test_utils::test_serde(please_ack, expected); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/decorators/attachment.rs
aries/messages/src/decorators/attachment.rs
use std::collections::HashMap; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use serde_json::Value; use shared::maybe_known::MaybeKnown; use typed_builder::TypedBuilder; use url::Url; use crate::misc::MimeType; /// Struct representing the `~attach` decorator from its [RFC](<https://github.com/decentralized-identity/aries-rfcs/blob/main/concepts/0017-attachments/README.md>). #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TypedBuilder)] #[serde(rename_all = "snake_case")] pub struct Attachment { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none", rename = "@id")] pub id: Option<String>, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub filename: Option<String>, // mimetype wrapped in MaybeKnown to handle any deserialization from any string. // other agents may be using mimetypes that this crate is not immediately aware of, but // we should not fail to deserialize as a result. #[builder(default, setter(transform = |x: MimeType| Some(MaybeKnown::Known(x))))] #[serde(skip_serializing_if = "Option::is_none", rename = "mime-type")] pub mime_type: Option<MaybeKnown<MimeType, String>>, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub lastmod_time: Option<DateTime<Utc>>, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub byte_count: Option<u64>, pub data: AttachmentData, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, TypedBuilder)] pub struct AttachmentData { // There probably is a better type for this??? #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub jws: Option<HashMap<String, Value>>, // Better type for this as well? #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub sha256: Option<String>, #[serde(flatten)] pub content: AttachmentType, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum AttachmentType { // Base64 encoded string Base64(String), // A valid JSON value Json(Value), // An URL list Links(Vec<Url>), } #[cfg(test)] #[allow(clippy::field_reassign_with_default)] pub mod tests { use serde_json::json; use super::*; use crate::misc::test_utils; pub fn make_minimal_attachment() -> Attachment { let data = json!({ "field": "test_json_data" }); let content = AttachmentType::Json(data); let attach_data = AttachmentData::builder().content(content).build(); Attachment::builder().data(attach_data).build() } pub fn make_extended_attachment() -> Attachment { let data = json!({ "field": "test_json_data" }); let content = AttachmentType::Json(data); let attach_data = AttachmentData::builder().content(content).build(); Attachment::builder() .data(attach_data) .id("test_id".to_owned()) .description("test_description".to_owned()) .filename("test_filename".to_owned()) .mime_type(MimeType::Json) .lastmod_time(DateTime::<Utc>::default()) .byte_count(64) .build() } #[test] fn test_base64_attach_type() { let data = "test_base64_str".to_owned(); let expected = json!({ "base64": data }); let attach_type = AttachmentType::Base64(data); test_utils::test_serde(attach_type, expected); } #[test] fn test_json_attach_type() { let data = json!({ "field": "test_json_data" }); let expected = json!({ "json": data }); let attach_type = AttachmentType::Json(data); test_utils::test_serde(attach_type, expected); } #[test] fn test_links_attach_type() { let data = vec!["https://dummy.dummy/dummy".parse().unwrap()]; let expected = json!({ "links": data }); let attach_type = AttachmentType::Links(data); test_utils::test_serde(attach_type, expected); } #[test] fn test_minimal_attach_data() { let data = json!({ "field": "test_json_data" }); let expected = json!({ "json": data }); let content = AttachmentType::Json(data); let attach_data = AttachmentData::builder().content(content).build(); test_utils::test_serde(attach_data, expected); } #[test] fn test_extended_attach_data() { let jws = json!({ "jws": "test_jws".to_owned()}); let sha256 = "test_sha256".to_owned(); let data = json!({ "field": "test_json_data" }); let expected = json!({ "json": data, "jws": jws, "sha256": sha256 }); let mut jws = HashMap::new(); jws.insert("jws".to_owned(), Value::String("test_jws".to_owned())); let content = AttachmentType::Json(data); let attach_data = AttachmentData::builder() .content(content) .jws(jws) .sha256(sha256) .build(); test_utils::test_serde(attach_data, expected); } #[test] fn test_minimal_attachment() { let attachment = make_minimal_attachment(); let expected = json!({ "data": attachment.data }); test_utils::test_serde(attachment, expected); } #[test] fn test_extended_attachment() { let attachment = make_extended_attachment(); let expected = json!({ "@id": attachment.id, "description": attachment.description, "filename": attachment.filename, "mime-type": attachment.mime_type, "lastmod_time": attachment.lastmod_time, "byte_count": attachment.byte_count, "data": attachment.data }); test_utils::test_serde(attachment, expected); } #[test] fn test_extended_attachment_with_unknown_mime() { let mut attachment = make_extended_attachment(); attachment.mime_type = Some(MaybeKnown::Unknown(String::from("unknown/vcx"))); let expected = json!({ "@id": attachment.id, "description": attachment.description, "filename": attachment.filename, "mime-type": "unknown/vcx", "lastmod_time": attachment.lastmod_time, "byte_count": attachment.byte_count, "data": attachment.data }); test_utils::test_serde(attachment, expected); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/decorators/localization.rs
aries/messages/src/decorators/localization.rs
use std::collections::HashMap; use isolang::Language; use serde::{ ser::{Error, SerializeMap}, Deserialize, Serialize, Serializer, }; use shared::misc::utils::CowStr; use typed_builder::TypedBuilder; use url::Url; /// Struct representing the `~l10n` decorator, when it decorates the entire message, from its [RFC](<https://github.com/decentralized-identity/aries-rfcs/blob/main/features/0043-l10n/README.md>). #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, TypedBuilder)] pub struct MsgLocalization { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub catalogs: Option<Vec<Url>>, // Might just be obsolete, but appears in <https://github.com/decentralized-identity/aries-rfcs/blob/main/features/0043-l10n/README.md> // Is details and locales the same thing? #[builder(default, setter(strip_option))] #[serde(alias = "details")] #[serde(skip_serializing_if = "Option::is_none")] pub locales: Option<HashMap<Locale, Vec<String>>>, } /// Struct representing the `~l10n` decorator, when it decorates a single field, from its [RFC](<https://github.com/decentralized-identity/aries-rfcs/blob/main/features/0043-l10n/README.md>). #[derive(Debug, Clone, Deserialize, Default, PartialEq, TypedBuilder)] pub struct FieldLocalization { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub locale: Option<Locale>, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub catalogs: Option<Vec<Url>>, #[builder(default)] #[serde(flatten)] #[serde(skip_serializing_if = "HashMap::is_empty")] pub translations: HashMap<Locale, String>, } /// Manual implementation because `serde_json` does not support /// non-string map keys. impl Serialize for FieldLocalization { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = Serializer::serialize_map(serializer, None)?; if !Option::is_none(&self.code) { state.serialize_entry("code", &self.code)?; } if !Option::is_none(&self.locale) { state.serialize_entry("locale", &self.locale)?; } if !Option::is_none(&self.catalogs) { state.serialize_entry("catalogs", &self.catalogs)?; } if !HashMap::is_empty(&self.translations) { for (key, value) in &self.translations { let key = <&str>::try_from(key).map_err(S::Error::custom)?; state.serialize_entry(key, value)?; } } SerializeMap::end(state) } } /// Represents an ISO 639-1, two letter, language code. /// /// We need to wrap this as the default serde /// behavior is to use ISO 639-3 codes and we need ISO 639-1; #[derive(Copy, Clone, Debug, Deserialize, PartialEq, Hash, Eq)] #[repr(transparent)] #[serde(try_from = "CowStr")] pub struct Locale(pub Language); impl Default for Locale { fn default() -> Self { Self(Language::Eng) } } impl<'a> TryFrom<&'a Locale> for &'a str { type Error = String; fn try_from(value: &'a Locale) -> Result<Self, Self::Error> { value .0 .to_639_1() .ok_or_else(|| format!("{} has no ISO 639-1 code", value.0)) } } impl<'a> TryFrom<CowStr<'a>> for Locale { type Error = String; fn try_from(value: CowStr<'a>) -> Result<Self, Self::Error> { let value = value.0.as_ref(); let lang = Language::from_639_1(value).ok_or_else(|| format!("unknown locale {value}"))?; Ok(Locale(lang)) } } impl Serialize for Locale { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let locale_str = <&str>::try_from(self).map_err(S::Error::custom)?; locale_str.serialize(serializer) } } #[cfg(test)] #[allow(clippy::field_reassign_with_default)] pub mod tests { use serde_json::{json, Value}; use super::*; use crate::misc::test_utils; pub fn make_minimal_field_localization() -> FieldLocalization { FieldLocalization::default() } pub fn make_extended_field_localization() -> FieldLocalization { let code = "test_code".to_owned(); let locale = Locale::default(); let catalogs = vec!["https://dummy.dummy/dummy".parse().unwrap()]; let translations = HashMap::from([(Locale(Language::Fra), "test, but in french".to_owned())]); FieldLocalization::builder() .code(code) .locale(locale) .catalogs(catalogs) .translations(translations) .build() } pub fn make_minimal_msg_localization() -> MsgLocalization { MsgLocalization::default() } pub fn make_extended_msg_localization() -> MsgLocalization { let catalogs = vec!["https://dummy.dummy/dummy".parse().unwrap()]; let locales = HashMap::from([( Locale(Language::Fra), vec!["test, but in french".to_owned()], )]); MsgLocalization::builder() .catalogs(catalogs) .locales(locales) .build() } #[test] fn test_minimal_field_localization() { let localization = make_minimal_field_localization(); let expected = json!({}); test_utils::test_serde(localization, expected); } #[test] fn test_extended_field_localization() { let localization = make_extended_field_localization(); let mut expected = json!({ "code": localization.code, "locale": localization.locale, "catalogs": localization.catalogs, }); let map = expected.as_object_mut().unwrap(); for (key, value) in &localization.translations { let key = <&str>::try_from(key).unwrap().to_owned(); let value = Value::String(value.to_owned()); map.insert(key, value); } test_utils::test_serde(localization, expected); } #[test] fn test_minimal_msg_localization() { let localization = make_minimal_msg_localization(); let expected = json!({}); test_utils::test_serde(localization, expected); } #[test] fn test_extended_msg_localization() { let localization = make_extended_msg_localization(); let expected = json!({ "catalogs": localization.catalogs, "locales": localization.locales }); test_utils::test_serde(localization, expected); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/decorators/timing.rs
aries/messages/src/decorators/timing.rs
use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; use crate::misc::utils; /// Struct representing the `~timing` decorator from its [RFC](<https://github.com/decentralized-identity/aries-rfcs/blob/main/features/0032-message-timing/README.md>). #[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq, TypedBuilder)] pub struct Timing { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] #[serde(serialize_with = "utils::serialize_opt_datetime")] pub in_time: Option<DateTime<Utc>>, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] #[serde(serialize_with = "utils::serialize_opt_datetime")] pub out_time: Option<DateTime<Utc>>, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] #[serde(serialize_with = "utils::serialize_opt_datetime")] pub stale_time: Option<DateTime<Utc>>, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] #[serde(serialize_with = "utils::serialize_opt_datetime")] pub expires_time: Option<DateTime<Utc>>, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub delay_milli: Option<u32>, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] #[serde(serialize_with = "utils::serialize_opt_datetime")] pub wait_until_time: Option<DateTime<Utc>>, } #[cfg(test)] #[allow(clippy::field_reassign_with_default)] pub mod tests { use serde_json::json; use super::*; use crate::misc::test_utils::{self, OptDateTimeRfc3339}; pub fn make_minimal_timing() -> Timing { Timing::default() } pub fn make_extended_timing() -> Timing { let dt = DateTime::default(); let delay_milli = 10; Timing::builder() .in_time(dt) .out_time(dt) .stale_time(dt) .expires_time(dt) .delay_milli(delay_milli) .wait_until_time(dt) .build() } #[test] fn test_minimal_timing() { let timing = make_minimal_timing(); let expected = json!({}); test_utils::test_serde(timing, expected); } #[test] fn test_extended_timing() { let timing = make_extended_timing(); let expected = json!({ "in_time": OptDateTimeRfc3339(&timing.in_time), "out_time": OptDateTimeRfc3339(&timing.out_time), "stale_time": OptDateTimeRfc3339(&timing.stale_time), "expires_time": OptDateTimeRfc3339(&timing.expires_time), "delay_milli": timing.delay_milli, "wait_until_time": OptDateTimeRfc3339(&timing.wait_until_time) }); test_utils::test_serde(timing, expected); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/decorators/mod.rs
aries/messages/src/decorators/mod.rs
pub mod attachment; pub mod localization; pub mod please_ack; pub mod thread; pub mod timing; pub mod transport;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/decorators/transport.rs
aries/messages/src/decorators/transport.rs
use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; use crate::decorators::thread::Thread; #[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] pub struct Transport { pub return_route: ReturnRoute, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub return_route_thread: Option<Thread>, } #[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq)] pub enum ReturnRoute { #[default] #[serde(rename = "none")] None, #[serde(rename = "all")] All, #[serde(rename = "thread")] Thread, } #[cfg(test)] #[allow(clippy::field_reassign_with_default)] mod tests { use serde_json::json; use super::*; use crate::misc::test_utils; #[test] fn test_transport_minimals() { // all variant let transport = Transport::builder().return_route(ReturnRoute::All).build(); let expected = json!({ "return_route": "all" }); test_utils::test_serde(transport, expected); // none variant let transport = Transport::builder().return_route(ReturnRoute::None).build(); let expected = json!({ "return_route": "none" }); test_utils::test_serde(transport, expected); } #[test] fn test_transport_extended() { // thread variant let thread = Thread::builder().thid("<thread id>".to_string()).build(); let transport = Transport::builder() .return_route(ReturnRoute::Thread) .return_route_thread(thread) .build(); let expected = json!({ "return_route": "thread", "return_route_thread": { "thid": "<thread id>" } }); test_utils::test_serde(transport, expected); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/decorators/thread.rs
aries/messages/src/decorators/thread.rs
use std::collections::HashMap; use serde::{Deserialize, Serialize}; use shared::maybe_known::MaybeKnown; use typed_builder::TypedBuilder; /// Struct representing the `~thread` decorator from its [RFC](<https://github.com/decentralized-identity/aries-rfcs/blob/main/concepts/0008-message-id-and-threading/README.md>). #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] pub struct Thread { pub thid: String, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub pthid: Option<String>, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub sender_order: Option<u32>, #[builder(default, setter(strip_option))] #[serde(default, skip_serializing_if = "Option::is_none")] pub received_orders: Option<HashMap<String, u32>>, // should get replaced with DID. #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub goal_code: Option<MaybeKnown<ThreadGoalCode>>, } // TODO: post-rebase check if this is dead code impl Thread { pub fn new(thid: String) -> Self { Self { thid, pthid: None, sender_order: None, received_orders: None, goal_code: None, } } } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub enum ThreadGoalCode { #[serde(rename = "aries.vc")] AriesVc, #[serde(rename = "aries.vc.issue")] AriesVcIssue, #[serde(rename = "aries.vc.verify")] AriesVcVerify, #[serde(rename = "aries.vc.revoke")] AriesVcRevoke, #[serde(rename = "aries.rel")] AriesRel, #[serde(rename = "aries.rel.build")] AriesRelBuild, } #[cfg(test)] #[allow(clippy::field_reassign_with_default)] pub mod tests { use serde_json::json; use super::*; use crate::misc::test_utils; pub fn make_minimal_thread() -> Thread { let thid = "test".to_owned(); Thread::builder().thid(thid).build() } pub fn make_extended_thread() -> Thread { let thid = "test".to_owned(); let pthid = "test_pthid".to_owned(); let sender_order = 5; let received_orders = HashMap::from([ ("a".to_owned(), 1), ("b".to_owned(), 2), ("c".to_owned(), 3), ]); let goal_code = MaybeKnown::Known(ThreadGoalCode::AriesVcVerify); Thread::builder() .thid(thid) .pthid(pthid) .sender_order(sender_order) .received_orders(received_orders) .goal_code(goal_code) .build() } #[test] fn test_minimal_thread() { let thread = make_minimal_thread(); let expected = json!({ "thid": thread.thid }); test_utils::test_serde(thread, expected); } #[test] fn test_extended_thread() { let thread = make_extended_thread(); let expected = json!({ "thid": thread.thid, "pthid": thread.pthid, "sender_order": thread.sender_order, "received_orders": thread.received_orders, "goal_code": thread.goal_code }); test_utils::test_serde(thread, expected); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/misc/mime_type.rs
aries/messages/src/misc/mime_type.rs
use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum MimeType { #[serde(rename = "application/json")] Json, #[serde(rename = "image/jpg")] Jpg, #[serde(rename = "image/jpeg")] Jpeg, #[serde(rename = "image/png")] Png, #[serde(rename = "application/pdf")] Pdf, #[serde(rename = "text/plain")] Plain, #[serde(rename = "text/string")] String, #[serde(rename = "didcomm/aip1")] Aip1, #[serde(rename = "didcomm/aip2;env=rfc19")] Aip2Rfc19, #[serde(rename = "didcomm/aip2;env=rfc587")] Aip2Rfc587, #[serde(rename = "didcomm/v2")] DidcommV2, }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/misc/utils.rs
aries/messages/src/misc/utils.rs
use chrono::{DateTime, Utc}; use serde::{de::Error, Deserializer, Serialize}; /// Used for creating a deserialization error. /// Some messages, or rather, message types, are not meant /// to be used as standalone messages. /// /// E.g: Connection signature message type or credential preview message type. pub(crate) fn not_standalone_msg<'de, D>(msg_type: &str) -> D::Error where D: Deserializer<'de>, { D::Error::custom(format!("{msg_type} is not a standalone message")) } /// Used for serialization of a [`DateTime<Utc>`] to the RFC3339 standard. pub(crate) fn serialize_datetime<S>(dt: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { use chrono::format::{Fixed, Item, Numeric::*, Pad::Zero}; const FMT_ITEMS: &[Item<'static>] = &[ Item::Numeric(Year, Zero), Item::Literal("-"), Item::Numeric(Month, Zero), Item::Literal("-"), Item::Numeric(Day, Zero), Item::Literal("T"), Item::Numeric(Hour, Zero), Item::Literal(":"), Item::Numeric(Minute, Zero), Item::Literal(":"), Item::Numeric(Second, Zero), Item::Fixed(Fixed::Nanosecond3), Item::Fixed(Fixed::TimezoneOffsetColonZ), ]; format_args!("{}", dt.format_with_items(FMT_ITEMS.iter())).serialize(serializer) } /// Used for serialization of an [`Option<DateTime<Utc>>`] to the RFC3339 standard. pub(crate) fn serialize_opt_datetime<S>( dt: &Option<DateTime<Utc>>, serializer: S, ) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match dt { Some(dt) => serialize_datetime(dt, serializer), None => serializer.serialize_none(), } } /// Macro used for implementing [`From`] for the given [`crate::msg_parts::MsgParts`] comprised /// of the content and decorators provided so it can be converted into an [`crate::AriesMessage`]. /// /// If no decorators are provided, the macro resorts to using [`crate::misc::NoDecorators`]. macro_rules! transit_to_aries_msg { // No decorators provided. ($content:ty, $($interm:ty),+) => { transit_to_aries_msg!($content:$crate::misc::NoDecorators, $($interm),+); }; // Decorators are given through the colon `:`. ($content:ty: $decorators:ty, $($interm:ty),+) => { impl From<$crate::msg_parts::MsgParts<$content, $decorators>> for $crate::AriesMessage { fn from(value: $crate::msg_parts::MsgParts<$content, $decorators>) -> Self { Self::from($crate::misc::utils::generate_from_stmt!(value, $($interm),+)) } } }; } /// Push-down accumulating macro used for generating all the intermediary [`From::from`] calls /// necessary to transition a type to another. /// /// See: <https://veykril.github.io/tlborm/decl-macros/patterns/push-down-acc.html>. macro_rules! generate_from_stmt { ($val:expr, $interm:ty) => { <$interm>::from($val) }; ($val:expr, $interm:ty, $($i:ty),+) => { $crate::misc::utils::generate_from_stmt!($crate::misc::utils::generate_from_stmt!($val, $interm), $($i),+) }; } /// Macro used for implementing [`From`] from a full message plus the given message kind and variant /// into [`crate::msg_types::MsgWithType`]. This then allows appending the `@type` field when /// serializing the message. macro_rules! into_msg_with_type { ($msg:ident, $kind:ident, $kind_var:ident) => { impl<'a> From<&'a $msg> for $crate::msg_types::MsgWithType<'a, $msg, $kind> { fn from(value: &'a $msg) -> $crate::msg_types::MsgWithType<'a, $msg, $kind> { $crate::msg_types::MsgWithType::new($kind::$kind_var, value) } } }; } pub(crate) use generate_from_stmt; pub(crate) use into_msg_with_type; pub(crate) use transit_to_aries_msg;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/misc/mod.rs
aries/messages/src/misc/mod.rs
mod mime_type; pub(crate) mod utils; pub use mime_type::MimeType; pub use shared::misc::{serde_ignored::SerdeIgnored as NoDecorators, utils::CowStr}; #[cfg(test)] pub mod test_utils { use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use shared::misc::utils::CowStr; use super::utils; use crate::{ msg_parts::MsgParts, msg_types::{traits::MessageKind, MessageType, Protocol}, AriesMessage, }; pub struct DateTimeRfc3339<'a>(pub &'a DateTime<Utc>); impl Serialize for DateTimeRfc3339<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { utils::serialize_datetime(self.0, serializer) } } pub struct OptDateTimeRfc3339<'a>(pub &'a Option<DateTime<Utc>>); impl Serialize for OptDateTimeRfc3339<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { utils::serialize_opt_datetime(self.0, serializer) } } pub fn test_msg_type<T>(protocol_str: &str, kind_str: &str, protocol_type: T) where Protocol: From<T>, { let s = format!("\"{protocol_str}/{kind_str}\""); let protocol = Protocol::from(protocol_type); let deserialized: CowStr = serde_json::from_str(&s).unwrap(); let deserialized = MessageType::try_from(deserialized.0.as_ref()).unwrap(); let expected = MessageType { protocol, kind: kind_str, }; let serialized = serde_json::to_string(&format_args!("{protocol}/{kind_str}")).unwrap(); assert_eq!(expected, deserialized); assert_eq!(s, serialized); } pub fn test_msg_type_resolution<T>(protocol_str: &str, protocol_type: T) where Protocol: From<T>, { let quoted = format!("\"{protocol_str}\""); let deserialized = serde_json::from_str(&quoted).unwrap(); assert_eq!(Protocol::from(protocol_type), deserialized) } pub fn test_msg<T, U, V>(content: T, decorators: U, msg_kind: V, expected: Value) where AriesMessage: From<MsgParts<T, U>>, V: MessageKind, Protocol: From<V::Parent>, { let id = "test".to_owned(); let msg = MsgParts::<T, U>::builder() .id(id) .content(content) .decorators(decorators) .build(); test_constructed_msg(msg, msg_kind, expected); } pub fn test_constructed_msg<M, V>(complete: M, msg_kind: V, mut expected: Value) where AriesMessage: From<M>, V: MessageKind, Protocol: From<V::Parent>, { let id = "test".to_owned(); let msg_type = build_msg_type(msg_kind); let obj = expected.as_object_mut().expect("JSON object"); obj.insert("@id".to_owned(), json!(id)); obj.insert("@type".to_owned(), json!(msg_type)); let msg = AriesMessage::from(complete); test_serde(msg, expected); } pub fn test_serde<T>(value: T, expected: Value) where T: for<'de> Deserialize<'de> + Serialize + std::fmt::Debug + PartialEq, { // Test serialization assert_eq!(serde_json::to_value(&value).unwrap(), expected); // Test deserialization from deserializer that owns data: let deserialized = T::deserialize(expected.clone()).unwrap(); assert_eq!(deserialized, value); // Test deserialization from deserialized that borrows data: let deserialized = T::deserialize(&expected).unwrap(); assert_eq!(deserialized, value); } fn build_msg_type<T>(msg_kind: T) -> String where T: MessageKind, Protocol: From<T::Parent>, { let kind = msg_kind.as_ref(); let protocol: Protocol = T::parent().into(); format!("{protocol}/{kind}") } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/msg_types/registry.rs
aries/messages/src/msg_types/registry.rs
use std::collections::HashMap; use lazy_static::lazy_static; use shared::maybe_known::MaybeKnown; use super::{role::Role, Protocol}; use crate::msg_types::{ present_proof::PresentProofTypeV2, protocols::{ basic_message::BasicMessageTypeV1, connection::ConnectionTypeV1, coordinate_mediation::CoordinateMediationTypeV1, cred_issuance::{CredentialIssuanceTypeV1, CredentialIssuanceTypeV2}, did_exchange::DidExchangeTypeV1, discover_features::DiscoverFeaturesTypeV1, notification::NotificationTypeV1, out_of_band::OutOfBandTypeV1, pickup::PickupTypeV2, present_proof::PresentProofTypeV1, report_problem::ReportProblemTypeV1, revocation::RevocationTypeV2, routing::RoutingTypeV1, signature::SignatureTypeV1, trust_ping::TrustPingTypeV1, }, }; type RegistryMap = HashMap<(&'static str, u8), Vec<RegistryEntry>>; /// An entry in the protocol registry. #[derive(Debug, Clone)] pub struct RegistryEntry { /// The [`Protocol`] instance corresponding to this entry pub protocol: Protocol, /// The minor version of in numeric (for easier semver resolution), pub minor: u8, /// A [`String`] representation of the *pid* pub str_pid: String, /// A [`Vec<Actor>`] representing the roles available in the protocol. pub roles: Vec<MaybeKnown<Role>>, } /// Extracts the necessary parts for constructing a [`RegistryEntry`] from a protocol minor version. macro_rules! extract_parts { ($name:expr) => {{ let roles = $crate::msg_types::traits::ProtocolVersion::roles(&$name); let protocol = Protocol::from($name); let (name, major, minor) = protocol.as_parts(); (name, major, minor, roles, Protocol::from($name)) }}; } fn map_insert( map: &mut RegistryMap, parts: (&'static str, u8, u8, Vec<MaybeKnown<Role>>, Protocol), ) { let (protocol_name, major, minor, roles, protocol) = parts; let str_pid = format!( "{}/{}/{}.{}", Protocol::DID_COM_ORG_PREFIX, protocol_name, major, minor ); let entry = RegistryEntry { protocol, minor, str_pid, roles, }; map.entry((protocol_name, major)).or_default().push(entry); } lazy_static! { /// The protocol registry, used as a baseline for the protocols and versions /// that an agent supports along with semver resolution. /// /// Keys are comprised of the protocol name and major version while /// the values are [`RegistryEntry`] instances. pub static ref PROTOCOL_REGISTRY: RegistryMap = { let mut m = HashMap::new(); map_insert(&mut m, extract_parts!(RoutingTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(BasicMessageTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(ConnectionTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(SignatureTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(CredentialIssuanceTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(CredentialIssuanceTypeV2::new_v2_0())); map_insert(&mut m, extract_parts!(DiscoverFeaturesTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(NotificationTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(OutOfBandTypeV1::new_v1_1())); map_insert(&mut m, extract_parts!(PresentProofTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(PresentProofTypeV2::new_v2_0())); map_insert(&mut m, extract_parts!(ReportProblemTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(RevocationTypeV2::new_v2_0())); map_insert(&mut m, extract_parts!(TrustPingTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(PickupTypeV2::new_v2_0())); map_insert(&mut m, extract_parts!(CoordinateMediationTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(DidExchangeTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(DidExchangeTypeV1::new_v1_1())); m }; } /// Looks into the protocol registry for (in order): /// * the exact protocol version requested /// * the maximum minor version of a protocol less than the minor version requested (e.g: requesting /// 1.7 should yield 1.6). pub fn get_supported_version(name: &'static str, major: u8, minor: u8) -> Option<u8> { PROTOCOL_REGISTRY .get(&(name, major)) .and_then(|v| v.iter().rev().map(|r| r.minor).find(|v| *v <= minor)) }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/msg_types/mod.rs
aries/messages/src/msg_types/mod.rs
//! Module that handles operations related solely to the protocol of a message, instead of it's //! content. The main type, [`Protocol`], represents a protocol name along with its (both major and //! minor) version. //! //! The module contains other types that work adjacently to the [`Protocol`] to represent a message //! kind, and along the protocol they make up the `@type` field of a message. pub mod protocols; pub mod registry; mod role; pub mod traits; use std::{marker::PhantomData, str::FromStr}; pub use protocols::{ basic_message, connection, cred_issuance, discover_features, notification, out_of_band, present_proof, report_problem, revocation, routing, trust_ping, Protocol, }; pub use role::Role; use serde::Serialize; use self::traits::MessageKind; /// Type used for parsing of a fully qualified message type. After parsing, /// it is matched on to determine the actual message struct to deserialize to. /// /// The [`Protocol`] and kind represent a complete `@type` field. #[derive(Debug, PartialEq)] pub(crate) struct MessageType<'a> { /// The [`Protocol`] part of the message type (e.g: https://didcomm.org/connections/1.0) pub protocol: Protocol, /// The message kind of the specific protocol (e.g: request) pub kind: &'a str, } impl<'a> TryFrom<&'a str> for MessageType<'a> { type Error = String; fn try_from(msg_type_str: &'a str) -> Result<Self, Self::Error> { // Split (from the right) at the first '/'. // The first element will be the string repr of the protocol // while the second will be the message kind. let Some((protocol_str, kind)) = msg_type_str.rsplit_once('/') else { return Err(format!("Invalid message type: {msg_type_str}")); }; // Parse the Protocol instance let protocol = match Protocol::from_str(protocol_str) { Ok(v) => Ok(v), Err(e) => { let msg = format!("Cannot parse message type: {msg_type_str}; Error: {e}"); Err(msg) } }?; // Create instance to be passed for specialized message deserialization later. let msg_type = Self { protocol, kind }; Ok(msg_type) } } /// Type used for serialization of a message along with appending it's `@type` field. #[derive(Serialize)] pub(crate) struct MsgWithType<'a, T, K> where K: MessageKind, Protocol: From<K::Parent>, { #[serde(rename = "@type")] #[serde(serialize_with = "serialize_msg_type")] kind: K, #[serde(flatten)] message: &'a T, } impl<'a, T, K> MsgWithType<'a, T, K> where K: MessageKind, Protocol: From<K::Parent>, { pub fn new(kind: K, message: &'a T) -> Self { Self { kind, message } } } /// Used for retrieving the [`Protocol`] first from the message kind /// and serializing them together. pub fn serialize_msg_type<S, K>(kind: &K, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, K: MessageKind, Protocol: From<K::Parent>, { let kind = kind.as_ref(); let protocol = Protocol::from(K::parent()); format_args!("{protocol}/{kind}").serialize(serializer) } /// Type used for binding an impl of [`MessageKind`] to a variant of an enum implementing /// [`crate::msg_types::traits::ProtocolVersion`]. /// /// The main reasons for abstracting over [`PhantomData`] is to make the generic type easier on the /// eyes and, more importantly, to be able to define a method to convert from a `&str` to the bound /// type [`T`]. /// /// Technically, a trait implemented on [`PhantomData`] would've achieved the same thing, but would /// require an import wherever it was used. A simple function accepting the [`PhantomData`] argument /// along with the `&str` would've also worked, but it would be less ergonomic. /// /// As per why the generic type is `fn() -> T` and not just `T`, the short story is *ownership*. /// /// The long story is that `PhantomData<T>` tells the drop checker that we *own* `T`, which we /// don't. While still a covariant, `fn() -> T` does not mean we own the `T`, so that lets the drop /// checker be more permissive. Not really important for our current use case, but it is /// *idiomatic*. /// /// Good reads and references: /// - <https://doc.rust-lang.org/std/marker/struct.PhantomData.html> /// - <https://doc.rust-lang.org/nomicon/phantom-data.html> /// - <https://doc.rust-lang.org/nomicon/dropck.html> #[derive(Copy, Clone, Debug, PartialEq)] #[repr(transparent)] pub struct MsgKindType<T: MessageKind>(PhantomData<fn() -> T>); impl<T> MsgKindType<T> where T: MessageKind, { pub fn new() -> Self { Self(PhantomData) } /// Method used for taking a `&str` and trying to convert it /// into the bound type [`T`]. It uses [`FromStr`] under the hood. /// /// # Errors /// /// The method will error out if an instance of `T` /// could not be constructed from the `&str`. pub fn kind_from_str(&self, kind_str: &str) -> Result<T, <T as FromStr>::Err> { kind_str.parse() } } impl<T: MessageKind> Default for MsgKindType<T> { fn default() -> Self { Self(Default::default()) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/msg_types/role.rs
aries/messages/src/msg_types/role.rs
use serde::{Deserialize, Serialize}; /// The roles an agent can have in a protocol. /// These are mainly for use in the [discover features](<https://github.com/decentralized-identity/aries-rfcs/blob/main/features/0031-discover-features/README.md>) protocol. #[derive(Clone, Deserialize, Debug, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] pub enum Role { Inviter, Invitee, Issuer, Holder, Prover, Verifier, Sender, Receiver, Requester, Responder, Notified, Notifier, Mediator, Recipient, }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/msg_types/traits.rs
aries/messages/src/msg_types/traits.rs
use std::str::FromStr; use shared::maybe_known::MaybeKnown; use crate::{error::MsgTypeResult, msg_types::role::Role}; /// Trait implemented on enums that represent the message kind of a protocol. /// They link upstream to the [`ProtocolVersion`] impl enum they are part of. /// The link downstream from the [`ProtocolVersion`] impl enum is done through the enum variant type /// binding. /// /// E.g: `RoutingV1_0` would implement this, and its variants would look like /// `RoutingV1_0::Forward`. From a protocol string such as `https://didcomm.org/routing/1.0/forward`, the variant would correspond to `forward`. /// /// This trait is typically implemented through deriving [`messages_macros::MessageType`] on the /// [`ProtocolVersion`] impl enum and annotating its variants. pub trait MessageKind: FromStr + AsRef<str> { type Parent: ProtocolVersion; /// Returns an instance of the parent, which should be the correctly /// variant corresponding to the minor version this type represents message kinds for. fn parent() -> Self::Parent; } /// Trait implemented on enums that represent a major version of a protocol and where /// the variants represent the minor version. /// /// E.g: `RoutingTypeV1` would implement this, and its variants would look like /// `RoutingTypeV1::V1_0`. From a protocol string such as `https://didcomm.org/routing/1.0/forward`, these would correspond to /// the `1` and `0`, respectively. /// /// This trait is typically implemented through deriving [`messages_macros::MessageType`]. pub trait ProtocolVersion: Sized { type Roles: IntoIterator<Item = MaybeKnown<Role>>; const MAJOR: u8; /// Tries to resolve the version of this protocol and returns /// an instance of itself on success. /// /// This is typically done by lookup in the [`crate::msg_types::registry::PROTOCOL_REGISTRY`] /// for the largest minor version less than or equal to the given `minor` argument. /// /// # Errors /// /// An error is returned if the version could not be resolved, /// which means we can't support the provided protocol version. // // NOTE: We already have the major version as a const declared in the trait. // so we just need the minor version. // // NOTE: The protocol name is also implemented at the enum level by the derive macro, // so it is accessible from here as well. fn try_resolve_version(minor: u8) -> MsgTypeResult<Self>; /// Returns the major and minor versions of the protocol. fn as_version_parts(&self) -> (u8, u8); /// Returns the roles the protocol provides. fn roles(&self) -> Self::Roles; } /// Trait implemented on enums that represent the name of a protocol. /// /// E.g: `RoutingType` would implement this, and its variants would look like `RoutingType::V1`. /// From a protocol string such as `https://didcomm.org/routing/1.0/forward`, the enum would correspond to `routing`. /// /// This trait is typically implemented through deriving [`messages_macros::MessageType`] on the /// protocol specific enum. pub trait ProtocolName: Sized { const PROTOCOL: &'static str; /// Tries to construct an instance of itself from the provided /// version parts. /// /// # Errors /// /// Will return an error if no variant matches the version parts provided. fn try_from_version_parts(major: u8, minor: u8) -> MsgTypeResult<Self>; /// Returns the protocol name, major and minor versions of the protocol. fn as_protocol_parts(&self) -> (&'static str, u8, u8); }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/msg_types/protocols/signature.rs
aries/messages/src/msg_types/protocols/signature.rs
use derive_more::{From, TryInto}; use messages_macros::MessageType; use strum_macros::{AsRefStr, EnumString}; use transitive::Transitive; use super::Protocol; use crate::msg_types::MsgKindType; #[derive(Copy, Clone, Debug, From, TryInto, PartialEq, MessageType)] #[msg_type(protocol = "signature")] pub enum SignatureType { V1(SignatureTypeV1), } #[derive(Copy, Clone, Debug, From, TryInto, PartialEq, Transitive, MessageType)] #[transitive(into(SignatureType, Protocol))] #[msg_type(major = 1)] pub enum SignatureTypeV1 { #[msg_type(minor = 0, roles = "")] // This is for accommodating the Connection response, it has no roles. V1_0(MsgKindType<SignatureTypeV1_0>), } #[derive(Copy, Clone, Debug, AsRefStr, EnumString, PartialEq)] pub enum SignatureTypeV1_0 { #[strum(serialize = "ed25519Sha512_single")] Ed25519Sha512Single, } #[cfg(test)] mod tests { use serde_json::json; use super::*; use crate::misc::test_utils; #[test] fn test_protocol_signature() { test_utils::test_serde( Protocol::from(SignatureTypeV1::new_v1_0()), json!("https://didcomm.org/signature/1.0"), ) } #[test] fn test_version_resolution_signature() { test_utils::test_msg_type_resolution( "https://didcomm.org/signature/1.255", SignatureTypeV1::new_v1_0(), ) } #[test] #[should_panic] fn test_unsupported_version_signature() { test_utils::test_serde( Protocol::from(SignatureTypeV1::new_v1_0()), json!("https://didcomm.org/signature/2.0"), ) } #[test] fn test_msg_type_sign() { test_utils::test_msg_type( "https://didcomm.org/signature/1.0", "ed25519Sha512_single", SignatureTypeV1::new_v1_0(), ) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/msg_types/protocols/routing.rs
aries/messages/src/msg_types/protocols/routing.rs
use derive_more::From; use messages_macros::MessageType; use strum_macros::{AsRefStr, EnumString}; use transitive::Transitive; use super::Protocol; use crate::msg_types::{role::Role, MsgKindType}; #[derive(Copy, Clone, Debug, From, PartialEq, MessageType)] #[msg_type(protocol = "routing")] pub enum RoutingType { V1(RoutingTypeV1), } #[derive(Copy, Clone, Debug, From, PartialEq, Transitive, MessageType)] #[transitive(into(RoutingType, Protocol))] #[msg_type(major = 1)] pub enum RoutingTypeV1 { #[msg_type(minor = 0, roles = "Role::Mediator")] V1_0(MsgKindType<RoutingTypeV1_0>), } #[derive(Copy, Clone, Debug, AsRefStr, EnumString, PartialEq)] #[strum(serialize_all = "kebab-case")] pub enum RoutingTypeV1_0 { Forward, } #[cfg(test)] mod tests { use serde_json::json; use super::*; use crate::misc::test_utils; #[test] fn test_protocol_routing() { test_utils::test_serde( Protocol::from(RoutingTypeV1::new_v1_0()), json!("https://didcomm.org/routing/1.0"), ) } #[test] fn test_version_resolution_routing() { test_utils::test_msg_type_resolution( "https://didcomm.org/routing/1.255", RoutingTypeV1::new_v1_0(), ) } #[test] #[should_panic] fn test_unsupported_version_routing() { test_utils::test_serde( Protocol::from(RoutingTypeV1::new_v1_0()), json!("https://didcomm.org/routing/2.0"), ) } #[test] fn test_msg_type_forward() { test_utils::test_msg_type( "https://didcomm.org/routing/1.0", "forward", RoutingTypeV1::new_v1_0(), ) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/msg_types/protocols/notification.rs
aries/messages/src/msg_types/protocols/notification.rs
use derive_more::From; use messages_macros::MessageType; use strum_macros::{AsRefStr, EnumString}; use transitive::Transitive; use super::Protocol; use crate::msg_types::{role::Role, MsgKindType}; #[derive(Copy, Clone, Debug, From, PartialEq, MessageType)] #[msg_type(protocol = "notification")] pub enum NotificationType { V1(NotificationTypeV1), } #[derive(Copy, Clone, Debug, From, PartialEq, Transitive, MessageType)] #[transitive(into(NotificationType, Protocol))] #[msg_type(major = 1)] pub enum NotificationTypeV1 { #[msg_type(minor = 0, roles = "Role::Notified, Role::Notifier")] V1_0(MsgKindType<NotificationTypeV1_0>), } #[derive(Copy, Clone, Debug, AsRefStr, EnumString, PartialEq)] #[strum(serialize_all = "kebab-case")] pub enum NotificationTypeV1_0 { Ack, ProblemReport, } #[cfg(test)] mod tests { use serde_json::json; use super::*; use crate::misc::test_utils; #[test] fn test_protocol_notification() { test_utils::test_serde( Protocol::from(NotificationTypeV1::new_v1_0()), json!("https://didcomm.org/notification/1.0"), ) } #[test] fn test_version_resolution_discover_features() { test_utils::test_msg_type_resolution( "https://didcomm.org/notification/1.255", NotificationTypeV1::new_v1_0(), ) } #[test] #[should_panic] fn test_unsupported_version_discover_features() { test_utils::test_serde( Protocol::from(NotificationTypeV1::new_v1_0()), json!("https://didcomm.org/notification/2.0"), ) } #[test] fn test_msg_type_ack() { test_utils::test_msg_type( "https://didcomm.org/notification/1.0", "ack", NotificationTypeV1::new_v1_0(), ) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/msg_types/protocols/basic_message.rs
aries/messages/src/msg_types/protocols/basic_message.rs
use derive_more::From; use messages_macros::MessageType; use strum_macros::{AsRefStr, EnumString}; use transitive::Transitive; use super::Protocol; use crate::msg_types::{role::Role, MsgKindType}; #[derive(Copy, Clone, Debug, From, PartialEq, MessageType)] #[msg_type(protocol = "basicmessage")] pub enum BasicMessageType { V1(BasicMessageTypeV1), } #[derive(Copy, Clone, Debug, From, PartialEq, Transitive, MessageType)] #[transitive(into(BasicMessageType, Protocol))] #[msg_type(major = 1)] pub enum BasicMessageTypeV1 { #[msg_type(minor = 0, roles = "Role::Receiver, Role::Sender")] V1_0(MsgKindType<BasicMessageTypeV1_0>), } #[derive(Copy, Clone, Debug, AsRefStr, EnumString, PartialEq)] #[strum(serialize_all = "kebab-case")] pub enum BasicMessageTypeV1_0 { Message, } #[cfg(test)] mod tests { use serde_json::json; use super::*; use crate::misc::test_utils; #[test] fn test_protocol_basic_message() { test_utils::test_serde( Protocol::from(BasicMessageTypeV1::new_v1_0()), json!("https://didcomm.org/basicmessage/1.0"), ) } #[test] fn test_version_resolution_basic_message() { test_utils::test_msg_type_resolution( "https://didcomm.org/basicmessage/1.255", BasicMessageTypeV1::new_v1_0(), ) } #[test] #[should_panic] fn test_unsupported_version_basic_message() { test_utils::test_serde( Protocol::from(BasicMessageTypeV1::new_v1_0()), json!("https://didcomm.org/basicmessage/2.0"), ) } #[test] fn test_msg_type_message() { test_utils::test_msg_type( "https://didcomm.org/basicmessage/1.0", "message", BasicMessageTypeV1::new_v1_0(), ) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/messages/src/msg_types/protocols/connection.rs
aries/messages/src/msg_types/protocols/connection.rs
use derive_more::{From, TryInto}; use messages_macros::MessageType; use strum_macros::{AsRefStr, EnumString}; use transitive::Transitive; use super::Protocol; use crate::msg_types::{role::Role, MsgKindType}; #[derive(Copy, Clone, Debug, From, TryInto, PartialEq, MessageType)] #[msg_type(protocol = "connections")] pub enum ConnectionType { V1(ConnectionTypeV1), } #[derive(Copy, Clone, Debug, From, TryInto, PartialEq, Transitive, MessageType)] #[transitive(into(ConnectionType, Protocol))] #[msg_type(major = 1)] pub enum ConnectionTypeV1 { #[msg_type(minor = 0, roles = "Role::Inviter, Role::Invitee")] V1_0(MsgKindType<ConnectionTypeV1_0>), } #[derive(Copy, Clone, Debug, AsRefStr, EnumString, PartialEq)] #[strum(serialize_all = "snake_case")] pub enum ConnectionTypeV1_0 { Invitation, Request, Response, ProblemReport, } #[cfg(test)] mod tests { use serde_json::json; use super::*; use crate::misc::test_utils; #[test] fn test_protocol_connections() { test_utils::test_serde( Protocol::from(ConnectionTypeV1::new_v1_0()), json!("https://didcomm.org/connections/1.0"), ) } #[test] fn test_version_resolution_connections() { test_utils::test_msg_type_resolution( "https://didcomm.org/connections/1.255", ConnectionTypeV1::new_v1_0(), ) } #[test] #[should_panic] fn test_unsupported_version_connections() { test_utils::test_serde( Protocol::from(ConnectionTypeV1::new_v1_0()), json!("https://didcomm.org/connections/2.0"), ) } #[test] fn test_msg_type_invitation() { test_utils::test_msg_type( "https://didcomm.org/connections/1.0", "invitation", ConnectionTypeV1::new_v1_0(), ) } #[test] fn test_msg_type_request() { test_utils::test_msg_type( "https://didcomm.org/connections/1.0", "request", ConnectionTypeV1::new_v1_0(), ) } #[test] fn test_msg_type_response() { test_utils::test_msg_type( "https://didcomm.org/connections/1.0", "response", ConnectionTypeV1::new_v1_0(), ) } #[test] fn test_msg_type_problem() { test_utils::test_msg_type( "https://didcomm.org/connections/1.0", "problem_report", ConnectionTypeV1::new_v1_0(), ) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false