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/errors/error.rs
aries/aries_vcx/src/errors/error.rs
use std::{error::Error, fmt}; use thiserror; pub mod prelude { pub use super::{err_msg, AriesVcxError, AriesVcxErrorKind, VcxResult}; } #[derive(Copy, Clone, Eq, PartialEq, Debug, thiserror::Error)] pub enum AriesVcxErrorKind { // Common #[error("Object is in invalid state for requested operation")] InvalidState, #[error("Invalid Configuration")] InvalidConfiguration, #[error("Authentication error")] AuthenticationError, #[error("Invalid JSON string")] InvalidJson, #[error("Invalid Option")] InvalidOption, #[error("Invalid MessagePack")] InvalidMessagePack, #[error("Object not ready for specified action")] NotReady, #[error("IO Error, possibly creating a backup wallet")] IOError, #[error( "Object (json, config, key, credential and etc...) passed to libindy has invalid structure" )] LibindyInvalidStructure, #[error("Parameter passed to libindy was invalid")] InvalidLibindyParam, #[error("Action is not supported")] ActionNotSupported, #[error("Invalid input parameter")] InvalidInput, #[error("Unimplemented feature")] UnimplementedFeature, // Credential Definition error #[error("Can't create, Credential Def already on ledger")] CredDefAlreadyCreated, #[error( "No revocation delta found in storage for this revocation registry. Were any credentials \ locally revoked?" )] RevDeltaNotFound, #[error("Failed to clean stored revocation delta")] RevDeltaFailedToClear, // Revocation #[error("Failed to create Revocation Registration Definition")] CreateRevRegDef, #[error("Invalid Revocation Details")] InvalidRevocationDetails, #[error("Unable to Update Revocation Delta On Ledger")] InvalidRevocationEntry, #[error("Invalid Credential Revocation timestamp")] InvalidRevocationTimestamp, #[error("No revocation definition found")] RevRegDefNotFound, // Issuer Credential #[error("Attributes provided to Credential Offer are not correct, possibly malformed")] InvalidAttributesStructure, // Proof #[error("Proof had invalid format")] InvalidProof, #[error("Schema was invalid or corrupt")] InvalidSchema, #[error("The Proof received does not have valid credentials listed.")] InvalidProofCredentialData, #[error("Proof Request Passed into Libindy Call Was Invalid")] InvalidProofRequest, #[error("The proof was rejected")] ProofRejected, // Schema #[error("No Schema for that schema sequence number")] InvalidSchemaSeqNo, #[error( "Duplicate Schema: Ledger Already Contains Schema For Given DID, Version, and Name \ Combination" )] DuplicationSchema, #[error("Unknown Rejection of Schema Creation, refer to libindy documentation")] UnknownSchemaRejection, // Pool #[error("Invalid genesis transactions path.")] InvalidGenesisTxnPath, #[error("Formatting for Pool Config are incorrect.")] CreatePoolConfig, #[error("Connection to Pool Ledger.")] PoolLedgerConnect, #[error("Ledger rejected submitted request.")] InvalidLedgerResponse, #[error("Ledger item not found.")] LedgerItemNotFound, #[error("No Pool open. Can't return handle.")] NoPoolOpen, #[error("Message failed in post")] PostMessageFailed, // Wallet #[error("Error Creating a wallet")] WalletCreate, #[error("Attempt to open wallet with invalid credentials")] WalletAccessFailed, #[error("Invalid Wallet or Search Handle")] InvalidWalletHandle, #[error("Indy wallet already exists")] DuplicationWallet, #[error("Wallet record not found")] WalletRecordNotFound, #[error("Record already exists in the wallet")] DuplicationWalletRecord, #[error("Wallet not found")] WalletNotFound, #[error("Indy wallet already open")] WalletAlreadyOpen, #[error("Attempted to add a Master Secret that already existed in wallet")] DuplicationMasterSecret, #[error("Attempted to add a DID to wallet when that DID already exists in wallet")] DuplicationDid, // Logger #[error("Logging Error")] LoggingError, // Validation #[error("Could not encode string to a big integer.")] EncodeError, #[error("Unknown Error")] UnknownError, #[error("Invalid DID")] InvalidDid, #[error("Invalid VERKEY")] InvalidVerkey, #[error("Invalid NONCE")] InvalidNonce, #[error("Invalid URL")] InvalidUrl, #[error("Unable to serialize")] SerializationError, #[error("Value needs to be base58")] NotBase58, #[error("Could not parse a value")] ParsingError, #[error("Unexpected wallet error")] WalletError, // A2A #[error("Invalid HTTP response.")] InvalidHttpResponse, #[error("Error Retrieving messages from API")] InvalidMessages, #[error("Ursa error")] UrsaError, #[error("No Agent pairwise information")] NoAgentInformation, #[error("Invalid message format")] InvalidMessageFormat, } #[derive(thiserror::Error)] pub struct AriesVcxError { msg: String, kind: AriesVcxErrorKind, backtrace: Option<String>, } fn format_error(err: &AriesVcxError, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "Error: {}", err.msg())?; match err.backtrace() { None => {} Some(backtrace) => { writeln!(f, "Backtrace: {backtrace}")?; } } let mut current = err.source(); while let Some(cause) = current { writeln!(f, "Caused by:\n{cause}")?; current = cause.source(); } Ok(()) } impl fmt::Display for AriesVcxError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { format_error(self, f) } } impl fmt::Debug for AriesVcxError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { format_error(self, f) } } fn try_capture_backtrace() -> Option<String> { #[cfg(feature = "backtrace_errors")] { use backtrace::Backtrace; let backtrace = Backtrace::new(); let mut filtered_backtrace = String::new(); for frame in backtrace.frames() { let symbols = frame.symbols(); if !symbols.is_empty() { let symbol = &symbols[0]; if let Some(filename) = symbol.filename() { if let Some(line) = symbol.lineno() { filtered_backtrace.push_str(&format!("[{}:{}]", filename.display(), line)); } } if let Some(name) = symbol.name() { filtered_backtrace.push_str(&format!(" {name}")); } filtered_backtrace.push('\n'); } } Some(filtered_backtrace) } #[cfg(not(feature = "backtrace_errors"))] None } impl AriesVcxError { fn new(kind: AriesVcxErrorKind, msg: String) -> Self { AriesVcxError { msg, kind, backtrace: try_capture_backtrace(), } } pub fn from_msg<D>(kind: AriesVcxErrorKind, msg: D) -> AriesVcxError where D: fmt::Display + fmt::Debug + Send + Sync + 'static, { Self::new(kind, msg.to_string()) } pub fn find_root_cause(&self) -> String { let mut current = self.source(); while let Some(cause) = current { if cause.source().is_none() { return cause.to_string(); } current = cause.source(); } self.to_string() } pub fn kind(&self) -> AriesVcxErrorKind { self.kind } pub fn msg(&self) -> &str { &self.msg } pub fn backtrace(&self) -> Option<&String> { self.backtrace.as_ref() } pub fn extend<D>(self, msg: D) -> AriesVcxError where D: fmt::Display + fmt::Debug + Send + Sync + 'static, { Self::new(self.kind, format!("{}\n{}", self.msg, msg)) } pub fn map<D>(self, kind: AriesVcxErrorKind, msg: D) -> AriesVcxError where D: fmt::Display + fmt::Debug + Send + Sync + 'static, { Self::new(kind, msg.to_string()) } } pub fn err_msg<D>(kind: AriesVcxErrorKind, msg: D) -> AriesVcxError where D: fmt::Display + fmt::Debug + Send + Sync + 'static, { AriesVcxError::from_msg(kind, msg) } pub type VcxResult<T> = Result<T, AriesVcxError>;
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/errors/mapping_others.rs
aries/aries_vcx/src/errors/mapping_others.rs
use std::{num::ParseIntError, string::FromUtf8Error, sync::PoisonError}; use base64::DecodeError; use did_doc::schema::{types::uri::UriWrapperError, utils::error::DidDocumentLookupError}; use shared::errors::http_error::HttpError; use url::ParseError; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind}, protocols::revocation_notification::sender::state_machine::SenderConfigBuilderError, }; impl From<SenderConfigBuilderError> for AriesVcxError { fn from(err: SenderConfigBuilderError) -> AriesVcxError { let vcx_error_kind = AriesVcxErrorKind::InvalidConfiguration; AriesVcxError::from_msg(vcx_error_kind, err.to_string()) } } impl From<serde_json::Error> for AriesVcxError { fn from(_err: serde_json::Error) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidJson, "Invalid json".to_string()) } } impl<T> From<PoisonError<T>> for AriesVcxError { fn from(err: PoisonError<T>) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidState, err.to_string()) } } impl From<HttpError> for AriesVcxError { fn from(err: HttpError) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::PostMessageFailed, err.to_string()) } } impl From<did_parser_nom::ParseError> for AriesVcxError { fn from(err: did_parser_nom::ParseError) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidState, err.to_string()) } } impl From<did_doc::error::DidDocumentBuilderError> for AriesVcxError { fn from(err: did_doc::error::DidDocumentBuilderError) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidState, err.to_string()) } } impl From<DidDocumentLookupError> for AriesVcxError { fn from(err: DidDocumentLookupError) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidState, err.to_string()) } } impl From<did_peer::error::DidPeerError> for AriesVcxError { fn from(err: did_peer::error::DidPeerError) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidState, err.to_string()) } } impl From<did_resolver::error::GenericError> for AriesVcxError { fn from(err: did_resolver::error::GenericError) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidState, err.to_string()) } } impl From<public_key::PublicKeyError> for AriesVcxError { fn from(err: public_key::PublicKeyError) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidState, err.to_string()) } } impl From<did_key::error::DidKeyError> for AriesVcxError { fn from(err: did_key::error::DidKeyError) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidState, err.to_string()) } } impl From<anoncreds_types::Error> for AriesVcxError { fn from(err: anoncreds_types::Error) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidState, err.to_string()) } } impl From<UriWrapperError> for AriesVcxError { fn from(err: UriWrapperError) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidInput, err.to_string()) } } impl From<ParseIntError> for AriesVcxError { fn from(err: ParseIntError) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidInput, err.to_string()) } } impl From<DecodeError> for AriesVcxError { fn from(err: DecodeError) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidInput, err.to_string()) } } impl From<FromUtf8Error> for AriesVcxError { fn from(err: FromUtf8Error) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidInput, err.to_string()) } } impl From<ParseError> for AriesVcxError { fn from(err: ParseError) -> Self { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidInput, err.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/errors/mod.rs
aries/aries_vcx/src/errors/mod.rs
pub mod error; mod mapping_anoncreds; mod mapping_diddoc; mod mapping_ledger; mod mapping_others; mod mapping_wallet;
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/errors/mapping_ledger.rs
aries/aries_vcx/src/errors/mapping_ledger.rs
use aries_vcx_ledger::errors::error::VcxLedgerError; use super::error::{AriesVcxError, AriesVcxErrorKind}; impl From<VcxLedgerError> for AriesVcxError { fn from(value: VcxLedgerError) -> Self { match value { VcxLedgerError::LedgerItemNotFound => { Self::from_msg(AriesVcxErrorKind::LedgerItemNotFound, value) } VcxLedgerError::InvalidLedgerResponse(_) => { Self::from_msg(AriesVcxErrorKind::InvalidLedgerResponse, value) } VcxLedgerError::DuplicationSchema => { Self::from_msg(AriesVcxErrorKind::DuplicationSchema, value) } VcxLedgerError::InvalidJson(_) => Self::from_msg(AriesVcxErrorKind::InvalidJson, value), VcxLedgerError::WalletError(_) => Self::from_msg(AriesVcxErrorKind::WalletError, value), VcxLedgerError::InvalidState(_) => { Self::from_msg(AriesVcxErrorKind::InvalidState, value) } VcxLedgerError::InvalidOption(_) => { Self::from_msg(AriesVcxErrorKind::InvalidOption, value) } VcxLedgerError::ParseError(_) => Self::from_msg(AriesVcxErrorKind::ParsingError, value), VcxLedgerError::UnimplementedFeature(_) => { Self::from_msg(AriesVcxErrorKind::UnimplementedFeature, value) } VcxLedgerError::InvalidConfiguration(_) => { Self::from_msg(AriesVcxErrorKind::InvalidConfiguration, value) } VcxLedgerError::PoolLedgerConnect(_) => { Self::from_msg(AriesVcxErrorKind::PoolLedgerConnect, value) } VcxLedgerError::IOError(_) => Self::from_msg(AriesVcxErrorKind::IOError, value), VcxLedgerError::InvalidInput(_) | VcxLedgerError::IndyVdrValidation(_) | VcxLedgerError::UnsupportedLedgerIdentifier(_) => { Self::from_msg(AriesVcxErrorKind::InvalidInput, value) } VcxLedgerError::UnknownError(_) => { Self::from_msg(AriesVcxErrorKind::UnknownError, value) } } } }
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/errors/mapping_diddoc.rs
aries/aries_vcx/src/errors/mapping_diddoc.rs
use diddoc_legacy::errors::error::{DiddocError, DiddocErrorKind}; use crate::errors::error::{AriesVcxError, AriesVcxErrorKind}; impl From<DiddocError> for AriesVcxError { fn from(msg_err: DiddocError) -> AriesVcxError { let vcx_error_kind: AriesVcxErrorKind = msg_err.kind().into(); AriesVcxError::from_msg(vcx_error_kind, msg_err.to_string()) } } impl From<DiddocErrorKind> for AriesVcxErrorKind { fn from(msg_err: DiddocErrorKind) -> AriesVcxErrorKind { match msg_err { DiddocErrorKind::InvalidState => AriesVcxErrorKind::InvalidState, DiddocErrorKind::InvalidJson => AriesVcxErrorKind::InvalidJson, DiddocErrorKind::InvalidDid => AriesVcxErrorKind::InvalidDid, DiddocErrorKind::InvalidVerkey => AriesVcxErrorKind::InvalidVerkey, DiddocErrorKind::InvalidUrl => AriesVcxErrorKind::InvalidUrl, DiddocErrorKind::NotBase58 => AriesVcxErrorKind::NotBase58, DiddocErrorKind::SerializationError => AriesVcxErrorKind::SerializationError, } } }
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/utils/didcomm_utils.rs
aries/aries_vcx/src/utils/didcomm_utils.rs
use did_doc::schema::{ did_doc::DidDocument, service::service_key_kind::ServiceKeyKind, types::uri::Uri, verification_method::VerificationMethodType, }; use public_key::{Key, KeyType}; use crate::errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}; pub(crate) fn resolve_service_key_to_typed_key( key: &ServiceKeyKind, did_document: &DidDocument, ) -> VcxResult<Key> { match key { ServiceKeyKind::DidKey(did_key) => Ok(did_key.key().clone()), ServiceKeyKind::Reference(reference) => { let verification_method = did_document.dereference_key(reference).ok_or_else(|| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!("Unable to dereference key: {reference}"), ) })?; let key = verification_method.public_key().map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!("Unable to get public key from verification method: {err}"), ) })?; Ok(key) } ServiceKeyKind::Value(value) => Ok(Key::new( value.as_bytes().to_vec(), public_key::KeyType::Ed25519, )?), } } /// Resolves the first ed25519 base58 public key (a.k.a. verkey) within the DIDDocuments key /// agreement keys. Useful for resolving keys that can be used for packing DIDCommV1 messages. pub fn resolve_ed25519_key_agreement(did_document: &DidDocument) -> VcxResult<Key> { let vm_types = [ VerificationMethodType::Ed25519VerificationKey2018, VerificationMethodType::Ed25519VerificationKey2020, VerificationMethodType::X25519KeyAgreementKey2019, VerificationMethodType::X25519KeyAgreementKey2020, VerificationMethodType::Multikey, // would be nice to search for X25519 VM types which could be derived into ed25519 keys // for the encryption envelope to use. // would be nice to search for other VM types which _could_ be ed25519 (jwk etc) ]; let vm = did_document.get_key_agreement_of_type(&vm_types)?; let key = vm.public_key()?; Ok(key.validate_key_type(KeyType::Ed25519)?.to_owned()) } pub fn get_ed25519_routing_keys( their_did_doc: &DidDocument, service_id: &Uri, ) -> VcxResult<Vec<Key>> { let service = their_did_doc.get_service_by_id(service_id)?; let Ok(routing_keys) = service.extra_field_routing_keys() else { return Ok(vec![]); }; let mut ed25519_routing_keys = Vec::new(); for key in routing_keys.iter() { let pub_key = resolve_service_key_to_typed_key(key, their_did_doc)?; if pub_key.key_type() == &KeyType::Ed25519 { ed25519_routing_keys.push(pub_key); } else { warn!( "Unexpected key with type {} in routing keys list", pub_key.key_type() ); } } Ok(ed25519_routing_keys) } pub fn get_ed25519_recipient_keys( their_did_doc: &DidDocument, service_id: &Uri, ) -> VcxResult<Vec<Key>> { let service = their_did_doc.get_service_by_id(service_id)?; let Ok(recipient_keys) = service.extra_field_recipient_keys() else { return Ok(vec![]); }; let mut ed25519_recipient_keys = Vec::new(); for key in recipient_keys.iter() { let pub_key = resolve_service_key_to_typed_key(key, their_did_doc)?; if pub_key.key_type() == &KeyType::Ed25519 { ed25519_recipient_keys.push(pub_key); } else { warn!( "Unexpected key with type {} in recipient keys list", pub_key.key_type() ); } } Ok(ed25519_recipient_keys) }
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/utils/serialization.rs
aries/aries_vcx/src/utils/serialization.rs
use crate::errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}; #[derive(Debug, Serialize, Deserialize)] pub struct ObjectWithVersion<'a, T> { pub version: &'a str, pub data: T, } impl<'a, T> ObjectWithVersion<'a, T> where T: ::serde::Serialize + ::serde::de::DeserializeOwned, { pub fn new(version: &'a str, data: T) -> ObjectWithVersion<'a, T> { ObjectWithVersion { version, data } } pub fn serialize(&self) -> VcxResult<String> { ::serde_json::to_string(self).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot serialize object: {err}"), ) }) } pub fn deserialize(data: &str) -> VcxResult<ObjectWithVersion<T>> where T: ::serde::de::DeserializeOwned, { ::serde_json::from_str(data).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot deserialize object: {err}"), ) }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(tag = "version")] pub enum SerializableObjectWithState<T, P> { #[serde(rename = "1.0")] V1 { data: T, state: P, source_id: String, thread_id: String, }, } #[cfg(test)] mod tests { use serde_json; use super::*; #[test] fn test_serialize() { let value = SerializableObjectWithState::V1 { data: vec!["name".to_string(), "age".to_string()], state: "1".to_string(), source_id: "foo".to_string(), thread_id: "bat".to_string(), }; let serialized = serde_json::to_string(&value).unwrap(); assert!(serialized.contains(r#""data":["name","age"]"#)); assert!(serialized.contains(r#""state":"1""#)); assert!(serialized.contains(r#""source_id":"foo""#)); assert!(serialized.contains(r#""thread_id":"bat""#)); } #[test] fn test_deserialize() { let serialized = r#" { "data": [ "name", "age" ], "state": "1", "source_id": "foo", "thread_id": "bat", "version": "1.0" } "#; let result = serde_json::from_str(serialized); let ans: SerializableObjectWithState<Vec<String>, String> = result.unwrap(); let (data, state, source_id, thread_id) = match ans { SerializableObjectWithState::V1 { data, state, source_id, thread_id, } => (data, state, source_id, thread_id), }; assert_eq!(data, vec!["name".to_string(), "age".to_string()]); assert_eq!(state, "1"); assert_eq!(source_id, "foo"); assert_eq!(thread_id, "bat"); } }
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/utils/validation.rs
aries/aries_vcx/src/utils/validation.rs
use bs58; use messages::msg_types::Role; use crate::{errors::error::prelude::*, utils::qualifier}; pub fn validate_did(did: &str) -> VcxResult<String> { if qualifier::is_fully_qualified(did) { Ok(did.to_string()) } else { let check_did = String::from(did); match bs58::decode(check_did.clone()).into_vec() { Ok(ref x) if x.len() == 16 => Ok(check_did), Ok(x) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidDid, format!( "Invalid DID length, expected 16 bytes, decoded {} bytes", x.len() ), )), Err(err) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotBase58, format!("DID is not valid base58, details: {err}"), )), } } } pub fn validate_key_delegate(delegate: &str) -> VcxResult<String> { //todo: find out what needs to be validated for key_delegate let check_delegate = String::from(delegate); Ok(check_delegate) } pub fn validate_actors(actors: &str) -> VcxResult<Vec<Role>> { ::serde_json::from_str(actors).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidOption, format!("Invalid actors: {err:?}"), ) }) } #[cfg(test)] mod unit_tests { use test_utils::devsetup::SetupMocks; use super::*; #[test] fn test_did_is_b58_and_valid_length() { let _setup = SetupMocks::init(); let to_did = "8XFh8yBzrpJQmNyZzgoTqB"; match validate_did(to_did) { Err(_) => panic!("Should be valid did"), Ok(x) => assert_eq!(x, to_did.to_string()), } } #[test] fn test_did_is_b58_but_invalid_length() { let _setup = SetupMocks::init(); let to_did = "8XFh8yBzrpJQmNyZzgoT"; match validate_did(to_did) { Err(x) => assert_eq!(x.kind(), AriesVcxErrorKind::InvalidDid), Ok(_) => panic!("Should be invalid did"), } } #[test] fn test_validate_did_with_non_base58() { let _setup = SetupMocks::init(); let to_did = "8*Fh8yBzrpJQmNyZzgoTqB"; match validate_did(to_did) { Err(x) => assert_eq!(x.kind(), AriesVcxErrorKind::NotBase58), Ok(_) => panic!("Should be invalid did"), } } }
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/utils/base64.rs
aries/aries_vcx/src/utils/base64.rs
use base64::{ alphabet, engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig}, }; /// A default [GeneralPurposeConfig] configuration with a [decode_padding_mode] of /// [DecodePaddingMode::Indifferent], and const LENIENT_PAD: GeneralPurposeConfig = GeneralPurposeConfig::new() .with_encode_padding(false) .with_decode_padding_mode(DecodePaddingMode::Indifferent); /// A [GeneralPurpose] engine using the [alphabet::URL_SAFE] base64 alphabet and /// [DecodePaddingMode::Indifferent] config to decode both padded and unpadded. /// It will encode with NO padding. /// In alignment with RFC 0017 https://github.com/decentralized-identity/aries-rfcs/tree/main/concepts/0017-attachments#base64url pub const URL_SAFE_LENIENT: GeneralPurpose = GeneralPurpose::new(&alphabet::URL_SAFE, LENIENT_PAD);
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/utils/openssl.rs
aries/aries_vcx/src/utils/openssl.rs
use num_bigint::BigUint; use sha2::{Digest, Sha256}; use crate::errors::error::prelude::*; pub fn encode(s: &str) -> VcxResult<String> { match s.parse::<u32>() { Ok(val) => Ok(val.to_string()), Err(_) => { let mut hasher = Sha256::new(); hasher.update(s.as_bytes()); let hash = hasher.finalize(); let bignum = BigUint::from_bytes_be(hash.as_slice()); let encoded = bignum.to_str_radix(10); Ok(encoded) } } } #[cfg(test)] mod test { use super::*; #[test] fn test_encoding() { // number { let value = "1234"; let expected_value = value; let encoded_value = encode(value).unwrap(); assert_eq!(expected_value, encoded_value); } // number with leading zero { let value = "01234"; let expected_value = "1234"; let encoded_value = encode(value).unwrap(); assert_eq!(expected_value, encoded_value); } // string { let value = "Cat"; let expected_value = "32770349619296211525721019403974704547883091481854305319049714074652726739013"; let encoded_value = encode(value).unwrap(); assert_eq!(expected_value, encoded_value); } } }
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/utils/qualifier.rs
aries/aries_vcx/src/utils/qualifier.rs
use regex::Regex; lazy_static! { pub static ref REGEX: Regex = Regex::new("did:([a-z0-9]+):([a-zA-Z0-9:.-_]*)").expect("Unexpected regex error occurred."); } pub fn is_fully_qualified(entity: &str) -> bool { REGEX.is_match(entity) } #[cfg(test)] mod test { use super::*; #[test] fn is_fully_qualified_works() { assert!(is_fully_qualified("did:indy:some")); assert!(!is_fully_qualified("did:indy")); assert!(!is_fully_qualified("indy:some")); } }
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/utils/mod.rs
aries/aries_vcx/src/utils/mod.rs
#[cfg(debug_assertions)] #[macro_export] macro_rules! secret { ($val:expr) => {{ $val }}; } #[cfg(not(debug_assertions))] #[macro_export] macro_rules! secret { ($val:expr) => {{ "_" }}; } pub mod base64; pub mod openssl; pub mod qualifier; #[macro_use] pub mod encryption_envelope; pub mod didcomm_utils; pub mod serialization; pub mod validation;
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/utils/encryption_envelope.rs
aries/aries_vcx/src/utils/encryption_envelope.rs
use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use did_doc::schema::{did_doc::DidDocument, types::uri::Uri}; use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::{ msg_fields::protocols::routing::{Forward, ForwardContent}, AriesMessage, }; use public_key::{Key, KeyType}; use uuid::Uuid; use crate::{ errors::error::prelude::*, utils::didcomm_utils::{ get_ed25519_recipient_keys, get_ed25519_routing_keys, resolve_ed25519_key_agreement, }, }; #[derive(Debug)] pub struct EncryptionEnvelope(pub Vec<u8>); impl EncryptionEnvelope { pub async fn create_from_legacy( wallet: &impl BaseWallet, data: &[u8], sender_vk: Option<&str>, did_doc: &AriesDidDoc, ) -> VcxResult<EncryptionEnvelope> { trace!( "EncryptionEnvelope::create >>> data: {data:?}, sender_vk: {sender_vk:?}, did_doc: {did_doc:?}" ); let recipient_key_base58 = did_doc .recipient_keys()? .first() .cloned() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!("No recipient key found in DIDDoc: {did_doc:?}"), ))?; let recipient_key = Key::from_base58(&recipient_key_base58, KeyType::Ed25519)?; let routing_keys = did_doc .routing_keys() .iter() .map(|routing_key| Key::from_base58(routing_key, KeyType::Ed25519)) .collect::<Result<Vec<_>, _>>()?; let sender_key = sender_vk .map(|key| Key::from_base58(key, KeyType::Ed25519)) .transpose()?; Self::create_from_keys(wallet, data, sender_key, recipient_key, routing_keys).await } /// Create encrypted message based on key agreement keys of our did document, counterparties /// did document and their specific service, identified by id, which must be part of their /// did document /// /// # Arguments /// /// * `our_did_doc` - Our did_document, which the counterparty should already be in possession /// of /// * `their_did_doc` - The did document of the counterparty, the recipient of the encrypted /// message /// * `their_service_id` - Id of service where message will be sent. The counterparty did /// document must contain Service object identified with such value. pub async fn create( wallet: &impl BaseWallet, data: &[u8], our_did_doc: &DidDocument, their_did_doc: &DidDocument, their_service_id: &Uri, ) -> VcxResult<EncryptionEnvelope> { let sender_vk = resolve_ed25519_key_agreement(our_did_doc)?; let recipient_key = { let service_keys = get_ed25519_recipient_keys(their_did_doc, their_service_id)?; match service_keys.into_iter().next() { Some(key) => key, // as a backup, use the first key agreement key, or none None => resolve_ed25519_key_agreement(their_did_doc)?, } }; let routing_keys = get_ed25519_routing_keys(their_did_doc, their_service_id)?; EncryptionEnvelope::create_from_keys( wallet, data, Some(sender_vk), recipient_key, routing_keys, ) .await } pub async fn create_from_keys( wallet: &impl BaseWallet, data: &[u8], sender_vk: Option<Key>, recipient_key: Key, routing_keys: Vec<Key>, ) -> VcxResult<EncryptionEnvelope> { // Validate keys are Ed25519 sender_vk .as_ref() .map(|key| key.validate_key_type(KeyType::Ed25519)) .transpose()?; for key in routing_keys.iter().as_ref() { key.validate_key_type(KeyType::Ed25519)?; } let message = EncryptionEnvelope::encrypt_for_pairwise( wallet, data, sender_vk, recipient_key.validate_key_type(KeyType::Ed25519)?.clone(), ) .await?; EncryptionEnvelope::wrap_into_forward_messages(wallet, message, recipient_key, routing_keys) .await .map(EncryptionEnvelope) } async fn encrypt_for_pairwise( wallet: &impl BaseWallet, data: &[u8], sender_vk: Option<Key>, recipient_key: Key, ) -> VcxResult<Vec<u8>> { debug!("Encrypting for pairwise; sender_vk: {sender_vk:?}, recipient_key: {recipient_key}"); let recipient_keys = vec![recipient_key]; wallet .pack_message(sender_vk, recipient_keys, data) .await .map_err(|err| err.into()) } async fn wrap_into_forward_messages( wallet: &impl BaseWallet, mut data: Vec<u8>, recipient_key: Key, routing_keys: Vec<Key>, ) -> VcxResult<Vec<u8>> { let mut forward_to_key = recipient_key; for routing_key in routing_keys { debug!( "Wrapping message in forward message; forward_to_key: {forward_to_key}, routing_key: {routing_key}" ); data = EncryptionEnvelope::wrap_into_forward( wallet, data, &forward_to_key, routing_key.clone(), ) .await?; forward_to_key.clone_from(&routing_key); } Ok(data) } async fn wrap_into_forward( wallet: &impl BaseWallet, data: Vec<u8>, forward_to_key: &Key, routing_key: Key, ) -> VcxResult<Vec<u8>> { let content = ForwardContent::builder() .to(forward_to_key.base58()) .msg(serde_json::from_slice(&data)?) .build(); let message: Forward = Forward::builder() .id(Uuid::new_v4().to_string()) .content(content) .build(); let message = json!(AriesMessage::from(message)).to_string(); let receiver_keys = vec![routing_key]; wallet .pack_message(None, receiver_keys, message.as_bytes()) .await .map_err(|err| err.into()) } // Will unpack a message as either anoncrypt or authcrypt. async fn unpack_a2a_message( wallet: &impl BaseWallet, encrypted_data: &[u8], ) -> VcxResult<(String, Option<Key>, Key)> { trace!( "EncryptionEnvelope::unpack_a2a_message >>> processing payload of {} bytes", encrypted_data.len() ); let unpacked_msg = wallet.unpack_message(encrypted_data).await?; let sender_key = unpacked_msg .sender_verkey .map(|key| Key::from_base58(&key, KeyType::Ed25519)) .transpose()?; Ok(( unpacked_msg.message, sender_key, Key::from_base58(&unpacked_msg.recipient_verkey, KeyType::Ed25519)?, )) } /// Unpacks an authcrypt or anoncrypt message returning the message, which is deserialized into an Aries message, as well as the sender key (if any -- anoncrypt does not return this) and the recipient key. Optionally takes expected_sender_vk, which does a comparison to ensure the sender key is the expected key. pub async fn unpack_aries_msg( wallet: &impl BaseWallet, encrypted_data: &[u8], expected_sender_vk: &Option<Key>, ) -> VcxResult<(AriesMessage, Option<Key>, Key)> { let (message, sender_vk, recipient_vk) = Self::unpack(wallet, encrypted_data, expected_sender_vk).await?; let a2a_message = serde_json::from_str(&message).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot deserialize A2A message: {err}"), ) })?; Ok((a2a_message, sender_vk, recipient_vk)) } /// Unpacks an authcrypt or anoncrypt message returning the message, the sender key (if any -- anoncrypt does not return this), and the recipient key. Optionally takes expected_sender_vk, which does a comparison to ensure the sender key is the expected key. pub async fn unpack( wallet: &impl BaseWallet, encrypted_data: &[u8], expected_sender_vk: &Option<Key>, ) -> VcxResult<(String, Option<Key>, Key)> { trace!( "EncryptionEnvelope::anon_unpack >>> processing payload of {} bytes", encrypted_data.len() ); let (a2a_message, sender_vk, recipient_vk) = Self::unpack_a2a_message(wallet, encrypted_data).await?; // If expected_sender_vk was provided and a sender_verkey exists, verify that they match if let Some(expected_key) = expected_sender_vk { match &sender_vk { Some(sender_vk) => { if sender_vk != expected_key { error!( "auth_unpack sender_vk != expected_sender_vk.... sender_vk: {sender_vk}, expected_sender_vk: {expected_key}" ); return Err(AriesVcxError::from_msg( AriesVcxErrorKind::AuthenticationError, format!( "Message did not pass authentication check. Expected sender verkey \ was {expected_key}, but actually was {sender_vk}" ), )); } } None => { error!("auth_unpack message was authcrypted"); return Err(AriesVcxError::from_msg( AriesVcxErrorKind::AuthenticationError, "Can't authenticate message because it was anoncrypted.", )); } } } Ok((a2a_message, sender_vk, recipient_vk)) } } #[cfg(test)] pub mod unit_tests { use aries_vcx_wallet::wallet::base_wallet::did_wallet::DidWallet; use serde_json::Value; use test_utils::devsetup::build_setup_profile; use super::*; #[tokio::test] async fn test_pack_unpack_anon() { let setup = build_setup_profile().await; let did_data = setup .wallet .create_and_store_my_did(None, None) .await .unwrap(); let data_original = "foobar"; let envelope = EncryptionEnvelope::create_from_keys( &setup.wallet, data_original.as_bytes(), None, did_data.verkey().clone(), [].to_vec(), ) .await .unwrap(); let (data_unpacked, sender_verkey, _) = EncryptionEnvelope::unpack(&setup.wallet, &envelope.0, &None) .await .unwrap(); assert_eq!(data_original, data_unpacked); assert!(sender_verkey.is_none()); } #[tokio::test] async fn test_pack_unpack_auth() { let setup = build_setup_profile().await; let sender_data = setup .wallet .create_and_store_my_did(None, None) .await .unwrap(); let recipient_data = setup .wallet .create_and_store_my_did(None, None) .await .unwrap(); let sender_vk = sender_data.verkey().clone(); let recipient_vk = recipient_data.verkey(); let data_original = "foobar"; let envelope = EncryptionEnvelope::create_from_keys( &setup.wallet, data_original.as_bytes(), Some(sender_vk.clone()), recipient_vk.clone(), [].to_vec(), ) .await .unwrap(); let (data_unpacked, _sender_vk_unpacked, _recipient_vk_unpacked) = EncryptionEnvelope::unpack(&setup.wallet, &envelope.0, &Some(sender_vk)) .await .unwrap(); assert_eq!(data_original, data_unpacked); } #[tokio::test] async fn test_pack_unpack_with_routing() { let setup = build_setup_profile().await; let sender_data = setup .wallet .create_and_store_my_did(None, None) .await .unwrap(); let recipient_data = setup .wallet .create_and_store_my_did(None, None) .await .unwrap(); let routing_data = setup .wallet .create_and_store_my_did(None, None) .await .unwrap(); let data_original = "foobar"; let envelope = EncryptionEnvelope::create_from_keys( &setup.wallet, data_original.as_bytes(), Some(sender_data.verkey().clone()), recipient_data.verkey().clone(), [routing_data.verkey().clone()].to_vec(), ) .await .unwrap(); let (fwd_msg, _, _) = EncryptionEnvelope::unpack(&setup.wallet, &envelope.0, &None) .await .unwrap(); let fwd_payload = serde_json::from_str::<Value>(&fwd_msg) .unwrap() .get("msg") .unwrap() .to_string(); let (core_payload, _, _) = EncryptionEnvelope::unpack(&setup.wallet, fwd_payload.as_bytes(), &None) .await .unwrap(); assert_eq!(data_original, core_payload); } #[tokio::test] async fn test_pack_unpack_unexpected_key_detection() { let setup = build_setup_profile().await; let alice_data = setup .wallet .create_and_store_my_did(None, None) .await .unwrap(); let bob_data = setup .wallet .create_and_store_my_did(None, None) .await .unwrap(); let recipient_data = setup .wallet .create_and_store_my_did(None, None) .await .unwrap(); let data_original = "foobar"; let envelope = EncryptionEnvelope::create_from_keys( &setup.wallet, data_original.as_bytes(), Some(bob_data.verkey().clone()), // bob trying to impersonate alice recipient_data.verkey().clone(), [].to_vec(), ) .await .unwrap(); let err = EncryptionEnvelope::unpack( &setup.wallet, &envelope.0, &Some(alice_data.verkey().clone()), ) .await; assert!(err.is_err()); assert_eq!( err.unwrap_err().kind(), AriesVcxErrorKind::AuthenticationError ); } }
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/common/mod.rs
aries/aries_vcx/src/common/mod.rs
pub mod credentials; pub mod keys; pub mod ledger; pub mod primitives; pub mod proofs; pub mod signing;
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/common/signing.rs
aries/aries_vcx/src/common/signing.rs
use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use base64::{self, Engine}; use messages::msg_fields::protocols::connection::{ response::{ConnectionSignature, ResponseContent}, ConnectionData, }; use public_key::{Key, KeyType}; use time; use crate::{errors::error::prelude::*, utils::base64::URL_SAFE_LENIENT}; // Utility function to handle both padded and unpadded Base64URL data fn base64url_decode(encoded: &str) -> VcxResult<Vec<u8>> { URL_SAFE_LENIENT.decode(encoded).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot decode Base64URL data: {err:?}"), ) }) } async fn get_signature_data( wallet: &impl BaseWallet, data: String, key: &str, ) -> VcxResult<(Vec<u8>, Vec<u8>)> { let now: u64 = time::OffsetDateTime::now_utc().unix_timestamp() as u64; let mut sig_data = now.to_be_bytes().to_vec(); sig_data.extend(data.as_bytes()); let signature = wallet .sign(&Key::from_base58(key, KeyType::Ed25519)?, &sig_data) .await?; Ok((signature, sig_data)) } pub async fn sign_connection_response( wallet: &impl BaseWallet, key: &str, con_data: &ConnectionData, ) -> VcxResult<ConnectionSignature> { let con_data = json!(con_data).to_string(); let (signature, sig_data) = get_signature_data(wallet, con_data, key).await?; let sig_data = URL_SAFE_LENIENT.encode(sig_data); let signature = URL_SAFE_LENIENT.encode(signature); let connection_sig = ConnectionSignature::new(signature, sig_data, key.to_string()); Ok(connection_sig) } pub async fn decode_signed_connection_response( wallet: &impl BaseWallet, response: ResponseContent, their_vk: &str, ) -> VcxResult<ConnectionData> { let signature = URL_SAFE_LENIENT .decode(response.connection_sig.signature.as_bytes()) .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot decode ConnectionResponse: {err:?}"), ) })?; let sig_data = base64url_decode(&response.connection_sig.sig_data)?; if !wallet .verify( &Key::from_base58(their_vk, KeyType::Ed25519)?, &sig_data, &signature, ) .await? { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, "ConnectionResponse signature is invalid for original Invite recipient key", )); } if response.connection_sig.signer != their_vk { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, "Signer declared in ConnectionResponse signed response is not matching the actual \ signer. Connection ", )); } let sig_data = &sig_data[8..]; let connection: ConnectionData = serde_json::from_slice(sig_data) .map_err(|err| AriesVcxError::from_msg(AriesVcxErrorKind::InvalidJson, err.to_string()))?; Ok(connection) } // #[cfg(test)] // pub mod unit_tests { // use crate::common::test_utils::{create_trustee_key, indy_handles_to_profile}; // use crate::utils::devsetup::SetupEmpty; // use aries_vcx_core::indy::utils::test_setup::with_wallet; // use aries_vcx_core::INVALID_POOL_HANDLE; // use diddoc_legacy::aries::diddoc::test_utils::*; // use messages::protocols::connection::response::test_utils::{_did, _response, _thread_id}; // use super::*; // #[test] // fn test_response_build_works() { // SetupEmpty::init(); // let response: Response = Response::default() // .set_did(_did()) // .set_thread_id(&_thread_id()) // .set_service_endpoint(_service_endpoint()) // .set_keys(_recipient_keys(), _routing_keys()); // assert_eq!(_response(), response); // } // #[tokio::test] // async fn test_response_encode_works() { // SetupEmpty::init(); // with_wallet(|wallet_handle| async move { // let profile = indy_handles_to_profile(wallet_handle, INVALID_POOL_HANDLE); // let trustee_key = create_trustee_key(&profile).await; // let signed_response: SignedResponse = // sign_connection_response(&profile.inject_wallet(), &trustee_key, _response()) // .await // .unwrap(); // assert_eq!( // _response(), // decode_signed_connection_response(&profile.inject_wallet(), signed_response, // &trustee_key) .await // .unwrap() // ); // }) // .await; // } // #[tokio::test] // async fn test_decode_returns_error_if_signer_differs() { // SetupEmpty::init(); // with_wallet(|wallet_handle| async move { // let profile = indy_handles_to_profile(wallet_handle, INVALID_POOL_HANDLE); // let trustee_key = create_trustee_key(&profile).await; // let mut signed_response: SignedResponse = // sign_connection_response(&profile.inject_wallet(), &trustee_key, _response()) // .await // .unwrap(); // signed_response.connection_sig.signer = // String::from("AAAAAAAAAAAAAAAAXkaJdrQejfztN4XqdsiV4ct3LXKL"); // decode_signed_connection_response(&profile.inject_wallet(), signed_response, &trustee_key) // .await // .unwrap_err(); // }) // .await; // } // } #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn test_decode_padded_and_unpadded_sig_data() { let encoded_padded = "T3BlbkFJIENoYXRHUFQ="; let encoded_unpadded = "T3BlbkFJIENoYXRHUFQ"; let decoded_padded = base64url_decode(encoded_padded).unwrap(); let decoded_unpadded = base64url_decode(encoded_unpadded).unwrap(); assert_eq!(decoded_padded, decoded_unpadded); } #[tokio::test] async fn test_invalid_json_error() { let non_json_input = "Not a JSON input"; let result = base64url_decode(non_json_input); let error = result.unwrap_err(); assert!(matches!(error.kind(), AriesVcxErrorKind::InvalidJson)); } }
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/common/keys.rs
aries/aries_vcx/src/common/keys.rs
use aries_vcx_ledger::ledger::base_ledger::{IndyLedgerRead, IndyLedgerWrite}; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use did_parser_nom::Did; use public_key::{Key, KeyType}; use serde_json::Value; use crate::errors::error::prelude::*; pub async fn rotate_verkey_apply( wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, did: &Did, temp_vk: &str, ) -> VcxResult<()> { let nym_result = indy_ledger_write .publish_nym( wallet, did, did, Some(&Key::from_base58(temp_vk, KeyType::Ed25519)?), None, None, ) .await?; let nym_result_json: Value = serde_json::from_str(&nym_result).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Cannot deserialize {nym_result:?} into Value, err: {err:?}"), ) })?; let response_type: String = nym_result_json["op"] .as_str() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!( "Cannot failed to convert {:?} into str", nym_result_json["op"] ), ))? .to_string(); if response_type != "REPLY" { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidLedgerResponse, format!("Obained non-success ledger response: {nym_result_json}"), )); } Ok(wallet.replace_did_key_apply(&did.to_string()).await?) } pub async fn rotate_verkey( wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, did: &Did, ) -> VcxResult<()> { let trustee_verkey = wallet.replace_did_key_start(&did.to_string(), None).await?; rotate_verkey_apply(wallet, indy_ledger_write, did, &trustee_verkey.base58()).await } pub async fn get_verkey_from_ledger( indy_ledger: &impl IndyLedgerRead, did: &Did, ) -> VcxResult<String> { let nym_response: String = indy_ledger.get_nym(did).await?; let nym_json: Value = serde_json::from_str(&nym_response).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Cannot deserialize {nym_response:?} into Value, err: {err:?}"), ) })?; let nym_data: String = nym_json["result"]["data"] .as_str() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!( "Cannot deserialize {:?} into String", nym_json["result"]["data"] ), ))? .to_string(); let nym_data: Value = serde_json::from_str(&nym_data).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Cannot deserialize {nym_data:?} into Value, err: {err:?}"), ) })?; let unparsed_verkey = nym_data["verkey"] .as_str() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Cannot deserialize {:?} into String", nym_data["verkey"]), ))? .to_string(); expand_abbreviated_verkey(did.id(), &unparsed_verkey) } /// Indy ledgers may return abbreviated verkeys, where the abbreviation only makes sense /// with the context of the NYM, this function expands them to full verkeys fn expand_abbreviated_verkey(nym: &str, verkey: &str) -> VcxResult<String> { let Some(stripped_verkey) = verkey.strip_prefix('~') else { // expansion not needed return Ok(verkey.to_string()); }; let mut decoded_nym = bs58::decode(nym).into_vec().map_err(|e| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidLedgerResponse, format!("Failed to decode did from base58: {nym} (error: {e})"), ) })?; let decoded_stripped_verkey = bs58::decode(stripped_verkey).into_vec().map_err(|e| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidLedgerResponse, format!("Failed to decode verkey from base58: {stripped_verkey} (error: {e})"), ) })?; decoded_nym.extend(&decoded_stripped_verkey); Ok(bs58::encode(decoded_nym).into_string()) } // todo: was originally written for vdrtool ledger implementation, ideally we should moc out // ledger client completely // #[cfg(test)] // mod test { // use aries_vcx_core::ledger::indy::pool_mocks::{enable_pool_mocks, PoolMocks}; // // #[tokio::test] // #[ignore] // #[cfg(all(not(feature = "vdr_proxy_ledger")))] // async fn test_pool_rotate_verkey_fails() { // use super::*; // // use crate::utils::devsetup::*; // use crate::utils::mockdata::mockdata_pool; // // SetupProfile::run(|setup| async move { // enable_pool_mocks(); // // PoolMocks::set_next_pool_response(mockdata_pool::RESPONSE_REQNACK); // PoolMocks::set_next_pool_response(mockdata_pool::NYM_REQUEST_VALID); // // let local_verkey_1 = setup // .profile // .inject_wallet() // .key_for_local_did(&setup.institution_did) // .await // .unwrap(); // assert_eq!( // rotate_verkey( // &setup.profile.inject_wallet(), // &setup.profile.inject_indy_ledger_write(), // &setup.institution_did // ) // .await // .unwrap_err() // .kind(), // AriesVcxErrorKind::InvalidLedgerResponse // ); // let local_verkey_2 = setup // .profile // .inject_wallet() // .key_for_local_did(&setup.institution_did) // .await // .unwrap(); // assert_eq!(local_verkey_1, local_verkey_2); // }) // .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/common/proofs/mod.rs
aries/aries_vcx/src/common/proofs/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/common/proofs/verifier/verifier_internal.rs
aries/aries_vcx/src/common/proofs/verifier/verifier_internal.rs
use anoncreds_types::data_types::identifiers::schema_id::SchemaId; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use serde_json::{self, Value}; use crate::{errors::error::prelude::*, utils::openssl::encode}; #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)] pub struct CredInfoVerifier { pub schema_id: SchemaId, pub cred_def_id: String, pub rev_reg_id: Option<String>, pub timestamp: Option<u64>, } pub fn get_credential_info(proof: &str) -> VcxResult<Vec<CredInfoVerifier>> { let mut rtn = Vec::new(); let credentials: Value = serde_json::from_str(proof).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot deserialize libndy proof: {err}"), ) })?; if let Value::Array(ref identifiers) = credentials["identifiers"] { for identifier in identifiers { if let (Some(schema_id), Some(cred_def_id)) = ( identifier["schema_id"].as_str(), identifier["cred_def_id"].as_str(), ) { let rev_reg_id = identifier["rev_reg_id"].as_str().map(|x| x.to_string()); let timestamp = identifier["timestamp"].as_u64(); rtn.push(CredInfoVerifier { schema_id: SchemaId::new(schema_id)?, cred_def_id: cred_def_id.to_string(), rev_reg_id, timestamp, }); } else { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidProofCredentialData, "Cannot get identifiers", )); } } } Ok(rtn) } pub fn validate_proof_revealed_attributes(proof_json: &str) -> VcxResult<()> { let proof: Value = serde_json::from_str(proof_json).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot deserialize libndy proof: {err}"), ) })?; let revealed_attrs = match proof["requested_proof"]["revealed_attrs"].as_object() { Some(revealed_attrs) => revealed_attrs, None => return Ok(()), }; for (attr1_referent, info) in revealed_attrs.iter() { let raw = info["raw"].as_str().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidProof, format!("Cannot get raw value for \"{attr1_referent}\" attribute"), ))?; let encoded_ = info["encoded"].as_str().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidProof, format!("Cannot get encoded value for \"{attr1_referent}\" attribute"), ))?; let expected_encoded = encode(raw)?; if expected_encoded != *encoded_ { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidProof, format!( "Encoded values are different. Expected: {expected_encoded}. From Proof: {encoded_}" ), )); } } Ok(()) } pub async fn build_cred_defs_json_verifier( ledger: &impl AnoncredsLedgerRead, credential_data: &[CredInfoVerifier], ) -> VcxResult<String> { trace!("build_cred_defs_json_verifier >>"); let mut credential_json = json!({}); for cred_info in credential_data.iter() { if credential_json.get(&cred_info.cred_def_id).is_none() { let cred_def_id = &cred_info.cred_def_id; let credential_def = ledger .get_cred_def(&cred_def_id.to_string().try_into()?, None) .await?; let credential_def = serde_json::to_value(&credential_def).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidProofCredentialData, format!("Cannot deserialize credential definition: {err}"), ) })?; credential_json[cred_def_id] = credential_def; } } Ok(credential_json.to_string()) } pub async fn build_schemas_json_verifier( ledger: &impl AnoncredsLedgerRead, credential_data: &[CredInfoVerifier], ) -> VcxResult<String> { trace!("build_schemas_json_verifier >>"); let mut schemas_json = json!({}); for cred_info in credential_data.iter() { if schemas_json.get(cred_info.schema_id.to_string()).is_none() { let schema_id = &cred_info.schema_id; let schema_json = ledger.get_schema(schema_id, None).await.map_err(|_err| { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidSchema, "Cannot get schema") })?; let schema_val = serde_json::to_value(&schema_json).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidSchema, format!("Cannot deserialize schema: {err}"), ) })?; schemas_json[schema_id.to_string()] = schema_val; } } Ok(schemas_json.to_string()) } pub async fn build_rev_reg_defs_json( ledger: &impl AnoncredsLedgerRead, credential_data: &[CredInfoVerifier], ) -> VcxResult<String> { trace!("build_rev_reg_defs_json >>"); let mut rev_reg_defs_json = json!({}); for cred_info in credential_data.iter().filter(|r| r.rev_reg_id.is_some()) { let rev_reg_id = cred_info .rev_reg_id .as_ref() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidRevocationDetails, format!( "build_rev_reg_defs_json >> Missing rev_reg_id in the record {cred_info:?}" ), ))?; if rev_reg_defs_json.get(rev_reg_id).is_none() { let (json, _meta) = ledger .get_rev_reg_def_json(&rev_reg_id.to_string().try_into()?) .await?; let rev_reg_def_json = serde_json::to_value(&json).or(Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Failed to deserialize as json rev_reg_def: {json:?}"), )))?; rev_reg_defs_json[rev_reg_id] = rev_reg_def_json; } } Ok(rev_reg_defs_json.to_string()) } pub async fn build_rev_reg_json( ledger: &impl AnoncredsLedgerRead, credential_data: &[CredInfoVerifier], ) -> VcxResult<String> { trace!("build_rev_reg_json >>"); let mut rev_regs_json = json!({}); for cred_info in credential_data.iter().filter(|r| r.rev_reg_id.is_some()) { let rev_reg_id = cred_info .rev_reg_id .as_ref() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidRevocationDetails, format!("build_rev_reg_json >> missing rev_reg_id in the record {cred_info:?}"), ))?; let timestamp = cred_info.timestamp.as_ref().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidRevocationTimestamp, format!("Revocation timestamp is missing on record {cred_info:?}"), ))?; if rev_regs_json.get(rev_reg_id).is_none() { let (rev_reg_json, timestamp) = ledger .get_rev_reg(&rev_reg_id.to_owned().try_into()?, timestamp.to_owned()) .await?; let rev_reg_json = serde_json::to_value(rev_reg_json.clone()).or(Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Failed to deserialize as json: {rev_reg_json:?}"), )))?; let rev_reg_json = json!({ timestamp.to_string(): rev_reg_json }); rev_regs_json[rev_reg_id] = rev_reg_json; } } Ok(rev_regs_json.to_string()) } #[cfg(test)] pub mod unit_tests { use anoncreds_types::data_types::ledger::cred_def::CredentialDefinition; use test_utils::{constants::*, devsetup::*, mockdata::mock_ledger::MockLedger}; use super::*; #[tokio::test] async fn test_build_cred_defs_json_verifier_with_multiple_credentials() { let _setup = SetupMocks::init(); let cred1 = CredInfoVerifier { schema_id: schema_id(), cred_def_id: CRED_DEF_ID.to_string(), rev_reg_id: None, timestamp: None, }; let cred2 = CredInfoVerifier { schema_id: schema_id(), cred_def_id: CRED_DEF_ID.to_string(), rev_reg_id: None, timestamp: None, }; let credentials = vec![cred1, cred2]; let ledger_read = MockLedger; let credential_json = build_cred_defs_json_verifier(&ledger_read, &credentials) .await .unwrap(); let json: CredentialDefinition = serde_json::from_str(CRED_DEF_JSON).unwrap(); let expected = json!({ CRED_DEF_ID: json }).to_string(); assert_eq!(credential_json, expected); } #[tokio::test] async fn test_build_schemas_json_verifier_with_multiple_schemas() { let _setup = SetupMocks::init(); let cred1 = CredInfoVerifier { schema_id: schema_id(), cred_def_id: "cred_def_key1".to_string(), rev_reg_id: None, timestamp: None, }; let cred2 = CredInfoVerifier { schema_id: schema_id(), cred_def_id: "cred_def_key2".to_string(), rev_reg_id: None, timestamp: None, }; let ledger_read = MockLedger; let credentials = vec![cred1, cred2]; let schema_json = build_schemas_json_verifier(&ledger_read, &credentials) .await .unwrap(); let json: Value = serde_json::from_str(SCHEMA_JSON).unwrap(); let expected = json!({ SCHEMA_ID: json }).to_string(); assert_eq!(schema_json, expected); } #[tokio::test] async fn test_build_rev_reg_defs_json() { let _setup = SetupMocks::init(); let cred1 = CredInfoVerifier { schema_id: schema_id(), cred_def_id: "cred_def_key1".to_string(), rev_reg_id: Some(REV_REG_ID.to_string()), timestamp: None, }; let cred2 = CredInfoVerifier { schema_id: schema_id(), cred_def_id: "cred_def_key2".to_string(), rev_reg_id: Some(REV_REG_ID.to_string()), timestamp: None, }; let ledger_read = MockLedger; let credentials = vec![cred1, cred2]; let rev_reg_defs_json = build_rev_reg_defs_json(&ledger_read, &credentials) .await .unwrap(); let json: Value = serde_json::to_value(rev_def_json()).unwrap(); let expected = json!({ REV_REG_ID: json }).to_string(); assert_eq!(rev_reg_defs_json, expected); } #[tokio::test] async fn test_build_rev_reg_json() { let _setup = SetupMocks::init(); let cred1 = CredInfoVerifier { schema_id: schema_id(), cred_def_id: "cred_def_key1".to_string(), rev_reg_id: Some(REV_REG_ID.to_string()), timestamp: Some(1), }; let cred2 = CredInfoVerifier { schema_id: schema_id(), cred_def_id: "cred_def_key2".to_string(), rev_reg_id: Some(REV_REG_ID.to_string()), timestamp: Some(2), }; let ledger_read = MockLedger; let credentials = vec![cred1, cred2]; let rev_reg_json = build_rev_reg_json(&ledger_read, &credentials) .await .unwrap(); let json: Value = serde_json::from_str(REV_REG_JSON).unwrap(); let expected = json!({REV_REG_ID:{"1":json}}).to_string(); assert_eq!(rev_reg_json, 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/aries_vcx/src/common/proofs/verifier/mod.rs
aries/aries_vcx/src/common/proofs/verifier/mod.rs
mod verifier_internal; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use crate::{ common::proofs::verifier::verifier_internal::{ build_cred_defs_json_verifier, build_rev_reg_defs_json, build_rev_reg_json, build_schemas_json_verifier, get_credential_info, validate_proof_revealed_attributes, }, errors::error::prelude::*, }; pub async fn validate_indy_proof( ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, proof_json: &str, proof_req_json: &str, ) -> VcxResult<bool> { validate_proof_revealed_attributes(proof_json)?; let credential_data = get_credential_info(proof_json)?; debug!("validate_indy_proof >> credential_data: {credential_data:?}"); let credential_defs_json = build_cred_defs_json_verifier(ledger, &credential_data).await?; let schemas_json = build_schemas_json_verifier(ledger, &credential_data).await?; let rev_reg_defs_json = build_rev_reg_defs_json(ledger, &credential_data) .await .unwrap_or(json!({}).to_string()); let rev_regs_json = build_rev_reg_json(ledger, &credential_data) .await .unwrap_or(json!({}).to_string()); debug!("validate_indy_proof >> credential_defs_json: {credential_defs_json}"); debug!("validate_indy_proof >> schemas_json: {schemas_json}"); trace!("validate_indy_proof >> proof_json: {proof_json}"); debug!("validate_indy_proof >> proof_req_json: {proof_req_json}"); debug!("validate_indy_proof >> rev_reg_defs_json: {rev_reg_defs_json}"); debug!("validate_indy_proof >> rev_regs_json: {rev_regs_json}"); anoncreds .verifier_verify_proof( serde_json::from_str(proof_req_json)?, serde_json::from_str(proof_json)?, serde_json::from_str(&schemas_json)?, serde_json::from_str(&credential_defs_json)?, serde_json::from_str(&rev_reg_defs_json)?, serde_json::from_str(&rev_regs_json)?, ) .await .map_err(|err| err.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/aries_vcx/src/common/proofs/prover/mod.rs
aries/aries_vcx/src/common/proofs/prover/mod.rs
mod prover_internal; use std::collections::HashMap; use anoncreds_types::data_types::messages::{ cred_selection::SelectedCredentials, pres_request::PresentationRequest, presentation::Presentation, }; 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 crate::{ common::proofs::prover::prover_internal::{ build_cred_defs_json_prover, build_requested_credentials_json, build_rev_states_json, build_schemas_json_prover, credential_def_identifiers, }, errors::error::prelude::*, global::settings, }; pub async fn generate_indy_proof( wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, credentials: &SelectedCredentials, self_attested_attrs: HashMap<String, String>, proof_req_data_json: PresentationRequest, ) -> VcxResult<Presentation> { trace!( "generate_indy_proof >>> credentials: {:?}, self_attested_attrs: {:?}", secret!(&credentials), secret!(&self_attested_attrs) ); let mut credentials_identifiers = credential_def_identifiers(credentials, &proof_req_data_json)?; let revoc_states_json = build_rev_states_json(ledger, anoncreds, &mut credentials_identifiers).await?; let requested_credentials = build_requested_credentials_json( &credentials_identifiers, self_attested_attrs, &proof_req_data_json, )?; let schemas_json = build_schemas_json_prover(ledger, &credentials_identifiers).await?; let credential_defs_json = build_cred_defs_json_prover(ledger, &credentials_identifiers).await?; anoncreds .prover_create_proof( wallet, proof_req_data_json, requested_credentials, &settings::DEFAULT_LINK_SECRET_ALIAS.to_string(), schemas_json, credential_defs_json, Some(revoc_states_json), ) .await .map_err(Into::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/aries_vcx/src/common/proofs/prover/prover_internal.rs
aries/aries_vcx/src/common/proofs/prover/prover_internal.rs
use std::{collections::HashMap, path::Path}; use anoncreds_types::data_types::{ identifiers::{cred_def_id::CredentialDefinitionId, schema_id::SchemaId}, messages::{ cred_selection::SelectedCredentials, pres_request::{NonRevokedInterval, PresentationRequest}, presentation::{RequestedAttribute, RequestedCredentials, RequestedPredicate}, }, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::{ BaseAnonCreds, CredentialDefinitionsMap, RevocationStatesMap, SchemasMap, }; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use chrono::Utc; use crate::errors::error::prelude::*; // TODO: Move to anoncreds_types #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)] pub struct CredInfoProver { pub referent: String, pub credential_referent: String, pub schema_id: SchemaId, pub cred_def_id: CredentialDefinitionId, pub rev_reg_id: Option<String>, pub cred_rev_id: Option<u32>, pub revocation_interval: Option<NonRevokedInterval>, pub tails_dir: Option<String>, pub timestamp: Option<u64>, pub revealed: Option<bool>, } pub async fn build_schemas_json_prover( ledger: &impl AnoncredsLedgerRead, credentials_identifiers: &Vec<CredInfoProver>, ) -> VcxResult<SchemasMap> { trace!("build_schemas_json_prover >>> credentials_identifiers: {credentials_identifiers:?}"); let mut rtn: SchemasMap = HashMap::new(); for cred_info in credentials_identifiers { if !rtn.contains_key(&cred_info.schema_id) { let schema_json = ledger .get_schema(&cred_info.schema_id, None) .await .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidSchema, format!("Cannot get schema id {}; {}", cred_info.schema_id, err), ) })?; rtn.insert(cred_info.schema_id.to_owned(), schema_json); } } Ok(rtn) } pub async fn build_cred_defs_json_prover( ledger: &impl AnoncredsLedgerRead, credentials_identifiers: &Vec<CredInfoProver>, ) -> VcxResult<CredentialDefinitionsMap> { trace!("build_cred_defs_json_prover >>> credentials_identifiers: {credentials_identifiers:?}"); let mut rtn: CredentialDefinitionsMap = HashMap::new(); for cred_info in credentials_identifiers { if !rtn.contains_key(&cred_info.cred_def_id) { let credential_def = ledger .get_cred_def(&cred_info.cred_def_id, None) .await .map_err(|_err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidProofCredentialData, "Cannot get credential definition", ) })?; rtn.insert(cred_info.cred_def_id.to_owned(), credential_def); } } Ok(rtn) } pub fn credential_def_identifiers( credentials: &SelectedCredentials, proof_req: &PresentationRequest, ) -> VcxResult<Vec<CredInfoProver>> { trace!("credential_def_identifiers >>> credentials: {credentials:?}, proof_req: {proof_req:?}"); let mut rtn = Vec::new(); for (referent, selected_cred) in credentials.credential_for_referent.iter() { let cred_info = &selected_cred.credential.cred_info; rtn.push(CredInfoProver { referent: referent.clone(), credential_referent: cred_info.referent.clone(), schema_id: cred_info.schema_id.clone(), cred_def_id: cred_info.cred_def_id.clone(), revocation_interval: _get_revocation_interval(referent, proof_req)?, timestamp: None, rev_reg_id: cred_info.rev_reg_id.clone(), cred_rev_id: cred_info.cred_rev_id, tails_dir: selected_cred.tails_dir.clone(), revealed: cred_info.revealed, }); } Ok(rtn) } fn _get_revocation_interval( attr_name: &str, proof_req: &PresentationRequest, ) -> VcxResult<Option<NonRevokedInterval>> { if let Some(attr) = proof_req.value().requested_attributes.get(attr_name) { Ok(attr .non_revoked .clone() .or(proof_req.value().non_revoked.clone().or(None))) } else if let Some(attr) = proof_req.value().requested_predicates.get(attr_name) { // Handle case for predicates Ok(attr .non_revoked .clone() .or(proof_req.value().non_revoked.clone().or(None))) } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidProofCredentialData, format!("Attribute not found for: {attr_name}"), )) } } pub async fn build_rev_states_json( ledger_read: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, credentials_identifiers: &mut Vec<CredInfoProver>, ) -> VcxResult<RevocationStatesMap> { trace!("build_rev_states_json >> credentials_identifiers: {credentials_identifiers:?}"); let mut rtn: RevocationStatesMap = HashMap::new(); let mut timestamps: HashMap<String, u64> = HashMap::new(); for cred_info in credentials_identifiers.iter_mut() { if let (Some(rev_reg_id), Some(cred_rev_id), Some(tails_dir)) = ( &cred_info.rev_reg_id, &cred_info.cred_rev_id, &cred_info.tails_dir, ) { if !rtn.contains_key(rev_reg_id) { // Does this make sense in case cred_info's for same rev_reg_ids have different // revocation intervals let (_from, to) = if let Some(ref interval) = cred_info.revocation_interval { (interval.from, interval.to) } else { (None, None) }; let parsed_id = &rev_reg_id.to_owned().try_into()?; let (rev_reg_def_json, meta) = ledger_read.get_rev_reg_def_json(parsed_id).await?; let on_or_before = to.unwrap_or(Utc::now().timestamp() as u64); let (rev_status_list, timestamp) = ledger_read .get_rev_status_list(parsed_id, on_or_before, Some(&meta)) .await?; let rev_state_json = anoncreds .create_revocation_state( Path::new(tails_dir), rev_reg_def_json, rev_status_list, *cred_rev_id, ) .await?; // TODO: proover should be able to create multiple states of same revocation policy // for different timestamps see ticket IS-1108 rtn.insert( rev_reg_id.to_string(), vec![(timestamp, rev_state_json)].into_iter().collect(), ); cred_info.timestamp = Some(timestamp); // Cache timestamp for future attributes that have the same rev_reg_id timestamps.insert(rev_reg_id.to_string(), timestamp); } // If the rev_reg_id is already in the map, timestamp may not be updated on cred_info // All further credential info gets the same timestamp as the first one if cred_info.timestamp.is_none() { cred_info.timestamp = timestamps.get(rev_reg_id).cloned(); } } } Ok(rtn) } pub fn build_requested_credentials_json( credentials_identifiers: &Vec<CredInfoProver>, self_attested_attrs: HashMap<String, String>, proof_req: &PresentationRequest, ) -> VcxResult<RequestedCredentials> { trace!( "build_requested_credentials_json >> credentials_identifiers: {credentials_identifiers:?}, self_attested_attrs: \ {self_attested_attrs:?}, proof_req: {proof_req:?}" ); let mut rtn = RequestedCredentials::default(); for cred_info in credentials_identifiers { if proof_req .value() .requested_attributes .contains_key(&cred_info.referent) { rtn.requested_attributes.insert( cred_info.referent.to_owned(), RequestedAttribute { cred_id: cred_info.credential_referent.to_owned(), timestamp: cred_info.timestamp, revealed: cred_info.revealed.unwrap_or(true), }, ); } } for cred_info in credentials_identifiers { if proof_req .value() .requested_predicates .contains_key(&cred_info.referent) { rtn.requested_predicates.insert( cred_info.referent.to_owned(), RequestedPredicate { cred_id: cred_info.credential_referent.to_owned(), timestamp: cred_info.timestamp, }, ); } } // handle if the attribute is not revealed rtn.self_attested_attributes = self_attested_attrs; Ok(rtn) } #[cfg(test)] pub mod pool_tests { use std::error::Error; use aries_vcx_ledger::ledger::indy::pool::test_utils::get_temp_dir_path; use test_utils::{ constants::{cred_def_id, schema_id, CRED_REV_ID, LICENCE_CRED_ID}, devsetup::build_setup_profile, }; use super::*; use crate::common::proofs::prover::prover_internal::{build_rev_states_json, CredInfoProver}; #[tokio::test] #[ignore] async fn test_pool_build_rev_states_json_empty() -> Result<(), Box<dyn Error>> { let setup = build_setup_profile().await; let mut empty_credential_identifiers = Vec::new(); assert_eq!( build_rev_states_json( &setup.ledger_read, &setup.anoncreds, empty_credential_identifiers.as_mut() ) .await?, HashMap::new() ); // no rev_reg_id let cred1 = CredInfoProver { referent: "height_1".to_string(), credential_referent: LICENCE_CRED_ID.to_string(), schema_id: schema_id(), cred_def_id: cred_def_id(), rev_reg_id: None, cred_rev_id: Some(CRED_REV_ID), tails_dir: Some(get_temp_dir_path().to_str().unwrap().to_string()), revocation_interval: None, timestamp: None, revealed: None, }; assert_eq!( build_rev_states_json(&setup.ledger_read, &setup.anoncreds, vec![cred1].as_mut()) .await?, HashMap::new() ); Ok(()) } } #[cfg(test)] pub mod unit_tests { use aries_vcx_ledger::ledger::indy::pool::test_utils::get_temp_dir_path; use serde_json::Value; use test_utils::{ constants::{ address_cred_def_id, address_schema_id, cred_def_id, schema_id, ADDRESS_CRED_DEF_ID, ADDRESS_CRED_ID, ADDRESS_REV_REG_ID, ADDRESS_SCHEMA_ID, CRED_DEF_ID, CRED_REV_ID, LICENCE_CRED_ID, REV_REG_ID, REV_STATE_JSON, SCHEMA_ID, }, devsetup::*, mockdata::{mock_anoncreds::MockAnoncreds, mock_ledger::MockLedger}, }; use super::*; fn proof_req_no_interval() -> PresentationRequest { let proof_req = json!({ "nonce": "123432421212", "name": "proof_req_1", "version": "1.0", "requested_attributes": { "address1_1": { "name": "address1" }, "zip_2": { "name": "zip" }, "height_1": { "name": "height" } }, "requested_predicates": {}, }) .to_string(); serde_json::from_str(&proof_req).unwrap() } #[tokio::test] async fn test_find_credential_def() { let _setup = SetupMocks::init(); let cred1 = CredInfoProver { referent: "height_1".to_string(), credential_referent: LICENCE_CRED_ID.to_string(), schema_id: schema_id(), cred_def_id: cred_def_id(), rev_reg_id: Some(REV_REG_ID.to_string()), cred_rev_id: Some(CRED_REV_ID), revocation_interval: None, tails_dir: None, timestamp: None, revealed: None, }; let cred2 = CredInfoProver { referent: "zip_2".to_string(), credential_referent: ADDRESS_CRED_ID.to_string(), schema_id: address_schema_id(), cred_def_id: address_cred_def_id(), rev_reg_id: Some(ADDRESS_REV_REG_ID.to_string()), cred_rev_id: Some(CRED_REV_ID), revocation_interval: None, tails_dir: None, timestamp: None, revealed: None, }; let creds = vec![cred1, cred2]; let ledger_read = MockLedger; let credential_def = build_cred_defs_json_prover(&ledger_read, &creds) .await .unwrap(); assert!(!credential_def.is_empty()); assert_eq!( credential_def.get(&cred_def_id()).unwrap().schema_id, SchemaId::new_unchecked("47") ); assert_eq!( credential_def.get(&cred_def_id()).unwrap().id, cred_def_id() ); } #[tokio::test] async fn test_find_schemas() { let _setup = SetupMocks::init(); let ledger_read = MockLedger; assert_eq!( build_schemas_json_prover(&ledger_read, &Vec::new()) .await .unwrap(), Default::default() ); let cred1 = CredInfoProver { referent: "height_1".to_string(), credential_referent: LICENCE_CRED_ID.to_string(), schema_id: schema_id(), cred_def_id: cred_def_id(), rev_reg_id: Some(REV_REG_ID.to_string()), cred_rev_id: Some(CRED_REV_ID), revocation_interval: None, tails_dir: None, timestamp: None, revealed: None, }; let cred2 = CredInfoProver { referent: "zip_2".to_string(), credential_referent: ADDRESS_CRED_ID.to_string(), schema_id: address_schema_id(), cred_def_id: address_cred_def_id(), rev_reg_id: Some(ADDRESS_REV_REG_ID.to_string()), cred_rev_id: Some(CRED_REV_ID), revocation_interval: None, tails_dir: None, timestamp: None, revealed: None, }; let creds = vec![cred1, cred2]; let ledger_read = MockLedger; let schemas = build_schemas_json_prover(&ledger_read, &creds) .await .unwrap(); assert!(!schemas.is_empty()); assert_eq!( schemas.get(&schema_id()).unwrap().name, "test-licence".to_string() ); } #[test] fn test_credential_def_identifiers() { let _setup = SetupMocks::init(); let cred1 = CredInfoProver { referent: "height_1".to_string(), credential_referent: LICENCE_CRED_ID.to_string(), schema_id: schema_id(), cred_def_id: cred_def_id(), rev_reg_id: Some(REV_REG_ID.to_string()), cred_rev_id: Some(CRED_REV_ID), revocation_interval: Some(NonRevokedInterval { from: Some(123), to: Some(456), }), tails_dir: Some(get_temp_dir_path().to_str().unwrap().to_string()), timestamp: None, revealed: None, }; let cred2 = CredInfoProver { referent: "zip_2".to_string(), credential_referent: ADDRESS_CRED_ID.to_string(), schema_id: address_schema_id(), cred_def_id: address_cred_def_id(), rev_reg_id: Some(ADDRESS_REV_REG_ID.to_string()), cred_rev_id: Some(CRED_REV_ID), revocation_interval: Some(NonRevokedInterval { from: None, to: Some(987), }), tails_dir: None, timestamp: None, revealed: None, }; let selected_credentials: Value = json!({ "attrs":{ "height_1":{ "credential": { "cred_info":{ "referent":LICENCE_CRED_ID, "attrs":{ "sex":"male", "age":"111", "name":"Bob", "height":"4'11" }, "schema_id": SCHEMA_ID, "cred_def_id": CRED_DEF_ID, "rev_reg_id":REV_REG_ID, "cred_rev_id":CRED_REV_ID }, "interval":null }, "tails_dir": get_temp_dir_path().to_str().unwrap().to_string(), }, "zip_2":{ "credential": { "cred_info":{ "referent":ADDRESS_CRED_ID, "attrs":{ "address1":"101 Tela Lane", "address2":"101 Wilson Lane", "zip":"87121", "state":"UT", "city":"SLC" }, "schema_id":ADDRESS_SCHEMA_ID, "cred_def_id":ADDRESS_CRED_DEF_ID, "rev_reg_id":ADDRESS_REV_REG_ID, "cred_rev_id":CRED_REV_ID }, "interval":null }, } } }); let proof_req = json!({ "nonce": "123432421212", "name": "proof_req_1", "version": "1.0", "requested_attributes": { "zip_2": { "name": "zip" }, "height_1": { "name": "height", "non_revoked": {"from": 123, "to": 456} } }, "requested_predicates": {}, "non_revoked": {"to": 987} }) .to_string(); let creds = credential_def_identifiers( &serde_json::from_value(selected_credentials).unwrap(), &serde_json::from_str(&proof_req).unwrap(), ) .unwrap(); assert_eq!(creds.len(), 2); assert!(creds.contains(&cred1)); assert!(creds.contains(&cred2)); } #[test] fn test_credential_def_identifiers_failure() { let _setup = SetupMocks::init(); // No Creds assert_eq!( credential_def_identifiers( &serde_json::from_str("{}").unwrap(), &proof_req_no_interval(), ) .unwrap(), Vec::new() ); assert_eq!( credential_def_identifiers( &serde_json::from_str(r#"{"attrs":{}}"#).unwrap(), &proof_req_no_interval(), ) .unwrap(), Vec::new() ); // Optional Revocation let mut selected_credentials: Value = json!({ "attrs":{ "height_1":{ "credential": { "cred_info":{ "referent":LICENCE_CRED_ID, "attrs":{ "sex":"male", "age":"111", "name":"Bob", "height":"4'11" }, "schema_id": SCHEMA_ID, "cred_def_id": CRED_DEF_ID, "cred_rev_id":CRED_REV_ID }, "interval":null }, "tails_dir": get_temp_dir_path().to_str().unwrap().to_string(), }, } }); let creds = vec![CredInfoProver { referent: "height_1".to_string(), credential_referent: LICENCE_CRED_ID.to_string(), schema_id: schema_id(), cred_def_id: cred_def_id(), rev_reg_id: None, cred_rev_id: Some(CRED_REV_ID), revocation_interval: None, tails_dir: Some(get_temp_dir_path().to_str().unwrap().to_string()), timestamp: None, revealed: None, }]; assert_eq!( &credential_def_identifiers( &serde_json::from_value(selected_credentials.clone()).unwrap(), &proof_req_no_interval(), ) .unwrap(), &creds ); // rev_reg_id is null selected_credentials["attrs"]["height_1"]["cred_info"]["rev_reg_id"] = serde_json::Value::Null; assert_eq!( &credential_def_identifiers( &serde_json::from_value(selected_credentials).unwrap(), &proof_req_no_interval(), ) .unwrap(), &creds ); } #[test] fn test_build_requested_credentials() { let _setup = SetupMocks::init(); let cred1 = CredInfoProver { referent: "height_1".to_string(), credential_referent: LICENCE_CRED_ID.to_string(), schema_id: schema_id(), cred_def_id: cred_def_id(), rev_reg_id: Some(REV_REG_ID.to_string()), cred_rev_id: Some(CRED_REV_ID), revocation_interval: None, tails_dir: None, timestamp: Some(800), revealed: None, }; let cred2 = CredInfoProver { referent: "zip_2".to_string(), credential_referent: ADDRESS_CRED_ID.to_string(), schema_id: address_schema_id(), cred_def_id: address_cred_def_id(), rev_reg_id: Some(ADDRESS_REV_REG_ID.to_string()), cred_rev_id: Some(CRED_REV_ID), revocation_interval: None, tails_dir: None, timestamp: Some(800), revealed: Some(false), }; let creds = vec![cred1, cred2]; let self_attested_attrs = json!({ "self_attested_attr_3": "my self attested 1", "self_attested_attr_4": "my self attested 2", }) .to_string(); let test: Value = json!({ "self_attested_attributes":{ "self_attested_attr_3": "my self attested 1", "self_attested_attr_4": "my self attested 2", }, "requested_attributes":{ "height_1": {"cred_id": LICENCE_CRED_ID, "revealed": true, "timestamp": 800}, "zip_2": {"cred_id": ADDRESS_CRED_ID, "revealed": false, "timestamp": 800}, }, "requested_predicates":{} }); let proof_req = json!({ "nonce": "123432421212", "name": "proof_req_1", "version": "1.0", "requested_attributes": { "height_1": { "name": "height_1", "non_revoked": {"from": 123, "to": 456} }, "zip_2": { "name": "zip_2" } }, "requested_predicates": {}, "non_revoked": {"from": 98, "to": 123} }); let proof_req: PresentationRequest = serde_json::from_value(proof_req).unwrap(); let requested_credential = build_requested_credentials_json( &creds, serde_json::from_str(&self_attested_attrs).unwrap(), &proof_req, ) .unwrap(); assert_eq!(test, serde_json::to_value(requested_credential).unwrap()); } #[tokio::test] async fn test_build_rev_states_json() { let _setup = SetupMocks::init(); let cred1 = CredInfoProver { referent: "height".to_string(), credential_referent: "abc".to_string(), schema_id: schema_id(), cred_def_id: cred_def_id(), rev_reg_id: Some(REV_REG_ID.to_string()), cred_rev_id: Some(CRED_REV_ID), tails_dir: Some(get_temp_dir_path().to_str().unwrap().to_string()), revocation_interval: None, timestamp: None, revealed: None, }; let mut cred_info = vec![cred1]; let anoncreds = MockAnoncreds; let ledger_read = MockLedger; let states = build_rev_states_json(&ledger_read, &anoncreds, cred_info.as_mut()) .await .unwrap(); let expected: RevocationStatesMap = vec![( REV_REG_ID.to_string(), vec![(1, serde_json::from_str(REV_STATE_JSON).unwrap())] .into_iter() .collect(), )] .into_iter() .collect(); assert_eq!(states, expected); assert!(cred_info[0].timestamp.is_some()); } #[test] fn test_get_credential_intervals_from_proof_req() { let _setup = SetupMocks::init(); let proof_req = json!({ "nonce": "123432421212", "name": "proof_req_1", "version": "1.0", "requested_attributes": { "address1_1": { "name": "address1", "non_revoked": {"from": 123, "to": 456} }, "zip_2": { "name": "zip" } }, "requested_predicates": {}, "non_revoked": {"from": 98, "to": 123} }); let proof_req: PresentationRequest = serde_json::from_value(proof_req).unwrap(); // Attribute not found in proof req assert_eq!( _get_revocation_interval("not here", &proof_req) .unwrap_err() .kind(), AriesVcxErrorKind::InvalidProofCredentialData ); // attribute interval overrides proof request interval let interval = Some(NonRevokedInterval { from: Some(123), to: Some(456), }); assert_eq!( _get_revocation_interval("address1_1", &proof_req).unwrap(), interval ); // when attribute interval is None, defaults to proof req interval let interval = Some(NonRevokedInterval { from: Some(98), to: Some(123), }); assert_eq!( _get_revocation_interval("zip_2", &proof_req).unwrap(), interval ); // No interval provided for attribute or proof req assert_eq!( _get_revocation_interval("address1_1", &proof_req_no_interval()).unwrap(), 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/common/primitives/revocation_registry.rs
aries/aries_vcx/src/common/primitives/revocation_registry.rs
use std::path::Path; use anoncreds_types::data_types::{ identifiers::cred_def_id::CredentialDefinitionId, ledger::rev_reg_def::RevocationRegistryDefinition, }; use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite}; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use did_parser_nom::Did; use super::credential_definition::PublicEntityStateType; use crate::errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}; #[derive(Clone, Deserialize, Debug, Serialize)] pub struct RevocationRegistry { cred_def_id: String, issuer_did: Did, pub rev_reg_id: String, rev_reg_def: RevocationRegistryDefinition, pub(in crate::common) rev_reg_entry: String, pub tails_dir: String, pub(in crate::common) max_creds: u32, pub(in crate::common) tag: u32, rev_reg_def_state: PublicEntityStateType, rev_reg_delta_state: PublicEntityStateType, } impl RevocationRegistry { pub async fn create( wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, issuer_did: &Did, cred_def_id: &CredentialDefinitionId, tails_dir: &str, max_creds: u32, tag: u32, ) -> VcxResult<RevocationRegistry> { trace!( "RevocationRegistry::create >>> issuer_did: {issuer_did}, cred_def_id: {cred_def_id}, tails_dir: {tails_dir}, \ max_creds: {max_creds}, tag_no: {tag}" ); let (rev_reg_id, rev_reg_def, rev_reg_entry) = generate_rev_reg( wallet, anoncreds, issuer_did, cred_def_id, tails_dir, max_creds, &format!("tag{tag}"), ) .await .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Failed to locally create a new Revocation Registry: {err:?}"), ) })?; Ok(RevocationRegistry { cred_def_id: cred_def_id.to_string(), issuer_did: issuer_did.to_owned(), rev_reg_id, rev_reg_def, rev_reg_entry, tails_dir: tails_dir.to_string(), max_creds, tag, rev_reg_def_state: PublicEntityStateType::Built, rev_reg_delta_state: PublicEntityStateType::Built, }) } pub fn get_rev_reg_id(&self) -> String { self.rev_reg_id.clone() } pub fn get_cred_def_id(&self) -> String { self.cred_def_id.clone() } pub fn get_rev_reg_def(&self) -> RevocationRegistryDefinition { self.rev_reg_def.clone() } pub fn get_tails_dir(&self) -> String { self.tails_dir.clone() } pub fn was_rev_reg_def_published(&self) -> bool { self.rev_reg_def_state == PublicEntityStateType::Published } pub fn was_rev_reg_delta_published(&self) -> bool { self.rev_reg_delta_state == PublicEntityStateType::Published } pub async fn publish_rev_reg_def( &mut self, wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerWrite, issuer_did: &Did, tails_url: &str, ) -> VcxResult<()> { trace!( "RevocationRegistry::publish_rev_reg_def >>> issuer_did:{}, rev_reg_id: {}, \ rev_reg_def:{:?}", issuer_did, &self.rev_reg_id, &self.rev_reg_def ); self.rev_reg_def.value.tails_location = String::from(tails_url); ledger .publish_rev_reg_def( wallet, serde_json::from_str(&serde_json::to_string(&self.rev_reg_def)?)?, issuer_did, ) .await .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!("Cannot publish revocation registry definition; {err}"), ) })?; self.rev_reg_def_state = PublicEntityStateType::Published; Ok(()) } pub async fn publish_rev_reg_delta( &mut self, wallet: &impl BaseWallet, ledger_write: &impl AnoncredsLedgerWrite, issuer_did: &Did, ) -> VcxResult<()> { trace!( "RevocationRegistry::publish_rev_reg_delta >>> issuer_did:{}, rev_reg_id: {}", issuer_did, self.rev_reg_id ); ledger_write .publish_rev_reg_delta( wallet, &self.rev_reg_id.to_string().try_into()?, serde_json::from_str(&self.rev_reg_entry)?, issuer_did, ) .await .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidRevocationEntry, format!("Cannot publish revocation entry; {err}"), ) })?; self.rev_reg_delta_state = PublicEntityStateType::Published; Ok(()) } pub async fn publish_revocation_primitives( &mut self, wallet: &impl BaseWallet, ledger_write: &impl AnoncredsLedgerWrite, tails_url: &str, ) -> VcxResult<()> { trace!("RevocationRegistry::publish_revocation_primitives >>> tails_url: {tails_url}"); self.publish_built_rev_reg_def(wallet, ledger_write, tails_url) .await?; self.publish_built_rev_reg_delta(wallet, ledger_write).await } async fn publish_built_rev_reg_delta( &mut self, wallet: &impl BaseWallet, ledger_write: &impl AnoncredsLedgerWrite, ) -> VcxResult<()> { let issuer_did = &self.issuer_did.clone(); if self.was_rev_reg_delta_published() { info!("No unpublished revocation registry delta found, nothing to publish") } else { self.publish_rev_reg_delta(wallet, ledger_write, issuer_did) .await?; } Ok(()) } async fn publish_built_rev_reg_def( &mut self, wallet: &impl BaseWallet, ledger_write: &impl AnoncredsLedgerWrite, tails_url: &str, ) -> VcxResult<()> { let issuer_did = &self.issuer_did.clone(); if self.was_rev_reg_def_published() { info!("No unpublished revocation registry definition found, nothing to publish") } else { self.publish_rev_reg_def(wallet, ledger_write, issuer_did, tails_url) .await?; } Ok(()) } pub fn to_string(&self) -> VcxResult<String> { serde_json::to_string(&self).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Cannot serialize revocation registry: {err:?}"), ) }) } pub fn from_string(rev_reg_data: &str) -> VcxResult<Self> { serde_json::from_str(rev_reg_data).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot deserialize revocation registry: {err:?}"), ) }) } pub async fn revoke_credential_local( &self, wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger: &impl AnoncredsLedgerRead, cred_rev_id: u32, ) -> VcxResult<()> { #[allow(deprecated)] // TODO - https://github.com/openwallet-foundation/vcx/issues/1309 let rev_reg_delta_json = ledger .get_rev_reg_delta_json(&self.rev_reg_id.to_string().try_into()?, None, None) .await? .0; anoncreds .revoke_credential_local( wallet, &self.rev_reg_id.to_owned().try_into()?, cred_rev_id, rev_reg_delta_json, ) .await .map_err(|err| err.into()) } pub async fn publish_local_revocations( &self, wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger_write: &impl AnoncredsLedgerWrite, submitter_did: &Did, ) -> VcxResult<()> { if let Some(delta) = anoncreds .get_rev_reg_delta(wallet, &self.rev_reg_id.to_owned().try_into()?) .await? { ledger_write .publish_rev_reg_delta( wallet, &self.rev_reg_id.to_string().try_into()?, delta, submitter_did, ) .await?; info!( "publish_local_revocations >>> rev_reg_delta published for rev_reg_id {}", self.rev_reg_id ); match anoncreds .clear_rev_reg_delta(wallet, &self.rev_reg_id.to_owned().try_into()?) .await { Ok(_) => { info!( "publish_local_revocations >>> rev_reg_delta storage cleared for \ rev_reg_id {}", self.rev_reg_id ); Ok(()) } Err(err) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::RevDeltaFailedToClear, format!( "Failed to clear revocation delta storage for rev_reg_id: {}, error: {err}", self.rev_reg_id ), )), } } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::RevDeltaNotFound, format!( "Failed to publish revocation delta for revocation registry {}, no delta \ found. Possibly already published?", self.rev_reg_id ), )) } } } pub async fn generate_rev_reg( wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, issuer_did: &Did, cred_def_id: &CredentialDefinitionId, tails_dir: &str, max_creds: u32, tag: &str, ) -> VcxResult<(String, RevocationRegistryDefinition, String)> { trace!( "generate_rev_reg >>> issuer_did: {issuer_did}, cred_def_id: {cred_def_id}, tails_file: {tails_dir}, max_creds: {max_creds}, \ tag: {tag}" ); let (rev_reg_id, rev_reg_def_json, rev_reg_entry_json) = anoncreds .issuer_create_and_store_revoc_reg( wallet, issuer_did, cred_def_id, Path::new(tails_dir), max_creds, tag, ) .await?; Ok(( rev_reg_id.to_string(), rev_reg_def_json, serde_json::to_string(&rev_reg_entry_json)?, )) }
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/common/primitives/mod.rs
aries/aries_vcx/src/common/primitives/mod.rs
pub mod credential_definition; pub mod credential_schema; pub mod revocation_registry;
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/common/primitives/credential_schema.rs
aries/aries_vcx/src/common/primitives/credential_schema.rs
use anoncreds_types::data_types::{ identifiers::schema_id::SchemaId, ledger::schema::Schema as LedgerSchema, }; use aries_vcx_anoncreds::{ anoncreds::base_anoncreds::BaseAnonCreds, constants::DEFAULT_SERIALIZE_VERSION, }; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerWrite; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use did_parser_nom::Did; use super::credential_definition::PublicEntityStateType; use crate::{ errors::error::{AriesVcxError, VcxResult}, utils::serialization::ObjectWithVersion, }; #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct Schema { pub data: Vec<String>, pub version: String, pub schema_id: SchemaId, pub name: String, pub source_id: String, #[serde(default)] submitter_did: Did, #[serde(default)] pub state: PublicEntityStateType, pub schema_json: LedgerSchema, } impl Schema { pub async fn create( anoncreds: &impl BaseAnonCreds, source_id: &str, submitter_did: &Did, name: &str, version: &str, attributes: Vec<String>, ) -> VcxResult<Self> { trace!( "Schema::create >>> submitter_did: {submitter_did}, name: {name}, version: {version}, attributes: {attributes:?}" ); let schema_json = anoncreds .issuer_create_schema(submitter_did, name, version, attributes.to_owned().into()) .await?; Ok(Self { source_id: source_id.to_string(), name: name.to_string(), data: attributes, version: version.to_string(), schema_id: schema_json.id.clone(), submitter_did: submitter_did.to_owned(), schema_json, state: PublicEntityStateType::Built, }) } pub async fn submitter_did(&self) -> String { self.submitter_did.to_string() } pub async fn publish( self, wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerWrite, ) -> VcxResult<Self> { trace!("Schema::publish >>>"); ledger .publish_schema(wallet, self.schema_json.clone(), &self.submitter_did, None) .await?; Ok(Self { state: PublicEntityStateType::Published, ..self }) } pub fn get_source_id(&self) -> String { self.source_id.clone() } pub fn get_schema_id(&self) -> SchemaId { self.schema_id.clone() } pub fn to_string_versioned(&self) -> VcxResult<String> { ObjectWithVersion::new(DEFAULT_SERIALIZE_VERSION, self.to_owned()) .serialize() .map_err(|err: AriesVcxError| err.extend("Cannot serialize Schema")) } pub fn from_string_versioned(data: &str) -> VcxResult<Schema> { ObjectWithVersion::deserialize(data) .map(|obj: ObjectWithVersion<Schema>| obj.data) .map_err(|err: AriesVcxError| err.extend("Cannot deserialize Schema")) } pub fn get_state(&self) -> u32 { self.state as u32 } } #[cfg(test)] mod tests { use test_utils::constants::{schema_id, schema_json, DID}; use super::*; #[test] fn test_to_string_versioned() { let schema = Schema { data: vec!["name".to_string(), "age".to_string()], version: "1.0".to_string(), schema_id: schema_id(), name: "test".to_string(), source_id: "1".to_string(), submitter_did: DID.to_string().parse().unwrap(), state: PublicEntityStateType::Built, schema_json: schema_json(), }; let serialized = schema.to_string_versioned().unwrap(); assert!(serialized.contains(r#""version":"1.0""#)); assert!(serialized.contains(r#""name":"test""#)); assert!(serialized.contains(r#""schema_id":""#)); assert!(serialized.contains(r#""source_id":"1""#)); assert!(serialized.contains(r#""data":["name","age"]"#)); } #[test] fn test_from_string_versioned() { let serialized = json!({ "version": "1.0", "data": { "data": [ "name", "age" ], "version": "1.0", "schema_id": "test_schema_id", "name": "test", "source_id": "1", "submitter_did": DID, "state": 1, "schema_json": schema_json() }}) .to_string(); let schema = Schema::from_string_versioned(&serialized).unwrap(); assert_eq!(schema.version, "1.0"); assert_eq!(schema.data, vec!["name".to_string(), "age".to_string()]); assert_eq!(schema.schema_id, SchemaId::new_unchecked("test_schema_id")); assert_eq!(schema.name, "test"); assert_eq!(schema.source_id, "1"); assert_eq!(schema.state, PublicEntityStateType::Published); } #[test] fn test_get_schema_id() { let schema = Schema { data: vec!["name".to_string(), "age".to_string()], version: "1.0".to_string(), schema_id: schema_id(), name: "test".to_string(), source_id: "1".to_string(), submitter_did: DID.to_string().parse().unwrap(), state: PublicEntityStateType::Built, schema_json: schema_json(), }; assert_eq!(schema.get_schema_id(), 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/common/primitives/credential_definition.rs
aries/aries_vcx/src/common/primitives/credential_definition.rs
use anoncreds_types::data_types::{ identifiers::{cred_def_id::CredentialDefinitionId, schema_id::SchemaId}, ledger::{ cred_def::{CredentialDefinition, SignatureType}, schema::Schema, }, messages::cred_definition_config::CredentialDefinitionConfig, }; use aries_vcx_anoncreds::{ anoncreds::base_anoncreds::BaseAnonCreds, constants::DEFAULT_SERIALIZE_VERSION, }; use aries_vcx_ledger::{ errors::error::VcxLedgerError, ledger::base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite}, }; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use did_parser_nom::Did; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, utils::serialization::ObjectWithVersion, }; #[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Default)] #[serde(try_from = "u8")] #[repr(u8)] pub enum PublicEntityStateType { Built = 0, #[default] Published = 1, } impl ::serde::Serialize for PublicEntityStateType { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer, { serializer.serialize_u8(*self as u8) } } impl TryFrom<u8> for PublicEntityStateType { type Error = String; fn try_from(value: u8) -> Result<Self, Self::Error> { match value { 0 => Ok(PublicEntityStateType::Built), 1 => Ok(PublicEntityStateType::Published), _ => Err(format!( "unknown {} value: {}", stringify!(PublicEntityStateType), value )), } } } // TODO: Deduplicate the data #[derive(Deserialize, Debug, Clone, Serialize, PartialEq, Eq)] pub struct CredentialDef { #[serde(alias = "cred_def_id")] id: CredentialDefinitionId, tag: String, source_id: String, issuer_did: Did, cred_def_json: String, support_revocation: bool, #[serde(default)] schema_id: SchemaId, #[serde(default)] pub state: PublicEntityStateType, } async fn _try_get_cred_def_from_ledger( ledger: &impl AnoncredsLedgerRead, issuer_did: &Did, cred_def_id: &CredentialDefinitionId, ) -> VcxResult<Option<String>> { match ledger.get_cred_def(cred_def_id, Some(issuer_did)).await { Ok(cred_def) => Ok(Some(serde_json::to_string(&cred_def)?)), Err(err) => match err { VcxLedgerError::LedgerItemNotFound => Ok(None), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidLedgerResponse, format!( "Failed to check presence of credential definition id {cred_def_id} on the \ ledger\nError: {err}" ), )), }, } } impl CredentialDef { #[allow(clippy::too_many_arguments)] pub async fn create( wallet: &impl BaseWallet, ledger_read: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, source_id: String, issuer_did: Did, schema_id: SchemaId, tag: String, support_revocation: bool, ) -> VcxResult<Self> { trace!("CredentialDef::create >>> source_id: {source_id}"); let schema_json = ledger_read .get_schema(&schema_id, Some(&issuer_did)) .await?; let cred_def = generate_cred_def( wallet, anoncreds, &issuer_did, &schema_id, schema_json, &tag, None, Some(support_revocation), ) .await?; Ok(Self { source_id, tag, id: cred_def.id.to_owned(), cred_def_json: serde_json::to_string(&cred_def)?, issuer_did, support_revocation, schema_id, state: PublicEntityStateType::Built, }) } pub fn was_published(&self) -> bool { self.state == PublicEntityStateType::Published } pub fn get_support_revocation(&self) -> bool { self.support_revocation } pub fn get_cred_def_json(&self) -> CredentialDefinition { serde_json::from_str(&self.cred_def_json).unwrap() } pub async fn publish_cred_def( self, wallet: &impl BaseWallet, ledger_read: &impl AnoncredsLedgerRead, ledger_write: &impl AnoncredsLedgerWrite, ) -> VcxResult<Self> { trace!( "publish_cred_def >>> issuer_did: {}, cred_def_id: {}", self.issuer_did, self.id ); if let Some(ledger_cred_def_json) = _try_get_cred_def_from_ledger(ledger_read, &self.issuer_did, &self.id).await? { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::CredDefAlreadyCreated, format!( "Credential definition with id {} already exists on the ledger: {}", self.id, ledger_cred_def_json ), )); } let cred_def_json = serde_json::from_str(&self.cred_def_json)?; ledger_write .publish_cred_def(wallet, cred_def_json, &self.issuer_did) .await?; Ok(Self { state: PublicEntityStateType::Published, ..self }) } pub fn from_string(data: &str) -> VcxResult<Self> { ObjectWithVersion::deserialize(data) .map(|obj: ObjectWithVersion<Self>| obj.data) .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot deserialize CredentialDefinition: {err}"), ) }) } pub fn to_string(&self) -> VcxResult<String> { ObjectWithVersion::new(DEFAULT_SERIALIZE_VERSION, self.to_owned()) .serialize() .map_err(|err: AriesVcxError| err.extend("Cannot serialize CredentialDefinition")) } pub fn get_data_json(&self) -> VcxResult<String> { serde_json::to_string(&self).map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, "Failed to serialize credential definition", ) }) } pub fn get_source_id(&self) -> &String { &self.source_id } pub fn get_cred_def_id(&self) -> &CredentialDefinitionId { &self.id } pub fn get_schema_id(&self) -> &SchemaId { &self.schema_id } pub fn set_source_id(&mut self, source_id: String) { self.source_id = source_id; } pub async fn update_state(&mut self, ledger: &impl AnoncredsLedgerRead) -> VcxResult<u32> { if (ledger .get_cred_def(&self.id.to_string().try_into()?, None) .await) .is_ok() { self.state = PublicEntityStateType::Published } Ok(self.state as u32) } pub fn get_state(&self) -> u32 { self.state as u32 } } #[allow(clippy::too_many_arguments)] pub async fn generate_cred_def( wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, issuer_did: &Did, schema_id: &SchemaId, schema_json: Schema, tag: &str, // TODO: These should not be options sig_type: Option<&str>, support_revocation: Option<bool>, ) -> VcxResult<CredentialDefinition> { trace!( "generate_cred_def >>> issuer_did: {issuer_did}, schema_json: {schema_json:?}, tag: {tag}, sig_type: {sig_type:?}, \ support_revocation: {support_revocation:?}" ); let config_json = CredentialDefinitionConfig { support_revocation: support_revocation.unwrap_or_default(), tag: tag.to_string(), signature_type: SignatureType::CL, }; let cred_def = anoncreds .issuer_create_and_store_credential_def( wallet, issuer_did, schema_id, schema_json, config_json, ) .await?; Ok(cred_def) }
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/common/ledger/service_didsov.rs
aries/aries_vcx/src/common/ledger/service_didsov.rs
use url::Url; pub const SERVICE_SUFFIX: &str = "indy"; pub const SERVICE_TYPE: &str = "IndyAgent"; // https://sovrin-foundation.github.io/sovrin/spec/did-method-spec-template.html #[derive(Debug, Deserialize, Serialize, Clone)] #[cfg_attr(test, derive(PartialEq, Eq))] #[serde(rename_all = "camelCase")] pub struct EndpointDidSov { pub endpoint: Url, #[serde(default)] pub routing_keys: Option<Vec<String>>, #[serde(default)] pub types: Option<Vec<String>>, } impl EndpointDidSov { pub fn create() -> Self { Self::default() } pub fn set_service_endpoint(mut self, service_endpoint: Url) -> Self { self.endpoint = service_endpoint; self } pub fn set_routing_keys(mut self, routing_keys: Option<Vec<String>>) -> Self { self.routing_keys = routing_keys; self } pub fn set_types(mut self, types: Option<Vec<String>>) -> Self { self.types = types; self } } impl Default for EndpointDidSov { fn default() -> EndpointDidSov { EndpointDidSov { endpoint: "https://dummy.dummy/dummy".parse().expect("valid url"), routing_keys: Some(Vec::new()), types: None, } } } #[cfg(test)] mod unit_tests { use did_doc::schema::service::typed::ServiceType; use diddoc_legacy::aries::diddoc::test_utils::{_routing_keys, _service_endpoint}; use test_utils::devsetup::SetupMocks; use crate::common::ledger::service_didsov::EndpointDidSov; #[test] fn test_service_comparison() { let service1 = EndpointDidSov::create() .set_service_endpoint(_service_endpoint()) .set_routing_keys(Some(_routing_keys())); let service2 = EndpointDidSov::create() .set_service_endpoint(_service_endpoint()) .set_routing_keys(Some(_routing_keys())); let service3 = EndpointDidSov::create() .set_service_endpoint("http://bogus_endpoint.com".parse().expect("valid url")) .set_routing_keys(Some(_routing_keys())); let service4 = EndpointDidSov::create() .set_service_endpoint(_service_endpoint()) .set_routing_keys(Some(_routing_keys())); assert_eq!(service1, service2); assert_eq!(service1, service4); assert_ne!(service1, service3); } #[test] fn test_didsov_service_serialization() { SetupMocks::init(); let service1 = EndpointDidSov::create() .set_service_endpoint(_service_endpoint()) .set_routing_keys(Some(_routing_keys())) .set_types(Some(vec![ ServiceType::AIP1.to_string(), ServiceType::DIDCommV1.to_string(), ServiceType::DIDCommV2.to_string(), "foobar".to_string(), ])); let expected = json!({ "endpoint": "http://localhost:8080/", "routingKeys": [ "Hezce2UWMZ3wUhVkh2LfKSs8nDzWwzs2Win7EzNN3YaR", "3LYuxJBJkngDbvJj4zjx13DBUdZ2P96eNybwd2n9L9AU" ], "types": ["endpoint", "did-communication", "DIDCommMessaging", "foobar"] }); assert_eq!(expected, json!(&service1)); } #[test] fn test_didsov_service_deserialization() { SetupMocks::init(); let data = json!({ "endpoint": "http://localhost:8080", "routingKeys": [ "Hezce2UWMZ3wUhVkh2LfKSs8nDzWwzs2Win7EzNN3YaR", "3LYuxJBJkngDbvJj4zjx13DBUdZ2P96eNybwd2n9L9AU" ], "types": ["endpoint", "did-communication", "DIDCommMessaging", "foobar"] }) .to_string(); let deserialized: EndpointDidSov = serde_json::from_str(&data).unwrap(); assert_eq!(deserialized.endpoint, _service_endpoint()); assert_eq!(deserialized.routing_keys, Some(_routing_keys())); assert_eq!( deserialized.types, Some(vec![ ServiceType::AIP1.to_string(), ServiceType::DIDCommV1.to_string(), ServiceType::DIDCommV2.to_string(), "foobar".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/common/ledger/transactions.rs
aries/aries_vcx/src/common/ledger/transactions.rs
use std::collections::HashMap; use aries_vcx_ledger::ledger::{ base_ledger::{IndyLedgerRead, IndyLedgerWrite}, indy_vdr_ledger::{LedgerRole, UpdateRole}, }; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use did_doc::schema::service::Service; use did_parser_nom::Did; use diddoc_legacy::aries::service::AriesService; use messages::msg_fields::protocols::out_of_band::invitation::OobService; use public_key::{Key, KeyType}; use serde_json::Value; use crate::{ common::{keys::get_verkey_from_ledger, ledger::service_didsov::EndpointDidSov}, errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, }; #[derive(Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Request { pub req_id: u64, pub identifier: String, pub signature: Option<String>, pub signatures: Option<HashMap<String, String>>, pub endorser: Option<String>, } #[derive(Deserialize, Debug)] #[serde(tag = "op")] pub enum Response { #[serde(rename = "REQNACK")] ReqNACK(Reject), #[serde(rename = "REJECT")] Reject(Reject), #[serde(rename = "REPLY")] Reply(Reply), } #[derive(Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Reject { pub reason: String, } #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum Reply { ReplyV0(ReplyV0), ReplyV1(ReplyV1), } #[derive(Debug, Deserialize)] pub struct ReplyV0 { pub result: Value, } #[derive(Debug, Deserialize)] pub struct ReplyV1 { pub data: ReplyDataV1, } #[derive(Debug, Deserialize)] pub struct ReplyDataV1 { pub result: Value, } pub async fn resolve_service( indy_ledger: &impl IndyLedgerRead, service: &OobService, ) -> VcxResult<AriesService> { match service { OobService::AriesService(service) => Ok(service.clone()), OobService::Did(did) => get_service(indy_ledger, &did.clone().parse()?).await, } } pub async fn add_new_did( wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, submitter_did: &Did, role: Option<&str>, ) -> VcxResult<(Did, String)> { let did_data = wallet.create_and_store_my_did(None, None).await?; let res = indy_ledger_write .publish_nym( wallet, submitter_did, &did_data.did().parse()?, Some(did_data.verkey()), None, role, ) .await?; check_response(&res)?; Ok((did_data.did().parse()?, did_data.verkey().base58())) } pub async fn get_service(ledger: &impl IndyLedgerRead, did: &Did) -> VcxResult<AriesService> { let attr_resp = ledger.get_attr(did, "endpoint").await?; let data = get_data_from_response(&attr_resp)?; if data["endpoint"].is_object() { let endpoint: EndpointDidSov = serde_json::from_value(data["endpoint"].clone())?; let recipient_keys = vec![get_verkey_from_ledger(ledger, did).await?]; let endpoint_url = endpoint.endpoint; return Ok(AriesService::create() .set_recipient_keys(recipient_keys) .set_service_endpoint(endpoint_url) .set_routing_keys(endpoint.routing_keys.unwrap_or_default())); } parse_legacy_endpoint_attrib(ledger, did).await } pub async fn parse_legacy_endpoint_attrib( indy_ledger: &impl IndyLedgerRead, did_raw: &Did, ) -> VcxResult<AriesService> { let attr_resp = indy_ledger.get_attr(did_raw, "service").await?; let data = get_data_from_response(&attr_resp)?; let ser_service = match data["service"].as_str() { Some(ser_service) => ser_service.to_string(), None => { warn!( "Failed converting service read from ledger {:?} to string, falling back to new \ single-serialized format", data["service"] ); data["service"].to_string() } }; serde_json::from_str(&ser_service).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Failed to deserialize service read from the ledger: {err:?}"), ) }) } pub async fn write_endorser_did( wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, submitter_did: &Did, target_did: &Did, target_vk: &str, alias: Option<String>, ) -> VcxResult<String> { let res = indy_ledger_write .write_did( wallet, submitter_did, target_did, &Key::from_base58(target_vk, KeyType::Ed25519)?, Some(UpdateRole::Set(LedgerRole::Endorser)), alias, ) .await?; check_response(&res)?; Ok(res) } pub async fn write_endpoint_legacy( wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, did: &Did, service: &AriesService, ) -> VcxResult<String> { let attrib_json = json!({ "service": service }).to_string(); let res = indy_ledger_write .add_attr(wallet, did, &attrib_json) .await?; check_response(&res)?; Ok(res) } pub async fn write_endpoint( wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, did: &Did, service: &EndpointDidSov, ) -> VcxResult<String> { let attrib_json = json!({ "endpoint": service }).to_string(); let res = indy_ledger_write .add_attr(wallet, did, &attrib_json) .await?; check_response(&res)?; Ok(res) } fn _service_to_didsov_endpoint_attribute(service: &Service) -> EndpointDidSov { let routing_keys: Option<Vec<String>> = service .extra_field_routing_keys() .ok() .map(|keys| keys.iter().map(|key| key.to_string()).collect()); let service_types = service.service_types(); let types_str: Vec<String> = service_types.iter().map(|t| t.to_string()).collect(); EndpointDidSov::create() .set_routing_keys(routing_keys) .set_types(Some(types_str)) .set_service_endpoint(service.service_endpoint().clone()) } pub async fn write_endpoint_from_service( wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, did: &Did, service: &Service, ) -> VcxResult<(String, EndpointDidSov)> { let attribute = _service_to_didsov_endpoint_attribute(service); let res = write_endpoint(wallet, indy_ledger_write, did, &attribute).await?; Ok((res, attribute)) } pub async fn add_attr( wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, did: &Did, attr: &str, ) -> VcxResult<()> { let res = indy_ledger_write.add_attr(wallet, did, attr).await?; check_response(&res) } pub async fn get_attr( ledger: &impl IndyLedgerRead, did: &Did, attr_name: &str, ) -> VcxResult<String> { let attr_resp = ledger.get_attr(did, attr_name).await?; let data = get_data_from_response(&attr_resp)?; match data.get(attr_name) { None => Ok("".into()), Some(attr) if attr.is_null() => Ok("".into()), Some(attr) => Ok(attr.to_string()), } } pub async fn clear_attr( wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, did: &Did, attr_name: &str, ) -> VcxResult<String> { indy_ledger_write .add_attr(wallet, did, &json!({ attr_name: Value::Null }).to_string()) .await .map_err(|err| err.into()) } fn check_response(response: &str) -> VcxResult<()> { match parse_response(response)? { Response::Reply(_) => Ok(()), Response::Reject(res) | Response::ReqNACK(res) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidLedgerResponse, format!("{res:?}"), )), } } fn parse_response(response: &str) -> VcxResult<Response> { serde_json::from_str::<Response>(response).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Cannot deserialize transaction response: {err:?}"), ) }) } fn get_data_from_response(resp: &str) -> VcxResult<serde_json::Value> { let resp: serde_json::Value = serde_json::from_str(resp).map_err(|err| { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidLedgerResponse, format!("{err:?}")) })?; serde_json::from_str(resp["result"]["data"].as_str().unwrap_or("{}")).map_err(|err| { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidLedgerResponse, format!("{err:?}")) }) } // #[cfg(test)] // mod test { // use crate::common::test_utils::mock_profile; // use messages::a2a::MessageId; // use messages::diddoc::aries::diddoc::test_utils::{ // _key_1, _key_1_did_key, _key_2, _key_2_did_key, _recipient_keys, _routing_keys, // _service_endpoint, }; // use messages::protocols::connection::invite::test_utils::_pairwise_invitation; // use messages::protocols::out_of_band::invitation::OutOfBandInvitation; // use super::*; // #[tokio::test] // async fn test_did_doc_from_invitation_works() { // let mut did_doc = AriesDidDoc::default(); // did_doc.set_id(MessageId::id().0); // did_doc.set_service_endpoint(_service_endpoint()); // did_doc.set_recipient_keys(_recipient_keys()); // did_doc.set_routing_keys(_routing_keys()); // assert_eq!( // did_doc, // into_did_doc(&mock_profile(), &Invitation::Pairwise(_pairwise_invitation())) // .await // .unwrap() // ); // } // #[tokio::test] // async fn test_did_doc_from_invitation_with_didkey_encoding_works() { // let recipient_keys = vec![_key_2()]; // let routing_keys_did_key = vec![_key_2_did_key()]; // let id = Uuid::new_v4().to_string(); // let mut did_doc = AriesDidDoc::default(); // did_doc.set_id(id.clone()); // did_doc.set_service_endpoint(_service_endpoint()); // did_doc.set_recipient_keys(recipient_keys); // did_doc.set_routing_keys(_routing_keys()); // let aries_service = ServiceOob::AriesService( // AriesService::create() // .set_service_endpoint(_service_endpoint()) // .set_routing_keys(_routing_keys()) // .set_recipient_keys(routing_keys_did_key), // ); // invitation.services.push(aries_service); // assert_eq!( // did_doc, // into_did_doc(&mock_profile(), &Invitation::OutOfBand(invitation)) // .await // .unwrap() // ); // } // #[tokio::test] // async fn test_did_key_to_did_raw() { // let recipient_keys = vec![_key_1()]; // let expected_output = vec![_key_1()]; // assert_eq!(normalize_keys_as_naked(recipient_keys).unwrap(), expected_output); // let recipient_keys = vec!["abc".to_string(), "def".to_string(), "ghi".to_string()]; // let expected_output = vec!["abc".to_string(), "def".to_string(), "ghi".to_string()]; // assert_eq!(normalize_keys_as_naked(recipient_keys).unwrap(), expected_output); // } // #[tokio::test] // async fn test_did_naked_to_did_raw() { // let recipient_keys = vec![_key_1_did_key(), _key_2_did_key()]; // let expected_output = vec![_key_1(), _key_2()]; // assert_eq!(normalize_keys_as_naked(recipient_keys).unwrap(), expected_output); // } // #[tokio::test] // async fn test_did_bad_format_without_z_prefix() { // let recipient_keys = vec!["did:key:invalid".to_string()]; // let test = normalize_keys_as_naked(recipient_keys).map_err(|e| e.kind()); // let expected_error_kind = AriesVcxErrorKind::InvalidDid; // assert_eq!(test.unwrap_err(), expected_error_kind); // } // #[tokio::test] // async fn test_did_bad_format_without_ed25519_public() { // let recipient_keys = vec!["did:key:zInvalid".to_string()]; // let test = normalize_keys_as_naked(recipient_keys).map_err(|e| e.kind()); // let expected_error_kind = AriesVcxErrorKind::InvalidDid; // assert_eq!(test.unwrap_err(), expected_error_kind); // } // #[tokio::test] // async fn test_public_key_to_did_naked_with_previously_known_keys_suggested() { // let did_pub_with_key = // "did:key:z6MkwHgArrRJq3tTdhQZKVAa1sdFgSAs5P5N1C4RJcD11Ycv".to_string(); let did_pub = // "HqR8GcAsVWPzXCZrdvCjAn5Frru1fVq1KB9VULEz6KqY".to_string(); let did_raw = // _ed25519_public_key_to_did_key(&did_pub).unwrap(); let recipient_keys = vec![did_raw]; // let expected_output = vec![did_pub_with_key]; // assert_eq!(recipient_keys, expected_output); // } // #[tokio::test] // async fn test_public_key_to_did_naked_with_previously_known_keys_rfc_0360() { // let did_pub_with_key_rfc_0360 = // "did:key:z6MkmjY8GnV5i9YTDtPETC2uUAW6ejw3nk5mXF5yci5ab7th".to_string(); let // did_pub_rfc_0360 = "8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K".to_string(); let // did_raw = _ed25519_public_key_to_did_key(&did_pub_rfc_0360).unwrap(); let recipient_keys // = vec![did_raw]; let expected_output = vec![did_pub_with_key_rfc_0360]; // assert_eq!(recipient_keys, expected_output); // } // #[tokio::test] // async fn test_did_naked_with_previously_known_keys_suggested() { // let did_pub_with_key = // vec!["did:key:z6MkwHgArrRJq3tTdhQZKVAa1sdFgSAs5P5N1C4RJcD11Ycv".to_string()]; let did_pub // = vec!["HqR8GcAsVWPzXCZrdvCjAn5Frru1fVq1KB9VULEz6KqY".to_string()]; assert_eq! // (normalize_keys_as_naked(did_pub_with_key).unwrap(), did_pub); } // #[tokio::test] // async fn test_did_naked_with_previously_known_keys_rfc_0360() { // let did_pub_with_key_rfc_0360 = // vec!["did:key:z6MkmjY8GnV5i9YTDtPETC2uUAW6ejw3nk5mXF5yci5ab7th".to_string()]; let // did_pub_rfc_0360 = vec!["8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K".to_string()]; // assert_eq!( // normalize_keys_as_naked(did_pub_with_key_rfc_0360).unwrap(), // did_pub_rfc_0360 // ); // } // }
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/common/ledger/mod.rs
aries/aries_vcx/src/common/ledger/mod.rs
pub mod service_didsov; pub mod transactions;
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/common/credentials/mod.rs
aries/aries_vcx/src/common/credentials/mod.rs
use aries_vcx_anoncreds::anoncreds::base_anoncreds::{BaseAnonCreds, CredentialId}; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use time::OffsetDateTime; use crate::errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}; pub mod encoding; pub async fn get_cred_rev_id( wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, cred_id: &CredentialId, ) -> VcxResult<u32> { let cred_json = anoncreds.prover_get_credential(wallet, cred_id).await?; cred_json.cred_rev_id.ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidRevocationDetails, "Credenial revocation id missing on credential - is this credential revokable?", )) } pub async fn is_cred_revoked( ledger: &impl AnoncredsLedgerRead, rev_reg_id: &str, rev_id: u32, ) -> VcxResult<bool> { let to = Some(OffsetDateTime::now_utc().unix_timestamp() as u64 + 100); #[allow(deprecated)] // TODO - https://github.com/openwallet-foundation/vcx/issues/1309 let (rev_reg_delta, _) = ledger .get_rev_reg_delta_json(&rev_reg_id.try_into()?, None, to) .await?; Ok(rev_reg_delta.value.revoked.iter().any(|s| s.eq(&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/common/credentials/encoding.rs
aries/aries_vcx/src/common/credentials/encoding.rs
use std::collections::HashMap; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, utils::openssl::encode, }; pub fn encode_attributes(attributes: &str) -> VcxResult<String> { let mut dictionary = HashMap::new(); match serde_json::from_str::<HashMap<String, serde_json::Value>>(attributes) { Ok(mut attributes) => { for (attr, attr_data) in attributes.iter_mut() { let first_attr = match attr_data { // new style input such as {"address2":"101 Wilson Lane"} serde_json::Value::String(str_type) => str_type, // old style input such as {"address2":["101 Wilson Lane"]} serde_json::Value::Array(array_type) => { let attrib_value: &str = match array_type.first().and_then(serde_json::Value::as_str) { Some(x) => x, None => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidAttributesStructure, "Attribute value not found", )); } }; warn!( "Old attribute format detected. See vcx_issuer_create_credential api \ for additional information." ); attrib_value } _ => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, "Invalid Json for Attribute data", )); } }; let encoded = encode(first_attr)?; let attrib_values = json!({ "raw": first_attr, "encoded": encoded }); dictionary.insert(attr.to_string(), attrib_values); } serde_json::to_string_pretty(&dictionary).map_err(|err| { warn!("Invalid Json for Attribute data"); AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Invalid Json for Attribute data: {err}"), ) }) } Err(_err) => { // TODO: Check error type match serde_json::from_str::<Vec<serde_json::Value>>(attributes) { Ok(mut attributes) => { for cred_value in attributes.iter_mut() { let name = 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 encoded = encode(value.as_str().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidAttributesStructure, format!("Failed to convert value {value:?} to string"), ))?)?; let attrib_values = json!({ "raw": value, "encoded": encoded }); let name = name .as_str() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidAttributesStructure, format!( "Failed to convert attribute name {cred_value:?} to string" ), ))? .to_string(); dictionary.insert(name, attrib_values); } serde_json::to_string_pretty(&dictionary).map_err(|err| { warn!("Invalid Json for Attribute data"); AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!("Invalid Json for Attribute data: {err}"), ) }) } Err(err) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidAttributesStructure, format!("Attribute value not found: {err:?}"), )), } } } } #[cfg(test)] pub mod unit_tests { use serde_json::Value; use test_utils::devsetup::*; use crate::common::credentials::encoding::encode_attributes; #[test] fn test_encode_with_several_attributes_success() { let _setup = SetupMocks::init(); let expected = json!({ "address2": { "encoded": "68086943237164982734333428280784300550565381723532936263016368251445461241953", "raw": "101 Wilson Lane" }, "zip": { "encoded": "87121", "raw": "87121" }, "city": { "encoded": "101327353979588246869873249766058188995681113722618593621043638294296500696424", "raw": "SLC" }, "address1": { "encoded": "63690509275174663089934667471948380740244018358024875547775652380902762701972", "raw": "101 Tela Lane" }, "state": { "encoded": "93856629670657830351991220989031130499313559332549427637940645777813964461231", "raw": "UT" } }); static TEST_CREDENTIAL_DATA: &str = r#"{"address2":["101 Wilson Lane"], "zip":["87121"], "state":["UT"], "city":["SLC"], "address1":["101 Tela Lane"] }"#; let results_json = encode_attributes(TEST_CREDENTIAL_DATA).unwrap(); let results: Value = serde_json::from_str(&results_json).unwrap(); assert_eq!(expected, results); } #[test] fn test_encode_with_one_attribute_success() { let _setup = SetupMocks::init(); let expected = json!({ "address2": { "encoded": "68086943237164982734333428280784300550565381723532936263016368251445461241953", "raw": "101 Wilson Lane" } }); static TEST_CREDENTIAL_DATA: &str = r#"{"address2":["101 Wilson Lane"]}"#; let expected_json = serde_json::to_string_pretty(&expected).unwrap(); let results_json = encode_attributes(TEST_CREDENTIAL_DATA).unwrap(); assert_eq!( expected_json, results_json, "encode_attributes failed to return expected results" ); } #[test] fn test_encode_with_aries_format_several_attributes_success() { let _setup = SetupMocks::init(); let expected = json!({ "address2": { "encoded": "68086943237164982734333428280784300550565381723532936263016368251445461241953", "raw": "101 Wilson Lane" }, "zip": { "encoded": "87121", "raw": "87121" }, "city": { "encoded": "101327353979588246869873249766058188995681113722618593621043638294296500696424", "raw": "SLC" }, "address1": { "encoded": "63690509275174663089934667471948380740244018358024875547775652380902762701972", "raw": "101 Tela Lane" }, "state": { "encoded": "93856629670657830351991220989031130499313559332549427637940645777813964461231", "raw": "UT" } }); static TEST_CREDENTIAL_DATA: &str = r#"[ {"name": "address2", "value": "101 Wilson Lane"}, {"name": "zip", "value": "87121"}, {"name": "state", "value": "UT"}, {"name": "city", "value": "SLC"}, {"name": "address1", "value": "101 Tela Lane"} ]"#; let results_json = encode_attributes(TEST_CREDENTIAL_DATA).unwrap(); let results: Value = serde_json::from_str(&results_json).unwrap(); assert_eq!(expected, results); } #[test] fn test_encode_with_new_format_several_attributes_success() { let _setup = SetupMocks::init(); let expected = json!({ "address2": { "encoded": "68086943237164982734333428280784300550565381723532936263016368251445461241953", "raw": "101 Wilson Lane" }, "zip": { "encoded": "87121", "raw": "87121" }, "city": { "encoded": "101327353979588246869873249766058188995681113722618593621043638294296500696424", "raw": "SLC" }, "address1": { "encoded": "63690509275174663089934667471948380740244018358024875547775652380902762701972", "raw": "101 Tela Lane" }, "state": { "encoded": "93856629670657830351991220989031130499313559332549427637940645777813964461231", "raw": "UT" } }); static TEST_CREDENTIAL_DATA: &str = r#"{"address2":"101 Wilson Lane", "zip":"87121", "state":"UT", "city":"SLC", "address1":"101 Tela Lane" }"#; let results_json = encode_attributes(TEST_CREDENTIAL_DATA).unwrap(); let results: Value = serde_json::from_str(&results_json).unwrap(); assert_eq!(expected, results); } #[test] fn test_encode_with_new_format_one_attribute_success() { let _setup = SetupMocks::init(); let expected = json!({ "address2": { "encoded": "68086943237164982734333428280784300550565381723532936263016368251445461241953", "raw": "101 Wilson Lane" } }); static TEST_CREDENTIAL_DATA: &str = r#"{"address2": "101 Wilson Lane"}"#; let expected_json = serde_json::to_string_pretty(&expected).unwrap(); let results_json = encode_attributes(TEST_CREDENTIAL_DATA).unwrap(); assert_eq!( expected_json, results_json, "encode_attributes failed to return expected results" ); } #[test] fn test_encode_with_mixed_format_several_attributes_success() { let _setup = SetupMocks::init(); // for reference....expectation is encode_attributes returns this: let expected = json!({ "address2": { "encoded": "68086943237164982734333428280784300550565381723532936263016368251445461241953", "raw": "101 Wilson Lane" }, "zip": { "encoded": "87121", "raw": "87121" }, "city": { "encoded": "101327353979588246869873249766058188995681113722618593621043638294296500696424", "raw": "SLC" }, "address1": { "encoded": "63690509275174663089934667471948380740244018358024875547775652380902762701972", "raw": "101 Tela Lane" }, "state": { "encoded": "93856629670657830351991220989031130499313559332549427637940645777813964461231", "raw": "UT" } }); static TEST_CREDENTIAL_DATA: &str = r#"{"address2":["101 Wilson Lane"], "zip":"87121", "state":"UT", "city":["SLC"], "address1":"101 Tela Lane" }"#; let results_json = encode_attributes(TEST_CREDENTIAL_DATA).unwrap(); let results: Value = serde_json::from_str(&results_json).unwrap(); assert_eq!(expected, results); } #[test] fn test_encode_bad_format_returns_error() { let _setup = SetupMocks::init(); static BAD_TEST_CREDENTIAL_DATA: &str = r#"{"format doesnt make sense"}"#; assert!(encode_attributes(BAD_TEST_CREDENTIAL_DATA).is_err()) } #[test] fn test_encode_old_format_empty_array_error() { let _setup = SetupMocks::init(); static BAD_TEST_CREDENTIAL_DATA: &str = r#"{"address2":[]}"#; assert!(encode_attributes(BAD_TEST_CREDENTIAL_DATA).is_err()) } #[test] fn test_encode_empty_field() { let _setup = SetupMocks::init(); let expected = json!({ "empty_field": { "encoded": "102987336249554097029535212322581322789799900648198034993379397001115665086549", "raw": "" } }); static TEST_CREDENTIAL_DATA: &str = r#"{"empty_field": ""}"#; let results_json = encode_attributes(TEST_CREDENTIAL_DATA).unwrap(); let results: Value = serde_json::from_str(&results_json).unwrap(); assert_eq!(expected, results); } }
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/mod.rs
aries/aries_vcx/src/protocols/mod.rs
use diddoc_legacy::aries::diddoc::AriesDidDoc; use futures::future::BoxFuture; use messages::AriesMessage; use crate::errors::error::VcxResult; pub mod common; pub mod connection; pub mod did_exchange; pub mod issuance; pub mod mediated_connection; pub mod oob; pub mod proof_presentation; pub mod revocation_notification; pub mod trustping; pub type SendClosure<'a> = Box<dyn FnOnce(AriesMessage) -> BoxFuture<'a, VcxResult<()>> + Send + Sync + 'a>; pub type SendClosureConnection<'a> = Box< dyn FnOnce(AriesMessage, String, AriesDidDoc) -> BoxFuture<'a, VcxResult<()>> + Send + Sync + 'a, >;
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/common.rs
aries/aries_vcx/src/protocols/common.rs
use messages::{ decorators::thread::Thread, msg_fields::protocols::report_problem::{ Description, ProblemReport, ProblemReportContent, ProblemReportDecorators, }, }; use uuid::Uuid; pub fn build_problem_report_msg(comment: Option<String>, thread_id: &str) -> ProblemReport { let id = Uuid::new_v4().to_string(); let content = ProblemReportContent::builder() .description( Description::builder() .code(comment.unwrap_or_default()) .build(), ) .build(); let decorators = ProblemReportDecorators::builder() .thread(Thread::builder().thid(thread_id.to_owned()).build()) .build(); ProblemReport::builder() .id(id) .content(content) .decorators(decorators) .build() } // #[cfg(test)] // mod test { // use crate::protocols::common::build_problem_report_msg; // use crate::utils::devsetup::{was_in_past, SetupMocks}; // #[test] // fn test_holder_build_problem_report_msg() { // let _setup = SetupMocks::init(); // let msg = build_problem_report_msg(Some("foo".into()), "12345"); // assert_eq!(msg.id, "test"); // assert_eq!(msg.decorators.thread.unwrap().thid, "12345"); // assert!(was_in_past( // &msg.decorators.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/revocation_notification/mod.rs
aries/aries_vcx/src/protocols/revocation_notification/mod.rs
pub mod receiver; pub mod sender; #[cfg(test)] pub mod test_utils { use messages::{ decorators::please_ack::{AckOn, PleaseAck}, msg_fields::protocols::revocation::revoke::{ RevocationFormat, Revoke, RevokeContent, RevokeDecorators, }, AriesMessage, }; use shared::maybe_known::MaybeKnown; use test_utils::constants::REV_REG_ID; use uuid::Uuid; use crate::{errors::error::VcxResult, protocols::SendClosure}; pub fn _send_message() -> SendClosure<'static> { Box::new(|_: AriesMessage| Box::pin(async { VcxResult::Ok(()) })) } pub fn _rev_reg_id() -> String { String::from(REV_REG_ID) } pub fn _cred_rev_id() -> u32 { 12 } pub fn _comment() -> String { "Comment.".to_string() } pub fn _revocation_notification(ack_on: Vec<AckOn>) -> Revoke { let id = Uuid::new_v4().to_string(); let content = RevokeContent::builder() .credential_id(format!("{}::{}", _rev_reg_id(), _cred_rev_id())) .revocation_format(MaybeKnown::Known(RevocationFormat::IndyAnoncreds)) .comment(_comment()) .build(); let decorators = RevokeDecorators::builder() .please_ack(PleaseAck::builder().on(ack_on).build()) .build(); Revoke::builder() .id(id) .content(content) .decorators(decorators) .build() } }
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/revocation_notification/sender/mod.rs
aries/aries_vcx/src/protocols/revocation_notification/sender/mod.rs
pub mod state_machine; 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/revocation_notification/sender/state_machine.rs
aries/aries_vcx/src/protocols/revocation_notification/sender/state_machine.rs
use messages::{ decorators::please_ack::{AckOn, PleaseAck}, msg_fields::protocols::revocation::{ ack::AckRevoke, revoke::{RevocationFormat, Revoke, RevokeContent, RevokeDecorators}, }, }; use shared::maybe_known::MaybeKnown; use uuid::Uuid; use crate::{ errors::error::prelude::*, handlers::util::verify_thread_id, protocols::{ revocation_notification::sender::states::{ finished::FinishedState, initial::InitialState, sent::NotificationSentState, }, SendClosure, }, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct RevocationNotificationSenderSM { state: SenderFullState, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum SenderFullState { Initial(InitialState), NotificationSent(NotificationSentState), Finished(FinishedState), } #[derive(Default, Builder)] pub struct SenderConfig { rev_reg_id: String, cred_rev_id: u32, comment: Option<String>, ack_on: Vec<AckOn>, } impl RevocationNotificationSenderSM { pub fn create() -> Self { Self { state: SenderFullState::Initial(InitialState), } } pub fn get_notification(&self) -> VcxResult<Revoke> { match &self.state { SenderFullState::NotificationSent(state) => Ok(state.get_notification()), SenderFullState::Finished(state) => Ok(state.get_notification()), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Revocation notification not yet known in this state", )), } } pub fn get_thread_id(&self) -> VcxResult<String> { match &self.state { SenderFullState::NotificationSent(state) => Ok(state.get_thread_id()), SenderFullState::Finished(state) => Ok(state.get_thread_id()), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Thread ID not yet known in this state", )), } } pub async fn send( self, config: SenderConfig, send_message: SendClosure<'_>, ) -> VcxResult<Self> { let state = match self.state { SenderFullState::Initial(_) | SenderFullState::NotificationSent(_) => { let SenderConfig { rev_reg_id, cred_rev_id, comment, ack_on, } = config; let id = Uuid::new_v4().to_string(); let content = RevokeContent::builder() .credential_id(format!("{rev_reg_id}::{cred_rev_id}")) .revocation_format(MaybeKnown::Known(RevocationFormat::IndyAnoncreds)); let content = if let Some(comment) = comment { content.comment(comment).build() } else { content.build() }; let decorators = RevokeDecorators::builder() .please_ack(PleaseAck::builder().on(ack_on).build()) .build(); let rev_msg: Revoke = Revoke::builder() .id(id) .content(content) .decorators(decorators) .build(); send_message(rev_msg.clone().into()).await?; let is_finished = !rev_msg .decorators .please_ack .as_ref() .map(|d| d.on.is_empty()) .unwrap_or(false); if is_finished { SenderFullState::Finished(FinishedState::new(rev_msg, None)) } else { SenderFullState::NotificationSent(NotificationSentState::new(rev_msg)) } } _ => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Ack already received", )); } }; Ok(Self { state }) } pub fn handle_ack(self, ack: AckRevoke) -> VcxResult<Self> { let state = match self.state { SenderFullState::NotificationSent(state) if state .get_notification() .decorators .please_ack .as_ref() .map(|d| d.on.is_empty()) .unwrap_or(false) => { verify_thread_id(&state.get_thread_id(), &ack.clone().into())?; SenderFullState::Finished(FinishedState::new(state.get_notification(), Some(ack))) } _ => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Ack not expected in this state", )); } }; Ok(Self { state }) } } #[cfg(test)] pub mod test_utils { use super::*; use crate::protocols::revocation_notification::test_utils::{ _comment, _cred_rev_id, _rev_reg_id, }; pub fn _sender_config(ack_on: Vec<AckOn>) -> SenderConfig { SenderConfigBuilder::default() .rev_reg_id(_rev_reg_id()) .cred_rev_id(_cred_rev_id()) .comment(Some(_comment())) .ack_on(ack_on) .build() .unwrap() } pub fn _sender() -> RevocationNotificationSenderSM { RevocationNotificationSenderSM::create() } } // #[cfg(test)] // pub mod unit_tests { // use messages::concepts::ack::test_utils::{_ack, _ack_1}; // use crate::protocols::revocation_notification::{ // sender::state_machine::test_utils::*, // test_utils::{_revocation_notification, _send_message}, // }; // use super::*; // async fn _to_revocation_notification_sent_state() -> RevocationNotificationSenderSM { // let sm = _sender() // .send(_sender_config(vec![AckOn::Receipt]), _send_message()) // .await // .unwrap(); // assert_match!(SenderFullState::NotificationSent(_), sm.state); // sm // } // async fn _to_finished_state_via_no_ack() -> RevocationNotificationSenderSM { // let sm = _sender().send(_sender_config(vec![]), _send_message()).await.unwrap(); // assert_match!(SenderFullState::Finished(_), sm.state); // sm // } // async fn _to_finished_state_via_ack() -> RevocationNotificationSenderSM { // let sm = _to_revocation_notification_sent_state().await; // let sm = sm.handle_ack(_ack()).unwrap(); // assert_match!(SenderFullState::Finished(_), sm.state); // sm // } // #[tokio::test] // async fn test_get_notification_from_notification_sent_state() { // let sm = _to_revocation_notification_sent_state().await; // assert_eq!( // sm.get_notification().unwrap(), // _revocation_notification(vec![AckOn::Receipt]) // ); // } // #[tokio::test] // async fn test_get_notification_from_finished_state() { // let sm = _to_finished_state_via_no_ack().await; // assert_eq!(sm.get_notification().unwrap(), _revocation_notification(vec![])); // } // #[tokio::test] // async fn test_get_thread_id_from_notification_sent_state() { // let sm = _to_revocation_notification_sent_state().await; // assert!(sm.get_thread_id().is_ok()); // } // #[tokio::test] // async fn test_get_thread_id_from_finished_state() { // let sm = _to_finished_state_via_no_ack().await; // assert!(sm.get_thread_id().is_ok()); // } // #[tokio::test] // async fn test_handle_ack_correct_thread_id() { // _to_finished_state_via_ack().await; // } // #[tokio::test] // async fn test_handle_ack_fails_incorrect_thread_id() { // let sm = _to_revocation_notification_sent_state().await; // assert!(sm.handle_ack(_ack_1()).is_err()); // } // #[tokio::test] // async fn test_handle_ack_cant_handle_ack_twice() { // let sm = _to_revocation_notification_sent_state().await; // assert!(sm.handle_ack(_ack()).unwrap().handle_ack(_ack()).is_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/revocation_notification/sender/states/sent.rs
aries/aries_vcx/src/protocols/revocation_notification/sender/states/sent.rs
use messages::msg_fields::protocols::revocation::revoke::Revoke; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct NotificationSentState { rev_msg: Revoke, } impl NotificationSentState { pub fn new(rev_msg: Revoke) -> Self { Self { rev_msg } } pub fn get_notification(&self) -> Revoke { self.rev_msg.clone() } pub fn get_thread_id(&self) -> String { self.rev_msg .decorators .thread .as_ref() .map(|t| t.thid.clone()) .unwrap_or(self.rev_msg.id.clone()) } }
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/revocation_notification/sender/states/finished.rs
aries/aries_vcx/src/protocols/revocation_notification/sender/states/finished.rs
use messages::msg_fields::protocols::revocation::{ack::AckRevoke, revoke::Revoke}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct FinishedState { rev_msg: Revoke, ack: Option<AckRevoke>, } impl FinishedState { pub fn new(rev_msg: Revoke, ack: Option<AckRevoke>) -> Self { Self { rev_msg, ack } } pub fn get_notification(&self) -> Revoke { self.rev_msg.clone() } pub fn get_thread_id(&self) -> String { self.rev_msg .decorators .thread .as_ref() .map(|t| t.thid.clone()) .unwrap_or(self.rev_msg.id.clone()) } }
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/revocation_notification/sender/states/mod.rs
aries/aries_vcx/src/protocols/revocation_notification/sender/states/mod.rs
pub(super) mod finished; pub(super) mod initial; pub(super) mod 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/revocation_notification/sender/states/initial.rs
aries/aries_vcx/src/protocols/revocation_notification/sender/states/initial.rs
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct InitialState;
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/revocation_notification/receiver/mod.rs
aries/aries_vcx/src/protocols/revocation_notification/receiver/mod.rs
pub mod state_machine; 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/revocation_notification/receiver/state_machine.rs
aries/aries_vcx/src/protocols/revocation_notification/receiver/state_machine.rs
use chrono::Utc; use messages::{ decorators::{please_ack::AckOn, thread::Thread, timing::Timing}, msg_fields::protocols::{ notification::ack::{AckContent, AckDecorators, AckStatus}, revocation::{ ack::AckRevoke, revoke::{RevocationFormat, Revoke}, }, }, }; use shared::maybe_known::MaybeKnown; use uuid::Uuid; use crate::{ errors::error::prelude::*, protocols::{ revocation_notification::receiver::states::{ finished::FinishedState, initial::InitialState, received::NotificationReceivedState, }, SendClosure, }, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct RevocationNotificationReceiverSM { state: ReceiverFullState, rev_reg_id: String, cred_rev_id: u32, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum ReceiverFullState { Initial(InitialState), NotificationReceived(NotificationReceivedState), Finished(FinishedState), } impl RevocationNotificationReceiverSM { pub fn create(rev_reg_id: String, cred_rev_id: u32) -> Self { Self { state: ReceiverFullState::Initial(InitialState), rev_reg_id, cred_rev_id, } } pub fn get_notification(&self) -> VcxResult<Revoke> { match &self.state { ReceiverFullState::NotificationReceived(state) => Ok(state.get_notification()), ReceiverFullState::Finished(state) => Ok(state.get_notification()), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Revocation notification not yet known in this state", )), } } pub fn get_thread_id(&self) -> VcxResult<String> { match &self.state { ReceiverFullState::NotificationReceived(state) => Ok(state.get_thread_id()), ReceiverFullState::Finished(state) => Ok(state.get_thread_id()), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Thread ID not yet known in this state", )), } } pub async fn handle_revocation_notification(self, notification: Revoke) -> VcxResult<Self> { let state = match self.state { ReceiverFullState::Initial(_) => { self.validate_revocation_notification(&notification)?; if !notification .decorators .please_ack .as_ref() .map(|d| d.on.is_empty()) .unwrap_or(false) || notification .decorators .please_ack .as_ref() .map(|d| d.on.contains(&AckOn::Receipt)) .unwrap_or(false) { ReceiverFullState::Finished(FinishedState::new(notification)) } else { ReceiverFullState::NotificationReceived(NotificationReceivedState::new( notification, )) } } _ => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Ack already received", )); } }; Ok(Self { state, ..self }) } pub async fn send_ack(self, send_message: SendClosure<'_>) -> VcxResult<Self> { let state = match self.state { ReceiverFullState::NotificationReceived(_) | ReceiverFullState::Finished(_) => { let notification = self.get_notification()?; if !notification .decorators .please_ack .as_ref() .map(|d| d.on.contains(&AckOn::Outcome)) .unwrap_or(false) { warn!( "Revocation notification should have already been sent or not sent at all" ); } let id = Uuid::new_v4().to_string(); let content = AckContent::builder().status(AckStatus::Ok).build(); let thread_id = notification .decorators .thread .as_ref() .map(|t| t.thid.clone()) .unwrap_or(notification.id.clone()); let decorators = AckDecorators::builder() .thread(Thread::builder().thid(thread_id).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); let ack = AckRevoke::builder() .id(id) .content(content) .decorators(decorators) .build(); send_message(ack).await?; ReceiverFullState::Finished(FinishedState::new(notification)) } _ => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Ack already sent", )); } }; Ok(Self { state, ..self }) } fn validate_revocation_notification(&self, notification: &Revoke) -> VcxResult<()> { let check_rev_format = || -> VcxResult<()> { if notification.content.revocation_format != MaybeKnown::Known(RevocationFormat::IndyAnoncreds) { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidRevocationDetails, "Received revocation notification with unsupported revocation format, only \ IndyAnoncreds supported", )) } else { Ok(()) } }; let cred_id = notification.content.credential_id.clone(); let parts = cred_id.split("::").collect::<Vec<&str>>(); let check_rev_reg_id = |()| -> VcxResult<()> { if let Some(rev_reg_id) = parts.first() { if *rev_reg_id != self.rev_reg_id { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidRevocationDetails, "Revocation registry ID in received notification does not match \ revocation registry ID of this credential", )) } else { Ok(()) } } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidRevocationDetails, "Invalid credential ID, missing revocation registry ID", )) } }; let check_cred_rev_id = |()| -> VcxResult<()> { if let Some(cred_rev_id) = parts.get(1) { if cred_rev_id.parse::<u32>()? != self.cred_rev_id { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidRevocationDetails, "Credential revocation ID in received notification does not match \ revocation ID of this credential", )) } else { Ok(()) } } else { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidRevocationDetails, "Invalid credential ID, missing revocation registry ID", )) } }; check_rev_format() .and_then(check_rev_reg_id) .and_then(check_cred_rev_id) } } #[cfg(test)] pub mod test_utils { use messages::AriesMessage; use super::*; use crate::protocols::revocation_notification::test_utils::{_cred_rev_id, _rev_reg_id}; pub fn _receiver() -> RevocationNotificationReceiverSM { RevocationNotificationReceiverSM::create(_rev_reg_id(), _cred_rev_id()) } pub fn _send_message_but_fail() -> SendClosure<'static> { Box::new(|_: AriesMessage| { Box::pin(async { Err(AriesVcxError::from_msg( AriesVcxErrorKind::IOError, "Mocked error", )) }) }) } } // #[cfg(test)] // pub mod unit_tests { // use std::sync::mpsc::sync_channel; // use messages::AriesMessage; // use crate::protocols::revocation_notification::{ // receiver::state_machine::test_utils::_receiver, // receiver::state_machine::test_utils::*, // test_utils::{_cred_rev_id, _rev_reg_id, _revocation_notification, _send_message}, // }; // use super::*; // async fn _to_revocation_notification_received_state() -> RevocationNotificationReceiverSM { // let sm = _receiver() // .handle_revocation_notification(_revocation_notification(vec![AckOn::Outcome]), // _send_message()) .await // .unwrap(); // assert_match!(ReceiverFullState::NotificationReceived(_), sm.state); // sm // } // async fn _to_finished_state_via_ack() -> RevocationNotificationReceiverSM { // let sm = _receiver() // .handle_revocation_notification(_revocation_notification(vec![AckOn::Receipt]), // _send_message()) .await // .unwrap(); // assert_match!(ReceiverFullState::Finished(_), sm.state); // sm // } // async fn _to_finished_state_via_no_ack() -> RevocationNotificationReceiverSM { // let sm = _receiver() // .handle_revocation_notification(_revocation_notification(vec![]), _send_message()) // .await // .unwrap(); // assert_match!(ReceiverFullState::Finished(_), sm.state); // sm // } // async fn _send_ack_on(ack_on: Vec<AckOn>) { // let sm = _receiver() // .handle_revocation_notification(_revocation_notification(ack_on), _send_message()) // .await // .unwrap(); // assert_match!(ReceiverFullState::Finished(_), sm.state); // let sm = sm.send_ack(_send_message()).await.unwrap(); // assert_match!(ReceiverFullState::Finished(_), sm.state); // } // #[tokio::test] // async fn test_handle_revocation_notification_sends_ack_when_requested() { // let (sender, receiver) = sync_channel(1); // let send_message: SendClosure = Box::new(move |_: AriesMessage| { // Box::pin(async move { // sender.send(true).unwrap(); // VcxResult::Ok(()) // }) // }); // let sm = RevocationNotificationReceiverSM::create(_rev_reg_id(), _cred_rev_id()) // .handle_revocation_notification(_revocation_notification(vec![AckOn::Receipt]), // send_message) .await // .unwrap(); // assert_match!(ReceiverFullState::Finished(_), sm.state); // assert!(receiver.recv().unwrap()); // } // #[tokio::test] // async fn test_handle_revocation_notification_doesnt_send_ack_when_not_requested() { // let sm = RevocationNotificationReceiverSM::create(_rev_reg_id(), _cred_rev_id()) // .handle_revocation_notification(_revocation_notification(vec![]), // _send_message_but_fail()) .await // .unwrap(); // assert_match!(ReceiverFullState::Finished(_), sm.state); // } // #[tokio::test] // async fn test_handle_revocation_notification_finishes_ack_requested_and_sent() { // _to_finished_state_via_ack().await; // } // #[tokio::test] // async fn test_handle_revocation_notification_finishes_when_ack_not_requested() { // _to_finished_state_via_no_ack().await; // } // #[tokio::test] // async fn test_handle_revocation_notification_waits_to_send_ack_on_outcome() { // _to_revocation_notification_received_state().await; // } // #[tokio::test] // async fn test_handle_revocation_notification_from_finished_state() { // assert!(_to_finished_state_via_ack() // .await // .handle_revocation_notification(_revocation_notification(vec![]), _send_message()) // .await // .is_err()); // assert!(_to_finished_state_via_no_ack() // .await // .handle_revocation_notification(_revocation_notification(vec![]), _send_message()) // .await // .is_err()); // } // #[tokio::test] // async fn test_handle_revocation_notification_from_notification_received_state() { // assert!(_to_revocation_notification_received_state() // .await // .handle_revocation_notification(_revocation_notification(vec![]), _send_message()) // .await // .is_err()); // assert!(_to_revocation_notification_received_state() // .await // .handle_revocation_notification(_revocation_notification(vec![]), _send_message()) // .await // .is_err()); // } // #[tokio::test] // async fn test_send_ack_on_outcome() { // assert!(_to_revocation_notification_received_state() // .await // .send_ack(_send_message()) // .await // .is_ok()); // } // #[tokio::test] // async fn test_send_ack_multiple_times_requested() { // _send_ack_on(vec![AckOn::Receipt, AckOn::Outcome]).await; // } // #[tokio::test] // async fn test_send_ack_multiple_times_not_requested() { // _send_ack_on(vec![AckOn::Receipt]).await; // } // #[tokio::test] // async fn test_send_ack_fails_before_notification_received() { // assert!(_receiver().send_ack(_send_message()).await.is_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/revocation_notification/receiver/states/finished.rs
aries/aries_vcx/src/protocols/revocation_notification/receiver/states/finished.rs
use messages::msg_fields::protocols::revocation::revoke::Revoke; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct FinishedState { rev_msg: Revoke, } impl FinishedState { pub fn new(rev_msg: Revoke) -> Self { Self { rev_msg } } pub fn get_notification(&self) -> Revoke { self.rev_msg.clone() } pub fn get_thread_id(&self) -> String { self.rev_msg .decorators .thread .as_ref() .map(|t| t.thid.clone()) .unwrap_or(self.rev_msg.id.clone()) } }
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/revocation_notification/receiver/states/mod.rs
aries/aries_vcx/src/protocols/revocation_notification/receiver/states/mod.rs
pub(super) mod finished; pub(super) mod initial; pub(super) mod 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/revocation_notification/receiver/states/initial.rs
aries/aries_vcx/src/protocols/revocation_notification/receiver/states/initial.rs
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct InitialState;
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/revocation_notification/receiver/states/received.rs
aries/aries_vcx/src/protocols/revocation_notification/receiver/states/received.rs
use messages::msg_fields::protocols::revocation::revoke::Revoke; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct NotificationReceivedState { rev_msg: Revoke, } impl NotificationReceivedState { pub fn new(rev_msg: Revoke) -> Self { Self { rev_msg } } pub fn get_notification(&self) -> Revoke { self.rev_msg.clone() } pub fn get_thread_id(&self) -> String { self.rev_msg .decorators .thread .as_ref() .map(|t| t.thid.clone()) .unwrap_or(self.rev_msg.id.clone()) } }
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/trustping/mod.rs
aries/aries_vcx/src/protocols/trustping/mod.rs
use ::uuid::Uuid; use chrono::Utc; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::trust_ping::{ ping::{Ping, PingContent, PingDecorators}, ping_response::{PingResponse, PingResponseDecorators}, }, AriesMessage, }; pub fn build_ping(request_response: bool, comment: Option<String>) -> Ping { let content = PingContent::builder().response_requested(request_response); let content = match comment { None => content.build(), Some(comment) => content.comment(comment).build(), }; let decorators = PingDecorators::builder() .timing(Timing::builder().out_time(Utc::now()).build()) .build(); Ping::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build() } pub fn build_ping_response(ping: &Ping) -> PingResponse { let thread_id = ping .decorators .thread .as_ref() .map(|t| t.thid.as_str()) .unwrap_or(ping.id.as_str()) .to_owned(); let decorators = PingResponseDecorators::builder() .thread(Thread::builder().thid(thread_id).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); PingResponse::builder() .id(Uuid::new_v4().to_string()) .decorators(decorators) .build() } pub fn build_ping_response_msg(ping: &Ping) -> AriesMessage { build_ping_response(ping).into() } // #[cfg(test)] // pub mod unit_tests { // use messages::protocols::trust_ping::ping::unit_tests::{_ping, _ping_no_thread}; // use messages::protocols::trust_ping::ping_response::unit_tests::_ping_response; // use super::*; // #[test] // fn test_build_ping_response_works() { // assert_eq!( // build_ping_response(&_ping()).get_thread_id(), // _ping_response().get_thread_id() // ); // assert_eq!( // build_ping_response(&_ping_no_thread()).get_thread_id(), // _ping_response().get_thread_id() // ); // assert_eq!( // build_ping_response(&_ping_no_thread()).get_thread_id(), // _ping_no_thread().id.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/aries_vcx/src/protocols/mediated_connection/pairwise_info.rs
aries/aries_vcx/src/protocols/mediated_connection/pairwise_info.rs
/// Making it easy to remove this in the future without duplicating the struct. pub use crate::protocols::connection::pairwise_info::PairwiseInfo;
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/mediated_connection/mod.rs
aries/aries_vcx/src/protocols/mediated_connection/mod.rs
pub mod invitee; pub mod inviter; pub mod pairwise_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/mediated_connection/inviter/mod.rs
aries/aries_vcx/src/protocols/mediated_connection/inviter/mod.rs
pub mod state_machine; 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/mediated_connection/inviter/state_machine.rs
aries/aries_vcx/src/protocols/mediated_connection/inviter/state_machine.rs
use std::{clone::Clone, collections::HashMap}; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use chrono::Utc; use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::{ connection::{ invitation::{Invitation, PairwiseInvitationContent}, problem_report::{ProblemReport, ProblemReportContent, ProblemReportDecorators}, request::Request, response::{Response, ResponseContent, ResponseDecorators}, Connection, ConnectionData, }, discover_features::{disclose::Disclose, query::QueryContent, ProtocolDescriptor}, trust_ping::TrustPing, }, AriesMessage, }; use url::Url; use uuid::Uuid; use crate::{ common::signing::sign_connection_response, errors::error::prelude::*, handlers::util::{verify_thread_id, AnyInvitation}, protocols::{ mediated_connection::{ inviter::states::{ completed::CompletedState, initial::InitialState, invited::InvitedState, requested::RequestedState, responded::RespondedState, }, pairwise_info::PairwiseInfo, }, SendClosureConnection, }, }; #[derive(Clone, Serialize, Deserialize)] pub struct SmMediatedConnectionInviter { pub source_id: String, thread_id: String, pub pairwise_info: PairwiseInfo, pub state: MediatedInviterFullState, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum MediatedInviterFullState { Initial(InitialState), Invited(InvitedState), Requested(RequestedState), Responded(RespondedState), Completed(CompletedState), } #[derive(Debug, PartialEq, Eq)] pub enum MediatedInviterState { Initial, Invited, Requested, Responded, Completed, } impl PartialEq for SmMediatedConnectionInviter { fn eq(&self, other: &Self) -> bool { self.source_id == other.source_id && self.pairwise_info == other.pairwise_info && self.state == other.state } } impl From<MediatedInviterFullState> for MediatedInviterState { fn from(state: MediatedInviterFullState) -> MediatedInviterState { match state { MediatedInviterFullState::Initial(_) => MediatedInviterState::Initial, MediatedInviterFullState::Invited(_) => MediatedInviterState::Invited, MediatedInviterFullState::Requested(_) => MediatedInviterState::Requested, MediatedInviterFullState::Responded(_) => MediatedInviterState::Responded, MediatedInviterFullState::Completed(_) => MediatedInviterState::Completed, } } } impl SmMediatedConnectionInviter { pub fn new(source_id: &str, pairwise_info: PairwiseInfo) -> Self { Self { source_id: source_id.to_string(), thread_id: Uuid::new_v4().to_string(), state: MediatedInviterFullState::Initial(InitialState::new(None)), pairwise_info, } } pub fn from( source_id: String, thread_id: String, pairwise_info: PairwiseInfo, state: MediatedInviterFullState, ) -> Self { Self { source_id, thread_id, pairwise_info, state, } } pub fn pairwise_info(&self) -> &PairwiseInfo { &self.pairwise_info } pub fn source_id(&self) -> &str { &self.source_id } pub fn get_state(&self) -> MediatedInviterState { MediatedInviterState::from(self.state.clone()) } pub fn state_object(&self) -> &MediatedInviterFullState { &self.state } pub fn their_did_doc(&self) -> Option<AriesDidDoc> { match self.state { MediatedInviterFullState::Initial(_) => None, MediatedInviterFullState::Invited(ref _state) => None, MediatedInviterFullState::Requested(ref state) => Some(state.did_doc.clone()), MediatedInviterFullState::Responded(ref state) => Some(state.did_doc.clone()), MediatedInviterFullState::Completed(ref state) => Some(state.did_doc.clone()), } } pub fn get_invitation(&self) -> Option<&AnyInvitation> { match self.state { MediatedInviterFullState::Invited(ref state) => Some(&state.invitation), _ => None, } } pub fn find_message_to_update_state( &self, messages: HashMap<String, AriesMessage>, ) -> Option<(String, AriesMessage)> { for (uid, message) in messages { if self.can_progress_state(&message) { return Some((uid, message)); } } None } pub fn get_protocols(&self) -> Vec<ProtocolDescriptor> { let query = QueryContent::builder().query("*".to_owned()).build(); query.lookup() } pub fn get_remote_protocols(&self) -> Option<Vec<ProtocolDescriptor>> { match self.state { MediatedInviterFullState::Completed(ref state) => state.protocols.clone(), _ => None, } } pub fn is_in_null_state(&self) -> bool { matches!(self.state, MediatedInviterFullState::Initial(_)) } pub fn is_in_final_state(&self) -> bool { matches!(self.state, MediatedInviterFullState::Completed(_)) } pub fn remote_did(&self) -> VcxResult<String> { self.their_did_doc() .map(|did_doc: AriesDidDoc| did_doc.id) .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Remote Connection DID is not set", )) } pub fn remote_vk(&self) -> VcxResult<String> { let did_did = self.their_did_doc().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Counterparty diddoc is not available.", ))?; did_did .recipient_keys()? .first() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Can't resolve recipient key from the counterparty diddoc.", )) .map(|s| s.to_string()) } pub fn can_progress_state(&self, message: &AriesMessage) -> bool { match self.state { MediatedInviterFullState::Invited(_) => matches!( message, AriesMessage::Connection(Connection::Request(_)) | AriesMessage::Connection(Connection::ProblemReport(_)) ), MediatedInviterFullState::Responded(_) => matches!( message, AriesMessage::Notification(_) | AriesMessage::TrustPing(TrustPing::Ping(_)) | AriesMessage::Connection(Connection::ProblemReport(_)) ), _ => false, } } pub fn create_invitation( self, routing_keys: Vec<String>, service_endpoint: Url, ) -> VcxResult<Self> { let state = match self.state { MediatedInviterFullState::Initial(state) => { let id = self.thread_id.clone(); let content = PairwiseInvitationContent::builder() .label(self.source_id.clone()) .recipient_keys(vec![self.pairwise_info.pw_vk.clone()]) .routing_keys(routing_keys) .service_endpoint(service_endpoint) .build(); let invite = Invitation::builder().id(id).content(content).build(); let invitation = AnyInvitation::Con(invite); MediatedInviterFullState::Invited((state, invitation).into()) } _ => self.state.clone(), }; Ok(Self { state, ..self }) } pub async fn handle_connection_request<'a>( self, wallet: &'a impl BaseWallet, request: Request, new_pairwise_info: &'a PairwiseInfo, new_routing_keys: Vec<String>, new_service_endpoint: Url, send_message: SendClosureConnection<'_>, ) -> VcxResult<Self> { if !matches!(self.state, MediatedInviterFullState::Initial(_)) { verify_thread_id(&self.get_thread_id(), &request.clone().into())?; }; let (state, thread_id) = match self.state { MediatedInviterFullState::Invited(_) | MediatedInviterFullState::Initial(_) => { if let Err(err) = request.content.connection.did_doc.validate() { let content = ProblemReportContent::builder() .explain(err.to_string()) .build(); let decorators = ProblemReportDecorators::builder() .thread(Thread::builder().thid(self.thread_id.clone()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); let problem_report: ProblemReport = ProblemReport::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build(); let sender_vk = self.pairwise_info().pw_vk.clone(); let did_doc = request.content.connection.did_doc.clone(); send_message(problem_report.clone().into(), sender_vk, did_doc) .await .ok(); return Ok(Self { state: MediatedInviterFullState::Initial((problem_report).into()), ..self }); }; let thread_id = request .decorators .thread .as_ref() .map(|t| t.thid.clone()) .unwrap_or(request.id.clone()); let signed_response = self .build_response( wallet, thread_id.clone(), new_pairwise_info, new_routing_keys, new_service_endpoint, ) .await?; ( MediatedInviterFullState::Requested((request, signed_response).into()), thread_id, ) } _ => (self.state, self.thread_id.clone()), }; Ok(Self { pairwise_info: new_pairwise_info.to_owned(), thread_id, state, ..self }) } pub fn handle_problem_report(self, problem_report: ProblemReport) -> VcxResult<Self> { let state = match self.state { MediatedInviterFullState::Responded(_) => { MediatedInviterFullState::Initial((problem_report).into()) } MediatedInviterFullState::Invited(_) => { MediatedInviterFullState::Initial((problem_report).into()) } _ => self.state, }; Ok(Self { state, ..self }) } pub async fn handle_send_response( self, send_message: SendClosureConnection<'_>, ) -> VcxResult<Self> { let state = match self.state { MediatedInviterFullState::Requested(state) => { send_message( state.signed_response.clone().into(), self.pairwise_info.pw_vk.clone(), state.did_doc.clone(), ) .await?; MediatedInviterFullState::Responded(state.into()) } _ => self.state, }; Ok(Self { state, ..self }) } pub fn handle_disclose(self, disclose: Disclose) -> VcxResult<Self> { let state = match self.state { MediatedInviterFullState::Completed(state) => { MediatedInviterFullState::Completed((state, disclose.content.protocols).into()) } _ => self.state, }; Ok(Self { state, ..self }) } pub async fn handle_confirmation_message(self, msg: &AriesMessage) -> VcxResult<Self> { verify_thread_id(&self.get_thread_id(), msg)?; match self.state { MediatedInviterFullState::Responded(state) => Ok(Self { state: MediatedInviterFullState::Completed(state.into()), ..self }), _ => Ok(self), } } pub fn get_thread_id(&self) -> String { self.thread_id.clone() } async fn build_response( &self, wallet: &impl BaseWallet, thread_id: String, new_pairwise_info: &PairwiseInfo, new_routing_keys: Vec<String>, new_service_endpoint: Url, ) -> VcxResult<Response> { match &self.state { MediatedInviterFullState::Invited(_) | MediatedInviterFullState::Initial(_) => { let new_recipient_keys = vec![new_pairwise_info.pw_vk.clone()]; let mut did_doc = AriesDidDoc::default(); let did = new_pairwise_info.pw_did.clone(); did_doc.set_id(new_pairwise_info.pw_did.clone()); did_doc.set_service_endpoint(new_service_endpoint); did_doc.set_routing_keys(new_routing_keys); did_doc.set_recipient_keys(new_recipient_keys); let con_data = ConnectionData::new(did, did_doc); let id = Uuid::new_v4().to_string(); let con_sig = sign_connection_response(wallet, &self.pairwise_info.pw_vk, &con_data).await?; let content = ResponseContent::builder().connection_sig(con_sig).build(); let decorators = ResponseDecorators::builder() .thread(Thread::builder().thid(thread_id).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); Ok(Response::builder() .id(id) .content(content) .decorators(decorators) .build()) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Building connection ack in current state is not allowed", )), } } } // #[cfg(test)] // pub mod unit_tests { // use messages::concepts::ack::test_utils::_ack; // use messages::protocols::connection::problem_report::unit_tests::_problem_report; // use messages::protocols::connection::request::unit_tests::_request; // use messages::protocols::connection::response::test_utils::_signed_response; // use messages::protocols::discovery::disclose::test_utils::_disclose; // use messages::protocols::discovery::query::test_utils::_query; // use messages::protocols::trust_ping::ping::unit_tests::_ping; // use crate::test::source_id; // use crate::utils::devsetup::SetupMocks; // use super::*; // pub mod inviter { // use crate::common::test_utils::mock_profile; // use super::*; // fn _send_message() -> SendClosureConnection { // Box::new(|_: A2AMessage, _: String, _: AriesDidDoc| Box::pin(async { // VcxResult::Ok(()) })) } // pub async fn inviter_sm() -> SmConnectionInviter { // let pairwise_info = // PairwiseInfo::create(&mock_profile().inject_wallet()).await.unwrap(); // SmConnectionInviter::new(&source_id(), pairwise_info) } // impl SmConnectionInviter { // fn to_inviter_invited_state(mut self) -> SmConnectionInviter { // let routing_keys: Vec<String> = vec!["verkey123".into()]; // let service_endpoint = String::from("https://example.org/agent"); // self = self.create_invitation(routing_keys, service_endpoint).unwrap(); // self // } // async fn to_inviter_requested_state(mut self) -> SmConnectionInviter { // self = self.to_inviter_invited_state(); // let new_pairwise_info = // PairwiseInfo::create(&mock_profile().inject_wallet()).await.unwrap(); let // new_routing_keys: Vec<String> = vec!["verkey456".into()]; let new_service_endpoint = String::from("https://example.org/agent"); // self = self // .handle_connection_request( // mock_profile().inject_wallet(), // _request(), // &new_pairwise_info, // new_routing_keys, // new_service_endpoint, // _send_message(), // ) // .await // .unwrap(); // self = self.handle_send_response(_send_message()).await.unwrap(); // self // } // async fn to_inviter_responded_state(mut self) -> SmConnectionInviter { // self = self.to_inviter_requested_state().await; // self = self.handle_send_response(_send_message()).await.unwrap(); // self // } // // todo: try reuse to_inviter_responded_state // async fn to_inviter_completed_state(mut self) -> SmConnectionInviter { // self = self.to_inviter_responded_state().await; // self = self // .handle_confirmation_message(&A2AMessage::Ack(_ack())) // .await // .unwrap(); // self // } // } // mod build_messages { // use messages::a2a::MessageId; // use crate::utils::devsetup::was_in_past; // use super::*; // #[tokio::test] // async fn test_build_connection_response_msg() { // let _setup = SetupMocks::init(); // let mut inviter = inviter_sm().await; // inviter = inviter.to_inviter_invited_state(); // let new_pairwise_info = PairwiseInfo { // pw_did: "AC3Gx1RoAz8iYVcfY47gjJ".to_string(), // pw_vk: "verkey456".to_string(), // }; // let new_routing_keys: Vec<String> = vec!["AC3Gx1RoAz8iYVcfY47gjJ".into()]; // let new_service_endpoint = String::from("https://example.org/agent"); // let msg = inviter // .build_response( // &mock_profile().inject_wallet(), // &_request(), // &new_pairwise_info, // new_routing_keys, // new_service_endpoint, // ) // .await // .unwrap(); // assert_eq!(msg.id, MessageId::default()); // assert!(was_in_past( // &msg.timing.unwrap().out_time.unwrap(), // chrono::Duration::milliseconds(100), // ) // .unwrap()); // } // } // mod get_thread_id { // use messages::concepts::ack::test_utils::_ack_random_thread; // use super::*; // #[tokio::test] // async fn ack_fails_with_incorrect_thread_id() { // let _setup = SetupMocks::init(); // let inviter = inviter_sm().await.to_inviter_responded_state().await; // assert!(inviter // .handle_confirmation_message(&A2AMessage::Ack(_ack_random_thread())) // .await // .is_err()) // } // } // mod new { // use super::*; // #[tokio::test] // async fn test_inviter_new() { // let _setup = SetupMocks::init(); // let inviter_sm = inviter_sm().await; // assert_match!(InviterFullState::Initial(_), inviter_sm.state); // assert_eq!(source_id(), inviter_sm.source_id()); // } // } // mod step { // use crate::utils::devsetup::SetupIndyMocks; // use super::*; // #[tokio::test] // async fn test_did_exchange_init() { // let _setup = SetupIndyMocks::init(); // let did_exchange_sm = inviter_sm().await; // assert_match!(InviterFullState::Initial(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_connect_message_from_null_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = inviter_sm().await; // let routing_keys: Vec<String> = vec!["verkey123".into()]; // let service_endpoint = String::from("https://example.org/agent"); // did_exchange_sm = did_exchange_sm // .create_invitation(routing_keys, service_endpoint) // .unwrap(); // assert_match!(InviterFullState::Invited(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_other_messages_from_null_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = inviter_sm().await; // did_exchange_sm = did_exchange_sm // .handle_confirmation_message(&A2AMessage::Ack(_ack())) // .await // .unwrap(); // assert_match!(InviterFullState::Initial(_), did_exchange_sm.state); // did_exchange_sm = // did_exchange_sm.handle_problem_report(_problem_report()).unwrap(); // assert_match!(InviterFullState::Initial(_), did_exchange_sm.state); } // #[tokio::test] // async fn test_did_exchange_handle_exchange_request_message_from_invited_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = inviter_sm().await.to_inviter_invited_state(); // let new_pairwise_info = PairwiseInfo { // pw_did: "AC3Gx1RoAz8iYVcfY47gjJ".to_string(), // pw_vk: "verkey456".to_string(), // }; // let new_routing_keys: Vec<String> = vec!["AC3Gx1RoAz8iYVcfY47gjJ".into()]; // let new_service_endpoint = String::from("https://example.org/agent"); // did_exchange_sm = did_exchange_sm // .handle_connection_request( // mock_profile().inject_wallet(), // _request(), // &new_pairwise_info, // new_routing_keys, // new_service_endpoint, // _send_message(), // ) // .await // .unwrap(); // did_exchange_sm = // did_exchange_sm.handle_send_response(_send_message()).await.unwrap(); // assert_match!(InviterFullState::Responded(_), did_exchange_sm.state); } // #[tokio::test] // async fn // test_did_exchange_handle_invalid_exchange_request_message_from_invited_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = inviter_sm().await.to_inviter_invited_state(); // let mut request = _request(); // request.connection.did_doc = AriesDidDoc::default(); // let new_pairwise_info = PairwiseInfo { // pw_did: "AC3Gx1RoAz8iYVcfY47gjJ".to_string(), // pw_vk: "verkey456".to_string(), // }; // let new_routing_keys: Vec<String> = vec!["AC3Gx1RoAz8iYVcfY47gjJ".into()]; // let new_service_endpoint = String::from("https://example.org/agent"); // did_exchange_sm = did_exchange_sm // .handle_connection_request( // mock_profile().inject_wallet(), // request, // &new_pairwise_info, // new_routing_keys, // new_service_endpoint, // _send_message(), // ) // .await // .unwrap(); // assert_match!(InviterFullState::Initial(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_problem_report_message_from_invited_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = inviter_sm().await.to_inviter_invited_state(); // did_exchange_sm = // did_exchange_sm.handle_problem_report(_problem_report()).unwrap(); // assert_match!(InviterFullState::Initial(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_other_message_from_null_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = inviter_sm().await.to_inviter_invited_state(); // let routing_keys: Vec<String> = vec!["verkey123".into()]; // let service_endpoint = String::from("https://example.org/agent"); // did_exchange_sm = did_exchange_sm // .create_invitation(routing_keys, service_endpoint) // .unwrap(); // assert_match!(InviterFullState::Invited(_), did_exchange_sm.state); // did_exchange_sm = did_exchange_sm // .handle_confirmation_message(&A2AMessage::Ack(_ack())) // .await // .unwrap(); // assert_match!(InviterFullState::Invited(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_ack_message_from_responded_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = inviter_sm().await.to_inviter_responded_state().await; // did_exchange_sm = did_exchange_sm // .handle_confirmation_message(&A2AMessage::Ack(_ack())) // .await // .unwrap(); // assert_match!(InviterFullState::Completed(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_ping_message_from_responded_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = inviter_sm().await.to_inviter_responded_state().await; // did_exchange_sm = did_exchange_sm // .handle_confirmation_message(&A2AMessage::Ping(_ping())) // .await // .unwrap(); // assert_match!(InviterFullState::Completed(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_problem_report_message_from_responded_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = inviter_sm().await.to_inviter_responded_state().await; // did_exchange_sm = // did_exchange_sm.handle_problem_report(_problem_report()).unwrap(); // assert_match!(InviterFullState::Initial(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_other_messages_from_responded_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = inviter_sm().await.to_inviter_responded_state().await; // let routing_keys: Vec<String> = vec!["verkey123".into()]; // let service_endpoint = String::from("https://example.org/agent"); // did_exchange_sm = did_exchange_sm // .create_invitation(routing_keys, service_endpoint) // .unwrap(); // assert_match!(InviterFullState::Responded(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_messages_from_completed_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = inviter_sm().await.to_inviter_completed_state().await; // // Ping // did_exchange_sm = did_exchange_sm // .handle_confirmation_message(&A2AMessage::Ping(_ping())) // .await // .unwrap(); // assert_match!(InviterFullState::Completed(_), did_exchange_sm.state); // // Ack // did_exchange_sm = did_exchange_sm // .handle_confirmation_message(&A2AMessage::Ack(_ack())) // .await // .unwrap(); // assert_match!(InviterFullState::Completed(_), did_exchange_sm.state); // // Disclose // assert!(did_exchange_sm.get_remote_protocols().is_none()); // did_exchange_sm = did_exchange_sm.handle_disclose(_disclose()).unwrap(); // assert_match!(InviterFullState::Completed(_), did_exchange_sm.state); // assert!(did_exchange_sm.get_remote_protocols().is_some()); // // Problem Report // did_exchange_sm = // did_exchange_sm.handle_problem_report(_problem_report()).unwrap(); // assert_match!(InviterFullState::Completed(_), did_exchange_sm.state); } // } // mod find_message_to_handle { // use crate::utils::devsetup::SetupIndyMocks; // use super::*; // #[tokio::test] // async fn test_find_message_to_handle_from_null_state() { // let _setup = SetupIndyMocks::init(); // let connection = inviter_sm().await; // // No messages // { // let messages = map!( // "key_1".to_string() => A2AMessage::ConnectionRequest(_request()), // "key_2".to_string() => // A2AMessage::ConnectionResponse(_signed_response()), "key_3".to_string() // => A2AMessage::ConnectionProblemReport(_problem_report()), // "key_4".to_string() => A2AMessage::Ping(_ping()), "key_5".to_string() => // A2AMessage::Ack(_ack()) ); // assert!(connection.find_message_to_update_state(messages).is_none()); // } // } // #[tokio::test] // async fn test_find_message_to_handle_from_invited_state() { // let _setup = SetupIndyMocks::init(); // let connection = inviter_sm().await.to_inviter_invited_state(); // // Connection Request // { // let messages = map!( // "key_1".to_string() => A2AMessage::Ping(_ping()), // "key_2".to_string() => A2AMessage::ConnectionRequest(_request()), // "key_3".to_string() => A2AMessage::ConnectionResponse(_signed_response()) // ); // let (uid, message) = // connection.find_message_to_update_state(messages).unwrap(); // assert_eq!("key_2", uid); assert_match!(A2AMessage::ConnectionRequest(_), // message); } // // Connection Problem Report // { // let messages = map!( // "key_1".to_string() => A2AMessage::Ping(_ping()), // "key_2".to_string() => A2AMessage::Ack(_ack()), // "key_3".to_string() => // A2AMessage::ConnectionProblemReport(_problem_report()) ); // let (uid, message) = // connection.find_message_to_update_state(messages).unwrap(); // assert_eq!("key_3", uid); // assert_match!(A2AMessage::ConnectionProblemReport(_), message); } // // No messages // {
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
true
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/mediated_connection/inviter/states/completed.rs
aries/aries_vcx/src/protocols/mediated_connection/inviter/states/completed.rs
use std::clone::Clone; use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::discover_features::ProtocolDescriptor; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CompletedState { pub did_doc: AriesDidDoc, pub protocols: Option<Vec<ProtocolDescriptor>>, pub thread_id: Option<String>, } impl From<(CompletedState, Vec<ProtocolDescriptor>)> for CompletedState { fn from((state, protocols): (CompletedState, Vec<ProtocolDescriptor>)) -> CompletedState { trace!("ConnectionInviter: transit state from CompleteState to CompleteState"); CompletedState { did_doc: state.did_doc, thread_id: state.thread_id, protocols: Some(protocols), } } }
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/mediated_connection/inviter/states/invited.rs
aries/aries_vcx/src/protocols/mediated_connection/inviter/states/invited.rs
use messages::msg_fields::protocols::connection::{ problem_report::ProblemReport, request::Request, response::Response, }; use crate::{ handlers::util::AnyInvitation, protocols::mediated_connection::inviter::states::{ initial::InitialState, requested::RequestedState, }, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct InvitedState { pub invitation: AnyInvitation, } // TODO: These have no justification for being here anymore impl From<ProblemReport> for InitialState { fn from(problem_report: ProblemReport) -> InitialState { trace!( "ConnectionInviter: transit state to InitialState, problem_report: {problem_report:?}" ); InitialState::new(Some(problem_report)) } } impl From<(Request, Response)> for RequestedState { fn from((request, signed_response): (Request, Response)) -> RequestedState { trace!("ConnectionInviter: transit state to RespondedState"); RequestedState { signed_response, did_doc: request.content.connection.did_doc, thread_id: request.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/mediated_connection/inviter/states/requested.rs
aries/aries_vcx/src/protocols/mediated_connection/inviter/states/requested.rs
use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::connection::{ problem_report::ProblemReport, response::Response, }; use crate::protocols::mediated_connection::inviter::states::{ initial::InitialState, responded::RespondedState, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct RequestedState { pub signed_response: Response, pub did_doc: AriesDidDoc, pub thread_id: String, } impl From<(RequestedState, ProblemReport)> for InitialState { fn from((_state, problem_report): (RequestedState, ProblemReport)) -> InitialState { trace!( "ConnectionInviter: transit state from RequestedState to InitialState, \ problem_report: {problem_report:?}" ); InitialState::new(Some(problem_report)) } } impl From<RequestedState> for RespondedState { fn from(state: RequestedState) -> RespondedState { trace!("ConnectionInviter: transit state from RequestedState to RespondedState"); RespondedState { signed_response: state.signed_response, did_doc: state.did_doc, } } }
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/mediated_connection/inviter/states/mod.rs
aries/aries_vcx/src/protocols/mediated_connection/inviter/states/mod.rs
pub(super) mod completed; pub(super) mod initial; pub(super) mod invited; pub(super) mod requested; pub(super) mod responded;
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/mediated_connection/inviter/states/responded.rs
aries/aries_vcx/src/protocols/mediated_connection/inviter/states/responded.rs
use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::connection::{ problem_report::ProblemReport, response::Response, }; use crate::protocols::mediated_connection::inviter::states::{ completed::CompletedState, initial::InitialState, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct RespondedState { pub signed_response: Response, pub did_doc: AriesDidDoc, } impl From<(RespondedState, ProblemReport)> for InitialState { fn from((_state, problem_report): (RespondedState, ProblemReport)) -> InitialState { trace!( "ConnectionInviter: transit state from RespondedState to InitialState, \ problem_report: {problem_report:?}" ); InitialState::new(Some(problem_report)) } } impl From<RespondedState> for CompletedState { fn from(state: RespondedState) -> CompletedState { trace!("ConnectionInviter: transit state from RespondedState to CompleteState"); CompletedState { did_doc: state.did_doc, thread_id: Some(state.signed_response.decorators.thread.thid), protocols: 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/mediated_connection/inviter/states/initial.rs
aries/aries_vcx/src/protocols/mediated_connection/inviter/states/initial.rs
use messages::msg_fields::protocols::connection::problem_report::ProblemReport; use crate::{ handlers::util::AnyInvitation, protocols::mediated_connection::inviter::states::invited::InvitedState, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct InitialState { problem_report: Option<ProblemReport>, } impl From<(InitialState, AnyInvitation)> for InvitedState { fn from((_state, invitation): (InitialState, AnyInvitation)) -> InvitedState { trace!("ConnectionInviter: transit state from InitialState to InvitedState"); InvitedState { invitation } } } impl InitialState { pub fn new(problem_report: Option<ProblemReport>) -> Self { InitialState { problem_report } } }
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/mediated_connection/invitee/mod.rs
aries/aries_vcx/src/protocols/mediated_connection/invitee/mod.rs
pub mod state_machine; 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/mediated_connection/invitee/state_machine.rs
aries/aries_vcx/src/protocols/mediated_connection/invitee/state_machine.rs
use std::{clone::Clone, collections::HashMap}; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use chrono::Utc; use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::{ connection::{ invitation::InvitationContent, problem_report::{ProblemReport, ProblemReportContent, ProblemReportDecorators}, request::{Request, RequestContent, RequestDecorators}, response::Response, Connection, ConnectionData, }, discover_features::{disclose::Disclose, query::QueryContent, ProtocolDescriptor}, notification::ack::{Ack, AckContent, AckDecorators, AckStatus}, }, AriesMessage, }; use url::Url; use uuid::Uuid; use crate::{ common::signing::decode_signed_connection_response, errors::error::prelude::*, handlers::util::{matches_thread_id, verify_thread_id, AnyInvitation}, protocols::{ mediated_connection::{ invitee::states::{ completed::CompletedState, initial::InitialState, invited::InvitedState, requested::RequestedState, responded::RespondedState, }, pairwise_info::PairwiseInfo, }, SendClosureConnection, }, }; #[derive(Clone, Serialize, Deserialize)] pub struct SmMediatedConnectionInvitee { source_id: String, thread_id: String, pairwise_info: PairwiseInfo, state: MediatedInviteeFullState, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum MediatedInviteeFullState { Initial(InitialState), Invited(InvitedState), Requested(RequestedState), Responded(RespondedState), Completed(CompletedState), } #[derive(Debug, PartialEq, Eq)] pub enum MediatedInviteeState { Initial, Invited, Requested, Responded, Completed, } impl PartialEq for SmMediatedConnectionInvitee { fn eq(&self, other: &Self) -> bool { self.source_id == other.source_id && self.pairwise_info == other.pairwise_info && self.state == other.state } } impl From<MediatedInviteeFullState> for MediatedInviteeState { fn from(state: MediatedInviteeFullState) -> MediatedInviteeState { match state { MediatedInviteeFullState::Initial(_) => MediatedInviteeState::Initial, MediatedInviteeFullState::Invited(_) => MediatedInviteeState::Invited, MediatedInviteeFullState::Requested(_) => MediatedInviteeState::Requested, MediatedInviteeFullState::Responded(_) => MediatedInviteeState::Responded, MediatedInviteeFullState::Completed(_) => MediatedInviteeState::Completed, } } } impl SmMediatedConnectionInvitee { pub fn new(source_id: &str, pairwise_info: PairwiseInfo, did_doc: AriesDidDoc) -> Self { SmMediatedConnectionInvitee { source_id: source_id.to_string(), thread_id: String::new(), state: MediatedInviteeFullState::Initial(InitialState::new(None, Some(did_doc))), pairwise_info, } } pub fn from( source_id: String, thread_id: String, pairwise_info: PairwiseInfo, state: MediatedInviteeFullState, ) -> Self { SmMediatedConnectionInvitee { source_id, thread_id, pairwise_info, state, } } pub fn pairwise_info(&self) -> &PairwiseInfo { &self.pairwise_info } pub fn source_id(&self) -> &str { &self.source_id } pub fn get_state(&self) -> MediatedInviteeState { MediatedInviteeState::from(self.state.clone()) } pub fn state_object(&self) -> &MediatedInviteeFullState { &self.state } pub fn is_in_null_state(&self) -> bool { matches!(self.state, MediatedInviteeFullState::Initial(_)) } pub fn is_in_final_state(&self) -> bool { matches!(self.state, MediatedInviteeFullState::Completed(_)) } pub fn their_did_doc(&self) -> Option<AriesDidDoc> { match self.state { MediatedInviteeFullState::Initial(ref state) => state.did_doc.clone(), MediatedInviteeFullState::Invited(ref state) => Some(state.did_doc.clone()), MediatedInviteeFullState::Requested(ref state) => Some(state.did_doc.clone()), MediatedInviteeFullState::Responded(ref state) => Some(state.did_doc.clone()), MediatedInviteeFullState::Completed(ref state) => Some(state.did_doc.clone()), } } pub fn bootstrap_did_doc(&self) -> Option<AriesDidDoc> { match self.state { MediatedInviteeFullState::Initial(ref state) => state.did_doc.clone(), MediatedInviteeFullState::Invited(ref state) => Some(state.did_doc.clone()), MediatedInviteeFullState::Requested(ref state) => Some(state.did_doc.clone()), MediatedInviteeFullState::Responded(ref state) => Some(state.did_doc.clone()), MediatedInviteeFullState::Completed(ref state) => Some(state.bootstrap_did_doc.clone()), } } pub fn get_invitation(&self) -> Option<&AnyInvitation> { match self.state { MediatedInviteeFullState::Invited(ref state) => Some(&state.invitation), _ => None, } } pub fn find_message_to_update_state( &self, messages: HashMap<String, AriesMessage>, ) -> Option<(String, AriesMessage)> { for (uid, message) in messages { if self.can_progress_state(&message) { return Some((uid, message)); } } None } pub fn get_protocols(&self) -> Vec<ProtocolDescriptor> { let query = QueryContent::builder().query("*".to_owned()).build(); query.lookup() } pub fn get_remote_protocols(&self) -> Option<Vec<ProtocolDescriptor>> { match self.state { MediatedInviteeFullState::Completed(ref state) => state.protocols.clone(), _ => None, } } pub fn remote_did(&self) -> VcxResult<String> { self.their_did_doc() .map(|did_doc: AriesDidDoc| did_doc.id) .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Remote Connection DID is not set", )) } pub fn remote_vk(&self) -> VcxResult<String> { let did_did = self.their_did_doc().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Counterparty diddoc is not available.", ))?; did_did .recipient_keys()? .first() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Can't resolve recipient key from the counterparty diddoc.", )) .map(|s| s.to_string()) } pub fn can_progress_state(&self, message: &AriesMessage) -> bool { match self.state { MediatedInviteeFullState::Requested(_) => matches!( message, AriesMessage::Connection(Connection::Response(_)) | AriesMessage::Connection(Connection::ProblemReport(_)) ), _ => false, } } fn build_connection_request_msg( &self, routing_keys: Vec<String>, service_endpoint: Url, ) -> VcxResult<(Request, String)> { match &self.state { MediatedInviteeFullState::Invited(state) => { let recipient_keys = vec![self.pairwise_info.pw_vk.clone()]; let id = Uuid::new_v4().to_string(); let mut did_doc = AriesDidDoc::default(); did_doc.set_service_endpoint(service_endpoint); did_doc.set_routing_keys(routing_keys); did_doc.set_recipient_keys(recipient_keys); did_doc.set_id(self.pairwise_info.pw_did.clone()); let con_data = ConnectionData::new(self.pairwise_info.pw_did.to_string(), did_doc); let content = RequestContent::builder() .label(self.source_id.to_string()) .connection(con_data) .build(); let decorators = RequestDecorators::builder() .timing(Timing::builder().out_time(Utc::now()).build()); let thread = match &state.invitation { AnyInvitation::Oob(invite) => Thread::builder() .thid(id.clone()) .pthid(invite.id.clone()) .build(), AnyInvitation::Con(invite) => match invite.content { InvitationContent::Public(_) => Thread::builder() .thid(id.clone()) .pthid(self.thread_id.clone()) .build(), InvitationContent::Pairwise(_) | InvitationContent::PairwiseDID(_) => { Thread::builder().thid(self.thread_id.clone()).build() } }, }; let thread_id = thread.thid.clone(); let decorators = decorators.thread(thread).build(); let request = Request::builder() .id(id) .content(content) .decorators(decorators) .build(); Ok((request, thread_id)) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Building connection request in current state is not allowed", )), } } fn build_connection_ack_msg(&self) -> VcxResult<Ack> { match &self.state { MediatedInviteeFullState::Responded(_) => { let content = AckContent::builder().status(AckStatus::Ok).build(); let decorators = AckDecorators::builder() .thread(Thread::builder().thid(self.thread_id.to_owned()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); Ok(Ack::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build()) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Building connection ack in current state is not allowed", )), } } pub fn handle_invitation(self, invitation: AnyInvitation) -> VcxResult<Self> { let Self { state, .. } = self; let thread_id = match &invitation { AnyInvitation::Con(i) => i.id.clone(), AnyInvitation::Oob(i) => i.id.clone(), }; let state = match state { MediatedInviteeFullState::Initial(state) => MediatedInviteeFullState::Invited( ( state.clone(), invitation, state.did_doc.ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Expected none None state.did_doc result given current state", ))?, ) .into(), ), s => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!("Cannot handle inviation: not in Initial state, current state: {s:?}"), )); } }; Ok(Self { state, thread_id, ..self }) } pub async fn send_connection_request( self, routing_keys: Vec<String>, service_endpoint: Url, send_message: SendClosureConnection<'_>, ) -> VcxResult<Self> { let (state, thread_id) = match self.state { MediatedInviteeFullState::Invited(ref state) => { let ddo = self.their_did_doc().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Missing did doc", ))?; let (request, thread_id) = self.build_connection_request_msg(routing_keys, service_endpoint)?; send_message( request.clone().into(), self.pairwise_info.pw_vk.clone(), ddo.clone(), ) .await?; ( MediatedInviteeFullState::Requested((state.clone(), request, ddo).into()), thread_id, ) } _ => (self.state.clone(), self.get_thread_id()), }; Ok(Self { state, thread_id, ..self }) } pub async fn handle_connection_response( self, wallet: &impl BaseWallet, response: Response, send_message: SendClosureConnection<'_>, ) -> VcxResult<Self> { verify_thread_id(&self.get_thread_id(), &response.clone().into())?; let state = match self.state { MediatedInviteeFullState::Requested(state) => { let remote_vk: String = state.did_doc.recipient_keys()?.first().cloned().ok_or( AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Cannot handle response: remote verkey not found", ), )?; match decode_signed_connection_response( wallet, response.content.clone(), &remote_vk, ) .await { Ok(con_data) => { let thread_id = state .request .decorators .thread .as_ref() .map(|t| t.thid.as_str()) .unwrap_or(state.request.id.as_str()); if !matches_thread_id!(response, thread_id) { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!( "Cannot handle response: thread id does not match: {thread_id:?}" ), )); } MediatedInviteeFullState::Responded((state, con_data).into()) } Err(err) => { let content = ProblemReportContent::builder() .explain(err.to_string()) .build(); let decorators = ProblemReportDecorators::builder() .thread(Thread::builder().thid(self.thread_id.to_owned()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); let problem_report: ProblemReport = ProblemReport::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build(); send_message( problem_report.clone().into(), self.pairwise_info.pw_vk.clone(), state.did_doc.clone(), ) .await .ok(); MediatedInviteeFullState::Initial((state.clone(), problem_report).into()) } } } _ => self.state.clone(), }; Ok(Self { state, ..self }) } pub fn handle_disclose(self, disclose: Disclose) -> VcxResult<Self> { let state = match self.state { MediatedInviteeFullState::Completed(state) => { MediatedInviteeFullState::Completed((state, disclose.content.protocols).into()) } _ => self.state, }; Ok(Self { state, ..self }) } pub async fn handle_send_ack(self, send_message: SendClosureConnection<'_>) -> VcxResult<Self> { let state = match self.state { MediatedInviteeFullState::Responded(ref state) => { let sender_vk = self.pairwise_info().pw_vk.clone(); let did_doc = state.resp_con_data.did_doc.clone(); send_message(self.build_connection_ack_msg()?.into(), sender_vk, did_doc).await?; MediatedInviteeFullState::Completed((state.clone()).into()) } _ => self.state.clone(), }; Ok(Self { state, ..self }) } pub fn handle_problem_report(self, _problem_report: ProblemReport) -> VcxResult<Self> { let state = match self.state { MediatedInviteeFullState::Requested(_state) => { MediatedInviteeFullState::Initial(InitialState::new(None, None)) } MediatedInviteeFullState::Invited(_state) => { MediatedInviteeFullState::Initial(InitialState::new(None, None)) } _ => self.state.clone(), }; Ok(Self { state, ..self }) } pub fn get_thread_id(&self) -> String { self.thread_id.clone() } } // #[cfg(test)] // pub mod unit_tests { // use messages::concepts::ack::test_utils::_ack; // use messages::protocols::connection::invite::test_utils::_pairwise_invitation; // use messages::protocols::connection::problem_report::unit_tests::_problem_report; // use messages::protocols::connection::request::unit_tests::_request; // use messages::protocols::connection::response::test_utils::_signed_response; // use messages::protocols::discovery::disclose::test_utils::_disclose; // use messages::protocols::trust_ping::ping::unit_tests::_ping; // use crate::test::source_id; // use crate::utils::devsetup::SetupMocks; // use super::*; // pub mod invitee { // use aries_vcx_wallet::wallet::base_wallet::BaseWallet; // use messages::diddoc::aries::diddoc::test_utils::{_did_doc_inlined_recipient_keys, // _service_endpoint}; use messages::protocols::connection::response::{Response, // SignedResponse}; // use crate::common::signing::sign_connection_response; // use crate::common::test_utils::mock_profile; // use super::*; // fn _send_message() -> SendClosureConnection { // Box::new(|_: A2AMessage, _: String, _: AriesDidDoc| Box::pin(async { Ok(()) })) // } // pub async fn invitee_sm() -> SmConnectionInvitee { // let pairwise_info = // PairwiseInfo::create(&mock_profile().inject_wallet()).await.unwrap(); // SmConnectionInvitee::new(&source_id(), pairwise_info, _did_doc_inlined_recipient_keys()) // } // impl SmConnectionInvitee { // pub fn to_invitee_invited_state(mut self) -> SmConnectionInvitee { // self = self // .handle_invitation(Invitation::Pairwise(_pairwise_invitation())) // .unwrap(); // self // } // pub async fn to_invitee_requested_state(mut self) -> SmConnectionInvitee { // self = self.to_invitee_invited_state(); // let routing_keys: Vec<String> = vec!["verkey123".into()]; // let service_endpoint = String::from("https://example.org/agent"); // self = self // .send_connection_request(routing_keys, service_endpoint, _send_message()) // .await // .unwrap(); // self // } // pub async fn to_invitee_completed_state(mut self) -> SmConnectionInvitee { // let key = "GJ1SzoWzavQYfNL9XkaJdrQejfztN4XqdsiV4ct3LXKL".to_string(); // self = self.to_invitee_requested_state().await; // self = self // .handle_connection_response( // &mock_profile().inject_wallet(), // _response(&mock_profile().inject_wallet(), &key, &_request().id.0).await, // _send_message(), // ) // .await // .unwrap(); // self = self.handle_send_ack(_send_message()).await.unwrap(); // self // } // } // async fn _response(wallet: &Arc<dyn BaseWallet>, key: &str, thread_id: &str) -> // SignedResponse { sign_connection_response( // wallet, // key, // Response::default() // .set_service_endpoint(_service_endpoint()) // .set_keys(vec![key.to_string()], vec![]) // .set_thread_id(thread_id), // ) // .await // .unwrap() // } // async fn _response_1(wallet: &Arc<dyn BaseWallet>, key: &str) -> SignedResponse { // sign_connection_response( // wallet, // key, // Response::default() // .set_service_endpoint(_service_endpoint()) // .set_keys(vec![key.to_string()], vec![]) // .set_thread_id("testid_1"), // ) // .await // .unwrap() // } // mod new { // use super::*; // #[tokio::test] // async fn test_invitee_new() { // let _setup = SetupMocks::init(); // let invitee_sm = invitee_sm().await; // assert_match!(InviteeFullState::Initial(_), invitee_sm.state); // assert_eq!(source_id(), invitee_sm.source_id()); // } // } // mod build_messages { // use super::*; // use crate::utils::devsetup::was_in_past; // use messages::a2a::MessageId; // use messages::concepts::ack::AckStatus; // #[tokio::test] // async fn test_build_connection_request_msg() { // let _setup = SetupMocks::init(); // let mut invitee = invitee_sm().await; // let msg_invitation = _pairwise_invitation(); // invitee = invitee // .handle_invitation(Invitation::Pairwise(msg_invitation.clone())) // .unwrap(); // let routing_keys: Vec<String> = // vec!["ABCD000000QYfNL9XkaJdrQejfztN4XqdsiV4ct30000".to_string()]; let service_endpoint = String::from("https://example.org"); // let (msg, _) = invitee // .build_connection_request_msg(routing_keys.clone(), service_endpoint.clone()) // .unwrap(); // assert_eq!(msg.connection.did_doc.routing_keys(), routing_keys); // assert_eq!( // msg.connection.did_doc.recipient_keys().unwrap(), // vec![invitee.pairwise_info.pw_vk.clone()] // ); // assert_eq!(msg.connection.did_doc.get_endpoint(), service_endpoint.to_string()); // assert_eq!(msg.id, MessageId::default()); // assert!(was_in_past( // &msg.timing.unwrap().out_time.unwrap(), // chrono::Duration::milliseconds(100) // ) // .unwrap()); // } // #[tokio::test] // async fn test_build_connection_ack_msg() { // let _setup = SetupMocks::init(); // let mut invitee = invitee_sm().await; // invitee = invitee.to_invitee_requested_state().await; // let msg_request = &_request(); // let recipient_key = "GJ1SzoWzavQYfNL9XkaJdrQejfztN4XqdsiV4ct3LXKL".to_string(); // invitee = invitee // .handle_connection_response( // &mock_profile().inject_wallet(), // _response(&mock_profile().inject_wallet(), &recipient_key, // &msg_request.id.0).await, _send_message(), // ) // .await // .unwrap(); // let msg = invitee.build_connection_ack_msg().unwrap(); // assert_eq!(msg.id, MessageId::default()); // assert_eq!(msg.thread.thid.unwrap(), msg_request.id.0); // assert_eq!(msg.status, AckStatus::Ok); // assert!(was_in_past( // &msg.timing.unwrap().out_time.unwrap(), // chrono::Duration::milliseconds(100) // ) // .unwrap()); // } // } // mod get_thread_id { // use super::*; // #[tokio::test] // async fn handle_response_fails_with_incorrect_thread_id() { // let _setup = SetupMocks::init(); // let key = "GJ1SzoWzavQYfNL9XkaJdrQejfztN4XqdsiV4ct3LXKL".to_string(); // let mut invitee = invitee_sm().await; // invitee = invitee // .handle_invitation(Invitation::Pairwise(_pairwise_invitation())) // .unwrap(); // let routing_keys: Vec<String> = vec!["verkey123".into()]; // let service_endpoint = String::from("https://example.org/agent"); // invitee = invitee // .send_connection_request(routing_keys, service_endpoint, _send_message()) // .await // .unwrap(); // assert_match!(InviteeState::Requested, invitee.get_state()); // assert!(invitee // .handle_connection_response( // &mock_profile().inject_wallet(), // _response_1(&mock_profile().inject_wallet(), &key).await, // _send_message() // ) // .await // .is_err()); // } // } // mod step { // use crate::utils::devsetup::SetupIndyMocks; // use super::*; // #[tokio::test] // async fn test_did_exchange_init() { // let _setup = SetupIndyMocks::init(); // let did_exchange_sm = invitee_sm().await; // assert_match!(InviteeFullState::Initial(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_invite_message_from_null_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = invitee_sm().await; // did_exchange_sm = did_exchange_sm // .handle_invitation(Invitation::Pairwise(_pairwise_invitation())) // .unwrap(); // assert_match!(InviteeFullState::Invited(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_wont_sent_connection_request_in_null_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = invitee_sm().await; // let routing_keys: Vec<String> = vec!["verkey123".into()]; // let service_endpoint = String::from("https://example.org/agent"); // did_exchange_sm = did_exchange_sm // .send_connection_request(routing_keys, service_endpoint, _send_message()) // .await // .unwrap(); // assert_match!(InviteeFullState::Initial(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_wont_accept_connection_response_in_null_state() { // let _setup = SetupIndyMocks::init(); // let did_exchange_sm = invitee_sm().await; // let key = "GJ1SzoWzavQYfNL9XkaJdrQejfztN4XqdsiV4ct3LXKL"; // assert!(did_exchange_sm // .handle_connection_response( // &mock_profile().inject_wallet(), // _response(&mock_profile().inject_wallet(), key, &_request().id.0).await, // _send_message() // ) // .await // .is_err()); // } // #[tokio::test] // async fn test_did_exchange_handle_connect_message_from_invited_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = invitee_sm().await.to_invitee_invited_state(); // let routing_keys: Vec<String> = vec!["verkey123".into()]; // let service_endpoint = String::from("https://example.org/agent"); // did_exchange_sm = did_exchange_sm // .send_connection_request(routing_keys, service_endpoint, _send_message()) // .await // .unwrap(); // assert_match!(InviteeFullState::Requested(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_problem_report_message_from_invited_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = invitee_sm().await.to_invitee_invited_state(); // did_exchange_sm = // did_exchange_sm.handle_problem_report(_problem_report()).unwrap(); // assert_match!(InviteeFullState::Initial(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_response_message_from_requested_state() { // let _setup = SetupIndyMocks::init(); // let key = "GJ1SzoWzavQYfNL9XkaJdrQejfztN4XqdsiV4ct3LXKL"; // let mut did_exchange_sm = invitee_sm().await.to_invitee_requested_state().await; // did_exchange_sm = did_exchange_sm // .handle_connection_response( // &mock_profile().inject_wallet(), // _response(&mock_profile().inject_wallet(), &key, &_request().id.0).await, // _send_message(), // ) // .await // .unwrap(); // did_exchange_sm = // did_exchange_sm.handle_send_ack(_send_message()).await.unwrap(); // assert_match!(InviteeFullState::Completed(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_other_messages_from_invited_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = invitee_sm().await.to_invitee_invited_state(); // did_exchange_sm = did_exchange_sm.handle_disclose(_disclose()).unwrap(); // assert_match!(InviteeFullState::Invited(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_invalid_response_message_from_requested_state() { // let _setup = SetupIndyMocks::init(); // let mut did_exchange_sm = invitee_sm().await.to_invitee_requested_state().await; // let mut signed_response = _signed_response(); // signed_response.connection_sig.signature = String::from("other"); // did_exchange_sm = did_exchange_sm // .handle_connection_response(&mock_profile().inject_wallet(), signed_response, // _send_message()) .await // .unwrap(); // did_exchange_sm = // did_exchange_sm.handle_send_ack(_send_message()).await.unwrap(); // assert_match!(InviteeFullState::Initial(_), did_exchange_sm.state); // } // #[tokio::test] // async fn test_did_exchange_handle_problem_report_message_from_requested_state() {
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
true
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/protocols/mediated_connection/invitee/states/completed.rs
aries/aries_vcx/src/protocols/mediated_connection/invitee/states/completed.rs
use std::clone::Clone; use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::{ connection::response::Response, discover_features::ProtocolDescriptor, }; use crate::protocols::mediated_connection::invitee::states::{ requested::RequestedState, responded::RespondedState, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CompletedState { pub did_doc: AriesDidDoc, pub bootstrap_did_doc: AriesDidDoc, pub protocols: Option<Vec<ProtocolDescriptor>>, } impl From<(CompletedState, Vec<ProtocolDescriptor>)> for CompletedState { fn from((state, protocols): (CompletedState, Vec<ProtocolDescriptor>)) -> CompletedState { trace!("ConnectionInvitee: transit state from CompleteState to CompleteState"); CompletedState { bootstrap_did_doc: state.bootstrap_did_doc, did_doc: state.did_doc, protocols: Some(protocols), } } } impl From<(RequestedState, AriesDidDoc, Response)> for CompletedState { fn from( (state, did_doc, _response): (RequestedState, AriesDidDoc, Response), ) -> CompletedState { trace!("ConnectionInvitee: transit state from RequestedState to CompleteState"); CompletedState { bootstrap_did_doc: state.did_doc, did_doc, protocols: None, } } } impl From<RespondedState> for CompletedState { fn from(state: RespondedState) -> CompletedState { trace!("ConnectionInvitee: transit state from RespondedState to CompleteState"); CompletedState { bootstrap_did_doc: state.did_doc, did_doc: state.resp_con_data.did_doc, protocols: 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/mediated_connection/invitee/states/invited.rs
aries/aries_vcx/src/protocols/mediated_connection/invitee/states/invited.rs
use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::connection::request::Request; use crate::{ handlers::util::AnyInvitation, protocols::mediated_connection::invitee::states::requested::RequestedState, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct InvitedState { pub invitation: AnyInvitation, pub did_doc: AriesDidDoc, } impl From<(InvitedState, Request, AriesDidDoc)> for RequestedState { fn from((_state, request, did_doc): (InvitedState, Request, AriesDidDoc)) -> RequestedState { trace!("ConnectionInvitee: transit state from InvitedState to RequestedState"); RequestedState { request, did_doc } } }
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/mediated_connection/invitee/states/requested.rs
aries/aries_vcx/src/protocols/mediated_connection/invitee/states/requested.rs
use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::connection::{ problem_report::ProblemReport, request::Request, ConnectionData, }; use crate::protocols::mediated_connection::invitee::states::{ initial::InitialState, responded::RespondedState, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct RequestedState { pub request: Request, pub did_doc: AriesDidDoc, } impl From<(RequestedState, ProblemReport)> for InitialState { fn from((_state, problem_report): (RequestedState, ProblemReport)) -> InitialState { trace!( "ConnectionInvitee: transit state from RequestedState to InitialState, \ problem_report: {problem_report:?}" ); InitialState::new(Some(problem_report), None) } } impl From<(RequestedState, ConnectionData)> for RespondedState { fn from((state, response): (RequestedState, ConnectionData)) -> RespondedState { trace!("ConnectionInvitee: transit state from RequestedState to RespondedState"); RespondedState { resp_con_data: response, did_doc: state.did_doc, request: state.request, } } }
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/mediated_connection/invitee/states/mod.rs
aries/aries_vcx/src/protocols/mediated_connection/invitee/states/mod.rs
pub(super) mod completed; pub(super) mod initial; pub(super) mod invited; pub(super) mod requested; pub(super) mod responded;
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/mediated_connection/invitee/states/responded.rs
aries/aries_vcx/src/protocols/mediated_connection/invitee/states/responded.rs
use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::connection::{ problem_report::ProblemReport, request::Request, ConnectionData, }; use crate::protocols::mediated_connection::invitee::states::initial::InitialState; /// For retro-fitting the new messages. #[derive(Serialize, Deserialize)] struct Response { connection: ConnectionData, } /// For retro-fitting the new messages. #[derive(Serialize, Deserialize)] struct RespondedStateDe { pub resp_con_data: Response, pub request: Request, pub did_doc: AriesDidDoc, } impl From<RespondedStateDe> for RespondedState { fn from(value: RespondedStateDe) -> Self { Self { resp_con_data: value.resp_con_data.connection, request: value.request, did_doc: value.did_doc, } } } impl From<RespondedState> for RespondedStateDe { fn from(value: RespondedState) -> Self { Self { resp_con_data: Response { connection: value.resp_con_data, }, request: value.request, did_doc: value.did_doc, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(from = "RespondedStateDe", into = "RespondedStateDe")] pub struct RespondedState { pub resp_con_data: ConnectionData, pub request: Request, pub did_doc: AriesDidDoc, } impl From<(RespondedState, ProblemReport)> for InitialState { fn from((_state, problem_report): (RespondedState, ProblemReport)) -> InitialState { trace!( "ConnectionInvitee: transit state from RespondedState to InitialState, \ problem_report: {problem_report:?}" ); InitialState::new(Some(problem_report), 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/mediated_connection/invitee/states/initial.rs
aries/aries_vcx/src/protocols/mediated_connection/invitee/states/initial.rs
use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::connection::problem_report::ProblemReport; use crate::{ handlers::util::AnyInvitation, protocols::mediated_connection::invitee::states::invited::InvitedState, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct InitialState { problem_report: Option<ProblemReport>, pub did_doc: Option<AriesDidDoc>, } impl From<(InitialState, AnyInvitation, AriesDidDoc)> for InvitedState { fn from( (_state, invitation, did_doc): (InitialState, AnyInvitation, AriesDidDoc), ) -> InvitedState { trace!("ConnectionInvitee: transit state from InitialState to InvitedState"); InvitedState { invitation, did_doc, } } } impl InitialState { pub fn new(problem_report: Option<ProblemReport>, did_doc: Option<AriesDidDoc>) -> Self { InitialState { problem_report, did_doc, } } }
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/proof_presentation/mod.rs
aries/aries_vcx/src/protocols/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/protocols/proof_presentation/verifier/mod.rs
aries/aries_vcx/src/protocols/proof_presentation/verifier/mod.rs
pub mod state_machine; pub mod states; pub mod verification_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/proof_presentation/verifier/verification_status.rs
aries/aries_vcx/src/protocols/proof_presentation/verifier/verification_status.rs
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub enum PresentationVerificationStatus { Valid, Invalid, Unavailable, } #[cfg(test)] pub mod unit_tests { use super::*; #[test] fn test_presentation_status_ser_deser() { assert_eq!( PresentationVerificationStatus::Valid, serde_json::from_str("\"Valid\"").unwrap() ); assert_eq!( PresentationVerificationStatus::Invalid, serde_json::from_str("\"Invalid\"").unwrap() ); assert_eq!( PresentationVerificationStatus::Unavailable, serde_json::from_str("\"Unavailable\"").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/proof_presentation/verifier/state_machine.rs
aries/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs
use std::fmt::Display; 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 chrono::Utc; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::{ notification::ack::{AckContent, AckDecorators, AckStatus}, present_proof::v1::{ ack::AckPresentationV1, present::PresentationV1, problem_report::PresentProofV1ProblemReport, propose::ProposePresentationV1, request::{ RequestPresentationV1, RequestPresentationV1Content, RequestPresentationV1Decorators, }, }, report_problem::ProblemReport, }, AriesMessage, }; use uuid::Uuid; use crate::{ errors::error::prelude::*, handlers::util::{make_attach_from_str, verify_thread_id, AttachmentId, Status}, protocols::{ common::build_problem_report_msg, proof_presentation::verifier::{ states::{ finished::FinishedState, initial::InitialVerifierState, presentation_proposal_received::PresentationProposalReceivedState, presentation_request_sent::PresentationRequestSentState, presentation_request_set::PresentationRequestSetState, }, verification_status::PresentationVerificationStatus, }, }, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] pub struct VerifierSM { source_id: String, thread_id: String, state: VerifierFullState, } #[derive(Debug, PartialEq, Eq)] pub enum VerifierState { Initial, PresentationProposalReceived, PresentationRequestSet, PresentationRequestSent, Finished, Failed, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum VerifierFullState { Initial(InitialVerifierState), PresentationRequestSet(PresentationRequestSetState), PresentationProposalReceived(PresentationProposalReceivedState), PresentationRequestSent(PresentationRequestSentState), Finished(FinishedState), } impl Display for VerifierFullState { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> { match *self { VerifierFullState::Initial(_) => f.write_str("Initial"), VerifierFullState::PresentationRequestSet(_) => f.write_str("PresentationRequestSet"), VerifierFullState::PresentationProposalReceived(_) => { f.write_str("PresentationProposalReceived") } VerifierFullState::PresentationRequestSent(_) => f.write_str("PresentationRequestSent"), VerifierFullState::Finished(_) => f.write_str("Finished"), } } } impl Default for VerifierFullState { fn default() -> Self { Self::Initial(InitialVerifierState::default()) } } pub fn build_verification_ack(thread_id: &str) -> AckPresentationV1 { let content = AckContent::builder().status(AckStatus::Ok).build(); let decorators = AckDecorators::builder() .thread(Thread::builder().thid(thread_id.to_owned()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); AckPresentationV1::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build() } pub fn build_starting_presentation_request( thread_id: &str, request_data: &PresentationRequest, comment: Option<String>, ) -> VcxResult<RequestPresentationV1> { let id = thread_id.to_owned(); let content = RequestPresentationV1Content::builder().request_presentations_attach(vec![ make_attach_from_str!( &json!(request_data).to_string(), AttachmentId::PresentationRequest.as_ref().to_string() ), ]); let content = if let Some(comment) = comment { content.comment(comment).build() } else { content.build() }; let decorators = RequestPresentationV1Decorators::builder() .timing(Timing::builder().out_time(Utc::now()).build()) .build(); Ok(RequestPresentationV1::builder() .id(id) .content(content) .decorators(decorators) .build()) } impl VerifierSM { pub fn new(source_id: &str) -> Self { Self { thread_id: String::new(), source_id: source_id.to_string(), state: VerifierFullState::Initial(InitialVerifierState {}), } } // todo: eliminate VcxResult (follow set_request err chain and eliminate possibility of err at // the bottom) pub fn from_request( source_id: &str, presentation_request_data: &PresentationRequest, ) -> VcxResult<Self> { let sm = Self { source_id: source_id.to_string(), thread_id: Uuid::new_v4().to_string(), state: VerifierFullState::Initial(InitialVerifierState {}), }; sm.set_presentation_request(presentation_request_data, None) } pub fn from_proposal(source_id: &str, presentation_proposal: &ProposePresentationV1) -> Self { Self { source_id: source_id.to_string(), thread_id: presentation_proposal.id.clone(), state: VerifierFullState::PresentationProposalReceived( PresentationProposalReceivedState::new(presentation_proposal.clone()), ), } } pub fn receive_presentation_proposal(self, proposal: ProposePresentationV1) -> VcxResult<Self> { verify_thread_id(&self.thread_id, &proposal.clone().into())?; let (state, thread_id) = match self.state { VerifierFullState::Initial(_) => { let thread_id = match proposal.decorators.thread { Some(ref thread) => thread.thid.clone(), None => proposal.id.clone(), }; ( VerifierFullState::PresentationProposalReceived( PresentationProposalReceivedState::new(proposal), ), thread_id, ) } VerifierFullState::PresentationRequestSent(_) => ( VerifierFullState::PresentationProposalReceived( PresentationProposalReceivedState::new(proposal), ), self.thread_id.clone(), ), s => { warn!("Unable to receive presentation proposal in state {s}"); (s, self.thread_id.clone()) } }; Ok(Self { state, thread_id, ..self }) } pub fn receive_presentation_request_reject( self, problem_report: ProblemReport, ) -> VcxResult<Self> { verify_thread_id( &self.thread_id, &AriesMessage::ReportProblem(problem_report.clone()), )?; let state = match self.state { VerifierFullState::PresentationRequestSent(state) => { VerifierFullState::Finished((state, problem_report).into()) } s => { warn!("Unable to receive presentation request reject in state {s}"); s } }; Ok(Self { state, ..self }) } pub async fn reject_presentation_proposal( self, problem_report: ProblemReport, ) -> VcxResult<Self> { let (state, thread_id) = match self.state { VerifierFullState::PresentationProposalReceived(state) => { let thread_id = match state.presentation_proposal.decorators.thread { Some(thread) => thread.thid, None => state.presentation_proposal.id, }; ( VerifierFullState::Finished(FinishedState::declined(problem_report)), thread_id, ) } s => { warn!("Unable to reject presentation proposal in state {s}"); (s, self.thread_id.clone()) } }; Ok(Self { state, thread_id, ..self }) } pub async fn verify_presentation<'a>( self, ledger: &'a impl AnoncredsLedgerRead, anoncreds: &'a impl BaseAnonCreds, presentation: PresentationV1, ) -> VcxResult<Self> { verify_thread_id(&self.thread_id, &presentation.clone().into())?; let state = match self.state { VerifierFullState::PresentationRequestSent(state) => { let verification_result = state .verify_presentation(ledger, anoncreds, &presentation, &self.thread_id) .await; match verification_result { Ok(()) => VerifierFullState::Finished( (state, presentation, PresentationVerificationStatus::Valid).into(), ), Err(err) => { let problem_report = build_problem_report_msg(Some(err.to_string()), &self.thread_id); match err.kind() { AriesVcxErrorKind::InvalidProof => VerifierFullState::Finished( (state, presentation, PresentationVerificationStatus::Invalid) .into(), ), _ => VerifierFullState::Finished((state, problem_report).into()), } } } } s => { warn!("Unable to verify presentation in state {s}"); s } }; Ok(Self { state, ..self }) } pub fn get_final_message(&self) -> VcxResult<AriesMessage> { match &self.state { VerifierFullState::Finished(ref state) => match &state.verification_status { PresentationVerificationStatus::Valid => { Ok(build_verification_ack(&self.thread_id).into()) } PresentationVerificationStatus::Invalid | PresentationVerificationStatus::Unavailable => match &state.status { Status::Undefined => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Cannot get final message in this state: finished, status undefined", )), Status::Success => Ok(build_problem_report_msg(None, &self.thread_id).into()), Status::Failed(problem_report) | Status::Declined(problem_report) => { let problem_report = PresentProofV1ProblemReport::builder() .id(problem_report.id.clone()) .content(problem_report.content.clone().into()) .decorators(problem_report.decorators.clone()) .build(); Ok(problem_report) } }, }, s => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!("Cannot get final message in this state: {s:?}"), )), } } pub fn set_presentation_request( self, request_data: &PresentationRequest, comment: Option<String>, ) -> VcxResult<Self> { let Self { source_id, thread_id, state, } = self; let state = match state { VerifierFullState::Initial(_) | VerifierFullState::PresentationRequestSet(_) | VerifierFullState::PresentationProposalReceived(_) => { let presentation_request = build_starting_presentation_request(&thread_id, request_data, comment)?; VerifierFullState::PresentationRequestSet(PresentationRequestSetState::new( presentation_request, )) } _ => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Cannot set presentation request in this state", )); } }; Ok(Self { source_id, state, thread_id, }) } pub fn mark_presentation_request_sent(self) -> VcxResult<Self> { let Self { state, source_id, thread_id, } = self; let state = match state { VerifierFullState::PresentationRequestSet(state) => { VerifierFullState::PresentationRequestSent(state.into()) } VerifierFullState::PresentationRequestSent(state) => { VerifierFullState::PresentationRequestSent(state) } _ => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Can not mark_presentation_request_msg_sent in current state.", )); } }; Ok(Self { source_id, thread_id, state, }) } pub fn source_id(&self) -> String { self.source_id.clone() } pub fn thread_id(&self) -> String { self.thread_id.clone() } pub fn get_state(&self) -> VerifierState { match self.state { VerifierFullState::Initial(_) => VerifierState::Initial, VerifierFullState::PresentationRequestSet(_) => VerifierState::PresentationRequestSet, VerifierFullState::PresentationProposalReceived(_) => { VerifierState::PresentationProposalReceived } VerifierFullState::PresentationRequestSent(_) => VerifierState::PresentationRequestSent, VerifierFullState::Finished(ref status) => match status.status { Status::Success => VerifierState::Finished, _ => VerifierState::Failed, }, } } pub fn progressable_by_message(&self) -> bool { match self.state { VerifierFullState::Initial(_) => true, VerifierFullState::PresentationRequestSet(_) => false, VerifierFullState::PresentationProposalReceived(_) => false, VerifierFullState::PresentationRequestSent(_) => true, VerifierFullState::Finished(_) => false, } } pub fn get_verification_status(&self) -> PresentationVerificationStatus { match self.state { VerifierFullState::Finished(ref state) => state.verification_status.clone(), _ => PresentationVerificationStatus::Unavailable, } } pub fn presentation_request_msg(&self) -> VcxResult<RequestPresentationV1> { match self.state { VerifierFullState::Initial(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Presentation request not set yet", )), VerifierFullState::PresentationRequestSet(ref state) => { Ok(state.presentation_request.clone()) } VerifierFullState::PresentationProposalReceived(ref state) => state .presentation_request .clone() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "No presentation request set", )), VerifierFullState::PresentationRequestSent(ref state) => { Ok(state.presentation_request.clone()) } VerifierFullState::Finished(ref state) => Ok(state .presentation_request .as_ref() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "No presentation request set", ))? .clone()), } } pub fn get_presentation_msg(&self) -> VcxResult<PresentationV1> { match self.state { VerifierFullState::Finished(ref state) => { state.presentation.clone().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "State machine is final state, but presentation is not available".to_string(), )) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Presentation not received yet", )), } } pub fn presentation_proposal(&self) -> VcxResult<ProposePresentationV1> { match self.state { VerifierFullState::PresentationProposalReceived(ref state) => { Ok(state.presentation_proposal.clone()) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Presentation proposal not received yet", )), } } }
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/proof_presentation/verifier/states/presentation_proposal_received.rs
aries/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_proposal_received.rs
use messages::msg_fields::protocols::present_proof::v1::{ propose::{PresentationPreview, ProposePresentationV1, ProposePresentationV1Content}, request::RequestPresentationV1, }; use uuid::Uuid; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationProposalReceivedState { pub presentation_proposal: ProposePresentationV1, pub presentation_request: Option<RequestPresentationV1>, } impl Default for PresentationProposalReceivedState { fn default() -> Self { let id = Uuid::new_v4().to_string(); let preview = PresentationPreview::new(Vec::new(), Vec::new()); let content = ProposePresentationV1Content::builder() .presentation_proposal(preview) .build(); Self { presentation_proposal: ProposePresentationV1::builder() .id(id) .content(content) .build(), presentation_request: None, } } } impl PresentationProposalReceivedState { pub fn new(presentation_proposal: ProposePresentationV1) -> Self { Self { presentation_proposal, ..Self::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/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_sent.rs
aries/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_sent.rs
use aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds; use aries_vcx_ledger::ledger::base_ledger::AnoncredsLedgerRead; use messages::msg_fields::protocols::{ present_proof::v1::{present::PresentationV1, request::RequestPresentationV1}, report_problem::ProblemReport, }; use crate::{ common::proofs::verifier::validate_indy_proof, errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, handlers::util::{get_attach_as_string, matches_thread_id, Status}, protocols::proof_presentation::verifier::{ states::finished::FinishedState, verification_status::PresentationVerificationStatus, }, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationRequestSentState { pub presentation_request: RequestPresentationV1, } impl PresentationRequestSentState { pub async fn verify_presentation( &self, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, presentation: &PresentationV1, thread_id: &str, ) -> VcxResult<()> { if !matches_thread_id!(presentation, thread_id) { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!( "Cannot handle proof presentation: thread id does not match: {:?}", presentation.decorators.thread.thid ), )); }; let proof_json = get_attach_as_string!(&presentation.content.presentations_attach); let proof_req_json = get_attach_as_string!( &self .presentation_request .content .request_presentations_attach ); let valid = validate_indy_proof(ledger, anoncreds, &proof_json, &proof_req_json).await?; if !valid { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidProof, "Presentation verification failed", )); } Ok(()) } } impl From<( PresentationRequestSentState, PresentationV1, PresentationVerificationStatus, )> for FinishedState { fn from( (state, presentation, verification_status): ( PresentationRequestSentState, PresentationV1, PresentationVerificationStatus, ), ) -> Self { trace!("transit state from PresentationRequestSentState to FinishedState"); FinishedState { presentation_request: Some(state.presentation_request), presentation: Some(presentation), status: Status::Success, verification_status, } } } impl From<(PresentationRequestSentState, ProblemReport)> for FinishedState { fn from((state, problem_report): (PresentationRequestSentState, ProblemReport)) -> Self { trace!( "transit state from PresentationRequestSentState to FinishedState; problem_report: \ {problem_report:?}" ); FinishedState { presentation_request: Some(state.presentation_request), presentation: None, status: Status::Failed(problem_report), verification_status: PresentationVerificationStatus::Unavailable, } } }
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/proof_presentation/verifier/states/presentation_request_set.rs
aries/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_set.rs
use messages::msg_fields::protocols::present_proof::v1::request::{ RequestPresentationV1, RequestPresentationV1Content, }; use uuid::Uuid; use crate::protocols::proof_presentation::verifier::states::presentation_request_sent::PresentationRequestSentState; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationRequestSetState { pub presentation_request: RequestPresentationV1, } impl Default for PresentationRequestSetState { fn default() -> Self { let id = Uuid::new_v4().to_string(); let content = RequestPresentationV1Content::builder() .request_presentations_attach(Vec::new()) .build(); Self { presentation_request: RequestPresentationV1::builder() .id(id) .content(content) .build(), } } } impl PresentationRequestSetState { pub fn new(presentation_request: RequestPresentationV1) -> Self { Self { presentation_request, } } } impl From<PresentationRequestSetState> for PresentationRequestSentState { fn from(state: PresentationRequestSetState) -> Self { trace!("transit state from PresentationRequestSetState to PresentationRequestSentState"); PresentationRequestSentState { presentation_request: state.presentation_request, } } }
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/proof_presentation/verifier/states/finished.rs
aries/aries_vcx/src/protocols/proof_presentation/verifier/states/finished.rs
use messages::msg_fields::protocols::{ present_proof::v1::{present::PresentationV1, request::RequestPresentationV1}, report_problem::ProblemReport, }; use serde::Deserialize; use crate::{ handlers::util::Status, protocols::proof_presentation::verifier::verification_status::PresentationVerificationStatus, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct FinishedState { pub presentation_request: Option<RequestPresentationV1>, pub presentation: Option<PresentationV1>, pub status: Status, pub verification_status: PresentationVerificationStatus, } impl FinishedState { pub fn declined(problem_report: ProblemReport) -> Self { trace!("transit state to FinishedState due to a rejection"); FinishedState { presentation_request: None, presentation: None, status: Status::Declined(problem_report), verification_status: PresentationVerificationStatus::Unavailable, } } } #[cfg(test)] pub mod unit_tests { use super::*; #[test] fn test_verifier_state_finished_ser_deser_valid() { let state = FinishedState { presentation_request: None, presentation: None, status: Status::Success, verification_status: PresentationVerificationStatus::Valid, }; let serialized = serde_json::to_string(&state).unwrap(); let expected = r#"{"presentation_request":null,"presentation":null,"status":"Success","verification_status":"Valid"}"#; assert_eq!(serialized, expected); let deserialized: FinishedState = serde_json::from_str(&serialized).unwrap(); assert_eq!(state, deserialized) } #[test] fn test_verifier_state_finished_ser_deser_unavailable() { let state = FinishedState { presentation_request: None, presentation: None, status: Status::Success, verification_status: PresentationVerificationStatus::Unavailable, }; let serialized = serde_json::to_string(&state).unwrap(); let expected = r#"{"presentation_request":null,"presentation":null,"status":"Success","verification_status":"Unavailable"}"#; assert_eq!(serialized, expected); let deserialized: FinishedState = serde_json::from_str(&serialized).unwrap(); assert_eq!(state, deserialized) } #[test] fn test_verifier_state_finished_ser_deser_invalid() { let state = FinishedState { presentation_request: None, presentation: None, status: Status::Success, verification_status: PresentationVerificationStatus::Invalid, }; let serialized = serde_json::to_string(&state).unwrap(); let expected = r#"{"presentation_request":null,"presentation":null,"status":"Success","verification_status":"Invalid"}"#; assert_eq!(serialized, expected); let deserialized: FinishedState = serde_json::from_str(&serialized).unwrap(); assert_eq!(state, deserialized) } }
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/proof_presentation/verifier/states/mod.rs
aries/aries_vcx/src/protocols/proof_presentation/verifier/states/mod.rs
pub(super) mod finished; pub(super) mod initial; pub(super) mod presentation_proposal_received; pub(super) mod presentation_request_sent; pub(super) mod presentation_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/proof_presentation/verifier/states/initial.rs
aries/aries_vcx/src/protocols/proof_presentation/verifier/states/initial.rs
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)] pub struct InitialVerifierState {}
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/proof_presentation/prover/mod.rs
aries/aries_vcx/src/protocols/proof_presentation/prover/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/proof_presentation/prover/state_machine.rs
aries/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs
use std::{collections::HashMap, fmt}; use anoncreds_types::data_types::messages::{ cred_selection::SelectedCredentials, presentation::Presentation, }; 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::{ present_proof::v1::{ ack::AckPresentationV1, present::{PresentationV1, PresentationV1Content, PresentationV1Decorators}, propose::{ PresentationPreview, ProposePresentationV1, ProposePresentationV1Content, ProposePresentationV1Decorators, }, request::RequestPresentationV1, }, report_problem::ProblemReport, }, }; use uuid::Uuid; use crate::{ errors::error::prelude::*, handlers::util::{make_attach_from_str, AttachmentId, PresentationProposalData, Status}, protocols::{ common::build_problem_report_msg, proof_presentation::prover::states::{ finished::FinishedState, initial::InitialProverState, presentation_preparation_failed::PresentationPreparationFailedState, presentation_prepared::PresentationPreparedState, presentation_proposal_sent::PresentationProposalSent, presentation_request_received::PresentationRequestReceived, presentation_sent::PresentationSentState, }, }, }; /// A state machine that tracks the evolution of states for a Prover during /// the Present Proof protocol. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] pub struct ProverSM { source_id: String, thread_id: String, state: ProverFullState, } #[derive(Debug, PartialEq, Eq)] pub enum ProverState { Initial, PresentationProposalSent, PresentationRequestReceived, PresentationPrepared, PresentationPreparationFailed, PresentationSent, Finished, Failed, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum ProverFullState { Initial(InitialProverState), PresentationProposalSent(PresentationProposalSent), PresentationRequestReceived(PresentationRequestReceived), PresentationPrepared(PresentationPreparedState), PresentationPreparationFailed(PresentationPreparationFailedState), PresentationSent(PresentationSentState), Finished(FinishedState), } impl fmt::Display for ProverFullState { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { ProverFullState::Initial(_) => f.write_str("Initial"), ProverFullState::PresentationProposalSent(_) => f.write_str("PresentationProposalSent"), ProverFullState::PresentationRequestReceived(_) => { f.write_str("PresentationRequestReceived") } ProverFullState::PresentationPrepared(_) => f.write_str("PresentationPrepared"), ProverFullState::PresentationPreparationFailed(_) => { f.write_str("PresentationPreparationFailed") } ProverFullState::PresentationSent(_) => f.write_str("PresentationSent"), ProverFullState::Finished(_) => f.write_str("Finished"), } } } fn build_presentation_msg( thread_id: &str, presentation: Presentation, ) -> VcxResult<PresentationV1> { let id = Uuid::new_v4().to_string(); let content = PresentationV1Content::builder() .presentations_attach(vec![make_attach_from_str!( &serde_json::to_string(&presentation)?, AttachmentId::Presentation.as_ref().to_string() )]) .build(); let decorators = PresentationV1Decorators::builder() .thread(Thread::builder().thid(thread_id.to_owned()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); Ok(PresentationV1::builder() .id(id) .content(content) .decorators(decorators) .build()) } impl Default for ProverFullState { fn default() -> Self { Self::PresentationRequestReceived(PresentationRequestReceived::default()) } } impl ProverSM { pub fn new(source_id: String) -> ProverSM { ProverSM { source_id, thread_id: Uuid::new_v4().to_string(), state: ProverFullState::Initial(InitialProverState {}), } } pub fn from_request( presentation_request: RequestPresentationV1, source_id: String, ) -> ProverSM { ProverSM { source_id, thread_id: presentation_request.id.clone(), state: ProverFullState::PresentationRequestReceived(PresentationRequestReceived { presentation_request, }), } } pub async fn build_presentation_proposal( self, proposal_data: PresentationProposalData, ) -> VcxResult<Self> { let state = match self.state { ProverFullState::Initial(_) => { let id = self.thread_id.clone(); let preview = PresentationPreview::new(proposal_data.attributes, proposal_data.predicates); let content = ProposePresentationV1Content::builder().presentation_proposal(preview); let content = if let Some(comment) = proposal_data.comment { content.comment(comment).build() } else { content.build() }; let proposal = ProposePresentationV1::builder() .id(id) .content(content) .build(); ProverFullState::PresentationProposalSent(PresentationProposalSent::new(proposal)) } ProverFullState::PresentationRequestReceived(_) => { let id = Uuid::new_v4().to_string(); let preview = PresentationPreview::new(proposal_data.attributes, proposal_data.predicates); let content = ProposePresentationV1Content::builder().presentation_proposal(preview); let content = if let Some(comment) = proposal_data.comment { content.comment(comment).build() } else { content.build() }; let decorators = ProposePresentationV1Decorators::builder() .thread(Thread::builder().thid(self.thread_id.clone()).build()) .build(); let proposal = ProposePresentationV1::builder() .id(id) .content(content) .decorators(decorators) .build(); ProverFullState::PresentationProposalSent(PresentationProposalSent::new(proposal)) } s => { warn!("Unable to set presentation proposal in state {s}"); s } }; Ok(Self { state, ..self }) } pub async fn decline_presentation_request( self, problem_report: ProblemReport, ) -> VcxResult<Self> { let state = match self.state { ProverFullState::PresentationRequestReceived(state) => { ProverFullState::Finished((state, problem_report).into()) } ProverFullState::PresentationPrepared(_) => { ProverFullState::Finished(FinishedState::declined(problem_report)) } s => { warn!("Unable to decline presentation request in state {s}"); s } }; Ok(Self { state, ..self }) } pub async fn negotiate_presentation(self) -> VcxResult<Self> { let state = match self.state { ProverFullState::PresentationRequestReceived(state) => { ProverFullState::Finished(state.into()) } ProverFullState::PresentationPrepared(state) => ProverFullState::Finished(state.into()), s => { warn!("Unable to send handle presentation proposal in state {s}"); s } }; Ok(Self { state, ..self }) } pub async fn generate_presentation( self, wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, credentials: SelectedCredentials, self_attested_attrs: HashMap<String, String>, ) -> VcxResult<Self> { let state = match self.state { ProverFullState::PresentationRequestReceived(state) => { match state .build_presentation( wallet, ledger, anoncreds, &credentials, self_attested_attrs, ) .await { Ok(presentation) => { let presentation = build_presentation_msg(&self.thread_id, presentation)?; ProverFullState::PresentationPrepared((state, presentation).into()) } Err(err) => { let problem_report = build_problem_report_msg(Some(err.to_string()), &self.thread_id); error!( "Failed bo build presentation, sending problem report: {problem_report:?}" ); ProverFullState::PresentationPreparationFailed( (state, problem_report).into(), ) } } } s => { warn!("Unable to send generate presentation in state {s}"); s } }; Ok(Self { state, ..self }) } pub fn mark_presentation_sent(self) -> VcxResult<Self> { let state = match self.state { ProverFullState::PresentationPrepared(state) => { ProverFullState::PresentationSent((state).into()) } ProverFullState::PresentationPreparationFailed(state) => { ProverFullState::Finished((state).into()) } s => { warn!("Unable to send send presentation in state {s}"); s } }; Ok(Self { state, ..self }) } pub fn get_problem_report(&self) -> VcxResult<ProblemReport> { match &self.state { ProverFullState::Finished(state) => match &state.status { Status::Failed(problem_report) | Status::Declined(problem_report) => { Ok(problem_report.clone()) } _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot get problem report", )), }, _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot get problem report", )), } } pub fn receive_presentation_request( self, request: RequestPresentationV1, ) -> VcxResult<ProverSM> { let prover_sm = match &self.state { ProverFullState::PresentationProposalSent(_) => { let state = ProverFullState::PresentationRequestReceived( PresentationRequestReceived::new(request), ); ProverSM { state, ..self } } _ => { warn!("Not supported in this state"); self } }; Ok(prover_sm) } pub fn receive_presentation_reject(self, problem_report: ProblemReport) -> VcxResult<ProverSM> { let prover_sm = match &self.state { ProverFullState::PresentationProposalSent(_) => { let state = ProverFullState::Finished(FinishedState::declined(problem_report)); ProverSM { state, ..self } } ProverFullState::PresentationSent(state) => { let state = ProverFullState::Finished((state.clone(), problem_report).into()); ProverSM { state, ..self } } _ => { warn!("Not supported in this state"); self } }; Ok(prover_sm) } pub fn receive_presentation_ack(self, ack: AckPresentationV1) -> VcxResult<Self> { let state = match self.state { ProverFullState::PresentationSent(state) => { ProverFullState::Finished((state, ack).into()) } s => { warn!("Unable to process presentation ack in state {s}"); s } }; Ok(Self { state, ..self }) } pub fn source_id(&self) -> String { self.source_id.clone() } pub fn get_thread_id(&self) -> VcxResult<String> { Ok(self.thread_id.clone()) } pub fn get_state(&self) -> ProverState { match self.state { ProverFullState::Initial(_) => ProverState::Initial, ProverFullState::PresentationProposalSent(_) => ProverState::PresentationProposalSent, ProverFullState::PresentationRequestReceived(_) => { ProverState::PresentationRequestReceived } ProverFullState::PresentationPrepared(_) => ProverState::PresentationPrepared, ProverFullState::PresentationPreparationFailed(_) => { ProverState::PresentationPreparationFailed } ProverFullState::PresentationSent(_) => ProverState::PresentationSent, ProverFullState::Finished(ref status) => match status.status { Status::Success => ProverState::Finished, _ => ProverState::Failed, }, } } pub fn progressable_by_message(&self) -> bool { trace!( "Prover::states::progressable_by_message >> state: {:?}", self.state ); match self.state { ProverFullState::Initial(_) => false, ProverFullState::PresentationProposalSent(_) => true, ProverFullState::PresentationRequestReceived(_) => false, ProverFullState::PresentationPrepared(_) => true, ProverFullState::PresentationPreparationFailed(_) => true, ProverFullState::PresentationSent(_) => true, ProverFullState::Finished(_) => false, } } pub fn get_presentation_status(&self) -> u32 { match self.state { ProverFullState::Finished(ref state) => state.status.code(), _ => Status::Undefined.code(), } } pub fn get_presentation_request(&self) -> VcxResult<&RequestPresentationV1> { match self.state { ProverFullState::Initial(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Presentation request is not available", )), ProverFullState::PresentationProposalSent(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Presentation request is not available", )), ProverFullState::PresentationRequestReceived(ref state) => { Ok(&state.presentation_request) } ProverFullState::PresentationPrepared(ref state) => Ok(&state.presentation_request), ProverFullState::PresentationPreparationFailed(ref state) => { Ok(&state.presentation_request) } ProverFullState::PresentationSent(ref state) => Ok(&state.presentation_request), ProverFullState::Finished(ref state) => { Ok(state .presentation_request .as_ref() .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Presentation request is not available", ))?) } } } pub fn get_presentation_msg(&self) -> VcxResult<&PresentationV1> { match self.state { ProverFullState::Initial(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Presentation is not created yet", )), ProverFullState::PresentationProposalSent(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Presentation is not created yet", )), ProverFullState::PresentationRequestReceived(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Presentation is not created yet", )), ProverFullState::PresentationPrepared(ref state) => Ok(&state.presentation), ProverFullState::PresentationPreparationFailed(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Presentation is not created yet", )), ProverFullState::PresentationSent(ref state) => Ok(&state.presentation), ProverFullState::Finished(ref state) => { Ok(state.presentation.as_ref().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Presentation is not available in Finished state", ))?) } } } pub fn get_presentation_proposal(&self) -> VcxResult<ProposePresentationV1> { match &self.state { ProverFullState::PresentationProposalSent(state) => Ok(state.proposal.clone()), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Cannot get proposal", )), } } }
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/proof_presentation/prover/states/presentation_request_received.rs
aries/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs
use std::collections::HashMap; use anoncreds_types::data_types::messages::{ cred_selection::SelectedCredentials, presentation::Presentation, }; 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::msg_fields::protocols::{ present_proof::v1::{ present::PresentationV1, request::{RequestPresentationV1, RequestPresentationV1Content}, }, report_problem::ProblemReport, }; use uuid::Uuid; use crate::{ common::proofs::prover::generate_indy_proof, errors::error::prelude::*, handlers::util::{get_attach_as_string, Status}, protocols::proof_presentation::prover::states::{ finished::FinishedState, presentation_preparation_failed::PresentationPreparationFailedState, presentation_prepared::PresentationPreparedState, }, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationRequestReceived { pub presentation_request: RequestPresentationV1, } impl Default for PresentationRequestReceived { fn default() -> Self { let id = Uuid::new_v4().to_string(); let content = RequestPresentationV1Content::builder() .request_presentations_attach(Vec::new()) .build(); Self { presentation_request: RequestPresentationV1::builder() .id(id) .content(content) .build(), } } } impl PresentationRequestReceived { pub fn new(presentation_request: RequestPresentationV1) -> Self { Self { presentation_request, } } pub async fn build_presentation( &self, wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, credentials: &SelectedCredentials, self_attested_attrs: HashMap<String, String>, ) -> VcxResult<Presentation> { let proof_req_data_json = serde_json::from_str(&get_attach_as_string!( &self .presentation_request .content .request_presentations_attach ))?; generate_indy_proof( wallet, ledger, anoncreds, credentials, self_attested_attrs, proof_req_data_json, ) .await } } impl From<(PresentationRequestReceived, ProblemReport)> for PresentationPreparationFailedState { fn from((state, problem_report): (PresentationRequestReceived, ProblemReport)) -> Self { trace!( "transit state from PresentationRequestReceived to PresentationPreparationFailedState" ); PresentationPreparationFailedState { presentation_request: state.presentation_request, problem_report, } } } impl From<(PresentationRequestReceived, PresentationV1)> for PresentationPreparedState { fn from((state, presentation): (PresentationRequestReceived, PresentationV1)) -> Self { trace!("transit state from PresentationRequestReceived to PresentationPreparedState"); PresentationPreparedState { presentation_request: state.presentation_request, presentation, } } } impl From<PresentationRequestReceived> for FinishedState { fn from(state: PresentationRequestReceived) -> Self { trace!("Prover: transit state from PresentationRequestReceived to FinishedState"); FinishedState { presentation_request: Some(state.presentation_request), presentation: None, status: Status::Success, } } } impl From<(PresentationRequestReceived, ProblemReport)> for FinishedState { fn from((state, problem_report): (PresentationRequestReceived, ProblemReport)) -> Self { trace!("Prover: transit state from PresentationRequestReceived to FinishedState"); FinishedState { presentation_request: Some(state.presentation_request), presentation: None, status: Status::Declined(problem_report), } } }
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/proof_presentation/prover/states/presentation_prepared.rs
aries/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_prepared.rs
use messages::msg_fields::protocols::present_proof::v1::{ present::PresentationV1, request::RequestPresentationV1, }; use crate::{ handlers::util::Status, protocols::proof_presentation::prover::states::{ finished::FinishedState, presentation_sent::PresentationSentState, }, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationPreparedState { pub presentation_request: RequestPresentationV1, pub presentation: PresentationV1, } impl From<PresentationPreparedState> for PresentationSentState { fn from(state: PresentationPreparedState) -> Self { trace!("transit state from PresentationPreparedState to PresentationSentState"); PresentationSentState { presentation_request: state.presentation_request, presentation: state.presentation, } } } impl From<PresentationPreparedState> for FinishedState { fn from(state: PresentationPreparedState) -> Self { trace!("transit state from PresentationPreparedState to FinishedState"); FinishedState { presentation_request: Some(state.presentation_request), presentation: Default::default(), status: Status::Undefined, } } }
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/proof_presentation/prover/states/finished.rs
aries/aries_vcx/src/protocols/proof_presentation/prover/states/finished.rs
use messages::msg_fields::protocols::{ present_proof::v1::{present::PresentationV1, request::RequestPresentationV1}, report_problem::ProblemReport, }; use crate::handlers::util::Status; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct FinishedState { pub presentation_request: Option<RequestPresentationV1>, pub presentation: Option<PresentationV1>, pub status: Status, } impl FinishedState { pub fn declined(problem_report: ProblemReport) -> Self { trace!("transit state to FinishedState due to a rejection"); FinishedState { presentation_request: None, presentation: None, status: Status::Declined(problem_report), } } }
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/proof_presentation/prover/states/presentation_proposal_sent.rs
aries/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_proposal_sent.rs
use messages::msg_fields::protocols::present_proof::v1::propose::{ PresentationPreview, ProposePresentationV1, ProposePresentationV1Content, }; use uuid::Uuid; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct PresentationProposalSent { pub proposal: ProposePresentationV1, } impl Default for PresentationProposalSent { fn default() -> Self { let id = Uuid::new_v4().to_string(); let preview = PresentationPreview::new(Vec::new(), Vec::new()); let content = ProposePresentationV1Content::builder() .presentation_proposal(preview) .build(); Self { proposal: ProposePresentationV1::builder() .id(id) .content(content) .build(), } } } impl PresentationProposalSent { pub fn new(proposal: ProposePresentationV1) -> Self { Self { proposal } } }
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/proof_presentation/prover/states/mod.rs
aries/aries_vcx/src/protocols/proof_presentation/prover/states/mod.rs
pub(super) mod finished; pub(super) mod initial; pub(super) mod presentation_preparation_failed; pub(super) mod presentation_prepared; pub(super) mod presentation_proposal_sent; pub(super) mod presentation_request_received; pub(super) mod presentation_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/proof_presentation/prover/states/presentation_sent.rs
aries/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_sent.rs
use messages::msg_fields::protocols::{ present_proof::v1::{ ack::AckPresentationV1, present::PresentationV1, request::RequestPresentationV1, }, report_problem::ProblemReport, }; use crate::{ handlers::util::Status, protocols::proof_presentation::prover::states::finished::FinishedState, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationSentState { pub presentation_request: RequestPresentationV1, pub presentation: PresentationV1, } impl From<(PresentationSentState, AckPresentationV1)> for FinishedState { fn from((state, _ack): (PresentationSentState, AckPresentationV1)) -> Self { trace!("transit state from PresentationSentState to FinishedState"); FinishedState { presentation_request: Some(state.presentation_request), presentation: Some(state.presentation), status: Status::Success, } } } impl From<(PresentationSentState, ProblemReport)> for FinishedState { fn from((state, problem_report): (PresentationSentState, ProblemReport)) -> Self { trace!("transit state from PresentationSentState to FinishedState"); FinishedState { presentation_request: Some(state.presentation_request), presentation: Some(state.presentation), status: Status::Failed(problem_report), } } }
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/proof_presentation/prover/states/initial.rs
aries/aries_vcx/src/protocols/proof_presentation/prover/states/initial.rs
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct InitialProverState {}
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/proof_presentation/prover/states/presentation_preparation_failed.rs
aries/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_preparation_failed.rs
use messages::msg_fields::protocols::{ present_proof::v1::request::RequestPresentationV1, report_problem::ProblemReport, }; use crate::{ handlers::util::Status, protocols::proof_presentation::prover::states::finished::FinishedState, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationPreparationFailedState { pub presentation_request: RequestPresentationV1, pub problem_report: ProblemReport, } impl From<PresentationPreparationFailedState> for FinishedState { fn from(state: PresentationPreparationFailedState) -> Self { trace!("transit state from PresentationPreparationFailedState to FinishedState"); FinishedState { presentation_request: Some(state.presentation_request), presentation: None, status: Status::Failed(state.problem_report), } } }
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/pairwise_info.rs
aries/aries_vcx/src/protocols/connection/pairwise_info.rs
use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use crate::errors::error::VcxResult; #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct PairwiseInfo { pub pw_did: String, pub pw_vk: String, } impl PairwiseInfo { pub async fn create(wallet: &impl BaseWallet) -> VcxResult<PairwiseInfo> { let did_data = wallet.create_and_store_my_did(None, None).await?; Ok(PairwiseInfo { pw_did: did_data.did().into(), pw_vk: did_data.verkey().base58(), }) } }
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/initiation_type.rs
aries/aries_vcx/src/protocols/connection/initiation_type.rs
/// Unit struct illustrating that the connection was initiated by an inviter. #[derive(Clone, Copy, Debug)] pub struct Inviter; /// Unit struct illustrating that the connection was initiated by an invitee. #[derive(Clone, Copy, Debug)] pub struct Invitee;
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/serializable.rs
aries/aries_vcx/src/protocols/connection/serializable.rs
use serde::Serialize; use crate::protocols::connection::{ initiation_type::{Invitee, Inviter}, invitee::states::{ completed::Completed as InviteeCompleted, initial::Initial as InviteeInitial, invited::Invited as InviteeInvited, requested::Requested as InviteeRequested, }, inviter::states::{ completed::Completed as InviterCompleted, initial::Initial as InviterInitial, invited::Invited as InviterInvited, requested::Requested as InviterRequested, }, pairwise_info::PairwiseInfo, Connection, }; /// Macro used for boilerplace implementation of the /// [`From`] trait from a concrete connection state to the equivalent reference state /// used for serialization. macro_rules! from_concrete_to_serializable { ($from:ident, $var:ident, $to:ident) => { impl<'a> From<&'a $from> for $to<'a> { fn from(value: &'a $from) -> Self { Self::$var(value) } } }; ($init_type:ident, $state:ident, $var:ident, $to:ident) => { impl<'a, S> From<(&'a $init_type, &'a S)> for $to<'a> where $state<'a>: From<&'a S>, S: 'a, { fn from(value: (&'a $init_type, &'a S)) -> Self { let (_, state) = value; let serde_state = From::from(state); Self::$var(serde_state) } } }; } /// Type used for serialization of a [`Connection`]. /// This struct is used transparently, under the hood, to convert a reference /// of a [`Connection`] (so we don't clone unnecessarily) to itself and then serialize it. #[derive(Debug, Serialize)] pub struct SerializableConnection<'a> { pub(super) source_id: &'a str, pub(super) pairwise_info: &'a PairwiseInfo, pub(super) state: RefState<'a>, } #[derive(Debug, Serialize)] pub enum RefState<'a> { Inviter(RefInviterState<'a>), Invitee(RefInviteeState<'a>), } #[derive(Debug, Serialize)] pub enum RefInviterState<'a> { Initial(&'a InviterInitial), Invited(&'a InviterInvited), Requested(&'a InviterRequested), Completed(&'a InviterCompleted), } #[derive(Debug, Serialize)] pub enum RefInviteeState<'a> { Initial(&'a InviteeInitial), Invited(&'a InviteeInvited), Requested(&'a InviteeRequested), Completed(&'a InviteeCompleted), } impl<'a, I, S> From<&'a Connection<I, S>> for SerializableConnection<'a> where RefState<'a>: From<(&'a I, &'a S)>, I: 'a, S: 'a, { fn from(value: &'a Connection<I, S>) -> Self { let state = From::from((&value.initiation_type, &value.state)); Self::new(&value.source_id, &value.pairwise_info, state) } } from_concrete_to_serializable!(Inviter, RefInviterState, Inviter, RefState); from_concrete_to_serializable!(Invitee, RefInviteeState, Invitee, RefState); from_concrete_to_serializable!(InviterInitial, Initial, RefInviterState); from_concrete_to_serializable!(InviterInvited, Invited, RefInviterState); from_concrete_to_serializable!(InviterRequested, Requested, RefInviterState); from_concrete_to_serializable!(InviterCompleted, Completed, RefInviterState); from_concrete_to_serializable!(InviteeInitial, Initial, RefInviteeState); from_concrete_to_serializable!(InviteeInvited, Invited, RefInviteeState); from_concrete_to_serializable!(InviteeRequested, Requested, RefInviteeState); from_concrete_to_serializable!(InviteeCompleted, Completed, RefInviteeState); impl<'a> SerializableConnection<'a> { fn new(source_id: &'a str, pairwise_info: &'a PairwiseInfo, state: RefState<'a>) -> Self { Self { source_id, pairwise_info, state, } } } /// Manual implementation of [`Serialize`] for [`Connection`], /// as we'll first convert into [`SerializableConnection`] for a [`Connection`] reference /// and serialize that. impl<I, S> Serialize for Connection<I, S> where for<'a> SerializableConnection<'a>: From<&'a Connection<I, S>>, { fn serialize<Serializer>( &self, serializer: Serializer, ) -> Result<Serializer::Ok, Serializer::Error> where Serializer: ::serde::Serializer, { SerializableConnection::from(self).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/aries_vcx/src/protocols/connection/mod.rs
aries/aries_vcx/src/protocols/connection/mod.rs
mod generic; pub mod initiation_type; pub mod invitee; pub mod inviter; pub mod pairwise_info; mod serializable; mod trait_bounds; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::{ msg_fields::protocols::discover_features::{ disclose::Disclose, query::QueryContent, ProtocolDescriptor, }, AriesMessage, }; pub use self::generic::{GenericConnection, State, ThinState}; use self::{ generic::GenericState, pairwise_info::PairwiseInfo, trait_bounds::{CompletedState, TheirDidDoc, ThreadId}, }; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, transport::Transport, utils::encryption_envelope::EncryptionEnvelope, }; /// A state machine for progressing through the [connection protocol](https://github.com/decentralized-identity/aries-rfcs/blob/main/features/0160-connection-protocol/README.md). #[derive(Clone, Deserialize)] #[serde(try_from = "GenericConnection")] #[serde(bound = "(I, S): TryFrom<GenericState, Error = AriesVcxError>")] pub struct Connection<I, S> { source_id: String, pairwise_info: PairwiseInfo, initiation_type: I, state: S, } impl<I, S> Connection<I, S> { pub fn from_parts( source_id: String, pairwise_info: PairwiseInfo, initiation_type: I, state: S, ) -> Self { Self { source_id, pairwise_info, initiation_type, state, } } pub fn into_parts(self) -> (String, PairwiseInfo, I, S) { let Self { source_id, pairwise_info, initiation_type, state, } = self; (source_id, pairwise_info, initiation_type, state) } pub fn pairwise_info(&self) -> &PairwiseInfo { &self.pairwise_info } pub fn source_id(&self) -> &str { &self.source_id } pub fn protocols(&self) -> Vec<ProtocolDescriptor> { let query = QueryContent::builder().query("*".to_owned()).build(); query.lookup() } } impl<I, S> Connection<I, S> where S: ThreadId, { pub fn thread_id(&self) -> &str { self.state.thread_id() } } impl<I, S> Connection<I, S> where S: TheirDidDoc, { pub fn their_did_doc(&self) -> &AriesDidDoc { self.state.their_did_doc() } pub async fn encrypt_message( &self, wallet: &impl BaseWallet, message: &AriesMessage, ) -> VcxResult<EncryptionEnvelope> { let sender_verkey = &self.pairwise_info().pw_vk; EncryptionEnvelope::create_from_legacy( wallet, json!(message).to_string().as_bytes(), Some(sender_verkey), self.their_did_doc(), ) .await } pub fn remote_did(&self) -> &str { &self.their_did_doc().id } pub fn remote_vk(&self) -> VcxResult<String> { self.their_did_doc() .recipient_keys()? .first() .map(ToOwned::to_owned) .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Can't resolve recipient key from the counterparty diddoc.", )) } pub async fn send_message<T>( &self, wallet: &impl BaseWallet, message: &AriesMessage, transport: &T, ) -> VcxResult<()> where T: Transport, { let msg = self.encrypt_message(wallet, message).await?.0; let service_endpoint = self.their_did_doc().get_endpoint().ok_or_else(|| { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidUrl, "No URL in DID Doc") })?; transport.send_message(msg, &service_endpoint).await } } impl<I, S> Connection<I, S> where S: CompletedState, { pub fn remote_protocols(&self) -> Option<&[ProtocolDescriptor]> { self.state.remote_protocols() } pub fn handle_disclose(&mut self, disclose: Disclose) { self.state.handle_disclose(disclose) } }
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/trait_bounds.rs
aries/aries_vcx/src/protocols/connection/trait_bounds.rs
use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::discover_features::{disclose::Disclose, ProtocolDescriptor}; /// Trait implemented for [`super::Connection`] states that store an [`AriesDidDoc`]. pub trait TheirDidDoc { /// Returns the [`AriesDidDoc`] currently being used by a [`super::Connection`]. fn their_did_doc(&self) -> &AriesDidDoc; } pub trait BootstrapDidDoc: TheirDidDoc { /// Returns the [`AriesDidDoc`] used to bootstrap the connection. /// By default, this will be the same as the [`AriesDidDoc`] currently being used /// by the connection. fn bootstrap_did_doc(&self) -> &AriesDidDoc { self.their_did_doc() } } /// Trait implemented for [`super::Connection`] states that keep track of a thread ID. pub trait ThreadId { fn thread_id(&self) -> &str; } /// Trait impletement for [`super::Connection`] in completed states. pub trait CompletedState { fn remote_protocols(&self) -> Option<&[ProtocolDescriptor]>; fn handle_disclose(&mut self, disclose: Disclose); } /// Marker trait used for implementing /// [`messages::protocols::connection::problem_report::ProblemReport`] handling on certain /// [`super::Connection`] types. #[allow(dead_code)] pub trait HandleProblem {}
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/inviter/mod.rs
aries/aries_vcx/src/protocols/connection/inviter/mod.rs
pub mod states; use ::uuid::Uuid; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use chrono::Utc; use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::connection::{ invitation::{Invitation, InvitationContent}, request::Request, response::{Response, ResponseContent, ResponseDecorators}, ConnectionData, }, AriesMessage, }; use url::Url; use self::states::{ completed::Completed, initial::Initial, invited::Invited, requested::Requested, }; use super::{initiation_type::Inviter, pairwise_info::PairwiseInfo, Connection}; use crate::{ common::signing::sign_connection_response, errors::error::VcxResult, handlers::util::{verify_thread_id, AnyInvitation}, }; pub type InviterConnection<S> = Connection<Inviter, S>; impl InviterConnection<Initial> { /// Creates a new [`InviterConnection<Initial>`]. /// /// The connection can transition to [`InviterConnection<Invited>`] by /// either `create_invitation` or `into_invited`. pub fn new_inviter(source_id: String, pairwise_info: PairwiseInfo) -> Self { Self { source_id, state: Initial, pairwise_info, initiation_type: Inviter, } } /// Generates a pairwise [`Invitation`] and transitions to [`InviterConnection<Invited>`]. pub fn create_invitation( self, routing_keys: Vec<String>, service_endpoint: Url, ) -> InviterConnection<Invited> { let id = Uuid::new_v4().to_string(); let content = InvitationContent::builder_pairwise() .label(self.source_id.clone()) .recipient_keys(vec![self.pairwise_info.pw_vk.clone()]) .routing_keys(routing_keys) .service_endpoint(service_endpoint) .build(); let invite = Invitation::builder().id(id).content(content).build(); let invitation = AnyInvitation::Con(invite); Connection { source_id: self.source_id, pairwise_info: self.pairwise_info, initiation_type: self.initiation_type, state: Invited::new(invitation), } } /// This is implemented for retro-fitting the previous implementation /// where a [`Request`] could get processed directly from the initial state. /// /// If you want to generate a new inviter and not create an invitation through /// [`InviterConnection<Initial>::create_invitation`] then you can call this /// to transition to the [`InviterConnection<Invited>`] directly by passing the /// expected thread_id (external's [`Invitation`] id). /// /// However, the advised method of handling connection requests is to clone /// the [`InviterConnection<Invited>`] and continue the protocol for every /// [`Request`] received for the generated invitation, assuming more than one /// invitees are expected. // // This is a workaround and it's not necessarily pretty, but is implemented // for backwards compatibility. pub fn into_invited(self, thread_id: &str) -> InviterConnection<Invited> { let id = thread_id.to_owned(); let content = InvitationContent::builder_pairwise() .label(self.source_id.clone()) .recipient_keys(vec![self.pairwise_info.pw_vk.clone()]) .service_endpoint( "https://dummy.dummy/dummy" .parse() .expect("url should be valid"), ) .build(); let invite = Invitation::builder().id(id).content(content).build(); let invitation = AnyInvitation::Con(invite); Connection { source_id: self.source_id, pairwise_info: self.pairwise_info, initiation_type: self.initiation_type, state: Invited::new(invitation), } } } impl InviterConnection<Invited> { // This should ideally belong in the Connection<Inviter, RequestedState> // but was placed here to retro-fit the previous API. async fn build_response_content( &self, wallet: &impl BaseWallet, thread_id: String, new_pairwise_info: &PairwiseInfo, new_service_endpoint: Url, new_routing_keys: Vec<String>, ) -> VcxResult<Response> { let new_recipient_keys = vec![new_pairwise_info.pw_vk.clone()]; let mut did_doc = AriesDidDoc::default(); let did = new_pairwise_info.pw_did.clone(); did_doc.set_id(new_pairwise_info.pw_did.clone()); did_doc.set_service_endpoint(new_service_endpoint); did_doc.set_routing_keys(new_routing_keys); did_doc.set_recipient_keys(new_recipient_keys); let con_data = ConnectionData::new(did, did_doc); let id = Uuid::new_v4().to_string(); let con_sig = sign_connection_response(wallet, &self.pairwise_info.pw_vk, &con_data).await?; let content = ResponseContent::builder().connection_sig(con_sig).build(); let decorators = ResponseDecorators::builder() .thread(Thread::builder().thid(thread_id).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); Ok(Response::builder() .id(id) .content(content) .decorators(decorators) .build()) } /// Processes a [`Request`] and transitions to [`InviterConnection<Requested>`]. /// /// # Errors /// /// Will return an error if either: /// * the [`Request`]'s thread ID does not match with the expected thread ID from an /// invitation /// * the [`Request`]'s DidDoc is not valid /// * generating new [`PairwiseInfo`] fails pub async fn handle_request( self, wallet: &impl BaseWallet, request: Request, new_service_endpoint: Url, new_routing_keys: Vec<String>, ) -> VcxResult<InviterConnection<Requested>> { trace!( "Connection::process_request >>> request: {request:?}, service_endpoint: {new_service_endpoint}, routing_keys: \ {new_routing_keys:?}", ); // There must be some other way to validate the thread ID other than cloning the entire // Request verify_thread_id(self.thread_id(), &request.clone().into())?; request.content.connection.did_doc.validate()?; // Generate new pairwise info that will be used from this point on // and incorporate that into the response. let new_pairwise_info = PairwiseInfo::create(wallet).await?; let thread_id = request .decorators .thread .map(|t| t.thid) .unwrap_or(request.id); let did_doc = request.content.connection.did_doc; let content = self .build_response_content( wallet, thread_id, &new_pairwise_info, new_service_endpoint, new_routing_keys, ) .await?; let state = Requested::new(content, did_doc); Ok(Connection { source_id: self.source_id, pairwise_info: new_pairwise_info, initiation_type: self.initiation_type, state, }) } /// Returns the [`Invitation`] generated by this inviter. /// /// NOTE: Calling [`InviterConnection<Initial>::into_invited()`] /// creates a dummy invitation behind the scenes. /// /// So this method will return garbage in that case. /// `into_invited` is implemented for backwards compatibility /// and should be avoided when possible. pub fn get_invitation(&self) -> &AnyInvitation { &self.state.invitation } } impl InviterConnection<Requested> { /// Returns pre-built [`Response`] message which shall be delivered to counterparty /// /// # Errors /// /// Will return an error if sending the response fails. pub fn get_connection_response_msg(&self) -> Response { self.state.signed_response.clone() } /// Acknowledges an invitee's connection by processing their first message /// and transitions to [`InviterConnection<Completed>`]. pub fn acknowledge_connection( self, _msg: &AriesMessage, ) -> VcxResult<InviterConnection<Completed>> { let state = Completed::new( self.state.did_doc, self.state.signed_response.decorators.thread.thid, None, ); Ok(Connection { source_id: self.source_id, pairwise_info: self.pairwise_info, initiation_type: self.initiation_type, 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/connection/inviter/states/completed.rs
aries/aries_vcx/src/protocols/connection/inviter/states/completed.rs
use std::clone::Clone; use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::discover_features::{disclose::Disclose, ProtocolDescriptor}; use crate::protocols::connection::trait_bounds::{CompletedState, TheirDidDoc, ThreadId}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Completed { pub(crate) did_doc: AriesDidDoc, pub(crate) thread_id: String, pub(crate) protocols: Option<Vec<ProtocolDescriptor>>, } impl Completed { pub fn new( did_doc: AriesDidDoc, thread_id: String, protocols: Option<Vec<ProtocolDescriptor>>, ) -> Self { Self { did_doc, thread_id, protocols, } } } impl TheirDidDoc for Completed { fn their_did_doc(&self) -> &AriesDidDoc { &self.did_doc } } impl ThreadId for Completed { fn thread_id(&self) -> &str { &self.thread_id } } impl CompletedState for Completed { fn remote_protocols(&self) -> Option<&[ProtocolDescriptor]> { self.protocols.as_deref() } fn handle_disclose(&mut self, disclose: Disclose) { self.protocols = Some(disclose.content.protocols) } }
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/inviter/states/invited.rs
aries/aries_vcx/src/protocols/connection/inviter/states/invited.rs
use crate::{ handlers::util::AnyInvitation, protocols::connection::trait_bounds::{HandleProblem, ThreadId}, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Invited { pub(crate) invitation: AnyInvitation, } impl Invited { pub fn new(invitation: AnyInvitation) -> Self { Self { invitation } } } 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(), } } } impl HandleProblem for Invited {}
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/inviter/states/requested.rs
aries/aries_vcx/src/protocols/connection/inviter/states/requested.rs
use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::connection::response::Response; use crate::protocols::connection::trait_bounds::{TheirDidDoc, ThreadId}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Requested { pub(crate) signed_response: Response, pub(crate) did_doc: AriesDidDoc, } impl Requested { pub fn new(signed_response: Response, did_doc: AriesDidDoc) -> Self { Self { signed_response, did_doc, } } } impl TheirDidDoc for Requested { fn their_did_doc(&self) -> &AriesDidDoc { &self.did_doc } } impl ThreadId for Requested { //TODO: This should land in the threadlike macro. fn thread_id(&self) -> &str { self.signed_response.decorators.thread.thid.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/inviter/states/mod.rs
aries/aries_vcx/src/protocols/connection/inviter/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/inviter/states/initial.rs
aries/aries_vcx/src/protocols/connection/inviter/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/connection/generic/thin_state.rs
aries/aries_vcx/src/protocols/connection/generic/thin_state.rs
use super::{GenericState, InviteeState, InviterState}; /// Small sized enum used for determining /// a connection's state in terms of initiation type. #[derive(Clone, Copy, Debug)] pub enum ThinState { Invitee(State), Inviter(State), } /// Small sized enum used for determining /// a connection's state in terms of connection stage. #[derive(Clone, Copy, Debug)] pub enum State { Initial, Invited, Requested, Responded, Completed, } impl From<&GenericState> for ThinState { fn from(value: &GenericState) -> Self { match value { GenericState::Invitee(v) => Self::Invitee(v.into()), GenericState::Inviter(v) => Self::Inviter(v.into()), } } } impl From<&InviterState> for State { fn from(value: &InviterState) -> Self { match value { InviterState::Initial(_) => Self::Initial, InviterState::Invited(_) => Self::Invited, InviterState::Requested(_) => Self::Requested, InviterState::Completed(_) => Self::Completed, } } } impl From<&InviteeState> for State { fn from(value: &InviteeState) -> Self { match value { InviteeState::Initial(_) => Self::Initial, InviteeState::Invited(_) => Self::Invited, InviteeState::Requested(_) => Self::Requested, InviteeState::Completed(_) => Self::Completed, } } }
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/generic/mod.rs
aries/aries_vcx/src/protocols/connection/generic/mod.rs
mod conversions; mod thin_state; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::AriesMessage; pub use self::thin_state::{State, ThinState}; use super::trait_bounds::BootstrapDidDoc; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, handlers::util::AnyInvitation, protocols::connection::{ invitee::states::{ completed::Completed as InviteeCompleted, initial::Initial as InviteeInitial, invited::Invited as InviteeInvited, requested::Requested as InviteeRequested, }, inviter::states::{ completed::Completed as InviterCompleted, initial::Initial as InviterInitial, invited::Invited as InviterInvited, requested::Requested as InviterRequested, }, pairwise_info::PairwiseInfo, trait_bounds::{TheirDidDoc, ThreadId}, }, transport::Transport, utils::encryption_envelope::EncryptionEnvelope, }; /// A type that can encapsulate a [`super::Connection`] of any state. /// While mainly used for deserialization, it exposes some methods for retrieving /// connection information. /// /// However, using methods directly from [`super::Connection`], if possible, comes with certain /// benefits such as being able to obtain an [`AriesDidDoc`] directly (if the state contains it) /// and not an [`Option<AriesDidDoc>`] (which is what [`GenericConnection`] provides). /// /// [`GenericConnection`] implements [`From`] for all [`super::Connection`] states and /// [`super::Connection`] implements [`TryFrom`] from [`GenericConnection`], with the conversion /// failing if the [`GenericConnection`] is in a different state than the requested one. /// This is also the mechanism used for direct deserialization of a [`super::Connection`]. /// /// Because a [`TryFrom`] conversion is fallible and consumes the [`GenericConnection`], a /// [`ThinState`] can be retrieved through [`GenericConnection::state`] method at runtime. In that /// case, a more dynamic conversion could be done this way: /// /// ``` /// # use aries_vcx::protocols::connection::invitee::states::{complete::Complete, initial::Initial}; /// # use aries_vcx::protocols::connection::initiation_type::Invitee; /// # use aries_vcx::protocols::mediated_connection::pairwise_info::PairwiseInfo; /// # use aries_vcx::protocols::connection::{GenericConnection, ThinState, State, Connection}; /// # /// # let con_inviter = Connection::new_invitee(String::new(), PairwiseInfo::default()); /// /// // We get a GenericConnection somehow /// let con: GenericConnection = con_inviter.into(); /// /// let mut initial_connections: Vec<Connection<Invitee, Initial>> = Vec::new(); /// let mut completed_connections: Vec<Connection<Invitee, Complete>> = Vec::new(); /// /// // Unwrapping after the match is sound /// // because we can guarantee the conversion will work /// match con.state() { /// ThinState::Invitee(State::Initial) => initial_connections.push(con.try_into().unwrap()), /// ThinState::Invitee(State::Complete) => completed_connections.push(con.try_into().unwrap()), /// _ => todo!() /// } /// ``` #[derive(Clone, Debug, Serialize, Deserialize)] pub struct GenericConnection { source_id: String, pairwise_info: PairwiseInfo, state: GenericState, } #[derive(Clone, Debug, Serialize, Deserialize)] pub enum GenericState { Inviter(InviterState), Invitee(InviteeState), } #[derive(Clone, Debug, Serialize, Deserialize)] pub enum InviterState { Initial(InviterInitial), Invited(InviterInvited), Requested(InviterRequested), Completed(InviterCompleted), } #[derive(Clone, Debug, Serialize, Deserialize)] pub enum InviteeState { Initial(InviteeInitial), Invited(InviteeInvited), Requested(InviteeRequested), Completed(InviteeCompleted), } impl GenericConnection { /// Returns the underlying [`super::Connection`]'s state as a [`ThinState`]. /// Used for pattern matching when there's no hint as to what connection type /// is expected from or stored into the [`GenericConnection`]. pub fn state(&self) -> ThinState { (&self.state).into() } pub fn thread_id(&self) -> Option<&str> { match &self.state { GenericState::Invitee(InviteeState::Initial(_)) => None, GenericState::Invitee(InviteeState::Invited(s)) => Some(s.thread_id()), GenericState::Invitee(InviteeState::Requested(s)) => Some(s.thread_id()), GenericState::Invitee(InviteeState::Completed(s)) => Some(s.thread_id()), GenericState::Inviter(InviterState::Initial(_)) => None, GenericState::Inviter(InviterState::Invited(s)) => Some(s.thread_id()), GenericState::Inviter(InviterState::Requested(s)) => Some(s.thread_id()), GenericState::Inviter(InviterState::Completed(s)) => Some(s.thread_id()), } } pub fn pairwise_info(&self) -> &PairwiseInfo { &self.pairwise_info } pub fn their_did_doc(&self) -> Option<&AriesDidDoc> { match &self.state { GenericState::Invitee(InviteeState::Initial(_)) => None, GenericState::Invitee(InviteeState::Invited(s)) => Some(s.their_did_doc()), GenericState::Invitee(InviteeState::Requested(s)) => Some(s.their_did_doc()), GenericState::Invitee(InviteeState::Completed(s)) => Some(s.their_did_doc()), GenericState::Inviter(InviterState::Initial(_)) => None, GenericState::Inviter(InviterState::Invited(_)) => None, GenericState::Inviter(InviterState::Requested(s)) => Some(s.their_did_doc()), GenericState::Inviter(InviterState::Completed(s)) => Some(s.their_did_doc()), } } pub fn bootstrap_did_doc(&self) -> Option<&AriesDidDoc> { match &self.state { GenericState::Inviter(_) => None, GenericState::Invitee(InviteeState::Initial(_)) => None, GenericState::Invitee(InviteeState::Invited(s)) => Some(s.bootstrap_did_doc()), GenericState::Invitee(InviteeState::Requested(s)) => Some(s.bootstrap_did_doc()), GenericState::Invitee(InviteeState::Completed(s)) => Some(s.bootstrap_did_doc()), } } pub fn remote_did(&self) -> Option<&str> { self.their_did_doc().map(|d| d.id.as_str()) } pub fn remote_vk(&self) -> VcxResult<String> { let did_doc = self.their_did_doc().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "No DidDoc present", ))?; did_doc .recipient_keys()? .first() .map(ToOwned::to_owned) .ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "Can't resolve recipient key from the counterparty diddoc.", )) } pub fn invitation(&self) -> Option<&AnyInvitation> { match &self.state { GenericState::Inviter(InviterState::Invited(s)) => Some(&s.invitation), GenericState::Invitee(InviteeState::Invited(s)) => Some(&s.invitation), _ => None, } } pub async fn encrypt_message( &self, wallet: &impl BaseWallet, message: &AriesMessage, ) -> VcxResult<EncryptionEnvelope> { let sender_verkey = &self.pairwise_info().pw_vk; let did_doc = self.their_did_doc().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "No DidDoc present", ))?; EncryptionEnvelope::create_from_legacy( wallet, json!(message).to_string().as_bytes(), Some(sender_verkey), did_doc, ) .await } pub async fn send_message<T>( &self, wallet: &impl BaseWallet, message: &AriesMessage, transport: &T, ) -> VcxResult<()> where T: Transport, { let did_doc = self.their_did_doc().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "No DidDoc present", ))?; let msg = self.encrypt_message(wallet, message).await?.0; let service_endpoint = did_doc.get_endpoint().ok_or_else(|| { AriesVcxError::from_msg(AriesVcxErrorKind::InvalidUrl, "No URL in DID Doc") })?; transport.send_message(msg, &service_endpoint).await } } /// Compile-time assurance that the [`GenericConnection`] and the hidden serialization type /// of the [`crate::protocols::connection::Connection`], if modified, will be modified together. #[cfg(test)] mod connection_serde_tests { use async_trait::async_trait; use chrono::Utc; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::{ connection::{ invitation::{Invitation, InvitationContent}, request::{Request, RequestContent, RequestDecorators}, response::{Response, ResponseContent, ResponseDecorators}, ConnectionData, }, notification::ack::{Ack, AckContent, AckDecorators, AckStatus}, }, }; use test_utils::{mock_wallet::MockWallet, mockdata::mock_ledger::MockLedger}; use url::Url; use uuid::Uuid; use super::*; use crate::{ common::signing::sign_connection_response, handlers::util::AnyInvitation, protocols::connection::{ invitee::InviteeConnection, inviter::InviterConnection, serializable::*, Connection, }, }; impl<'a> From<RefInviteeState<'a>> for InviteeState { fn from(value: RefInviteeState<'a>) -> Self { match value { RefInviteeState::Initial(s) => Self::Initial(s.to_owned()), RefInviteeState::Invited(s) => Self::Invited(s.to_owned()), RefInviteeState::Requested(s) => Self::Requested(s.to_owned()), RefInviteeState::Completed(s) => Self::Completed(s.to_owned()), } } } impl<'a> From<RefInviterState<'a>> for InviterState { fn from(value: RefInviterState<'a>) -> Self { match value { RefInviterState::Initial(s) => Self::Initial(s.to_owned()), RefInviterState::Invited(s) => Self::Invited(s.to_owned()), RefInviterState::Requested(s) => Self::Requested(s.to_owned()), RefInviterState::Completed(s) => Self::Completed(s.to_owned()), } } } impl<'a> From<RefState<'a>> for GenericState { fn from(value: RefState<'a>) -> Self { match value { RefState::Invitee(s) => Self::Invitee(s.into()), RefState::Inviter(s) => Self::Inviter(s.into()), } } } impl<'a> From<SerializableConnection<'a>> for GenericConnection { fn from(value: SerializableConnection<'a>) -> Self { let SerializableConnection { source_id, pairwise_info, state, } = value; Self { source_id: source_id.to_owned(), pairwise_info: pairwise_info.to_owned(), state: state.into(), } } } impl<'a> From<&'a InviteeState> for RefInviteeState<'a> { fn from(value: &'a InviteeState) -> Self { match value { InviteeState::Initial(s) => Self::Initial(s), InviteeState::Invited(s) => Self::Invited(s), InviteeState::Requested(s) => Self::Requested(s), InviteeState::Completed(s) => Self::Completed(s), } } } impl<'a> From<&'a InviterState> for RefInviterState<'a> { fn from(value: &'a InviterState) -> Self { match value { InviterState::Initial(s) => Self::Initial(s), InviterState::Invited(s) => Self::Invited(s), InviterState::Requested(s) => Self::Requested(s), InviterState::Completed(s) => Self::Completed(s), } } } impl<'a> From<&'a GenericState> for RefState<'a> { fn from(value: &'a GenericState) -> Self { match value { GenericState::Invitee(s) => Self::Invitee(s.into()), GenericState::Inviter(s) => Self::Inviter(s.into()), } } } impl<'a> From<&'a GenericConnection> for SerializableConnection<'a> { fn from(value: &'a GenericConnection) -> Self { let GenericConnection { source_id, pairwise_info, state, } = value; Self { source_id, pairwise_info, state: state.into(), } } } struct MockTransport; #[async_trait] impl Transport for MockTransport { async fn send_message(&self, _msg: Vec<u8>, _service_endpoint: &Url) -> VcxResult<()> { Ok(()) } } fn serde_test<I, S>(con: Connection<I, S>) where I: Clone, S: Clone, for<'a> SerializableConnection<'a>: From<&'a Connection<I, S>>, GenericConnection: From<Connection<I, S>>, Connection<I, S>: TryFrom<GenericConnection, Error = AriesVcxError>, (I, S): TryFrom<GenericState, Error = AriesVcxError>, { // Clone and convert to generic let gen_con = GenericConnection::from(con.clone()); // Serialize concrete and generic connections, then compare. let con_string = serde_json::to_string(&con).unwrap(); let gen_con_string = serde_json::to_string(&gen_con).unwrap(); assert_eq!(con_string, gen_con_string); // Deliberately reversing the strings that were serialized. // The states are identical, so the cross-deserialization should work. let con: Connection<I, S> = serde_json::from_str(&gen_con_string).unwrap(); let gen_con: GenericConnection = serde_json::from_str(&con_string).unwrap(); // Serialize and compare again. let con_string = serde_json::to_string(&con).unwrap(); let gen_con_string = serde_json::to_string(&gen_con).unwrap(); assert_eq!(con_string, gen_con_string); } const SOURCE_ID: &str = "connection_serde_tests"; const PW_KEY: &str = "7Z9ZajGKvb6BMsZ9TBEqxMHktxGdts3FvAbKSJT5XgzK"; const SERVICE_ENDPOINT: &str = "https://localhost:8080"; async fn make_initial_parts() -> (String, PairwiseInfo) { let source_id = SOURCE_ID.to_owned(); let wallet = MockWallet; let pairwise_info = PairwiseInfo::create(&wallet).await.unwrap(); (source_id, pairwise_info) } async fn make_invitee_initial() -> InviteeConnection<InviteeInitial> { let (source_id, pairwise_info) = make_initial_parts().await; Connection::new_invitee(source_id, pairwise_info) } async fn make_invitee_invited() -> InviteeConnection<InviteeInvited> { let indy_ledger = MockLedger; let content = InvitationContent::builder_pairwise() .label(String::new()) .recipient_keys(vec![PW_KEY.to_owned()]) .service_endpoint(SERVICE_ENDPOINT.parse().unwrap()) .build(); let pw_invite = Invitation::builder() .id(Uuid::new_v4().to_string()) .content(content) .build(); let invitation = AnyInvitation::Con(pw_invite); make_invitee_initial() .await .accept_invitation(&indy_ledger, invitation) .await .unwrap() } async fn make_invitee_requested() -> InviteeConnection<InviteeRequested> { let service_endpoint = SERVICE_ENDPOINT.parse().unwrap(); let routing_keys = vec![]; make_invitee_invited() .await .prepare_request(service_endpoint, routing_keys) .await .unwrap() } async fn make_invitee_completed() -> InviteeConnection<InviteeCompleted> { let wallet = MockWallet; let con = make_invitee_requested().await; let mut con_data = ConnectionData::new(PW_KEY.to_owned(), AriesDidDoc::default()); PW_KEY.clone_into(&mut con_data.did_doc.id); con_data.did_doc.set_recipient_keys(vec![PW_KEY.to_owned()]); con_data.did_doc.set_routing_keys(Vec::new()); let sig_data = sign_connection_response(&wallet, PW_KEY, &con_data) .await .unwrap(); let content = ResponseContent::builder().connection_sig(sig_data).build(); let decorators = ResponseDecorators::builder() .thread(Thread::builder().thid(con.thread_id().to_owned()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); let response = Response::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build(); let con = con.handle_response(&wallet, response).await.unwrap(); con.send_message(&wallet, &con.get_ack().into(), &MockTransport) .await .unwrap(); con } async fn make_inviter_initial() -> InviterConnection<InviterInitial> { let (source_id, pairwise_info) = make_initial_parts().await; Connection::new_inviter(source_id, pairwise_info) } async fn make_inviter_invited() -> InviterConnection<InviterInvited> { make_inviter_initial() .await .into_invited(&String::default()) } async fn make_inviter_requested() -> InviterConnection<InviterRequested> { let wallet = MockWallet; let con = make_inviter_invited().await; let new_service_endpoint = SERVICE_ENDPOINT .to_owned() .parse() .expect("url should be valid"); let new_routing_keys = vec![]; let mut con_data = ConnectionData::new(PW_KEY.to_owned(), AriesDidDoc::default()); PW_KEY.clone_into(&mut con_data.did_doc.id); con_data.did_doc.set_recipient_keys(vec![PW_KEY.to_owned()]); con_data.did_doc.set_routing_keys(Vec::new()); let content = RequestContent::builder() .label(PW_KEY.to_owned()) .connection(con_data) .build(); let decorators = RequestDecorators::builder() .thread(Thread::builder().thid(con.thread_id().to_owned()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); let request = Request::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build(); con.handle_request(&wallet, request, new_service_endpoint, new_routing_keys) .await .unwrap() } async fn make_inviter_completed() -> InviterConnection<InviterCompleted> { let con = make_inviter_requested().await; let content = AckContent::builder().status(AckStatus::Ok).build(); let decorators = AckDecorators::builder() .thread(Thread::builder().thid(con.thread_id().to_owned()).build()) .build(); let msg = Ack::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) .build(); con.acknowledge_connection(&msg).unwrap() } macro_rules! generate_test { ($name:ident, $func:ident) => { #[tokio::test] async fn $name() { let con = $func().await; serde_test(con); } }; } generate_test!(invitee_connection_initial, make_invitee_initial); generate_test!(invitee_connection_invited, make_invitee_invited); generate_test!(invitee_connection_requested, make_invitee_requested); generate_test!(invitee_connection_complete, make_invitee_completed); generate_test!(inviter_connection_initial, make_inviter_initial); generate_test!(inviter_connection_invited, make_inviter_invited); generate_test!(inviter_connection_requested, make_inviter_requested); generate_test!(inviter_connection_complete, make_inviter_completed); }
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/generic/conversions.rs
aries/aries_vcx/src/protocols/connection/generic/conversions.rs
use super::{GenericConnection, GenericState, InviteeState, InviterState}; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind}, protocols::connection::{ initiation_type::{Invitee, Inviter}, invitee::states::{ completed::Completed as InviteeCompleted, initial::Initial as InviteeInitial, invited::Invited as InviteeInvited, requested::Requested as InviteeRequested, }, inviter::states::{ completed::Completed as InviterCompleted, initial::Initial as InviterInitial, invited::Invited as InviterInvited, requested::Requested as InviterRequested, }, Connection, }, }; /// Macro used for boilerplace implementation of the /// [`From`] trait from a concrete connection state to the equivalent vague state. macro_rules! from_concrete_to_vague { ($from:ident, $var:ident, $to:ident) => { impl From<$from> for $to { fn from(value: $from) -> Self { Self::$var(value) } } }; ($init_type:ident, $state:ident, $var:ident, $to:ident) => { impl<S> From<($init_type, S)> for $to where $state: From<S>, { fn from(value: ($init_type, S)) -> Self { let (_, state) = value; let serde_state = From::from(state); Self::$var(serde_state) } } }; } /// Macro used for boilerplace implementation of the /// [`TryFrom`] trait from a vague connection state to a concrete state. macro_rules! try_from_vague_to_concrete { ($from:ident, $var:ident, $to:ident) => { impl TryFrom<$from> for $to { type Error = AriesVcxError; fn try_from(value: $from) -> Result<Self, Self::Error> { match value { $from::$var(s) => Ok(s), _ => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, format!("unexpected connection state: {:?}!", value), )), } } } }; ($state:ident, $good_var:ident, $bad_var:ident, $init_type:ident) => { impl<S> TryFrom<GenericState> for ($init_type, S) where S: TryFrom<$state, Error = AriesVcxError>, { type Error = AriesVcxError; fn try_from(value: GenericState) -> Result<Self, Self::Error> { match value { GenericState::$good_var(s) => S::try_from(s).map(|s| ($init_type, s)), GenericState::$bad_var(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, concat!( "Expected ", stringify!(VagueState::$good_var), "connection state, found ", stringify!(VagueState::$bad_var), ), )), } } } }; } // ---------------------------- From Concrete State to Vague State implementations // ---------------------------- impl<I, S> From<Connection<I, S>> for GenericConnection where GenericState: From<(I, S)>, { fn from(value: Connection<I, S>) -> Self { let state = From::from((value.initiation_type, value.state)); Self { source_id: value.source_id, pairwise_info: value.pairwise_info, state, } } } from_concrete_to_vague!(Inviter, InviterState, Inviter, GenericState); from_concrete_to_vague!(Invitee, InviteeState, Invitee, GenericState); from_concrete_to_vague!(InviterInitial, Initial, InviterState); from_concrete_to_vague!(InviterInvited, Invited, InviterState); from_concrete_to_vague!(InviterRequested, Requested, InviterState); from_concrete_to_vague!(InviterCompleted, Completed, InviterState); from_concrete_to_vague!(InviteeInitial, Initial, InviteeState); from_concrete_to_vague!(InviteeInvited, Invited, InviteeState); from_concrete_to_vague!(InviteeRequested, Requested, InviteeState); from_concrete_to_vague!(InviteeCompleted, Completed, InviteeState); // ---------------------------- Try From Vague State to Concrete State implementations // ---------------------------- impl<I, S> TryFrom<GenericConnection> for Connection<I, S> where (I, S): TryFrom<GenericState, Error = AriesVcxError>, { type Error = AriesVcxError; fn try_from(value: GenericConnection) -> Result<Self, Self::Error> { let (initiation_type, state) = TryFrom::try_from(value.state)?; let con = Connection::from_parts(value.source_id, value.pairwise_info, initiation_type, state); Ok(con) } } try_from_vague_to_concrete!(InviterState, Inviter, Invitee, Inviter); try_from_vague_to_concrete!(InviteeState, Invitee, Inviter, Invitee); try_from_vague_to_concrete!(InviterState, Initial, InviterInitial); try_from_vague_to_concrete!(InviterState, Invited, InviterInvited); try_from_vague_to_concrete!(InviterState, Requested, InviterRequested); try_from_vague_to_concrete!(InviterState, Completed, InviterCompleted); try_from_vague_to_concrete!(InviteeState, Initial, InviteeInitial); try_from_vague_to_concrete!(InviteeState, Invited, InviteeInvited); try_from_vague_to_concrete!(InviteeState, Requested, InviteeRequested); try_from_vague_to_concrete!(InviteeState, Completed, InviteeCompleted);
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/mod.rs
aries/aries_vcx/src/protocols/connection/invitee/mod.rs
pub mod states; use aries_vcx_ledger::ledger::base_ledger::IndyLedgerRead; use aries_vcx_wallet::wallet::base_wallet::BaseWallet; use chrono::Utc; use diddoc_legacy::aries::{diddoc::AriesDidDoc, service::AriesService}; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::{ connection::{ invitation::{Invitation, InvitationContent}, request::{Request, RequestContent, RequestDecorators}, response::Response, ConnectionData, }, notification::ack::{Ack, AckContent, AckDecorators, AckStatus}, }, }; use url::Url; use uuid::Uuid; use self::states::{ completed::Completed, initial::Initial, invited::Invited, requested::Requested, }; use super::{ initiation_type::Invitee, pairwise_info::PairwiseInfo, trait_bounds::BootstrapDidDoc, Connection, }; use crate::{ common::{ledger::transactions::get_service, signing::decode_signed_connection_response}, errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, handlers::util::{matches_thread_id, AnyInvitation}, protocols::{connection::trait_bounds::ThreadId, oob::oob_invitation_to_legacy_did_doc}, }; /// Convenience alias pub type InviteeConnection<S> = Connection<Invitee, S>; impl InviteeConnection<Initial> { /// Creates a new [`InviteeConnection<Initial>`]. pub fn new_invitee(source_id: String, pairwise_info: PairwiseInfo) -> Self { Self { source_id, state: Initial, pairwise_info, initiation_type: Invitee, } } /// Accepts an [`Invitation`] and transitions to [`InviteeConnection<Invited>`]. /// /// # Errors /// /// Will error out if a DidDoc could not be resolved from the [`Invitation`]. pub async fn accept_invitation( self, indy_ledger: &impl IndyLedgerRead, invitation: AnyInvitation, ) -> VcxResult<InviteeConnection<Invited>> { trace!( "Connection::accept_invitation >>> invitation: {:?}", &invitation ); let did_doc = any_invitation_into_did_doc(indy_ledger, &invitation).await?; let state = Invited::new(did_doc, invitation); // Convert to `InvitedState` Ok(Connection { state, source_id: self.source_id, pairwise_info: self.pairwise_info, initiation_type: Invitee, }) } } impl InviteeConnection<Invited> { /// Sends a [`Request`] to the inviter and transitions to [`InviteeConnection<Requested>`]. /// /// # Errors /// /// Will error out if sending the request fails. pub async fn prepare_request( self, service_endpoint: Url, routing_keys: Vec<String>, ) -> VcxResult<InviteeConnection<Requested>> { trace!("Connection::prepare_request"); let recipient_keys = vec![self.pairwise_info.pw_vk.clone()]; let id = Uuid::new_v4().to_string(); let mut did_doc = AriesDidDoc { id: self.pairwise_info.pw_did.to_string(), ..Default::default() }; did_doc.set_service_endpoint(service_endpoint); did_doc.set_routing_keys(routing_keys); did_doc.set_recipient_keys(recipient_keys); let con_data = ConnectionData::new(self.pairwise_info.pw_did.to_string(), did_doc); let content = RequestContent::builder() .label(self.source_id.to_string()) .connection(con_data) .build(); let decorators = RequestDecorators::builder().timing(Timing::builder().out_time(Utc::now()).build()); // Depending on the invitation type, we set the connection's thread ID // and the request parent and thread ID differently. // // When using a Public or OOB invitation, the invitation's ID (current thread ID) // is used as the parent thread ID, while the request ID is set as thread ID. // // Multiple invitees can use the same invitation in these cases, hence the common // parent thread ID and different thread IDs (request IDs are unique). // // When the invitation is Pairwise, it is designed to be sent to a single invitee. // In this case, we reuse the invitation ID (current thread ID) as the thread ID // in both the connection and the request. let thread = match &self.state.invitation { AnyInvitation::Oob(invite) => Thread::builder() .thid(id.clone()) .pthid(invite.id.clone()) .build(), AnyInvitation::Con(invite) => match invite.content { InvitationContent::Public(_) => Thread::builder() .thid(id.clone()) .pthid(self.state.thread_id().to_owned()) .build(), InvitationContent::Pairwise(_) | InvitationContent::PairwiseDID(_) => { Thread::builder() .thid(self.state.thread_id().to_owned()) .build() } }, }; let thread_id = thread.thid.clone(); let decorators = decorators.thread(thread).build(); let request = Request::builder() .id(id) .content(content) .decorators(decorators) .build(); Ok(Connection { state: Requested::new(self.state.did_doc, thread_id, request), source_id: self.source_id, pairwise_info: self.pairwise_info, initiation_type: Invitee, }) } } impl InviteeConnection<Requested> { /// Processes a [`SignedResponse`] from the inviter and transitions to /// [`InviteeConnection<Responded>`]. /// /// # Errors /// /// Will error out if: /// * the thread ID of the response does not match the connection thread ID /// * no recipient verkeys are provided in the response. /// * decoding the signed response fails pub async fn handle_response( self, wallet: &impl BaseWallet, response: Response, ) -> VcxResult<InviteeConnection<Completed>> { let is_match = matches_thread_id!(response, self.state.thread_id()); if !is_match { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!( "Cannot handle message {:?}: thread id does not match, expected {:?}", response, self.state.thread_id() ), )); }; let keys = &self.state.did_doc.recipient_keys()?; let their_vk = keys.first().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, "Cannot handle response: remote verkey not found", ))?; let did_doc = decode_signed_connection_response(wallet, response.content, their_vk) .await? .did_doc; let state = Completed::new(did_doc, self.state.did_doc, self.state.thread_id, None); Ok(Connection { state, source_id: self.source_id, pairwise_info: self.pairwise_info, initiation_type: Invitee, }) } pub fn get_request(&self) -> &Request { &self.state.request } } impl InviteeConnection<Completed> { /// Sends an acknowledgement message to the inviter and transitions to /// [`InviteeConnection<Completed>`]. /// /// # Errors /// /// Will error out if sending the message fails. pub fn get_ack(&self) -> Ack { let id = Uuid::new_v4().to_string(); let content = AckContent::builder().status(AckStatus::Ok).build(); let decorators = AckDecorators::builder() .thread(Thread::builder().thid(self.state.thread_id.clone()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); Ack::builder() .id(id) .content(content) .decorators(decorators) .build() } } impl<S> InviteeConnection<S> where S: BootstrapDidDoc, { pub fn bootstrap_did_doc(&self) -> &AriesDidDoc { self.state.bootstrap_did_doc() } } pub async fn any_invitation_into_did_doc( indy_ledger: &impl IndyLedgerRead, invitation: &AnyInvitation, ) -> VcxResult<AriesDidDoc> { let mut did_doc: AriesDidDoc = AriesDidDoc::default(); let (service_endpoint, recipient_keys, routing_keys) = match invitation { AnyInvitation::Con(Invitation { content: InvitationContent::Public(content), .. }) => { did_doc.set_id(content.did.to_string()); let service = get_service(indy_ledger, &content.did.parse()?) .await .unwrap_or_else(|err| { error!("Failed to obtain service definition from the ledger: {err}"); AriesService::default() }); ( service.service_endpoint, service.recipient_keys, service.routing_keys, ) } AnyInvitation::Con(Invitation { id, content: InvitationContent::Pairwise(content), .. }) => { did_doc.set_id(id.clone()); ( content.service_endpoint.clone(), content.recipient_keys.clone(), content.routing_keys.clone(), ) } AnyInvitation::Con(Invitation { content: InvitationContent::PairwiseDID(_content), .. }) => { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidDid, "PairwiseDID invitation not supported yet!", )) } AnyInvitation::Oob(invitation) => { return oob_invitation_to_legacy_did_doc(indy_ledger, invitation).await } }; did_doc.set_service_endpoint(service_endpoint); did_doc.set_recipient_keys(recipient_keys); did_doc.set_routing_keys(routing_keys); Ok(did_doc) }
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/completed.rs
aries/aries_vcx/src/protocols/connection/invitee/states/completed.rs
use std::clone::Clone; use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::msg_fields::protocols::discover_features::{disclose::Disclose, ProtocolDescriptor}; use crate::protocols::connection::trait_bounds::{ BootstrapDidDoc, CompletedState, TheirDidDoc, ThreadId, }; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Completed { pub(crate) did_doc: AriesDidDoc, pub(crate) bootstrap_did_doc: AriesDidDoc, pub(crate) thread_id: String, pub(crate) protocols: Option<Vec<ProtocolDescriptor>>, } impl Completed { pub fn new( did_doc: AriesDidDoc, bootstrap_did_doc: AriesDidDoc, thread_id: String, protocols: Option<Vec<ProtocolDescriptor>>, ) -> Self { Self { did_doc, bootstrap_did_doc, thread_id, protocols, } } } impl TheirDidDoc for Completed { fn their_did_doc(&self) -> &AriesDidDoc { &self.did_doc } } impl BootstrapDidDoc for Completed { fn bootstrap_did_doc(&self) -> &AriesDidDoc { &self.bootstrap_did_doc } } impl ThreadId for Completed { fn thread_id(&self) -> &str { &self.thread_id } } impl CompletedState for Completed { fn remote_protocols(&self) -> Option<&[ProtocolDescriptor]> { self.protocols.as_deref() } fn handle_disclose(&mut self, disclose: Disclose) { self.protocols = Some(disclose.content.protocols) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false