From 3a5293aef84b9fb19aeb3e19d6d0550e748976c2 Mon Sep 17 00:00:00 2001 From: Bogdan Mircea <98585737+bobozaur@users.noreply.github.com> Date: Thu, 19 Oct 2023 12:14:17 +0300 Subject: [PATCH 1/6] Extract primitives and remove Profile (#1016) * Extract primitives and remove Profile (#1016) Signed-off-by: Bogdan Mircea --- agency_client/Cargo.toml | 4 - agency_client/src/messages/a2a_message.rs | 1 - agency_client/src/messages/create_key.rs | 3 - .../src/messages/update_com_method.rs | 1 - agency_client/src/testing/mod.rs | 1 - .../aries-vcx-agent/src/agent/agent_struct.rs | 24 +- agents/rust/aries-vcx-agent/src/agent/init.rs | 56 ++-- .../src/services/connection.rs | 35 +-- .../src/services/credential_definition.rs | 31 ++- .../aries-vcx-agent/src/services/holder.rs | 33 ++- .../aries-vcx-agent/src/services/issuer.rs | 21 +- .../aries-vcx-agent/src/services/prover.rs | 26 +- .../src/services/revocation_registry.rs | 34 ++- .../aries-vcx-agent/src/services/schema.rs | 33 ++- .../aries-vcx-agent/src/services/verifier.rs | 25 +- aries_vcx/src/common/anoncreds.rs | 49 ++-- aries_vcx/src/common/credentials/encoding.rs | 18 +- aries_vcx/src/common/credentials/mod.rs | 97 ++++--- aries_vcx/src/common/keys.rs | 2 +- aries_vcx/src/common/ledger/service_didsov.rs | 10 +- aries_vcx/src/common/ledger/transactions.rs | 20 +- .../primitives/credential_definition.rs | 52 ++-- .../common/primitives/credential_schema.rs | 9 +- .../common/primitives/revocation_registry.rs | 48 +++- aries_vcx/src/common/proofs/proof_request.rs | 16 +- aries_vcx/src/common/proofs/prover/mod.rs | 3 + .../common/proofs/prover/prover_internal.rs | 26 +- aries_vcx/src/common/proofs/verifier/mod.rs | 128 ++++++--- aries_vcx/src/common/test_utils.rs | 41 ++- aries_vcx/src/core/mod.rs | 1 - aries_vcx/src/core/profile/ledger.rs | 85 ------ aries_vcx/src/core/profile/mod.rs | 57 ---- .../src/core/profile/modular_libs_profile.rs | 70 ----- .../src/core/profile/vdr_proxy_profile.rs | 96 ------- aries_vcx/src/handlers/issuance/holder.rs | 30 +- aries_vcx/src/handlers/issuance/issuer.rs | 24 +- .../src/handlers/proof_presentation/prover.rs | 7 +- aries_vcx/src/lib.rs | 1 - .../issuance/holder/state_machine.rs | 29 +- .../issuance/issuer/state_machine.rs | 11 +- .../prover/state_machine.rs | 10 +- .../states/presentation_request_received.rs | 3 + aries_vcx/src/utils/devsetup.rs | 237 +++++++++++----- aries_vcx/src/utils/ledger.rs | 42 +++ .../utils/mockdata/profile/mock_anoncreds.rs | 70 ++++- .../src/utils/mockdata/profile/mock_ledger.rs | 16 +- .../utils/mockdata/profile/mock_profile.rs | 39 --- aries_vcx/src/utils/mockdata/profile/mod.rs | 1 - aries_vcx/src/utils/mod.rs | 1 + aries_vcx/src/utils/test_logger.rs | 6 +- aries_vcx/src/utils/validation.rs | 8 +- aries_vcx/tests/test_connection.rs | 51 +++- aries_vcx/tests/test_credential_issuance.rs | 30 +- aries_vcx/tests/test_credential_retrieval.rs | 28 +- aries_vcx/tests/test_pool.rs | 180 ++++++------ aries_vcx/tests/test_proof_presentation.rs | 49 ++-- aries_vcx/tests/test_revocations.rs | 222 +++++++-------- aries_vcx/tests/utils/scenarios/connection.rs | 88 ++++-- .../utils/scenarios/credential_issuance.rs | 191 +++++++++---- .../utils/scenarios/proof_presentation.rs | 178 ++++++++---- aries_vcx/tests/utils/test_agent.rs | 66 ++++- .../src/anoncreds/base_anoncreds.rs | 53 +++- .../src/anoncreds/credx_anoncreds.rs | 263 ++++++++++-------- aries_vcx_core/src/ledger/base_ledger.rs | 24 +- aries_vcx_core/src/ledger/indy_vdr_ledger.rs | 132 ++++----- aries_vcx_core/src/ledger/mod.rs | 1 - .../src/ledger/request_signer/base_wallet.rs | 27 -- .../src/ledger/request_signer/mod.rs | 11 - .../ledger/request_submitter/vdr_ledger.rs | 33 +-- .../src/ledger/request_submitter/vdr_proxy.rs | 1 + did_resolver_sov/tests/resolution.rs | 16 +- libvcx_core/src/api_vcx/api_global/ledger.rs | 44 ++- libvcx_core/src/api_vcx/api_global/pool.rs | 33 +-- libvcx_core/src/api_vcx/api_global/wallet.rs | 25 +- .../src/api_vcx/api_handle/credential.rs | 18 +- .../src/api_vcx/api_handle/credential_def.rs | 6 +- .../src/api_vcx/api_handle/disclosed_proof.rs | 14 +- .../api_vcx/api_handle/issuer_credential.rs | 7 +- .../api_vcx/api_handle/mediated_connection.rs | 11 +- .../api_vcx/api_handle/object_cache/mod.rs | 10 +- .../api_vcx/api_handle/revocation_registry.rs | 10 +- libvcx_core/src/api_vcx/api_handle/schema.rs | 18 +- libvdrtools/indy-wallet/src/lib.rs | 2 +- messages/src/msg_types/registry.rs | 4 +- uniffi_aries_vcx/core/src/core/profile.rs | 26 +- .../core/src/core/unpack_message.rs | 5 +- .../core/src/handlers/connection.rs | 1 - 87 files changed, 2024 insertions(+), 1545 deletions(-) delete mode 100644 aries_vcx/src/core/mod.rs delete mode 100644 aries_vcx/src/core/profile/ledger.rs delete mode 100644 aries_vcx/src/core/profile/mod.rs delete mode 100644 aries_vcx/src/core/profile/modular_libs_profile.rs delete mode 100644 aries_vcx/src/core/profile/vdr_proxy_profile.rs create mode 100644 aries_vcx/src/utils/ledger.rs delete mode 100644 aries_vcx/src/utils/mockdata/profile/mock_profile.rs delete mode 100644 aries_vcx_core/src/ledger/request_signer/base_wallet.rs delete mode 100644 aries_vcx_core/src/ledger/request_signer/mod.rs diff --git a/agency_client/Cargo.toml b/agency_client/Cargo.toml index ed4207538d..043a6808c8 100644 --- a/agency_client/Cargo.toml +++ b/agency_client/Cargo.toml @@ -8,10 +8,6 @@ edition.workspace = true [lib] doctest = false -[features] -test_utils = [] -general_test = ["test_utils"] - [dependencies] async-trait = "0.1.53" env_logger = "0.9.0" diff --git a/agency_client/src/messages/a2a_message.rs b/agency_client/src/messages/a2a_message.rs index 5bfe28cb7e..608738471d 100644 --- a/agency_client/src/messages/a2a_message.rs +++ b/agency_client/src/messages/a2a_message.rs @@ -196,7 +196,6 @@ impl A2AMessageKinds { } } -#[cfg(feature = "general_test")] #[cfg(test)] mod test { use serde_json::json; diff --git a/agency_client/src/messages/create_key.rs b/agency_client/src/messages/create_key.rs index 8f205566d2..13863ca7a4 100644 --- a/agency_client/src/messages/create_key.rs +++ b/agency_client/src/messages/create_key.rs @@ -65,14 +65,12 @@ impl CreateKeyBuilder { } } -#[cfg(feature = "general_test")] #[cfg(test)] mod tests { use super::*; use crate::errors::error::AgencyClientErrorKind; #[test] - #[cfg(feature = "general_test")] fn test_create_key_set_values() { let for_did = "11235yBzrpJQmNyZzgoTqB"; let for_verkey = "EkVTa7SCJ5SntpYyX7CSb2pcBhiVGT9kWSagA8a9T69A"; @@ -85,7 +83,6 @@ mod tests { } #[test] - #[cfg(feature = "general_test")] fn test_create_key_set_invalid_did_errors() { let for_did = "11235yBzrpJQmNyZzgoT"; let res = CreateKeyBuilder::create().for_did(for_did).unwrap_err(); diff --git a/agency_client/src/messages/update_com_method.rs b/agency_client/src/messages/update_com_method.rs index 4e848b3548..6cba921823 100644 --- a/agency_client/src/messages/update_com_method.rs +++ b/agency_client/src/messages/update_com_method.rs @@ -64,7 +64,6 @@ impl UpdateComMethod { } #[cfg(test)] -#[cfg(feature = "general_test")] mod tests { use super::*; diff --git a/agency_client/src/testing/mod.rs b/agency_client/src/testing/mod.rs index ba8a8e088e..b536c40c5e 100644 --- a/agency_client/src/testing/mod.rs +++ b/agency_client/src/testing/mod.rs @@ -2,5 +2,4 @@ pub mod mocking; #[rustfmt::skip] pub mod test_constants; pub mod test_settings; -#[cfg(feature = "test_utils")] pub mod test_utils; diff --git a/agents/rust/aries-vcx-agent/src/agent/agent_struct.rs b/agents/rust/aries-vcx-agent/src/agent/agent_struct.rs index 48e4f3d1b8..5498180fb2 100644 --- a/agents/rust/aries-vcx-agent/src/agent/agent_struct.rs +++ b/agents/rust/aries-vcx-agent/src/agent/agent_struct.rs @@ -1,6 +1,7 @@ use std::sync::Arc; -use aries_vcx::core::profile::modular_libs_profile::ModularLibsProfile; +use aries_vcx::utils::devsetup::{DefaultIndyLedgerRead, DefaultIndyLedgerWrite}; +use aries_vcx_core::{anoncreds::credx_anoncreds::IndyCredxAnonCreds, wallet::indy::IndySdkWallet}; use crate::{ agent::agent_config::AgentConfig, @@ -14,7 +15,10 @@ use crate::{ #[derive(Clone)] pub struct Agent { - pub(super) profile: Arc, + pub(super) ledger_read: Arc, + pub(super) ledger_write: Arc, + pub(super) anoncreds: IndyCredxAnonCreds, + pub(super) wallet: Arc, pub(super) config: AgentConfig, pub(super) connections: Arc, pub(super) schemas: Arc, @@ -27,8 +31,20 @@ pub struct Agent { } impl Agent { - pub fn profile(&self) -> &ModularLibsProfile { - &self.profile + pub fn ledger_read(&self) -> &DefaultIndyLedgerRead { + &self.ledger_read + } + + pub fn ledger_write(&self) -> &DefaultIndyLedgerWrite { + &self.ledger_write + } + + pub fn anoncreds(&self) -> &IndyCredxAnonCreds { + &self.anoncreds + } + + pub fn wallet(&self) -> &IndySdkWallet { + &self.wallet } pub fn agent_config(&self) -> AgentConfig { diff --git a/agents/rust/aries-vcx-agent/src/agent/init.rs b/agents/rust/aries-vcx-agent/src/agent/init.rs index 9108a1d9a2..9be7b85b11 100644 --- a/agents/rust/aries-vcx-agent/src/agent/init.rs +++ b/agents/rust/aries-vcx-agent/src/agent/init.rs @@ -1,8 +1,7 @@ use std::sync::Arc; use aries_vcx::{ - core::profile::{ledger::VcxPoolConfig, modular_libs_profile::ModularLibsProfile, Profile}, - global::settings::DEFAULT_LINK_SECRET_ALIAS, + global::settings::DEFAULT_LINK_SECRET_ALIAS, utils::devsetup::dev_build_profile_modular, }; use aries_vcx_core::{ self, @@ -66,52 +65,69 @@ impl Agent { let wallet = Arc::new(IndySdkWallet::new(wallet_handle)); - let pool_config = VcxPoolConfig { - genesis_file_path: init_config.pool_config.genesis_path, - indy_vdr_config: None, - response_cache_config: None, - }; + let (ledger_read, ledger_write, anoncreds) = + dev_build_profile_modular(init_config.pool_config.genesis_path); + let ledger_read = Arc::new(ledger_read); + let ledger_write = Arc::new(ledger_write); - let indy_profile = ModularLibsProfile::init(wallet, pool_config).unwrap(); - let profile = Arc::new(indy_profile); - let anoncreds = profile.anoncreds(); anoncreds - .prover_create_link_secret(DEFAULT_LINK_SECRET_ALIAS) + .prover_create_link_secret(wallet.as_ref(), DEFAULT_LINK_SECRET_ALIAS) .await .unwrap(); let connections = Arc::new(ServiceConnections::new( - Arc::clone(&profile), + ledger_read.clone(), + wallet.clone(), init_config.service_endpoint, )); let schemas = Arc::new(ServiceSchemas::new( - Arc::clone(&profile), + ledger_read.clone(), + ledger_write.clone(), + anoncreds, + wallet.clone(), config_issuer.institution_did.clone(), )); - let cred_defs = Arc::new(ServiceCredentialDefinitions::new(Arc::clone(&profile))); + let cred_defs = Arc::new(ServiceCredentialDefinitions::new( + ledger_read.clone(), + ledger_write.clone(), + anoncreds, + wallet.clone(), + )); let rev_regs = Arc::new(ServiceRevocationRegistries::new( - Arc::clone(&profile), + ledger_write.clone(), + anoncreds, + wallet.clone(), config_issuer.institution_did.clone(), )); let issuer = Arc::new(ServiceCredentialsIssuer::new( - Arc::clone(&profile), + anoncreds, + wallet.clone(), connections.clone(), )); let holder = Arc::new(ServiceCredentialsHolder::new( - Arc::clone(&profile), + ledger_read.clone(), + anoncreds, + wallet.clone(), connections.clone(), )); let verifier = Arc::new(ServiceVerifier::new( - Arc::clone(&profile), + ledger_read.clone(), + anoncreds, + wallet.clone(), connections.clone(), )); let prover = Arc::new(ServiceProver::new( - Arc::clone(&profile), + ledger_read.clone(), + anoncreds, + wallet.clone(), connections.clone(), )); Ok(Self { - profile, + ledger_read, + ledger_write, + anoncreds, + wallet, connections, schemas, cred_defs, diff --git a/agents/rust/aries-vcx-agent/src/services/connection.rs b/agents/rust/aries-vcx-agent/src/services/connection.rs index d349d0ec7f..dd47579705 100644 --- a/agents/rust/aries-vcx-agent/src/services/connection.rs +++ b/agents/rust/aries-vcx-agent/src/services/connection.rs @@ -1,7 +1,6 @@ use std::sync::{Arc, Mutex}; use aries_vcx::{ - core::profile::{modular_libs_profile::ModularLibsProfile, Profile}, handlers::util::AnyInvitation, messages::msg_fields::protocols::{ connection::{request::Request, response::Response}, @@ -10,7 +9,9 @@ use aries_vcx::{ protocols::connection::{ pairwise_info::PairwiseInfo, Connection, GenericConnection, State, ThinState, }, + utils::devsetup::DefaultIndyLedgerRead, }; +use aries_vcx_core::wallet::indy::IndySdkWallet; use url::Url; use crate::{ @@ -22,17 +23,23 @@ use crate::{ pub type ServiceEndpoint = Url; pub struct ServiceConnections { - profile: Arc, + ledger_read: Arc, + wallet: Arc, service_endpoint: ServiceEndpoint, connections: Arc>, } impl ServiceConnections { - pub fn new(profile: Arc, service_endpoint: ServiceEndpoint) -> Self { + pub fn new( + ledger_read: Arc, + wallet: Arc, + service_endpoint: ServiceEndpoint, + ) -> Self { Self { - profile, service_endpoint, connections: Arc::new(ObjectCache::new("connections")), + ledger_read, + wallet, } } @@ -40,7 +47,7 @@ impl ServiceConnections { &self, pw_info: Option, ) -> AgentResult { - let pw_info = pw_info.unwrap_or(PairwiseInfo::create(self.profile.wallet()).await?); + let pw_info = pw_info.unwrap_or(PairwiseInfo::create(self.wallet.as_ref()).await?); let inviter = Connection::new_inviter("".to_owned(), pw_info) .create_invitation(vec![], self.service_endpoint.clone()); let invite = inviter.get_invitation().clone(); @@ -52,9 +59,9 @@ impl ServiceConnections { } pub async fn receive_invitation(&self, invite: AnyInvitation) -> AgentResult { - let pairwise_info = PairwiseInfo::create(self.profile.wallet()).await?; + let pairwise_info = PairwiseInfo::create(self.wallet.as_ref()).await?; let invitee = Connection::new_invitee("".to_owned(), pairwise_info) - .accept_invitation(self.profile.ledger_read(), invite) + .accept_invitation(self.ledger_read.as_ref(), invite) .await?; let thread_id = invitee.thread_id().to_owned(); @@ -69,7 +76,7 @@ impl ServiceConnections { .await?; let request = invitee.get_request().clone(); invitee - .send_message(self.profile.wallet(), &request.into(), &HttpClient) + .send_message(self.wallet.as_ref(), &request.into(), &HttpClient) .await?; self.connections.insert(thread_id, invitee.into())?; Ok(()) @@ -94,7 +101,7 @@ impl ServiceConnections { let inviter = inviter .handle_request( - self.profile.wallet(), + self.wallet.as_ref(), request, self.service_endpoint.clone(), vec![], @@ -110,7 +117,7 @@ impl ServiceConnections { let inviter: Connection<_, _> = self.connections.get(thread_id)?.try_into()?; let response = inviter.get_connection_response_msg(); inviter - .send_message(self.profile.wallet(), &response.into(), &HttpClient) + .send_message(self.wallet.as_ref(), &response.into(), &HttpClient) .await?; self.connections.insert(thread_id, inviter.into())?; @@ -121,7 +128,7 @@ impl ServiceConnections { pub async fn accept_response(&self, thread_id: &str, response: Response) -> AgentResult<()> { let invitee: Connection<_, _> = self.connections.get(thread_id)?.try_into()?; let invitee = invitee - .handle_response(self.profile.wallet(), response) + .handle_response(self.wallet.as_ref(), response) .await?; self.connections.insert(thread_id, invitee.into())?; @@ -132,11 +139,7 @@ impl ServiceConnections { pub async fn send_ack(&self, thread_id: &str) -> AgentResult<()> { let invitee: Connection<_, _> = self.connections.get(thread_id)?.try_into()?; invitee - .send_message( - self.profile.wallet(), - &invitee.get_ack().into(), - &HttpClient, - ) + .send_message(self.wallet.as_ref(), &invitee.get_ack().into(), &HttpClient) .await?; self.connections.insert(thread_id, invitee.into())?; diff --git a/agents/rust/aries-vcx-agent/src/services/credential_definition.rs b/agents/rust/aries-vcx-agent/src/services/credential_definition.rs index 3b013615ec..afdaa47c6b 100644 --- a/agents/rust/aries-vcx-agent/src/services/credential_definition.rs +++ b/agents/rust/aries-vcx-agent/src/services/credential_definition.rs @@ -2,8 +2,9 @@ use std::sync::{Arc, Mutex}; use aries_vcx::{ common::primitives::credential_definition::{CredentialDef, CredentialDefConfig}, - core::profile::{modular_libs_profile::ModularLibsProfile, Profile}, + utils::devsetup::{DefaultIndyLedgerRead, DefaultIndyLedgerWrite}, }; +use aries_vcx_core::{anoncreds::credx_anoncreds::IndyCredxAnonCreds, wallet::indy::IndySdkWallet}; use crate::{ error::*, @@ -11,22 +12,34 @@ use crate::{ }; pub struct ServiceCredentialDefinitions { - profile: Arc, + ledger_read: Arc, + ledger_write: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, cred_defs: ObjectCache, } impl ServiceCredentialDefinitions { - pub fn new(profile: Arc) -> Self { + pub fn new( + ledger_read: Arc, + ledger_write: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, + ) -> Self { Self { - profile, cred_defs: ObjectCache::new("cred-defs"), + ledger_read, + ledger_write, + anoncreds, + wallet, } } pub async fn create_cred_def(&self, config: CredentialDefConfig) -> AgentResult { let cd = CredentialDef::create( - self.profile.ledger_read(), - self.profile.anoncreds(), + self.wallet.as_ref(), + self.ledger_read.as_ref(), + &self.anoncreds, "".to_string(), config, true, @@ -38,7 +51,11 @@ impl ServiceCredentialDefinitions { pub async fn publish_cred_def(&self, thread_id: &str) -> AgentResult<()> { let cred_def = self.cred_defs.get(thread_id)?; let cred_def = cred_def - .publish_cred_def(self.profile.ledger_read(), self.profile.ledger_write()) + .publish_cred_def( + self.wallet.as_ref(), + self.ledger_read.as_ref(), + self.ledger_write.as_ref(), + ) .await?; self.cred_defs.insert(thread_id, cred_def)?; Ok(()) diff --git a/agents/rust/aries-vcx-agent/src/services/holder.rs b/agents/rust/aries-vcx-agent/src/services/holder.rs index 6c9a9a39f0..53567055ce 100644 --- a/agents/rust/aries-vcx-agent/src/services/holder.rs +++ b/agents/rust/aries-vcx-agent/src/services/holder.rs @@ -1,7 +1,6 @@ use std::sync::Arc; use aries_vcx::{ - core::profile::{modular_libs_profile::ModularLibsProfile, Profile}, handlers::issuance::holder::Holder, messages::{ msg_fields::protocols::cred_issuance::v1::{ @@ -11,7 +10,9 @@ use aries_vcx::{ AriesMessage, }, protocols::{issuance::holder::state_machine::HolderState, SendClosure}, + utils::devsetup::DefaultIndyLedgerRead, }; +use aries_vcx_core::{anoncreds::credx_anoncreds::IndyCredxAnonCreds, wallet::indy::IndySdkWallet}; use crate::{ error::*, @@ -36,20 +37,26 @@ impl HolderWrapper { } pub struct ServiceCredentialsHolder { - profile: Arc, + ledger_read: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, creds_holder: ObjectCache, service_connections: Arc, } impl ServiceCredentialsHolder { pub fn new( - profile: Arc, + ledger_read: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, service_connections: Arc, ) -> Self { Self { - profile, service_connections, creds_holder: ObjectCache::new("creds-holder"), + ledger_read, + anoncreds, + wallet, } } @@ -69,7 +76,7 @@ impl ServiceCredentialsHolder { propose_credential: ProposeCredentialV1, ) -> AgentResult { let connection = self.service_connections.get_by_id(connection_id)?; - let wallet = self.profile.wallet(); + let wallet = self.wallet.as_ref(); let mut holder = Holder::create("")?; holder.set_proposal(propose_credential.clone())?; @@ -108,7 +115,7 @@ impl ServiceCredentialsHolder { (None, None) => return Err(AgentError::from_kind(AgentErrorKind::InvalidArguments)), }; let connection = self.service_connections.get_by_id(&connection_id)?; - let wallet = self.profile.wallet(); + let wallet = self.wallet.as_ref(); let pw_did = connection.pairwise_info().pw_did.to_string(); let send_closure: SendClosure = Box::new(|msg: AriesMessage| { @@ -116,8 +123,9 @@ impl ServiceCredentialsHolder { }); let msg_response = holder .prepare_credential_request( - self.profile.ledger_read(), - self.profile.anoncreds(), + self.wallet.as_ref(), + self.ledger_read.as_ref(), + &self.anoncreds, pw_did, ) .await?; @@ -136,12 +144,13 @@ impl ServiceCredentialsHolder { let mut holder = self.get_holder(thread_id)?; let connection_id = self.get_connection_id(thread_id)?; let connection = self.service_connections.get_by_id(&connection_id)?; - let wallet = self.profile.wallet(); + let wallet = self.wallet.as_ref(); holder .process_credential( - self.profile.ledger_read(), - self.profile.anoncreds(), + self.wallet.as_ref(), + self.ledger_read.as_ref(), + &self.anoncreds, msg_issue_credential.clone(), ) .await?; @@ -168,7 +177,7 @@ impl ServiceCredentialsHolder { pub async fn is_revokable(&self, thread_id: &str) -> AgentResult { self.get_holder(thread_id)? - .is_revokable(self.profile.ledger_read()) + .is_revokable(self.ledger_read.as_ref()) .await .map_err(|err| err.into()) } diff --git a/agents/rust/aries-vcx-agent/src/services/issuer.rs b/agents/rust/aries-vcx-agent/src/services/issuer.rs index 0e828b5fa6..06eeed9707 100644 --- a/agents/rust/aries-vcx-agent/src/services/issuer.rs +++ b/agents/rust/aries-vcx-agent/src/services/issuer.rs @@ -1,7 +1,6 @@ use std::sync::Arc; use aries_vcx::{ - core::profile::{modular_libs_profile::ModularLibsProfile, Profile}, handlers::{issuance::issuer::Issuer, util::OfferInfo}, messages::{ msg_fields::protocols::cred_issuance::v1::{ @@ -12,6 +11,7 @@ use aries_vcx::{ }, protocols::{issuance::issuer::state_machine::IssuerState, SendClosure}, }; +use aries_vcx_core::{anoncreds::credx_anoncreds::IndyCredxAnonCreds, wallet::indy::IndySdkWallet}; use crate::{ error::*, @@ -36,20 +36,23 @@ impl IssuerWrapper { } pub struct ServiceCredentialsIssuer { - profile: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, creds_issuer: ObjectCache, service_connections: Arc, } impl ServiceCredentialsIssuer { pub fn new( - profile: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, service_connections: Arc, ) -> Self { Self { - profile, service_connections, creds_issuer: ObjectCache::new("creds-issuer"), + anoncreds, + wallet, } } @@ -89,10 +92,10 @@ impl ServiceCredentialsIssuer { }; let connection = self.service_connections.get_by_id(&connection_id)?; issuer - .build_credential_offer_msg(self.profile.anoncreds(), offer_info, None) + .build_credential_offer_msg(self.wallet.as_ref(), &self.anoncreds, offer_info, None) .await?; - let wallet = self.profile.wallet(); + let wallet = self.wallet.as_ref(); let send_closure: SendClosure = Box::new(|msg: AriesMessage| { Box::pin(async move { connection.send_message(wallet, &msg, &HttpClient).await }) @@ -143,13 +146,15 @@ impl ServiceCredentialsIssuer { } = self.creds_issuer.get(thread_id)?; let connection = self.service_connections.get_by_id(&connection_id)?; - let wallet = self.profile.wallet(); + let wallet = self.wallet.as_ref(); let send_closure: SendClosure = Box::new(|msg: AriesMessage| { Box::pin(async move { connection.send_message(wallet, &msg, &HttpClient).await }) }); - issuer.build_credential(self.profile.anoncreds()).await?; + issuer + .build_credential(self.wallet.as_ref(), &self.anoncreds) + .await?; match issuer.get_state() { IssuerState::Failed => { let problem_report = issuer.get_problem_report()?; diff --git a/agents/rust/aries-vcx-agent/src/services/prover.rs b/agents/rust/aries-vcx-agent/src/services/prover.rs index 7f9f92765e..6c9219c97c 100644 --- a/agents/rust/aries-vcx-agent/src/services/prover.rs +++ b/agents/rust/aries-vcx-agent/src/services/prover.rs @@ -1,7 +1,6 @@ use std::{collections::HashMap, sync::Arc}; use aries_vcx::{ - core::profile::{modular_libs_profile::ModularLibsProfile, Profile}, handlers::{ proof_presentation::{prover::Prover, types::SelectedCredentials}, util::PresentationProposalData, @@ -13,7 +12,9 @@ use aries_vcx::{ AriesMessage, }, protocols::{proof_presentation::prover::state_machine::ProverState, SendClosure}, + utils::devsetup::DefaultIndyLedgerRead, }; +use aries_vcx_core::{anoncreds::credx_anoncreds::IndyCredxAnonCreds, wallet::indy::IndySdkWallet}; use serde_json::Value; use super::connection::ServiceConnections; @@ -39,20 +40,26 @@ impl ProverWrapper { } pub struct ServiceProver { - profile: Arc, + ledger_read: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, provers: ObjectCache, service_connections: Arc, } impl ServiceProver { pub fn new( - profile: Arc, + ledger_read: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, service_connections: Arc, ) -> Self { Self { - profile, service_connections, provers: ObjectCache::new("provers"), + ledger_read, + anoncreds, + wallet, } } @@ -72,7 +79,7 @@ impl ServiceProver { tails_dir: Option<&str>, ) -> AgentResult { let credentials = prover - .retrieve_credentials(self.profile.anoncreds()) + .retrieve_credentials(self.wallet.as_ref(), &self.anoncreds) .await?; let mut res_credentials = SelectedCredentials::default(); @@ -109,7 +116,7 @@ impl ServiceProver { let connection = self.service_connections.get_by_id(connection_id)?; let mut prover = Prover::create("")?; - let wallet = self.profile.wallet(); + let wallet = self.wallet.as_ref(); let send_closure: SendClosure = Box::new(|msg: AriesMessage| { Box::pin(async move { connection.send_message(wallet, &msg, &HttpClient).await }) @@ -145,14 +152,15 @@ impl ServiceProver { .await?; prover .generate_presentation( - self.profile.ledger_read(), - self.profile.anoncreds(), + self.wallet.as_ref(), + self.ledger_read.as_ref(), + &self.anoncreds, credentials, HashMap::new(), ) .await?; - let wallet = self.profile.wallet(); + let wallet = self.wallet.as_ref(); let send_closure: SendClosure = Box::new(|msg: AriesMessage| { Box::pin(async move { connection.send_message(wallet, &msg, &HttpClient).await }) diff --git a/agents/rust/aries-vcx-agent/src/services/revocation_registry.rs b/agents/rust/aries-vcx-agent/src/services/revocation_registry.rs index 312f20c491..68f73171de 100644 --- a/agents/rust/aries-vcx-agent/src/services/revocation_registry.rs +++ b/agents/rust/aries-vcx-agent/src/services/revocation_registry.rs @@ -5,8 +5,9 @@ use std::{ use aries_vcx::{ common::primitives::revocation_registry::RevocationRegistry, - core::profile::{modular_libs_profile::ModularLibsProfile, Profile}, + utils::devsetup::DefaultIndyLedgerWrite, }; +use aries_vcx_core::{anoncreds::credx_anoncreds::IndyCredxAnonCreds, wallet::indy::IndySdkWallet}; use crate::{ error::*, @@ -14,17 +15,26 @@ use crate::{ }; pub struct ServiceRevocationRegistries { - profile: Arc, + ledger_write: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, issuer_did: String, rev_regs: ObjectCache, } impl ServiceRevocationRegistries { - pub fn new(profile: Arc, issuer_did: String) -> Self { + pub fn new( + ledger_write: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, + issuer_did: String, + ) -> Self { Self { - profile, issuer_did, rev_regs: ObjectCache::new("rev-regs"), + ledger_write, + anoncreds, + wallet, } } @@ -40,7 +50,8 @@ impl ServiceRevocationRegistries { pub async fn create_rev_reg(&self, cred_def_id: &str, max_creds: u32) -> AgentResult { let rev_reg = RevocationRegistry::create( - self.profile.anoncreds(), + self.wallet.as_ref(), + &self.anoncreds, &self.issuer_did, cred_def_id, "/tmp", @@ -67,7 +78,11 @@ impl ServiceRevocationRegistries { pub async fn publish_rev_reg(&self, thread_id: &str, tails_url: &str) -> AgentResult<()> { let mut rev_reg = self.rev_regs.get(thread_id)?; rev_reg - .publish_revocation_primitives(self.profile.ledger_write(), tails_url) + .publish_revocation_primitives( + self.wallet.as_ref(), + self.ledger_write.as_ref(), + tails_url, + ) .await?; self.rev_regs.insert(thread_id, rev_reg)?; Ok(()) @@ -76,7 +91,7 @@ impl ServiceRevocationRegistries { pub async fn revoke_credential_locally(&self, id: &str, cred_rev_id: &str) -> AgentResult<()> { let rev_reg = self.rev_regs.get(id)?; rev_reg - .revoke_credential_local(self.profile.anoncreds(), cred_rev_id) + .revoke_credential_local(self.wallet.as_ref(), &self.anoncreds, cred_rev_id) .await?; Ok(()) } @@ -85,8 +100,9 @@ impl ServiceRevocationRegistries { let rev_reg = self.rev_regs.get(id)?; rev_reg .publish_local_revocations( - self.profile.anoncreds(), - self.profile.ledger_write(), + self.wallet.as_ref(), + &self.anoncreds, + self.ledger_write.as_ref(), &self.issuer_did, ) .await?; diff --git a/agents/rust/aries-vcx-agent/src/services/schema.rs b/agents/rust/aries-vcx-agent/src/services/schema.rs index f7d238ff60..3826c6d1a7 100644 --- a/agents/rust/aries-vcx-agent/src/services/schema.rs +++ b/agents/rust/aries-vcx-agent/src/services/schema.rs @@ -2,9 +2,12 @@ use std::sync::{Arc, Mutex}; use aries_vcx::{ common::primitives::credential_schema::Schema, - core::profile::{modular_libs_profile::ModularLibsProfile, Profile}, + utils::devsetup::{DefaultIndyLedgerRead, DefaultIndyLedgerWrite}, +}; +use aries_vcx_core::{ + anoncreds::credx_anoncreds::IndyCredxAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, + wallet::indy::IndySdkWallet, }; -use aries_vcx_core::ledger::base_ledger::AnoncredsLedgerRead; use crate::{ error::*, @@ -12,17 +15,29 @@ use crate::{ }; pub struct ServiceSchemas { - profile: Arc, + ledger_read: Arc, + ledger_write: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, issuer_did: String, schemas: ObjectCache, } impl ServiceSchemas { - pub fn new(profile: Arc, issuer_did: String) -> Self { + pub fn new( + ledger_read: Arc, + ledger_write: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, + issuer_did: String, + ) -> Self { Self { - profile, issuer_did, schemas: ObjectCache::new("schemas"), + ledger_read, + ledger_write, + anoncreds, + wallet, } } @@ -33,7 +48,7 @@ impl ServiceSchemas { attributes: &Vec, ) -> AgentResult { let schema = Schema::create( - self.profile.anoncreds(), + &self.anoncreds, "", &self.issuer_did, name, @@ -46,13 +61,15 @@ impl ServiceSchemas { pub async fn publish_schema(&self, thread_id: &str) -> AgentResult<()> { let schema = self.schemas.get(thread_id)?; - let schema = schema.publish(self.profile.ledger_write()).await?; + let schema = schema + .publish(self.wallet.as_ref(), self.ledger_write.as_ref()) + .await?; self.schemas.insert(thread_id, schema)?; Ok(()) } pub async fn schema_json(&self, thread_id: &str) -> AgentResult { - let ledger = self.profile.ledger_read(); + let ledger = self.ledger_read.as_ref(); Ok(ledger.get_schema(thread_id, None).await?) } diff --git a/agents/rust/aries-vcx-agent/src/services/verifier.rs b/agents/rust/aries-vcx-agent/src/services/verifier.rs index 2fc10cf15b..3240120785 100644 --- a/agents/rust/aries-vcx-agent/src/services/verifier.rs +++ b/agents/rust/aries-vcx-agent/src/services/verifier.rs @@ -2,7 +2,6 @@ use std::sync::Arc; use aries_vcx::{ common::proofs::proof_request::PresentationRequestData, - core::profile::{modular_libs_profile::ModularLibsProfile, Profile}, handlers::proof_presentation::verifier::Verifier, messages::{ msg_fields::protocols::present_proof::{ @@ -16,7 +15,9 @@ use aries_vcx::{ }, SendClosure, }, + utils::devsetup::DefaultIndyLedgerRead, }; +use aries_vcx_core::{anoncreds::credx_anoncreds::IndyCredxAnonCreds, wallet::indy::IndySdkWallet}; use super::connection::ServiceConnections; use crate::{ @@ -41,20 +42,26 @@ impl VerifierWrapper { } pub struct ServiceVerifier { - profile: Arc, + ledger_read: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, verifiers: ObjectCache, service_connections: Arc, } impl ServiceVerifier { pub fn new( - profile: Arc, + ledger_read: Arc, + anoncreds: IndyCredxAnonCreds, + wallet: Arc, service_connections: Arc, ) -> Self { Self { - profile, service_connections, verifiers: ObjectCache::new("verifiers"), + ledger_read, + anoncreds, + wallet, } } @@ -71,7 +78,7 @@ impl ServiceVerifier { Verifier::create_from_request("".to_string(), &request)? }; - let wallet = self.profile.wallet(); + let wallet = self.wallet.as_ref(); let send_closure: SendClosure = Box::new(|msg: AriesMessage| { Box::pin(async move { connection.send_message(wallet, &msg, &HttpClient).await }) @@ -103,18 +110,14 @@ impl ServiceVerifier { connection_id, } = self.verifiers.get(thread_id)?; let connection = self.service_connections.get_by_id(&connection_id)?; - let wallet = self.profile.wallet(); + let wallet = self.wallet.as_ref(); let send_closure: SendClosure = Box::new(|msg: AriesMessage| { Box::pin(async move { connection.send_message(wallet, &msg, &HttpClient).await }) }); let message = verifier - .verify_presentation( - self.profile.ledger_read(), - self.profile.anoncreds(), - presentation, - ) + .verify_presentation(self.ledger_read.as_ref(), &self.anoncreds, presentation) .await?; send_closure(message).await?; self.verifiers diff --git a/aries_vcx/src/common/anoncreds.rs b/aries_vcx/src/common/anoncreds.rs index 98c264a04a..e2cfcc2625 100644 --- a/aries_vcx/src/common/anoncreds.rs +++ b/aries_vcx/src/common/anoncreds.rs @@ -20,9 +20,9 @@ pub mod integration_tests { async fn test_pool_returns_error_if_proof_request_is_malformed() { run_setup!(|setup| async move { let proof_req = "{"; - let anoncreds = setup.profile.anoncreds(); + let anoncreds = setup.anoncreds; let result = anoncreds - .prover_get_credentials_for_proof_req(proof_req) + .prover_get_credentials_for_proof_req(&setup.wallet, proof_req) .await; assert_eq!( result.unwrap_err().kind(), @@ -52,14 +52,14 @@ pub mod integration_tests { }) .to_string(); - let anoncreds = setup.profile.anoncreds(); + let anoncreds = setup.anoncreds; let _result = anoncreds - .prover_get_credentials_for_proof_req(&proof_req) + .prover_get_credentials_for_proof_req(&setup.wallet, &proof_req) .await .unwrap(); let result_malformed_json = anoncreds - .prover_get_credentials_for_proof_req("{}") + .prover_get_credentials_for_proof_req(&setup.wallet, "{}") .await .unwrap_err(); assert_eq!( @@ -96,9 +96,9 @@ pub mod integration_tests { }) .to_string(); - let anoncreds = setup.profile.anoncreds(); + let anoncreds = setup.anoncreds; let _result = anoncreds - .prover_get_credentials_for_proof_req(&proof_req) + .prover_get_credentials_for_proof_req(&setup.wallet, &proof_req) .await .unwrap(); }) @@ -110,41 +110,46 @@ pub mod integration_tests { async fn test_pool_revoke_credential() { run_setup!(|setup| async move { let schema = create_and_write_test_schema( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, crate::utils::constants::DEFAULT_SCHEMA_ATTRS, ) .await; let cred_def = create_and_write_test_cred_def( - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, &schema.schema_id, true, ) .await; let rev_reg = create_and_publish_test_rev_reg( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, &cred_def.get_cred_def_id(), ) .await; let cred_id = create_and_write_credential( - setup.profile.anoncreds(), - setup.profile.anoncreds(), + &setup.wallet, + &setup.wallet, + &setup.anoncreds, + &setup.anoncreds, &setup.institution_did, &cred_def, Some(&rev_reg), ) .await; - let cred_rev_id = get_cred_rev_id(setup.profile.anoncreds(), &cred_id) + let cred_rev_id = get_cred_rev_id(&setup.wallet, &setup.anoncreds, &cred_id) .await .unwrap(); - let ledger = setup.profile.ledger_read(); + let ledger = setup.ledger_read; let (_, first_rev_reg_delta, first_timestamp) = ledger .get_rev_reg_delta_json(&rev_reg.rev_reg_id, None, None) @@ -159,10 +164,11 @@ pub mod integration_tests { assert_eq!(first_rev_reg_delta, test_same_delta); assert_eq!(first_timestamp, test_same_timestamp); - let anoncreds = setup.profile.anoncreds(); + let anoncreds = &setup.anoncreds; anoncreds .revoke_credential_local( + &setup.wallet, get_temp_dir_path().to_str().unwrap(), &rev_reg.rev_reg_id, &cred_rev_id, @@ -172,8 +178,9 @@ pub mod integration_tests { rev_reg .publish_local_revocations( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, ) .await diff --git a/aries_vcx/src/common/credentials/encoding.rs b/aries_vcx/src/common/credentials/encoding.rs index d16cc0915a..5f31f48ffb 100644 --- a/aries_vcx/src/common/credentials/encoding.rs +++ b/aries_vcx/src/common/credentials/encoding.rs @@ -116,7 +116,7 @@ pub mod unit_tests { #[test] fn test_encode_with_several_attributes_success() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let expected = json!({ "address2": { @@ -155,7 +155,7 @@ pub mod unit_tests { #[test] fn test_encode_with_one_attribute_success() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let expected = json!({ "address2": { @@ -178,7 +178,7 @@ pub mod unit_tests { #[test] fn test_encode_with_aries_format_several_attributes_success() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let expected = json!({ "address2": { @@ -219,7 +219,7 @@ pub mod unit_tests { #[test] fn test_encode_with_new_format_several_attributes_success() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let expected = json!({ "address2": { @@ -259,7 +259,7 @@ pub mod unit_tests { #[test] fn test_encode_with_new_format_one_attribute_success() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let expected = json!({ "address2": { @@ -282,7 +282,7 @@ pub mod unit_tests { #[test] fn test_encode_with_mixed_format_several_attributes_success() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); // for reference....expectation is encode_attributes returns this: @@ -324,7 +324,7 @@ pub mod unit_tests { #[test] fn test_encode_bad_format_returns_error() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); static BAD_TEST_CREDENTIAL_DATA: &str = r#"{"format doesnt make sense"}"#; @@ -333,7 +333,7 @@ pub mod unit_tests { #[test] fn test_encode_old_format_empty_array_error() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); static BAD_TEST_CREDENTIAL_DATA: &str = r#"{"address2":[]}"#; @@ -342,7 +342,7 @@ pub mod unit_tests { #[test] fn test_encode_empty_field() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let expected = json!({ "empty_field": { diff --git a/aries_vcx/src/common/credentials/mod.rs b/aries_vcx/src/common/credentials/mod.rs index 7f734580c7..5efe5ffd21 100644 --- a/aries_vcx/src/common/credentials/mod.rs +++ b/aries_vcx/src/common/credentials/mod.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, + wallet::base_wallet::BaseWallet, }; use time::OffsetDateTime; @@ -20,8 +21,12 @@ struct ProverCredential { cred_rev_id: Option, } -pub async fn get_cred_rev_id(anoncreds: &impl BaseAnonCreds, cred_id: &str) -> VcxResult { - let cred_json = anoncreds.prover_get_credential(cred_id).await?; +pub async fn get_cred_rev_id( + wallet: &impl BaseWallet, + anoncreds: &impl BaseAnonCreds, + cred_id: &str, +) -> VcxResult { + let cred_json = anoncreds.prover_get_credential(wallet, cred_id).await?; let prover_cred = serde_json::from_str::(&cred_json).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, @@ -62,44 +67,48 @@ mod integration_tests { async fn test_pool_prover_get_credential() { run_setup!(|setup| async move { let schema = create_and_write_test_schema( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, crate::utils::constants::DEFAULT_SCHEMA_ATTRS, ) .await; let cred_def = create_and_write_test_cred_def( - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, &schema.schema_id, true, ) .await; let rev_reg = create_and_publish_test_rev_reg( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, &cred_def.get_cred_def_id(), ) .await; let cred_id = create_and_write_credential( - setup.profile.anoncreds(), - setup.profile.anoncreds(), + &setup.wallet, + &setup.wallet, + &setup.anoncreds, + &setup.anoncreds, &setup.institution_did, &cred_def, Some(&rev_reg), ) .await; - let cred_rev_id = get_cred_rev_id(setup.profile.anoncreds(), &cred_id) + let cred_rev_id = get_cred_rev_id(&setup.wallet, &setup.anoncreds, &cred_id) .await .unwrap(); let cred_json = setup - .profile - .anoncreds() - .prover_get_credential(&cred_id) + .anoncreds + .prover_get_credential(&setup.wallet, &cred_id) .await .unwrap(); let prover_cred = serde_json::from_str::(&cred_json).unwrap(); @@ -117,52 +126,55 @@ mod integration_tests { async fn test_pool_is_cred_revoked() { run_setup!(|setup| async move { let schema = create_and_write_test_schema( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, crate::utils::constants::DEFAULT_SCHEMA_ATTRS, ) .await; let cred_def = create_and_write_test_cred_def( - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, &schema.schema_id, true, ) .await; let rev_reg = create_and_publish_test_rev_reg( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, &cred_def.get_cred_def_id(), ) .await; let cred_id = create_and_write_credential( - setup.profile.anoncreds(), - setup.profile.anoncreds(), + &setup.wallet, + &setup.wallet, + &setup.anoncreds, + &setup.anoncreds, &setup.institution_did, &cred_def, Some(&rev_reg), ) .await; - let cred_rev_id = get_cred_rev_id(setup.profile.anoncreds(), &cred_id) + let cred_rev_id = get_cred_rev_id(&setup.wallet, &setup.anoncreds, &cred_id) .await .unwrap(); - assert!(!is_cred_revoked( - setup.profile.ledger_read(), - &rev_reg.rev_reg_id, - &cred_rev_id - ) - .await - .unwrap()); + assert!( + !is_cred_revoked(&setup.ledger_read, &rev_reg.rev_reg_id, &cred_rev_id) + .await + .unwrap() + ); setup - .profile - .anoncreds() + .anoncreds .revoke_credential_local( + &setup.wallet, &rev_reg.get_tails_dir(), &rev_reg.rev_reg_id, &cred_rev_id, @@ -171,8 +183,9 @@ mod integration_tests { .unwrap(); rev_reg .publish_local_revocations( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, ) .await @@ -180,13 +193,11 @@ mod integration_tests { std::thread::sleep(std::time::Duration::from_millis(500)); - assert!(is_cred_revoked( - setup.profile.ledger_read(), - &rev_reg.rev_reg_id, - &cred_rev_id - ) - .await - .unwrap()); + assert!( + is_cred_revoked(&setup.ledger_read, &rev_reg.rev_reg_id, &cred_rev_id) + .await + .unwrap() + ); }) .await; } diff --git a/aries_vcx/src/common/keys.rs b/aries_vcx/src/common/keys.rs index 79f1b4f724..ae6973efa2 100644 --- a/aries_vcx/src/common/keys.rs +++ b/aries_vcx/src/common/keys.rs @@ -13,7 +13,7 @@ pub async fn rotate_verkey_apply( temp_vk: &str, ) -> VcxResult<()> { let nym_result = indy_ledger_write - .publish_nym(did, did, Some(temp_vk), None, None) + .publish_nym(wallet, did, did, Some(temp_vk), None, None) .await?; let nym_result_json: Value = serde_json::from_str(&nym_result).map_err(|err| { diff --git a/aries_vcx/src/common/ledger/service_didsov.rs b/aries_vcx/src/common/ledger/service_didsov.rs index a028ebdc6c..6960ba44c9 100644 --- a/aries_vcx/src/common/ledger/service_didsov.rs +++ b/aries_vcx/src/common/ledger/service_didsov.rs @@ -63,12 +63,10 @@ impl Default for EndpointDidSov { #[cfg(test)] #[allow(clippy::unwrap_used)] mod unit_tests { + use agency_client::testing::test_utils::SetupMocks; use diddoc_legacy::aries::diddoc::test_utils::{_routing_keys, _service_endpoint}; - use crate::{ - common::ledger::service_didsov::{DidSovServiceType, EndpointDidSov}, - utils::devsetup::SetupEmpty, - }; + use crate::common::ledger::service_didsov::{DidSovServiceType, EndpointDidSov}; #[test] fn test_service_comparison() { @@ -95,7 +93,7 @@ mod unit_tests { #[test] fn test_didsov_service_serialization() { - SetupEmpty::init(); + SetupMocks::init(); let service1 = EndpointDidSov::create() .set_service_endpoint(_service_endpoint()) .set_routing_keys(Some(_routing_keys())) @@ -118,7 +116,7 @@ mod unit_tests { #[test] fn test_didsov_service_deserialization() { - SetupEmpty::init(); + SetupMocks::init(); let data = json!({ "endpoint": "http://localhost:8080", diff --git a/aries_vcx/src/common/ledger/transactions.rs b/aries_vcx/src/common/ledger/transactions.rs index 3f34c8723c..d08354015e 100644 --- a/aries_vcx/src/common/ledger/transactions.rs +++ b/aries_vcx/src/common/ledger/transactions.rs @@ -92,7 +92,7 @@ pub async fn add_new_did( let (did, verkey) = wallet.create_and_store_my_did(None, None).await?; let res = indy_ledger_write - .publish_nym(submitter_did, &did, Some(&verkey), None, role) + .publish_nym(wallet, submitter_did, &did, Some(&verkey), None, role) .await?; check_response(&res)?; @@ -284,6 +284,7 @@ pub async fn parse_legacy_endpoint_attrib( } pub async fn write_endorser_did( + wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, submitter_did: &str, target_did: &str, @@ -292,6 +293,7 @@ pub async fn write_endorser_did( ) -> VcxResult { let res = indy_ledger_write .write_did( + wallet, submitter_did, target_did, target_vk, @@ -304,33 +306,40 @@ pub async fn write_endorser_did( } pub async fn write_endpoint_legacy( + wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, did: &str, service: &AriesService, ) -> VcxResult { let attrib_json = json!({ "service": service }).to_string(); - let res = indy_ledger_write.add_attr(did, &attrib_json).await?; + 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: &str, service: &EndpointDidSov, ) -> VcxResult { let attrib_json = json!({ "endpoint": service }).to_string(); - let res = indy_ledger_write.add_attr(did, &attrib_json).await?; + let res = indy_ledger_write + .add_attr(wallet, did, &attrib_json) + .await?; check_response(&res)?; Ok(res) } pub async fn add_attr( + wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, did: &str, attr: &str, ) -> VcxResult<()> { - let res = indy_ledger_write.add_attr(did, attr).await?; + let res = indy_ledger_write.add_attr(wallet, did, attr).await?; check_response(&res) } @@ -349,12 +358,13 @@ pub async fn get_attr( } pub async fn clear_attr( + wallet: &impl BaseWallet, indy_ledger_write: &impl IndyLedgerWrite, did: &str, attr_name: &str, ) -> VcxResult { indy_ledger_write - .add_attr(did, &json!({ attr_name: Value::Null }).to_string()) + .add_attr(wallet, did, &json!({ attr_name: Value::Null }).to_string()) .await .map_err(|err| err.into()) } diff --git a/aries_vcx/src/common/primitives/credential_definition.rs b/aries_vcx/src/common/primitives/credential_definition.rs index edffa25892..43c88457ec 100644 --- a/aries_vcx/src/common/primitives/credential_definition.rs +++ b/aries_vcx/src/common/primitives/credential_definition.rs @@ -2,6 +2,7 @@ use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, errors::error::AriesVcxCoreErrorKind, ledger::base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite}, + wallet::base_wallet::BaseWallet, }; use crate::{ @@ -93,6 +94,7 @@ async fn _try_get_cred_def_from_ledger( } impl CredentialDef { pub async fn create( + wallet: &impl BaseWallet, ledger_read: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, source_id: String, @@ -113,6 +115,7 @@ impl CredentialDef { .get_schema(&schema_id, Some(&issuer_did)) .await?; let (cred_def_id, cred_def_json) = generate_cred_def( + wallet, anoncreds, &issuer_did, &schema_json, @@ -147,6 +150,7 @@ impl CredentialDef { pub async fn publish_cred_def( self, + wallet: &impl BaseWallet, ledger_read: &impl AnoncredsLedgerRead, ledger_write: &impl AnoncredsLedgerWrite, ) -> VcxResult { @@ -167,7 +171,7 @@ impl CredentialDef { )); } ledger_write - .publish_cred_def(&self.cred_def_json, &self.issuer_did) + .publish_cred_def(wallet, &self.cred_def_json, &self.issuer_did) .await?; Ok(Self { state: PublicEntityStateType::Published, @@ -230,6 +234,7 @@ impl CredentialDef { } pub async fn generate_cred_def( + wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, issuer_did: &str, schema_json: &str, @@ -252,6 +257,7 @@ pub async fn generate_cred_def( anoncreds .issuer_create_and_store_credential_def( + wallet, issuer_did, schema_json, tag, @@ -285,22 +291,24 @@ pub mod integration_tests { async fn test_pool_create_cred_def_real() { run_setup!(|setup| async move { let schema = create_and_write_test_schema( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; - let ledger_read = setup.profile.ledger_read(); - let ledger_write = setup.profile.ledger_write(); + let ledger_read = setup.ledger_read; + let ledger_write = &setup.ledger_write; let schema_json = ledger_read .get_schema(&schema.schema_id, None) .await .unwrap(); let (cred_def_id, cred_def_json_local) = generate_cred_def( - setup.profile.anoncreds(), + &setup.wallet, + &setup.anoncreds, &setup.institution_did, &schema_json, "tag_1", @@ -311,7 +319,7 @@ pub mod integration_tests { .unwrap(); ledger_write - .publish_cred_def(&cred_def_json_local, &setup.institution_did) + .publish_cred_def(&setup.wallet, &cred_def_json_local, &setup.institution_did) .await .unwrap(); @@ -333,21 +341,23 @@ pub mod integration_tests { async fn test_pool_create_rev_reg_def() { run_setup!(|setup| async move { let schema = create_and_write_test_schema( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; - let ledger_read = setup.profile.ledger_read(); - let ledger_write = setup.profile.ledger_write(); + let ledger_read = &setup.ledger_read; + let ledger_write = &setup.ledger_write; let schema_json = ledger_read .get_schema(&schema.schema_id, None) .await .unwrap(); let (cred_def_id, cred_def_json) = generate_cred_def( - setup.profile.anoncreds(), + &setup.wallet, + &setup.anoncreds, &setup.institution_did, &schema_json, "tag_1", @@ -357,14 +367,15 @@ pub mod integration_tests { .await .unwrap(); ledger_write - .publish_cred_def(&cred_def_json, &setup.institution_did) + .publish_cred_def(&setup.wallet, &cred_def_json, &setup.institution_did) .await .unwrap(); let path = get_temp_dir_path(); let (rev_reg_def_id, rev_reg_def_json, rev_reg_entry_json) = generate_rev_reg( - setup.profile.anoncreds(), + &setup.wallet, + &setup.anoncreds, &setup.institution_did, &cred_def_id, path.to_str().unwrap(), @@ -374,11 +385,20 @@ pub mod integration_tests { .await .unwrap(); ledger_write - .publish_rev_reg_def(&json!(rev_reg_def_json).to_string(), &setup.institution_did) + .publish_rev_reg_def( + &setup.wallet, + &json!(rev_reg_def_json).to_string(), + &setup.institution_did, + ) .await .unwrap(); ledger_write - .publish_rev_reg_delta(&rev_reg_def_id, &rev_reg_entry_json, &setup.institution_did) + .publish_rev_reg_delta( + &setup.wallet, + &rev_reg_def_id, + &rev_reg_entry_json, + &setup.institution_did, + ) .await .unwrap(); }) diff --git a/aries_vcx/src/common/primitives/credential_schema.rs b/aries_vcx/src/common/primitives/credential_schema.rs index e19b730bc1..113ac5ca44 100644 --- a/aries_vcx/src/common/primitives/credential_schema.rs +++ b/aries_vcx/src/common/primitives/credential_schema.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite}, + wallet::base_wallet::BaseWallet, }; use super::credential_definition::PublicEntityStateType; @@ -78,11 +79,15 @@ impl Schema { self.submitter_did.clone() } - pub async fn publish(self, ledger: &impl AnoncredsLedgerWrite) -> VcxResult { + pub async fn publish( + self, + wallet: &impl BaseWallet, + ledger: &impl AnoncredsLedgerWrite, + ) -> VcxResult { trace!("Schema::publish >>>"); ledger - .publish_schema(&self.schema_json, &self.submitter_did, None) + .publish_schema(wallet, &self.schema_json, &self.submitter_did, None) .await?; Ok(Self { diff --git a/aries_vcx/src/common/primitives/revocation_registry.rs b/aries_vcx/src/common/primitives/revocation_registry.rs index 3c0cf77b55..1318947729 100644 --- a/aries_vcx/src/common/primitives/revocation_registry.rs +++ b/aries_vcx/src/common/primitives/revocation_registry.rs @@ -1,6 +1,6 @@ use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, errors::error::AriesVcxCoreErrorKind, - ledger::base_ledger::AnoncredsLedgerWrite, + ledger::base_ledger::AnoncredsLedgerWrite, wallet::base_wallet::BaseWallet, }; use super::credential_definition::PublicEntityStateType; @@ -22,6 +22,7 @@ pub struct RevocationRegistry { impl RevocationRegistry { pub async fn create( + wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, issuer_did: &str, cred_def_id: &str, @@ -39,6 +40,7 @@ impl RevocationRegistry { tag ); let (rev_reg_id, rev_reg_def, rev_reg_entry) = generate_rev_reg( + wallet, anoncreds, issuer_did, cred_def_id, @@ -96,6 +98,7 @@ impl RevocationRegistry { pub async fn publish_rev_reg_def( &mut self, + wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerWrite, issuer_did: &str, tails_url: &str, @@ -109,7 +112,7 @@ impl RevocationRegistry { ); self.rev_reg_def.value.tails_location = String::from(tails_url); ledger - .publish_rev_reg_def(&json!(self.rev_reg_def).to_string(), issuer_did) + .publish_rev_reg_def(wallet, &json!(self.rev_reg_def).to_string(), issuer_did) .await .map_err(|err| { err.map( @@ -123,6 +126,7 @@ impl RevocationRegistry { pub async fn publish_rev_reg_delta( &mut self, + wallet: &impl BaseWallet, ledger_write: &impl AnoncredsLedgerWrite, issuer_did: &str, ) -> VcxResult<()> { @@ -132,7 +136,7 @@ impl RevocationRegistry { self.rev_reg_id ); ledger_write - .publish_rev_reg_delta(&self.rev_reg_id, &self.rev_reg_entry, issuer_did) + .publish_rev_reg_delta(wallet, &self.rev_reg_id, &self.rev_reg_entry, issuer_did) .await .map_err(|err| { err.map( @@ -146,6 +150,7 @@ impl RevocationRegistry { pub async fn publish_revocation_primitives( &mut self, + wallet: &impl BaseWallet, ledger_write: &impl AnoncredsLedgerWrite, tails_url: &str, ) -> VcxResult<()> { @@ -153,26 +158,29 @@ impl RevocationRegistry { "RevocationRegistry::publish_revocation_primitives >>> tails_url: {}", tails_url ); - self.publish_built_rev_reg_def(ledger_write, tails_url) + self.publish_built_rev_reg_def(wallet, ledger_write, tails_url) .await?; - self.publish_built_rev_reg_delta(ledger_write).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(ledger_write, issuer_did).await?; + 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<()> { @@ -180,7 +188,7 @@ impl RevocationRegistry { if self.was_rev_reg_def_published() { info!("No unpublished revocation registry definition found, nothing to publish") } else { - self.publish_rev_reg_def(ledger_write, issuer_did, tails_url) + self.publish_rev_reg_def(wallet, ledger_write, issuer_did, tails_url) .await?; } Ok(()) @@ -206,24 +214,29 @@ impl RevocationRegistry { pub async fn revoke_credential_local( &self, + wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, cred_rev_id: &str, ) -> VcxResult<()> { anoncreds - .revoke_credential_local(&self.tails_dir, &self.rev_reg_id, cred_rev_id) + .revoke_credential_local(wallet, &self.tails_dir, &self.rev_reg_id, cred_rev_id) .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: &str, ) -> VcxResult<()> { - if let Some(delta) = anoncreds.get_rev_reg_delta(&self.rev_reg_id).await? { + if let Some(delta) = anoncreds + .get_rev_reg_delta(wallet, &self.rev_reg_id) + .await? + { ledger_write - .publish_rev_reg_delta(&self.rev_reg_id, &delta, submitter_did) + .publish_rev_reg_delta(wallet, &self.rev_reg_id, &delta, submitter_did) .await?; info!( @@ -231,7 +244,10 @@ impl RevocationRegistry { self.rev_reg_id ); - match anoncreds.clear_rev_reg_delta(&self.rev_reg_id).await { + match anoncreds + .clear_rev_reg_delta(wallet, &self.rev_reg_id) + .await + { Ok(_) => { info!( "publish_local_revocations >>> rev_reg_delta storage cleared for \ @@ -282,6 +298,7 @@ pub struct RevocationRegistryDefinition { pub ver: String, } pub async fn generate_rev_reg( + wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, issuer_did: &str, cred_def_id: &str, @@ -300,7 +317,14 @@ pub async fn generate_rev_reg( ); let (rev_reg_id, rev_reg_def_json, rev_reg_entry_json) = anoncreds - .issuer_create_and_store_revoc_reg(issuer_did, cred_def_id, tails_dir, max_creds, tag) + .issuer_create_and_store_revoc_reg( + wallet, + issuer_did, + cred_def_id, + tails_dir, + max_creds, + tag, + ) .await?; let rev_reg_def: RevocationRegistryDefinition = serde_json::from_str(&rev_reg_def_json) diff --git a/aries_vcx/src/common/proofs/proof_request.rs b/aries_vcx/src/common/proofs/proof_request.rs index e0f88eb464..b03df0ea3c 100644 --- a/aries_vcx/src/common/proofs/proof_request.rs +++ b/aries_vcx/src/common/proofs/proof_request.rs @@ -179,6 +179,7 @@ pub mod test_utils { #[cfg(test)] #[allow(clippy::unwrap_used)] mod unit_tests { + use agency_client::testing::test_utils::SetupMocks; use serde_json::Value; use super::*; @@ -186,7 +187,6 @@ mod unit_tests { utils, utils::{ constants::{REQUESTED_ATTRS, REQUESTED_PREDICATES}, - devsetup::SetupDefaults, mockdata::{mockdata_proof, profile::mock_anoncreds::MockAnoncreds}, }, }; @@ -205,7 +205,7 @@ mod unit_tests { #[tokio::test] async fn test_proof_request_msg() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let anoncreds = MockAnoncreds; let request = ProofRequestData::create(&anoncreds, "Test") @@ -240,7 +240,7 @@ mod unit_tests { #[tokio::test] async fn test_requested_attrs_constructed_correctly() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let anoncreds = MockAnoncreds; let request = ProofRequestData::create(&anoncreds, "") @@ -253,7 +253,7 @@ mod unit_tests { #[tokio::test] async fn test_requested_attrs_constructed_correctly_preformatted() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let expected_req_attrs = _expected_req_attrs(); let req_attrs_string = serde_json::to_string(&expected_req_attrs).unwrap(); @@ -269,7 +269,7 @@ mod unit_tests { #[tokio::test] async fn test_requested_predicates_constructed_correctly() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let mut check_predicates: HashMap = HashMap::new(); let attr_info1: PredicateInfo = serde_json::from_str( @@ -311,7 +311,7 @@ mod unit_tests { #[tokio::test] async fn test_requested_attrs_constructed_correctly_for_names() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let attr_info = json!({ "names": ["name", "age", "email"], @@ -345,7 +345,7 @@ mod unit_tests { #[tokio::test] async fn test_should_return_error_if_name_and_names_passed_together() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let attr_info = json!({ "name": "name", @@ -367,7 +367,7 @@ mod unit_tests { #[test] fn test_indy_proof_req_parses_correctly() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let _proof_req: ProofRequestData = serde_json::from_str(utils::constants::INDY_PROOF_REQ_JSON).unwrap(); diff --git a/aries_vcx/src/common/proofs/prover/mod.rs b/aries_vcx/src/common/proofs/prover/mod.rs index 0f364f3afe..b5ddc20a2d 100644 --- a/aries_vcx/src/common/proofs/prover/mod.rs +++ b/aries_vcx/src/common/proofs/prover/mod.rs @@ -4,6 +4,7 @@ use std::collections::HashMap; use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, + wallet::base_wallet::BaseWallet, }; use crate::{ @@ -21,6 +22,7 @@ use crate::{ }; pub async fn generate_indy_proof( + wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, credentials: &SelectedCredentials, @@ -64,6 +66,7 @@ pub async fn generate_indy_proof( let proof = anoncreds .prover_create_proof( + wallet, proof_req_data_json, &requested_credentials, settings::DEFAULT_LINK_SECRET_ALIAS, diff --git a/aries_vcx/src/common/proofs/prover/prover_internal.rs b/aries_vcx/src/common/proofs/prover/prover_internal.rs index 733c64d12a..1c7656f4c4 100644 --- a/aries_vcx/src/common/proofs/prover/prover_internal.rs +++ b/aries_vcx/src/common/proofs/prover/prover_internal.rs @@ -290,13 +290,9 @@ pub mod pool_tests { run_setup!(|setup| async move { // empty vector assert_eq!( - build_rev_states_json( - setup.profile.ledger_read(), - setup.profile.anoncreds(), - Vec::new().as_mut() - ) - .await - .unwrap(), + build_rev_states_json(&setup.ledger_read, &setup.anoncreds, Vec::new().as_mut()) + .await + .unwrap(), "{}".to_string() ); @@ -314,13 +310,9 @@ pub mod pool_tests { revealed: None, }; assert_eq!( - build_rev_states_json( - setup.profile.ledger_read(), - setup.profile.anoncreds(), - vec![cred1].as_mut() - ) - .await - .unwrap(), + build_rev_states_json(&setup.ledger_read, &setup.anoncreds, vec![cred1].as_mut()) + .await + .unwrap(), "{}".to_string() ); }) @@ -450,7 +442,7 @@ pub mod unit_tests { #[test] fn test_credential_def_identifiers() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let cred1 = CredInfoProver { referent: "height_1".to_string(), @@ -549,7 +541,7 @@ pub mod unit_tests { #[test] fn test_credential_def_identifiers_failure() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); // No Creds assert_eq!( @@ -727,7 +719,7 @@ pub mod unit_tests { #[test] fn test_get_credential_intervals_from_proof_req() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let proof_req = json!({ "nonce": "123432421212", diff --git a/aries_vcx/src/common/proofs/verifier/mod.rs b/aries_vcx/src/common/proofs/verifier/mod.rs index ed0ec3e4c7..d31c3d7760 100644 --- a/aries_vcx/src/common/proofs/verifier/mod.rs +++ b/aries_vcx/src/common/proofs/verifier/mod.rs @@ -62,6 +62,7 @@ pub mod integration_tests { use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite}, + wallet::base_wallet::BaseWallet, }; use super::*; @@ -80,6 +81,8 @@ pub mod integration_tests { // FUTURE - issuer and holder seperation only needed whilst modular deps not fully implemented async fn create_indy_proof( + wallet_issuer: &impl BaseWallet, + wallet_holder: &impl BaseWallet, anoncreds_issuer: &impl BaseAnonCreds, anoncreds_holder: &impl BaseAnonCreds, ledger_read: &impl AnoncredsLedgerRead, @@ -87,6 +90,8 @@ pub mod integration_tests { did: &str, ) -> (String, String, String, String) { let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( + wallet_issuer, + wallet_holder, anoncreds_issuer, anoncreds_holder, ledger_read, @@ -142,12 +147,13 @@ pub mod integration_tests { .to_string(); anoncreds_holder - .prover_get_credentials_for_proof_req(&proof_req) + .prover_get_credentials_for_proof_req(wallet_holder, &proof_req) .await .unwrap(); let proof = anoncreds_holder .prover_create_proof( + wallet_holder, &proof_req, &requested_credentials_json, "main", @@ -160,7 +166,10 @@ pub mod integration_tests { (schemas, cred_defs, proof_req, proof) } + #[allow(clippy::too_many_arguments)] async fn create_proof_with_predicate( + wallet_issuer: &impl BaseWallet, + wallet_holder: &impl BaseWallet, anoncreds_issuer: &impl BaseAnonCreds, anoncreds_holder: &impl BaseAnonCreds, ledger_read: &impl AnoncredsLedgerRead, @@ -169,6 +178,8 @@ pub mod integration_tests { include_predicate_cred: bool, ) -> (String, String, String, String) { let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( + wallet_issuer, + wallet_holder, anoncreds_issuer, anoncreds_holder, ledger_read, @@ -238,12 +249,13 @@ pub mod integration_tests { .to_string(); anoncreds_holder - .prover_get_credentials_for_proof_req(&proof_req) + .prover_get_credentials_for_proof_req(wallet_holder, &proof_req) .await .unwrap(); let proof = anoncreds_holder .prover_create_proof( + wallet_holder, &proof_req, &requested_credentials_json, "main", @@ -256,7 +268,10 @@ pub mod integration_tests { (schemas, cred_defs, proof_req, proof) } + #[allow(clippy::too_many_arguments)] async fn create_and_store_nonrevocable_credential( + wallet_issuer: &impl BaseWallet, + wallet_holder: &impl BaseWallet, anoncreds_issuer: &impl BaseAnonCreds, anoncreds_holder: &impl BaseAnonCreds, ledger_read: &impl AnoncredsLedgerRead, @@ -264,11 +279,17 @@ pub mod integration_tests { issuer_did: &str, attr_list: &str, ) -> (Schema, CredentialDef, String) { - let schema = - create_and_write_test_schema(anoncreds_issuer, ledger_write, issuer_did, attr_list) - .await; + let schema = create_and_write_test_schema( + wallet_issuer, + anoncreds_issuer, + ledger_write, + issuer_did, + attr_list, + ) + .await; let cred_def = create_and_write_test_cred_def( + wallet_issuer, anoncreds_issuer, ledger_read, ledger_write, @@ -280,6 +301,8 @@ pub mod integration_tests { tokio::time::sleep(Duration::from_millis(500)).await; let cred_id = create_and_write_credential( + wallet_issuer, + wallet_holder, anoncreds_issuer, anoncreds_holder, issuer_did, @@ -309,7 +332,7 @@ pub mod integration_tests { let revocation_details = r#"{"support_revocation":false}"#.to_string(); let name = "Optional".to_owned(); - let proof_req_json = ProofRequestData::create(setup.profile.anoncreds(), &name) + let proof_req_json = ProofRequestData::create(&setup.anoncreds, &name) .await .unwrap() .set_requested_attributes_as_string(requested_attrs) @@ -321,9 +344,10 @@ pub mod integration_tests { let proof_req_json = serde_json::to_string(&proof_req_json).unwrap(); - let anoncreds = setup.profile.anoncreds(); + let anoncreds = &setup.anoncreds; let prover_proof_json = anoncreds .prover_create_proof( + &setup.wallet, &proof_req_json, &json!({ "self_attested_attributes":{ @@ -343,8 +367,8 @@ pub mod integration_tests { .unwrap(); assert!(validate_indy_proof( - setup.profile.ledger_read(), - setup.profile.anoncreds(), + &setup.ledger_read, + &setup.anoncreds, &prover_proof_json, &proof_req_json ) @@ -376,7 +400,7 @@ pub mod integration_tests { let revocation_details = r#"{"support_revocation":true}"#.to_string(); let name = "Optional".to_owned(); - let proof_req_json = ProofRequestData::create(setup.profile.anoncreds(), &name) + let proof_req_json = ProofRequestData::create(&setup.anoncreds, &name) .await .unwrap() .set_requested_attributes_as_string(requested_attrs) @@ -389,10 +413,12 @@ pub mod integration_tests { let proof_req_json = serde_json::to_string(&proof_req_json).unwrap(); let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( - setup.profile.anoncreds(), - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.wallet, + &setup.anoncreds, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, utils::constants::DEFAULT_SCHEMA_ATTRS, ) @@ -401,9 +427,10 @@ pub mod integration_tests { serde_json::from_str(cred_def.get_cred_def_json()).unwrap(); let schema_json: serde_json::Value = serde_json::from_str(&schema.schema_json).unwrap(); - let anoncreds = setup.profile.anoncreds(); + let anoncreds = &setup.anoncreds; let prover_proof_json = anoncreds .prover_create_proof( + &setup.wallet, &proof_req_json, &json!({ "self_attested_attributes":{ @@ -425,8 +452,8 @@ pub mod integration_tests { .unwrap(); assert_eq!( validate_indy_proof( - setup.profile.ledger_read(), - setup.profile.anoncreds(), + &setup.ledger_read, + &setup.anoncreds, &prover_proof_json, &proof_req_json ) @@ -440,8 +467,8 @@ pub mod integration_tests { serde_json::from_str(&proof_req_json).unwrap(); proof_req_json["requested_attributes"]["attribute_0"]["restrictions"] = json!({}); assert!(validate_indy_proof( - setup.profile.ledger_read(), - setup.profile.anoncreds(), + &setup.ledger_read, + &setup.anoncreds, &prover_proof_json, &proof_req_json.to_string() ) @@ -474,7 +501,7 @@ pub mod integration_tests { let revocation_details = r#"{"support_revocation":true}"#.to_string(); let name = "Optional".to_owned(); - let proof_req_json = ProofRequestData::create(setup.profile.anoncreds(), &name) + let proof_req_json = ProofRequestData::create(&setup.anoncreds, &name) .await .unwrap() .set_requested_attributes_as_string(requested_attrs) @@ -487,10 +514,12 @@ pub mod integration_tests { let proof_req_json = serde_json::to_string(&proof_req_json).unwrap(); let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( - setup.profile.anoncreds(), - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.wallet, + &setup.anoncreds, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, utils::constants::DEFAULT_SCHEMA_ATTRS, ) @@ -499,9 +528,10 @@ pub mod integration_tests { serde_json::from_str(cred_def.get_cred_def_json()).unwrap(); let schema_json: serde_json::Value = serde_json::from_str(&schema.schema_json).unwrap(); - let anoncreds = setup.profile.anoncreds(); + let anoncreds = &setup.anoncreds; let prover_proof_json = anoncreds .prover_create_proof( + &setup.wallet, &proof_req_json, &json!({ "self_attested_attributes":{ @@ -522,8 +552,8 @@ pub mod integration_tests { .await .unwrap(); assert!(validate_indy_proof( - setup.profile.ledger_read(), - setup.profile.anoncreds(), + &setup.ledger_read, + &setup.anoncreds, &prover_proof_json, &proof_req_json ) @@ -539,8 +569,8 @@ pub mod integration_tests { assert_eq!( validate_indy_proof( - setup.profile.ledger_read(), - setup.profile.anoncreds(), + &setup.ledger_read, + &setup.anoncreds, &prover_proof_json, &proof_req_json ) @@ -557,8 +587,8 @@ pub mod integration_tests { assert_eq!( validate_indy_proof( - setup.profile.ledger_read(), - setup.profile.anoncreds(), + &setup.ledger_read, + &setup.anoncreds, &prover_proof_json, &proof_req_json ) @@ -576,15 +606,17 @@ pub mod integration_tests { async fn test_pool_prover_verify_proof() { run_setup!(|setup| async move { let (schemas, cred_defs, proof_req, proof) = create_indy_proof( - setup.profile.anoncreds(), - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.wallet, + &setup.anoncreds, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, ) .await; - let anoncreds = setup.profile.anoncreds(); + let anoncreds = &setup.anoncreds; let proof_validation = anoncreds .verifier_verify_proof(&proof_req, &proof, &schemas, &cred_defs, "{}", "{}") .await @@ -600,16 +632,18 @@ pub mod integration_tests { async fn test_pool_prover_verify_proof_with_predicate_success_case() { run_setup!(|setup| async move { let (schemas, cred_defs, proof_req, proof) = create_proof_with_predicate( - setup.profile.anoncreds(), - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.wallet, + &setup.anoncreds, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, true, ) .await; - let anoncreds = setup.profile.anoncreds(); + let anoncreds = &setup.anoncreds; let proof_validation = anoncreds .verifier_verify_proof(&proof_req, &proof, &schemas, &cred_defs, "{}", "{}") .await @@ -625,16 +659,18 @@ pub mod integration_tests { async fn test_pool_prover_verify_proof_with_predicate_fail_case() { run_setup!(|setup| async move { let (schemas, cred_defs, proof_req, proof) = create_proof_with_predicate( - setup.profile.anoncreds(), - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.wallet, + &setup.anoncreds, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, false, ) .await; - let anoncreds = setup.profile.anoncreds(); + let anoncreds = &setup.anoncreds; anoncreds .verifier_verify_proof(&proof_req, &proof, &schemas, &cred_defs, "{}", "{}") .await diff --git a/aries_vcx/src/common/test_utils.rs b/aries_vcx/src/common/test_utils.rs index f3e5f1a5fa..07a8b9184d 100644 --- a/aries_vcx/src/common/test_utils.rs +++ b/aries_vcx/src/common/test_utils.rs @@ -8,6 +8,7 @@ use aries_vcx_core::{ base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite}, indy::pool::test_utils::get_temp_dir_path, }, + wallet::base_wallet::BaseWallet, }; use super::primitives::credential_schema::Schema; @@ -27,6 +28,7 @@ use crate::{ }; pub async fn create_and_write_test_schema( + wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger_write: &impl AnoncredsLedgerWrite, submitter_did: &str, @@ -42,12 +44,13 @@ pub async fn create_and_write_test_schema( ) .await .unwrap(); - let schema = schema.publish(ledger_write).await.unwrap(); + let schema = schema.publish(wallet, ledger_write).await.unwrap(); std::thread::sleep(Duration::from_millis(500)); schema } pub async fn create_and_write_test_cred_def( + wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger_read: &impl AnoncredsLedgerRead, ledger_write: &impl AnoncredsLedgerWrite, @@ -56,6 +59,7 @@ pub async fn create_and_write_test_cred_def( revokable: bool, ) -> CredentialDef { CredentialDef::create( + wallet, ledger_read, anoncreds, "1".to_string(), @@ -69,30 +73,40 @@ pub async fn create_and_write_test_cred_def( ) .await .unwrap() - .publish_cred_def(ledger_read, ledger_write) + .publish_cred_def(wallet, ledger_read, ledger_write) .await .unwrap() } pub async fn create_and_publish_test_rev_reg( + wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger_write: &impl AnoncredsLedgerWrite, issuer_did: &str, cred_def_id: &str, ) -> RevocationRegistry { let tails_dir = get_temp_dir_path().as_path().to_str().unwrap().to_string(); - let mut rev_reg = - RevocationRegistry::create(anoncreds, issuer_did, cred_def_id, &tails_dir, 10, 1) - .await - .unwrap(); + let mut rev_reg = RevocationRegistry::create( + wallet, + anoncreds, + issuer_did, + cred_def_id, + &tails_dir, + 10, + 1, + ) + .await + .unwrap(); rev_reg - .publish_revocation_primitives(ledger_write, TEST_TAILS_URL) + .publish_revocation_primitives(wallet, ledger_write, TEST_TAILS_URL) .await .unwrap(); rev_reg } pub async fn create_and_write_credential( + wallet_issuer: &impl BaseWallet, + wallet_holder: &impl BaseWallet, anoncreds_issuer: &impl BaseAnonCreds, anoncreds_holder: &impl BaseAnonCreds, institution_did: &str, @@ -104,11 +118,12 @@ pub async fn create_and_write_credential( let encoded_attributes = encode_attributes(credential_data).unwrap(); let offer = anoncreds_issuer - .issuer_create_credential_offer(&cred_def.get_cred_def_id()) + .issuer_create_credential_offer(wallet_issuer, &cred_def.get_cred_def_id()) .await .unwrap(); let (req, req_meta) = anoncreds_holder .prover_create_credential_req( + wallet_holder, institution_did, &offer, cred_def.get_cred_def_json(), @@ -128,12 +143,20 @@ pub async fn create_and_write_credential( }; println!("rev_reg_def_json: {:?}", rev_reg_def_json); let (cred, _, _) = anoncreds_issuer - .issuer_create_credential(&offer, &req, &encoded_attributes, rev_reg_id, tails_dir) + .issuer_create_credential( + wallet_issuer, + &offer, + &req, + &encoded_attributes, + rev_reg_id, + tails_dir, + ) .await .unwrap(); anoncreds_holder .prover_store_credential( + wallet_holder, None, &req_meta, &cred, diff --git a/aries_vcx/src/core/mod.rs b/aries_vcx/src/core/mod.rs deleted file mode 100644 index 6b76aba686..0000000000 --- a/aries_vcx/src/core/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod profile; diff --git a/aries_vcx/src/core/profile/ledger.rs b/aries_vcx/src/core/profile/ledger.rs deleted file mode 100644 index d952272073..0000000000 --- a/aries_vcx/src/core/profile/ledger.rs +++ /dev/null @@ -1,85 +0,0 @@ -use std::{sync::Arc, time::Duration}; - -use aries_vcx_core::{ - ledger::{ - base_ledger::TxnAuthrAgrmtOptions, - indy_vdr_ledger::{ - IndyVdrLedgerRead, IndyVdrLedgerReadConfig, IndyVdrLedgerWrite, - IndyVdrLedgerWriteConfig, ProtocolVersion, - }, - request_signer::base_wallet::BaseWalletRequestSigner, - request_submitter::vdr_ledger::{IndyVdrLedgerPool, IndyVdrSubmitter}, - response_cacher::in_memory::{InMemoryResponseCacher, InMemoryResponseCacherConfig}, - }, - wallet::base_wallet::BaseWallet, - PoolConfig, ResponseParser, -}; - -use crate::errors::error::VcxResult; -/// TODO: Rename these -pub type ArcIndyVdrLedgerRead = IndyVdrLedgerRead; -pub type ArcIndyVdrLedgerWrite = IndyVdrLedgerWrite; - -pub struct VcxPoolConfig { - pub genesis_file_path: String, - pub indy_vdr_config: Option, - pub response_cache_config: Option, -} - -pub fn build_ledger_components( - wallet: Arc, - pool_config: VcxPoolConfig, -) -> VcxResult<(ArcIndyVdrLedgerRead, ArcIndyVdrLedgerWrite)> { - let indy_vdr_config = match pool_config.indy_vdr_config { - None => PoolConfig::default(), - Some(cfg) => cfg, - }; - let cache_config = match pool_config.response_cache_config { - None => InMemoryResponseCacherConfig::builder() - .ttl(Duration::from_secs(60)) - .capacity(1000)? - .build(), - Some(cfg) => cfg, - }; - - let ledger_pool = - IndyVdrLedgerPool::new(pool_config.genesis_file_path, indy_vdr_config, vec![])?; - - let request_submitter = Arc::new(IndyVdrSubmitter::new(ledger_pool)); - - let ledger_read = indyvdr_build_ledger_read(request_submitter.clone(), cache_config)?; - let ledger_write = indyvdr_build_ledger_write(wallet, request_submitter, None); - - Ok((ledger_read, ledger_write)) -} - -pub fn indyvdr_build_ledger_read( - request_submitter: Arc, - cache_config: InMemoryResponseCacherConfig, -) -> VcxResult> { - let response_parser = Arc::new(ResponseParser); - let response_cacher = Arc::new(InMemoryResponseCacher::new(cache_config)); - - let config_read = IndyVdrLedgerReadConfig { - request_submitter, - response_parser, - response_cacher, - protocol_version: ProtocolVersion::node_1_4(), - }; - Ok(IndyVdrLedgerRead::new(config_read)) -} - -pub fn indyvdr_build_ledger_write( - wallet: Arc, - request_submitter: Arc, - taa_options: Option, -) -> IndyVdrLedgerWrite { - let request_signer = Arc::new(BaseWalletRequestSigner::new(wallet.clone())); - let config_write = IndyVdrLedgerWriteConfig { - request_signer, - request_submitter, - taa_options, - protocol_version: ProtocolVersion::node_1_4(), - }; - IndyVdrLedgerWrite::new(config_write) -} diff --git a/aries_vcx/src/core/profile/mod.rs b/aries_vcx/src/core/profile/mod.rs deleted file mode 100644 index 563dcff7f4..0000000000 --- a/aries_vcx/src/core/profile/mod.rs +++ /dev/null @@ -1,57 +0,0 @@ -pub mod ledger; -#[cfg(all(feature = "credx", feature = "vdrtools_wallet"))] -pub mod modular_libs_profile; -#[cfg(feature = "vdr_proxy_ledger")] -pub mod vdr_proxy_profile; - -use std::sync::Arc; - -use aries_vcx_core::{ - anoncreds::base_anoncreds::BaseAnonCreds, - ledger::{ - base_ledger::{ - AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite, - TxnAuthrAgrmtOptions, - }, - indy_vdr_ledger::GetTxnAuthorAgreementData, - }, - wallet::base_wallet::BaseWallet, -}; -use async_trait::async_trait; - -use crate::errors::error::VcxResult; - -const DEFAULT_AML_LABEL: &str = "eula"; - -pub async fn prepare_taa_options( - ledger_read: Arc, -) -> VcxResult> { - if let Some(taa_result) = ledger_read.get_txn_author_agreement().await? { - let taa_result: GetTxnAuthorAgreementData = serde_json::from_str(&taa_result)?; - Ok(Some(TxnAuthrAgrmtOptions { - version: taa_result.version, - text: taa_result.text, - mechanism: DEFAULT_AML_LABEL.to_string(), - })) - } else { - Ok(None) - } -} - -#[async_trait] -pub trait Profile: std::fmt::Debug + Send + Sync { - type LedgerRead: IndyLedgerRead + AnoncredsLedgerRead; - type LedgerWrite: IndyLedgerWrite + AnoncredsLedgerWrite; - type Anoncreds: BaseAnonCreds; - type Wallet: BaseWallet; - - fn ledger_read(&self) -> &Self::LedgerRead; - - fn ledger_write(&self) -> &Self::LedgerWrite; - - fn anoncreds(&self) -> &Self::Anoncreds; - - fn wallet(&self) -> &Self::Wallet; - - fn update_taa_configuration(&self, taa_options: TxnAuthrAgrmtOptions) -> VcxResult<()>; -} diff --git a/aries_vcx/src/core/profile/modular_libs_profile.rs b/aries_vcx/src/core/profile/modular_libs_profile.rs deleted file mode 100644 index c7f0f310b4..0000000000 --- a/aries_vcx/src/core/profile/modular_libs_profile.rs +++ /dev/null @@ -1,70 +0,0 @@ -use std::sync::Arc; - -use aries_vcx_core::{ - anoncreds::credx_anoncreds::IndyCredxAnonCreds, - ledger::base_ledger::{TaaConfigurator, TxnAuthrAgrmtOptions}, - wallet::indy::IndySdkWallet, -}; -use async_trait::async_trait; - -use super::{ - ledger::{ArcIndyVdrLedgerRead, ArcIndyVdrLedgerWrite}, - Profile, -}; -use crate::{ - core::profile::ledger::{build_ledger_components, VcxPoolConfig}, - errors::error::VcxResult, -}; - -#[allow(dead_code)] -#[derive(Debug)] -pub struct ModularLibsProfile { - wallet: Arc, - anoncreds: IndyCredxAnonCreds, - indy_ledger_read: ArcIndyVdrLedgerRead, - indy_ledger_write: ArcIndyVdrLedgerWrite, -} - -impl ModularLibsProfile { - pub fn init(wallet: Arc, vcx_pool_config: VcxPoolConfig) -> VcxResult { - let anoncreds = IndyCredxAnonCreds::new(wallet.clone()); - let (ledger_read, ledger_write) = build_ledger_components(wallet.clone(), vcx_pool_config)?; - - Ok(ModularLibsProfile { - wallet, - anoncreds, - indy_ledger_read: ledger_read, - indy_ledger_write: ledger_write, - }) - } -} - -#[async_trait] -impl Profile for ModularLibsProfile { - type LedgerRead = ArcIndyVdrLedgerRead; - type LedgerWrite = ArcIndyVdrLedgerWrite; - type Anoncreds = IndyCredxAnonCreds; - type Wallet = IndySdkWallet; - - fn ledger_read(&self) -> &Self::LedgerRead { - &self.indy_ledger_read - } - - fn ledger_write(&self) -> &Self::LedgerWrite { - &self.indy_ledger_write - } - - fn anoncreds(&self) -> &Self::Anoncreds { - &self.anoncreds - } - - fn wallet(&self) -> &Self::Wallet { - &self.wallet - } - - fn update_taa_configuration(&self, taa_options: TxnAuthrAgrmtOptions) -> VcxResult<()> { - self.indy_ledger_write - .set_txn_author_agreement_options(taa_options) - .map_err(|e| e.into()) - } -} diff --git a/aries_vcx/src/core/profile/vdr_proxy_profile.rs b/aries_vcx/src/core/profile/vdr_proxy_profile.rs deleted file mode 100644 index 3d3e9381b2..0000000000 --- a/aries_vcx/src/core/profile/vdr_proxy_profile.rs +++ /dev/null @@ -1,96 +0,0 @@ -use std::{sync::Arc, time::Duration}; - -use aries_vcx_core::{ - anoncreds::credx_anoncreds::IndyCredxAnonCreds, - ledger::{ - base_ledger::{TaaConfigurator, TxnAuthrAgrmtOptions}, - indy_vdr_ledger::{ - IndyVdrLedgerRead, IndyVdrLedgerReadConfig, IndyVdrLedgerWrite, - IndyVdrLedgerWriteConfig, ProtocolVersion, - }, - request_signer::base_wallet::BaseWalletRequestSigner, - request_submitter::vdr_proxy::VdrProxySubmitter, - response_cacher::in_memory::{InMemoryResponseCacher, InMemoryResponseCacherConfig}, - }, - wallet::indy::IndySdkWallet, - ResponseParser, VdrProxyClient, -}; -use async_trait::async_trait; - -use super::{prepare_taa_options, Profile}; -use crate::errors::error::VcxResult; - -#[derive(Debug)] -pub struct VdrProxyProfile { - wallet: Arc, - anoncreds: IndyCredxAnonCreds, - indy_ledger_read: Arc>, - indy_ledger_write: IndyVdrLedgerWrite, -} - -impl VdrProxyProfile { - pub async fn init(wallet: Arc, client: VdrProxyClient) -> VcxResult { - let anoncreds = IndyCredxAnonCreds::new(wallet.clone()); - let request_signer = Arc::new(BaseWalletRequestSigner::new(wallet.clone())); - let request_submitter = Arc::new(VdrProxySubmitter::new(Arc::new(client))); - let response_parser = Arc::new(ResponseParser); - let cacher_config = InMemoryResponseCacherConfig::builder() - .ttl(Duration::from_secs(60)) - .capacity(1000)? - .build(); - let response_cacher = Arc::new(InMemoryResponseCacher::new(cacher_config)); - - let config_read = IndyVdrLedgerReadConfig { - request_submitter: request_submitter.clone(), - response_parser, - response_cacher, - protocol_version: ProtocolVersion::node_1_4(), - }; - let ledger_read = Arc::new(IndyVdrLedgerRead::new(config_read)); - - let config_write = IndyVdrLedgerWriteConfig { - request_submitter, - request_signer, - taa_options: prepare_taa_options(ledger_read.clone()).await?, - protocol_version: ProtocolVersion::node_1_4(), - }; - let ledger_write = IndyVdrLedgerWrite::new(config_write); - - Ok(VdrProxyProfile { - wallet, - anoncreds, - indy_ledger_read: ledger_read, - indy_ledger_write: ledger_write, - }) - } -} - -#[async_trait] -impl Profile for VdrProxyProfile { - type LedgerRead = IndyVdrLedgerRead; - type LedgerWrite = IndyVdrLedgerWrite; - type Anoncreds = IndyCredxAnonCreds; - type Wallet = IndySdkWallet; - - fn ledger_read(&self) -> &Self::LedgerRead { - &self.indy_ledger_read - } - - fn ledger_write(&self) -> &Self::LedgerWrite { - &self.indy_ledger_write - } - - fn anoncreds(&self) -> &Self::Anoncreds { - &self.anoncreds - } - - fn wallet(&self) -> &Self::Wallet { - &self.wallet - } - - fn update_taa_configuration(&self, taa_options: TxnAuthrAgrmtOptions) -> VcxResult<()> { - self.ledger_write() - .set_txn_author_agreement_options(taa_options) - .map_err(|e| e.into()) - } -} diff --git a/aries_vcx/src/handlers/issuance/holder.rs b/aries_vcx/src/handlers/issuance/holder.rs index b1beec1309..8bbf64414b 100644 --- a/aries_vcx/src/handlers/issuance/holder.rs +++ b/aries_vcx/src/handlers/issuance/holder.rs @@ -96,6 +96,7 @@ impl Holder { pub async fn prepare_credential_request( &mut self, + wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, my_pw_did: String, @@ -103,7 +104,7 @@ impl Holder { self.holder_sm = self .holder_sm .clone() - .prepare_credential_request(ledger, anoncreds, my_pw_did) + .prepare_credential_request(wallet, ledger, anoncreds, my_pw_did) .await?; match self.get_state() { HolderState::Failed => Ok(self.get_problem_report()?.into()), @@ -141,6 +142,7 @@ impl Holder { pub async fn process_credential( &mut self, + wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, credential: IssueCredentialV1, @@ -148,7 +150,7 @@ impl Holder { self.holder_sm = self .holder_sm .clone() - .receive_credential(ledger, anoncreds, credential) + .receive_credential(wallet, ledger, anoncreds, credential) .await?; Ok(()) } @@ -207,22 +209,31 @@ impl Holder { pub async fn is_revoked( &self, + wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, ) -> VcxResult { - self.holder_sm.is_revoked(ledger, anoncreds).await + self.holder_sm.is_revoked(wallet, ledger, anoncreds).await } - pub async fn delete_credential(&self, anoncreds: &impl BaseAnonCreds) -> VcxResult<()> { - self.holder_sm.delete_credential(anoncreds).await + pub async fn delete_credential( + &self, + wallet: &impl BaseWallet, + anoncreds: &impl BaseAnonCreds, + ) -> VcxResult<()> { + self.holder_sm.delete_credential(wallet, anoncreds).await } pub fn get_credential_status(&self) -> VcxResult { Ok(self.holder_sm.credential_status()) } - pub async fn get_cred_rev_id(&self, anoncreds: &impl BaseAnonCreds) -> VcxResult { - get_cred_rev_id(anoncreds, &self.get_cred_id()?).await + pub async fn get_cred_rev_id( + &self, + wallet: &impl BaseWallet, + anoncreds: &impl BaseAnonCreds, + ) -> VcxResult { + get_cred_rev_id(wallet, anoncreds, &self.get_cred_id()?).await } pub async fn handle_revocation_notification( @@ -238,7 +249,7 @@ impl Holder { // TODO: Store to remember notification was received along with details RevocationNotificationReceiver::build( self.get_rev_reg_id()?, - self.get_cred_rev_id(anoncreds).await?, + self.get_cred_rev_id(wallet, anoncreds).await?, ) .handle_revocation_notification(notification, send_message) .await?; @@ -257,6 +268,7 @@ impl Holder { pub async fn process_aries_msg( &mut self, + wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, message: AriesMessage, @@ -270,7 +282,7 @@ impl Holder { )) => { self.holder_sm .clone() - .receive_credential(ledger, anoncreds, credential) + .receive_credential(wallet, ledger, anoncreds, credential) .await? } // TODO: What about credential issuance problem report? diff --git a/aries_vcx/src/handlers/issuance/issuer.rs b/aries_vcx/src/handlers/issuance/issuer.rs index 116323511a..b7db488cf9 100644 --- a/aries_vcx/src/handlers/issuance/issuer.rs +++ b/aries_vcx/src/handlers/issuance/issuer.rs @@ -1,5 +1,6 @@ use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, + wallet::base_wallet::BaseWallet, }; use messages::{ misc::MimeType, @@ -143,13 +144,14 @@ impl Issuer { // from that pub async fn build_credential_offer_msg( &mut self, + wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, offer_info: OfferInfo, comment: Option, ) -> VcxResult<()> { let credential_preview = _build_credential_preview(&offer_info.credential_json)?; let libindy_cred_offer = anoncreds - .issuer_create_credential_offer(&offer_info.cred_def_id) + .issuer_create_credential_offer(wallet, &offer_info.cred_def_id) .await?; self.issuer_sm = self.issuer_sm.clone().build_credential_offer_msg( &libindy_cred_offer, @@ -179,8 +181,16 @@ impl Issuer { Ok(()) } - pub async fn build_credential(&mut self, anoncreds: &impl BaseAnonCreds) -> VcxResult<()> { - self.issuer_sm = self.issuer_sm.clone().build_credential(anoncreds).await?; + pub async fn build_credential( + &mut self, + wallet: &impl BaseWallet, + anoncreds: &impl BaseAnonCreds, + ) -> VcxResult<()> { + self.issuer_sm = self + .issuer_sm + .clone() + .build_credential(wallet, anoncreds) + .await?; Ok(()) } @@ -214,7 +224,11 @@ impl Issuer { )) } - pub async fn revoke_credential_local(&self, anoncreds: &impl BaseAnonCreds) -> VcxResult<()> { + pub async fn revoke_credential_local( + &self, + wallet: &impl BaseWallet, + anoncreds: &impl BaseAnonCreds, + ) -> VcxResult<()> { let revocation_info: RevocationInfoV1 = self.issuer_sm .get_revocation_info() @@ -228,7 +242,7 @@ impl Issuer { revocation_info.tails_file, ) { anoncreds - .revoke_credential_local(&tails_file, &rev_reg_id, &cred_rev_id) + .revoke_credential_local(wallet, &tails_file, &rev_reg_id, &cred_rev_id) .await?; } else { return Err(AriesVcxError::from_msg( diff --git a/aries_vcx/src/handlers/proof_presentation/prover.rs b/aries_vcx/src/handlers/proof_presentation/prover.rs index 32050516d7..752df1e9ed 100644 --- a/aries_vcx/src/handlers/proof_presentation/prover.rs +++ b/aries_vcx/src/handlers/proof_presentation/prover.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, + wallet::base_wallet::BaseWallet, }; use chrono::Utc; use messages::{ @@ -70,12 +71,13 @@ impl Prover { pub async fn retrieve_credentials( &self, + wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ) -> VcxResult { trace!("Prover::retrieve_credentials >>>"); let presentation_request = self.presentation_request_data()?; let json_retrieved_credentials = anoncreds - .prover_get_credentials_for_proof_req(&presentation_request) + .prover_get_credentials_for_proof_req(wallet, &presentation_request) .await?; trace!( "Prover::retrieve_credentials >>> presentation_request: {presentation_request}, \ @@ -86,6 +88,7 @@ impl Prover { pub async fn generate_presentation( &mut self, + wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, credentials: SelectedCredentials, @@ -99,7 +102,7 @@ impl Prover { self.prover_sm = self .prover_sm .clone() - .generate_presentation(ledger, anoncreds, credentials, self_attested_attrs) + .generate_presentation(wallet, ledger, anoncreds, credentials, self_attested_attrs) .await?; Ok(()) } diff --git a/aries_vcx/src/lib.rs b/aries_vcx/src/lib.rs index 4feabd20f6..144611a420 100644 --- a/aries_vcx/src/lib.rs +++ b/aries_vcx/src/lib.rs @@ -33,6 +33,5 @@ pub mod global; pub mod protocols; pub mod common; -pub mod core; pub mod errors; pub mod transport; diff --git a/aries_vcx/src/protocols/issuance/holder/state_machine.rs b/aries_vcx/src/protocols/issuance/holder/state_machine.rs index 68e2c0a5d0..79c1f54862 100644 --- a/aries_vcx/src/protocols/issuance/holder/state_machine.rs +++ b/aries_vcx/src/protocols/issuance/holder/state_machine.rs @@ -2,6 +2,7 @@ use std::fmt; use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, + wallet::base_wallet::BaseWallet, }; use chrono::Utc; use messages::{ @@ -205,6 +206,7 @@ impl HolderSM { pub async fn prepare_credential_request<'a>( self, + wallet: &impl BaseWallet, ledger: &'a impl AnoncredsLedgerRead, anoncreds: &'a impl BaseAnonCreds, my_pw_did: String, @@ -213,6 +215,7 @@ impl HolderSM { let state = match self.state { HolderFullState::OfferReceived(state_data) => { match build_credential_request_msg( + wallet, ledger, anoncreds, self.thread_id.clone(), @@ -264,6 +267,7 @@ impl HolderSM { pub async fn receive_credential<'a>( self, + wallet: &'a impl BaseWallet, ledger: &'a impl AnoncredsLedgerRead, anoncreds: &'a impl BaseAnonCreds, credential: IssueCredentialV1, @@ -272,6 +276,7 @@ impl HolderSM { let state = match self.state { HolderFullState::RequestSet(state_data) => { match _store_credential( + wallet, ledger, anoncreds, &credential, @@ -434,13 +439,14 @@ impl HolderSM { pub async fn is_revoked( &self, + wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, ) -> VcxResult { if self.is_revokable(ledger).await? { let rev_reg_id = self.get_rev_reg_id()?; let cred_id = self.get_cred_id()?; - let rev_id = get_cred_rev_id(anoncreds, &cred_id).await?; + let rev_id = get_cred_rev_id(wallet, anoncreds, &cred_id).await?; is_cred_revoked(ledger, &rev_reg_id, &rev_id).await } else { Err(AriesVcxError::from_msg( @@ -450,7 +456,11 @@ impl HolderSM { } } - pub async fn delete_credential(&self, anoncreds: &impl BaseAnonCreds) -> VcxResult<()> { + pub async fn delete_credential( + &self, + wallet: &impl BaseWallet, + anoncreds: &impl BaseAnonCreds, + ) -> VcxResult<()> { trace!("Holder::delete_credential"); match self.state { @@ -460,7 +470,7 @@ impl HolderSM { "Cannot get credential: credential id not found", ))?; anoncreds - .prover_delete_credential(&cred_id) + .prover_delete_credential(wallet, &cred_id) .await .map_err(|err| err.into()) } @@ -532,6 +542,7 @@ fn _parse_rev_reg_id_from_credential(credential: &str) -> VcxResult VcxResult { + pub async fn build_credential( + self, + wallet: &impl BaseWallet, + anoncreds: &impl BaseAnonCreds, + ) -> VcxResult { let state = match self.state { IssuerFullState::RequestReceived(state_data) => { match create_credential( + wallet, anoncreds, &state_data.request, &state_data.rev_reg_id, @@ -559,7 +565,9 @@ impl IssuerSM { } } +#[allow(clippy::too_many_arguments)] async fn create_credential( + wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, request: &RequestCredentialV1, rev_reg_id: &Option, @@ -592,6 +600,7 @@ async fn create_credential( let cred_data = encode_attributes(cred_data)?; let (libindy_credential, cred_rev_id, _) = anoncreds .issuer_create_credential( + wallet, &offer, &request, &cred_data, diff --git a/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs b/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs index 07318b0cd0..85240c15f7 100644 --- a/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs +++ b/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs @@ -2,6 +2,7 @@ use std::{collections::HashMap, fmt}; use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, + wallet::base_wallet::BaseWallet, }; use chrono::Utc; use messages::{ @@ -229,6 +230,7 @@ impl ProverSM { pub async fn generate_presentation( self, + wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, credentials: SelectedCredentials, @@ -237,7 +239,13 @@ impl ProverSM { let state = match self.state { ProverFullState::PresentationRequestReceived(state) => { match state - .build_presentation(ledger, anoncreds, &credentials, &self_attested_attrs) + .build_presentation( + wallet, + ledger, + anoncreds, + &credentials, + &self_attested_attrs, + ) .await { Ok(presentation) => { diff --git a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs index ae9fcd4cd9..676d92d7f7 100644 --- a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs +++ b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, + wallet::base_wallet::BaseWallet, }; use messages::msg_fields::protocols::{ present_proof::{ @@ -56,6 +57,7 @@ impl PresentationRequestReceived { pub async fn build_presentation( &self, + wallet: &impl BaseWallet, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, credentials: &SelectedCredentials, @@ -69,6 +71,7 @@ impl PresentationRequestReceived { ); generate_indy_proof( + wallet, ledger, anoncreds, credentials, diff --git a/aries_vcx/src/utils/devsetup.rs b/aries_vcx/src/utils/devsetup.rs index 1e01db48a6..3420c0e128 100644 --- a/aries_vcx/src/utils/devsetup.rs +++ b/aries_vcx/src/utils/devsetup.rs @@ -1,33 +1,53 @@ #![allow(clippy::unwrap_used)] +#![allow(unused_imports)] use std::{ - fs, + env, fs, future::Future, sync::{Arc, Once}, }; use agency_client::testing::mocking::{enable_agency_mocks, AgencyMockDecrypted}; use aries_vcx_core::{ - ledger::indy::pool::test_utils::{create_testpool_genesis_txn_file, get_temp_file_path}, + anoncreds::{base_anoncreds::BaseAnonCreds, credx_anoncreds::IndyCredxAnonCreds}, + ledger::{ + base_ledger::{ + AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite, + TxnAuthrAgrmtOptions, + }, + indy::pool::test_utils::{create_testpool_genesis_txn_file, get_temp_file_path}, + indy_vdr_ledger::{ + GetTxnAuthorAgreementData, IndyVdrLedgerRead, IndyVdrLedgerReadConfig, + IndyVdrLedgerWrite, IndyVdrLedgerWriteConfig, ProtocolVersion, + }, + request_submitter::vdr_ledger::{IndyVdrLedgerPool, IndyVdrSubmitter}, + response_cacher::in_memory::{InMemoryResponseCacher, InMemoryResponseCacherConfig}, + }, + wallet::base_wallet::BaseWallet, + PoolConfig, ResponseParser, +}; +#[cfg(feature = "vdr_proxy_ledger")] +use aries_vcx_core::{ledger::request_submitter::vdr_proxy::VdrProxySubmitter, VdrProxyClient}; +#[cfg(feature = "vdrtools_wallet")] +use aries_vcx_core::{ wallet::indy::{ did_mocks::DidMocks, wallet::{create_and_open_wallet, create_and_store_my_did}, - IndySdkWallet, WalletConfig, + WalletConfig, }, WalletHandle, }; use chrono::{DateTime, Duration, Utc}; -#[cfg(all(feature = "credx", feature = "vdrtools_wallet"))] -use crate::core::profile::modular_libs_profile::ModularLibsProfile; -#[cfg(feature = "vdr_proxy_ledger")] -use crate::core::profile::vdr_proxy_profile::VdrProxyProfile; +use super::ledger::{indyvdr_build_ledger_read, indyvdr_build_ledger_write}; use crate::{ - core::profile::Profile, + errors::error::VcxResult, global::settings, utils::{constants::POOL1_TXN, file::write_file, test_logger::LibvcxDefaultLogger}, }; +const DEFAULT_AML_LABEL: &str = "eula"; + lazy_static! { static ref TEST_LOGGING_INIT: Once = Once::new(); } @@ -38,9 +58,40 @@ pub fn init_test_logging() { }) } -pub struct SetupEmpty; +pub type DefaultIndyLedgerRead = IndyVdrLedgerRead; +pub type DefaultIndyLedgerWrite = IndyVdrLedgerWrite; + +pub struct VcxPoolConfig { + pub genesis_file_path: String, + pub indy_vdr_config: Option, + pub response_cache_config: Option, +} + +pub fn build_ledger_components( + pool_config: VcxPoolConfig, +) -> VcxResult<(DefaultIndyLedgerRead, DefaultIndyLedgerWrite)> { + let indy_vdr_config = match pool_config.indy_vdr_config { + None => PoolConfig::default(), + Some(cfg) => cfg, + }; + let cache_config = match pool_config.response_cache_config { + None => InMemoryResponseCacherConfig::builder() + .ttl(std::time::Duration::from_secs(60)) + .capacity(1000)? + .build(), + Some(cfg) => cfg, + }; -pub struct SetupDefaults; + let ledger_pool = + IndyVdrLedgerPool::new(pool_config.genesis_file_path, indy_vdr_config, vec![])?; + + let request_submitter = IndyVdrSubmitter::new(ledger_pool); + + let ledger_read = indyvdr_build_ledger_read(request_submitter.clone(), cache_config)?; + let ledger_write = indyvdr_build_ledger_write(request_submitter, None); + + Ok((ledger_read, ledger_write)) +} pub struct SetupMocks; @@ -48,13 +99,36 @@ pub const AGENCY_ENDPOINT: &str = "http://localhost:8080"; pub const AGENCY_DID: &str = "VsKV7grR1BUE29mG2Fm2kX"; pub const AGENCY_VERKEY: &str = "Hezce2UWMZ3wUhVkh2LfKSs8nDzWwzs2Win7EzNN3YaR"; -#[derive(Clone)] -pub struct SetupProfile { +pub struct SetupProfile +where + LR: IndyLedgerRead + AnoncredsLedgerRead, + LW: IndyLedgerWrite + AnoncredsLedgerWrite, + A: BaseAnonCreds, + W: BaseWallet, +{ pub institution_did: String, - pub profile: P, + pub ledger_read: LR, + pub ledger_write: LW, + pub anoncreds: A, + pub wallet: W, pub genesis_file_path: String, } +pub async fn prepare_taa_options( + ledger_read: &impl IndyLedgerRead, +) -> VcxResult> { + if let Some(taa_result) = ledger_read.get_txn_author_agreement().await? { + let taa_result: GetTxnAuthorAgreementData = serde_json::from_str(&taa_result)?; + Ok(Some(TxnAuthrAgrmtOptions { + version: taa_result.version, + text: taa_result.text, + mechanism: DEFAULT_AML_LABEL.to_string(), + })) + } else { + Ok(None) + } +} + pub struct SetupPoolDirectory { pub genesis_file_path: String, } @@ -65,37 +139,11 @@ pub fn reset_global_state() { DidMocks::clear_mocks(); } -impl SetupEmpty { - pub fn init() -> SetupEmpty { - init_test_logging(); - SetupEmpty {} - } -} - -impl Drop for SetupEmpty { - fn drop(&mut self) { - reset_global_state(); - } -} - -impl SetupDefaults { - pub fn init() -> SetupDefaults { - init_test_logging(); - SetupDefaults {} - } -} - -impl Drop for SetupDefaults { - fn drop(&mut self) { - reset_global_state(); - } -} - impl SetupMocks { pub fn init() -> SetupMocks { init_test_logging(); enable_agency_mocks(); - SetupMocks {} + SetupMocks } } @@ -129,42 +177,77 @@ pub async fn dev_setup_wallet_indy(key_seed: &str) -> (String, WalletHandle) { #[cfg(all(feature = "credx", feature = "vdrtools_wallet"))] pub fn dev_build_profile_modular( genesis_file_path: String, - wallet: Arc, -) -> ModularLibsProfile { +) -> ( + DefaultIndyLedgerRead, + DefaultIndyLedgerWrite, + IndyCredxAnonCreds, +) { info!("dev_build_profile_modular >>"); - let vcx_pool_config = crate::core::profile::ledger::VcxPoolConfig { + let vcx_pool_config = VcxPoolConfig { genesis_file_path, indy_vdr_config: None, response_cache_config: None, }; - ModularLibsProfile::init(wallet, vcx_pool_config).unwrap() -} -#[cfg(feature = "vdr_proxy_ledger")] -pub async fn dev_build_profile_vdr_proxy_ledger(wallet: Arc) -> VdrProxyProfile { - use std::env; + let anoncreds = IndyCredxAnonCreds; + let (ledger_read, ledger_write) = build_ledger_components(vcx_pool_config).unwrap(); - use aries_vcx_core::VdrProxyClient; + (ledger_read, ledger_write, anoncreds) +} +#[cfg(feature = "vdr_proxy_ledger")] +pub async fn dev_build_profile_vdr_proxy_ledger() -> ( + IndyVdrLedgerRead, + IndyVdrLedgerWrite, + IndyCredxAnonCreds, +) { info!("dev_build_profile_vdr_proxy_ledger >>"); let client_url = env::var("VDR_PROXY_CLIENT_URL").unwrap_or_else(|_| "http://127.0.0.1:3030".to_string()); let client = VdrProxyClient::new(&client_url).unwrap(); - VdrProxyProfile::init(wallet, client).await.unwrap() + let anoncreds = IndyCredxAnonCreds; + let request_submitter = VdrProxySubmitter::new(Arc::new(client)); + let response_parser = ResponseParser; + let cacher_config = InMemoryResponseCacherConfig::builder() + .ttl(std::time::Duration::from_secs(60)) + .capacity(1000) + .unwrap() + .build(); + let response_cacher = InMemoryResponseCacher::new(cacher_config); + + let config_read = IndyVdrLedgerReadConfig { + request_submitter: request_submitter.clone(), + response_parser, + response_cacher, + protocol_version: ProtocolVersion::Node1_4, + }; + let ledger_read = IndyVdrLedgerRead::new(config_read); + + let config_write = IndyVdrLedgerWriteConfig { + request_submitter, + taa_options: prepare_taa_options(&ledger_read).await.unwrap(), + protocol_version: ProtocolVersion::Node1_4, + }; + let ledger_write = IndyVdrLedgerWrite::new(config_write); + + (ledger_read, ledger_write, anoncreds) } #[allow(unreachable_code)] #[allow(unused_variables)] pub async fn dev_build_featured_profile( genesis_file_path: String, - wallet: Arc, -) -> impl Profile { +) -> ( + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, +) { #[cfg(feature = "vdr_proxy_ledger")] return { info!("SetupProfile >> using vdr proxy profile"); - dev_build_profile_vdr_proxy_ledger(wallet).await + dev_build_profile_vdr_proxy_ledger().await }; #[cfg(all( @@ -174,21 +257,20 @@ pub async fn dev_build_featured_profile( ))] return { info!("SetupProfile >> using modular profile"); - dev_build_profile_modular(genesis_file_path, wallet) + dev_build_profile_modular(genesis_file_path) }; #[cfg(not(any( all(feature = "credx", feature = "vdrtools_wallet"), feature = "vdr_proxy_ledger" )))] - super::mockdata::profile::mock_profile::MockProfile + (MockLedger, MockLedger, MockAnoncreds) } #[macro_export] macro_rules! run_setup { ($func:expr) => {{ use aries_vcx_core::anoncreds::base_anoncreds::BaseAnonCreds; - use $crate::core::profile::Profile; $crate::utils::devsetup::init_test_logging(); @@ -205,21 +287,23 @@ macro_rules! run_setup { let (public_did, wallet_handle) = $crate::utils::devsetup::dev_setup_wallet_indy($crate::utils::constants::TRUSTEE_SEED) .await; - let wallet = std::sync::Arc::new(aries_vcx_core::wallet::indy::IndySdkWallet::new( - wallet_handle, - )); - let profile = - $crate::utils::devsetup::dev_build_featured_profile(genesis_file_path.clone(), wallet) - .await; - profile - .anoncreds() - .prover_create_link_secret(aries_vcx_core::global::settings::DEFAULT_LINK_SECRET_ALIAS) + let wallet = aries_vcx_core::wallet::indy::IndySdkWallet::new(wallet_handle); + let (ledger_read, ledger_write, anoncreds) = + $crate::utils::devsetup::dev_build_featured_profile(genesis_file_path.clone()).await; + anoncreds + .prover_create_link_secret( + &wallet, + aries_vcx_core::global::settings::DEFAULT_LINK_SECRET_ALIAS, + ) .await .unwrap(); $crate::utils::devsetup::SetupProfile::new( + ledger_read, + ledger_write, + anoncreds, + wallet, public_did.to_string(), - profile, genesis_file_path, ) .await @@ -227,16 +311,29 @@ macro_rules! run_setup { }}; } -impl

SetupProfile

+impl SetupProfile where - P: Profile, + LR: IndyLedgerRead + AnoncredsLedgerRead, + LW: IndyLedgerWrite + AnoncredsLedgerWrite, + A: BaseAnonCreds, + W: BaseWallet, { - pub async fn new(institution_did: String, profile: P, genesis_file_path: String) -> Self { + pub async fn new( + ledger_read: LR, + ledger_write: LW, + anoncreds: A, + wallet: W, + institution_did: String, + genesis_file_path: String, + ) -> Self { debug!("genesis_file_path: {}", genesis_file_path); SetupProfile { institution_did, - profile, genesis_file_path, + ledger_read, + ledger_write, + anoncreds, + wallet, } } diff --git a/aries_vcx/src/utils/ledger.rs b/aries_vcx/src/utils/ledger.rs new file mode 100644 index 0000000000..ac54737eec --- /dev/null +++ b/aries_vcx/src/utils/ledger.rs @@ -0,0 +1,42 @@ +use aries_vcx_core::{ + ledger::{ + base_ledger::TxnAuthrAgrmtOptions, + indy_vdr_ledger::{ + IndyVdrLedgerRead, IndyVdrLedgerReadConfig, IndyVdrLedgerWrite, + IndyVdrLedgerWriteConfig, ProtocolVersion, + }, + request_submitter::vdr_ledger::IndyVdrSubmitter, + response_cacher::in_memory::{InMemoryResponseCacher, InMemoryResponseCacherConfig}, + }, + ResponseParser, +}; + +use crate::errors::error::VcxResult; + +pub fn indyvdr_build_ledger_read( + request_submitter: IndyVdrSubmitter, + cache_config: InMemoryResponseCacherConfig, +) -> VcxResult> { + let response_parser = ResponseParser; + let response_cacher = InMemoryResponseCacher::new(cache_config); + + let config_read = IndyVdrLedgerReadConfig { + request_submitter, + response_parser, + response_cacher, + protocol_version: ProtocolVersion::Node1_4, + }; + Ok(IndyVdrLedgerRead::new(config_read)) +} + +pub fn indyvdr_build_ledger_write( + request_submitter: IndyVdrSubmitter, + taa_options: Option, +) -> IndyVdrLedgerWrite { + let config_write = IndyVdrLedgerWriteConfig { + request_submitter, + taa_options, + protocol_version: ProtocolVersion::Node1_4, + }; + IndyVdrLedgerWrite::new(config_write) +} diff --git a/aries_vcx/src/utils/mockdata/profile/mock_anoncreds.rs b/aries_vcx/src/utils/mockdata/profile/mock_anoncreds.rs index c035366cf9..0a495faa0c 100644 --- a/aries_vcx/src/utils/mockdata/profile/mock_anoncreds.rs +++ b/aries_vcx/src/utils/mockdata/profile/mock_anoncreds.rs @@ -1,6 +1,7 @@ use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, errors::error::{AriesVcxCoreError, AriesVcxCoreErrorKind, VcxCoreResult}, + wallet::base_wallet::BaseWallet, }; use async_trait::async_trait; @@ -37,6 +38,7 @@ impl BaseAnonCreds for MockAnoncreds { async fn issuer_create_and_store_revoc_reg( &self, + __wallet: &impl BaseWallet, _issuer_did: &str, _cred_def_id: &str, _tails_dir: &str, @@ -52,6 +54,7 @@ impl BaseAnonCreds for MockAnoncreds { async fn issuer_create_and_store_credential_def( &self, + __wallet: &impl BaseWallet, _issuer_did: &str, _schema_json: &str, _tag: &str, @@ -65,12 +68,17 @@ impl BaseAnonCreds for MockAnoncreds { )) } - async fn issuer_create_credential_offer(&self, _cred_def_id: &str) -> VcxCoreResult { + async fn issuer_create_credential_offer( + &self, + __wallet: &impl BaseWallet, + _cred_def_id: &str, + ) -> VcxCoreResult { Ok(LIBINDY_CRED_OFFER.to_string()) } async fn issuer_create_credential( &self, + __wallet: &impl BaseWallet, _cred_offer_json: &str, _cred_req_json: &str, _cred_values_json: &str, @@ -82,6 +90,7 @@ impl BaseAnonCreds for MockAnoncreds { async fn prover_create_proof( &self, + __wallet: &impl BaseWallet, _proof_req_json: &str, _requested_credentials_json: &str, _master_secret_id: &str, @@ -92,7 +101,11 @@ impl BaseAnonCreds for MockAnoncreds { Ok(utils::constants::PROOF_JSON.to_owned()) } - async fn prover_get_credential(&self, _cred_id: &str) -> VcxCoreResult { + async fn prover_get_credential( + &self, + __wallet: &impl BaseWallet, + _cred_id: &str, + ) -> VcxCoreResult { // not needed yet Err(AriesVcxCoreError::from_msg( AriesVcxCoreErrorKind::UnimplementedFeature, @@ -100,7 +113,11 @@ impl BaseAnonCreds for MockAnoncreds { )) } - async fn prover_get_credentials(&self, _filter_json: Option<&str>) -> VcxCoreResult { + async fn prover_get_credentials( + &self, + __wallet: &impl BaseWallet, + _filter_json: Option<&str>, + ) -> VcxCoreResult { // not needed yet Err(AriesVcxCoreError::from_msg( AriesVcxCoreErrorKind::UnimplementedFeature, @@ -110,6 +127,7 @@ impl BaseAnonCreds for MockAnoncreds { async fn prover_get_credentials_for_proof_req( &self, + _wallet: &impl BaseWallet, _proof_request_json: &str, ) -> VcxCoreResult { match get_mock_creds_retrieved_for_proof_request() { @@ -127,6 +145,7 @@ impl BaseAnonCreds for MockAnoncreds { // todo: change _prover_did argument, see: https://github.com/hyperledger/aries-vcx/issues/950 async fn prover_create_credential_req( &self, + _wallet: &impl BaseWallet, _prover_did: &str, _cred_offer_json: &str, _cred_def_json: &str, @@ -151,6 +170,7 @@ impl BaseAnonCreds for MockAnoncreds { async fn prover_store_credential( &self, + _wallet: &impl BaseWallet, _cred_id: Option<&str>, _cred_req_metadata_json: &str, _cred_json: &str, @@ -160,7 +180,11 @@ impl BaseAnonCreds for MockAnoncreds { Ok("cred_id".to_string()) } - async fn prover_delete_credential(&self, _cred_id: &str) -> VcxCoreResult<()> { + async fn prover_delete_credential( + &self, + _wallet: &impl BaseWallet, + _cred_id: &str, + ) -> VcxCoreResult<()> { // not needed yet Err(AriesVcxCoreError::from_msg( AriesVcxCoreErrorKind::UnimplementedFeature, @@ -168,7 +192,11 @@ impl BaseAnonCreds for MockAnoncreds { )) } - async fn prover_create_link_secret(&self, _link_secret_id: &str) -> VcxCoreResult { + async fn prover_create_link_secret( + &self, + _wallet: &impl BaseWallet, + _link_secret_id: &str, + ) -> VcxCoreResult { Ok(settings::DEFAULT_LINK_SECRET_ALIAS.to_string()) } @@ -188,6 +216,7 @@ impl BaseAnonCreds for MockAnoncreds { async fn revoke_credential_local( &self, + _wallet: &impl BaseWallet, _tails_dir: &str, _rev_reg_id: &str, _cred_rev_id: &str, @@ -195,11 +224,19 @@ impl BaseAnonCreds for MockAnoncreds { Ok(()) } - async fn get_rev_reg_delta(&self, _rev_reg_id: &str) -> VcxCoreResult> { + async fn get_rev_reg_delta( + &self, + _wallet: &impl BaseWallet, + _rev_reg_id: &str, + ) -> VcxCoreResult> { Ok(Some(REV_REG_DELTA_JSON.to_string())) } - async fn clear_rev_reg_delta(&self, _rev_reg_id: &str) -> VcxCoreResult<()> { + async fn clear_rev_reg_delta( + &self, + _wallet: &impl BaseWallet, + _rev_reg_id: &str, + ) -> VcxCoreResult<()> { Ok(()) } @@ -215,6 +252,7 @@ mod unit_tests { use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, errors::error::{AriesVcxCoreErrorKind, VcxCoreResult}, + wallet::mock_wallet::MockWallet, }; use crate::utils::mockdata::profile::mock_anoncreds::MockAnoncreds; @@ -231,7 +269,7 @@ mod unit_tests { ) } - let anoncreds: Box = Box::new(MockAnoncreds); + let anoncreds = MockAnoncreds; assert_unimplemented( anoncreds @@ -240,18 +278,22 @@ mod unit_tests { ); assert_unimplemented( anoncreds - .issuer_create_and_store_revoc_reg("", "", "", 0, "") + .issuer_create_and_store_revoc_reg(&MockWallet, "", "", "", 0, "") + .await, + ); + assert_unimplemented( + anoncreds + .issuer_create_and_store_credential_def(&MockWallet, "", "", "", None, "") .await, ); + assert_unimplemented(anoncreds.prover_get_credential(&MockWallet, "").await); + assert_unimplemented(anoncreds.prover_get_credentials(&MockWallet, None).await); assert_unimplemented( anoncreds - .issuer_create_and_store_credential_def("", "", "", None, "") + .prover_get_credentials_for_proof_req(&MockWallet, "") .await, ); - assert_unimplemented(anoncreds.prover_get_credential("").await); - assert_unimplemented(anoncreds.prover_get_credentials(None).await); - assert_unimplemented(anoncreds.prover_get_credentials_for_proof_req("").await); - assert_unimplemented(anoncreds.prover_delete_credential("").await); + assert_unimplemented(anoncreds.prover_delete_credential(&MockWallet, "").await); assert_unimplemented(anoncreds.issuer_create_schema("", "", "", "").await); } } diff --git a/aries_vcx/src/utils/mockdata/profile/mock_ledger.rs b/aries_vcx/src/utils/mockdata/profile/mock_ledger.rs index 34f9e48485..7fffaf223b 100644 --- a/aries_vcx/src/utils/mockdata/profile/mock_ledger.rs +++ b/aries_vcx/src/utils/mockdata/profile/mock_ledger.rs @@ -4,6 +4,7 @@ use aries_vcx_core::{ base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite}, indy_vdr_ledger::UpdateRole, }, + wallet::base_wallet::BaseWallet, }; use async_trait::async_trait; @@ -50,6 +51,7 @@ impl IndyLedgerRead for MockLedger { impl IndyLedgerWrite for MockLedger { async fn set_endorser( &self, + wallet: &impl BaseWallet, submitter_did: &str, request: &str, endorser: &str, @@ -59,6 +61,7 @@ impl IndyLedgerWrite for MockLedger { async fn endorse_transaction( &self, + wallet: &impl BaseWallet, endorser_did: &str, request_json: &str, ) -> VcxCoreResult<()> { @@ -67,6 +70,7 @@ impl IndyLedgerWrite for MockLedger { async fn publish_nym( &self, + wallet: &impl BaseWallet, submitter_did: &str, target_did: &str, verkey: Option<&str>, @@ -76,12 +80,18 @@ impl IndyLedgerWrite for MockLedger { Ok(r#"{"rc":"success"}"#.to_string()) } - async fn add_attr(&self, target_did: &str, attrib_json: &str) -> VcxCoreResult { + async fn add_attr( + &self, + wallet: &impl BaseWallet, + target_did: &str, + attrib_json: &str, + ) -> VcxCoreResult { Ok(r#"{"rc":"success"}"#.to_string()) } async fn write_did( &self, + wallet: &impl BaseWallet, submitter_did: &str, target_did: &str, target_vk: &str, @@ -138,6 +148,7 @@ impl AnoncredsLedgerRead for MockLedger { impl AnoncredsLedgerWrite for MockLedger { async fn publish_schema( &self, + wallet: &impl BaseWallet, schema_json: &str, submitter_did: &str, endorser_did: Option, @@ -147,6 +158,7 @@ impl AnoncredsLedgerWrite for MockLedger { async fn publish_cred_def( &self, + wallet: &impl BaseWallet, cred_def_json: &str, submitter_did: &str, ) -> VcxCoreResult<()> { @@ -155,6 +167,7 @@ impl AnoncredsLedgerWrite for MockLedger { async fn publish_rev_reg_def( &self, + wallet: &impl BaseWallet, rev_reg_def: &str, submitter_did: &str, ) -> VcxCoreResult<()> { @@ -163,6 +176,7 @@ impl AnoncredsLedgerWrite for MockLedger { async fn publish_rev_reg_delta( &self, + wallet: &impl BaseWallet, rev_reg_id: &str, rev_reg_entry_json: &str, submitter_did: &str, diff --git a/aries_vcx/src/utils/mockdata/profile/mock_profile.rs b/aries_vcx/src/utils/mockdata/profile/mock_profile.rs deleted file mode 100644 index 357a9421d4..0000000000 --- a/aries_vcx/src/utils/mockdata/profile/mock_profile.rs +++ /dev/null @@ -1,39 +0,0 @@ -use aries_vcx_core::{ledger::base_ledger::TxnAuthrAgrmtOptions, wallet::mock_wallet::MockWallet}; -use async_trait::async_trait; - -use super::{mock_anoncreds::MockAnoncreds, mock_ledger::MockLedger}; -use crate::{core::profile::Profile, errors::error::VcxResult}; - -/// Implementation of a [Profile] which uses [MockLedger], [MockAnoncreds] and [MockWallet] to -/// return mock data for all Profile methods. Only for unit testing purposes -#[derive(Debug)] -pub struct MockProfile; - -#[async_trait] -impl Profile for MockProfile { - type LedgerRead = MockLedger; - type LedgerWrite = MockLedger; - type Anoncreds = MockAnoncreds; - type Wallet = MockWallet; - - fn ledger_read(&self) -> &Self::LedgerRead { - &MockLedger - } - - fn ledger_write(&self) -> &Self::LedgerWrite { - &MockLedger - } - - fn anoncreds(&self) -> &Self::Anoncreds { - &MockAnoncreds - } - - fn wallet(&self) -> &Self::Wallet { - &MockWallet - } - - fn update_taa_configuration(&self, _taa_options: TxnAuthrAgrmtOptions) -> VcxResult<()> { - error!("update_taa_configuration not implemented for MockProfile"); - Ok(()) - } -} diff --git a/aries_vcx/src/utils/mockdata/profile/mod.rs b/aries_vcx/src/utils/mockdata/profile/mod.rs index 704a0287e5..ff388553a0 100644 --- a/aries_vcx/src/utils/mockdata/profile/mod.rs +++ b/aries_vcx/src/utils/mockdata/profile/mod.rs @@ -1,3 +1,2 @@ pub mod mock_anoncreds; pub mod mock_ledger; -pub mod mock_profile; diff --git a/aries_vcx/src/utils/mod.rs b/aries_vcx/src/utils/mod.rs index f6586aa221..79ef4b3e4d 100644 --- a/aries_vcx/src/utils/mod.rs +++ b/aries_vcx/src/utils/mod.rs @@ -30,6 +30,7 @@ macro_rules! secret { #[rustfmt::skip] pub mod constants; pub mod file; +pub mod ledger; pub mod mockdata; pub mod openssl; pub mod provision; diff --git a/aries_vcx/src/utils/test_logger.rs b/aries_vcx/src/utils/test_logger.rs index 784ad44c32..2c063e9ee6 100644 --- a/aries_vcx/src/utils/test_logger.rs +++ b/aries_vcx/src/utils/test_logger.rs @@ -55,10 +55,10 @@ fn text_no_color_format(buf: &mut Formatter, record: &Record) -> std::io::Result impl LibvcxDefaultLogger { pub fn init_testing_logger() { - env::var("RUST_LOG").map_or((), |log_pattern| { + if let Ok(log_pattern) = env::var("RUST_LOG") { LibvcxDefaultLogger::init(Some(log_pattern)) - .expect("Failed to initialize LibvcxDefaultLogger for testing"); - }); + .expect("Failed to initialize LibvcxDefaultLogger for testing") + } } pub fn init(pattern: Option) -> VcxResult<()> { diff --git a/aries_vcx/src/utils/validation.rs b/aries_vcx/src/utils/validation.rs index be4781f182..cdd703244c 100644 --- a/aries_vcx/src/utils/validation.rs +++ b/aries_vcx/src/utils/validation.rs @@ -43,11 +43,11 @@ pub fn validate_actors(actors: &str) -> VcxResult> { #[cfg(test)] mod unit_tests { use super::*; - use crate::utils::devsetup::SetupDefaults; + use crate::utils::devsetup::SetupMocks; #[test] fn test_did_is_b58_and_valid_length() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let to_did = "8XFh8yBzrpJQmNyZzgoTqB"; match validate_did(to_did) { @@ -58,7 +58,7 @@ mod unit_tests { #[test] fn test_did_is_b58_but_invalid_length() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let to_did = "8XFh8yBzrpJQmNyZzgoT"; match validate_did(to_did) { @@ -69,7 +69,7 @@ mod unit_tests { #[test] fn test_validate_did_with_non_base58() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let to_did = "8*Fh8yBzrpJQmNyZzgoTqB"; match validate_did(to_did) { diff --git a/aries_vcx/tests/test_connection.rs b/aries_vcx/tests/test_connection.rs index 15be5b549b..70e9ceab55 100644 --- a/aries_vcx/tests/test_connection.rs +++ b/aries_vcx/tests/test_connection.rs @@ -6,10 +6,16 @@ pub mod utils; use aries_vcx::{ common::ledger::transactions::write_endpoint_legacy, - core::profile::Profile, protocols::{connection::GenericConnection, mediated_connection::pairwise_info::PairwiseInfo}, utils::{devsetup::*, encryption_envelope::EncryptionEnvelope}, }; +use aries_vcx_core::{ + anoncreds::base_anoncreds::BaseAnonCreds, + ledger::base_ledger::{ + AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite, + }, + wallet::base_wallet::BaseWallet, +}; use chrono::Utc; use diddoc_legacy::aries::service::AriesService; use messages::{ @@ -49,13 +55,18 @@ fn build_basic_message(content: String) -> BasicMessage { .build() } -async fn decrypt_message( - consumer: &TestAgent

, +async fn decrypt_message( + consumer: &TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, received: Vec, consumer_to_institution: &GenericConnection, ) -> AriesMessage { EncryptionEnvelope::auth_unpack( - consumer.profile.wallet(), + &consumer.wallet, received, &consumer_to_institution.remote_vk().unwrap(), ) @@ -63,28 +74,46 @@ async fn decrypt_message( .unwrap() } -async fn send_and_receive_message( - consumer: &TestAgent, - insitution: &TestAgent, +async fn send_and_receive_message( + consumer: &TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, + insitution: &TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, institution_to_consumer: &GenericConnection, consumer_to_institution: &GenericConnection, message: &AriesMessage, ) -> AriesMessage { let encrypted_message = institution_to_consumer - .encrypt_message(insitution.profile.wallet(), message) + .encrypt_message(&insitution.wallet, message) .await .unwrap() .0; decrypt_message(consumer, encrypted_message, consumer_to_institution).await } -async fn create_service(faber: &TestAgent

) { - let pairwise_info = PairwiseInfo::create(faber.profile.wallet()).await.unwrap(); +async fn create_service( + faber: &TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, +) { + let pairwise_info = PairwiseInfo::create(&faber.wallet).await.unwrap(); let service = AriesService::create() .set_service_endpoint("http://dummy.org".parse().unwrap()) .set_recipient_keys(vec![pairwise_info.pw_vk.clone()]); write_endpoint_legacy( - faber.profile.ledger_write(), + &faber.wallet, + &faber.ledger_write, &faber.institution_did, &service, ) diff --git a/aries_vcx/tests/test_credential_issuance.rs b/aries_vcx/tests/test_credential_issuance.rs index 6f8b85da6c..2e91e396f7 100644 --- a/aries_vcx/tests/test_credential_issuance.rs +++ b/aries_vcx/tests/test_credential_issuance.rs @@ -29,7 +29,10 @@ async fn test_agency_pool_double_issuance_issuer_is_verifier() { let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( - &institution.profile, + &institution.wallet, + &institution.ledger_read, + &institution.ledger_write, + &institution.anoncreds, &institution.institution_did, ) .await; @@ -81,8 +84,14 @@ async fn test_agency_pool_two_creds_one_rev_reg() { let mut verifier = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; - let (schema, cred_def, rev_reg) = - create_address_schema_creddef_revreg(&issuer.profile, &issuer.institution_did).await; + let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( + &issuer.wallet, + &issuer.ledger_read, + &issuer.ledger_write, + &issuer.anoncreds, + &issuer.institution_did, + ) + .await; let credential_data1 = credential_data_address_1().to_string(); let _credential_handle1 = exchange_credential( &mut consumer, @@ -142,7 +151,10 @@ async fn test_agency_pool_credential_exchange_via_proposal() { let mut consumer = create_test_agent(setup.genesis_file_path).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( - &institution.profile, + &institution.wallet, + &institution.ledger_read, + &institution.ledger_write, + &institution.anoncreds, &institution.institution_did, ) .await; @@ -170,7 +182,10 @@ async fn test_agency_pool_credential_exchange_via_proposal_failed() { let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( - &institution.profile, + &institution.wallet, + &institution.ledger_read, + &institution.ledger_write, + &institution.anoncreds, &institution.institution_did, ) .await; @@ -209,7 +224,10 @@ async fn test_agency_pool_credential_exchange_via_proposal_with_negotiation() { let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( - &institution.profile, + &institution.wallet, + &institution.ledger_read, + &institution.ledger_write, + &institution.anoncreds, &institution.institution_did, ) .await; diff --git a/aries_vcx/tests/test_credential_retrieval.rs b/aries_vcx/tests/test_credential_retrieval.rs index 5deba6aca2..baee3904e2 100644 --- a/aries_vcx/tests/test_credential_retrieval.rs +++ b/aries_vcx/tests/test_credential_retrieval.rs @@ -73,7 +73,7 @@ async fn test_agency_pool_retrieve_credentials_empty() { let proof: Prover = Prover::create_from_request("1", proof_req).unwrap(); let retrieved_creds = proof - .retrieve_credentials(setup.profile.anoncreds()) + .retrieve_credentials(&setup.wallet, &setup.anoncreds) .await .unwrap(); assert_eq!( @@ -111,7 +111,7 @@ async fn test_agency_pool_retrieve_credentials_empty() { let proof: Prover = Prover::create_from_request("2", proof_req).unwrap(); let retrieved_creds = proof - .retrieve_credentials(setup.profile.anoncreds()) + .retrieve_credentials(&setup.wallet, &setup.anoncreds) .await .unwrap(); assert_eq!( @@ -134,24 +134,28 @@ async fn test_agency_pool_retrieve_credentials_empty() { async fn test_agency_pool_case_for_proof_req_doesnt_matter_for_retrieve_creds() { run_setup!(|setup| async move { let schema = create_and_write_test_schema( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; let cred_def = create_and_write_test_cred_def( - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, &schema.schema_id, true, ) .await; create_and_write_credential( - setup.profile.anoncreds(), - setup.profile.anoncreds(), + &setup.wallet, + &setup.wallet, + &setup.anoncreds, + &setup.anoncreds, &setup.institution_did, &cred_def, None, @@ -197,7 +201,7 @@ async fn test_agency_pool_case_for_proof_req_doesnt_matter_for_retrieve_creds() // All lower case let retrieved_creds = proof - .retrieve_credentials(setup.profile.anoncreds()) + .retrieve_credentials(&setup.wallet, &setup.anoncreds) .await .unwrap(); assert_eq!( @@ -233,7 +237,7 @@ async fn test_agency_pool_case_for_proof_req_doesnt_matter_for_retrieve_creds() .build(); let proof: Prover = Prover::create_from_request("2", proof_req).unwrap(); let retrieved_creds2 = proof - .retrieve_credentials(setup.profile.anoncreds()) + .retrieve_credentials(&setup.wallet, &setup.anoncreds) .await .unwrap(); assert_eq!( @@ -269,7 +273,7 @@ async fn test_agency_pool_case_for_proof_req_doesnt_matter_for_retrieve_creds() .build(); let proof: Prover = Prover::create_from_request("1", proof_req).unwrap(); let retrieved_creds3 = proof - .retrieve_credentials(setup.profile.anoncreds()) + .retrieve_credentials(&setup.wallet, &setup.anoncreds) .await .unwrap(); assert_eq!( diff --git a/aries_vcx/tests/test_pool.rs b/aries_vcx/tests/test_pool.rs index e39bce0e4d..b1c24bee4d 100644 --- a/aries_vcx/tests/test_pool.rs +++ b/aries_vcx/tests/test_pool.rs @@ -29,7 +29,6 @@ use aries_vcx::{ create_and_write_test_schema, }, }, - core::profile::Profile, errors::error::AriesVcxErrorKind, run_setup, utils::{ @@ -54,14 +53,17 @@ use crate::utils::{ // TODO: Deduplicate with create_and_store_revocable_credential_def async fn create_and_store_nonrevocable_credential_def( + wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger_read: &impl AnoncredsLedgerRead, ledger_write: &impl AnoncredsLedgerWrite, issuer_did: &str, attr_list: &str, ) -> (String, String, String, String, CredentialDef) { - let schema = create_and_write_test_schema(anoncreds, ledger_write, issuer_did, attr_list).await; + let schema = + create_and_write_test_schema(wallet, anoncreds, ledger_write, issuer_did, attr_list).await; let cred_def = create_and_write_test_cred_def( + wallet, anoncreds, ledger_read, ledger_write, @@ -85,14 +87,17 @@ async fn create_and_store_nonrevocable_credential_def( // TODO: Deduplicate with create_and_store_nonrevocable_credential_def async fn create_and_store_revocable_credential_def( + wallet: &impl BaseWallet, anoncreds: &impl BaseAnonCreds, ledger_read: &impl AnoncredsLedgerRead, ledger_write: &impl AnoncredsLedgerWrite, issuer_did: &str, attr_list: &str, ) -> (Schema, CredentialDef, RevocationRegistry) { - let schema = create_and_write_test_schema(anoncreds, ledger_write, issuer_did, attr_list).await; + let schema = + create_and_write_test_schema(wallet, anoncreds, ledger_write, issuer_did, attr_list).await; let cred_def = create_and_write_test_cred_def( + wallet, anoncreds, ledger_read, ledger_write, @@ -102,6 +107,7 @@ async fn create_and_store_revocable_credential_def( ) .await; let rev_reg = create_and_publish_test_rev_reg( + wallet, anoncreds, ledger_write, issuer_did, @@ -118,25 +124,20 @@ async fn create_and_store_revocable_credential_def( async fn test_pool_rotate_verkey() { run_setup!(|setup| async move { let (did, verkey) = add_new_did( - setup.profile.wallet(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.ledger_write, &setup.institution_did, None, ) .await .unwrap(); - rotate_verkey(setup.profile.wallet(), setup.profile.ledger_write(), &did) + rotate_verkey(&setup.wallet, &setup.ledger_write, &did) .await .unwrap(); tokio::time::sleep(Duration::from_millis(1000)).await; - let local_verkey = setup - .profile - .wallet() - .key_for_local_did(&did) - .await - .unwrap(); + let local_verkey = setup.wallet.key_for_local_did(&did).await.unwrap(); - let ledger_verkey = get_verkey_from_ledger(setup.profile.ledger_read(), &did) + let ledger_verkey = get_verkey_from_ledger(&setup.ledger_read, &did) .await .unwrap(); assert_ne!(verkey, ledger_verkey); @@ -151,18 +152,17 @@ async fn test_pool_add_get_service() { run_setup!(|setup| async move { let did = setup.institution_did.clone(); let expect_service = AriesService::default(); - write_endpoint_legacy(setup.profile.ledger_write(), &did, &expect_service) + write_endpoint_legacy(&setup.wallet, &setup.ledger_write, &did, &expect_service) .await .unwrap(); thread::sleep(Duration::from_millis(50)); - let service = get_service(setup.profile.ledger_read(), &did) - .await - .unwrap(); + let service = get_service(&setup.ledger_read, &did).await.unwrap(); assert_eq!(expect_service, service); // clean up written legacy service clear_attr( - setup.profile.ledger_write(), + &setup.wallet, + &setup.ledger_write, &setup.institution_did, "service", ) @@ -178,23 +178,23 @@ async fn test_pool_write_new_endorser_did() { SetupPoolDirectory::run(|setup| async move { let faber = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let acme = create_test_agent(setup.genesis_file_path.clone()).await; - let acme_vk = get_verkey_from_wallet( - acme.profile.wallet().get_wallet_handle(), - &acme.institution_did, - ) - .await - .unwrap(); + let acme_vk = + get_verkey_from_wallet(acme.wallet.get_wallet_handle(), &acme.institution_did) + .await + .unwrap(); let attrib_json = json!({ "attrib_name": "foo"}).to_string(); assert!(add_attr( - acme.profile.ledger_write(), + &acme.wallet, + &acme.ledger_write, &acme.institution_did, &attrib_json ) .await .is_err()); write_endorser_did( - faber.profile.ledger_write(), + &faber.wallet, + &faber.ledger_write, &faber.institution_did, &acme.institution_did, &acme_vk, @@ -204,7 +204,8 @@ async fn test_pool_write_new_endorser_did() { .unwrap(); thread::sleep(Duration::from_millis(50)); add_attr( - acme.profile.ledger_write(), + &acme.wallet, + &acme.ledger_write, &acme.institution_did, &attrib_json, ) @@ -222,15 +223,13 @@ async fn test_pool_add_get_service_public() { let create_service = EndpointDidSov::create() .set_service_endpoint("https://example.org".parse().unwrap()) .set_routing_keys(Some(vec!["did:sov:456".into()])); - write_endpoint(setup.profile.ledger_write(), &did, &create_service) + write_endpoint(&setup.wallet, &setup.ledger_write, &did, &create_service) .await .unwrap(); thread::sleep(Duration::from_millis(50)); - let service = get_service(setup.profile.ledger_read(), &did) - .await - .unwrap(); + let service = get_service(&setup.ledger_read, &did).await.unwrap(); let expect_recipient_key = - get_verkey_from_ledger(setup.profile.ledger_read(), &setup.institution_did) + get_verkey_from_ledger(&setup.ledger_read, &setup.institution_did) .await .unwrap(); let expect_service = AriesService::default() @@ -241,7 +240,8 @@ async fn test_pool_add_get_service_public() { // clean up written endpoint clear_attr( - setup.profile.ledger_write(), + &setup.wallet, + &setup.ledger_write, &setup.institution_did, "endpoint", ) @@ -259,15 +259,13 @@ async fn test_pool_add_get_service_public_none_routing_keys() { let create_service = EndpointDidSov::create() .set_service_endpoint("https://example.org".parse().unwrap()) .set_routing_keys(None); - write_endpoint(setup.profile.ledger_write(), &did, &create_service) + write_endpoint(&setup.wallet, &setup.ledger_write, &did, &create_service) .await .unwrap(); thread::sleep(Duration::from_millis(50)); - let service = get_service(setup.profile.ledger_read(), &did) - .await - .unwrap(); + let service = get_service(&setup.ledger_read, &did).await.unwrap(); let expect_recipient_key = - get_verkey_from_ledger(setup.profile.ledger_read(), &setup.institution_did) + get_verkey_from_ledger(&setup.ledger_read, &setup.institution_did) .await .unwrap(); let expect_service = AriesService::default() @@ -278,7 +276,8 @@ async fn test_pool_add_get_service_public_none_routing_keys() { // clean up written endpoint clear_attr( - setup.profile.ledger_write(), + &setup.wallet, + &setup.ledger_write, &setup.institution_did, "endpoint", ) @@ -299,14 +298,12 @@ async fn test_pool_multiple_service_formats() { .set_service_endpoint("https://example1.org".parse().unwrap()) .set_recipient_keys(vec!["did:sov:123".into()]) .set_routing_keys(vec!["did:sov:456".into()]); - write_endpoint_legacy(setup.profile.ledger_write(), &did, &service_1) + write_endpoint_legacy(&setup.wallet, &setup.ledger_write, &did, &service_1) .await .unwrap(); // Get service and verify it is in the old format - let service = get_service(setup.profile.ledger_read(), &did) - .await - .unwrap(); + let service = get_service(&setup.ledger_read, &did).await.unwrap(); assert_eq!(service_1, service); // Write new service format @@ -315,18 +312,16 @@ async fn test_pool_multiple_service_formats() { let service_2 = EndpointDidSov::create() .set_service_endpoint(endpoint_url_2.parse().unwrap()) .set_routing_keys(Some(routing_keys_2.clone())); - write_endpoint(setup.profile.ledger_write(), &did, &service_2) + write_endpoint(&setup.wallet, &setup.ledger_write, &did, &service_2) .await .unwrap(); thread::sleep(Duration::from_millis(50)); // Get service and verify it is in the new format - let service = get_service(setup.profile.ledger_read(), &did) - .await - .unwrap(); + let service = get_service(&setup.ledger_read, &did).await.unwrap(); let expect_recipient_key = - get_verkey_from_ledger(setup.profile.ledger_read(), &setup.institution_did) + get_verkey_from_ledger(&setup.ledger_read, &setup.institution_did) .await .unwrap(); let expect_service = AriesService::default() @@ -337,7 +332,8 @@ async fn test_pool_multiple_service_formats() { // Clear up written endpoint clear_attr( - setup.profile.ledger_write(), + &setup.wallet, + &setup.ledger_write, &setup.institution_did, "endpoint", ) @@ -347,9 +343,7 @@ async fn test_pool_multiple_service_formats() { thread::sleep(Duration::from_millis(50)); // Get service and verify it is in the old format - let service = get_service(setup.profile.ledger_read(), &did) - .await - .unwrap(); + let service = get_service(&setup.ledger_read, &did).await.unwrap(); assert_eq!(service_1, service); }) .await; @@ -366,25 +360,30 @@ async fn test_pool_add_get_attr() { "attr_key_2": "attr_value_2", } }); - add_attr(setup.profile.ledger_write(), &did, &attr_json.to_string()) - .await - .unwrap(); + add_attr( + &setup.wallet, + &setup.ledger_write, + &did, + &attr_json.to_string(), + ) + .await + .unwrap(); thread::sleep(Duration::from_millis(50)); - let attr = get_attr(setup.profile.ledger_read(), &did, "attr_json") + let attr = get_attr(&setup.ledger_read, &did, "attr_json") .await .unwrap(); assert_eq!(attr, attr_json["attr_json"].to_string()); - clear_attr(setup.profile.ledger_write(), &did, "attr_json") + clear_attr(&setup.wallet, &setup.ledger_write, &did, "attr_json") .await .unwrap(); thread::sleep(Duration::from_millis(50)); - let attr = get_attr(setup.profile.ledger_read(), &did, "attr_json") + let attr = get_attr(&setup.ledger_read, &did, "attr_json") .await .unwrap(); assert_eq!(attr, ""); - let attr = get_attr(setup.profile.ledger_read(), &did, "nonexistent") + let attr = get_attr(&setup.ledger_read, &did, "nonexistent") .await .unwrap(); assert_eq!(attr, ""); @@ -397,15 +396,16 @@ async fn test_pool_add_get_attr() { async fn test_agency_pool_get_credential_def() { run_setup!(|setup| async move { let (_, _, cred_def_id, cred_def_json, _) = create_and_store_nonrevocable_credential_def( - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; - let ledger = setup.profile.ledger_read(); + let ledger = &setup.ledger_read; let r_cred_def_json = ledger.get_cred_def(&cred_def_id, None).await.unwrap(); let def1: serde_json::Value = serde_json::from_str(&cred_def_json).unwrap(); @@ -422,16 +422,18 @@ async fn test_pool_rev_reg_def_fails_for_cred_def_created_without_revocation() { // Cred def is created with support_revocation=false, // revoc_reg_def will fail in libindy because cred_Def doesn't have revocation keys let (_, _, cred_def_id, _, _) = create_and_store_nonrevocable_credential_def( - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; let rc = generate_rev_reg( - setup.profile.anoncreds(), + &setup.wallet, + &setup.anoncreds, &setup.institution_did, &cred_def_id, get_temp_file_path("path.txt").to_str().unwrap(), @@ -454,15 +456,16 @@ async fn test_pool_get_rev_reg_def_json() { run_setup!(|setup| async move { let attrs = format!("{:?}", attr_names_address_list()); let (_, _, rev_reg) = create_and_store_revocable_credential_def( - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, &attrs, ) .await; - let ledger = setup.profile.ledger_read(); + let ledger = &setup.ledger_read; let _json = ledger .get_rev_reg_def_json(&rev_reg.rev_reg_id) .await @@ -477,15 +480,16 @@ async fn test_pool_get_rev_reg_delta_json() { run_setup!(|setup| async move { let attrs = format!("{:?}", attr_names_address_list()); let (_, _, rev_reg) = create_and_store_revocable_credential_def( - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, &attrs, ) .await; - let ledger = setup.profile.ledger_read(); + let ledger = &setup.ledger_read; let (id, _delta, _timestamp) = ledger .get_rev_reg_delta_json(&rev_reg.rev_reg_id, None, None) .await @@ -502,9 +506,10 @@ async fn test_pool_get_rev_reg() { run_setup!(|setup| async move { let attrs = format!("{:?}", attr_names_address_list()); let (_, _, rev_reg) = create_and_store_revocable_credential_def( - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, &attrs, ) @@ -514,7 +519,7 @@ async fn test_pool_get_rev_reg() { rev_reg.get_rev_reg_def().value.tails_location ); - let ledger = setup.profile.ledger_read(); + let ledger = &setup.ledger_read; let (id, _rev_reg, _timestamp) = ledger .get_rev_reg( &rev_reg.rev_reg_id, @@ -533,14 +538,15 @@ async fn test_pool_get_rev_reg() { async fn test_pool_create_and_get_schema() { run_setup!(|setup| async move { let schema = create_and_write_test_schema( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, DEFAULT_SCHEMA_ATTRS, ) .await; - let ledger = setup.profile.ledger_read(); + let ledger = &setup.ledger_read; let rc = ledger.get_schema(&schema.schema_id, None).await; let retrieved_schema = rc.unwrap(); @@ -555,17 +561,17 @@ async fn test_pool_create_rev_reg_delta_from_ledger() { run_setup!(|setup| async move { let attrs = format!("{:?}", attr_names_address_list()); let (_, _, rev_reg) = create_and_store_revocable_credential_def( - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, &attrs, ) .await; let (_, rev_reg_delta_json, _) = setup - .profile - .ledger_read() + .ledger_read .get_rev_reg_delta_json(&rev_reg.rev_reg_id, None, None) .await .unwrap(); diff --git a/aries_vcx/tests/test_proof_presentation.rs b/aries_vcx/tests/test_proof_presentation.rs index 4ba070df07..f6426a3cde 100644 --- a/aries_vcx/tests/test_proof_presentation.rs +++ b/aries_vcx/tests/test_proof_presentation.rs @@ -41,31 +41,36 @@ use crate::utils::{ async fn test_agency_pool_generate_proof_with_predicates() { run_setup!(|setup| async move { let schema = create_and_write_test_schema( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, aries_vcx::utils::constants::DEFAULT_SCHEMA_ATTRS, ) .await; let cred_def = create_and_write_test_cred_def( - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_read, + &setup.ledger_write, &setup.institution_did, &schema.schema_id, true, ) .await; let rev_reg = create_and_publish_test_rev_reg( - setup.profile.anoncreds(), - setup.profile.ledger_write(), + &setup.wallet, + &setup.anoncreds, + &setup.ledger_write, &setup.institution_did, &cred_def.get_cred_def_id(), ) .await; let _cred_id = create_and_write_credential( - setup.profile.anoncreds(), - setup.profile.anoncreds(), + &setup.wallet, + &setup.wallet, + &setup.anoncreds, + &setup.anoncreds, &setup.institution_did, &cred_def, Some(&rev_reg), @@ -110,7 +115,7 @@ async fn test_agency_pool_generate_proof_with_predicates() { let mut proof: Prover = Prover::create_from_request("1", proof_req).unwrap(); let all_creds = proof - .retrieve_credentials(setup.profile.anoncreds()) + .retrieve_credentials(&setup.wallet, &setup.anoncreds) .await .unwrap(); let selected_credentials: serde_json::Value = json!({ @@ -134,8 +139,9 @@ async fn test_agency_pool_generate_proof_with_predicates() { }); proof .generate_presentation( - setup.profile.ledger_read(), - setup.profile.anoncreds(), + &setup.wallet, + &setup.ledger_read, + &setup.anoncreds, serde_json::from_value(selected_credentials).unwrap(), serde_json::from_value(self_attested).unwrap(), ) @@ -145,8 +151,8 @@ async fn test_agency_pool_generate_proof_with_predicates() { let final_message = verifier .verify_presentation( - setup.profile.ledger_read(), - setup.profile.anoncreds(), + &setup.ledger_read, + &setup.anoncreds, proof.get_presentation_msg().unwrap(), ) .await @@ -174,7 +180,10 @@ async fn test_agency_pool_presentation_via_proposal() { let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( - &institution.profile, + &institution.wallet, + &institution.ledger_read, + &institution.ledger_write, + &institution.anoncreds, &institution.institution_did, ) .await; @@ -217,7 +226,10 @@ async fn test_agency_pool_presentation_via_proposal_with_rejection() { let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( - &institution.profile, + &institution.wallet, + &institution.ledger_read, + &institution.ledger_write, + &institution.anoncreds, &institution.institution_did, ) .await; @@ -251,7 +263,10 @@ async fn test_agency_pool_presentation_via_proposal_with_negotiation() { let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( - &institution.profile, + &institution.wallet, + &institution.ledger_read, + &institution.ledger_write, + &institution.anoncreds, &institution.institution_did, ) .await; diff --git a/aries_vcx/tests/test_revocations.rs b/aries_vcx/tests/test_revocations.rs index 8fe1aa29d0..38cc50e5c3 100644 --- a/aries_vcx/tests/test_revocations.rs +++ b/aries_vcx/tests/test_revocations.rs @@ -8,7 +8,6 @@ pub mod utils; use std::{thread, time::Duration}; use aries_vcx::{ - core::profile::Profile, protocols::proof_presentation::verifier::{ state_machine::VerifierState, verification_status::PresentationVerificationStatus, }, @@ -37,10 +36,7 @@ async fn test_agency_pool_basic_revocation() { let (schema, cred_def, rev_reg, issuer) = issue_address_credential(&mut consumer, &mut institution).await; - assert!(!issuer - .is_revoked(institution.profile.ledger_read()) - .await - .unwrap()); + assert!(!issuer.is_revoked(&institution.ledger_read).await.unwrap()); let time_before_revocation = time::OffsetDateTime::now_utc().unix_timestamp() as u64; revoke_credential_and_publish_accumulator(&mut institution, &issuer, &rev_reg).await; @@ -48,10 +44,7 @@ async fn test_agency_pool_basic_revocation() { tokio::time::sleep(Duration::from_millis(1000)).await; let time_after_revocation = time::OffsetDateTime::now_utc().unix_timestamp() as u64; - assert!(issuer - .is_revoked(institution.profile.ledger_read()) - .await - .unwrap()); + assert!(issuer.is_revoked(&institution.ledger_read).await.unwrap()); let requested_attrs = requested_attrs_address( &institution.institution_did, @@ -80,8 +73,8 @@ async fn test_agency_pool_basic_revocation() { verifier .verify_presentation( - institution.profile.ledger_read(), - institution.profile.anoncreds(), + &institution.ledger_read, + &institution.anoncreds, presentation, ) .await @@ -105,10 +98,7 @@ async fn test_agency_pool_revoked_credential_might_still_work() { let (schema, cred_def, rev_reg, issuer) = issue_address_credential(&mut consumer, &mut institution).await; - assert!(!issuer - .is_revoked(institution.profile.ledger_read()) - .await - .unwrap()); + assert!(!issuer.is_revoked(&institution.ledger_read).await.unwrap()); tokio::time::sleep(Duration::from_millis(1000)).await; let time_before_revocation = time::OffsetDateTime::now_utc().unix_timestamp() as u64; @@ -146,8 +136,8 @@ async fn test_agency_pool_revoked_credential_might_still_work() { verifier .verify_presentation( - institution.profile.ledger_read(), - institution.profile.anoncreds(), + &institution.ledger_read, + &institution.anoncreds, presentation, ) .await @@ -172,10 +162,7 @@ async fn test_agency_pool_local_revocation() { issue_address_credential(&mut consumer, &mut institution).await; revoke_credential_local(&mut institution, &issuer, &rev_reg.rev_reg_id).await; - assert!(!issuer - .is_revoked(institution.profile.ledger_read()) - .await - .unwrap()); + assert!(!issuer.is_revoked(&institution.ledger_read).await.unwrap()); let verifier_handler = exchange_proof( &mut institution, @@ -190,10 +177,7 @@ async fn test_agency_pool_local_revocation() { PresentationVerificationStatus::Valid ); - assert!(!issuer - .is_revoked(institution.profile.ledger_read()) - .await - .unwrap()); + assert!(!issuer.is_revoked(&institution.ledger_read).await.unwrap()); publish_revocation(&mut institution, &rev_reg).await; @@ -210,10 +194,7 @@ async fn test_agency_pool_local_revocation() { PresentationVerificationStatus::Invalid ); - assert!(issuer - .is_revoked(institution.profile.ledger_read()) - .await - .unwrap()); + assert!(issuer.is_revoked(&institution.ledger_read).await.unwrap()); }) .await; } @@ -229,7 +210,10 @@ async fn test_agency_batch_revocation() { // Issue and send three credentials of the same schema let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( - &institution.profile, + &institution.wallet, + &institution.ledger_read, + &institution.ledger_write, + &institution.anoncreds, &institution.institution_did, ) .await; @@ -267,15 +251,15 @@ async fn test_agency_batch_revocation() { revoke_credential_local(&mut institution, &issuer_credential1, &rev_reg.rev_reg_id).await; revoke_credential_local(&mut institution, &issuer_credential2, &rev_reg.rev_reg_id).await; assert!(!issuer_credential1 - .is_revoked(institution.profile.ledger_read()) + .is_revoked(&institution.ledger_read) .await .unwrap()); assert!(!issuer_credential2 - .is_revoked(institution.profile.ledger_read()) + .is_revoked(&institution.ledger_read) .await .unwrap()); assert!(!issuer_credential3 - .is_revoked(institution.profile.ledger_read()) + .is_revoked(&institution.ledger_read) .await .unwrap()); @@ -322,15 +306,15 @@ async fn test_agency_batch_revocation() { tokio::time::sleep(Duration::from_millis(1000)).await; assert!(issuer_credential1 - .is_revoked(institution.profile.ledger_read()) + .is_revoked(&institution.ledger_read) .await .unwrap()); assert!(issuer_credential2 - .is_revoked(institution.profile.ledger_read()) + .is_revoked(&institution.ledger_read) .await .unwrap()); assert!(!issuer_credential3 - .is_revoked(institution.profile.ledger_read()) + .is_revoked(&institution.ledger_read) .await .unwrap()); @@ -383,8 +367,14 @@ async fn test_agency_pool_two_creds_one_rev_reg_revoke_first() { let mut verifier = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; - let (schema, cred_def, rev_reg) = - create_address_schema_creddef_revreg(&issuer.profile, &issuer.institution_did).await; + let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( + &issuer.wallet, + &issuer.ledger_read, + &issuer.ledger_write, + &issuer.anoncreds, + &issuer.institution_did, + ) + .await; let credential_data1 = credential_data_address_1().to_string(); let issuer_credential1 = exchange_credential( &mut consumer, @@ -408,11 +398,11 @@ async fn test_agency_pool_two_creds_one_rev_reg_revoke_first() { .await; assert!(!issuer_credential1 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); assert!(!issuer_credential2 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); @@ -433,11 +423,7 @@ async fn test_agency_pool_two_creds_one_rev_reg_revoke_first() { ) .await; proof_verifier - .verify_presentation( - verifier.profile.ledger_read(), - verifier.profile.anoncreds(), - presentation, - ) + .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await .unwrap(); assert_eq!(proof_verifier.get_state(), VerifierState::Finished); @@ -462,11 +448,7 @@ async fn test_agency_pool_two_creds_one_rev_reg_revoke_first() { .await; proof_verifier - .verify_presentation( - verifier.profile.ledger_read(), - verifier.profile.anoncreds(), - presentation, - ) + .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await .unwrap(); assert_eq!( @@ -475,11 +457,11 @@ async fn test_agency_pool_two_creds_one_rev_reg_revoke_first() { ); assert!(issuer_credential1 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); assert!(!issuer_credential2 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); }) @@ -495,8 +477,14 @@ async fn test_agency_pool_two_creds_one_rev_reg_revoke_second() { let mut verifier = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; - let (schema, cred_def, rev_reg) = - create_address_schema_creddef_revreg(&issuer.profile, &issuer.institution_did).await; + let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( + &issuer.wallet, + &issuer.ledger_read, + &issuer.ledger_write, + &issuer.anoncreds, + &issuer.institution_did, + ) + .await; let credential_data1 = credential_data_address_1().to_string(); let issuer_credential1 = exchange_credential( &mut consumer, @@ -520,11 +508,11 @@ async fn test_agency_pool_two_creds_one_rev_reg_revoke_second() { .await; assert!(!issuer_credential1 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); assert!(!issuer_credential2 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); @@ -544,11 +532,7 @@ async fn test_agency_pool_two_creds_one_rev_reg_revoke_second() { ) .await; proof_verifier - .verify_presentation( - verifier.profile.ledger_read(), - verifier.profile.anoncreds(), - presentation, - ) + .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await .unwrap(); assert_eq!(proof_verifier.get_state(), VerifierState::Finished); @@ -572,11 +556,7 @@ async fn test_agency_pool_two_creds_one_rev_reg_revoke_second() { .await; proof_verifier - .verify_presentation( - verifier.profile.ledger_read(), - verifier.profile.anoncreds(), - presentation, - ) + .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await .unwrap(); assert_eq!( @@ -585,11 +565,11 @@ async fn test_agency_pool_two_creds_one_rev_reg_revoke_second() { ); assert!(!issuer_credential1 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); assert!(issuer_credential2 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); }) @@ -604,8 +584,14 @@ async fn test_agency_pool_two_creds_two_rev_reg_id() { let mut verifier = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; - let (schema, cred_def, rev_reg) = - create_address_schema_creddef_revreg(&issuer.profile, &issuer.institution_did).await; + let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( + &issuer.wallet, + &issuer.ledger_read, + &issuer.ledger_write, + &issuer.anoncreds, + &issuer.institution_did, + ) + .await; let credential_data1 = credential_data_address_1().to_string(); let issuer_credential1 = exchange_credential( &mut consumer, @@ -643,11 +629,7 @@ async fn test_agency_pool_two_creds_two_rev_reg_id() { ) .await; proof_verifier - .verify_presentation( - verifier.profile.ledger_read(), - verifier.profile.anoncreds(), - presentation, - ) + .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await .unwrap(); assert_eq!(proof_verifier.get_state(), VerifierState::Finished); @@ -671,11 +653,7 @@ async fn test_agency_pool_two_creds_two_rev_reg_id() { ) .await; proof_verifier - .verify_presentation( - verifier.profile.ledger_read(), - verifier.profile.anoncreds(), - presentation, - ) + .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await .unwrap(); assert_eq!(proof_verifier.get_state(), VerifierState::Finished); @@ -685,11 +663,11 @@ async fn test_agency_pool_two_creds_two_rev_reg_id() { ); assert!(!issuer_credential1 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); assert!(!issuer_credential2 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); }) @@ -705,8 +683,14 @@ async fn test_agency_pool_two_creds_two_rev_reg_id_revoke_first() { let mut verifier = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; - let (schema, cred_def, rev_reg) = - create_address_schema_creddef_revreg(&issuer.profile, &issuer.institution_did).await; + let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( + &issuer.wallet, + &issuer.ledger_read, + &issuer.ledger_write, + &issuer.anoncreds, + &issuer.institution_did, + ) + .await; let credential_data1 = credential_data_address_1().to_string(); let issuer_credential1 = exchange_credential( &mut consumer, @@ -731,11 +715,11 @@ async fn test_agency_pool_two_creds_two_rev_reg_id_revoke_first() { .await; assert!(!issuer_credential1 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); assert!(!issuer_credential2 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); @@ -755,11 +739,7 @@ async fn test_agency_pool_two_creds_two_rev_reg_id_revoke_first() { ) .await; proof_verifier - .verify_presentation( - verifier.profile.ledger_read(), - verifier.profile.anoncreds(), - presentation, - ) + .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await .unwrap(); assert_eq!(proof_verifier.get_state(), VerifierState::Finished); @@ -783,11 +763,7 @@ async fn test_agency_pool_two_creds_two_rev_reg_id_revoke_first() { .await; proof_verifier - .verify_presentation( - verifier.profile.ledger_read(), - verifier.profile.anoncreds(), - presentation, - ) + .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await .unwrap(); assert_eq!( @@ -796,11 +772,11 @@ async fn test_agency_pool_two_creds_two_rev_reg_id_revoke_first() { ); assert!(issuer_credential1 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); assert!(!issuer_credential2 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); }) @@ -815,8 +791,14 @@ async fn test_agency_pool_two_creds_two_rev_reg_id_revoke_second() { let mut verifier = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path).await; - let (schema, cred_def, rev_reg) = - create_address_schema_creddef_revreg(&issuer.profile, &issuer.institution_did).await; + let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( + &issuer.wallet, + &issuer.ledger_read, + &issuer.ledger_write, + &issuer.anoncreds, + &issuer.institution_did, + ) + .await; let credential_data1 = credential_data_address_1().to_string(); let issuer_credential1 = exchange_credential( &mut consumer, @@ -841,11 +823,11 @@ async fn test_agency_pool_two_creds_two_rev_reg_id_revoke_second() { .await; assert!(!issuer_credential1 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); assert!(!issuer_credential2 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); @@ -867,11 +849,7 @@ async fn test_agency_pool_two_creds_two_rev_reg_id_revoke_second() { .await; proof_verifier - .verify_presentation( - verifier.profile.ledger_read(), - verifier.profile.anoncreds(), - presentation, - ) + .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await .unwrap(); assert_eq!(proof_verifier.get_state(), VerifierState::Finished); @@ -895,11 +873,7 @@ async fn test_agency_pool_two_creds_two_rev_reg_id_revoke_second() { .await; proof_verifier - .verify_presentation( - verifier.profile.ledger_read(), - verifier.profile.anoncreds(), - presentation, - ) + .verify_presentation(&verifier.ledger_read, &verifier.anoncreds, presentation) .await .unwrap(); assert_eq!(proof_verifier.get_state(), VerifierState::Finished); @@ -909,11 +883,11 @@ async fn test_agency_pool_two_creds_two_rev_reg_id_revoke_second() { ); assert!(!issuer_credential1 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); assert!(issuer_credential2 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); }) @@ -927,8 +901,14 @@ async fn test_agency_pool_three_creds_one_rev_reg_revoke_all() { let mut issuer = create_test_agent_trustee(setup.genesis_file_path.clone()).await; let mut consumer = create_test_agent(setup.genesis_file_path.clone()).await; - let (_schema, cred_def, rev_reg) = - create_address_schema_creddef_revreg(&issuer.profile, &issuer.institution_did).await; + let (_schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( + &issuer.wallet, + &issuer.ledger_read, + &issuer.ledger_write, + &issuer.anoncreds, + &issuer.institution_did, + ) + .await; let issuer_credential1 = exchange_credential( &mut consumer, @@ -941,7 +921,7 @@ async fn test_agency_pool_three_creds_one_rev_reg_revoke_all() { .await; assert!(!issuer_credential1 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); revoke_credential_local(&mut issuer, &issuer_credential1, &rev_reg.rev_reg_id).await; @@ -957,7 +937,7 @@ async fn test_agency_pool_three_creds_one_rev_reg_revoke_all() { .await; assert!(!issuer_credential2 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); @@ -977,15 +957,15 @@ async fn test_agency_pool_three_creds_one_rev_reg_revoke_all() { thread::sleep(Duration::from_millis(100)); assert!(issuer_credential1 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); assert!(issuer_credential2 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); assert!(issuer_credential3 - .is_revoked(issuer.profile.ledger_read()) + .is_revoked(&issuer.ledger_read) .await .unwrap()); }) diff --git a/aries_vcx/tests/utils/scenarios/connection.rs b/aries_vcx/tests/utils/scenarios/connection.rs index dfee4c1359..c039c24a79 100644 --- a/aries_vcx/tests/utils/scenarios/connection.rs +++ b/aries_vcx/tests/utils/scenarios/connection.rs @@ -1,6 +1,5 @@ use aries_vcx::{ common::ledger::transactions::into_did_doc, - core::profile::Profile, errors::error::VcxResult, handlers::{out_of_band::sender::OutOfBandSender, util::AnyInvitation}, protocols::{ @@ -9,6 +8,13 @@ use aries_vcx::{ }, transport::Transport, }; +use aries_vcx_core::{ + anoncreds::base_anoncreds::BaseAnonCreds, + ledger::base_ledger::{ + AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite, + }, + wallet::base_wallet::BaseWallet, +}; use async_trait::async_trait; use messages::{ msg_fields::protocols::{ @@ -25,9 +31,19 @@ use uuid::Uuid; use crate::utils::test_agent::TestAgent; -async fn establish_connection_from_invite( - alice: &mut TestAgent, - faber: &mut TestAgent, +async fn establish_connection_from_invite( + alice: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, invitation: AnyInvitation, inviter_pairwise_info: PairwiseInfo, ) -> (GenericConnection, GenericConnection) { @@ -41,9 +57,9 @@ async fn establish_connection_from_invite( } } - let invitee_pairwise_info = PairwiseInfo::create(alice.profile.wallet()).await.unwrap(); + let invitee_pairwise_info = PairwiseInfo::create(&alice.wallet).await.unwrap(); let invitee = Connection::new_invitee("".to_owned(), invitee_pairwise_info) - .accept_invitation(alice.profile.ledger_read(), invitation.clone()) + .accept_invitation(&alice.ledger_read, invitation.clone()) .await .unwrap() .prepare_request("http://dummy.org".parse().unwrap(), vec![]) @@ -54,7 +70,7 @@ async fn establish_connection_from_invite( let inviter = Connection::new_inviter("".to_owned(), inviter_pairwise_info) .into_invited(invitation.id()) .handle_request( - faber.profile.wallet(), + &faber.wallet, request, "http://dummy.org".parse().unwrap(), vec![], @@ -64,7 +80,7 @@ async fn establish_connection_from_invite( let response = inviter.get_connection_response_msg(); let invitee = invitee - .handle_response(alice.profile.wallet(), response) + .handle_response(&alice.wallet, response) .await .unwrap(); let ack = invitee.get_ack(); @@ -74,9 +90,19 @@ async fn establish_connection_from_invite( (invitee.into(), inviter.into()) } -pub async fn create_connections_via_oob_invite( - alice: &mut TestAgent, - faber: &mut TestAgent, +pub async fn create_connections_via_oob_invite( + alice: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, ) -> (GenericConnection, GenericConnection) { let oob_sender = OutOfBandSender::create() .set_label("test-label") @@ -88,9 +114,7 @@ pub async fn create_connections_via_oob_invite( ))) .unwrap(); let invitation = AnyInvitation::Oob(oob_sender.oob.clone()); - let ddo = into_did_doc(alice.profile.ledger_read(), &invitation) - .await - .unwrap(); + let ddo = into_did_doc(&alice.ledger_read, &invitation).await.unwrap(); // TODO: Create a key and write on ledger instead let inviter_pairwise_info = PairwiseInfo { pw_did: ddo.clone().id, @@ -99,9 +123,19 @@ pub async fn create_connections_via_oob_invite( establish_connection_from_invite(alice, faber, invitation, inviter_pairwise_info).await } -pub async fn create_connections_via_public_invite( - alice: &mut TestAgent, - faber: &mut TestAgent, +pub async fn create_connections_via_public_invite( + alice: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, ) -> (GenericConnection, GenericConnection) { let content = InvitationContent::builder_public() .label("faber".to_owned()) @@ -114,7 +148,7 @@ pub async fn create_connections_via_public_invite( .content(content) .build(), ); - let ddo = into_did_doc(alice.profile.ledger_read(), &public_invite) + let ddo = into_did_doc(&alice.ledger_read, &public_invite) .await .unwrap(); // TODO: Create a key and write on ledger instead @@ -126,11 +160,21 @@ pub async fn create_connections_via_public_invite( .await } -pub async fn create_connections_via_pairwise_invite( - alice: &mut TestAgent, - faber: &mut TestAgent, +pub async fn create_connections_via_pairwise_invite( + alice: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, ) -> (GenericConnection, GenericConnection) { - let inviter_pairwise_info = PairwiseInfo::create(faber.profile.wallet()).await.unwrap(); + let inviter_pairwise_info = PairwiseInfo::create(&faber.wallet).await.unwrap(); let invite = { let id = Uuid::new_v4().to_string(); let content = InvitationContent::builder_pairwise() diff --git a/aries_vcx/tests/utils/scenarios/credential_issuance.rs b/aries_vcx/tests/utils/scenarios/credential_issuance.rs index 7763ce78e0..a9383a0f3f 100644 --- a/aries_vcx/tests/utils/scenarios/credential_issuance.rs +++ b/aries_vcx/tests/utils/scenarios/credential_issuance.rs @@ -11,7 +11,6 @@ use aries_vcx::{ create_and_write_test_schema, }, }, - core::profile::Profile, handlers::{ issuance::{holder::Holder, issuer::Issuer}, util::OfferInfo, @@ -22,6 +21,13 @@ use aries_vcx::{ }, utils::constants::TEST_TAILS_URL, }; +use aries_vcx_core::{ + anoncreds::base_anoncreds::BaseAnonCreds, + ledger::base_ledger::{ + AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite, + }, + wallet::base_wallet::BaseWallet, +}; use messages::msg_fields::protocols::{ cred_issuance::v1::{ offer_credential::OfferCredentialV1, propose_credential::ProposeCredentialV1, @@ -34,15 +40,15 @@ use serde_json::json; use super::{attr_names_address_list, create_credential_proposal, credential_data_address_1}; use crate::utils::test_agent::TestAgent; -pub async fn create_address_schema_creddef_revreg( - profile: &P, +pub async fn create_address_schema_creddef_revreg( + wallet: &impl BaseWallet, + ledger_read: &(impl IndyLedgerRead + AnoncredsLedgerRead), + ledger_write: &(impl IndyLedgerWrite + AnoncredsLedgerWrite), + anoncreds: &impl BaseAnonCreds, institution_did: &str, ) -> (Schema, CredentialDef, RevocationRegistry) { - let ledger_read = profile.ledger_read(); - let ledger_write = profile.ledger_write(); - let anoncreds = profile.anoncreds(); - let schema = create_and_write_test_schema( + wallet, anoncreds, ledger_write, institution_did, @@ -50,6 +56,7 @@ pub async fn create_address_schema_creddef_revreg( ) .await; let cred_def = create_and_write_test_cred_def( + wallet, anoncreds, ledger_read, ledger_write, @@ -59,6 +66,7 @@ pub async fn create_address_schema_creddef_revreg( ) .await; let rev_reg = create_and_publish_test_rev_reg( + wallet, anoncreds, ledger_write, institution_did, @@ -83,8 +91,13 @@ pub fn create_issuer_from_proposal(proposal: ProposeCredentialV1) -> Issuer { issuer } -pub async fn accept_credential_proposal( - faber: &mut TestAgent

, +pub async fn accept_credential_proposal( + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, issuer: &mut Issuer, cred_proposal: ProposeCredentialV1, rev_reg_id: Option, @@ -98,7 +111,8 @@ pub async fn accept_credential_proposal( }; issuer .build_credential_offer_msg( - faber.profile.anoncreds(), + &faber.wallet, + &faber.anoncreds, offer_info, Some("comment".into()), ) @@ -107,16 +121,22 @@ pub async fn accept_credential_proposal( issuer.get_credential_offer().unwrap() } -pub async fn accept_offer( - alice: &mut TestAgent

, +pub async fn accept_offer( + alice: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, cred_offer: OfferCredentialV1, holder: &mut Holder, ) -> RequestCredentialV1 { // TODO: Replace with message-specific handler holder .process_aries_msg( - alice.profile.ledger_read(), - alice.profile.anoncreds(), + &alice.wallet, + &alice.ledger_read, + &alice.anoncreds, cred_offer.into(), ) .await @@ -125,12 +145,10 @@ pub async fn accept_offer( assert!(holder.get_offer().is_ok()); holder .prepare_credential_request( - alice.profile.ledger_read(), - alice.profile.anoncreds(), - PairwiseInfo::create(alice.profile.wallet()) - .await - .unwrap() - .pw_did, + &alice.wallet, + &alice.ledger_read, + &alice.anoncreds, + PairwiseInfo::create(&alice.wallet).await.unwrap().pw_did, ) .await .unwrap(); @@ -138,16 +156,22 @@ pub async fn accept_offer( holder.get_msg_credential_request().unwrap() } -pub async fn decline_offer( - alice: &mut TestAgent

, +pub async fn decline_offer( + alice: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, cred_offer: OfferCredentialV1, holder: &mut Holder, ) -> ProblemReport { // TODO: Replace with message-specific handler holder .process_aries_msg( - alice.profile.ledger_read(), - alice.profile.anoncreds(), + &alice.wallet, + &alice.ledger_read, + &alice.anoncreds, cred_offer.into(), ) .await @@ -158,9 +182,19 @@ pub async fn decline_offer( problem_report } -pub async fn send_credential( - alice: &mut TestAgent, - faber: &mut TestAgent, +pub async fn send_credential( + alice: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, issuer_credential: &mut Issuer, holder_credential: &mut Holder, cred_request: RequestCredentialV1, @@ -179,7 +213,7 @@ pub async fn send_credential( assert_eq!(thread_id, issuer_credential.get_thread_id().unwrap()); issuer_credential - .build_credential(faber.profile.anoncreds()) + .build_credential(&faber.wallet, &faber.anoncreds) .await .unwrap(); let credential = issuer_credential.get_msg_issue_credential().unwrap(); @@ -188,15 +222,16 @@ pub async fn send_credential( assert_eq!(thread_id, holder_credential.get_thread_id().unwrap()); assert_eq!( holder_credential - .is_revokable(alice.profile.ledger_read()) + .is_revokable(&alice.ledger_read) .await .unwrap(), revokable ); holder_credential .process_credential( - alice.profile.ledger_read(), - alice.profile.anoncreds(), + &alice.wallet, + &alice.ledger_read, + &alice.anoncreds, credential, ) .await @@ -204,7 +239,7 @@ pub async fn send_credential( assert_eq!(HolderState::Finished, holder_credential.get_state()); assert_eq!( holder_credential - .is_revokable(alice.profile.ledger_read()) + .is_revokable(&alice.ledger_read) .await .unwrap(), revokable @@ -220,13 +255,28 @@ pub async fn send_credential( } } -pub async fn issue_address_credential( - consumer: &mut TestAgent, - institution: &mut TestAgent, +pub async fn issue_address_credential( + consumer: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, + institution: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, ) -> (Schema, CredentialDef, RevocationRegistry, Issuer) { - let (schema, cred_def, rev_reg) = - create_address_schema_creddef_revreg(&institution.profile, &institution.institution_did) - .await; + let (schema, cred_def, rev_reg) = create_address_schema_creddef_revreg( + &institution.wallet, + &institution.ledger_read, + &institution.ledger_write, + &institution.anoncreds, + &institution.institution_did, + ) + .await; let issuer = exchange_credential( consumer, institution, @@ -239,9 +289,19 @@ pub async fn issue_address_credential( (schema, cred_def, rev_reg, issuer) } -pub async fn exchange_credential( - consumer: &mut TestAgent, - institution: &mut TestAgent, +pub async fn exchange_credential( + consumer: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, + institution: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, credential_data: String, cred_def: &CredentialDef, rev_reg: &RevocationRegistry, @@ -262,15 +322,25 @@ pub async fn exchange_credential( ) .await; assert!(!holder_credential - .is_revoked(consumer.profile.ledger_read(), consumer.profile.anoncreds(),) + .is_revoked(&consumer.wallet, &consumer.ledger_read, &consumer.anoncreds) .await .unwrap()); issuer } -pub async fn exchange_credential_with_proposal( - consumer: &mut TestAgent, - institution: &mut TestAgent, +pub async fn exchange_credential_with_proposal( + consumer: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, + institution: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, schema_id: &str, cred_def_id: &str, rev_reg_id: Option, @@ -301,8 +371,13 @@ pub async fn exchange_credential_with_proposal( (holder, issuer) } -async fn create_credential_offer( - faber: &mut TestAgent

, +async fn create_credential_offer( + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, cred_def: &CredentialDef, rev_reg: &RevocationRegistry, credential_json: &str, @@ -317,7 +392,8 @@ async fn create_credential_offer( let mut issuer = Issuer::create("1").unwrap(); issuer .build_credential_offer_msg( - faber.profile.anoncreds(), + &faber.wallet, + &faber.anoncreds, offer_info, comment.map(String::from), ) @@ -326,20 +402,23 @@ async fn create_credential_offer( issuer } -async fn create_credential_request( - alice: &mut TestAgent

, +async fn create_credential_request( + alice: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, cred_offer: OfferCredentialV1, ) -> Holder { let mut holder = Holder::create_from_offer("TEST_CREDENTIAL", cred_offer).unwrap(); assert_eq!(HolderState::OfferReceived, holder.get_state()); holder .prepare_credential_request( - alice.profile.ledger_read(), - alice.profile.anoncreds(), - PairwiseInfo::create(alice.profile.wallet()) - .await - .unwrap() - .pw_did, + &alice.wallet, + &alice.ledger_read, + &alice.anoncreds, + PairwiseInfo::create(&alice.wallet).await.unwrap().pw_did, ) .await .unwrap(); diff --git a/aries_vcx/tests/utils/scenarios/proof_presentation.rs b/aries_vcx/tests/utils/scenarios/proof_presentation.rs index 1b6d327d0b..c1635a3def 100644 --- a/aries_vcx/tests/utils/scenarios/proof_presentation.rs +++ b/aries_vcx/tests/utils/scenarios/proof_presentation.rs @@ -7,7 +7,6 @@ use aries_vcx::{ }, proofs::{proof_request::PresentationRequestData, proof_request_internal::AttrInfo}, }, - core::profile::Profile, handlers::{ issuance::issuer::Issuer, proof_presentation::{ @@ -25,8 +24,13 @@ use aries_vcx::{ }, utils::constants::{DEFAULT_PROOF_NAME, TEST_TAILS_URL}, }; -use aries_vcx_core::ledger::{ - base_ledger::AnoncredsLedgerRead, indy::pool::test_utils::get_temp_dir_path, +use aries_vcx_core::{ + anoncreds::base_anoncreds::BaseAnonCreds, + ledger::{ + base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite}, + indy::pool::test_utils::get_temp_dir_path, + }, + wallet::base_wallet::BaseWallet, }; use messages::{ msg_fields::protocols::{ @@ -57,15 +61,20 @@ pub async fn create_proof_proposal(prover: &mut Prover, cred_def_id: &str) -> Pr proposal } -pub async fn accept_proof_proposal( - faber: &mut TestAgent

, +pub async fn accept_proof_proposal( + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, verifier: &mut Verifier, presentation_proposal: ProposePresentation, ) -> RequestPresentation { verifier .process_aries_msg( - faber.profile.ledger_read(), - faber.profile.anoncreds(), + &faber.ledger_read, + &faber.anoncreds, presentation_proposal.clone().into(), ) .await @@ -84,12 +93,11 @@ pub async fn accept_proof_proposal( ..AttrInfo::default() }) .collect(); - let presentation_request_data = - PresentationRequestData::create(faber.profile.anoncreds(), "request-1") - .await - .unwrap() - .set_requested_attributes_as_vec(attrs) - .unwrap(); + let presentation_request_data = PresentationRequestData::create(&faber.anoncreds, "request-1") + .await + .unwrap() + .set_requested_attributes_as_vec(attrs) + .unwrap(); verifier .set_presentation_request(presentation_request_data, None) .unwrap(); @@ -116,14 +124,19 @@ pub async fn receive_proof_proposal_rejection(prover: &mut Prover, rejection: Pr assert_eq!(prover.get_state(), ProverState::Failed); } -pub async fn create_proof_request_data( - faber: &mut TestAgent

, +pub async fn create_proof_request_data( + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, requested_attrs: &str, requested_preds: &str, revocation_interval: &str, request_name: Option<&str>, ) -> PresentationRequestData { - PresentationRequestData::create(faber.profile.anoncreds(), request_name.unwrap_or("name")) + PresentationRequestData::create(&faber.anoncreds, request_name.unwrap_or("name")) .await .unwrap() .set_requested_attributes_as_string(requested_attrs.to_string()) @@ -147,8 +160,13 @@ pub async fn create_verifier_from_request_data( verifier } -pub async fn generate_and_send_proof( - alice: &mut TestAgent

, +pub async fn generate_and_send_proof( + alice: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, prover: &mut Prover, selected_credentials: SelectedCredentials, ) -> Option { @@ -159,8 +177,9 @@ pub async fn generate_and_send_proof( ); prover .generate_presentation( - alice.profile.ledger_read(), - alice.profile.anoncreds(), + &alice.wallet, + &alice.ledger_read, + &alice.anoncreds, selected_credentials, HashMap::new(), ) @@ -182,17 +201,18 @@ pub async fn generate_and_send_proof( } } -pub async fn verify_proof( - faber: &mut TestAgent

, +pub async fn verify_proof( + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, verifier: &mut Verifier, presentation: Presentation, ) -> AckPresentation { let msg = verifier - .verify_presentation( - faber.profile.ledger_read(), - faber.profile.anoncreds(), - presentation, - ) + .verify_presentation(&faber.ledger_read, &faber.anoncreds, presentation) .await .unwrap(); let msg = match msg { @@ -208,8 +228,13 @@ pub async fn verify_proof( msg } -pub async fn revoke_credential_and_publish_accumulator( - faber: &mut TestAgent

, +pub async fn revoke_credential_and_publish_accumulator( + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, issuer_credential: &Issuer, rev_reg: &RevocationRegistry, ) { @@ -217,27 +242,33 @@ pub async fn revoke_credential_and_publish_accumulator( rev_reg .publish_local_revocations( - faber.profile.anoncreds(), - faber.profile.ledger_write(), + &faber.wallet, + &faber.anoncreds, + &faber.ledger_write, &faber.institution_did, ) .await .unwrap(); } -pub async fn revoke_credential_local( - faber: &mut TestAgent

, +pub async fn revoke_credential_local( + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, issuer_credential: &Issuer, rev_reg_id: &str, ) { - let ledger = faber.profile.ledger_read(); + let ledger = &faber.ledger_read; let (_, delta, timestamp) = ledger .get_rev_reg_delta_json(rev_reg_id, None, None) .await .unwrap(); issuer_credential - .revoke_credential_local(faber.profile.anoncreds()) + .revoke_credential_local(&faber.wallet, &faber.anoncreds) .await .unwrap(); @@ -250,13 +281,19 @@ pub async fn revoke_credential_local( // cache } -pub async fn rotate_rev_reg( - faber: &mut TestAgent

, +pub async fn rotate_rev_reg( + faber: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, credential_def: &CredentialDef, rev_reg: &RevocationRegistry, ) -> RevocationRegistry { let mut rev_reg = RevocationRegistry::create( - faber.profile.anoncreds(), + &faber.wallet, + &faber.anoncreds, &faber.institution_did, &credential_def.get_cred_def_id(), &rev_reg.get_tails_dir(), @@ -266,28 +303,39 @@ pub async fn rotate_rev_reg( .await .unwrap(); rev_reg - .publish_revocation_primitives(faber.profile.ledger_write(), TEST_TAILS_URL) + .publish_revocation_primitives(&faber.wallet, &faber.ledger_write, TEST_TAILS_URL) .await .unwrap(); rev_reg } -pub async fn publish_revocation( - institution: &mut TestAgent

, +pub async fn publish_revocation( + institution: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, rev_reg: &RevocationRegistry, ) { rev_reg .publish_local_revocations( - institution.profile.anoncreds(), - institution.profile.ledger_write(), + &institution.wallet, + &institution.anoncreds, + &institution.ledger_write, &institution.institution_did, ) .await .unwrap(); } -pub async fn verifier_create_proof_and_send_request( - institution: &mut TestAgent

, +pub async fn verifier_create_proof_and_send_request( + institution: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, schema_id: &str, cred_def_id: &str, request_name: Option<&str>, @@ -310,9 +358,14 @@ pub async fn verifier_create_proof_and_send_request( create_verifier_from_request_data(presentation_request_data).await } -pub async fn prover_select_credentials( +pub async fn prover_select_credentials( prover: &mut Prover, - alice: &mut TestAgent

, + alice: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, presentation_request: RequestPresentation, preselected_credentials: Option<&str>, ) -> SelectedCredentials { @@ -322,7 +375,7 @@ pub async fn prover_select_credentials( .unwrap(); assert_eq!(prover.get_state(), ProverState::PresentationRequestReceived); let retrieved_credentials = prover - .retrieve_credentials(alice.profile.anoncreds()) + .retrieve_credentials(&alice.wallet, &alice.anoncreds) .await .unwrap(); info!("prover_select_credentials >> retrieved_credentials: {retrieved_credentials:?}"); @@ -341,8 +394,13 @@ pub async fn prover_select_credentials( } } -pub async fn prover_select_credentials_and_send_proof( - alice: &mut TestAgent

, +pub async fn prover_select_credentials_and_send_proof( + alice: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, presentation_request: RequestPresentation, preselected_credentials: Option<&str>, ) -> Presentation { @@ -432,9 +490,19 @@ pub fn match_preselected_credentials( selected_credentials } -pub async fn exchange_proof( - institution: &mut TestAgent, - consumer: &mut TestAgent, +pub async fn exchange_proof( + institution: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, + consumer: &mut TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, + >, schema_id: &str, cred_def_id: &str, request_name: Option<&str>, @@ -451,8 +519,8 @@ pub async fn exchange_proof( verifier .verify_presentation( - institution.profile.ledger_read(), - institution.profile.anoncreds(), + &institution.ledger_read, + &institution.anoncreds, presentation, ) .await diff --git a/aries_vcx/tests/utils/test_agent.rs b/aries_vcx/tests/utils/test_agent.rs index 38b2ba77d8..f3a87658ac 100644 --- a/aries_vcx/tests/utils/test_agent.rs +++ b/aries_vcx/tests/utils/test_agent.rs @@ -1,9 +1,6 @@ #![allow(clippy::diverging_sub_expression)] -use std::sync::Arc; - use aries_vcx::{ - core::profile::Profile, global::settings::DEFAULT_LINK_SECRET_ALIAS, utils::{ constants::TRUSTEE_SEED, @@ -11,10 +8,25 @@ use aries_vcx::{ random::generate_random_seed, }, }; -use aries_vcx_core::{anoncreds::base_anoncreds::BaseAnonCreds, wallet::indy::IndySdkWallet}; +use aries_vcx_core::{ + anoncreds::base_anoncreds::BaseAnonCreds, + ledger::base_ledger::{ + AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite, + }, + wallet::{base_wallet::BaseWallet, indy::IndySdkWallet}, +}; -pub struct TestAgent { - pub profile: P, +pub struct TestAgent +where + LR: IndyLedgerRead + AnoncredsLedgerRead, + LW: IndyLedgerWrite + AnoncredsLedgerWrite, + A: BaseAnonCreds, + W: BaseWallet, +{ + pub ledger_read: LR, + pub ledger_write: LW, + pub anoncreds: A, + pub wallet: W, pub institution_did: String, pub genesis_file_path: String, } @@ -22,26 +34,50 @@ pub struct TestAgent { async fn create_test_agent_from_seed( seed: &str, genesis_file_path: String, -) -> TestAgent { +) -> TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, +> { let (institution_did, wallet_handle) = dev_setup_wallet_indy(seed).await; - let wallet = Arc::new(IndySdkWallet::new(wallet_handle)); - let profile = dev_build_featured_profile(genesis_file_path.clone(), wallet).await; - profile - .anoncreds() - .prover_create_link_secret(DEFAULT_LINK_SECRET_ALIAS) + let wallet = IndySdkWallet::new(wallet_handle); + let (ledger_read, ledger_write, anoncreds) = + dev_build_featured_profile(genesis_file_path.clone()).await; + + anoncreds + .prover_create_link_secret(&wallet, DEFAULT_LINK_SECRET_ALIAS) .await .unwrap(); + TestAgent { genesis_file_path, - profile, institution_did, + wallet, + ledger_read, + ledger_write, + anoncreds, } } -pub async fn create_test_agent_trustee(genesis_file_path: String) -> TestAgent { +pub async fn create_test_agent_trustee( + genesis_file_path: String, +) -> TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, +> { create_test_agent_from_seed(TRUSTEE_SEED, genesis_file_path).await } -pub async fn create_test_agent(genesis_file_path: String) -> TestAgent { +pub async fn create_test_agent( + genesis_file_path: String, +) -> TestAgent< + impl IndyLedgerRead + AnoncredsLedgerRead, + impl IndyLedgerWrite + AnoncredsLedgerWrite, + impl BaseAnonCreds, + impl BaseWallet, +> { create_test_agent_from_seed(&generate_random_seed(), genesis_file_path).await } diff --git a/aries_vcx_core/src/anoncreds/base_anoncreds.rs b/aries_vcx_core/src/anoncreds/base_anoncreds.rs index 6390bd1c54..04bfbbb3b0 100644 --- a/aries_vcx_core/src/anoncreds/base_anoncreds.rs +++ b/aries_vcx_core/src/anoncreds/base_anoncreds.rs @@ -1,6 +1,6 @@ use async_trait::async_trait; -use crate::errors::error::VcxCoreResult; +use crate::{errors::error::VcxCoreResult, wallet::base_wallet::BaseWallet}; /// Trait defining standard 'anoncreds' related functionality. The APIs, including /// input and output types are based off the indy Anoncreds API: @@ -19,6 +19,7 @@ pub trait BaseAnonCreds: std::fmt::Debug + Send + Sync { async fn issuer_create_and_store_revoc_reg( &self, + wallet: &impl BaseWallet, issuer_did: &str, cred_def_id: &str, tails_dir: &str, @@ -28,6 +29,7 @@ pub trait BaseAnonCreds: std::fmt::Debug + Send + Sync { async fn issuer_create_and_store_credential_def( &self, + wallet: &impl BaseWallet, issuer_did: &str, schema_json: &str, tag: &str, @@ -35,10 +37,15 @@ pub trait BaseAnonCreds: std::fmt::Debug + Send + Sync { config_json: &str, ) -> VcxCoreResult<(String, String)>; - async fn issuer_create_credential_offer(&self, cred_def_id: &str) -> VcxCoreResult; + async fn issuer_create_credential_offer( + &self, + wallet: &impl BaseWallet, + cred_def_id: &str, + ) -> VcxCoreResult; async fn issuer_create_credential( &self, + wallet: &impl BaseWallet, cred_offer_json: &str, cred_req_json: &str, cred_values_json: &str, @@ -46,8 +53,10 @@ pub trait BaseAnonCreds: std::fmt::Debug + Send + Sync { tails_dir: Option, ) -> VcxCoreResult<(String, Option, Option)>; + #[allow(clippy::too_many_arguments)] async fn prover_create_proof( &self, + wallet: &impl BaseWallet, proof_req_json: &str, requested_credentials_json: &str, master_secret_id: &str, @@ -56,17 +65,27 @@ pub trait BaseAnonCreds: std::fmt::Debug + Send + Sync { revoc_states_json: Option<&str>, ) -> VcxCoreResult; - async fn prover_get_credential(&self, cred_id: &str) -> VcxCoreResult; + async fn prover_get_credential( + &self, + wallet: &impl BaseWallet, + cred_id: &str, + ) -> VcxCoreResult; - async fn prover_get_credentials(&self, filter_json: Option<&str>) -> VcxCoreResult; + async fn prover_get_credentials( + &self, + wallet: &impl BaseWallet, + filter_json: Option<&str>, + ) -> VcxCoreResult; async fn prover_get_credentials_for_proof_req( &self, + wallet: &impl BaseWallet, proof_request_json: &str, ) -> VcxCoreResult; async fn prover_create_credential_req( &self, + wallet: &impl BaseWallet, prover_did: &str, cred_offer_json: &str, cred_def_json: &str, @@ -84,6 +103,7 @@ pub trait BaseAnonCreds: std::fmt::Debug + Send + Sync { async fn prover_store_credential( &self, + wallet: &impl BaseWallet, cred_id: Option<&str>, cred_req_metadata_json: &str, cred_json: &str, @@ -91,9 +111,17 @@ pub trait BaseAnonCreds: std::fmt::Debug + Send + Sync { rev_reg_def_json: Option<&str>, ) -> VcxCoreResult; - async fn prover_delete_credential(&self, cred_id: &str) -> VcxCoreResult<()>; + async fn prover_delete_credential( + &self, + wallet: &impl BaseWallet, + cred_id: &str, + ) -> VcxCoreResult<()>; - async fn prover_create_link_secret(&self, link_secret_id: &str) -> VcxCoreResult; + async fn prover_create_link_secret( + &self, + wallet: &impl BaseWallet, + link_secret_id: &str, + ) -> VcxCoreResult; async fn issuer_create_schema( &self, @@ -107,14 +135,23 @@ pub trait BaseAnonCreds: std::fmt::Debug + Send + Sync { // PURE Anoncreds) async fn revoke_credential_local( &self, + wallet: &impl BaseWallet, tails_dir: &str, rev_reg_id: &str, cred_rev_id: &str, ) -> VcxCoreResult<()>; - async fn get_rev_reg_delta(&self, rev_reg_id: &str) -> VcxCoreResult>; + async fn get_rev_reg_delta( + &self, + wallet: &impl BaseWallet, + rev_reg_id: &str, + ) -> VcxCoreResult>; - async fn clear_rev_reg_delta(&self, rev_reg_id: &str) -> VcxCoreResult<()>; + async fn clear_rev_reg_delta( + &self, + wallet: &impl BaseWallet, + rev_reg_id: &str, + ) -> VcxCoreResult<()>; async fn generate_nonce(&self) -> VcxCoreResult; } diff --git a/aries_vcx_core/src/anoncreds/credx_anoncreds.rs b/aries_vcx_core/src/anoncreds/credx_anoncreds.rs index 6b2d2f3988..1b5dbd7ca1 100644 --- a/aries_vcx_core/src/anoncreds/credx_anoncreds.rs +++ b/aries_vcx_core/src/anoncreds/credx_anoncreds.rs @@ -188,29 +188,27 @@ impl BaseWallet for WalletAdapter { } } -#[derive(Debug)] -pub struct IndyCredxAnonCreds { - wallet: WalletAdapter, -} +#[derive(Debug, Copy, Clone)] +pub struct IndyCredxAnonCreds; impl IndyCredxAnonCreds { - pub fn new(wallet: Arc) -> Self { - IndyCredxAnonCreds { - wallet: WalletAdapter(wallet), - } - } - - async fn get_wallet_record_value(&self, category: &str, id: &str) -> VcxCoreResult + async fn get_wallet_record_value( + wallet: &impl BaseWallet, + category: &str, + id: &str, + ) -> VcxCoreResult where T: DeserializeOwned, { - let str_record = self.wallet.get_wallet_record_value(category, id).await?; + let str_record = wallet.get_wallet_record_value(category, id).await?; serde_json::from_str(&str_record).map_err(From::from) } - async fn get_link_secret(&self, link_secret_id: &str) -> VcxCoreResult { - let record = self - .wallet + async fn get_link_secret( + wallet: &impl BaseWallet, + link_secret_id: &str, + ) -> VcxCoreResult { + let record = wallet .get_wallet_record(CATEGORY_LINK_SECRET, link_secret_id, "{}") .await?; @@ -232,9 +230,11 @@ impl IndyCredxAnonCreds { Ok(LinkSecret { value: ursa_ms }) } - async fn _get_credential(&self, credential_id: &str) -> VcxCoreResult { - let cred_record = self - .wallet + async fn _get_credential( + wallet: &impl BaseWallet, + credential_id: &str, + ) -> VcxCoreResult { + let cred_record = wallet .get_wallet_record(CATEGORY_CREDENTIAL, credential_id, "{}") .await?; let cred_record: Value = serde_json::from_str(&cred_record)?; @@ -247,9 +247,11 @@ impl IndyCredxAnonCreds { Ok(credential) } - async fn _get_credentials(&self, wql: &str) -> VcxCoreResult> { - let mut record_iterator = self - .wallet + async fn _get_credentials( + wallet: &impl BaseWallet, + wql: &str, + ) -> VcxCoreResult> { + let mut record_iterator = wallet .iterate_wallet_records(CATEGORY_CREDENTIAL, wql, "{}") .await?; let records = record_iterator.collect().await?; @@ -275,6 +277,7 @@ impl IndyCredxAnonCreds { async fn _get_credentials_for_proof_req_for_attr_name( &self, + wallet: &impl BaseWallet, restrictions: Option<&Value>, attr_names: Vec, ) -> VcxCoreResult> { @@ -314,7 +317,7 @@ impl IndyCredxAnonCreds { let wql_query = serde_json::to_string(&wql_query)?; - self._get_credentials(&wql_query).await + Self::_get_credentials(wallet, &wql_query).await } } @@ -376,6 +379,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { async fn issuer_create_and_store_revoc_reg( &self, + wallet: &impl BaseWallet, issuer_did: &str, cred_def_id: &str, tails_dir: &str, @@ -386,9 +390,8 @@ impl BaseAnonCreds for IndyCredxAnonCreds { let mut tails_writer = TailsFileWriter::new(Some(tails_dir.to_owned())); - let cred_def = self - .get_wallet_record_value(CATEGORY_CRED_DEF, cred_def_id) - .await?; + let cred_def = + Self::get_wallet_record_value(wallet, CATEGORY_CRED_DEF, cred_def_id).await?; let rev_reg_id = credx::issuer::make_revocation_registry_id( &issuer_did, @@ -397,12 +400,10 @@ impl BaseAnonCreds for IndyCredxAnonCreds { RegistryType::CL_ACCUM, )?; - let res_rev_reg = self - .get_wallet_record_value(CATEGORY_REV_REG, &rev_reg_id.0) - .await; - let res_rev_reg_def = self - .get_wallet_record_value(CATEGORY_REV_REG_DEF, &rev_reg_id.0) - .await; + let res_rev_reg = + Self::get_wallet_record_value(wallet, CATEGORY_REV_REG, &rev_reg_id.0).await; + let res_rev_reg_def = + Self::get_wallet_record_value(wallet, CATEGORY_REV_REG_DEF, &rev_reg_id.0).await; if let (Ok(rev_reg), Ok(rev_reg_def)) = (res_rev_reg, res_rev_reg_def) { return Ok((rev_reg_id.0, rev_reg, rev_reg_def)); @@ -428,7 +429,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { let str_rev_reg_info = serde_json::to_string(&rev_reg_info)?; - self.wallet + wallet .add_wallet_record( CATEGORY_REV_REG_INFO, &rev_reg_id.0, @@ -439,13 +440,13 @@ impl BaseAnonCreds for IndyCredxAnonCreds { let str_rev_reg_def = serde_json::to_string(&rev_reg_def)?; - self.wallet + wallet .add_wallet_record(CATEGORY_REV_REG_DEF, &rev_reg_id.0, &str_rev_reg_def, None) .await?; let str_rev_reg_def_priv = serde_json::to_string(&rev_reg_def_priv)?; - self.wallet + wallet .add_wallet_record( CATEGORY_REV_REG_DEF_PRIV, &rev_reg_id.0, @@ -456,7 +457,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { let str_rev_reg = serde_json::to_string(&rev_reg)?; - self.wallet + wallet .add_wallet_record(CATEGORY_REV_REG, &rev_reg_id.0, &str_rev_reg, None) .await?; @@ -465,6 +466,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { async fn issuer_create_and_store_credential_def( &self, + wallet: &impl BaseWallet, issuer_did: &str, schema_json: &str, tag: &str, @@ -491,9 +493,8 @@ impl BaseAnonCreds for IndyCredxAnonCreds { )?; // If cred def already exists, return it - if let Ok(cred_def) = self - .get_wallet_record_value(CATEGORY_CRED_DEF, &cred_def_id.0) - .await + if let Ok(cred_def) = + Self::get_wallet_record_value(wallet, CATEGORY_CRED_DEF, &cred_def_id.0).await { return Ok((cred_def_id.0, cred_def)); } @@ -511,13 +512,13 @@ impl BaseAnonCreds for IndyCredxAnonCreds { let str_cred_def = serde_json::to_string(&cred_def)?; // Store stuff in wallet - self.wallet + wallet .add_wallet_record(CATEGORY_CRED_DEF, &cred_def_id.0, &str_cred_def, None) .await?; let str_cred_def_priv = serde_json::to_string(&cred_def_priv)?; - self.wallet + wallet .add_wallet_record( CATEGORY_CRED_DEF_PRIV, &cred_def_id.0, @@ -528,7 +529,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { let str_cred_key_proof = serde_json::to_string(&cred_key_correctness_proof)?; - self.wallet + wallet .add_wallet_record( CATEGORY_CRED_KEY_CORRECTNESS_PROOF, &cred_def_id.0, @@ -537,8 +538,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { ) .await?; - let store_schema_res = self - .wallet + let store_schema_res = wallet .add_wallet_record(CATEGORY_CRED_SCHEMA, schema.id(), schema_json, None) .await; @@ -546,7 +546,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { warn!("Storing schema {schema_json} failed - {e}. It's possible it is already stored.") } - self.wallet + wallet .add_wallet_record( CATEGORY_CRED_MAP_SCHEMA_ID, &cred_def_id.0, @@ -559,17 +559,19 @@ impl BaseAnonCreds for IndyCredxAnonCreds { Ok((cred_def_id.0.to_owned(), str_cred_def)) } - async fn issuer_create_credential_offer(&self, cred_def_id: &str) -> VcxCoreResult { - let cred_def = self - .get_wallet_record_value(CATEGORY_CRED_DEF, cred_def_id) - .await?; + async fn issuer_create_credential_offer( + &self, + wallet: &impl BaseWallet, + cred_def_id: &str, + ) -> VcxCoreResult { + let cred_def = + Self::get_wallet_record_value(wallet, CATEGORY_CRED_DEF, cred_def_id).await?; - let correctness_proof = self - .get_wallet_record_value(CATEGORY_CRED_KEY_CORRECTNESS_PROOF, cred_def_id) - .await?; + let correctness_proof = + Self::get_wallet_record_value(wallet, CATEGORY_CRED_KEY_CORRECTNESS_PROOF, cred_def_id) + .await?; - let schema_id = self - .wallet + let schema_id = wallet .get_wallet_record_value(CATEGORY_CRED_MAP_SCHEMA_ID, cred_def_id) .await?; @@ -584,6 +586,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { async fn issuer_create_credential( &self, + wallet: &impl BaseWallet, cred_offer_json: &str, cred_req_json: &str, cred_values_json: &str, @@ -598,30 +601,26 @@ impl BaseAnonCreds for IndyCredxAnonCreds { // it let cred_def_id = &cred_offer.cred_def_id.0; - let cred_def = self - .get_wallet_record_value(CATEGORY_CRED_DEF, cred_def_id) - .await?; + let cred_def = + Self::get_wallet_record_value(wallet, CATEGORY_CRED_DEF, cred_def_id).await?; - let cred_def_private = self - .get_wallet_record_value(CATEGORY_CRED_DEF_PRIV, cred_def_id) - .await?; + let cred_def_private = + Self::get_wallet_record_value(wallet, CATEGORY_CRED_DEF_PRIV, cred_def_id).await?; let mut revocation_config_parts = match &rev_reg_id { Some(rev_reg_id) => { - let rev_reg_def = self - .get_wallet_record_value(CATEGORY_REV_REG_DEF, rev_reg_id) - .await?; + let rev_reg_def = + Self::get_wallet_record_value(wallet, CATEGORY_REV_REG_DEF, rev_reg_id).await?; - let rev_reg_def_priv = self - .get_wallet_record_value(CATEGORY_REV_REG_DEF_PRIV, rev_reg_id) - .await?; + let rev_reg_def_priv = + Self::get_wallet_record_value(wallet, CATEGORY_REV_REG_DEF_PRIV, rev_reg_id) + .await?; - let rev_reg = self - .get_wallet_record_value(CATEGORY_REV_REG, rev_reg_id) - .await?; - let rev_reg_info: RevocationRegistryInfo = self - .get_wallet_record_value(CATEGORY_REV_REG_INFO, rev_reg_id) - .await?; + let rev_reg = + Self::get_wallet_record_value(wallet, CATEGORY_REV_REG, rev_reg_id).await?; + let rev_reg_info: RevocationRegistryInfo = + Self::get_wallet_record_value(wallet, CATEGORY_REV_REG_INFO, rev_reg_id) + .await?; Some((rev_reg_def, rev_reg_def_priv, rev_reg, rev_reg_info)) } @@ -687,11 +686,11 @@ impl BaseAnonCreds for IndyCredxAnonCreds { let cred_rev_id = rev_reg_info.curr_id.to_string(); let str_rev_reg_info = serde_json::to_string(&rev_reg_info)?; - self.wallet + wallet .update_wallet_record_value(CATEGORY_REV_REG, &rev_reg_id, str_rev_reg) .await?; - self.wallet + wallet .update_wallet_record_value( CATEGORY_REV_REG_INFO, &rev_reg_id, @@ -718,6 +717,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { /// "timestamp": Optional }}, } } async fn prover_create_proof( &self, + wallet: &impl BaseWallet, proof_req_json: &str, requested_credentials_json: &str, link_secret_id: &str, @@ -769,7 +769,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { // mapping made for this credential already, add reft and its revealed status req_attr_refts_revealed.push((reft.to_string(), revealed)); } else { - let credential = self._get_credential(cred_id).await?; + let credential = Self::_get_credential(wallet, cred_id).await?; let (timestamp, rev_state) = get_rev_state(cred_id, &credential, detail, rev_states.as_ref())?; @@ -796,7 +796,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { // mapping made for this credential already, add reft req_preds_refts.push(reft.to_string()); } else { - let credential = self._get_credential(cred_id).await?; + let credential = Self::_get_credential(wallet, cred_id).await?; let (timestamp, rev_state) = get_rev_state(cred_id, &credential, detail, rev_states.as_ref())?; @@ -851,7 +851,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { None }; - let link_secret = self.get_link_secret(link_secret_id).await?; + let link_secret = Self::get_link_secret(wallet, link_secret_id).await?; let presentation = credx::prover::create_presentation( &pres_req, @@ -865,20 +865,28 @@ impl BaseAnonCreds for IndyCredxAnonCreds { Ok(serde_json::to_string(&presentation)?) } - async fn prover_get_credential(&self, cred_id: &str) -> VcxCoreResult { - let cred = self._get_credential(cred_id).await?; + async fn prover_get_credential( + &self, + wallet: &impl BaseWallet, + cred_id: &str, + ) -> VcxCoreResult { + let cred = Self::_get_credential(wallet, cred_id).await?; let cred_info = _make_cred_info(cred_id, &cred)?; Ok(serde_json::to_string(&cred_info)?) } - async fn prover_get_credentials(&self, filter_json: Option<&str>) -> VcxCoreResult { + async fn prover_get_credentials( + &self, + wallet: &impl BaseWallet, + filter_json: Option<&str>, + ) -> VcxCoreResult { // filter_json should map to WQL query directly // TODO - future - may wish to validate the filter_json for more accurate error reporting let creds_wql = filter_json.map_or("{}", |x| x); - let creds = self._get_credentials(creds_wql).await?; + let creds = Self::_get_credentials(wallet, creds_wql).await?; let cred_info_list: VcxCoreResult> = creds .iter() @@ -890,7 +898,11 @@ impl BaseAnonCreds for IndyCredxAnonCreds { Ok(serde_json::to_string(&cred_info_list)?) } - async fn prover_get_credentials_for_proof_req(&self, proof_req: &str) -> VcxCoreResult { + async fn prover_get_credentials_for_proof_req( + &self, + wallet: &impl BaseWallet, + proof_req: &str, + ) -> VcxCoreResult { let proof_req_v: Value = serde_json::from_str(proof_req).map_err(|e| { AriesVcxCoreError::from_msg(AriesVcxCoreErrorKind::InvalidProofRequest, e) })?; @@ -965,7 +977,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { let restrictions = requested_val.get("restrictions"); let credx_creds = self - ._get_credentials_for_proof_req_for_attr_name(restrictions, attr_names) + ._get_credentials_for_proof_req_for_attr_name(wallet, restrictions, attr_names) .await?; let mut credentials_json = vec![]; @@ -985,6 +997,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { async fn prover_create_credential_req( &self, + wallet: &impl BaseWallet, prover_did: &str, credential_offer_json: &str, credential_def_json: &str, @@ -993,7 +1006,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { let prover_did = DidValue::new(prover_did, None); let cred_def: CredentialDefinition = serde_json::from_str(credential_def_json)?; let credential_offer: CredentialOffer = serde_json::from_str(credential_offer_json)?; - let link_secret = self.get_link_secret(link_secret_id).await?; + let link_secret = Self::get_link_secret(wallet, link_secret_id).await?; let (cred_req, cred_req_metadata) = credx::prover::create_credential_request( &prover_did, @@ -1053,6 +1066,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { async fn prover_store_credential( &self, + wallet: &impl BaseWallet, cred_id: Option<&str>, cred_req_meta: &str, cred_json: &str, @@ -1062,7 +1076,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { let mut credential: CredxCredential = serde_json::from_str(cred_json)?; let cred_request_metadata: CredentialRequestMetadata = serde_json::from_str(cred_req_meta)?; let link_secret_id = &cred_request_metadata.master_secret_name; - let link_secret = self.get_link_secret(link_secret_id).await?; + let link_secret = Self::get_link_secret(wallet, link_secret_id).await?; let cred_def: CredentialDefinition = serde_json::from_str(cred_def_json)?; let rev_reg_def: Option = if let Some(rev_reg_def_json) = rev_reg_def_json { @@ -1122,7 +1136,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { let record_value = serde_json::to_string(&credential)?; let tags_json: HashMap = serde_json::from_value(tags)?; - self.wallet + wallet .add_wallet_record( CATEGORY_CREDENTIAL, &credential_id, @@ -1134,9 +1148,12 @@ impl BaseAnonCreds for IndyCredxAnonCreds { Ok(credential_id) } - async fn prover_create_link_secret(&self, link_secret_id: &str) -> VcxCoreResult { - let existing_record = self - .wallet + async fn prover_create_link_secret( + &self, + wallet: &impl BaseWallet, + link_secret_id: &str, + ) -> VcxCoreResult { + let existing_record = wallet .get_wallet_record(CATEGORY_LINK_SECRET, link_secret_id, "{}") .await .ok(); // ignore error, as we only care about whether it exists or not @@ -1175,15 +1192,19 @@ impl BaseAnonCreds for IndyCredxAnonCreds { ) })?; - self.wallet + wallet .add_wallet_record(CATEGORY_LINK_SECRET, link_secret_id, &ms_decimal, None) .await?; return Ok(link_secret_id.to_string()); } - async fn prover_delete_credential(&self, cred_id: &str) -> VcxCoreResult<()> { - self.wallet + async fn prover_delete_credential( + &self, + wallet: &impl BaseWallet, + cred_id: &str, + ) -> VcxCoreResult<()> { + wallet .delete_wallet_record(CATEGORY_CREDENTIAL, cred_id) .await } @@ -1208,6 +1229,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { async fn revoke_credential_local( &self, + wallet: &impl BaseWallet, _tails_dir: &str, rev_reg_id: &str, cred_rev_id: &str, @@ -1219,21 +1241,16 @@ impl BaseAnonCreds for IndyCredxAnonCreds { ) })?; - let rev_reg = self - .get_wallet_record_value(CATEGORY_REV_REG, rev_reg_id) - .await?; + let rev_reg = Self::get_wallet_record_value(wallet, CATEGORY_REV_REG, rev_reg_id).await?; - let rev_reg_def = self - .get_wallet_record_value(CATEGORY_REV_REG_DEF, rev_reg_id) - .await?; + let rev_reg_def = + Self::get_wallet_record_value(wallet, CATEGORY_REV_REG_DEF, rev_reg_id).await?; - let rev_reg_priv = self - .get_wallet_record_value(CATEGORY_REV_REG_DEF_PRIV, rev_reg_id) - .await?; + let rev_reg_priv = + Self::get_wallet_record_value(wallet, CATEGORY_REV_REG_DEF_PRIV, rev_reg_id).await?; - let mut rev_reg_info: RevocationRegistryInfo = self - .get_wallet_record_value(CATEGORY_REV_REG_INFO, rev_reg_id) - .await?; + let mut rev_reg_info: RevocationRegistryInfo = + Self::get_wallet_record_value(wallet, CATEGORY_REV_REG_INFO, rev_reg_id).await?; let (issuance_type, cred_def_id) = match &rev_reg_def { RevocationRegistryDefinition::RevocationRegistryDefinitionV1(r) => { @@ -1241,9 +1258,8 @@ impl BaseAnonCreds for IndyCredxAnonCreds { } }; - let cred_def = self - .get_wallet_record_value(CATEGORY_CRED_DEF, cred_def_id) - .await?; + let cred_def = + Self::get_wallet_record_value(wallet, CATEGORY_CRED_DEF, cred_def_id).await?; match issuance_type { IssuanceType::ISSUANCE_ON_DEMAND => { @@ -1280,7 +1296,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { cred_rev_id, )?; - let old_str_rev_reg_delta = self.get_rev_reg_delta(rev_reg_id).await?; + let old_str_rev_reg_delta = self.get_rev_reg_delta(wallet, rev_reg_id).await?; let rev_reg_delta = old_str_rev_reg_delta .as_ref() @@ -1297,17 +1313,17 @@ impl BaseAnonCreds for IndyCredxAnonCreds { let str_rev_reg = serde_json::to_string(&rev_reg)?; let str_rev_reg_delta = serde_json::to_string(&rev_reg_delta)?; - self.wallet + wallet .update_wallet_record_value(CATEGORY_REV_REG, rev_reg_id, &str_rev_reg) .await?; - self.wallet + wallet .update_wallet_record_value(CATEGORY_REV_REG_INFO, rev_reg_id, &str_rev_reg_info) .await?; match old_str_rev_reg_delta { Some(_) => { - self.wallet + wallet .update_wallet_record_value( CATEGORY_REV_REG_DELTA, rev_reg_id, @@ -1316,7 +1332,7 @@ impl BaseAnonCreds for IndyCredxAnonCreds { .await? } None => { - self.wallet + wallet .add_wallet_record(CATEGORY_REV_REG_DELTA, rev_reg_id, &str_rev_reg_delta, None) .await? } @@ -1325,10 +1341,17 @@ impl BaseAnonCreds for IndyCredxAnonCreds { Ok(()) } - async fn get_rev_reg_delta(&self, rev_reg_id: &str) -> VcxCoreResult> { - let res_rev_reg_delta = self - .get_wallet_record_value::(CATEGORY_REV_REG_DELTA, rev_reg_id) - .await; + async fn get_rev_reg_delta( + &self, + wallet: &impl BaseWallet, + rev_reg_id: &str, + ) -> VcxCoreResult> { + let res_rev_reg_delta = Self::get_wallet_record_value::( + wallet, + CATEGORY_REV_REG_DELTA, + rev_reg_id, + ) + .await; if let Err(err) = &res_rev_reg_delta { warn!( @@ -1355,9 +1378,13 @@ impl BaseAnonCreds for IndyCredxAnonCreds { Ok(res_rev_reg_delta.ok().flatten()) } - async fn clear_rev_reg_delta(&self, rev_reg_id: &str) -> VcxCoreResult<()> { - if self.get_rev_reg_delta(rev_reg_id).await?.is_some() { - self.wallet + async fn clear_rev_reg_delta( + &self, + wallet: &impl BaseWallet, + rev_reg_id: &str, + ) -> VcxCoreResult<()> { + if self.get_rev_reg_delta(wallet, rev_reg_id).await?.is_some() { + wallet .delete_wallet_record(CATEGORY_REV_REG_DELTA, rev_reg_id) .await?; } diff --git a/aries_vcx_core/src/ledger/base_ledger.rs b/aries_vcx_core/src/ledger/base_ledger.rs index b52d7d47da..37916df78b 100644 --- a/aries_vcx_core/src/ledger/base_ledger.rs +++ b/aries_vcx_core/src/ledger/base_ledger.rs @@ -4,7 +4,7 @@ use async_trait::async_trait; use indy_vdr::ledger::constants::UpdateRole; use serde::Serialize; -use crate::errors::error::VcxCoreResult; +use crate::{errors::error::VcxCoreResult, wallet::base_wallet::BaseWallet}; #[async_trait] pub trait IndyLedgerRead: Debug + Send + Sync { @@ -22,6 +22,7 @@ pub trait IndyLedgerRead: Debug + Send + Sync { pub trait IndyLedgerWrite: Debug + Send + Sync { async fn publish_nym( &self, + wallet: &impl BaseWallet, submitter_did: &str, target_did: &str, verkey: Option<&str>, @@ -30,18 +31,26 @@ pub trait IndyLedgerWrite: Debug + Send + Sync { ) -> VcxCoreResult; async fn set_endorser( &self, + wallet: &impl BaseWallet, submitter_did: &str, request: &str, endorser: &str, ) -> VcxCoreResult; async fn endorse_transaction( &self, + wallet: &impl BaseWallet, endorser_did: &str, request_json: &str, ) -> VcxCoreResult<()>; - async fn add_attr(&self, target_did: &str, attrib_json: &str) -> VcxCoreResult; + async fn add_attr( + &self, + wallet: &impl BaseWallet, + target_did: &str, + attrib_json: &str, + ) -> VcxCoreResult; async fn write_did( &self, + wallet: &impl BaseWallet, submitter_did: &str, target_did: &str, target_vk: &str, @@ -80,19 +89,26 @@ pub trait AnoncredsLedgerRead: Debug + Send + Sync { pub trait AnoncredsLedgerWrite: Debug + Send + Sync { async fn publish_schema( &self, + wallet: &impl BaseWallet, schema_json: &str, submitter_did: &str, endorser_did: Option, ) -> VcxCoreResult<()>; - async fn publish_cred_def(&self, cred_def_json: &str, submitter_did: &str) - -> VcxCoreResult<()>; + async fn publish_cred_def( + &self, + wallet: &impl BaseWallet, + cred_def_json: &str, + submitter_did: &str, + ) -> VcxCoreResult<()>; async fn publish_rev_reg_def( &self, + wallet: &impl BaseWallet, rev_reg_def: &str, submitter_did: &str, ) -> VcxCoreResult<()>; async fn publish_rev_reg_delta( &self, + wallet: &impl BaseWallet, rev_reg_id: &str, rev_reg_entry_json: &str, submitter_did: &str, diff --git a/aries_vcx_core/src/ledger/indy_vdr_ledger.rs b/aries_vcx_core/src/ledger/indy_vdr_ledger.rs index d9267d3cba..fa60c13afb 100644 --- a/aries_vcx_core/src/ledger/indy_vdr_ledger.rs +++ b/aries_vcx_core/src/ledger/indy_vdr_ledger.rs @@ -1,7 +1,7 @@ use std::{ fmt::{Debug, Formatter}, str::FromStr, - sync::{Arc, RwLock}, + sync::RwLock, }; use async_trait::async_trait; @@ -12,7 +12,10 @@ use indy_ledger_response_parser::{ use indy_vdr as vdr; use serde_json::Value; use time::OffsetDateTime; -pub use vdr::ledger::constants::{LedgerRole, UpdateRole}; +pub use vdr::{ + ledger::constants::{LedgerRole, UpdateRole}, + pool::ProtocolVersion, +}; use vdr::{ ledger::{ identifiers::{CredentialDefinitionId, RevocationRegistryId, SchemaId}, @@ -26,14 +29,13 @@ use vdr::{ }, RequestBuilder, }, - pool::{LedgerType, PreparedRequest, ProtocolVersion as VdrProtocolVersion}, + pool::{LedgerType, PreparedRequest}, utils::{did::DidValue, Qualifiable}, }; use super::{ base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite}, map_error_not_found_to_none, - request_signer::RequestSigner, request_submitter::RequestSubmitter, response_cacher::ResponseCacher, }; @@ -43,6 +45,7 @@ use crate::{ base_ledger::{TaaConfigurator, TxnAuthrAgrmtOptions}, common::verify_transaction_can_be_endorsed, }, + wallet::base_wallet::BaseWallet, }; // TODO: Should implement builders for these configs... @@ -52,19 +55,17 @@ where T: RequestSubmitter + Send + Sync, V: ResponseCacher + Send + Sync, { - pub request_submitter: Arc, - pub response_parser: Arc, - pub response_cacher: Arc, + pub request_submitter: T, + pub response_parser: ResponseParser, + pub response_cacher: V, pub protocol_version: ProtocolVersion, } -pub struct IndyVdrLedgerWriteConfig +pub struct IndyVdrLedgerWriteConfig where T: RequestSubmitter + Send + Sync, - U: RequestSigner + Send + Sync, { - pub request_signer: Arc, - pub request_submitter: Arc, + pub request_submitter: T, pub taa_options: Option, pub protocol_version: ProtocolVersion, } @@ -74,19 +75,17 @@ where T: RequestSubmitter + Send + Sync, V: ResponseCacher + Send + Sync, { - request_submitter: Arc, - response_parser: Arc, - response_cacher: Arc, + request_submitter: T, + response_parser: ResponseParser, + response_cacher: V, protocol_version: ProtocolVersion, } -pub struct IndyVdrLedgerWrite +pub struct IndyVdrLedgerWrite where T: RequestSubmitter + Send + Sync, - U: RequestSigner + Send + Sync, { - request_signer: Arc, - request_submitter: Arc, + request_submitter: T, taa_options: RwLock>, protocol_version: ProtocolVersion, } @@ -106,7 +105,7 @@ where } pub fn request_builder(&self) -> VcxCoreResult { - Ok(RequestBuilder::new(self.protocol_version.0)) + Ok(RequestBuilder::new(self.protocol_version)) } async fn submit_request( @@ -145,14 +144,12 @@ where } } -impl IndyVdrLedgerWrite +impl IndyVdrLedgerWrite where T: RequestSubmitter + Send + Sync, - U: RequestSigner + Send + Sync, { - pub fn new(config: IndyVdrLedgerWriteConfig) -> Self { + pub fn new(config: IndyVdrLedgerWriteConfig) -> Self { Self { - request_signer: config.request_signer, request_submitter: config.request_submitter, taa_options: RwLock::new(None), protocol_version: config.protocol_version, @@ -160,25 +157,36 @@ where } pub fn request_builder(&self) -> VcxCoreResult { - Ok(RequestBuilder::new(self.protocol_version.0)) + Ok(RequestBuilder::new(self.protocol_version)) + } + + async fn sign_request( + wallet: &impl BaseWallet, + did: &str, + request: &PreparedRequest, + ) -> VcxCoreResult> { + let to_sign = request.get_signature_input()?; + let signer_verkey = wallet.key_for_local_did(did).await?; + let signature = wallet.sign(&signer_verkey, to_sign.as_bytes()).await?; + Ok(signature) } async fn sign_and_submit_request( &self, + wallet: &impl BaseWallet, submitter_did: &str, request: PreparedRequest, ) -> VcxCoreResult { let mut request = request; - let signature = self.request_signer.sign(submitter_did, &request).await?; + let signature = Self::sign_request(wallet, submitter_did, &request).await?; request.set_signature(&signature)?; self.request_submitter.submit(request).await } } -impl TaaConfigurator for IndyVdrLedgerWrite +impl TaaConfigurator for IndyVdrLedgerWrite where T: RequestSubmitter + Send + Sync, - U: RequestSigner + Send + Sync, { fn set_txn_author_agreement_options( &self, @@ -204,10 +212,9 @@ where } } -impl Debug for IndyVdrLedgerWrite +impl Debug for IndyVdrLedgerWrite where T: RequestSubmitter + Send + Sync, - U: RequestSigner + Send + Sync, { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "IndyVdrLedgerWrite instance") @@ -281,10 +288,9 @@ where } } -impl IndyVdrLedgerWrite +impl IndyVdrLedgerWrite where T: RequestSubmitter + Send + Sync, - U: RequestSigner + Send + Sync, { async fn append_txn_author_agreement_to_request( &self, @@ -311,13 +317,13 @@ where } #[async_trait] -impl IndyLedgerWrite for IndyVdrLedgerWrite +impl IndyLedgerWrite for IndyVdrLedgerWrite where T: RequestSubmitter + Send + Sync, - U: RequestSigner + Send + Sync, { async fn publish_nym( &self, + wallet: &impl BaseWallet, submitter_did: &str, target_did: &str, verkey: Option<&str>, @@ -336,35 +342,43 @@ where None, )?; let request = self.append_txn_author_agreement_to_request(request).await?; - self.sign_and_submit_request(submitter_did, request).await + self.sign_and_submit_request(wallet, submitter_did, request) + .await } async fn set_endorser( &self, + wallet: &impl BaseWallet, submitter_did: &str, request_json: &str, endorser: &str, ) -> VcxCoreResult { let mut request = PreparedRequest::from_request_json(request_json)?; request.set_endorser(&DidValue::from_str(endorser)?)?; - let signature_submitter = self.request_signer.sign(submitter_did, &request).await?; + let signature_submitter = Self::sign_request(wallet, submitter_did, &request).await?; request.set_multi_signature(&DidValue::from_str(submitter_did)?, &signature_submitter)?; Ok(request.req_json.to_string()) } async fn endorse_transaction( &self, + wallet: &impl BaseWallet, endorser_did: &str, request_json: &str, ) -> VcxCoreResult<()> { let mut request = PreparedRequest::from_request_json(request_json)?; verify_transaction_can_be_endorsed(request_json, endorser_did)?; - let signature_endorser = self.request_signer.sign(endorser_did, &request).await?; + let signature_endorser = Self::sign_request(wallet, endorser_did, &request).await?; request.set_multi_signature(&DidValue::from_str(endorser_did)?, &signature_endorser)?; self.request_submitter.submit(request).await.map(|_| ()) } - async fn add_attr(&self, target_did: &str, attrib_json: &str) -> VcxCoreResult { + async fn add_attr( + &self, + wallet: &impl BaseWallet, + target_did: &str, + attrib_json: &str, + ) -> VcxCoreResult { let identifier = DidValue::from_str(target_did)?; let dest = DidValue::from_str(target_did)?; let request = self.request_builder()?.build_attrib_request( @@ -375,11 +389,13 @@ where None, )?; let request = self.append_txn_author_agreement_to_request(request).await?; - self.sign_and_submit_request(target_did, request).await + self.sign_and_submit_request(wallet, target_did, request) + .await } async fn write_did( &self, + wallet: &impl BaseWallet, submitter_did: &str, target_did: &str, target_vk: &str, @@ -402,7 +418,9 @@ where None, )?; let request = self.append_txn_author_agreement_to_request(request).await?; - let response = self.sign_and_submit_request(submitter_did, request).await?; + let response = self + .sign_and_submit_request(wallet, submitter_did, request) + .await?; debug!("write_did << response: {response}"); return Ok(response); } @@ -539,13 +557,13 @@ where } #[async_trait] -impl AnoncredsLedgerWrite for IndyVdrLedgerWrite +impl AnoncredsLedgerWrite for IndyVdrLedgerWrite where T: RequestSubmitter + Send + Sync, - U: RequestSigner + Send + Sync, { async fn publish_schema( &self, + wallet: &impl BaseWallet, schema_json: &str, submitter_did: &str, _endorser_did: Option, @@ -562,7 +580,9 @@ where // .await?, // )? // } - let sign_result = self.sign_and_submit_request(submitter_did, request).await; + let sign_result = self + .sign_and_submit_request(wallet, submitter_did, request) + .await; if let Err(err) = &sign_result { if let AriesVcxCoreErrorKind::InvalidLedgerResponse = err.kind() { @@ -580,6 +600,7 @@ where async fn publish_cred_def( &self, + wallet: &impl BaseWallet, cred_def_json: &str, submitter_did: &str, ) -> VcxCoreResult<()> { @@ -590,13 +611,14 @@ where CredentialDefinition::CredentialDefinitionV1(cred_def_data), )?; let request = self.append_txn_author_agreement_to_request(request).await?; - self.sign_and_submit_request(submitter_did, request) + self.sign_and_submit_request(wallet, submitter_did, request) .await .map(|_| ()) } async fn publish_rev_reg_def( &self, + wallet: &impl BaseWallet, rev_reg_def: &str, submitter_did: &str, ) -> VcxCoreResult<()> { @@ -607,13 +629,14 @@ where RevocationRegistryDefinition::RevocationRegistryDefinitionV1(rev_reg_def_data), )?; let request = self.append_txn_author_agreement_to_request(request).await?; - self.sign_and_submit_request(submitter_did, request) + self.sign_and_submit_request(wallet, submitter_did, request) .await .map(|_| ()) } async fn publish_rev_reg_delta( &self, + wallet: &impl BaseWallet, rev_reg_id: &str, rev_reg_entry_json: &str, submitter_did: &str, @@ -628,27 +651,8 @@ where RevocationRegistryDelta::RevocationRegistryDeltaV1(rev_reg_delta_data), )?; let request = self.append_txn_author_agreement_to_request(request).await?; - self.sign_and_submit_request(submitter_did, request) + self.sign_and_submit_request(wallet, submitter_did, request) .await .map(|_| ()) } } - -#[derive(Debug)] -pub struct ProtocolVersion(VdrProtocolVersion); - -impl Default for ProtocolVersion { - fn default() -> Self { - ProtocolVersion(VdrProtocolVersion::Node1_4) - } -} - -impl ProtocolVersion { - pub fn node_1_3() -> Self { - ProtocolVersion(VdrProtocolVersion::Node1_3) - } - - pub fn node_1_4() -> Self { - ProtocolVersion(VdrProtocolVersion::Node1_4) - } -} diff --git a/aries_vcx_core/src/ledger/mod.rs b/aries_vcx_core/src/ledger/mod.rs index f21c5e3bc8..7eb94ae89e 100644 --- a/aries_vcx_core/src/ledger/mod.rs +++ b/aries_vcx_core/src/ledger/mod.rs @@ -5,7 +5,6 @@ pub mod common; pub mod indy; pub mod indy_vdr_ledger; -pub mod request_signer; pub mod request_submitter; pub mod response_cacher; diff --git a/aries_vcx_core/src/ledger/request_signer/base_wallet.rs b/aries_vcx_core/src/ledger/request_signer/base_wallet.rs deleted file mode 100644 index 3933c2d731..0000000000 --- a/aries_vcx_core/src/ledger/request_signer/base_wallet.rs +++ /dev/null @@ -1,27 +0,0 @@ -use std::sync::Arc; - -use async_trait::async_trait; -use indy_vdr::pool::PreparedRequest; - -use super::RequestSigner; -use crate::{errors::error::VcxCoreResult, wallet::base_wallet::BaseWallet}; - -pub struct BaseWalletRequestSigner { - wallet: Arc, -} - -impl BaseWalletRequestSigner { - pub fn new(wallet: Arc) -> Self { - Self { wallet } - } -} - -#[async_trait] -impl RequestSigner for BaseWalletRequestSigner { - async fn sign(&self, did: &str, request: &PreparedRequest) -> VcxCoreResult> { - let to_sign = request.get_signature_input()?; - let signer_verkey = self.wallet.key_for_local_did(did).await?; - let signature = self.wallet.sign(&signer_verkey, to_sign.as_bytes()).await?; - Ok(signature) - } -} diff --git a/aries_vcx_core/src/ledger/request_signer/mod.rs b/aries_vcx_core/src/ledger/request_signer/mod.rs deleted file mode 100644 index 150574427b..0000000000 --- a/aries_vcx_core/src/ledger/request_signer/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -pub mod base_wallet; - -use async_trait::async_trait; -use indy_vdr::pool::PreparedRequest; - -use crate::errors::error::VcxCoreResult; - -#[async_trait] -pub trait RequestSigner: Send + Sync { - async fn sign(&self, did: &str, request: &PreparedRequest) -> VcxCoreResult>; -} diff --git a/aries_vcx_core/src/ledger/request_submitter/vdr_ledger.rs b/aries_vcx_core/src/ledger/request_submitter/vdr_ledger.rs index b7efe67eca..274a7fe1fd 100644 --- a/aries_vcx_core/src/ledger/request_submitter/vdr_ledger.rs +++ b/aries_vcx_core/src/ledger/request_submitter/vdr_ledger.rs @@ -1,6 +1,7 @@ use std::{ collections::{hash_map::RandomState, HashMap}, fmt::{Debug, Formatter}, + sync::Arc, }; use async_trait::async_trait; @@ -14,14 +15,15 @@ use tokio::sync::oneshot; use super::RequestSubmitter; use crate::errors::error::{AriesVcxCoreError, AriesVcxCoreErrorKind, VcxCoreResult}; +#[derive(Clone)] pub struct IndyVdrLedgerPool { - pub(self) runner: Option, + runner: Arc, } impl IndyVdrLedgerPool { pub fn new_from_runner(runner: PoolRunner) -> Self { IndyVdrLedgerPool { - runner: Some(runner), + runner: Arc::new(runner), } } @@ -51,7 +53,7 @@ impl IndyVdrLedgerPool { .into_runner()?; Ok(IndyVdrLedgerPool { - runner: Some(runner), + runner: Arc::new(runner), }) } } @@ -64,6 +66,7 @@ impl Debug for IndyVdrLedgerPool { } } +#[derive(Clone)] pub struct IndyVdrSubmitter { pool: IndyVdrLedgerPool, } @@ -87,23 +90,13 @@ impl RequestSubmitter for IndyVdrSubmitter { VdrError, >; let (sender, recv) = oneshot::channel::(); - self.pool - .runner - .as_ref() - .ok_or( - // should not happen - strictly for unit testing - AriesVcxCoreError::from_msg( - AriesVcxCoreErrorKind::NoPoolOpen, - "IndyVdrLedgerPool runner was not provided", - ), - )? - .send_request( - request, - Box::new(move |result| { - // unable to handle a failure from `send` here - sender.send(result).ok(); - }), - )?; + self.pool.runner.send_request( + request, + Box::new(move |result| { + // unable to handle a failure from `send` here + sender.send(result).ok(); + }), + )?; let send_req_result: VdrSendRequestResult = recv .await diff --git a/aries_vcx_core/src/ledger/request_submitter/vdr_proxy.rs b/aries_vcx_core/src/ledger/request_submitter/vdr_proxy.rs index de2d694971..e51cc84933 100644 --- a/aries_vcx_core/src/ledger/request_submitter/vdr_proxy.rs +++ b/aries_vcx_core/src/ledger/request_submitter/vdr_proxy.rs @@ -7,6 +7,7 @@ use indy_vdr_proxy_client::VdrProxyClient; use super::RequestSubmitter; use crate::errors::error::VcxCoreResult; +#[derive(Clone)] pub struct VdrProxySubmitter { client: Arc, } diff --git a/did_resolver_sov/tests/resolution.rs b/did_resolver_sov/tests/resolution.rs index 38dc4b41b2..6a01dab3fe 100644 --- a/did_resolver_sov/tests/resolution.rs +++ b/did_resolver_sov/tests/resolution.rs @@ -5,21 +5,25 @@ use aries_vcx::{ service_didsov::{DidSovServiceType, EndpointDidSov}, transactions::write_endpoint, }, - core::profile::Profile, run_setup, }; +use aries_vcx_core::{ledger::base_ledger::IndyLedgerWrite, wallet::base_wallet::BaseWallet}; use did_resolver::{ did_parser::Did, traits::resolvable::{resolution_options::DidResolutionOptions, DidResolvable}, }; use did_resolver_sov::resolution::DidSovResolver; -async fn write_test_endpoint(profile: &impl Profile, did: &str) { +async fn write_test_endpoint( + wallet: &impl BaseWallet, + ledger_write: &impl IndyLedgerWrite, + did: &str, +) { let endpoint = EndpointDidSov::create() .set_service_endpoint("http://localhost:8080".parse().unwrap()) .set_routing_keys(Some(vec!["key1".to_string(), "key2".to_string()])) .set_types(Some(vec![DidSovServiceType::Endpoint])); - write_endpoint(profile.ledger_write(), did, &endpoint) + write_endpoint(wallet, ledger_write, did, &endpoint) .await .unwrap(); thread::sleep(Duration::from_millis(50)); @@ -29,8 +33,8 @@ async fn write_test_endpoint(profile: &impl Profile, did: &str) { async fn write_service_on_ledger_and_resolve_did_doc() { run_setup!(|init| async move { let did = format!("did:sov:{}", init.institution_did); - write_test_endpoint(&init.profile, &init.institution_did).await; - let resolver = DidSovResolver::new(init.profile.ledger_read()); + write_test_endpoint(&init.wallet, &init.ledger_write, &init.institution_did).await; + let resolver = DidSovResolver::new(&init.ledger_read); let did_doc = resolver .resolve( &Did::parse(did.clone()).unwrap(), @@ -48,7 +52,7 @@ async fn test_error_handling_during_resolution() { run_setup!(|init| async move { let did = format!("did:unknownmethod:{}", init.institution_did); - let resolver = DidSovResolver::new(init.profile.ledger_read()); + let resolver = DidSovResolver::new(&init.ledger_read); let result = resolver .resolve( diff --git a/libvcx_core/src/api_vcx/api_global/ledger.rs b/libvcx_core/src/api_vcx/api_global/ledger.rs index b6ea9a17c8..04ed572900 100644 --- a/libvcx_core/src/api_vcx/api_global/ledger.rs +++ b/libvcx_core/src/api_vcx/api_global/ledger.rs @@ -25,8 +25,13 @@ use crate::{ }; pub async fn endorse_transaction(transaction: &str, endorser_did: &str) -> LibvcxResult<()> { + let wallet = get_main_wallet()?; let ledger = get_main_ledger_write()?; - map_ariesvcx_core_result(ledger.endorse_transaction(endorser_did, transaction).await) + map_ariesvcx_core_result( + ledger + .endorse_transaction(wallet.as_ref(), endorser_did, transaction) + .await, + ) } pub async fn get_ledger_txn(seq_no: i32, submitter_did: Option) -> LibvcxResult { @@ -61,6 +66,7 @@ pub async fn ledger_write_endpoint_legacy( routing_keys: Vec, endpoint: String, ) -> LibvcxResult { + let wallet = get_main_wallet()?; let service = AriesService::create() .set_service_endpoint(Url::from_str(&endpoint).map_err(|err| { @@ -68,7 +74,13 @@ pub async fn ledger_write_endpoint_legacy( })?) .set_recipient_keys(recipient_keys) .set_routing_keys(routing_keys); - write_endpoint_legacy(get_main_ledger_write()?.as_ref(), target_did, &service).await?; + write_endpoint_legacy( + wallet.as_ref(), + get_main_ledger_write()?.as_ref(), + target_did, + &service, + ) + .await?; Ok(service) } @@ -77,6 +89,7 @@ pub async fn ledger_write_endpoint( routing_keys: Vec, endpoint: String, ) -> LibvcxResult { + let wallet = get_main_wallet()?; let service = EndpointDidSov::create() .set_service_endpoint(Url::from_str(&endpoint).map_err(|err| { @@ -87,7 +100,13 @@ pub async fn ledger_write_endpoint( DidSovServiceType::DidCommunication, ])) .set_routing_keys(Some(routing_keys)); - write_endpoint(get_main_ledger_write()?.as_ref(), target_did, &service).await?; + write_endpoint( + wallet.as_ref(), + get_main_ledger_write()?.as_ref(), + target_did, + &service, + ) + .await?; Ok(service) } @@ -101,7 +120,16 @@ pub async fn ledger_get_attr(target_did: &str, attr: &str) -> LibvcxResult LibvcxResult { - map_ariesvcx_result(clear_attr(get_main_ledger_write()?.as_ref(), target_did, attr).await) + let wallet = get_main_wallet()?; + map_ariesvcx_result( + clear_attr( + wallet.as_ref(), + get_main_ledger_write()?.as_ref(), + target_did, + attr, + ) + .await, + ) } pub async fn ledger_write_endorser_did( @@ -110,8 +138,10 @@ pub async fn ledger_write_endorser_did( target_vk: &str, alias: Option, ) -> LibvcxResult { + let wallet = get_main_wallet()?; map_ariesvcx_result( write_endorser_did( + wallet.as_ref(), get_main_ledger_write()?.as_ref(), submitter_did, target_did, @@ -160,7 +190,7 @@ pub mod tests { get_txns_sovrin_testnet, }, global::settings::DEFAULT_GENESIS_PATH, - utils::devsetup::SetupEmpty, + utils::devsetup::SetupMocks, }; use crate::api_vcx::api_global::{ @@ -171,7 +201,7 @@ pub mod tests { #[tokio::test] async fn test_vcx_get_sovrin_taa() { - let _setup = SetupEmpty::init(); + let _setup = SetupMocks::init(); _create_and_open_wallet().await.unwrap(); let genesis_path = get_temp_file_path(DEFAULT_GENESIS_PATH) .to_str() @@ -195,7 +225,7 @@ pub mod tests { #[tokio::test] async fn test_vcx_set_active_txn_author_agreement_meta() { - let _setup = SetupEmpty::init(); + let _setup = SetupMocks::init(); _create_and_open_wallet().await.unwrap(); let genesis_path = get_temp_file_path(DEFAULT_GENESIS_PATH) .to_str() diff --git a/libvcx_core/src/api_vcx/api_global/pool.rs b/libvcx_core/src/api_vcx/api_global/pool.rs index c155d62187..4a952838b0 100644 --- a/libvcx_core/src/api_vcx/api_global/pool.rs +++ b/libvcx_core/src/api_vcx/api_global/pool.rs @@ -12,28 +12,22 @@ use aries_vcx::{ InMemoryResponseCacherConfig, InMemoryResponseCacherConfigBuilder, }, }, - wallet::base_wallet::BaseWallet, PoolConfig, }, - core::profile::ledger::{indyvdr_build_ledger_read, indyvdr_build_ledger_write}, + utils::ledger::{indyvdr_build_ledger_read, indyvdr_build_ledger_write}, }; use aries_vcx_core::ledger::{ indy_vdr_ledger::{IndyVdrLedgerRead, IndyVdrLedgerWrite}, - request_signer::base_wallet::BaseWalletRequestSigner, response_cacher::in_memory::InMemoryResponseCacher, }; -use crate::{ - api_vcx::api_global::profile::get_main_wallet, - errors::error::{LibvcxError, LibvcxResult}, -}; +use crate::errors::error::{LibvcxError, LibvcxResult}; pub static GLOBAL_LEDGER_INDY_READ: RwLock< Option>>, > = RwLock::new(None); -pub static GLOBAL_LEDGER_INDY_WRITE: RwLock< - Option>>, -> = RwLock::new(None); +pub static GLOBAL_LEDGER_INDY_WRITE: RwLock>>> = + RwLock::new(None); pub fn is_main_pool_open() -> bool { GLOBAL_LEDGER_INDY_READ @@ -73,11 +67,10 @@ impl TryFrom for InMemoryResponseCacherConfi } fn build_components_ledger( - base_wallet: Arc, libvcx_pool_config: &LibvcxLedgerConfig, ) -> LibvcxResult<( IndyVdrLedgerRead, - IndyVdrLedgerWrite, + IndyVdrLedgerWrite, )> { let indy_vdr_config = match &libvcx_pool_config.pool_config { None => PoolConfig::default(), @@ -88,7 +81,7 @@ fn build_components_ledger( indy_vdr_config, libvcx_pool_config.exclude_nodes.clone().unwrap_or_default(), )?; - let request_submitter = Arc::new(IndyVdrSubmitter::new(ledger_pool)); + let request_submitter = IndyVdrSubmitter::new(ledger_pool); let cache_config = match &libvcx_pool_config.cache_config { None => InMemoryResponseCacherConfig::builder() @@ -98,7 +91,7 @@ fn build_components_ledger( Some(cfg) => cfg.clone().try_into()?, }; let ledger_read = indyvdr_build_ledger_read(request_submitter.clone(), cache_config)?; - let ledger_write = indyvdr_build_ledger_write(base_wallet, request_submitter, None); + let ledger_write = indyvdr_build_ledger_write(request_submitter, None); Ok((ledger_read, ledger_write)) } @@ -112,9 +105,7 @@ pub fn reset_ledger_components() -> LibvcxResult<()> { } pub async fn setup_ledger_components(config: &LibvcxLedgerConfig) -> LibvcxResult<()> { - let base_wallet = get_main_wallet()?; - - let (ledger_read, ledger_write) = build_components_ledger(base_wallet, config)?; + let (ledger_read, ledger_write) = build_components_ledger(config)?; let mut indy_read_guard = GLOBAL_LEDGER_INDY_READ.write()?; *indy_read_guard = Some(Arc::new(ledger_read)); let mut indy_write_guard = GLOBAL_LEDGER_INDY_WRITE.write()?; @@ -159,7 +150,7 @@ pub mod tests { global::settings::DEFAULT_GENESIS_PATH, utils::{ constants::POOL1_TXN, - devsetup::{SetupDefaults, SetupEmpty, TempFile}, + devsetup::{SetupMocks, TempFile}, }, }; use serde_json; @@ -218,7 +209,7 @@ pub mod tests { #[tokio::test] #[ignore] async fn test_open_pool() { - let _setup = SetupEmpty::init(); + let _setup = SetupMocks::init(); _create_and_open_wallet().await.unwrap(); let genesis_path = get_temp_file_path(DEFAULT_GENESIS_PATH) .to_str() @@ -240,7 +231,7 @@ pub mod tests { #[tokio::test] #[ignore] async fn test_open_pool_fails_if_genesis_file_is_invalid() { - let _setup = SetupEmpty::init(); + let _setup = SetupMocks::init(); _create_and_open_wallet().await.unwrap(); let _genesis_transactions = @@ -260,7 +251,7 @@ pub mod tests { #[tokio::test] #[ignore] async fn test_open_pool_fails_if_genesis_path_is_invalid() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); _create_and_open_wallet().await.unwrap(); let config = LibvcxLedgerConfig { diff --git a/libvcx_core/src/api_vcx/api_global/wallet.rs b/libvcx_core/src/api_vcx/api_global/wallet.rs index 15cfda7116..063b37ff6e 100644 --- a/libvcx_core/src/api_vcx/api_global/wallet.rs +++ b/libvcx_core/src/api_vcx/api_global/wallet.rs @@ -51,19 +51,13 @@ fn build_component_base_wallet(wallet_handle: WalletHandle) -> Arc) -> Arc { - Arc::new(IndyCredxAnonCreds::new(base_wallet.clone())) -} - fn setup_global_wallet(wallet_handle: WalletHandle) -> LibvcxResult<()> { // new way let base_wallet_impl = build_component_base_wallet(wallet_handle); let mut b_wallet = GLOBAL_BASE_WALLET.write()?; *b_wallet = Some(base_wallet_impl.clone()); // anoncreds - let base_anoncreds_impl = build_component_anoncreds(base_wallet_impl); + let base_anoncreds_impl = Arc::new(IndyCredxAnonCreds); let mut b_anoncreds = GLOBAL_BASE_ANONCREDS.write()?; *b_anoncreds = Some(base_anoncreds_impl); Ok(()) @@ -105,10 +99,11 @@ pub async fn close_main_wallet() -> LibvcxResult<()> { pub async fn create_main_wallet(config: &WalletConfig) -> LibvcxResult<()> { let wallet_handle = create_and_open_as_main_wallet(config).await?; trace!("Created wallet with handle {:?}", wallet_handle); + let wallet = get_main_wallet()?; // If MS is already in wallet then just continue get_main_anoncreds()? - .prover_create_link_secret(DEFAULT_LINK_SECRET_ALIAS) + .prover_create_link_secret(wallet.as_ref(), DEFAULT_LINK_SECRET_ALIAS) .await .ok(); @@ -367,7 +362,7 @@ pub mod tests { wallet::delete_wallet, RestoreWalletConfigs, WalletConfig, WalletRecord, }, global::settings::{DEFAULT_WALLET_BACKUP_KEY, DEFAULT_WALLET_KEY, WALLET_KDF_RAW}, - utils::devsetup::{SetupDefaults, SetupEmpty, TempFile}, + utils::devsetup::{SetupMocks, TempFile}, }; use crate::{ @@ -406,7 +401,7 @@ pub mod tests { #[tokio::test] async fn test_wallet_create() { - let _setup = SetupEmpty::init(); + let _setup = SetupMocks::init(); let wallet_name = format!("test_create_wallet_{}", uuid::Uuid::new_v4()); let config: WalletConfig = serde_json::from_value(json!({ @@ -528,7 +523,7 @@ pub mod tests { #[tokio::test] async fn test_wallet_export_import() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let wallet_name = uuid::Uuid::new_v4().to_string(); let export_file = TempFile::prepare_path(&wallet_name); let wallet_config = WalletConfig { @@ -564,7 +559,7 @@ pub mod tests { #[tokio::test] async fn test_wallet_open_with_incorrect_key_fails() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let wallet_name = uuid::Uuid::new_v4().to_string(); let _export_file = TempFile::prepare_path(&wallet_name); let mut wallet_config = WalletConfig { @@ -588,7 +583,7 @@ pub mod tests { #[tokio::test] async fn test_wallet_open_with_wrong_name_fails() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let wallet_config: WalletConfig = serde_json::from_value(json!({ "wallet_name": "different_wallet_name", @@ -608,7 +603,7 @@ pub mod tests { #[tokio::test] async fn test_wallet_open_of_imported_wallet_succeeds() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let (export_wallet_path, wallet_name, wallet_config) = _create_main_wallet_and_its_backup().await; @@ -636,7 +631,7 @@ pub mod tests { #[tokio::test] async fn test_wallet_import_of_opened_wallet_fails() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let (export_wallet_path, wallet_name, wallet_config) = _create_main_wallet_and_its_backup().await; diff --git a/libvcx_core/src/api_vcx/api_handle/credential.rs b/libvcx_core/src/api_vcx/api_handle/credential.rs index b13052c91c..0d9603f3c2 100644 --- a/libvcx_core/src/api_vcx/api_handle/credential.rs +++ b/libvcx_core/src/api_vcx/api_handle/credential.rs @@ -17,7 +17,7 @@ use serde_json; use crate::{ api_vcx::{ - api_global::profile::{get_main_anoncreds, get_main_ledger_read}, + api_global::profile::{get_main_anoncreds, get_main_ledger_read, get_main_wallet}, api_handle::{ mediated_connection::{self, send_message}, object_cache::ObjectCache, @@ -163,6 +163,7 @@ pub async fn update_state( Some(aries_msg) => { credential .process_aries_msg( + get_main_wallet()?.as_ref(), get_main_ledger_read()?.as_ref(), get_main_anoncreds()?.as_ref(), aries_msg.clone(), @@ -236,7 +237,7 @@ pub async fn delete_credential(handle: u32) -> LibvcxResult<()> { ); let credential = HANDLE_MAP.get_cloned(handle)?; credential - .delete_credential(get_main_anoncreds()?.as_ref()) + .delete_credential(get_main_wallet()?.as_ref(), get_main_anoncreds()?.as_ref()) .await?; HANDLE_MAP.release(handle) } @@ -267,6 +268,7 @@ pub async fn send_credential_request(handle: u32, connection_handle: u32) -> Lib let my_pw_did = mediated_connection::get_pw_did(connection_handle)?; let msg_response = credential .prepare_credential_request( + get_main_wallet()?.as_ref(), get_main_ledger_read()?.as_ref(), get_main_anoncreds()?.as_ref(), my_pw_did, @@ -414,7 +416,7 @@ pub mod tests { messages::msg_fields::protocols::cred_issuance::v1::issue_credential::IssueCredentialV1, protocols::issuance::holder::state_machine::HolderState, utils::{ - devsetup::{SetupDefaults, SetupMocks}, + devsetup::SetupMocks, mockdata::{ mockdata_credex, mockdata_credex::{ @@ -444,7 +446,7 @@ pub mod tests { #[test] fn test_vcx_credential_release() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let handle = credential_create_with_offer( "test_credential_create_with_offer", ARIES_CREDENTIAL_OFFER, @@ -459,7 +461,7 @@ pub mod tests { #[tokio::test] async fn test_credential_create_with_offer() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let handle = credential_create_with_offer( "test_credential_create_with_offer", @@ -471,7 +473,7 @@ pub mod tests { #[tokio::test] async fn test_credential_create_with_offer_with_json_attach() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let handle = credential_create_with_offer( "test_credential_create_with_offer", @@ -483,7 +485,7 @@ pub mod tests { #[tokio::test] async fn test_credential_create_with_bad_offer() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let err = credential_create_with_offer( "test_credential_create_with_bad_offer", @@ -495,7 +497,7 @@ pub mod tests { #[tokio::test] async fn test_credential_serialize_deserialize() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let handle1 = credential_create_with_offer( "test_credential_serialize_deserialize", diff --git a/libvcx_core/src/api_vcx/api_handle/credential_def.rs b/libvcx_core/src/api_vcx/api_handle/credential_def.rs index a30ac62e1e..a35854b67b 100644 --- a/libvcx_core/src/api_vcx/api_handle/credential_def.rs +++ b/libvcx_core/src/api_vcx/api_handle/credential_def.rs @@ -4,7 +4,9 @@ use aries_vcx::common::primitives::credential_definition::{ use crate::{ api_vcx::{ - api_global::profile::{get_main_anoncreds, get_main_ledger_read, get_main_ledger_write}, + api_global::profile::{ + get_main_anoncreds, get_main_ledger_read, get_main_ledger_write, get_main_wallet, + }, api_handle::object_cache::ObjectCache, }, errors::error::{LibvcxError, LibvcxErrorKind, LibvcxResult}, @@ -38,6 +40,7 @@ pub async fn create( })?; let cred_def = CredentialDef::create( + get_main_wallet()?.as_ref(), get_main_ledger_read()?.as_ref(), get_main_anoncreds()?.as_ref(), source_id, @@ -54,6 +57,7 @@ pub async fn publish(handle: u32) -> LibvcxResult<()> { if !cd.was_published() { cd = cd .publish_cred_def( + get_main_wallet()?.as_ref(), get_main_ledger_read()?.as_ref(), get_main_ledger_write()?.as_ref(), ) diff --git a/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs b/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs index af5b9cd576..3b1e68a725 100644 --- a/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs +++ b/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs @@ -12,7 +12,7 @@ use serde_json; use super::mediated_connection::send_message; use crate::{ api_vcx::{ - api_global::profile::{get_main_anoncreds, get_main_ledger_read}, + api_global::profile::{get_main_anoncreds, get_main_ledger_read, get_main_wallet}, api_handle::{mediated_connection, object_cache::ObjectCache}, }, errors::error::{LibvcxError, LibvcxErrorKind, LibvcxResult}, @@ -214,6 +214,7 @@ pub async fn generate_proof( let mut proof = HANDLE_MAP.get_cloned(handle)?; proof .generate_presentation( + get_main_wallet()?.as_ref(), get_main_ledger_read()?.as_ref(), get_main_anoncreds()?.as_ref(), serde_json::from_str(credentials)?, @@ -243,7 +244,7 @@ pub async fn decline_presentation_request( pub async fn retrieve_credentials(handle: u32) -> LibvcxResult { let proof = HANDLE_MAP.get_cloned(handle)?; let retrieved_creds = proof - .retrieve_credentials(get_main_anoncreds()?.as_ref()) + .retrieve_credentials(get_main_wallet()?.as_ref(), get_main_anoncreds()?.as_ref()) .await?; Ok(serde_json::to_string(&retrieved_creds)?) @@ -339,10 +340,7 @@ mod tests { use aries_vcx::{ utils, - utils::{ - devsetup::{SetupDefaults, SetupMocks}, - mockdata::mockdata_proof::ARIES_PROOF_REQUEST_PRESENTATION, - }, + utils::{devsetup::SetupMocks, mockdata::mockdata_proof::ARIES_PROOF_REQUEST_PRESENTATION}, }; use serde_json::Value; @@ -411,7 +409,7 @@ mod tests { #[tokio::test] async fn test_deserialize_fails() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); assert_eq!( from_string("{}").unwrap_err().kind(), @@ -421,7 +419,7 @@ mod tests { #[tokio::test] async fn test_deserialize_succeeds_with_self_attest_allowed() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let handle = create_with_proof_request("id", ARIES_PROOF_REQUEST_PRESENTATION).unwrap(); diff --git a/libvcx_core/src/api_vcx/api_handle/issuer_credential.rs b/libvcx_core/src/api_vcx/api_handle/issuer_credential.rs index 6975cf1957..1c26ce2613 100644 --- a/libvcx_core/src/api_vcx/api_handle/issuer_credential.rs +++ b/libvcx_core/src/api_vcx/api_handle/issuer_credential.rs @@ -189,6 +189,7 @@ pub async fn build_credential_offer_msg_v2( }; credential .build_credential_offer_msg( + get_main_wallet()?.as_ref(), get_main_anoncreds()?.as_ref(), offer_info.clone(), comment.map(|s| s.to_string()), @@ -236,7 +237,7 @@ pub async fn send_credential_offer_nonmediated( pub async fn send_credential(handle: u32, connection_handle: u32) -> LibvcxResult { let mut credential = ISSUER_CREDENTIAL_MAP.get_cloned(handle)?; credential - .build_credential(get_main_anoncreds()?.as_ref()) + .build_credential(get_main_wallet()?.as_ref(), get_main_anoncreds()?.as_ref()) .await?; match credential.get_state() { IssuerState::Failed => { @@ -261,7 +262,7 @@ pub async fn send_credential_nonmediated(handle: u32, connection_handle: u32) -> Box::pin(async move { con.send_message(wallet.as_ref(), &msg, &HttpClient).await }) }); credential - .build_credential(get_main_anoncreds()?.as_ref()) + .build_credential(get_main_wallet()?.as_ref(), get_main_anoncreds()?.as_ref()) .await?; match credential.get_state() { IssuerState::Failed => { @@ -281,7 +282,7 @@ pub async fn send_credential_nonmediated(handle: u32, connection_handle: u32) -> pub async fn revoke_credential_local(handle: u32) -> LibvcxResult<()> { let credential = ISSUER_CREDENTIAL_MAP.get_cloned(handle)?; credential - .revoke_credential_local(get_main_anoncreds()?.as_ref()) + .revoke_credential_local(get_main_wallet()?.as_ref(), get_main_anoncreds()?.as_ref()) .await .map_err(|err| err.into()) } diff --git a/libvcx_core/src/api_vcx/api_handle/mediated_connection.rs b/libvcx_core/src/api_vcx/api_handle/mediated_connection.rs index dda90818f6..dc0ad823a9 100644 --- a/libvcx_core/src/api_vcx/api_handle/mediated_connection.rs +++ b/libvcx_core/src/api_vcx/api_handle/mediated_connection.rs @@ -538,10 +538,7 @@ pub mod test_utils { pub mod tests { use aries_vcx::{ self, - utils::{ - constants, - devsetup::{SetupEmpty, SetupMocks}, - }, + utils::{constants, devsetup::SetupMocks}, }; use serde_json::Value; @@ -549,7 +546,7 @@ pub mod tests { use crate::api_vcx::VcxStateType; fn _setup() { - let _setup = SetupEmpty::init(); + let _setup = SetupMocks::init(); } fn _source_id() -> &'static str { @@ -558,7 +555,7 @@ pub mod tests { #[tokio::test] async fn test_get_state_fails() { - let _setup = SetupEmpty::init(); + let _setup = SetupMocks::init(); let state = get_state(1); assert_eq!(state, VcxStateType::VcxStateNone as u32); @@ -566,7 +563,7 @@ pub mod tests { #[tokio::test] async fn test_get_string_fails() { - let _setup = SetupEmpty::init(); + let _setup = SetupMocks::init(); let rc = to_string(0); assert_eq!(rc.unwrap_err().kind(), LibvcxErrorKind::InvalidHandle); diff --git a/libvcx_core/src/api_vcx/api_handle/object_cache/mod.rs b/libvcx_core/src/api_vcx/api_handle/object_cache/mod.rs index fe760a9e67..53f21a137a 100644 --- a/libvcx_core/src/api_vcx/api_handle/object_cache/mod.rs +++ b/libvcx_core/src/api_vcx/api_handle/object_cache/mod.rs @@ -283,20 +283,20 @@ where #[cfg(test)] mod tests { - use aries_vcx::utils::devsetup::SetupDefaults; + use aries_vcx::utils::devsetup::SetupMocks; use crate::api_vcx::api_handle::object_cache::ObjectCache; #[test] fn create_test() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let _c: ObjectCache = ObjectCache::new("cache0-u32"); } #[test] fn get_closure() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let test: ObjectCache = ObjectCache::new("cache1-u32"); let handle = test.add(2222).unwrap(); @@ -306,7 +306,7 @@ mod tests { #[test] fn to_string_test() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let test: ObjectCache = ObjectCache::new("cache2-u32"); let handle = test.add(2222).unwrap(); @@ -317,7 +317,7 @@ mod tests { #[test] fn mut_object_test() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let test: ObjectCache = ObjectCache::new("cache3-string"); let handle = test.add(String::from("TEST")).unwrap(); diff --git a/libvcx_core/src/api_vcx/api_handle/revocation_registry.rs b/libvcx_core/src/api_vcx/api_handle/revocation_registry.rs index fe784ab9d9..06a4df116c 100644 --- a/libvcx_core/src/api_vcx/api_handle/revocation_registry.rs +++ b/libvcx_core/src/api_vcx/api_handle/revocation_registry.rs @@ -4,7 +4,7 @@ use aries_vcx::common::primitives::revocation_registry::{ use crate::{ api_vcx::{ - api_global::profile::{get_main_anoncreds, get_main_ledger_write}, + api_global::profile::{get_main_anoncreds, get_main_ledger_write, get_main_wallet}, api_handle::object_cache::ObjectCache, }, errors::error::{LibvcxError, LibvcxErrorKind, LibvcxResult}, @@ -32,6 +32,7 @@ pub async fn create(config: RevocationRegistryConfig) -> LibvcxResult { tag, } = config; let rev_reg = RevocationRegistry::create( + get_main_wallet()?.as_ref(), get_main_anoncreds()?.as_ref(), &issuer_did, &cred_def_id, @@ -47,7 +48,11 @@ pub async fn create(config: RevocationRegistryConfig) -> LibvcxResult { pub async fn publish(handle: u32, tails_url: &str) -> LibvcxResult { let mut rev_reg = REV_REG_MAP.get_cloned(handle)?; rev_reg - .publish_revocation_primitives(get_main_ledger_write()?.as_ref(), tails_url) + .publish_revocation_primitives( + get_main_wallet()?.as_ref(), + get_main_ledger_write()?.as_ref(), + tails_url, + ) .await?; REV_REG_MAP.insert(handle, rev_reg)?; Ok(handle) @@ -57,6 +62,7 @@ pub async fn publish_revocations(handle: u32, submitter_did: &str) -> LibvcxResu let rev_reg = REV_REG_MAP.get_cloned(handle)?; rev_reg .publish_local_revocations( + get_main_wallet()?.as_ref(), get_main_anoncreds()?.as_ref(), get_main_ledger_write()?.as_ref(), submitter_did, diff --git a/libvcx_core/src/api_vcx/api_handle/schema.rs b/libvcx_core/src/api_vcx/api_handle/schema.rs index fe0cf9b278..0c8796f2b8 100644 --- a/libvcx_core/src/api_vcx/api_handle/schema.rs +++ b/libvcx_core/src/api_vcx/api_handle/schema.rs @@ -5,7 +5,9 @@ use serde_json; use crate::{ api_vcx::{ - api_global::profile::{get_main_anoncreds, get_main_ledger_read, get_main_ledger_write}, + api_global::profile::{ + get_main_anoncreds, get_main_ledger_read, get_main_ledger_write, get_main_wallet, + }, api_handle::object_cache::ObjectCache, }, errors::error::{LibvcxError, LibvcxErrorKind, LibvcxResult}, @@ -50,7 +52,10 @@ pub async fn create_and_publish_schema( &data, ) .await? - .publish(get_main_ledger_write()?.as_ref()) + .publish( + get_main_wallet()?.as_ref(), + get_main_ledger_write()?.as_ref(), + ) .await?; std::thread::sleep(std::time::Duration::from_millis(100)); debug!( @@ -164,16 +169,13 @@ pub mod test_utils { #[cfg(test)] pub mod tests { - use aries_vcx::{ - global::settings::DEFAULT_DID, - utils::devsetup::{SetupDefaults, SetupEmpty}, - }; + use aries_vcx::{global::settings::DEFAULT_DID, utils::devsetup::SetupMocks}; use super::*; #[tokio::test] async fn test_create_schema_fails() { - let _setup = SetupDefaults::init(); + let _setup = SetupMocks::init(); let err = create_and_publish_schema( DEFAULT_DID, @@ -189,7 +191,7 @@ pub mod tests { #[test] fn test_handle_errors() { - let _setup = SetupEmpty::init(); + let _setup = SetupMocks::init(); assert_eq!( to_string(13435178).unwrap_err().kind(), diff --git a/libvdrtools/indy-wallet/src/lib.rs b/libvdrtools/indy-wallet/src/lib.rs index 8528783d88..8ebda41fe7 100644 --- a/libvdrtools/indy-wallet/src/lib.rs +++ b/libvdrtools/indy-wallet/src/lib.rs @@ -1168,7 +1168,7 @@ impl Ord for WalletRecord { impl PartialOrd for WalletRecord { fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> { - (&self.type_, &self.id).partial_cmp(&(&other.type_, &other.id)) + Some(self.cmp(other)) } } diff --git a/messages/src/msg_types/registry.rs b/messages/src/msg_types/registry.rs index bdec49cfcc..d387f66d84 100644 --- a/messages/src/msg_types/registry.rs +++ b/messages/src/msg_types/registry.rs @@ -63,9 +63,7 @@ fn map_insert( roles, }; - map.entry((protocol_name, major)) - .or_insert(Vec::new()) - .push(entry); + map.entry((protocol_name, major)).or_default().push(entry); } lazy_static! { diff --git a/uniffi_aries_vcx/core/src/core/profile.rs b/uniffi_aries_vcx/core/src/core/profile.rs index 7e0c995b1c..17bbff06ca 100644 --- a/uniffi_aries_vcx/core/src/core/profile.rs +++ b/uniffi_aries_vcx/core/src/core/profile.rs @@ -6,46 +6,38 @@ use aries_vcx::{ ledger::base_ledger::TxnAuthrAgrmtOptions, wallet::indy::{wallet::create_and_open_wallet, IndySdkWallet, WalletConfig}, }, - core::profile::Profile, errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, utils::mockdata::profile::mock_ledger::MockLedger, }; -use async_trait::async_trait; use crate::{errors::error::VcxUniFFIResult, runtime::block_on}; #[derive(Debug)] pub struct UniffiProfile { - wallet: Arc, + wallet: IndySdkWallet, anoncreds: IndyCredxAnonCreds, ledger_read: MockLedger, ledger_write: MockLedger, } -#[async_trait] -impl Profile for UniffiProfile { - type LedgerRead = MockLedger; - type LedgerWrite = MockLedger; - type Anoncreds = IndyCredxAnonCreds; - type Wallet = IndySdkWallet; - - fn ledger_read(&self) -> &Self::LedgerRead { +impl UniffiProfile { + pub fn ledger_read(&self) -> &MockLedger { &self.ledger_read } - fn ledger_write(&self) -> &Self::LedgerWrite { + pub fn ledger_write(&self) -> &MockLedger { &self.ledger_write } - fn anoncreds(&self) -> &Self::Anoncreds { + pub fn anoncreds(&self) -> &IndyCredxAnonCreds { &self.anoncreds } - fn wallet(&self) -> &Self::Wallet { + pub fn wallet(&self) -> &IndySdkWallet { &self.wallet } - fn update_taa_configuration(&self, _taa_options: TxnAuthrAgrmtOptions) -> VcxResult<()> { + pub fn update_taa_configuration(&self, _taa_options: TxnAuthrAgrmtOptions) -> VcxResult<()> { Err(AriesVcxError::from_msg( AriesVcxErrorKind::ActionNotSupported, "update_taa_configuration no implemented for VdrtoolsProfile", @@ -61,9 +53,9 @@ pub fn new_indy_profile(wallet_config: WalletConfig) -> VcxUniFFIResult Date: Thu, 19 Oct 2023 13:28:24 +0200 Subject: [PATCH 2/6] Bump rustix from 0.37.24 to 0.37.25 (#1019) Bumps [rustix](https://github.com/bytecodealliance/rustix) from 0.37.24 to 0.37.25. - [Release notes](https://github.com/bytecodealliance/rustix/releases) - [Commits](https://github.com/bytecodealliance/rustix/compare/v0.37.24...v0.37.25) --- updated-dependencies: - dependency-name: rustix dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Cargo.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 13141df045..9889f1a9da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -509,7 +509,7 @@ dependencies = [ "log", "parking", "polling", - "rustix 0.37.24", + "rustix 0.37.25", "slab", "socket2 0.4.9", "waker-fn", @@ -3517,9 +3517,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.37.24" +version = "0.37.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4279d76516df406a8bd37e7dff53fd37d1a093f997a3c34a5c21658c126db06d" +checksum = "d4eb579851244c2c03e7c24f501c3432bed80b8f720af1d6e5b0e0f01555a035" dependencies = [ "bitflags 1.3.2", "errno", From 787b51c366db62666c44e3c1f4c74f6ccee2f97f Mon Sep 17 00:00:00 2001 From: nain-F49FF806 <126972030+nain-F49FF806@users.noreply.github.com> Date: Thu, 19 Oct 2023 18:30:33 +0200 Subject: [PATCH 3/6] Add support for pickup protocol messages (#1018) Add support for mediation related protocol messages (#1018) Signed-off-by: Naian <126972030+nain-F49FF806@users.noreply.github.com> --- aries_vcx/src/handlers/util.rs | 14 +++ messages/src/decorators/mod.rs | 1 + messages/src/decorators/transport.rs | 63 +++++++++++ messages/src/lib.rs | 10 +- messages/src/msg_fields/protocols/mod.rs | 1 + .../msg_fields/protocols/pickup/delivery.rs | 87 +++++++++++++++ .../protocols/pickup/delivery_request.rs | 62 +++++++++++ .../protocols/pickup/live_delivery_change.rs | 56 ++++++++++ .../protocols/pickup/messages_received.rs | 57 ++++++++++ .../src/msg_fields/protocols/pickup/mod.rs | 100 ++++++++++++++++++ .../src/msg_fields/protocols/pickup/status.rs | 58 ++++++++++ .../protocols/pickup/status_request.rs | 55 ++++++++++ messages/src/msg_types/protocols/mod.rs | 10 +- messages/src/msg_types/protocols/pickup.rs | 32 ++++++ messages/src/msg_types/registry.rs | 3 + 15 files changed, 604 insertions(+), 5 deletions(-) create mode 100644 messages/src/decorators/transport.rs create mode 100644 messages/src/msg_fields/protocols/pickup/delivery.rs create mode 100644 messages/src/msg_fields/protocols/pickup/delivery_request.rs create mode 100644 messages/src/msg_fields/protocols/pickup/live_delivery_change.rs create mode 100644 messages/src/msg_fields/protocols/pickup/messages_received.rs create mode 100644 messages/src/msg_fields/protocols/pickup/mod.rs create mode 100644 messages/src/msg_fields/protocols/pickup/status.rs create mode 100644 messages/src/msg_fields/protocols/pickup/status_request.rs create mode 100644 messages/src/msg_types/protocols/pickup.rs diff --git a/aries_vcx/src/handlers/util.rs b/aries_vcx/src/handlers/util.rs index a31af6808a..592017ea65 100644 --- a/aries_vcx/src/handlers/util.rs +++ b/aries_vcx/src/handlers/util.rs @@ -5,6 +5,7 @@ use messages::{ discover_features::DiscoverFeatures, notification::Notification, out_of_band::{invitation::Invitation as OobInvitation, OutOfBand}, + pickup::Pickup, present_proof::{ propose::{Predicate, PresentationAttr}, PresentProof, @@ -180,6 +181,19 @@ pub fn verify_thread_id(thread_id: &str, message: &AriesMessage) -> VcxResult<() AriesMessage::Routing(msg) => msg.id == thread_id, AriesMessage::TrustPing(TrustPing::Ping(msg)) => matches_opt_thread_id!(msg, thread_id), AriesMessage::TrustPing(TrustPing::PingResponse(msg)) => matches_thread_id!(msg, thread_id), + AriesMessage::Pickup(Pickup::Status(msg)) => matches_opt_thread_id!(msg, thread_id), + AriesMessage::Pickup(Pickup::StatusRequest(msg)) => matches_opt_thread_id!(msg, thread_id), + AriesMessage::Pickup(Pickup::Delivery(msg)) => matches_opt_thread_id!(msg, thread_id), + AriesMessage::Pickup(Pickup::DeliveryRequest(msg)) => { + matches_opt_thread_id!(msg, thread_id) + } + + AriesMessage::Pickup(Pickup::MessagesReceived(msg)) => { + matches_opt_thread_id!(msg, thread_id) + } + AriesMessage::Pickup(Pickup::LiveDeliveryChange(msg)) => { + matches_opt_thread_id!(msg, thread_id) + } }; if !is_match { diff --git a/messages/src/decorators/mod.rs b/messages/src/decorators/mod.rs index 3509c41229..6302a2517f 100644 --- a/messages/src/decorators/mod.rs +++ b/messages/src/decorators/mod.rs @@ -3,3 +3,4 @@ pub mod localization; pub mod please_ack; pub mod thread; pub mod timing; +pub mod transport; diff --git a/messages/src/decorators/transport.rs b/messages/src/decorators/transport.rs new file mode 100644 index 0000000000..5ec2e6ac15 --- /dev/null +++ b/messages/src/decorators/transport.rs @@ -0,0 +1,63 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::decorators::thread::Thread; + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct Transport { + pub return_route: ReturnRoute, + #[builder(default, setter(strip_option))] + #[serde(skip_serializing_if = "Option::is_none")] + pub return_route_thread: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq)] +pub enum ReturnRoute { + #[default] + #[serde(rename = "none")] + None, + #[serde(rename = "all")] + All, + #[serde(rename = "thread")] + Thread, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + + use super::*; + use crate::misc::test_utils; + + #[test] + fn test_transport_minimals() { + // all variant + let transport = Transport::builder().return_route(ReturnRoute::All).build(); + let expected = json!({ + "return_route": "all" + }); + test_utils::test_serde(transport, expected); + // none variant + let transport = Transport::builder().return_route(ReturnRoute::None).build(); + let expected = json!({ + "return_route": "none" + }); + test_utils::test_serde(transport, expected); + } + #[test] + fn test_transport_extended() { + // thread variant + let thread = Thread::builder().thid("".to_string()).build(); + let transport = Transport::builder() + .return_route(ReturnRoute::Thread) + .return_route_thread(thread) + .build(); + let expected = json!({ + "return_route": "thread", + "return_route_thread": { "thid": "" } + }); + test_utils::test_serde(transport, expected); + } +} diff --git a/messages/src/lib.rs b/messages/src/lib.rs index 6ac2d5d9f9..eb4f80e93e 100644 --- a/messages/src/lib.rs +++ b/messages/src/lib.rs @@ -15,8 +15,9 @@ pub mod msg_types; use derive_more::From; use misc::utils; -use msg_fields::protocols::cred_issuance::{ - v1::CredentialIssuanceV1, v2::CredentialIssuanceV2, CredentialIssuance, +use msg_fields::protocols::{ + cred_issuance::{v1::CredentialIssuanceV1, v2::CredentialIssuanceV2, CredentialIssuance}, + pickup::Pickup, }; use msg_types::{ cred_issuance::CredentialIssuanceType, report_problem::ReportProblemTypeV1_0, @@ -65,6 +66,7 @@ pub enum AriesMessage { BasicMessage(BasicMessage), OutOfBand(OutOfBand), Notification(Notification), + Pickup(Pickup), } impl DelayedSerde for AriesMessage { @@ -164,6 +166,9 @@ impl DelayedSerde for AriesMessage { Notification::delayed_deserialize((msg_type, kind_str), deserializer) .map(From::from) } + Protocol::PickupType(msg_type) => { + Pickup::delayed_deserialize((msg_type, kind_str), deserializer).map(From::from) + } } } @@ -184,6 +189,7 @@ impl DelayedSerde for AriesMessage { Self::BasicMessage(v) => MsgWithType::from(v).serialize(serializer), Self::OutOfBand(v) => v.delayed_serialize(serializer), Self::Notification(v) => v.delayed_serialize(serializer), + Self::Pickup(v) => v.delayed_serialize(serializer), } } } diff --git a/messages/src/msg_fields/protocols/mod.rs b/messages/src/msg_fields/protocols/mod.rs index c7d73091cc..bae4e6a82c 100644 --- a/messages/src/msg_fields/protocols/mod.rs +++ b/messages/src/msg_fields/protocols/mod.rs @@ -4,6 +4,7 @@ pub mod cred_issuance; pub mod discover_features; pub mod notification; pub mod out_of_band; +pub mod pickup; pub mod present_proof; pub mod report_problem; pub mod revocation; diff --git a/messages/src/msg_fields/protocols/pickup/delivery.rs b/messages/src/msg_fields/protocols/pickup/delivery.rs new file mode 100644 index 0000000000..6e8726a650 --- /dev/null +++ b/messages/src/msg_fields/protocols/pickup/delivery.rs @@ -0,0 +1,87 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + decorators::{attachment::Attachment, thread::Thread, transport::Transport}, + msg_parts::MsgParts, +}; + +pub type Delivery = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct DeliveryContent { + #[builder(default, setter(strip_option))] + #[serde(skip_serializing_if = "Option::is_none")] + pub recipient_key: Option, + #[serde(rename = "~attach")] + pub attach: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct DeliveryDecorators { + #[builder(default, setter(strip_option))] + #[serde(rename = "~transport")] + #[serde(skip_serializing_if = "Option::is_none")] + pub transport: Option, + #[builder(default, setter(strip_option))] + #[serde(rename = "~thread")] + #[serde(skip_serializing_if = "Option::is_none")] + pub thread: Option, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + + use super::*; + use crate::{ + decorators::{ + attachment::{AttachmentData, AttachmentType}, + thread::Thread, + }, + misc::test_utils, + msg_types::protocols::pickup::PickupTypeV2_0, + }; + #[test] + fn test_delivery() { + let expected = json!( + { + "@id": "123456781", + "~thread": { + "thid": "" + }, + "@type": "https://didcomm.org/messagepickup/2.0/delivery", + "recipient_key": "", + "~attach": [{ + "@id": "", + "data": { + "base64": "" + } + }] + } + ); + let attach = Attachment::builder() + .id("".to_owned()) + .data( + AttachmentData::builder() + .content(AttachmentType::Base64("".into())) + .build(), + ) + .build(); + let content = DeliveryContent::builder() + .recipient_key("".to_owned()) + .attach(vec![attach]) + .build(); + let decorators = DeliveryDecorators::builder() + .thread( + Thread::builder() + .thid("".to_owned()) + .build(), + ) + .build(); + + test_utils::test_msg(content, decorators, PickupTypeV2_0::Delivery, expected); + } +} diff --git a/messages/src/msg_fields/protocols/pickup/delivery_request.rs b/messages/src/msg_fields/protocols/pickup/delivery_request.rs new file mode 100644 index 0000000000..17d2734b41 --- /dev/null +++ b/messages/src/msg_fields/protocols/pickup/delivery_request.rs @@ -0,0 +1,62 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + decorators::{thread::Thread, transport::Transport}, + msg_parts::MsgParts, +}; + +pub type DeliveryRequest = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct DeliveryRequestContent { + pub limit: u32, + #[builder(default, setter(strip_option))] + #[serde(skip_serializing_if = "Option::is_none")] + pub recipient_key: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct DeliveryRequestDecorators { + #[builder(default, setter(strip_option))] + #[serde(rename = "~thread")] + #[serde(skip_serializing_if = "Option::is_none")] + pub thread: Option, + #[builder(default, setter(strip_option))] + #[serde(rename = "~transport")] + #[serde(skip_serializing_if = "Option::is_none")] + pub transport: Option, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + + use super::*; + use crate::{misc::test_utils, msg_types::protocols::pickup::PickupTypeV2_0}; + #[test] + fn test_delivery_request() { + let expected = json!( + { + "@id": "123456781", + "@type": "https://didcomm.org/messagepickup/2.0/delivery-request", + "limit": 10, + "recipient_key": "" + } + ); + let content = DeliveryRequestContent::builder() + .recipient_key("".to_owned()) + .limit(10) + .build(); + let decorators = DeliveryRequestDecorators::builder().build(); + + test_utils::test_msg( + content, + decorators, + PickupTypeV2_0::DeliveryRequest, + expected, + ); + } +} diff --git a/messages/src/msg_fields/protocols/pickup/live_delivery_change.rs b/messages/src/msg_fields/protocols/pickup/live_delivery_change.rs new file mode 100644 index 0000000000..ddc6deb752 --- /dev/null +++ b/messages/src/msg_fields/protocols/pickup/live_delivery_change.rs @@ -0,0 +1,56 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + decorators::{thread::Thread, transport::Transport}, + msg_parts::MsgParts, +}; + +pub type LiveDeliveryChange = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct LiveDeliveryChangeContent { + pub live_delivery: bool, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct LiveDeliveryChangeDecorators { + #[builder(default, setter(strip_option))] + #[serde(rename = "~transport")] + #[serde(skip_serializing_if = "Option::is_none")] + pub transport: Option, + #[builder(default, setter(strip_option))] + #[serde(rename = "~thread")] + #[serde(skip_serializing_if = "Option::is_none")] + pub thread: Option, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + + use super::*; + use crate::{misc::test_utils, msg_types::protocols::pickup::PickupTypeV2_0}; + #[test] + fn test_live_delivery_change() { + let expected = json!( + { + "@type": "https://didcomm.org/messagepickup/2.0/live-delivery-change", + "live_delivery": true + } + ); + let content = LiveDeliveryChangeContent::builder() + .live_delivery(true) + .build(); + let decorators = LiveDeliveryChangeDecorators::builder().build(); + + test_utils::test_msg( + content, + decorators, + PickupTypeV2_0::LiveDeliveryChange, + expected, + ); + } +} diff --git a/messages/src/msg_fields/protocols/pickup/messages_received.rs b/messages/src/msg_fields/protocols/pickup/messages_received.rs new file mode 100644 index 0000000000..47ebdf2151 --- /dev/null +++ b/messages/src/msg_fields/protocols/pickup/messages_received.rs @@ -0,0 +1,57 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + decorators::{thread::Thread, transport::Transport}, + msg_parts::MsgParts, +}; + +pub type MessagesReceived = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct MessagesReceivedContent { + pub message_id_list: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct MessagesReceivedDecorators { + #[builder(default, setter(strip_option))] + #[serde(rename = "~transport")] + #[serde(skip_serializing_if = "Option::is_none")] + pub transport: Option, + #[builder(default, setter(strip_option))] + #[serde(rename = "~thread")] + #[serde(skip_serializing_if = "Option::is_none")] + pub thread: Option, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + + use super::*; + use crate::{misc::test_utils, msg_types::protocols::pickup::PickupTypeV2_0}; + #[test] + fn test_messages_received() { + let expected = json!( + { + "@type": "https://didcomm.org/messagepickup/2.0/messages-received", + "message_id_list": ["123","456"] + } + + ); + let content = MessagesReceivedContent::builder() + .message_id_list(vec!["123".to_string(), "456".to_string()]) + .build(); + let decorators = MessagesReceivedDecorators::builder().build(); + + test_utils::test_msg( + content, + decorators, + PickupTypeV2_0::MessagesReceived, + expected, + ); + } +} diff --git a/messages/src/msg_fields/protocols/pickup/mod.rs b/messages/src/msg_fields/protocols/pickup/mod.rs new file mode 100644 index 0000000000..cdc4ec2373 --- /dev/null +++ b/messages/src/msg_fields/protocols/pickup/mod.rs @@ -0,0 +1,100 @@ +mod delivery; +mod delivery_request; +mod live_delivery_change; +mod messages_received; +mod status; +mod status_request; +use derive_more::From; +use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; + +use self::{ + delivery::{Delivery, DeliveryContent, DeliveryDecorators}, + delivery_request::{DeliveryRequest, DeliveryRequestContent, DeliveryRequestDecorators}, + live_delivery_change::{ + LiveDeliveryChange, LiveDeliveryChangeContent, LiveDeliveryChangeDecorators, + }, + messages_received::{MessagesReceived, MessagesReceivedContent, MessagesReceivedDecorators}, + status::{Status, StatusContent, StatusDecorators}, + status_request::{StatusRequest, StatusRequestContent, StatusRequestDecorators}, +}; +use crate::{ + misc::utils::{into_msg_with_type, transit_to_aries_msg}, + msg_fields::traits::DelayedSerde, + msg_types::{ + protocols::pickup::{PickupType, PickupTypeV2, PickupTypeV2_0}, + MsgWithType, + }, +}; + +#[derive(Clone, Debug, From, PartialEq)] +pub enum Pickup { + Status(Status), + StatusRequest(StatusRequest), + DeliveryRequest(DeliveryRequest), + Delivery(Delivery), + MessagesReceived(MessagesReceived), + LiveDeliveryChange(LiveDeliveryChange), +} + +impl DelayedSerde for Pickup { + type MsgType<'a> = (PickupType, &'a str); + + fn delayed_deserialize<'de, D>( + msg_type: Self::MsgType<'de>, + deserializer: D, + ) -> Result + where + D: Deserializer<'de>, + { + let (protocol, kind_str) = msg_type; + + let kind = match protocol { + PickupType::V2(PickupTypeV2::V2_0(kind)) => kind.kind_from_str(kind_str), + }; + + match kind.map_err(D::Error::custom)? { + PickupTypeV2_0::StatusRequest => { + StatusRequest::deserialize(deserializer).map(From::from) + } + PickupTypeV2_0::Status => Status::deserialize(deserializer).map(From::from), + PickupTypeV2_0::DeliveryRequest => { + DeliveryRequest::deserialize(deserializer).map(From::from) + } + PickupTypeV2_0::Delivery => Delivery::deserialize(deserializer).map(From::from), + PickupTypeV2_0::MessagesReceived => { + MessagesReceived::deserialize(deserializer).map(From::from) + } + PickupTypeV2_0::LiveDeliveryChange => { + LiveDeliveryChange::deserialize(deserializer).map(From::from) + } + } + } + + fn delayed_serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self { + Self::Status(v) => MsgWithType::from(v).serialize(serializer), + Self::StatusRequest(v) => MsgWithType::from(v).serialize(serializer), + Self::Delivery(v) => MsgWithType::from(v).serialize(serializer), + Self::DeliveryRequest(v) => MsgWithType::from(v).serialize(serializer), + Self::MessagesReceived(v) => MsgWithType::from(v).serialize(serializer), + Self::LiveDeliveryChange(v) => MsgWithType::from(v).serialize(serializer), + } + } +} + +transit_to_aries_msg!(StatusContent: StatusDecorators, Pickup); +transit_to_aries_msg!(StatusRequestContent: StatusRequestDecorators, Pickup); +transit_to_aries_msg!(DeliveryContent: DeliveryDecorators, Pickup); +transit_to_aries_msg!(DeliveryRequestContent: DeliveryRequestDecorators, Pickup); +transit_to_aries_msg!(MessagesReceivedContent: MessagesReceivedDecorators, Pickup); +transit_to_aries_msg!(LiveDeliveryChangeContent: LiveDeliveryChangeDecorators, Pickup); + +into_msg_with_type!(Status, PickupTypeV2_0, Status); +into_msg_with_type!(StatusRequest, PickupTypeV2_0, StatusRequest); +into_msg_with_type!(Delivery, PickupTypeV2_0, Delivery); +into_msg_with_type!(DeliveryRequest, PickupTypeV2_0, DeliveryRequest); +into_msg_with_type!(MessagesReceived, PickupTypeV2_0, MessagesReceived); +into_msg_with_type!(LiveDeliveryChange, PickupTypeV2_0, LiveDeliveryChange); diff --git a/messages/src/msg_fields/protocols/pickup/status.rs b/messages/src/msg_fields/protocols/pickup/status.rs new file mode 100644 index 0000000000..0543911844 --- /dev/null +++ b/messages/src/msg_fields/protocols/pickup/status.rs @@ -0,0 +1,58 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + decorators::{thread::Thread, transport::Transport}, + msg_parts::MsgParts, +}; + +pub type Status = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct StatusContent { + pub message_count: u32, + #[builder(default, setter(strip_option))] + #[serde(skip_serializing_if = "Option::is_none")] + pub recipient_key: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct StatusDecorators { + #[builder(default, setter(strip_option))] + #[serde(rename = "~transport")] + #[serde(skip_serializing_if = "Option::is_none")] + pub transport: Option, + #[builder(default, setter(strip_option))] + #[serde(rename = "~thread")] + #[serde(skip_serializing_if = "Option::is_none")] + pub thread: Option, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + + use super::*; + use crate::{misc::test_utils, msg_types::protocols::pickup::PickupTypeV2_0}; + + #[test] + fn test_status() { + let expected = json!( + { + "@id": "123456781", + "@type": "https://didcomm.org/messagepickup/2.0/status", + "recipient_key": "", + "message_count": 7, + } + ); + let content = StatusContent::builder() + .recipient_key("".to_owned()) + .message_count(7) + .build(); + let decorators = StatusDecorators::builder().build(); + + test_utils::test_msg(content, decorators, PickupTypeV2_0::Status, expected); + } +} diff --git a/messages/src/msg_fields/protocols/pickup/status_request.rs b/messages/src/msg_fields/protocols/pickup/status_request.rs new file mode 100644 index 0000000000..cb61f63d89 --- /dev/null +++ b/messages/src/msg_fields/protocols/pickup/status_request.rs @@ -0,0 +1,55 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + decorators::{thread::Thread, transport::Transport}, + msg_parts::MsgParts, +}; + +pub type StatusRequest = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct StatusRequestContent { + #[builder(default, setter(strip_option))] + #[serde(skip_serializing_if = "Option::is_none")] + pub recipient_key: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct StatusRequestDecorators { + #[builder(default, setter(strip_option))] + #[serde(rename = "~transport")] + #[serde(skip_serializing_if = "Option::is_none")] + pub transport: Option, + #[builder(default, setter(strip_option))] + #[serde(rename = "~thread")] + #[serde(skip_serializing_if = "Option::is_none")] + pub thread: Option, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + + use super::*; + use crate::{misc::test_utils, msg_types::protocols::pickup::PickupTypeV2_0}; + + #[test] + fn test_status_request() { + let expected = json!( + { + "@id": "123456781", + "@type": "https://didcomm.org/messagepickup/2.0/status-request", + "recipient_key": "" + } + ); + let content = StatusRequestContent::builder() + .recipient_key("".to_owned()) + .build(); + let decorators = StatusRequestDecorators::builder().build(); + + test_utils::test_msg(content, decorators, PickupTypeV2_0::StatusRequest, expected); + } +} diff --git a/messages/src/msg_types/protocols/mod.rs b/messages/src/msg_types/protocols/mod.rs index 73cb74d936..81060fed83 100644 --- a/messages/src/msg_types/protocols/mod.rs +++ b/messages/src/msg_types/protocols/mod.rs @@ -7,9 +7,9 @@ use shared_vcx::misc::utils::CowStr; use self::{ basic_message::BasicMessageType, connection::ConnectionType, cred_issuance::CredentialIssuanceType, discover_features::DiscoverFeaturesType, - notification::NotificationType, out_of_band::OutOfBandType, present_proof::PresentProofType, - report_problem::ReportProblemType, revocation::RevocationType, routing::RoutingType, - signature::SignatureType, trust_ping::TrustPingType, + notification::NotificationType, out_of_band::OutOfBandType, pickup::PickupType, + present_proof::PresentProofType, report_problem::ReportProblemType, revocation::RevocationType, + routing::RoutingType, signature::SignatureType, trust_ping::TrustPingType, }; use crate::{ error::{MsgTypeError, MsgTypeResult}, @@ -22,6 +22,7 @@ pub mod cred_issuance; pub mod discover_features; pub mod notification; pub mod out_of_band; +pub mod pickup; pub mod present_proof; pub mod report_problem; pub mod revocation; @@ -58,6 +59,7 @@ pub enum Protocol { BasicMessageType(BasicMessageType), OutOfBandType(OutOfBandType), NotificationType(NotificationType), + PickupType(PickupType), } /// Utility macro to avoid harder to read and error prone calling @@ -93,6 +95,7 @@ impl Protocol { match_protocol!(BasicMessageType, protocol, major, minor); match_protocol!(OutOfBandType, protocol, major, minor); match_protocol!(NotificationType, protocol, major, minor); + match_protocol!(PickupType, protocol, major, minor); Err(MsgTypeError::unknown_protocol(protocol.to_owned())) } @@ -112,6 +115,7 @@ impl Protocol { Self::BasicMessageType(v) => v.as_protocol_parts(), Self::OutOfBandType(v) => v.as_protocol_parts(), Self::NotificationType(v) => v.as_protocol_parts(), + Self::PickupType(v) => v.as_protocol_parts(), } } diff --git a/messages/src/msg_types/protocols/pickup.rs b/messages/src/msg_types/protocols/pickup.rs new file mode 100644 index 0000000000..90eb93fe89 --- /dev/null +++ b/messages/src/msg_types/protocols/pickup.rs @@ -0,0 +1,32 @@ +use derive_more::{From, TryInto}; +use messages_macros::MessageType; +use strum_macros::{AsRefStr, EnumString}; +use transitive::Transitive; + +use super::Protocol; +use crate::msg_types::{MsgKindType, Role}; + +#[derive(Copy, Clone, Debug, From, TryInto, PartialEq, MessageType)] +#[msg_type(protocol = "messagepickup")] +pub enum PickupType { + V2(PickupTypeV2), +} + +#[derive(Copy, Clone, Debug, From, TryInto, PartialEq, Transitive, MessageType)] +#[transitive(into(PickupType, Protocol))] +#[msg_type(major = 2)] +pub enum PickupTypeV2 { + #[msg_type(minor = 0, roles = "Role::Mediator")] + V2_0(MsgKindType), +} + +#[derive(Copy, Clone, Debug, AsRefStr, EnumString, PartialEq)] +#[strum(serialize_all = "kebab-case")] +pub enum PickupTypeV2_0 { + Status, + StatusRequest, + DeliveryRequest, + Delivery, + MessagesReceived, + LiveDeliveryChange, +} diff --git a/messages/src/msg_types/registry.rs b/messages/src/msg_types/registry.rs index d387f66d84..f77dc34b3e 100644 --- a/messages/src/msg_types/registry.rs +++ b/messages/src/msg_types/registry.rs @@ -11,6 +11,7 @@ use crate::msg_types::protocols::{ discover_features::DiscoverFeaturesTypeV1, notification::NotificationTypeV1, out_of_band::OutOfBandTypeV1, + pickup::PickupTypeV2, present_proof::PresentProofTypeV1, report_problem::ReportProblemTypeV1, revocation::RevocationTypeV2, @@ -87,6 +88,8 @@ lazy_static! { map_insert(&mut m, extract_parts!(ReportProblemTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(RevocationTypeV2::new_v2_0())); map_insert(&mut m, extract_parts!(TrustPingTypeV1::new_v1_0())); + map_insert(&mut m, extract_parts!(PickupTypeV2::new_v2_0())); + m }; } From f7c1e6671447b1bf41cb0dd66b984f345a42ef8c Mon Sep 17 00:00:00 2001 From: gmulhearn-anonyome <90162009+gmulhearn-anonyome@users.noreply.github.com> Date: Fri, 20 Oct 2023 17:17:53 +1000 Subject: [PATCH 4/6] Present Proof V2.0 message structures (#1017) Present Proof V2.0 message structures --------- Signed-off-by: George Mulhearn --- .../aries-vcx-agent/src/services/prover.rs | 8 +- .../aries-vcx-agent/src/services/verifier.rs | 8 +- .../src/handlers/out_of_band/receiver.rs | 14 +- aries_vcx/src/handlers/out_of_band/sender.rs | 6 +- .../proof_presentation/mediated_prover.rs | 15 +- .../proof_presentation/mediated_verifier.rs | 21 ++- .../src/handlers/proof_presentation/prover.rs | 44 +++--- .../handlers/proof_presentation/verifier.rs | 39 +++-- aries_vcx/src/handlers/util.rs | 33 ++++- .../prover/state_machine.rs | 50 ++++--- .../prover/states/finished.rs | 6 +- .../states/presentation_preparation_failed.rs | 4 +- .../prover/states/presentation_prepared.rs | 8 +- .../states/presentation_proposal_sent.rs | 12 +- .../states/presentation_request_received.rs | 18 +-- .../prover/states/presentation_sent.rs | 12 +- .../verifier/state_machine.rs | 50 +++---- .../verifier/states/finished.rs | 6 +- .../states/presentation_proposal_received.rs | 16 +- .../states/presentation_request_sent.rs | 10 +- .../states/presentation_request_set.rs | 12 +- aries_vcx/src/utils/filters.rs | 10 +- aries_vcx/tests/test_credential_retrieval.rs | 24 +-- aries_vcx/tests/test_proof_presentation.rs | 7 +- aries_vcx/tests/utils/scenarios/data.rs | 2 +- .../utils/scenarios/proof_presentation.rs | 38 +++-- .../src/api_vcx/api_handle/disclosed_proof.rs | 21 ++- messages/src/lib.rs | 29 +++- .../common/attachment_format_specifier.rs | 23 +++ .../src/msg_fields/protocols/common/mod.rs | 1 + .../cred_issuance/v2/issue_credential.rs | 2 +- .../protocols/cred_issuance/v2/mod.rs | 10 +- .../cred_issuance/v2/offer_credential.rs | 3 +- .../cred_issuance/v2/propose_credential.rs | 3 +- .../cred_issuance/v2/request_credential.rs | 2 +- messages/src/msg_fields/protocols/mod.rs | 1 + .../msg_fields/protocols/present_proof/mod.rs | 119 +-------------- .../protocols/present_proof/{ => v1}/ack.rs | 14 +- .../protocols/present_proof/v1/mod.rs | 133 +++++++++++++++++ .../present_proof/{ => v1}/present.rs | 14 +- .../present_proof/{ => v1}/problem_report.rs | 16 +- .../present_proof/{ => v1}/propose.rs | 15 +- .../present_proof/{ => v1}/request.rs | 15 +- .../protocols/present_proof/v2/ack.rs | 80 ++++++++++ .../protocols/present_proof/v2/mod.rs | 134 +++++++++++++++++ .../protocols/present_proof/v2/present.rs | 134 +++++++++++++++++ .../present_proof/v2/problem_report.rs | 137 ++++++++++++++++++ .../protocols/present_proof/v2/propose.rs | 126 ++++++++++++++++ .../protocols/present_proof/v2/request.rs | 132 +++++++++++++++++ .../src/msg_types/protocols/present_proof.rs | 106 +++++++++++++- messages/src/msg_types/registry.rs | 32 ++-- 51 files changed, 1372 insertions(+), 403 deletions(-) create mode 100644 messages/src/msg_fields/protocols/common/attachment_format_specifier.rs create mode 100644 messages/src/msg_fields/protocols/common/mod.rs rename messages/src/msg_fields/protocols/present_proof/{ => v1}/ack.rs (79%) create mode 100644 messages/src/msg_fields/protocols/present_proof/v1/mod.rs rename messages/src/msg_fields/protocols/present_proof/{ => v1}/present.rs (87%) rename messages/src/msg_fields/protocols/present_proof/{ => v1}/problem_report.rs (89%) rename messages/src/msg_fields/protocols/present_proof/{ => v1}/propose.rs (93%) rename messages/src/msg_fields/protocols/present_proof/{ => v1}/request.rs (84%) create mode 100644 messages/src/msg_fields/protocols/present_proof/v2/ack.rs create mode 100644 messages/src/msg_fields/protocols/present_proof/v2/mod.rs create mode 100644 messages/src/msg_fields/protocols/present_proof/v2/present.rs create mode 100644 messages/src/msg_fields/protocols/present_proof/v2/problem_report.rs create mode 100644 messages/src/msg_fields/protocols/present_proof/v2/propose.rs create mode 100644 messages/src/msg_fields/protocols/present_proof/v2/request.rs diff --git a/agents/rust/aries-vcx-agent/src/services/prover.rs b/agents/rust/aries-vcx-agent/src/services/prover.rs index 6c9219c97c..39c3b9731a 100644 --- a/agents/rust/aries-vcx-agent/src/services/prover.rs +++ b/agents/rust/aries-vcx-agent/src/services/prover.rs @@ -6,8 +6,8 @@ use aries_vcx::{ util::PresentationProposalData, }, messages::{ - msg_fields::protocols::present_proof::{ - ack::AckPresentation, request::RequestPresentation, + msg_fields::protocols::present_proof::v1::{ + ack::AckPresentationV1, request::RequestPresentationV1, }, AriesMessage, }, @@ -98,7 +98,7 @@ impl ServiceProver { pub fn create_from_request( &self, connection_id: &str, - request: RequestPresentation, + request: RequestPresentationV1, ) -> AgentResult { self.service_connections.get_by_id(connection_id)?; let prover = Prover::create_from_request("", request)?; @@ -178,7 +178,7 @@ impl ServiceProver { pub fn process_presentation_ack( &self, thread_id: &str, - ack: AckPresentation, + ack: AckPresentationV1, ) -> AgentResult { let ProverWrapper { mut prover, diff --git a/agents/rust/aries-vcx-agent/src/services/verifier.rs b/agents/rust/aries-vcx-agent/src/services/verifier.rs index 3240120785..40b0342dd0 100644 --- a/agents/rust/aries-vcx-agent/src/services/verifier.rs +++ b/agents/rust/aries-vcx-agent/src/services/verifier.rs @@ -4,8 +4,8 @@ use aries_vcx::{ common::proofs::proof_request::PresentationRequestData, handlers::proof_presentation::verifier::Verifier, messages::{ - msg_fields::protocols::present_proof::{ - present::Presentation, propose::ProposePresentation, + msg_fields::protocols::present_proof::v1::{ + present::PresentationV1, propose::ProposePresentationV1, }, AriesMessage, }, @@ -69,7 +69,7 @@ impl ServiceVerifier { &self, connection_id: &str, request: PresentationRequestData, - proposal: Option, + proposal: Option, ) -> AgentResult { let connection = self.service_connections.get_by_id(connection_id)?; let mut verifier = if let Some(proposal) = proposal { @@ -103,7 +103,7 @@ impl ServiceVerifier { pub async fn verify_presentation( &self, thread_id: &str, - presentation: Presentation, + presentation: PresentationV1, ) -> AgentResult<()> { let VerifierWrapper { mut verifier, diff --git a/aries_vcx/src/handlers/out_of_band/receiver.rs b/aries_vcx/src/handlers/out_of_band/receiver.rs index c0bb718537..b714d9c46f 100644 --- a/aries_vcx/src/handlers/out_of_band/receiver.rs +++ b/aries_vcx/src/handlers/out_of_band/receiver.rs @@ -18,7 +18,7 @@ use messages::{ invitation::{Invitation, OobService}, OutOfBand, }, - present_proof::{present::Presentation, request::RequestPresentation, PresentProof}, + present_proof::v1::{present::PresentationV1, request::RequestPresentationV1}, }, AriesMessage, }; @@ -263,20 +263,18 @@ impl OutOfBandReceiver { } AttachmentId::PresentationRequest => { let request = - RequestPresentation::deserialize(&attach_json).map_err(|_| { + RequestPresentationV1::deserialize(&attach_json).map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Failed to deserialize attachment: {attach_json:?}"), ) })?; - return Ok(Some(AriesMessage::PresentProof( - PresentProof::RequestPresentation(request), - ))); + return Ok(Some(request.into())); } AttachmentId::Presentation => { let mut presentation = - Presentation::deserialize(&attach_json).map_err(|_| { + PresentationV1::deserialize(&attach_json).map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Failed to deserialize attachment: {attach_json:?}"), @@ -285,9 +283,7 @@ impl OutOfBandReceiver { presentation.decorators.thread.pthid = Some(self.oob.id.clone()); - return Ok(Some(AriesMessage::PresentProof( - PresentProof::Presentation(presentation), - ))); + return Ok(Some(presentation.into())); } }, None => { diff --git a/aries_vcx/src/handlers/out_of_band/sender.rs b/aries_vcx/src/handlers/out_of_band/sender.rs index d849993a6f..a754d71907 100644 --- a/aries_vcx/src/handlers/out_of_band/sender.rs +++ b/aries_vcx/src/handlers/out_of_band/sender.rs @@ -7,7 +7,7 @@ use messages::{ invitation::{Invitation, InvitationContent, InvitationDecorators, OobService}, OobGoalCode, }, - present_proof::PresentProof, + present_proof::{v1::PresentProofV1, PresentProof}, }, msg_types::Protocol, AriesMessage, @@ -92,7 +92,9 @@ impl OutOfBandSender { pub fn append_a2a_message(mut self, msg: AriesMessage) -> VcxResult { let (attach_id, attach) = match msg { - a2a_msg @ AriesMessage::PresentProof(PresentProof::RequestPresentation(_)) => ( + a2a_msg @ AriesMessage::PresentProof(PresentProof::V1( + PresentProofV1::RequestPresentation(_), + )) => ( AttachmentId::PresentationRequest, json!(&a2a_msg).to_string(), ), diff --git a/aries_vcx/src/handlers/proof_presentation/mediated_prover.rs b/aries_vcx/src/handlers/proof_presentation/mediated_prover.rs index faaee77677..e5e8c14638 100644 --- a/aries_vcx/src/handlers/proof_presentation/mediated_prover.rs +++ b/aries_vcx/src/handlers/proof_presentation/mediated_prover.rs @@ -1,7 +1,10 @@ use std::collections::HashMap; use messages::{ - msg_fields::protocols::{notification::Notification, present_proof::PresentProof}, + msg_fields::protocols::{ + notification::Notification, + present_proof::{v1::PresentProofV1, PresentProof}, + }, AriesMessage, }; @@ -32,7 +35,9 @@ pub fn prover_find_message_to_handle( return Some((uid, message)); } } - AriesMessage::PresentProof(PresentProof::RequestPresentation(msg)) => { + AriesMessage::PresentProof(PresentProof::V1( + PresentProofV1::RequestPresentation(msg), + )) => { if matches_opt_thread_id!(msg, sm.get_thread_id().unwrap().as_str()) { return Some((uid, message)); } @@ -45,7 +50,7 @@ pub fn prover_find_message_to_handle( return Some((uid, message)); } } - AriesMessage::PresentProof(PresentProof::Ack(msg)) => { + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Ack(msg))) => { if matches_thread_id!(msg, sm.get_thread_id().unwrap().as_str()) { return Some((uid, message)); } @@ -60,7 +65,9 @@ pub fn prover_find_message_to_handle( return Some((uid, message)); } } - AriesMessage::PresentProof(PresentProof::ProblemReport(msg)) => { + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::ProblemReport( + msg, + ))) => { if matches_opt_thread_id!(msg, sm.get_thread_id().unwrap().as_str()) { return Some((uid, message)); } diff --git a/aries_vcx/src/handlers/proof_presentation/mediated_verifier.rs b/aries_vcx/src/handlers/proof_presentation/mediated_verifier.rs index bb7d861b94..de9b04c072 100644 --- a/aries_vcx/src/handlers/proof_presentation/mediated_verifier.rs +++ b/aries_vcx/src/handlers/proof_presentation/mediated_verifier.rs @@ -1,6 +1,9 @@ use std::collections::HashMap; -use messages::{msg_fields::protocols::present_proof::PresentProof, AriesMessage}; +use messages::{ + msg_fields::protocols::present_proof::{v1::PresentProofV1, PresentProof}, + AriesMessage, +}; use crate::{ handlers::{ @@ -22,21 +25,29 @@ pub fn verifier_find_message_to_handle( for (uid, message) in messages { match sm.get_state() { VerifierState::Initial => match &message { - AriesMessage::PresentProof(PresentProof::ProposePresentation(_)) => { + AriesMessage::PresentProof(PresentProof::V1( + PresentProofV1::ProposePresentation(_), + )) => { return Some((uid, message)); } - AriesMessage::PresentProof(PresentProof::RequestPresentation(_)) => { + AriesMessage::PresentProof(PresentProof::V1( + PresentProofV1::RequestPresentation(_), + )) => { return Some((uid, message)); } _ => {} }, VerifierState::PresentationRequestSent => match &message { - AriesMessage::PresentProof(PresentProof::Presentation(presentation)) => { + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Presentation( + presentation, + ))) => { if matches_thread_id!(presentation, sm.get_thread_id().unwrap().as_str()) { return Some((uid, message)); } } - AriesMessage::PresentProof(PresentProof::ProposePresentation(proposal)) => { + AriesMessage::PresentProof(PresentProof::V1( + PresentProofV1::ProposePresentation(proposal), + )) => { if matches_opt_thread_id!(proposal, sm.get_thread_id().unwrap().as_str()) { return Some((uid, message)); } diff --git a/aries_vcx/src/handlers/proof_presentation/prover.rs b/aries_vcx/src/handlers/proof_presentation/prover.rs index 752df1e9ed..dcff12167f 100644 --- a/aries_vcx/src/handlers/proof_presentation/prover.rs +++ b/aries_vcx/src/handlers/proof_presentation/prover.rs @@ -10,13 +10,16 @@ use messages::{ msg_fields::protocols::{ notification::Notification, present_proof::{ - ack::AckPresentation, - present::Presentation, - propose::{ - PresentationPreview, ProposePresentation, ProposePresentationContent, - ProposePresentationDecorators, + v1::{ + ack::AckPresentationV1, + present::PresentationV1, + propose::{ + PresentationPreview, ProposePresentationV1, ProposePresentationV1Content, + ProposePresentationV1Decorators, + }, + request::RequestPresentationV1, + PresentProofV1, }, - request::RequestPresentation, PresentProof, }, }, @@ -49,7 +52,7 @@ impl Prover { pub fn create_from_request( source_id: &str, - presentation_request: RequestPresentation, + presentation_request: RequestPresentationV1, ) -> VcxResult { trace!( "Prover::create_from_request >>> source_id: {}, presentation_request: {:?}", @@ -107,14 +110,14 @@ impl Prover { Ok(()) } - pub fn get_presentation_msg(&self) -> VcxResult { + pub fn get_presentation_msg(&self) -> VcxResult { Ok(self.prover_sm.get_presentation_msg()?.to_owned()) } pub async fn build_presentation_proposal( &mut self, proposal_data: PresentationProposalData, - ) -> VcxResult { + ) -> VcxResult { trace!("Prover::build_presentation_proposal >>>"); self.prover_sm = self .prover_sm @@ -140,7 +143,7 @@ impl Prover { } } - pub fn process_presentation_ack(&mut self, ack: AckPresentation) -> VcxResult<()> { + pub fn process_presentation_ack(&mut self, ack: AckPresentationV1) -> VcxResult<()> { trace!("Prover::process_presentation_ack >>>"); self.prover_sm = self.prover_sm.clone().receive_presentation_ack(ack)?; Ok(()) @@ -191,11 +194,13 @@ impl Prover { pub async fn process_aries_msg(&mut self, message: AriesMessage) -> VcxResult<()> { let prover_sm = match message { - AriesMessage::PresentProof(PresentProof::RequestPresentation(request)) => self + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::RequestPresentation( + request, + ))) => self .prover_sm .clone() .receive_presentation_request(request)?, - AriesMessage::PresentProof(PresentProof::Ack(ack)) => { + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Ack(ack))) => { self.prover_sm.clone().receive_presentation_ack(ack)? } AriesMessage::ReportProblem(report) => { @@ -205,10 +210,11 @@ impl Prover { .prover_sm .clone() .receive_presentation_reject(report.into())?, - AriesMessage::PresentProof(PresentProof::ProblemReport(report)) => self - .prover_sm - .clone() - .receive_presentation_reject(report.into())?, + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::ProblemReport(report))) => { + self.prover_sm + .clone() + .receive_presentation_reject(report.into())? + } _ => self.prover_sm.clone(), }; self.prover_sm = prover_sm; @@ -249,16 +255,16 @@ impl Prover { let thread_id = self.prover_sm.get_thread_id()?; let id = Uuid::new_v4().to_string(); - let content = ProposePresentationContent::builder() + let content = ProposePresentationV1Content::builder() .presentation_proposal(presentation_preview) .build(); - let decorators = ProposePresentationDecorators::builder() + let decorators = ProposePresentationV1Decorators::builder() .thread(Thread::builder().thid(thread_id.to_owned()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); - let proposal = ProposePresentation::builder() + let proposal = ProposePresentationV1::builder() .id(id) .content(content) .decorators(decorators) diff --git a/aries_vcx/src/handlers/proof_presentation/verifier.rs b/aries_vcx/src/handlers/proof_presentation/verifier.rs index 1ab9c51586..ba5f2565b7 100644 --- a/aries_vcx/src/handlers/proof_presentation/verifier.rs +++ b/aries_vcx/src/handlers/proof_presentation/verifier.rs @@ -5,7 +5,10 @@ use messages::{ msg_fields::protocols::{ notification::Notification, present_proof::{ - present::Presentation, propose::ProposePresentation, request::RequestPresentation, + v1::{ + present::PresentationV1, propose::ProposePresentationV1, + request::RequestPresentationV1, PresentProofV1, + }, PresentProof, }, report_problem::ProblemReport, @@ -55,7 +58,7 @@ impl Verifier { pub fn create_from_proposal( source_id: &str, - presentation_proposal: &ProposePresentation, + presentation_proposal: &ProposePresentationV1, ) -> VcxResult { trace!( "Issuer::create_from_proposal >>> source_id: {:?}, presentation_proposal: {:?}", @@ -76,7 +79,7 @@ impl Verifier { } // TODO: Find a better name for this method - pub fn mark_presentation_request_sent(&mut self) -> VcxResult { + pub fn mark_presentation_request_sent(&mut self) -> VcxResult { if self.verifier_sm.get_state() == VerifierState::PresentationRequestSet { let request = self.verifier_sm.presentation_request_msg()?; self.verifier_sm = self.verifier_sm.clone().mark_presentation_request_sent()?; @@ -94,7 +97,7 @@ impl Verifier { &mut self, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, - presentation: Presentation, + presentation: PresentationV1, ) -> VcxResult { trace!("Verifier::verify_presentation >>>"); self.verifier_sm = self @@ -123,7 +126,7 @@ impl Verifier { Ok(()) } - pub fn get_presentation_request_msg(&self) -> VcxResult { + pub fn get_presentation_request_msg(&self) -> VcxResult { self.verifier_sm.presentation_request_msg() } @@ -134,7 +137,7 @@ impl Verifier { )) } - pub fn get_presentation_msg(&self) -> VcxResult { + pub fn get_presentation_msg(&self) -> VcxResult { self.verifier_sm.get_presentation_msg() } @@ -149,7 +152,7 @@ impl Verifier { )) } - pub fn get_presentation_proposal(&self) -> VcxResult { + pub fn get_presentation_proposal(&self) -> VcxResult { self.verifier_sm.presentation_proposal() } @@ -164,13 +167,17 @@ impl Verifier { message: AriesMessage, ) -> VcxResult> { let (verifier_sm, message) = match message { - AriesMessage::PresentProof(PresentProof::ProposePresentation(proposal)) => ( + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::ProposePresentation( + proposal, + ))) => ( self.verifier_sm .clone() .receive_presentation_proposal(proposal)?, None, ), - AriesMessage::PresentProof(PresentProof::Presentation(presentation)) => { + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Presentation( + presentation, + ))) => { let sm = self .verifier_sm .clone() @@ -190,12 +197,14 @@ impl Verifier { .receive_presentation_request_reject(report.into())?, None, ), - AriesMessage::PresentProof(PresentProof::ProblemReport(report)) => ( - self.verifier_sm - .clone() - .receive_presentation_request_reject(report.into())?, - None, - ), + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::ProblemReport(report))) => { + ( + self.verifier_sm + .clone() + .receive_presentation_request_reject(report.into())?, + None, + ) + } _ => (self.verifier_sm.clone(), None), }; self.verifier_sm = verifier_sm; diff --git a/aries_vcx/src/handlers/util.rs b/aries_vcx/src/handlers/util.rs index 592017ea65..088f8c5267 100644 --- a/aries_vcx/src/handlers/util.rs +++ b/aries_vcx/src/handlers/util.rs @@ -7,7 +7,11 @@ use messages::{ out_of_band::{invitation::Invitation as OobInvitation, OutOfBand}, pickup::Pickup, present_proof::{ - propose::{Predicate, PresentationAttr}, + v1::{ + propose::{Predicate, PresentationAttr}, + PresentProofV1, + }, + v2::PresentProofV2, PresentProof, }, report_problem::ProblemReport, @@ -162,17 +166,34 @@ pub fn verify_thread_id(thread_id: &str, message: &AriesMessage) -> VcxResult<() AriesMessage::OutOfBand(OutOfBand::HandshakeReuseAccepted(msg)) => { matches_thread_id!(msg, thread_id) } - AriesMessage::PresentProof(PresentProof::Ack(msg)) => matches_thread_id!(msg, thread_id), - AriesMessage::PresentProof(PresentProof::Presentation(msg)) => { + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Ack(msg))) => { matches_thread_id!(msg, thread_id) } - AriesMessage::PresentProof(PresentProof::ProposePresentation(msg)) => { + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Presentation(msg))) => { + matches_thread_id!(msg, thread_id) + } + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::ProposePresentation(msg))) => { + matches_opt_thread_id!(msg, thread_id) + } + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::RequestPresentation(msg))) => { + matches_opt_thread_id!(msg, thread_id) + } + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::ProblemReport(msg))) => { + matches_opt_thread_id!(msg, thread_id) + } + AriesMessage::PresentProof(PresentProof::V2(PresentProofV2::Ack(msg))) => { + matches_thread_id!(msg, thread_id) + } + AriesMessage::PresentProof(PresentProof::V2(PresentProofV2::Presentation(msg))) => { + matches_thread_id!(msg, thread_id) + } + AriesMessage::PresentProof(PresentProof::V2(PresentProofV2::ProposePresentation(msg))) => { matches_opt_thread_id!(msg, thread_id) } - AriesMessage::PresentProof(PresentProof::RequestPresentation(msg)) => { + AriesMessage::PresentProof(PresentProof::V2(PresentProofV2::RequestPresentation(msg))) => { matches_opt_thread_id!(msg, thread_id) } - AriesMessage::PresentProof(PresentProof::ProblemReport(msg)) => { + AriesMessage::PresentProof(PresentProof::V2(PresentProofV2::ProblemReport(msg))) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::ReportProblem(msg) => matches_opt_thread_id!(msg, thread_id), diff --git a/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs b/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs index 85240c15f7..d120a1186f 100644 --- a/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs +++ b/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs @@ -8,14 +8,14 @@ use chrono::Utc; use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::{ - present_proof::{ - ack::AckPresentation, - present::{Presentation, PresentationContent, PresentationDecorators}, + present_proof::v1::{ + ack::AckPresentationV1, + present::{PresentationV1, PresentationV1Content, PresentationV1Decorators}, propose::{ - PresentationPreview, ProposePresentation, ProposePresentationContent, - ProposePresentationDecorators, + PresentationPreview, ProposePresentationV1, ProposePresentationV1Content, + ProposePresentationV1Decorators, }, - request::RequestPresentation, + request::RequestPresentationV1, }, report_problem::ProblemReport, }, @@ -94,22 +94,22 @@ impl fmt::Display for ProverFullState { fn build_presentation_msg( thread_id: &str, presentation_attachment: String, -) -> VcxResult { +) -> VcxResult { let id = Uuid::new_v4().to_string(); - let content = PresentationContent::builder() + let content = PresentationV1Content::builder() .presentations_attach(vec![make_attach_from_str!( &presentation_attachment, AttachmentId::Presentation.as_ref().to_string() )]) .build(); - let decorators = PresentationDecorators::builder() + let decorators = PresentationV1Decorators::builder() .thread(Thread::builder().thid(thread_id.to_owned()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); - Ok(Presentation::builder() + Ok(PresentationV1::builder() .id(id) .content(content) .decorators(decorators) @@ -131,7 +131,10 @@ impl ProverSM { } } - pub fn from_request(presentation_request: RequestPresentation, source_id: String) -> ProverSM { + pub fn from_request( + presentation_request: RequestPresentationV1, + source_id: String, + ) -> ProverSM { ProverSM { source_id, thread_id: presentation_request.id.clone(), @@ -150,7 +153,8 @@ impl ProverSM { let id = self.thread_id.clone(); let preview = PresentationPreview::new(proposal_data.attributes, proposal_data.predicates); - let content = ProposePresentationContent::builder().presentation_proposal(preview); + let content = + ProposePresentationV1Content::builder().presentation_proposal(preview); let content = if let Some(comment) = proposal_data.comment { content.comment(comment).build() @@ -158,7 +162,7 @@ impl ProverSM { content.build() }; - let proposal = ProposePresentation::builder() + let proposal = ProposePresentationV1::builder() .id(id) .content(content) .build(); @@ -169,18 +173,19 @@ impl ProverSM { let preview = PresentationPreview::new(proposal_data.attributes, proposal_data.predicates); - let content = ProposePresentationContent::builder().presentation_proposal(preview); + 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 = ProposePresentationDecorators::builder() + let decorators = ProposePresentationV1Decorators::builder() .thread(Thread::builder().thid(self.thread_id.clone()).build()) .build(); - let proposal = ProposePresentation::builder() + let proposal = ProposePresentationV1::builder() .id(id) .content(content) .decorators(decorators) @@ -307,7 +312,10 @@ impl ProverSM { } } - pub fn receive_presentation_request(self, request: RequestPresentation) -> VcxResult { + pub fn receive_presentation_request( + self, + request: RequestPresentationV1, + ) -> VcxResult { let prover_sm = match &self.state { ProverFullState::PresentationProposalSent(_) => { let state = ProverFullState::PresentationRequestReceived( @@ -341,7 +349,7 @@ impl ProverSM { Ok(prover_sm) } - pub fn receive_presentation_ack(self, ack: AckPresentation) -> VcxResult { + pub fn receive_presentation_ack(self, ack: AckPresentationV1) -> VcxResult { let state = match self.state { ProverFullState::PresentationSent(state) => { ProverFullState::Finished((state, ack).into()) @@ -404,7 +412,7 @@ impl ProverSM { } } - pub fn get_presentation_request(&self) -> VcxResult<&RequestPresentation> { + pub fn get_presentation_request(&self) -> VcxResult<&RequestPresentationV1> { match self.state { ProverFullState::Initial(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, @@ -434,7 +442,7 @@ impl ProverSM { } } - pub fn get_presentation_msg(&self) -> VcxResult<&Presentation> { + pub fn get_presentation_msg(&self) -> VcxResult<&PresentationV1> { match self.state { ProverFullState::Initial(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, @@ -463,7 +471,7 @@ impl ProverSM { } } - pub fn get_presentation_proposal(&self) -> VcxResult { + pub fn get_presentation_proposal(&self) -> VcxResult { match &self.state { ProverFullState::PresentationProposalSent(state) => Ok(state.proposal.clone()), _ => Err(AriesVcxError::from_msg( diff --git a/aries_vcx/src/protocols/proof_presentation/prover/states/finished.rs b/aries_vcx/src/protocols/proof_presentation/prover/states/finished.rs index 7f549d0d3a..3600d50040 100644 --- a/aries_vcx/src/protocols/proof_presentation/prover/states/finished.rs +++ b/aries_vcx/src/protocols/proof_presentation/prover/states/finished.rs @@ -1,5 +1,5 @@ use messages::msg_fields::protocols::{ - present_proof::{present::Presentation, request::RequestPresentation}, + present_proof::v1::{present::PresentationV1, request::RequestPresentationV1}, report_problem::ProblemReport, }; @@ -7,8 +7,8 @@ use crate::handlers::util::Status; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct FinishedState { - pub presentation_request: Option, - pub presentation: Option, + pub presentation_request: Option, + pub presentation: Option, pub status: Status, } diff --git a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_preparation_failed.rs b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_preparation_failed.rs index 02e291e421..74d81753a1 100644 --- a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_preparation_failed.rs +++ b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_preparation_failed.rs @@ -1,5 +1,5 @@ use messages::msg_fields::protocols::{ - present_proof::request::RequestPresentation, report_problem::ProblemReport, + present_proof::v1::request::RequestPresentationV1, report_problem::ProblemReport, }; use crate::{ @@ -8,7 +8,7 @@ use crate::{ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationPreparationFailedState { - pub presentation_request: RequestPresentation, + pub presentation_request: RequestPresentationV1, pub problem_report: ProblemReport, } diff --git a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_prepared.rs b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_prepared.rs index 65b071d7a6..8f6040f8d0 100644 --- a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_prepared.rs +++ b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_prepared.rs @@ -1,5 +1,5 @@ -use messages::msg_fields::protocols::present_proof::{ - present::Presentation, request::RequestPresentation, +use messages::msg_fields::protocols::present_proof::v1::{ + present::PresentationV1, request::RequestPresentationV1, }; use crate::{ @@ -11,8 +11,8 @@ use crate::{ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationPreparedState { - pub presentation_request: RequestPresentation, - pub presentation: Presentation, + pub presentation_request: RequestPresentationV1, + pub presentation: PresentationV1, } impl From for PresentationSentState { diff --git a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_proposal_sent.rs b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_proposal_sent.rs index b43ced5895..b54d175643 100644 --- a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_proposal_sent.rs +++ b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_proposal_sent.rs @@ -1,11 +1,11 @@ -use messages::msg_fields::protocols::present_proof::propose::{ - PresentationPreview, ProposePresentation, ProposePresentationContent, +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: ProposePresentation, + pub proposal: ProposePresentationV1, } impl Default for PresentationProposalSent { @@ -13,12 +13,12 @@ impl Default for PresentationProposalSent { let id = Uuid::new_v4().to_string(); let preview = PresentationPreview::new(Vec::new(), Vec::new()); - let content = ProposePresentationContent::builder() + let content = ProposePresentationV1Content::builder() .presentation_proposal(preview) .build(); Self { - proposal: ProposePresentation::builder() + proposal: ProposePresentationV1::builder() .id(id) .content(content) .build(), @@ -27,7 +27,7 @@ impl Default for PresentationProposalSent { } impl PresentationProposalSent { - pub fn new(proposal: ProposePresentation) -> Self { + pub fn new(proposal: ProposePresentationV1) -> Self { Self { proposal } } } diff --git a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs index 676d92d7f7..7637ddd546 100644 --- a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs +++ b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs @@ -5,9 +5,9 @@ use aries_vcx_core::{ wallet::base_wallet::BaseWallet, }; use messages::msg_fields::protocols::{ - present_proof::{ - present::Presentation, - request::{RequestPresentation, RequestPresentationContent}, + present_proof::v1::{ + present::PresentationV1, + request::{RequestPresentationV1, RequestPresentationV1Content}, }, report_problem::ProblemReport, }; @@ -29,18 +29,18 @@ use crate::{ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationRequestReceived { - pub presentation_request: RequestPresentation, + pub presentation_request: RequestPresentationV1, } impl Default for PresentationRequestReceived { fn default() -> Self { let id = Uuid::new_v4().to_string(); - let content = RequestPresentationContent::builder() + let content = RequestPresentationV1Content::builder() .request_presentations_attach(Vec::new()) .build(); Self { - presentation_request: RequestPresentation::builder() + presentation_request: RequestPresentationV1::builder() .id(id) .content(content) .build(), @@ -49,7 +49,7 @@ impl Default for PresentationRequestReceived { } impl PresentationRequestReceived { - pub fn new(presentation_request: RequestPresentation) -> Self { + pub fn new(presentation_request: RequestPresentationV1) -> Self { Self { presentation_request, } @@ -94,8 +94,8 @@ impl From<(PresentationRequestReceived, ProblemReport)> for PresentationPreparat } } -impl From<(PresentationRequestReceived, Presentation)> for PresentationPreparedState { - fn from((state, presentation): (PresentationRequestReceived, Presentation)) -> Self { +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, diff --git a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_sent.rs b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_sent.rs index 2b702a17fa..791862b448 100644 --- a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_sent.rs +++ b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_sent.rs @@ -1,5 +1,7 @@ use messages::msg_fields::protocols::{ - present_proof::{ack::AckPresentation, present::Presentation, request::RequestPresentation}, + present_proof::v1::{ + ack::AckPresentationV1, present::PresentationV1, request::RequestPresentationV1, + }, report_problem::ProblemReport, }; @@ -9,12 +11,12 @@ use crate::{ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationSentState { - pub presentation_request: RequestPresentation, - pub presentation: Presentation, + pub presentation_request: RequestPresentationV1, + pub presentation: PresentationV1, } -impl From<(PresentationSentState, AckPresentation)> for FinishedState { - fn from((state, _ack): (PresentationSentState, AckPresentation)) -> Self { +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), diff --git a/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs b/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs index 513cfc4584..1d7427ff79 100644 --- a/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs +++ b/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs @@ -8,15 +8,15 @@ use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::{ notification::ack::{AckContent, AckDecorators, AckStatus}, - present_proof::{ - ack::AckPresentation, - present::Presentation, - problem_report::PresentProofProblemReport, - propose::ProposePresentation, + present_proof::v1::{ + ack::AckPresentationV1, + present::PresentationV1, + problem_report::PresentProofV1ProblemReport, + propose::ProposePresentationV1, request::{ - RequestPresentation, RequestPresentationContent, RequestPresentationDecorators, + RequestPresentationV1, RequestPresentationV1Content, + RequestPresentationV1Decorators, }, - PresentProof, }, report_problem::ProblemReport, }, @@ -88,7 +88,7 @@ impl Default for VerifierFullState { } } -pub fn build_verification_ack(thread_id: &str) -> AckPresentation { +pub fn build_verification_ack(thread_id: &str) -> AckPresentationV1 { let content = AckContent::builder().status(AckStatus::Ok).build(); let decorators = AckDecorators::builder() @@ -96,7 +96,7 @@ pub fn build_verification_ack(thread_id: &str) -> AckPresentation { .timing(Timing::builder().out_time(Utc::now()).build()) .build(); - AckPresentation::builder() + AckPresentationV1::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) @@ -107,10 +107,10 @@ pub fn build_starting_presentation_request( thread_id: &str, request_data: &PresentationRequestData, comment: Option, -) -> VcxResult { +) -> VcxResult { let id = thread_id.to_owned(); - let content = RequestPresentationContent::builder().request_presentations_attach(vec![ + let content = RequestPresentationV1Content::builder().request_presentations_attach(vec![ make_attach_from_str!( &json!(request_data).to_string(), AttachmentId::PresentationRequest.as_ref().to_string() @@ -123,11 +123,11 @@ pub fn build_starting_presentation_request( content.build() }; - let decorators = RequestPresentationDecorators::builder() + let decorators = RequestPresentationV1Decorators::builder() .timing(Timing::builder().out_time(Utc::now()).build()) .build(); - Ok(RequestPresentation::builder() + Ok(RequestPresentationV1::builder() .id(id) .content(content) .decorators(decorators) @@ -157,7 +157,7 @@ impl VerifierSM { sm.set_presentation_request(presentation_request_data, None) } - pub fn from_proposal(source_id: &str, presentation_proposal: &ProposePresentation) -> Self { + pub fn from_proposal(source_id: &str, presentation_proposal: &ProposePresentationV1) -> Self { Self { source_id: source_id.to_string(), thread_id: presentation_proposal.id.clone(), @@ -167,11 +167,8 @@ impl VerifierSM { } } - pub fn receive_presentation_proposal(self, proposal: ProposePresentation) -> VcxResult { - verify_thread_id( - &self.thread_id, - &AriesMessage::PresentProof(PresentProof::ProposePresentation(proposal.clone())), - )?; + pub fn receive_presentation_proposal(self, proposal: ProposePresentationV1) -> VcxResult { + 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 { @@ -257,12 +254,9 @@ impl VerifierSM { self, ledger: &'a impl AnoncredsLedgerRead, anoncreds: &'a impl BaseAnonCreds, - presentation: Presentation, + presentation: PresentationV1, ) -> VcxResult { - verify_thread_id( - &self.thread_id, - &AriesMessage::PresentProof(PresentProof::Presentation(presentation.clone())), - )?; + verify_thread_id(&self.thread_id, &presentation.clone().into())?; let state = match self.state { VerifierFullState::PresentationRequestSent(state) => { let verification_result = state @@ -309,7 +303,7 @@ impl VerifierSM { )), Status::Success => Ok(build_problem_report_msg(None, &self.thread_id).into()), Status::Failed(problem_report) | Status::Declined(problem_report) => { - let problem_report = PresentProofProblemReport::builder() + let problem_report = PresentProofV1ProblemReport::builder() .id(problem_report.id.clone()) .content(problem_report.content.clone().into()) .decorators(problem_report.decorators.clone()) @@ -427,7 +421,7 @@ impl VerifierSM { } } - pub fn presentation_request_msg(&self) -> VcxResult { + pub fn presentation_request_msg(&self) -> VcxResult { match self.state { VerifierFullState::Initial(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, @@ -457,7 +451,7 @@ impl VerifierSM { } } - pub fn get_presentation_msg(&self) -> VcxResult { + pub fn get_presentation_msg(&self) -> VcxResult { match self.state { VerifierFullState::Finished(ref state) => { state.presentation.clone().ok_or(AriesVcxError::from_msg( @@ -472,7 +466,7 @@ impl VerifierSM { } } - pub fn presentation_proposal(&self) -> VcxResult { + pub fn presentation_proposal(&self) -> VcxResult { match self.state { VerifierFullState::PresentationProposalReceived(ref state) => { Ok(state.presentation_proposal.clone()) diff --git a/aries_vcx/src/protocols/proof_presentation/verifier/states/finished.rs b/aries_vcx/src/protocols/proof_presentation/verifier/states/finished.rs index 6d3f23b060..29e696d677 100644 --- a/aries_vcx/src/protocols/proof_presentation/verifier/states/finished.rs +++ b/aries_vcx/src/protocols/proof_presentation/verifier/states/finished.rs @@ -1,5 +1,5 @@ use messages::msg_fields::protocols::{ - present_proof::{present::Presentation, request::RequestPresentation}, + present_proof::v1::{present::PresentationV1, request::RequestPresentationV1}, report_problem::ProblemReport, }; use serde::Deserialize; @@ -11,8 +11,8 @@ use crate::{ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct FinishedState { - pub presentation_request: Option, - pub presentation: Option, + pub presentation_request: Option, + pub presentation: Option, pub status: Status, pub verification_status: PresentationVerificationStatus, } diff --git a/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_proposal_received.rs b/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_proposal_received.rs index 8f6e53efa0..653e000997 100644 --- a/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_proposal_received.rs +++ b/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_proposal_received.rs @@ -1,13 +1,13 @@ -use messages::msg_fields::protocols::present_proof::{ - propose::{PresentationPreview, ProposePresentation, ProposePresentationContent}, - request::RequestPresentation, +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: ProposePresentation, - pub presentation_request: Option, + pub presentation_proposal: ProposePresentationV1, + pub presentation_request: Option, } impl Default for PresentationProposalReceivedState { @@ -15,12 +15,12 @@ impl Default for PresentationProposalReceivedState { let id = Uuid::new_v4().to_string(); let preview = PresentationPreview::new(Vec::new(), Vec::new()); - let content = ProposePresentationContent::builder() + let content = ProposePresentationV1Content::builder() .presentation_proposal(preview) .build(); Self { - presentation_proposal: ProposePresentation::builder() + presentation_proposal: ProposePresentationV1::builder() .id(id) .content(content) .build(), @@ -30,7 +30,7 @@ impl Default for PresentationProposalReceivedState { } impl PresentationProposalReceivedState { - pub fn new(presentation_proposal: ProposePresentation) -> Self { + pub fn new(presentation_proposal: ProposePresentationV1) -> Self { Self { presentation_proposal, ..Self::default() diff --git a/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_sent.rs b/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_sent.rs index 3b18743f14..b348f10514 100644 --- a/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_sent.rs +++ b/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_sent.rs @@ -2,7 +2,7 @@ use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, }; use messages::msg_fields::protocols::{ - present_proof::{present::Presentation, request::RequestPresentation}, + present_proof::v1::{present::PresentationV1, request::RequestPresentationV1}, report_problem::ProblemReport, }; @@ -17,7 +17,7 @@ use crate::{ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationRequestSentState { - pub presentation_request: RequestPresentation, + pub presentation_request: RequestPresentationV1, } impl PresentationRequestSentState { @@ -25,7 +25,7 @@ impl PresentationRequestSentState { &self, ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, - presentation: &Presentation, + presentation: &PresentationV1, thread_id: &str, ) -> VcxResult<()> { if !matches_thread_id!(presentation, thread_id) { @@ -62,14 +62,14 @@ impl PresentationRequestSentState { impl From<( PresentationRequestSentState, - Presentation, + PresentationV1, PresentationVerificationStatus, )> for FinishedState { fn from( (state, presentation, verification_status): ( PresentationRequestSentState, - Presentation, + PresentationV1, PresentationVerificationStatus, ), ) -> Self { diff --git a/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_set.rs b/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_set.rs index 0da4e752ff..25be0a7ff9 100644 --- a/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_set.rs +++ b/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_set.rs @@ -1,5 +1,5 @@ -use messages::msg_fields::protocols::present_proof::request::{ - RequestPresentation, RequestPresentationContent, +use messages::msg_fields::protocols::present_proof::v1::request::{ + RequestPresentationV1, RequestPresentationV1Content, }; use uuid::Uuid; @@ -7,18 +7,18 @@ use crate::protocols::proof_presentation::verifier::states::presentation_request #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationRequestSetState { - pub presentation_request: RequestPresentation, + pub presentation_request: RequestPresentationV1, } impl Default for PresentationRequestSetState { fn default() -> Self { let id = Uuid::new_v4().to_string(); - let content = RequestPresentationContent::builder() + let content = RequestPresentationV1Content::builder() .request_presentations_attach(Vec::new()) .build(); Self { - presentation_request: RequestPresentation::builder() + presentation_request: RequestPresentationV1::builder() .id(id) .content(content) .build(), @@ -27,7 +27,7 @@ impl Default for PresentationRequestSetState { } impl PresentationRequestSetState { - pub fn new(presentation_request: RequestPresentation) -> Self { + pub fn new(presentation_request: RequestPresentationV1) -> Self { Self { presentation_request, } diff --git a/aries_vcx/src/utils/filters.rs b/aries_vcx/src/utils/filters.rs index 293ce6f7d1..a8ce56de88 100644 --- a/aries_vcx/src/utils/filters.rs +++ b/aries_vcx/src/utils/filters.rs @@ -2,7 +2,7 @@ use messages::{ decorators::attachment::Attachment, msg_fields::protocols::{ cred_issuance::v1::offer_credential::OfferCredentialV1, - present_proof::request::RequestPresentation, + present_proof::v1::request::RequestPresentationV1, }, }; use serde_json; @@ -16,9 +16,9 @@ fn __accommodate_macro(attachments: &[Attachment]) -> VcxResult { fn _filter_proof_requests_by_name( requests: &str, match_name: &str, -) -> VcxResult> { - let presentation_requests: Vec = - serde_json::from_str(requests).map_err(|err| { +) -> VcxResult> { + let presentation_requests: Vec = serde_json::from_str(requests) + .map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!( @@ -79,7 +79,7 @@ fn _filter_offers_by_comment( // todo: need not to return Result, can be modified to return String, never error - likely for other // functions in this file as well pub fn filter_proof_requests_by_name(requests: &str, name: &str) -> VcxResult { - let presentation_requests: Vec = + let presentation_requests: Vec = _filter_proof_requests_by_name(requests, name)?; let filtered: String = serde_json::to_string(&presentation_requests).map_err(|err| { AriesVcxError::from_msg( diff --git a/aries_vcx/tests/test_credential_retrieval.rs b/aries_vcx/tests/test_credential_retrieval.rs index baee3904e2..7f85672f39 100644 --- a/aries_vcx/tests/test_credential_retrieval.rs +++ b/aries_vcx/tests/test_credential_retrieval.rs @@ -28,8 +28,8 @@ use base64::{engine::general_purpose, Engine}; use messages::{ decorators::attachment::{Attachment, AttachmentData, AttachmentType}, misc::MimeType, - msg_fields::protocols::present_proof::request::{ - RequestPresentation, RequestPresentationContent, + msg_fields::protocols::present_proof::v1::request::{ + RequestPresentationV1, RequestPresentationV1Content, }, }; @@ -60,13 +60,13 @@ async fn test_agency_pool_retrieve_credentials_empty() { .mime_type(MimeType::Json) .build(); - let content = RequestPresentationContent::builder() + let content = RequestPresentationV1Content::builder() .request_presentations_attach(vec![attach]) .build(); // test retrieving credentials for empty proof request returns "{}" let id = "test_id".to_owned(); - let proof_req = RequestPresentation::builder() + let proof_req = RequestPresentationV1::builder() .id(id) .content(content) .build(); @@ -97,14 +97,14 @@ async fn test_agency_pool_retrieve_credentials_empty() { .mime_type(MimeType::Json) .build(); - let content = RequestPresentationContent::builder() + let content = RequestPresentationV1Content::builder() .request_presentations_attach(vec![attach]) .build(); // test retrieving credentials for the proof request returns the referent with no cred // matches let id = "test_id".to_owned(); - let proof_req = RequestPresentation::builder() + let proof_req = RequestPresentationV1::builder() .id(id) .content(content) .build(); @@ -189,11 +189,11 @@ async fn test_agency_pool_case_for_proof_req_doesnt_matter_for_retrieve_creds() .mime_type(MimeType::Json) .build(); - let content = RequestPresentationContent::builder() + let content = RequestPresentationV1Content::builder() .request_presentations_attach(vec![attach]) .build(); - let proof_req = RequestPresentation::builder() + let proof_req = RequestPresentationV1::builder() .id(id) .content(content) .build(); @@ -227,11 +227,11 @@ async fn test_agency_pool_case_for_proof_req_doesnt_matter_for_retrieve_creds() .mime_type(MimeType::Json) .build(); - let content = RequestPresentationContent::builder() + let content = RequestPresentationV1Content::builder() .request_presentations_attach(vec![attach]) .build(); - let proof_req = RequestPresentation::builder() + let proof_req = RequestPresentationV1::builder() .id(id) .content(content) .build(); @@ -263,11 +263,11 @@ async fn test_agency_pool_case_for_proof_req_doesnt_matter_for_retrieve_creds() .mime_type(MimeType::Json) .build(); - let content = RequestPresentationContent::builder() + let content = RequestPresentationV1Content::builder() .request_presentations_attach(vec![attach]) .build(); - let proof_req = RequestPresentation::builder() + let proof_req = RequestPresentationV1::builder() .id(id) .content(content) .build(); diff --git a/aries_vcx/tests/test_proof_presentation.rs b/aries_vcx/tests/test_proof_presentation.rs index f6426a3cde..6ae62b1d56 100644 --- a/aries_vcx/tests/test_proof_presentation.rs +++ b/aries_vcx/tests/test_proof_presentation.rs @@ -25,7 +25,10 @@ use aries_vcx::{ run_setup, utils::devsetup::*, }; -use messages::{msg_fields::protocols::present_proof::PresentProof, AriesMessage}; +use messages::{ + msg_fields::protocols::present_proof::{v1::PresentProofV1, PresentProof}, + AriesMessage, +}; use crate::utils::{ scenarios::{ @@ -158,7 +161,7 @@ async fn test_agency_pool_generate_proof_with_predicates() { .await .unwrap(); - if let AriesMessage::PresentProof(PresentProof::Ack(_)) = final_message { + if let AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Ack(_))) = final_message { assert_eq!(verifier.get_state(), VerifierState::Finished); assert_eq!( verifier.get_verification_status(), diff --git a/aries_vcx/tests/utils/scenarios/data.rs b/aries_vcx/tests/utils/scenarios/data.rs index 4dbd7a049c..d6d062d013 100644 --- a/aries_vcx/tests/utils/scenarios/data.rs +++ b/aries_vcx/tests/utils/scenarios/data.rs @@ -8,7 +8,7 @@ use messages::{ CredentialPreviewV1, }, }, - present_proof::propose::PresentationAttr, + present_proof::v1::propose::PresentationAttr, }, }; use serde_json::{json, Value}; diff --git a/aries_vcx/tests/utils/scenarios/proof_presentation.rs b/aries_vcx/tests/utils/scenarios/proof_presentation.rs index c1635a3def..f56d9ae625 100644 --- a/aries_vcx/tests/utils/scenarios/proof_presentation.rs +++ b/aries_vcx/tests/utils/scenarios/proof_presentation.rs @@ -35,8 +35,11 @@ use aries_vcx_core::{ use messages::{ msg_fields::protocols::{ present_proof::{ - ack::AckPresentation, present::Presentation, propose::ProposePresentation, - request::RequestPresentation, PresentProof, + v1::{ + ack::AckPresentationV1, present::PresentationV1, propose::ProposePresentationV1, + request::RequestPresentationV1, PresentProofV1, + }, + PresentProof, }, report_problem::ProblemReport, }, @@ -47,7 +50,10 @@ use serde_json::Value; use super::requested_attrs_address; use crate::utils::{scenarios::requested_attr_objects, test_agent::TestAgent}; -pub async fn create_proof_proposal(prover: &mut Prover, cred_def_id: &str) -> ProposePresentation { +pub async fn create_proof_proposal( + prover: &mut Prover, + cred_def_id: &str, +) -> ProposePresentationV1 { let attrs = requested_attr_objects(cred_def_id); let mut proposal_data = PresentationProposalData::default(); for attr in attrs.into_iter() { @@ -69,8 +75,8 @@ pub async fn accept_proof_proposal( impl BaseWallet, >, verifier: &mut Verifier, - presentation_proposal: ProposePresentation, -) -> RequestPresentation { + presentation_proposal: ProposePresentationV1, +) -> RequestPresentationV1 { verifier .process_aries_msg( &faber.ledger_read, @@ -104,7 +110,7 @@ pub async fn accept_proof_proposal( verifier.mark_presentation_request_sent().unwrap() } -pub async fn reject_proof_proposal(presentation_proposal: &ProposePresentation) -> ProblemReport { +pub async fn reject_proof_proposal(presentation_proposal: &ProposePresentationV1) -> ProblemReport { let mut verifier = Verifier::create_from_proposal("1", presentation_proposal).unwrap(); assert_eq!( verifier.get_state(), @@ -147,7 +153,7 @@ pub async fn create_proof_request_data( .unwrap() } -pub async fn create_prover_from_request(presentation_request: RequestPresentation) -> Prover { +pub async fn create_prover_from_request(presentation_request: RequestPresentationV1) -> Prover { Prover::create_from_request(DEFAULT_PROOF_NAME, presentation_request).unwrap() } @@ -169,7 +175,7 @@ pub async fn generate_and_send_proof( >, prover: &mut Prover, selected_credentials: SelectedCredentials, -) -> Option { +) -> Option { let thread_id = prover.get_thread_id().unwrap(); info!( "generate_and_send_proof >>> generating proof using selected credentials {:?}", @@ -192,7 +198,9 @@ pub async fn generate_and_send_proof( info!("generate_and_send_proof :: proof sent"); assert_eq!(thread_id, prover.get_thread_id().unwrap()); let message = match message { - AriesMessage::PresentProof(PresentProof::Presentation(presentation)) => presentation, + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Presentation( + presentation, + ))) => presentation, _ => panic!("Unexpected message type"), }; Some(message) @@ -209,14 +217,14 @@ pub async fn verify_proof( impl BaseWallet, >, verifier: &mut Verifier, - presentation: Presentation, -) -> AckPresentation { + presentation: PresentationV1, +) -> AckPresentationV1 { let msg = verifier .verify_presentation(&faber.ledger_read, &faber.anoncreds, presentation) .await .unwrap(); let msg = match msg { - AriesMessage::PresentProof(PresentProof::Ack(ack)) => ack, + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::Ack(ack))) => ack, _ => panic!("Unexpected message type"), }; // TODO: Perhaps we should leave verification on the caller @@ -366,7 +374,7 @@ pub async fn prover_select_credentials( impl BaseAnonCreds, impl BaseWallet, >, - presentation_request: RequestPresentation, + presentation_request: RequestPresentationV1, preselected_credentials: Option<&str>, ) -> SelectedCredentials { prover @@ -401,9 +409,9 @@ pub async fn prover_select_credentials_and_send_proof( impl BaseAnonCreds, impl BaseWallet, >, - presentation_request: RequestPresentation, + presentation_request: RequestPresentationV1, preselected_credentials: Option<&str>, -) -> Presentation { +) -> PresentationV1 { let mut prover = create_prover_from_request(presentation_request.clone()).await; let selected_credentials = prover_select_credentials( &mut prover, diff --git a/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs b/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs index 3b1e68a725..349e54ae79 100644 --- a/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs +++ b/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs @@ -3,7 +3,10 @@ use aries_vcx::{ mediated_prover::prover_find_message_to_handle, prover::Prover, }, messages::{ - msg_fields::protocols::present_proof::{request::RequestPresentation, PresentProof}, + msg_fields::protocols::present_proof::{ + v1::{request::RequestPresentationV1, PresentProofV1}, + PresentProof, + }, AriesMessage, }, }; @@ -37,7 +40,7 @@ pub fn create_with_proof_request(source_id: &str, proof_req: &str) -> LibvcxResu proof_req ); - let presentation_request: RequestPresentation = + let presentation_request: RequestPresentationV1 = serde_json::from_str(proof_req).map_err(|err| { LibvcxError::from_msg( LibvcxErrorKind::InvalidJson, @@ -60,8 +63,8 @@ pub async fn create_with_msgid( ) -> LibvcxResult<(u32, String)> { let proof_request = get_proof_request(connection_handle, msg_id).await?; - let presentation_request: RequestPresentation = - serde_json::from_str(&proof_request).map_err(|err| { + let presentation_request: RequestPresentationV1 = serde_json::from_str(&proof_request) + .map_err(|err| { LibvcxError::from_msg( LibvcxErrorKind::InvalidJson, format!( @@ -285,9 +288,9 @@ async fn get_proof_request(connection_handle: u32, msg_id: &str) -> LibvcxResult let message = mediated_connection::get_message_by_id(connection_handle, msg_id).await?; match message { - AriesMessage::PresentProof(PresentProof::RequestPresentation(presentation_request)) => { - presentation_request - } + AriesMessage::PresentProof(PresentProof::V1(PresentProofV1::RequestPresentation( + presentation_request, + ))) => presentation_request, msg => { return Err(LibvcxError::from_msg( LibvcxErrorKind::InvalidMessages, @@ -315,7 +318,9 @@ pub async fn get_proof_request_messages(connection_handle: u32) -> LibvcxResult< .await? .into_iter() .filter_map(|(_, message)| match message { - AriesMessage::PresentProof(PresentProof::RequestPresentation(_)) => Some(message), + AriesMessage::PresentProof(PresentProof::V1( + PresentProofV1::RequestPresentation(_), + )) => Some(message), _ => None, }) .collect(); diff --git a/messages/src/lib.rs b/messages/src/lib.rs index eb4f80e93e..46ea11b5f9 100644 --- a/messages/src/lib.rs +++ b/messages/src/lib.rs @@ -18,10 +18,11 @@ use misc::utils; use msg_fields::protocols::{ cred_issuance::{v1::CredentialIssuanceV1, v2::CredentialIssuanceV2, CredentialIssuance}, pickup::Pickup, + present_proof::{v2::PresentProofV2, PresentProof}, }; use msg_types::{ - cred_issuance::CredentialIssuanceType, report_problem::ReportProblemTypeV1_0, - routing::RoutingTypeV1_0, MsgWithType, + cred_issuance::CredentialIssuanceType, present_proof::PresentProofType, + report_problem::ReportProblemTypeV1_0, routing::RoutingTypeV1_0, MsgWithType, }; use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; @@ -30,8 +31,9 @@ use crate::{ protocols::{ basic_message::BasicMessage, connection::Connection, discover_features::DiscoverFeatures, notification::Notification, - out_of_band::OutOfBand, present_proof::PresentProof, report_problem::ProblemReport, - revocation::Revocation, routing::Forward, trust_ping::TrustPing, + out_of_band::OutOfBand, present_proof::v1::PresentProofV1, + report_problem::ProblemReport, revocation::Revocation, routing::Forward, + trust_ping::TrustPing, }, traits::DelayedSerde, }, @@ -135,9 +137,19 @@ impl DelayedSerde for AriesMessage { } } } - Protocol::PresentProofType(msg_type) => { - PresentProof::delayed_deserialize((msg_type, kind_str), deserializer) - .map(From::from) + Protocol::PresentProofType(PresentProofType::V1(msg_type)) => { + PresentProofV1::delayed_deserialize( + (PresentProofType::V1(msg_type), kind_str), + deserializer, + ) + .map(|x| AriesMessage::from(PresentProof::V1(x))) + } + Protocol::PresentProofType(PresentProofType::V2(msg_type)) => { + PresentProofV2::delayed_deserialize( + (PresentProofType::V2(msg_type), kind_str), + deserializer, + ) + .map(|x| AriesMessage::from(PresentProof::V2(x))) } Protocol::TrustPingType(msg_type) => { TrustPing::delayed_deserialize((msg_type, kind_str), deserializer).map(From::from) @@ -183,7 +195,8 @@ impl DelayedSerde for AriesMessage { Self::CredentialIssuance(CredentialIssuance::V1(v)) => v.delayed_serialize(serializer), Self::CredentialIssuance(CredentialIssuance::V2(v)) => v.delayed_serialize(serializer), Self::ReportProblem(v) => MsgWithType::from(v).serialize(serializer), - Self::PresentProof(v) => v.delayed_serialize(serializer), + Self::PresentProof(PresentProof::V1(v)) => v.delayed_serialize(serializer), + Self::PresentProof(PresentProof::V2(v)) => v.delayed_serialize(serializer), Self::TrustPing(v) => v.delayed_serialize(serializer), Self::DiscoverFeatures(v) => v.delayed_serialize(serializer), Self::BasicMessage(v) => MsgWithType::from(v).serialize(serializer), diff --git a/messages/src/msg_fields/protocols/common/attachment_format_specifier.rs b/messages/src/msg_fields/protocols/common/attachment_format_specifier.rs new file mode 100644 index 0000000000..1bf91efc5d --- /dev/null +++ b/messages/src/msg_fields/protocols/common/attachment_format_specifier.rs @@ -0,0 +1,23 @@ +use serde::{Deserialize, Serialize}; +use shared_vcx::maybe_known::MaybeKnown; +use typed_builder::TypedBuilder; + +/// Specifies that a particular Attachment, with the id of `attach_id`, has the format of `format`. +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, TypedBuilder)] +#[serde(rename_all = "snake_case")] +pub struct AttachmentFormatSpecifier { + pub attach_id: String, + pub format: MaybeKnown, +} + +/// If `attach_id` is not [None], this specifies that a particular Attachment, with the id of +/// `attach_id`, has the format of `format`. If `attach_id` is [None], this structure is used to +/// indicate that a particular attachment `format` is supported by the sender of the message. +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, TypedBuilder)] +#[serde(rename_all = "snake_case")] +pub struct OptionalIdAttachmentFormatSpecifier { + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub attach_id: Option, + pub format: MaybeKnown, +} diff --git a/messages/src/msg_fields/protocols/common/mod.rs b/messages/src/msg_fields/protocols/common/mod.rs new file mode 100644 index 0000000000..72073c81b1 --- /dev/null +++ b/messages/src/msg_fields/protocols/common/mod.rs @@ -0,0 +1 @@ +pub mod attachment_format_specifier; diff --git a/messages/src/msg_fields/protocols/cred_issuance/v2/issue_credential.rs b/messages/src/msg_fields/protocols/cred_issuance/v2/issue_credential.rs index 19adc8b769..228e07b7c6 100644 --- a/messages/src/msg_fields/protocols/cred_issuance/v2/issue_credential.rs +++ b/messages/src/msg_fields/protocols/cred_issuance/v2/issue_credential.rs @@ -1,9 +1,9 @@ use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; -use super::AttachmentFormatSpecifier; use crate::{ decorators::{attachment::Attachment, please_ack::PleaseAck, thread::Thread, timing::Timing}, + msg_fields::protocols::common::attachment_format_specifier::AttachmentFormatSpecifier, msg_parts::MsgParts, }; diff --git a/messages/src/msg_fields/protocols/cred_issuance/v2/mod.rs b/messages/src/msg_fields/protocols/cred_issuance/v2/mod.rs index 8f9d100c62..3fd932f4e9 100644 --- a/messages/src/msg_fields/protocols/cred_issuance/v2/mod.rs +++ b/messages/src/msg_fields/protocols/cred_issuance/v2/mod.rs @@ -11,8 +11,7 @@ use std::str::FromStr; use derive_more::From; use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; -use shared_vcx::{maybe_known::MaybeKnown, misc::utils::CowStr}; -use typed_builder::TypedBuilder; +use shared_vcx::misc::utils::CowStr; use self::{ ack::{AckCredentialV2, AckCredentialV2Content}, @@ -175,13 +174,6 @@ impl Serialize for CredentialPreviewV2MsgType { } } -#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, TypedBuilder)] -#[serde(rename_all = "snake_case")] -pub struct AttachmentFormatSpecifier { - attach_id: String, - format: MaybeKnown, -} - transit_to_aries_msg!( OfferCredentialV2Content: OfferCredentialV2Decorators, CredentialIssuanceV2, CredentialIssuance diff --git a/messages/src/msg_fields/protocols/cred_issuance/v2/offer_credential.rs b/messages/src/msg_fields/protocols/cred_issuance/v2/offer_credential.rs index 495ff6f1e4..f5bb521c43 100644 --- a/messages/src/msg_fields/protocols/cred_issuance/v2/offer_credential.rs +++ b/messages/src/msg_fields/protocols/cred_issuance/v2/offer_credential.rs @@ -1,9 +1,10 @@ use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; -use super::{AttachmentFormatSpecifier, CredentialPreviewV2}; +use super::CredentialPreviewV2; use crate::{ decorators::{attachment::Attachment, thread::Thread, timing::Timing}, + msg_fields::protocols::common::attachment_format_specifier::AttachmentFormatSpecifier, msg_parts::MsgParts, }; diff --git a/messages/src/msg_fields/protocols/cred_issuance/v2/propose_credential.rs b/messages/src/msg_fields/protocols/cred_issuance/v2/propose_credential.rs index 1350cea084..54864668e0 100644 --- a/messages/src/msg_fields/protocols/cred_issuance/v2/propose_credential.rs +++ b/messages/src/msg_fields/protocols/cred_issuance/v2/propose_credential.rs @@ -1,9 +1,10 @@ use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; -use super::{AttachmentFormatSpecifier, CredentialPreviewV2}; +use super::CredentialPreviewV2; use crate::{ decorators::{attachment::Attachment, thread::Thread, timing::Timing}, + msg_fields::protocols::common::attachment_format_specifier::AttachmentFormatSpecifier, msg_parts::MsgParts, }; diff --git a/messages/src/msg_fields/protocols/cred_issuance/v2/request_credential.rs b/messages/src/msg_fields/protocols/cred_issuance/v2/request_credential.rs index e916f3be67..d4d590129c 100644 --- a/messages/src/msg_fields/protocols/cred_issuance/v2/request_credential.rs +++ b/messages/src/msg_fields/protocols/cred_issuance/v2/request_credential.rs @@ -1,9 +1,9 @@ use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; -use super::AttachmentFormatSpecifier; use crate::{ decorators::{attachment::Attachment, thread::Thread, timing::Timing}, + msg_fields::protocols::common::attachment_format_specifier::AttachmentFormatSpecifier, msg_parts::MsgParts, }; diff --git a/messages/src/msg_fields/protocols/mod.rs b/messages/src/msg_fields/protocols/mod.rs index bae4e6a82c..ae5b4a78ad 100644 --- a/messages/src/msg_fields/protocols/mod.rs +++ b/messages/src/msg_fields/protocols/mod.rs @@ -1,4 +1,5 @@ pub mod basic_message; +pub mod common; pub mod connection; pub mod cred_issuance; pub mod discover_features; diff --git a/messages/src/msg_fields/protocols/present_proof/mod.rs b/messages/src/msg_fields/protocols/present_proof/mod.rs index e03dc143e7..00d8c8b0e8 100644 --- a/messages/src/msg_fields/protocols/present_proof/mod.rs +++ b/messages/src/msg_fields/protocols/present_proof/mod.rs @@ -1,119 +1,12 @@ -//! Module containing the `present proof` protocol messages, as defined in the [RFC](). - -pub mod ack; -pub mod present; -pub mod problem_report; -pub mod propose; -pub mod request; - use derive_more::From; -use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; -use self::{ - ack::{AckPresentation, AckPresentationContent}, - present::{Presentation, PresentationContent, PresentationDecorators}, - problem_report::{PresentProofProblemReport, PresentProofProblemReportContent}, - propose::{ProposePresentation, ProposePresentationContent, ProposePresentationDecorators}, - request::{RequestPresentation, RequestPresentationContent, RequestPresentationDecorators}, -}; -use super::{notification::ack::AckDecorators, report_problem::ProblemReportDecorators}; -use crate::{ - misc::utils::{self, into_msg_with_type, transit_to_aries_msg}, - msg_fields::traits::DelayedSerde, - msg_types::{ - protocols::present_proof::{PresentProofType, PresentProofTypeV1, PresentProofTypeV1_0}, - MsgWithType, - }, -}; +use self::{v1::PresentProofV1, v2::PresentProofV2}; + +pub mod v1; +pub mod v2; #[derive(Clone, Debug, From, PartialEq)] pub enum PresentProof { - ProposePresentation(ProposePresentation), - RequestPresentation(RequestPresentation), - Presentation(Presentation), - Ack(AckPresentation), - ProblemReport(PresentProofProblemReport), + V1(PresentProofV1), + V2(PresentProofV2), } - -impl DelayedSerde for PresentProof { - type MsgType<'a> = (PresentProofType, &'a str); - - fn delayed_deserialize<'de, D>( - msg_type: Self::MsgType<'de>, - deserializer: D, - ) -> Result - where - D: Deserializer<'de>, - { - let (protocol, kind_str) = msg_type; - - let kind = match protocol { - PresentProofType::V1(PresentProofTypeV1::V1_0(kind)) => kind.kind_from_str(kind_str), - }; - - match kind.map_err(D::Error::custom)? { - PresentProofTypeV1_0::ProposePresentation => { - ProposePresentation::deserialize(deserializer).map(From::from) - } - PresentProofTypeV1_0::RequestPresentation => { - RequestPresentation::deserialize(deserializer).map(From::from) - } - PresentProofTypeV1_0::Presentation => { - Presentation::deserialize(deserializer).map(From::from) - } - PresentProofTypeV1_0::Ack => AckPresentation::deserialize(deserializer).map(From::from), - PresentProofTypeV1_0::ProblemReport => { - PresentProofProblemReport::deserialize(deserializer).map(From::from) - } - PresentProofTypeV1_0::PresentationPreview => { - Err(utils::not_standalone_msg::(kind_str)) - } - } - } - - fn delayed_serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - match self { - Self::ProposePresentation(v) => MsgWithType::from(v).serialize(serializer), - Self::RequestPresentation(v) => MsgWithType::from(v).serialize(serializer), - Self::Presentation(v) => MsgWithType::from(v).serialize(serializer), - Self::Ack(v) => MsgWithType::from(v).serialize(serializer), - Self::ProblemReport(v) => MsgWithType::from(v).serialize(serializer), - } - } -} - -transit_to_aries_msg!( - ProposePresentationContent: ProposePresentationDecorators, - PresentProof -); -transit_to_aries_msg!( - RequestPresentationContent: RequestPresentationDecorators, - PresentProof -); -transit_to_aries_msg!(PresentationContent: PresentationDecorators, PresentProof); -transit_to_aries_msg!(AckPresentationContent: AckDecorators, PresentProof); -transit_to_aries_msg!( - PresentProofProblemReportContent: ProblemReportDecorators, - PresentProof -); - -into_msg_with_type!( - ProposePresentation, - PresentProofTypeV1_0, - ProposePresentation -); -into_msg_with_type!( - RequestPresentation, - PresentProofTypeV1_0, - RequestPresentation -); -into_msg_with_type!(Presentation, PresentProofTypeV1_0, Presentation); -into_msg_with_type!(AckPresentation, PresentProofTypeV1_0, Ack); -into_msg_with_type!( - PresentProofProblemReport, - PresentProofTypeV1_0, - ProblemReport -); diff --git a/messages/src/msg_fields/protocols/present_proof/ack.rs b/messages/src/msg_fields/protocols/present_proof/v1/ack.rs similarity index 79% rename from messages/src/msg_fields/protocols/present_proof/ack.rs rename to messages/src/msg_fields/protocols/present_proof/v1/ack.rs index cd2cd5679c..6ac5cd3e82 100644 --- a/messages/src/msg_fields/protocols/present_proof/ack.rs +++ b/messages/src/msg_fields/protocols/present_proof/v1/ack.rs @@ -6,22 +6,22 @@ use crate::{ msg_parts::MsgParts, }; -pub type AckPresentation = MsgParts; +pub type AckPresentationV1 = MsgParts; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] #[serde(transparent)] -pub struct AckPresentationContent { +pub struct AckPresentationV1Content { pub inner: AckContent, } -impl From for AckPresentationContent { +impl From for AckPresentationV1Content { fn from(value: AckContent) -> Self { Self { inner: value } } } -impl From for Ack { - fn from(value: AckPresentation) -> Self { +impl From for Ack { + fn from(value: AckPresentationV1) -> Self { Self::builder() .id(value.id) .content(value.content.inner) @@ -46,7 +46,7 @@ mod tests { #[test] fn test_minimal_ack_proof() { - let content: AckPresentationContent = AckContent::builder().status(AckStatus::Ok).build(); + let content: AckPresentationV1Content = AckContent::builder().status(AckStatus::Ok).build(); let decorators = AckDecorators::builder() .thread(make_extended_thread()) @@ -62,7 +62,7 @@ mod tests { #[test] fn test_extended_ack_proof() { - let content: AckPresentationContent = AckContent::builder().status(AckStatus::Ok).build(); + let content: AckPresentationV1Content = AckContent::builder().status(AckStatus::Ok).build(); let decorators = AckDecorators::builder() .thread(make_extended_thread()) diff --git a/messages/src/msg_fields/protocols/present_proof/v1/mod.rs b/messages/src/msg_fields/protocols/present_proof/v1/mod.rs new file mode 100644 index 0000000000..2fb836a3b0 --- /dev/null +++ b/messages/src/msg_fields/protocols/present_proof/v1/mod.rs @@ -0,0 +1,133 @@ +//! Module containing the `present proof` protocol messages, as defined in the [RFC](). + +pub mod ack; +pub mod present; +pub mod problem_report; +pub mod propose; +pub mod request; + +use derive_more::From; +use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; + +use self::{ + ack::{AckPresentationV1, AckPresentationV1Content}, + present::{PresentationV1, PresentationV1Content, PresentationV1Decorators}, + problem_report::{PresentProofV1ProblemReport, PresentProofV1ProblemReportContent}, + propose::{ + ProposePresentationV1, ProposePresentationV1Content, ProposePresentationV1Decorators, + }, + request::{ + RequestPresentationV1, RequestPresentationV1Content, RequestPresentationV1Decorators, + }, +}; +use super::PresentProof; +use crate::{ + misc::utils::{self, into_msg_with_type, transit_to_aries_msg}, + msg_fields::{ + protocols::{notification::ack::AckDecorators, report_problem::ProblemReportDecorators}, + traits::DelayedSerde, + }, + msg_types::{ + protocols::present_proof::{PresentProofType, PresentProofTypeV1, PresentProofTypeV1_0}, + MsgWithType, + }, +}; + +#[derive(Clone, Debug, From, PartialEq)] +pub enum PresentProofV1 { + ProposePresentation(ProposePresentationV1), + RequestPresentation(RequestPresentationV1), + Presentation(PresentationV1), + Ack(AckPresentationV1), + ProblemReport(PresentProofV1ProblemReport), +} + +impl DelayedSerde for PresentProofV1 { + type MsgType<'a> = (PresentProofType, &'a str); + + fn delayed_deserialize<'de, D>( + msg_type: Self::MsgType<'de>, + deserializer: D, + ) -> Result + where + D: Deserializer<'de>, + { + let (protocol, kind_str) = msg_type; + + let kind = match protocol { + PresentProofType::V1(PresentProofTypeV1::V1_0(kind)) => kind.kind_from_str(kind_str), + PresentProofType::V2(_) => { + return Err(D::Error::custom( + "Cannot deserialize present-proof-v2 message type into present-proof-v1", + )) + } + }; + + match kind.map_err(D::Error::custom)? { + PresentProofTypeV1_0::ProposePresentation => { + ProposePresentationV1::deserialize(deserializer).map(From::from) + } + PresentProofTypeV1_0::RequestPresentation => { + RequestPresentationV1::deserialize(deserializer).map(From::from) + } + PresentProofTypeV1_0::Presentation => { + PresentationV1::deserialize(deserializer).map(From::from) + } + PresentProofTypeV1_0::Ack => { + AckPresentationV1::deserialize(deserializer).map(From::from) + } + PresentProofTypeV1_0::ProblemReport => { + PresentProofV1ProblemReport::deserialize(deserializer).map(From::from) + } + PresentProofTypeV1_0::PresentationPreview => { + Err(utils::not_standalone_msg::(kind_str)) + } + } + } + + fn delayed_serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self { + Self::ProposePresentation(v) => MsgWithType::from(v).serialize(serializer), + Self::RequestPresentation(v) => MsgWithType::from(v).serialize(serializer), + Self::Presentation(v) => MsgWithType::from(v).serialize(serializer), + Self::Ack(v) => MsgWithType::from(v).serialize(serializer), + Self::ProblemReport(v) => MsgWithType::from(v).serialize(serializer), + } + } +} + +transit_to_aries_msg!( + ProposePresentationV1Content: ProposePresentationV1Decorators, + PresentProofV1, PresentProof +); +transit_to_aries_msg!( + RequestPresentationV1Content: RequestPresentationV1Decorators, + PresentProofV1, PresentProof +); +transit_to_aries_msg!(PresentationV1Content: PresentationV1Decorators, PresentProofV1, PresentProof); +transit_to_aries_msg!(AckPresentationV1Content: AckDecorators, PresentProofV1, PresentProof); +transit_to_aries_msg!( + PresentProofV1ProblemReportContent: ProblemReportDecorators, + PresentProofV1, PresentProof +); + +into_msg_with_type!( + ProposePresentationV1, + PresentProofTypeV1_0, + ProposePresentation +); +into_msg_with_type!( + RequestPresentationV1, + PresentProofTypeV1_0, + RequestPresentation +); +into_msg_with_type!(PresentationV1, PresentProofTypeV1_0, Presentation); +into_msg_with_type!(AckPresentationV1, PresentProofTypeV1_0, Ack); +into_msg_with_type!( + PresentProofV1ProblemReport, + PresentProofTypeV1_0, + ProblemReport +); diff --git a/messages/src/msg_fields/protocols/present_proof/present.rs b/messages/src/msg_fields/protocols/present_proof/v1/present.rs similarity index 87% rename from messages/src/msg_fields/protocols/present_proof/present.rs rename to messages/src/msg_fields/protocols/present_proof/v1/present.rs index d714ca2cdf..a812d3728e 100644 --- a/messages/src/msg_fields/protocols/present_proof/present.rs +++ b/messages/src/msg_fields/protocols/present_proof/v1/present.rs @@ -6,10 +6,10 @@ use crate::{ msg_parts::MsgParts, }; -pub type Presentation = MsgParts; +pub type PresentationV1 = MsgParts; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] -pub struct PresentationContent { +pub struct PresentationV1Content { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub comment: Option, @@ -18,7 +18,7 @@ pub struct PresentationContent { } #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] -pub struct PresentationDecorators { +pub struct PresentationV1Decorators { #[serde(rename = "~thread")] pub thread: Thread, #[builder(default, setter(strip_option))] @@ -50,11 +50,11 @@ mod tests { #[test] fn test_minimal_present_proof() { - let content = PresentationContent::builder() + let content = PresentationV1Content::builder() .presentations_attach(vec![make_extended_attachment()]) .build(); - let decorators = PresentationDecorators::builder() + let decorators = PresentationV1Decorators::builder() .thread(make_extended_thread()) .build(); @@ -73,12 +73,12 @@ mod tests { #[test] fn test_extended_present_proof() { - let content = PresentationContent::builder() + let content = PresentationV1Content::builder() .presentations_attach(vec![make_extended_attachment()]) .comment("test_comment".to_owned()) .build(); - let decorators = PresentationDecorators::builder() + let decorators = PresentationV1Decorators::builder() .thread(make_extended_thread()) .timing(make_extended_timing()) .please_ack(make_minimal_please_ack()) diff --git a/messages/src/msg_fields/protocols/present_proof/problem_report.rs b/messages/src/msg_fields/protocols/present_proof/v1/problem_report.rs similarity index 89% rename from messages/src/msg_fields/protocols/present_proof/problem_report.rs rename to messages/src/msg_fields/protocols/present_proof/v1/problem_report.rs index 0c03437c42..69bb7c14a8 100644 --- a/messages/src/msg_fields/protocols/present_proof/problem_report.rs +++ b/messages/src/msg_fields/protocols/present_proof/v1/problem_report.rs @@ -8,23 +8,23 @@ use crate::{ msg_parts::MsgParts, }; -pub type PresentProofProblemReport = - MsgParts; +pub type PresentProofV1ProblemReport = + MsgParts; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] #[serde(transparent)] -pub struct PresentProofProblemReportContent { +pub struct PresentProofV1ProblemReportContent { pub inner: ProblemReportContent, } -impl From for PresentProofProblemReportContent { +impl From for PresentProofV1ProblemReportContent { fn from(value: ProblemReportContent) -> Self { Self { inner: value } } } -impl From for ProblemReport { - fn from(value: PresentProofProblemReport) -> Self { +impl From for ProblemReport { + fn from(value: PresentProofV1ProblemReport) -> Self { Self::builder() .id(value.id) .content(value.content.inner) @@ -68,7 +68,7 @@ mod tests { "description": content.description }); - let content = PresentProofProblemReportContent::builder() + let content = PresentProofV1ProblemReportContent::builder() .inner(content) .build(); @@ -123,7 +123,7 @@ mod tests { "fix-hint~l10n": decorators.fix_hint_locale }); - let content = PresentProofProblemReportContent::builder() + let content = PresentProofV1ProblemReportContent::builder() .inner(content) .build(); diff --git a/messages/src/msg_fields/protocols/present_proof/propose.rs b/messages/src/msg_fields/protocols/present_proof/v1/propose.rs similarity index 93% rename from messages/src/msg_fields/protocols/present_proof/propose.rs rename to messages/src/msg_fields/protocols/present_proof/v1/propose.rs index 8234fb9060..bd8eeb8253 100644 --- a/messages/src/msg_fields/protocols/present_proof/propose.rs +++ b/messages/src/msg_fields/protocols/present_proof/v1/propose.rs @@ -15,10 +15,11 @@ use crate::{ }, }; -pub type ProposePresentation = MsgParts; +pub type ProposePresentationV1 = + MsgParts; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] -pub struct ProposePresentationContent { +pub struct ProposePresentationV1Content { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub comment: Option, @@ -26,7 +27,7 @@ pub struct ProposePresentationContent { } #[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] -pub struct ProposePresentationDecorators { +pub struct ProposePresentationV1Decorators { #[builder(default, setter(strip_option))] #[serde(rename = "~thread")] #[serde(skip_serializing_if = "Option::is_none")] @@ -176,11 +177,11 @@ mod tests { .threshold(1000) .build(); let preview = PresentationPreview::new(vec![attribute], vec![predicate]); - let content = ProposePresentationContent::builder() + let content = ProposePresentationV1Content::builder() .presentation_proposal(preview) .build(); - let decorators = ProposePresentationDecorators::default(); + let decorators = ProposePresentationV1Decorators::default(); let expected = json!({ "presentation_proposal": content.presentation_proposal @@ -205,12 +206,12 @@ mod tests { .threshold(1000) .build(); let preview = PresentationPreview::new(vec![attribute], vec![predicate]); - let content = ProposePresentationContent::builder() + let content = ProposePresentationV1Content::builder() .presentation_proposal(preview) .comment("test_comment".to_owned()) .build(); - let decorators = ProposePresentationDecorators::builder() + let decorators = ProposePresentationV1Decorators::builder() .thread(make_extended_thread()) .timing(make_extended_timing()) .build(); diff --git a/messages/src/msg_fields/protocols/present_proof/request.rs b/messages/src/msg_fields/protocols/present_proof/v1/request.rs similarity index 84% rename from messages/src/msg_fields/protocols/present_proof/request.rs rename to messages/src/msg_fields/protocols/present_proof/v1/request.rs index ea0eb0bd11..72b7a8ed50 100644 --- a/messages/src/msg_fields/protocols/present_proof/request.rs +++ b/messages/src/msg_fields/protocols/present_proof/v1/request.rs @@ -6,10 +6,11 @@ use crate::{ msg_parts::MsgParts, }; -pub type RequestPresentation = MsgParts; +pub type RequestPresentationV1 = + MsgParts; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] -pub struct RequestPresentationContent { +pub struct RequestPresentationV1Content { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub comment: Option, @@ -18,7 +19,7 @@ pub struct RequestPresentationContent { } #[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] -pub struct RequestPresentationDecorators { +pub struct RequestPresentationV1Decorators { #[builder(default, setter(strip_option))] #[serde(rename = "~thread")] #[serde(skip_serializing_if = "Option::is_none")] @@ -47,11 +48,11 @@ mod tests { #[test] fn test_minimal_request_proof() { - let content = RequestPresentationContent::builder() + let content = RequestPresentationV1Content::builder() .request_presentations_attach(vec![make_extended_attachment()]) .build(); - let decorators = RequestPresentationDecorators::default(); + let decorators = RequestPresentationV1Decorators::default(); let expected = json!({ "request_presentations~attach": content.request_presentations_attach, @@ -67,12 +68,12 @@ mod tests { #[test] fn test_extended_request_proof() { - let content = RequestPresentationContent::builder() + let content = RequestPresentationV1Content::builder() .request_presentations_attach(vec![make_extended_attachment()]) .comment("test_comment".to_owned()) .build(); - let decorators = RequestPresentationDecorators::builder() + let decorators = RequestPresentationV1Decorators::builder() .thread(make_extended_thread()) .timing(make_extended_timing()) .build(); diff --git a/messages/src/msg_fields/protocols/present_proof/v2/ack.rs b/messages/src/msg_fields/protocols/present_proof/v2/ack.rs new file mode 100644 index 0000000000..c018cf7ebc --- /dev/null +++ b/messages/src/msg_fields/protocols/present_proof/v2/ack.rs @@ -0,0 +1,80 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + msg_fields::protocols::notification::ack::{Ack, AckContent, AckDecorators}, + msg_parts::MsgParts, +}; + +pub type AckPresentationV2 = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +#[serde(transparent)] +pub struct AckPresentationV2Content { + pub inner: AckContent, +} + +impl From for AckPresentationV2Content { + fn from(value: AckContent) -> Self { + Self { inner: value } + } +} + +impl From for Ack { + fn from(value: AckPresentationV2) -> Self { + Self::builder() + .id(value.id) + .content(value.content.inner) + .decorators(value.decorators) + .build() + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + + use super::*; + use crate::{ + decorators::{thread::tests::make_extended_thread, timing::tests::make_extended_timing}, + misc::test_utils, + msg_fields::protocols::notification::ack::AckStatus, + msg_types::present_proof::PresentProofTypeV2_0, + }; + + #[test] + fn test_minimal_ack_proof() { + let content: AckPresentationV2Content = AckContent::builder().status(AckStatus::Ok).build(); + + let decorators = AckDecorators::builder() + .thread(make_extended_thread()) + .build(); + + let expected = json!({ + "status": content.inner.status, + "~thread": decorators.thread + }); + + test_utils::test_msg(content, decorators, PresentProofTypeV2_0::Ack, expected); + } + + #[test] + fn test_extended_ack_proof() { + let content: AckPresentationV2Content = AckContent::builder().status(AckStatus::Ok).build(); + + let decorators = AckDecorators::builder() + .thread(make_extended_thread()) + .timing(make_extended_timing()) + .build(); + + let expected = json!({ + "status": content.inner.status, + "~thread": decorators.thread, + "~timing": decorators.timing + }); + + test_utils::test_msg(content, decorators, PresentProofTypeV2_0::Ack, expected); + } +} diff --git a/messages/src/msg_fields/protocols/present_proof/v2/mod.rs b/messages/src/msg_fields/protocols/present_proof/v2/mod.rs new file mode 100644 index 0000000000..8f98769126 --- /dev/null +++ b/messages/src/msg_fields/protocols/present_proof/v2/mod.rs @@ -0,0 +1,134 @@ +//! Module containing the `present proof` protocol messages, as defined in the [RFC](). + +pub mod ack; +pub mod present; +pub mod problem_report; +pub mod propose; +pub mod request; + +use derive_more::From; +use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; + +use self::{ + ack::{AckPresentationV2, AckPresentationV2Content}, + present::{PresentationV2, PresentationV2Content, PresentationV2Decorators}, + problem_report::{PresentProofV2ProblemReport, PresentProofV2ProblemReportContent}, + propose::{ + ProposePresentationV2, ProposePresentationV2Content, ProposePresentationV2Decorators, + }, + request::{ + RequestPresentationV2, RequestPresentationV2Content, RequestPresentationV2Decorators, + }, +}; +use super::PresentProof; +use crate::{ + misc::utils::{self, into_msg_with_type, transit_to_aries_msg}, + msg_fields::{ + protocols::{notification::ack::AckDecorators, report_problem::ProblemReportDecorators}, + traits::DelayedSerde, + }, + msg_types::{ + present_proof::{PresentProofTypeV2, PresentProofTypeV2_0}, + protocols::present_proof::PresentProofType, + MsgWithType, + }, +}; + +#[derive(Clone, Debug, From, PartialEq)] +pub enum PresentProofV2 { + ProposePresentation(ProposePresentationV2), + RequestPresentation(RequestPresentationV2), + Presentation(PresentationV2), + Ack(AckPresentationV2), + ProblemReport(PresentProofV2ProblemReport), +} + +impl DelayedSerde for PresentProofV2 { + type MsgType<'a> = (PresentProofType, &'a str); + + fn delayed_deserialize<'de, D>( + msg_type: Self::MsgType<'de>, + deserializer: D, + ) -> Result + where + D: Deserializer<'de>, + { + let (protocol, kind_str) = msg_type; + + let kind = match protocol { + PresentProofType::V2(PresentProofTypeV2::V2_0(kind)) => kind.kind_from_str(kind_str), + PresentProofType::V1(_) => { + return Err(D::Error::custom( + "Cannot deserialize present-proof-v1 message type into present-proof-v2", + )) + } + }; + + match kind.map_err(D::Error::custom)? { + PresentProofTypeV2_0::ProposePresentation => { + ProposePresentationV2::deserialize(deserializer).map(From::from) + } + PresentProofTypeV2_0::RequestPresentation => { + RequestPresentationV2::deserialize(deserializer).map(From::from) + } + PresentProofTypeV2_0::Presentation => { + PresentationV2::deserialize(deserializer).map(From::from) + } + PresentProofTypeV2_0::Ack => { + AckPresentationV2::deserialize(deserializer).map(From::from) + } + PresentProofTypeV2_0::ProblemReport => { + PresentProofV2ProblemReport::deserialize(deserializer).map(From::from) + } + PresentProofTypeV2_0::PresentationPreview => { + Err(utils::not_standalone_msg::(kind_str)) + } + } + } + + fn delayed_serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self { + Self::ProposePresentation(v) => MsgWithType::from(v).serialize(serializer), + Self::RequestPresentation(v) => MsgWithType::from(v).serialize(serializer), + Self::Presentation(v) => MsgWithType::from(v).serialize(serializer), + Self::Ack(v) => MsgWithType::from(v).serialize(serializer), + Self::ProblemReport(v) => MsgWithType::from(v).serialize(serializer), + } + } +} + +transit_to_aries_msg!( + ProposePresentationV2Content: ProposePresentationV2Decorators, + PresentProofV2, PresentProof +); +transit_to_aries_msg!( + RequestPresentationV2Content: RequestPresentationV2Decorators, + PresentProofV2, PresentProof +); +transit_to_aries_msg!(PresentationV2Content: PresentationV2Decorators, PresentProofV2, PresentProof); +transit_to_aries_msg!(AckPresentationV2Content: AckDecorators, PresentProofV2, PresentProof); +transit_to_aries_msg!( + PresentProofV2ProblemReportContent: ProblemReportDecorators, + PresentProofV2, PresentProof +); + +into_msg_with_type!( + ProposePresentationV2, + PresentProofTypeV2_0, + ProposePresentation +); +into_msg_with_type!( + RequestPresentationV2, + PresentProofTypeV2_0, + RequestPresentation +); +into_msg_with_type!(PresentationV2, PresentProofTypeV2_0, Presentation); +into_msg_with_type!(AckPresentationV2, PresentProofTypeV2_0, Ack); +into_msg_with_type!( + PresentProofV2ProblemReport, + PresentProofTypeV2_0, + ProblemReport +); diff --git a/messages/src/msg_fields/protocols/present_proof/v2/present.rs b/messages/src/msg_fields/protocols/present_proof/v2/present.rs new file mode 100644 index 0000000000..4d1bb76d79 --- /dev/null +++ b/messages/src/msg_fields/protocols/present_proof/v2/present.rs @@ -0,0 +1,134 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + decorators::{attachment::Attachment, please_ack::PleaseAck, thread::Thread, timing::Timing}, + msg_fields::protocols::common::attachment_format_specifier::AttachmentFormatSpecifier, + msg_parts::MsgParts, +}; + +pub type PresentationV2 = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +pub struct PresentationV2Content { + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub goal_code: Option, + pub formats: Vec>, + #[serde(rename = "presentations~attach")] + pub presentations_attach: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +pub struct PresentationV2Decorators { + #[serde(rename = "~thread")] + pub thread: Thread, + #[builder(default, setter(strip_option))] + #[serde(rename = "~please_ack")] + #[serde(skip_serializing_if = "Option::is_none")] + pub please_ack: Option, + #[builder(default, setter(strip_option))] + #[serde(rename = "~timing")] + #[serde(skip_serializing_if = "Option::is_none")] + pub timing: Option, +} + +/// Format types derived from Aries RFC Registry: +/// https://github.com/hyperledger/aries-rfcs/tree/b3a3942ef052039e73cd23d847f42947f8287da2/features/0454-present-proof-v2#presentations-attachment-registry +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] +pub enum PresentationAttachmentFormatType { + #[serde(rename = "hlindy/proof@v2.0")] + HyperledgerIndyProof2_0, + #[serde(rename = "dif/presentation-exchange/submission@v1.0")] + DifPresentationExchangeSubmission1_0, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + use shared_vcx::maybe_known::MaybeKnown; + + use super::*; + use crate::{ + decorators::{ + attachment::tests::make_extended_attachment, + please_ack::tests::make_minimal_please_ack, thread::tests::make_extended_thread, + timing::tests::make_extended_timing, + }, + misc::test_utils, + msg_types::present_proof::PresentProofTypeV2_0, + }; + + #[test] + fn test_minimal_present_proof() { + let content = PresentationV2Content::builder() + .formats(vec![AttachmentFormatSpecifier { + attach_id: "1".to_owned(), + format: MaybeKnown::Known( + PresentationAttachmentFormatType::HyperledgerIndyProof2_0, + ), + }]) + .presentations_attach(vec![make_extended_attachment()]) + .build(); + + let decorators = PresentationV2Decorators::builder() + .thread(make_extended_thread()) + .build(); + + let expected = json!({ + "formats": content.formats, + "presentations~attach": content.presentations_attach, + "~thread": decorators.thread + }); + + test_utils::test_msg( + content, + decorators, + PresentProofTypeV2_0::Presentation, + expected, + ); + } + + #[test] + fn test_extended_present_proof() { + let content = PresentationV2Content::builder() + .formats(vec![AttachmentFormatSpecifier { + attach_id: "1".to_owned(), + format: MaybeKnown::Known( + PresentationAttachmentFormatType::HyperledgerIndyProof2_0, + ), + }]) + .presentations_attach(vec![make_extended_attachment()]) + .comment(Some("test_comment".to_owned())) + .goal_code(Some("goal.goal".to_owned())) + .build(); + + let decorators = PresentationV2Decorators::builder() + .thread(make_extended_thread()) + .timing(make_extended_timing()) + .please_ack(make_minimal_please_ack()) + .build(); + + let expected = json!({ + "comment": content.comment, + "goal_code": content.goal_code, + "formats": content.formats, + "presentations~attach": content.presentations_attach, + "~thread": decorators.thread, + "~timing": decorators.timing, + "~please_ack": decorators.please_ack + }); + + test_utils::test_msg( + content, + decorators, + PresentProofTypeV2_0::Presentation, + expected, + ); + } +} diff --git a/messages/src/msg_fields/protocols/present_proof/v2/problem_report.rs b/messages/src/msg_fields/protocols/present_proof/v2/problem_report.rs new file mode 100644 index 0000000000..438038ba12 --- /dev/null +++ b/messages/src/msg_fields/protocols/present_proof/v2/problem_report.rs @@ -0,0 +1,137 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + msg_fields::protocols::report_problem::{ + ProblemReport, ProblemReportContent, ProblemReportDecorators, + }, + msg_parts::MsgParts, +}; + +pub type PresentProofV2ProblemReport = + MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +#[serde(transparent)] +pub struct PresentProofV2ProblemReportContent { + pub inner: ProblemReportContent, +} + +impl From for PresentProofV2ProblemReportContent { + fn from(value: ProblemReportContent) -> Self { + Self { inner: value } + } +} + +impl From for ProblemReport { + fn from(value: PresentProofV2ProblemReport) -> Self { + Self::builder() + .id(value.id) + .content(value.content.inner) + .decorators(value.decorators) + .build() + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use std::collections::HashMap; + + use serde_json::json; + + use super::*; + use crate::{ + decorators::{ + localization::tests::make_extended_field_localization, + thread::tests::make_extended_thread, timing::tests::make_extended_timing, + }, + misc::test_utils, + msg_fields::protocols::report_problem::{ + Description, Impact, Where, WhereParty, WhoRetries, + }, + msg_types::present_proof::PresentProofTypeV2_0, + }; + + #[test] + fn test_minimal_problem_report() { + let description = Description::builder() + .code("test_problem_report_code".to_owned()) + .build(); + let content: ProblemReportContent = ProblemReportContent::builder() + .description(description) + .build(); + let decorators = ProblemReportDecorators::default(); + + let expected = json!({ + "description": content.description + }); + + let content = PresentProofV2ProblemReportContent::builder() + .inner(content) + .build(); + + test_utils::test_msg( + content, + decorators, + PresentProofTypeV2_0::ProblemReport, + expected, + ); + } + + #[test] + fn test_extended_problem_report() { + let description = Description::builder() + .code("test_problem_report_code".to_owned()) + .build(); + let content: ProblemReportContent = ProblemReportContent::builder() + .description(description) + .who_retries(WhoRetries::Me) + .fix_hint("test_fix_hint".to_owned()) + .impact(Impact::Connection) + .location(Where::new(WhereParty::Me, "test_location".to_owned())) + .noticed_time("test_noticed_time".to_owned()) + .tracking_uri("https://dummy.dummy/dummy".parse().unwrap()) + .escalation_uri("https://dummy.dummy/dummy".parse().unwrap()) + .problem_items(vec![HashMap::from([( + "test_prob_item_key".to_owned(), + "test_prob_item_value".to_owned(), + )])]) + .build(); + + let decorators = ProblemReportDecorators::builder() + .thread(make_extended_thread()) + .timing(make_extended_timing()) + .description_locale(make_extended_field_localization()) + .fix_hint_locale(make_extended_field_localization()) + .build(); + + let expected = json!({ + "description": content.description, + "who_retries": content.who_retries, + "fix-hint": content.fix_hint, + "impact": content.impact, + "where": content.location, + "noticed_time": content.noticed_time, + "tracking-uri": content.tracking_uri, + "escalation-uri": content.escalation_uri, + "problem_items": content.problem_items, + "~thread": decorators.thread, + "~timing": decorators.timing, + "description~l10n": decorators.description_locale, + "fix-hint~l10n": decorators.fix_hint_locale + }); + + let content = PresentProofV2ProblemReportContent::builder() + .inner(content) + .build(); + + test_utils::test_msg( + content, + decorators, + PresentProofTypeV2_0::ProblemReport, + expected, + ); + } +} diff --git a/messages/src/msg_fields/protocols/present_proof/v2/propose.rs b/messages/src/msg_fields/protocols/present_proof/v2/propose.rs new file mode 100644 index 0000000000..5342323489 --- /dev/null +++ b/messages/src/msg_fields/protocols/present_proof/v2/propose.rs @@ -0,0 +1,126 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + decorators::{attachment::Attachment, thread::Thread, timing::Timing}, + msg_fields::protocols::common::attachment_format_specifier::OptionalIdAttachmentFormatSpecifier, + msg_parts::MsgParts, +}; + +pub type ProposePresentationV2 = + MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +pub struct ProposePresentationV2Content { + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub goal_code: Option, // TODO - spec does not specify what goal codes to use.. + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + pub formats: Vec>, + #[serde(rename = "proposals~attach", skip_serializing_if = "Option::is_none")] + pub proposals_attach: Option>, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct ProposePresentationV2Decorators { + #[builder(default)] + #[serde(rename = "~thread")] + #[serde(skip_serializing_if = "Option::is_none")] + pub thread: Option, + #[builder(default)] + #[serde(rename = "~timing")] + #[serde(skip_serializing_if = "Option::is_none")] + pub timing: Option, +} + +/// Format types derived from Aries RFC Registry: +/// https://github.com/hyperledger/aries-rfcs/tree/b3a3942ef052039e73cd23d847f42947f8287da2/features/0454-present-proof-v2#propose-attachment-registry +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] +pub enum ProposePresentationAttachmentFormatType { + #[serde(rename = "dif/presentation-exchange/definitions@v1.0")] + DifPresentationExchangeDefinitions1_0, + #[serde(rename = "hlindy/proof-req@v2.0")] + HyperledgerIndyProofRequest2_0, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + use shared_vcx::maybe_known::MaybeKnown; + + use super::*; + use crate::{ + decorators::{ + attachment::tests::make_extended_attachment, thread::tests::make_extended_thread, + timing::tests::make_extended_timing, + }, + misc::test_utils, + msg_types::present_proof::PresentProofTypeV2_0, + }; + + #[test] + fn test_minimal_propose_proof() { + let content = ProposePresentationV2Content::builder() + .formats(vec![OptionalIdAttachmentFormatSpecifier { + attach_id: None, + format: MaybeKnown::Known( + ProposePresentationAttachmentFormatType::HyperledgerIndyProofRequest2_0, + ), + }]) + .proposals_attach(None) + .build(); + + let decorators = ProposePresentationV2Decorators::default(); + + let expected = json!({ + "formats": content.formats + }); + + test_utils::test_msg( + content, + decorators, + PresentProofTypeV2_0::ProposePresentation, + expected, + ); + } + + #[test] + fn test_extended_propose_proof() { + let content = ProposePresentationV2Content::builder() + .formats(vec![OptionalIdAttachmentFormatSpecifier { + attach_id: Some("1".to_owned()), + format: MaybeKnown::Known( + ProposePresentationAttachmentFormatType::HyperledgerIndyProofRequest2_0, + ), + }]) + .proposals_attach(Some(vec![make_extended_attachment()])) + .goal_code(Some("goal.goal".to_owned())) + .comment(Some("test_comment".to_owned())) + .build(); + + let decorators = ProposePresentationV2Decorators::builder() + .thread(Some(make_extended_thread())) + .timing(Some(make_extended_timing())) + .build(); + + let expected = json!({ + "comment": content.comment, + "goal_code": content.goal_code, + "formats": content.formats, + "proposals~attach": content.proposals_attach, + "~thread": decorators.thread, + "~timing": decorators.timing + }); + + test_utils::test_msg( + content, + decorators, + PresentProofTypeV2_0::ProposePresentation, + expected, + ); + } +} diff --git a/messages/src/msg_fields/protocols/present_proof/v2/request.rs b/messages/src/msg_fields/protocols/present_proof/v2/request.rs new file mode 100644 index 0000000000..c204dce398 --- /dev/null +++ b/messages/src/msg_fields/protocols/present_proof/v2/request.rs @@ -0,0 +1,132 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + decorators::{attachment::Attachment, thread::Thread, timing::Timing}, + msg_fields::protocols::common::attachment_format_specifier::AttachmentFormatSpecifier, + msg_parts::MsgParts, +}; + +pub type RequestPresentationV2 = + MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +pub struct RequestPresentationV2Content { + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub goal_code: Option, // TODO - spec does not specify what goal codes to use.. + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub will_confirm: Option, + pub formats: Vec>, + #[serde(rename = "request_presentations~attach")] + pub request_presentations_attach: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct RequestPresentationV2Decorators { + #[builder(default)] + #[serde(rename = "~thread")] + #[serde(skip_serializing_if = "Option::is_none")] + pub thread: Option, + #[builder(default)] + #[serde(rename = "~timing")] + #[serde(skip_serializing_if = "Option::is_none")] + pub timing: Option, +} + +/// Format types derived from Aries RFC Registry: +/// https://github.com/hyperledger/aries-rfcs/tree/b3a3942ef052039e73cd23d847f42947f8287da2/features/0454-present-proof-v2#presentation-request-attachment-registry +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] +pub enum PresentationRequestAttachmentFormatType { + #[serde(rename = "hlindy/proof-req@v2.0")] + HyperledgerIndyProofRequest2_0, + #[serde(rename = "dif/presentation-exchange/definitions@v1.0")] + DifPresentationExchangeDefinitions1_0, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + use shared_vcx::maybe_known::MaybeKnown; + + use super::*; + use crate::{ + decorators::{ + attachment::tests::make_extended_attachment, thread::tests::make_extended_thread, + timing::tests::make_extended_timing, + }, + misc::test_utils, + msg_types::present_proof::PresentProofTypeV2_0, + }; + + #[test] + fn test_minimal_request_proof() { + let content = RequestPresentationV2Content::builder() + .formats(vec![AttachmentFormatSpecifier { + attach_id: "1".to_owned(), + format: MaybeKnown::Known( + PresentationRequestAttachmentFormatType::HyperledgerIndyProofRequest2_0, + ), + }]) + .request_presentations_attach(vec![make_extended_attachment()]) + .build(); + + let decorators = RequestPresentationV2Decorators::default(); + + let expected = json!({ + "formats": content.formats, + "request_presentations~attach": content.request_presentations_attach, + }); + + test_utils::test_msg( + content, + decorators, + PresentProofTypeV2_0::RequestPresentation, + expected, + ); + } + + #[test] + fn test_extended_request_proof() { + let content = RequestPresentationV2Content::builder() + .formats(vec![AttachmentFormatSpecifier { + attach_id: "1".to_owned(), + format: MaybeKnown::Known( + PresentationRequestAttachmentFormatType::HyperledgerIndyProofRequest2_0, + ), + }]) + .request_presentations_attach(vec![make_extended_attachment()]) + .goal_code(Some("goal.goal".to_owned())) + .comment(Some("test_comment".to_owned())) + .will_confirm(Some(true)) + .build(); + + let decorators = RequestPresentationV2Decorators::builder() + .thread(Some(make_extended_thread())) + .timing(Some(make_extended_timing())) + .build(); + + let expected = json!({ + "formats": content.formats, + "request_presentations~attach": content.request_presentations_attach, + "goal_code": content.goal_code, + "comment": content.comment, + "will_confirm": content.will_confirm, + "~thread": decorators.thread, + "~timing": decorators.timing + }); + + test_utils::test_msg( + content, + decorators, + PresentProofTypeV2_0::RequestPresentation, + expected, + ); + } +} diff --git a/messages/src/msg_types/protocols/present_proof.rs b/messages/src/msg_types/protocols/present_proof.rs index ce23ced537..986a72a547 100644 --- a/messages/src/msg_types/protocols/present_proof.rs +++ b/messages/src/msg_types/protocols/present_proof.rs @@ -10,6 +10,7 @@ use crate::msg_types::{role::Role, MsgKindType}; #[msg_type(protocol = "present-proof")] pub enum PresentProofType { V1(PresentProofTypeV1), + V2(PresentProofTypeV2), } #[derive(Copy, Clone, Debug, From, TryInto, PartialEq, Transitive, MessageType)] @@ -20,6 +21,14 @@ pub enum PresentProofTypeV1 { V1_0(MsgKindType), } +#[derive(Copy, Clone, Debug, From, TryInto, PartialEq, Transitive, MessageType)] +#[transitive(into(PresentProofType, Protocol))] +#[msg_type(major = 2)] +pub enum PresentProofTypeV2 { + #[msg_type(minor = 0, roles = "Role::Prover, Role::Verifier")] + V2_0(MsgKindType), +} + #[derive(Copy, Clone, Debug, AsRefStr, EnumString, PartialEq)] #[strum(serialize_all = "kebab-case")] pub enum PresentProofTypeV1_0 { @@ -31,6 +40,17 @@ pub enum PresentProofTypeV1_0 { ProblemReport, } +#[derive(Copy, Clone, Debug, AsRefStr, EnumString, PartialEq)] +#[strum(serialize_all = "kebab-case")] +pub enum PresentProofTypeV2_0 { + ProposePresentation, + RequestPresentation, + Presentation, + PresentationPreview, + Ack, + ProblemReport, +} + #[cfg(test)] mod tests { use serde_json::json; @@ -39,7 +59,7 @@ mod tests { use crate::misc::test_utils; #[test] - fn test_protocol_present_proof() { + fn test_protocol_present_proof_v1() { test_utils::test_serde( Protocol::from(PresentProofTypeV1::new_v1_0()), json!("https://didcomm.org/present-proof/1.0"), @@ -47,7 +67,7 @@ mod tests { } #[test] - fn test_version_resolution_present_proof() { + fn test_version_resolution_present_proof_v1() { test_utils::test_msg_type_resolution( "https://didcomm.org/present-proof/1.255", PresentProofTypeV1::new_v1_0(), @@ -56,7 +76,7 @@ mod tests { #[test] #[should_panic] - fn test_unsupported_version_present_proof() { + fn test_unsupported_version_present_proof_v1() { test_utils::test_serde( Protocol::from(PresentProofTypeV1::new_v1_0()), json!("https://didcomm.org/present-proof/2.0"), @@ -64,7 +84,7 @@ mod tests { } #[test] - fn test_msg_type_propose() { + fn test_msg_type_propose_v1() { test_utils::test_msg_type( "https://didcomm.org/present-proof/1.0", "propose-presentation", @@ -73,7 +93,7 @@ mod tests { } #[test] - fn test_msg_type_request() { + fn test_msg_type_request_v1() { test_utils::test_msg_type( "https://didcomm.org/present-proof/1.0", "request-presentation", @@ -82,7 +102,7 @@ mod tests { } #[test] - fn test_msg_type_presentation() { + fn test_msg_type_presentation_v1() { test_utils::test_msg_type( "https://didcomm.org/present-proof/1.0", "presentation", @@ -91,7 +111,7 @@ mod tests { } #[test] - fn test_msg_type_preview() { + fn test_msg_type_preview_v1() { test_utils::test_msg_type( "https://didcomm.org/present-proof/1.0", "presentation-preview", @@ -100,11 +120,81 @@ mod tests { } #[test] - fn test_msg_type_ack() { + fn test_msg_type_ack_v1() { test_utils::test_msg_type( "https://didcomm.org/present-proof/1.0", "ack", PresentProofTypeV1::new_v1_0(), ) } + + #[test] + fn test_protocol_present_proof_v2() { + test_utils::test_serde( + Protocol::from(PresentProofTypeV2::new_v2_0()), + json!("https://didcomm.org/present-proof/2.0"), + ) + } + + #[test] + fn test_version_resolution_present_proof_v2() { + test_utils::test_msg_type_resolution( + "https://didcomm.org/present-proof/2.255", + PresentProofTypeV2::new_v2_0(), + ) + } + + #[test] + #[should_panic] + fn test_unsupported_version_present_proof_v2() { + test_utils::test_serde( + Protocol::from(PresentProofTypeV2::new_v2_0()), + json!("https://didcomm.org/present-proof/1.0"), + ) + } + + #[test] + fn test_msg_type_propose_v2() { + test_utils::test_msg_type( + "https://didcomm.org/present-proof/2.0", + "propose-presentation", + PresentProofTypeV2::new_v2_0(), + ) + } + + #[test] + fn test_msg_type_request_v2() { + test_utils::test_msg_type( + "https://didcomm.org/present-proof/2.0", + "request-presentation", + PresentProofTypeV2::new_v2_0(), + ) + } + + #[test] + fn test_msg_type_presentation_v2() { + test_utils::test_msg_type( + "https://didcomm.org/present-proof/2.0", + "presentation", + PresentProofTypeV2::new_v2_0(), + ) + } + + #[test] + fn test_msg_type_preview_v2() { + test_utils::test_msg_type( + "https://didcomm.org/present-proof/2.0", + "presentation-preview", + PresentProofTypeV2::new_v2_0(), + ) + } + + #[test] + fn test_msg_type_ack_v2() { + test_utils::test_msg_type( + "https://didcomm.org/present-proof/2.0", + "ack", + PresentProofTypeV2::new_v2_0(), + ) + } } diff --git a/messages/src/msg_types/registry.rs b/messages/src/msg_types/registry.rs index f77dc34b3e..addd216948 100644 --- a/messages/src/msg_types/registry.rs +++ b/messages/src/msg_types/registry.rs @@ -4,20 +4,23 @@ use lazy_static::lazy_static; use shared_vcx::maybe_known::MaybeKnown; use super::{role::Role, Protocol}; -use crate::msg_types::protocols::{ - basic_message::BasicMessageTypeV1, - connection::ConnectionTypeV1, - cred_issuance::{CredentialIssuanceTypeV1, CredentialIssuanceTypeV2}, - discover_features::DiscoverFeaturesTypeV1, - notification::NotificationTypeV1, - out_of_band::OutOfBandTypeV1, - pickup::PickupTypeV2, - present_proof::PresentProofTypeV1, - report_problem::ReportProblemTypeV1, - revocation::RevocationTypeV2, - routing::RoutingTypeV1, - signature::SignatureTypeV1, - trust_ping::TrustPingTypeV1, +use crate::msg_types::{ + present_proof::PresentProofTypeV2, + protocols::{ + basic_message::BasicMessageTypeV1, + connection::ConnectionTypeV1, + cred_issuance::{CredentialIssuanceTypeV1, CredentialIssuanceTypeV2}, + discover_features::DiscoverFeaturesTypeV1, + notification::NotificationTypeV1, + out_of_band::OutOfBandTypeV1, + pickup::PickupTypeV2, + present_proof::PresentProofTypeV1, + report_problem::ReportProblemTypeV1, + revocation::RevocationTypeV2, + routing::RoutingTypeV1, + signature::SignatureTypeV1, + trust_ping::TrustPingTypeV1, + }, }; type RegistryMap = HashMap<(&'static str, u8), Vec>; @@ -85,6 +88,7 @@ lazy_static! { map_insert(&mut m, extract_parts!(NotificationTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(OutOfBandTypeV1::new_v1_1())); map_insert(&mut m, extract_parts!(PresentProofTypeV1::new_v1_0())); + map_insert(&mut m, extract_parts!(PresentProofTypeV2::new_v2_0())); map_insert(&mut m, extract_parts!(ReportProblemTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(RevocationTypeV2::new_v2_0())); map_insert(&mut m, extract_parts!(TrustPingTypeV1::new_v1_0())); From 1a414f019b0c4cb6fef79ce119660a571b850176 Mon Sep 17 00:00:00 2001 From: Patrik Date: Fri, 20 Oct 2023 11:26:55 +0200 Subject: [PATCH 5/6] Refactor: reuse parse_numalgo to avoid duplication (#1020) Signed-off-by: Patrik Stas --- did_peer/src/peer_did/numalgos/mod.rs | 18 ++++++++++++------ did_peer/src/peer_did/numalgos/traits.rs | 13 ++----------- 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/did_peer/src/peer_did/numalgos/mod.rs b/did_peer/src/peer_did/numalgos/mod.rs index 8c3c1efa25..d816f9a468 100644 --- a/did_peer/src/peer_did/numalgos/mod.rs +++ b/did_peer/src/peer_did/numalgos/mod.rs @@ -23,17 +23,23 @@ pub enum NumalgoKind { DidShortening(Numalgo3), } -impl Display for NumalgoKind { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl NumalgoKind { + pub fn to_char(&self) -> char { match self { - NumalgoKind::InceptionKeyWithoutDoc(_) => Numalgo0::NUMALGO_CHAR.fmt(f), - NumalgoKind::GenesisDoc(_) => Numalgo1::NUMALGO_CHAR.fmt(f), - NumalgoKind::MultipleInceptionKeys(_) => Numalgo2::NUMALGO_CHAR.fmt(f), - NumalgoKind::DidShortening(_) => Numalgo3::NUMALGO_CHAR.fmt(f), + NumalgoKind::InceptionKeyWithoutDoc(_) => Numalgo0::NUMALGO_CHAR, + NumalgoKind::GenesisDoc(_) => Numalgo1::NUMALGO_CHAR, + NumalgoKind::MultipleInceptionKeys(_) => Numalgo2::NUMALGO_CHAR, + NumalgoKind::DidShortening(_) => Numalgo3::NUMALGO_CHAR, } } } +impl Display for NumalgoKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.to_char().fmt(f) + } +} + impl TryFrom for NumalgoKind { type Error = DidPeerError; diff --git a/did_peer/src/peer_did/numalgos/traits.rs b/did_peer/src/peer_did/numalgos/traits.rs index c7283422a5..67f988dd91 100644 --- a/did_peer/src/peer_did/numalgos/traits.rs +++ b/did_peer/src/peer_did/numalgos/traits.rs @@ -5,7 +5,7 @@ use did_parser::Did; use super::numalgo3::Numalgo3; use crate::{ error::DidPeerError, - peer_did::{validate::validate, PeerDid}, + peer_did::{parse::parse_numalgo, validate::validate, PeerDid}, peer_did_resolver::options::PublicKeyEncoding, }; @@ -18,20 +18,11 @@ pub trait Numalgo: Sized + Default { >::Error: Into, { let did: Did = did.try_into().map_err(Into::into)?; - - let numalgo_char = did.id().chars().next().ok_or_else(|| { - DidPeerError::DidValidationError(format!( - "Invalid did: unable to read numalgo character in did {}", - did.did() - )) - })?; - + let numalgo_char = parse_numalgo(&did)?.to_char(); if numalgo_char != Self::NUMALGO_CHAR { return Err(DidPeerError::InvalidNumalgoCharacter(numalgo_char)); } - validate(&did)?; - Ok(PeerDid::from_parts(did, Self::default())) } } From dbaac13bf2054549a6e37c4d2ad293184df0c66f Mon Sep 17 00:00:00 2001 From: Patrik Date: Tue, 24 Oct 2023 12:59:00 +0200 Subject: [PATCH 6/6] Update readmes (#1024) * Update readmes Signed-off-by: Patrik Stas Signed-off-by: Miroslav Kovar Co-authored-by: Miroslav Kovar --- README.md | 29 ++++++++++++++--------------- agents/rust/README.md | 4 ++++ libvcx_core/README.md | 3 --- 3 files changed, 18 insertions(+), 18 deletions(-) create mode 100644 agents/rust/README.md diff --git a/README.md b/README.md index 6be00ff0c6..f774a74967 100644 --- a/README.md +++ b/README.md @@ -4,23 +4,22 @@ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Join the chat at https://chat.hyperledger.org/channel/aries](https://img.shields.io/badge/Chat%20on-Hyperledger%20Chat-blue)](https://chat.hyperledger.org/channel/aries) -The repository contains -- Rust library `aries-vcx` implementing Aries protocols, -- collection of supporting projects. +The repository contains a set of crates to build [Aries](https://github.com/hyperledger/aries-rfcs/) / [DIDComm](https://didcomm.org/) applications in Rust. -## If you are Rust 🦀 developer -You can build your Rust project on top of -- [`aries-vcx`](aries_vcx) - ready to go Rust library to work with Aries protocols for didcomm, VC issuance and verification. +## Aries components + - [`aries_vcx`](aries_vcx) - Library implementing DIDComm protocols, with focus on verifiable credential issuance and verification. + - [`messages`](messages) - Library for building and parsing Aries messages. + - `aries_vcx_core` - Interfaces for interaction with ledgers, wallets and credentials. + - [`agents`](agents/rust) - Aries agents built on top of `aries_vcx`. + +## General components + - `did_parser` - Building and parsing [DIDs](https://w3c.github.io/did-core/). + - `did_doc` - Building and parsing DID Documents. + - `did_peer`, `did_sov`, `did_web`, `did_key` - DID resolvers for different [DID methods](https://w3c.github.io/did-spec-registries/#did-methods). -Additionally, `aries-vcx` is built on top of smaller Rust crates which are part of this repo: -- [`aries_vcx_core`](aries_vcx_core) - foundational APIs to interact with ledger, wallet and anoncreds. -- [`messages`](messages) - crate for building and parsing Aries messages -- [`did_doc`](diddoc) - crate to work with DIDDocs - -## If you are mobile 📱 developer -Aries-vcx can be used to build native mobile applications. You can write part of your mobile backend in Rust on top of -`aries-vcx` crate. Then expose FFI API for iOS/android environments. -- There's POC in progress [`uniffi_aries_vcx`](./uniffi_aries_vcx) using UniFFI library to autogenerate Swift and Kotlin wrappers. +## Mobile 📱 + - [`uniffi_aries_vcx`](./uniffi_aries_vcx) - UniFFI wrapper for `aries_vcx` and sample mobile app + - [`simple_message_relay`](./tools/simple_message_relay) - simple implementation of message relay service for development / testing purposes # Reach out 👋 - Ask a question on [discord](https://discord.com/channels/905194001349627914/955480822675308604) diff --git a/agents/rust/README.md b/agents/rust/README.md new file mode 100644 index 0000000000..20188f7543 --- /dev/null +++ b/agents/rust/README.md @@ -0,0 +1,4 @@ +# Rust agents +This directory contains some of Rust agents built on top of the `aries_vcx` crate: +- `aries-vcx-agent` - aries agent library providing used to build our cross-framework testing [backchannel](https://github.com/hyperledger/aries-agent-test-harness/tree/main/aries-backchannels/aries-vcx) + diff --git a/libvcx_core/README.md b/libvcx_core/README.md index a5032dedd9..34194227a7 100644 --- a/libvcx_core/README.md +++ b/libvcx_core/README.md @@ -2,6 +2,3 @@ This is foundational crate for - NodeJS wrapper [`vcx-napi-rs`](../wrappers/vcx-napi-rs) -## Architecture - -Libvcx architecture diagram