diff --git a/Cargo.lock b/Cargo.lock index d5e8dd16b0..831305dc5b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -231,24 +231,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "agency_client" -version = "0.62.0" -dependencies = [ - "async-trait", - "env_logger 0.9.3", - "lazy_static", - "log", - "regex", - "serde", - "serde_derive", - "serde_json", - "shared", - "thiserror", - "url", - "uuid 0.8.2", -] - [[package]] name = "ahash" version = "0.8.8" @@ -472,14 +454,13 @@ dependencies = [ "shared", "thiserror", "url", - "uuid 1.5.0", + "uuid", ] [[package]] name = "aries_vcx" version = "0.62.0" dependencies = [ - "agency_client", "anoncreds_types", "aries_vcx_core", "async-channel", @@ -519,7 +500,7 @@ dependencies = [ "time 0.3.20", "tokio", "url", - "uuid 1.5.0", + "uuid", "wallet_migrator", ] @@ -527,7 +508,6 @@ dependencies = [ name = "aries_vcx_core" version = "0.1.0" dependencies = [ - "agency_client", "anoncreds", "anoncreds_types", "aries-askar", @@ -553,7 +533,7 @@ dependencies = [ "time 0.3.20", "tokio", "typed-builder 0.18.1", - "uuid 1.5.0", + "uuid", ] [[package]] @@ -667,7 +647,7 @@ dependencies = [ "sqlx", "tokio", "url", - "uuid 1.5.0", + "uuid", "zeroize", ] @@ -1905,7 +1885,7 @@ dependencies = [ "thiserror", "tokio", "url", - "uuid 1.5.0", + "uuid", ] [[package]] @@ -3394,7 +3374,7 @@ dependencies = [ "tokio", "tower-http", "url", - "uuid 1.5.0", + "uuid", ] [[package]] @@ -5211,7 +5191,6 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" name = "test_utils" version = "0.62.0" dependencies = [ - "agency_client", "anoncreds_types", "aries_vcx_core", "async-trait", @@ -5223,7 +5202,7 @@ dependencies = [ "public_key", "rand 0.8.5", "serde_json", - "uuid 1.5.0", + "uuid", ] [[package]] @@ -5813,15 +5792,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "uuid" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" -dependencies = [ - "getrandom 0.2.10", -] - [[package]] name = "uuid" version = "1.5.0" diff --git a/Cargo.toml b/Cargo.toml index 6b1f922e23..45515038cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,6 @@ resolver = "2" members = [ "aries/aries_vcx", - "aries/misc/legacy/agency_client", "aries/misc/legacy/libvdrtools", "aries/messages_macros", "aries/messages", diff --git a/aries/aries_vcx/Cargo.toml b/aries/aries_vcx/Cargo.toml index 772e0d3ff5..fe9b317514 100644 --- a/aries/aries_vcx/Cargo.toml +++ b/aries/aries_vcx/Cargo.toml @@ -38,7 +38,6 @@ askar_wallet = [ ] [dependencies] -agency_client = { path = "../misc/legacy/agency_client" } messages = { path = "../messages" } diddoc_legacy = { path = "../misc/legacy/diddoc_legacy" } aries_vcx_core = { path = "../aries_vcx_core" } diff --git a/aries/aries_vcx/src/common/ledger/service_didsov.rs b/aries/aries_vcx/src/common/ledger/service_didsov.rs index 2b722cd74f..6c7499c9cb 100644 --- a/aries/aries_vcx/src/common/ledger/service_didsov.rs +++ b/aries/aries_vcx/src/common/ledger/service_didsov.rs @@ -62,8 +62,8 @@ impl Default for EndpointDidSov { #[cfg(test)] mod unit_tests { - use agency_client::testing::test_utils::SetupMocks; use diddoc_legacy::aries::diddoc::test_utils::{_routing_keys, _service_endpoint}; + use test_utils::devsetup::SetupMocks; use crate::common::ledger::service_didsov::{DidSovServiceType, EndpointDidSov}; diff --git a/aries/aries_vcx/src/errors/mapping_agency_client.rs b/aries/aries_vcx/src/errors/mapping_agency_client.rs deleted file mode 100644 index c8d2b6d158..0000000000 --- a/aries/aries_vcx/src/errors/mapping_agency_client.rs +++ /dev/null @@ -1,32 +0,0 @@ -use agency_client::errors::error::{AgencyClientError, AgencyClientErrorKind}; - -use crate::errors::error::{AriesVcxError, AriesVcxErrorKind}; - -impl From for AriesVcxError { - fn from(agency_err: AgencyClientError) -> AriesVcxError { - let vcx_error_kind: AriesVcxErrorKind = agency_err.kind().into(); - AriesVcxError::from_msg(vcx_error_kind, agency_err.to_string()) - } -} - -impl From for AriesVcxErrorKind { - fn from(agency_err: AgencyClientErrorKind) -> AriesVcxErrorKind { - match agency_err { - AgencyClientErrorKind::InvalidState => AriesVcxErrorKind::InvalidState, - AgencyClientErrorKind::InvalidConfiguration => AriesVcxErrorKind::InvalidConfiguration, - AgencyClientErrorKind::InvalidJson => AriesVcxErrorKind::InvalidJson, - AgencyClientErrorKind::InvalidOption => AriesVcxErrorKind::InvalidOption, - AgencyClientErrorKind::InvalidMessagePack => AriesVcxErrorKind::InvalidMessagePack, - AgencyClientErrorKind::IOError => AriesVcxErrorKind::IOError, - AgencyClientErrorKind::PostMessageFailed => AriesVcxErrorKind::PostMessageFailed, - AgencyClientErrorKind::InvalidWalletHandle => AriesVcxErrorKind::InvalidWalletHandle, - AgencyClientErrorKind::UnknownError => AriesVcxErrorKind::UnknownError, - AgencyClientErrorKind::InvalidDid => AriesVcxErrorKind::InvalidDid, - AgencyClientErrorKind::InvalidVerkey => AriesVcxErrorKind::InvalidVerkey, - AgencyClientErrorKind::InvalidUrl => AriesVcxErrorKind::InvalidUrl, - AgencyClientErrorKind::SerializationError => AriesVcxErrorKind::SerializationError, - AgencyClientErrorKind::NotBase58 => AriesVcxErrorKind::NotBase58, - AgencyClientErrorKind::InvalidHttpResponse => AriesVcxErrorKind::InvalidHttpResponse, - } - } -} diff --git a/aries/aries_vcx/src/errors/mod.rs b/aries/aries_vcx/src/errors/mod.rs index 2f36b17875..0ae94d25b2 100644 --- a/aries/aries_vcx/src/errors/mod.rs +++ b/aries/aries_vcx/src/errors/mod.rs @@ -1,4 +1,3 @@ pub mod error; -mod mapping_agency_client; mod mapping_diddoc; mod mapping_others; diff --git a/aries/aries_vcx/src/handlers/issuance/holder.rs b/aries/aries_vcx/src/handlers/issuance/holder.rs index 2391070712..7a4eed17e8 100644 --- a/aries/aries_vcx/src/handlers/issuance/holder.rs +++ b/aries/aries_vcx/src/handlers/issuance/holder.rs @@ -29,10 +29,7 @@ use uuid::Uuid; use crate::{ common::credentials::get_cred_rev_id, errors::error::prelude::*, - handlers::{ - mediated_connection::MediatedConnection, - revocation_notification::receiver::RevocationNotificationReceiver, - }, + handlers::revocation_notification::receiver::RevocationNotificationReceiver, protocols::issuance::holder::state_machine::{HolderFullState, HolderSM, HolderState}, }; @@ -242,17 +239,15 @@ impl Holder { ledger: &impl AnoncredsLedgerRead, anoncreds: &impl BaseAnonCreds, wallet: &impl BaseWallet, - connection: &MediatedConnection, notification: Revoke, ) -> VcxResult<()> { if self.holder_sm.is_revokable(ledger).await? { - let send_message = connection.send_message_closure(wallet).await?; // TODO: Store to remember notification was received along with details RevocationNotificationReceiver::build( self.get_rev_reg_id()?, self.get_cred_rev_id(wallet, anoncreds).await?, ) - .handle_revocation_notification(notification, send_message) + .handle_revocation_notification(notification) .await?; Ok(()) } else { diff --git a/aries/aries_vcx/src/handlers/mediated_connection/cloud_agent.rs b/aries/aries_vcx/src/handlers/mediated_connection/cloud_agent.rs deleted file mode 100644 index 07211ad498..0000000000 --- a/aries/aries_vcx/src/handlers/mediated_connection/cloud_agent.rs +++ /dev/null @@ -1,291 +0,0 @@ -use std::{collections::HashMap, sync::Arc}; - -use agency_client::{ - agency_client::AgencyClient, api::downloaded_message::DownloadedMessageEncrypted, - messages::update_message::UIDsByConn, - wallet::base_agency_client_wallet::BaseAgencyClientWallet, -}; -use aries_vcx_core::wallet::agency_client_wallet::ToBaseWallet; -use messages::AriesMessage; -use url::Url; - -use crate::{ - agency_client::MessageStatusCode, errors::error::prelude::*, - protocols::mediated_connection::pairwise_info::PairwiseInfo, - utils::encryption_envelope::EncryptionEnvelope, -}; - -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CloudAgentInfo { - pub agent_did: String, - pub agent_vk: String, -} - -pub async fn create_agent_keys( - agency_client: &AgencyClient, - source_id: &str, - pw_did: &str, - pw_verkey: &str, -) -> VcxResult<(String, String)> { - debug!( - "creating pairwise keys on agent for connection {}", - source_id - ); - trace!( - "create_agent_keys >>> source_id: {}, pw_did: {}, pw_verkey: {}", - source_id, - pw_did, - pw_verkey - ); - - let (agent_did, agent_verkey) = agency_client - .create_connection_agent(pw_did, pw_verkey) - .await?; - - trace!( - "create_agent_keys <<< agent_did: {}, agent_verkey: {}", - agent_did, - agent_verkey - ); - Ok((agent_did, agent_verkey)) -} - -fn _log_messages_optionally(_a2a_messages: &HashMap) { - { - for message in _a2a_messages.values() { - let serialized_msg = serde_json::to_string_pretty(message) - .unwrap_or_else(|_err| String::from("Failed to serialize AriesMessage.")); - warn!("Fetched decrypted connection messages:\n{}", serialized_msg); - } - } -} - -impl CloudAgentInfo { - pub async fn create( - agency_client: &AgencyClient, - pairwise_info: &PairwiseInfo, - ) -> VcxResult { - trace!( - "CloudAgentInfo::create >>> pairwise_info: {:?}", - pairwise_info - ); - let (agent_did, agent_vk) = create_agent_keys( - agency_client, - "", - &pairwise_info.pw_did, - &pairwise_info.pw_vk, - ) - .await?; - Ok(CloudAgentInfo { - agent_did, - agent_vk, - }) - } - - pub async fn destroy( - &self, - agency_client: &AgencyClient, - pairwise_info: &PairwiseInfo, - ) -> VcxResult<()> { - trace!("CloudAgentInfo::delete >>>"); - agency_client - .delete_connection_agent( - &pairwise_info.pw_did, - &pairwise_info.pw_vk, - &self.agent_did, - &self.agent_vk, - ) - .await - .map_err(|err| err.into()) - } - - // todo: eliminate this function - pub fn service_endpoint(&self, agency_client: &AgencyClient) -> VcxResult { - Ok(agency_client.get_agency_url_full()?) - } - - // todo: implement this in agency_client - pub fn routing_keys(&self, agency_client: &AgencyClient) -> VcxResult> { - let agency_vk = agency_client.get_agency_vk(); - Ok(vec![self.agent_vk.to_string(), agency_vk]) - } - - pub async fn update_message_status( - &self, - agency_client: &AgencyClient, - pairwise_info: &PairwiseInfo, - uid: String, - ) -> VcxResult<()> { - trace!("CloudAgentInfo::update_message_status >>> uid: {:?}", uid); - - let messages_to_update = vec![UIDsByConn { - pairwise_did: pairwise_info.pw_did.clone(), - uids: vec![uid], - }]; - - agency_client - .update_messages(MessageStatusCode::Reviewed, messages_to_update) - .await - .map_err(|err| err.into()) - } - - pub async fn download_encrypted_messages( - &self, - agency_client: &AgencyClient, - msg_uid: Option>, - status_codes: Option>, - pairwise_info: &PairwiseInfo, - ) -> VcxResult> { - trace!("CloudAgentInfo::download_encrypted_messages >>>"); - agency_client - .get_encrypted_connection_messages( - &pairwise_info.pw_did, - &pairwise_info.pw_vk, - &self.agent_did, - &self.agent_vk, - msg_uid, - status_codes, - ) - .await - .map_err(|err| err.into()) - } - - pub async fn get_messages( - &self, - agency_client: &AgencyClient, - expect_sender_vk: &str, - pairwise_info: &PairwiseInfo, - ) -> VcxResult> { - trace!( - "CloudAgentInfo::get_messages >>> expect_sender_vk: {}", - expect_sender_vk - ); - let messages = self - .download_encrypted_messages( - agency_client, - None, - Some(vec![MessageStatusCode::Received]), - pairwise_info, - ) - .await?; - debug!( - "CloudAgentInfo::get_messages >>> obtained {} messages", - messages.len() - ); - let a2a_messages = self - .decrypt_decode_messages(&agency_client.get_wallet(), &messages, expect_sender_vk) - .await?; - _log_messages_optionally(&a2a_messages); - Ok(a2a_messages) - } - - pub async fn get_messages_noauth( - &self, - agency_client: &AgencyClient, - pairwise_info: &PairwiseInfo, - uids: Option>, - ) -> VcxResult> { - trace!("CloudAgentInfo::get_messages_noauth >>>"); - let messages = self - .download_encrypted_messages( - agency_client, - uids, - Some(vec![MessageStatusCode::Received]), - pairwise_info, - ) - .await?; - debug!( - "CloudAgentInfo::get_messages_noauth >>> obtained {} messages", - messages.len() - ); - let a2a_messages = self - .decrypt_decode_messages_noauth(&agency_client.get_wallet(), &messages) - .await?; - _log_messages_optionally(&a2a_messages); - Ok(a2a_messages) - } - - pub async fn get_message_by_id( - &self, - agency_client: &AgencyClient, - msg_id: &str, - expected_sender_vk: &str, - pairwise_info: &PairwiseInfo, - ) -> VcxResult { - trace!("CloudAgentInfo::get_message_by_id >>> msg_id: {:?}", msg_id); - let mut messages = self - .download_encrypted_messages( - agency_client, - Some(vec![msg_id.to_string()]), - None, - pairwise_info, - ) - .await?; - let message = messages.pop().ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::InvalidMessages, - format!("Message not found for id: {:?}", msg_id), - ))?; - let message = self - .decrypt_decode_message(&agency_client.get_wallet(), &message, expected_sender_vk) - .await?; - Ok(message) - } - - async fn decrypt_decode_messages( - &self, - wallet: &Arc, - messages: &Vec, - expected_sender_vk: &str, - ) -> VcxResult> { - let mut a2a_messages: HashMap = HashMap::new(); - for message in messages { - a2a_messages.insert( - message.uid.clone(), - self.decrypt_decode_message(wallet, message, expected_sender_vk) - .await?, - ); - } - Ok(a2a_messages) - } - - async fn decrypt_decode_messages_noauth( - &self, - wallet: &Arc, - messages: &Vec, - ) -> VcxResult> { - let mut a2a_messages: HashMap = HashMap::new(); - for message in messages { - a2a_messages.insert( - message.uid.clone(), - self.decrypt_decode_message_noauth(wallet, message).await?, - ); - } - Ok(a2a_messages) - } - - async fn decrypt_decode_message( - &self, - wallet: &Arc, - message: &DownloadedMessageEncrypted, - expected_sender_vk: &str, - ) -> VcxResult { - EncryptionEnvelope::auth_unpack_aries_msg( - &wallet.to_base_wallet(), - message.payload()?, - expected_sender_vk, - ) - .await - } - - async fn decrypt_decode_message_noauth( - &self, - wallet: &Arc, - message: &DownloadedMessageEncrypted, - ) -> VcxResult { - Ok( - EncryptionEnvelope::anon_unpack_aries_msg(&wallet.to_base_wallet(), message.payload()?) - .await? - .0, - ) - } -} diff --git a/aries/aries_vcx/src/handlers/mediated_connection/legacy_agent_info.rs b/aries/aries_vcx/src/handlers/mediated_connection/legacy_agent_info.rs deleted file mode 100644 index db2db2af9b..0000000000 --- a/aries/aries_vcx/src/handlers/mediated_connection/legacy_agent_info.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct LegacyAgentInfo { - pub pw_did: String, - pub pw_vk: String, - pub agent_did: String, - pub agent_vk: String, -} diff --git a/aries/aries_vcx/src/handlers/mediated_connection/mod.rs b/aries/aries_vcx/src/handlers/mediated_connection/mod.rs deleted file mode 100644 index 4434be0125..0000000000 --- a/aries/aries_vcx/src/handlers/mediated_connection/mod.rs +++ /dev/null @@ -1,1284 +0,0 @@ -use std::{collections::HashMap, fmt}; - -use agency_client::{ - agency_client::AgencyClient, api::downloaded_message::DownloadedMessage, MessageStatusCode, -}; -use aries_vcx_core::wallet::base_wallet::BaseWallet; -use chrono::Utc; -use diddoc_legacy::aries::diddoc::AriesDidDoc; -use futures::{future::BoxFuture, StreamExt}; -use messages::{ - decorators::timing::Timing, - msg_fields::protocols::{ - basic_message::{BasicMessage, BasicMessageContent, BasicMessageDecorators}, - connection::{invitation::InvitationContent, request::Request, Connection}, - out_of_band::OutOfBand, - trust_ping::TrustPing, - }, - AriesMessage, -}; -use serde::{ - de::{Error, MapAccess, Visitor}, - Deserialize, Deserializer, Serialize, Serializer, -}; -use serde_json::Value; -use url::Url; -use uuid::Uuid; - -use crate::{ - errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, - handlers::{ - mediated_connection::{ - cloud_agent::CloudAgentInfo, legacy_agent_info::LegacyAgentInfo, util::send_message, - }, - trust_ping::TrustPingSender, - util::AnyInvitation, - }, - protocols::{ - connection::pairwise_info::PairwiseInfo, - mediated_connection::{ - invitee::state_machine::{ - MediatedInviteeFullState, MediatedInviteeState, SmMediatedConnectionInvitee, - }, - inviter::state_machine::{ - MediatedInviterFullState, MediatedInviterState, SmMediatedConnectionInviter, - }, - }, - oob::{build_handshake_reuse_accepted_msg, build_handshake_reuse_msg}, - trustping::build_ping_response, - SendClosure, SendClosureConnection, - }, - utils::serialization::SerializableObjectWithState, -}; - -pub mod cloud_agent; -pub mod legacy_agent_info; -pub(crate) mod util; - -#[derive(Clone, PartialEq)] -pub struct MediatedConnection { - connection_sm: SmMediatedConnection, - cloud_agent_info: Option, - autohop_enabled: bool, -} - -#[derive(Clone, PartialEq)] -pub enum SmMediatedConnection { - Inviter(SmMediatedConnectionInviter), - Invitee(SmMediatedConnectionInvitee), -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub enum SmConnectionState { - Inviter(MediatedInviterFullState), - Invitee(MediatedInviteeFullState), -} - -#[derive(Debug, Serialize)] -struct ConnectionInfo { - my: SideDetails, - their: Option, -} - -#[derive(Debug, PartialEq, Eq)] -pub enum MediatedConnectionState { - Inviter(MediatedInviterState), - Invitee(MediatedInviteeState), -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct SideDetails { - did: String, - recipient_keys: Vec, - routing_keys: Vec, - service_endpoint: Url, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum MediatedConnectionActor { - Inviter, - Invitee, -} - -impl MediatedConnection { - pub async fn create( - source_id: &str, - wallet: &impl BaseWallet, - agency_client: &AgencyClient, - autohop_enabled: bool, - ) -> VcxResult { - trace!("MediatedConnection::create >>> source_id: {}", source_id); - let pairwise_info = PairwiseInfo::create(wallet).await?; - let cloud_agent_info = Some(CloudAgentInfo::create(agency_client, &pairwise_info).await?); - Ok(Self { - cloud_agent_info, - connection_sm: SmMediatedConnection::Inviter(SmMediatedConnectionInviter::new( - source_id, - pairwise_info, - )), - autohop_enabled, - }) - } - - pub async fn create_with_invite( - source_id: &str, - wallet: &impl BaseWallet, - agency_client: &AgencyClient, - invitation: AnyInvitation, - did_doc: AriesDidDoc, - autohop_enabled: bool, - ) -> VcxResult { - trace!( - "MediatedConnection::create_with_invite >>> source_id: {}, invitation: {:?}", - source_id, - invitation - ); - let pairwise_info = PairwiseInfo::create(wallet).await?; - let cloud_agent_info = Some(CloudAgentInfo::create(agency_client, &pairwise_info).await?); - let mut connection = Self { - cloud_agent_info, - connection_sm: SmMediatedConnection::Invitee(SmMediatedConnectionInvitee::new( - source_id, - pairwise_info, - did_doc, - )), - autohop_enabled, - }; - connection.process_invite(invitation)?; - Ok(connection) - } - - pub async fn create_with_request( - wallet: &impl BaseWallet, - request: Request, - pairwise_info: PairwiseInfo, - agency_client: &AgencyClient, - ) -> VcxResult { - trace!( - "MediatedConnection::create_with_request >>> request: {:?}, pairwise_info: {:?}", - request, - pairwise_info - ); - let mut connection = Self { - cloud_agent_info: None, - connection_sm: SmMediatedConnection::Inviter(SmMediatedConnectionInviter::new( - &request.id, - pairwise_info, - )), - autohop_enabled: true, - }; - connection - .process_request(wallet, agency_client, request) - .await?; - Ok(connection) - } - - pub fn from_parts( - source_id: String, - thread_id: String, - pairwise_info: PairwiseInfo, - cloud_agent_info: Option, - state: SmConnectionState, - autohop_enabled: bool, - ) -> Self { - match state { - SmConnectionState::Inviter(state) => Self { - cloud_agent_info, - connection_sm: SmMediatedConnection::Inviter(SmMediatedConnectionInviter::from( - source_id, - thread_id, - pairwise_info, - state, - )), - autohop_enabled, - }, - SmConnectionState::Invitee(state) => Self { - cloud_agent_info, - connection_sm: SmMediatedConnection::Invitee(SmMediatedConnectionInvitee::from( - source_id, - thread_id, - pairwise_info, - state, - )), - autohop_enabled, - }, - } - } - - pub fn source_id(&self) -> String { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => sm_inviter.source_id(), - SmMediatedConnection::Invitee(sm_invitee) => sm_invitee.source_id(), - } - .into() - } - - pub fn get_thread_id(&self) -> String { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => sm_inviter.get_thread_id(), - SmMediatedConnection::Invitee(sm_invitee) => sm_invitee.get_thread_id(), - } - } - - pub fn get_state(&self) -> MediatedConnectionState { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => { - MediatedConnectionState::Inviter(sm_inviter.get_state()) - } - SmMediatedConnection::Invitee(sm_invitee) => { - MediatedConnectionState::Invitee(sm_invitee.get_state()) - } - } - } - - pub fn pairwise_info(&self) -> &PairwiseInfo { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => sm_inviter.pairwise_info(), - SmMediatedConnection::Invitee(sm_invitee) => sm_invitee.pairwise_info(), - } - } - - pub fn cloud_agent_info(&self) -> Option { - self.cloud_agent_info.clone() - } - - pub fn remote_did(&self) -> VcxResult { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => sm_inviter.remote_did(), - SmMediatedConnection::Invitee(sm_invitee) => sm_invitee.remote_did(), - } - } - - pub fn remote_vk(&self) -> VcxResult { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => sm_inviter.remote_vk(), - SmMediatedConnection::Invitee(sm_invitee) => sm_invitee.remote_vk(), - } - } - - pub fn state_object(&self) -> SmConnectionState { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => { - SmConnectionState::Inviter(sm_inviter.state_object().clone()) - } - SmMediatedConnection::Invitee(sm_invitee) => { - SmConnectionState::Invitee(sm_invitee.state_object().clone()) - } - } - } - - pub fn get_source_id(&self) -> String { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => sm_inviter.source_id(), - SmMediatedConnection::Invitee(sm_invitee) => sm_invitee.source_id(), - } - .to_string() - } - - pub fn their_did_doc(&self) -> Option { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => sm_inviter.their_did_doc(), - SmMediatedConnection::Invitee(sm_invitee) => sm_invitee.their_did_doc(), - } - } - - pub fn bootstrap_did_doc(&self) -> Option { - match &self.connection_sm { - SmMediatedConnection::Inviter(_sm_inviter) => None, /* TODO: Inviter can remember - * bootstrap */ - // agent too, but we don't need it - SmMediatedConnection::Invitee(sm_invitee) => sm_invitee.bootstrap_did_doc(), - } - } - - pub fn is_in_null_state(&self) -> bool { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => sm_inviter.is_in_null_state(), - SmMediatedConnection::Invitee(sm_invitee) => sm_invitee.is_in_null_state(), - } - } - - pub fn is_in_final_state(&self) -> bool { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => sm_inviter.is_in_final_state(), - SmMediatedConnection::Invitee(sm_invitee) => sm_invitee.is_in_final_state(), - } - } - - pub fn process_invite(&mut self, invitation: AnyInvitation) -> VcxResult<()> { - trace!( - "MediatedConnection::process_invite >>> invitation: {:?}", - invitation - ); - self.connection_sm = match &self.connection_sm { - SmMediatedConnection::Inviter(_sm_inviter) => { - return Err(AriesVcxError::from_msg( - AriesVcxErrorKind::NotReady, - "Invalid action", - )); - } - SmMediatedConnection::Invitee(sm_invitee) => { - SmMediatedConnection::Invitee(sm_invitee.clone().handle_invitation(invitation)?) - } - }; - Ok(()) - } - - pub async fn process_request( - &mut self, - wallet: &impl BaseWallet, - agency_client: &AgencyClient, - request: Request, - ) -> VcxResult<()> { - trace!( - "MediatedConnection::process_request >>> request: {:?}", - request - ); - let (connection_sm, new_cloud_agent_info) = match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => { - let send_message = self.send_message_closure_connection(wallet); - let new_pairwise_info = PairwiseInfo::create(wallet).await?; - let new_cloud_agent = - CloudAgentInfo::create(agency_client, &new_pairwise_info).await?; - let new_routing_keys = new_cloud_agent.routing_keys(agency_client)?; - let new_service_endpoint = agency_client.get_agency_url_full()?; - ( - SmMediatedConnection::Inviter( - sm_inviter - .clone() - .handle_connection_request( - wallet, - request, - &new_pairwise_info, - new_routing_keys, - new_service_endpoint, - send_message, - ) - .await?, - ), - new_cloud_agent, - ) - } - SmMediatedConnection::Invitee(_) => { - return Err(AriesVcxError::from_msg( - AriesVcxErrorKind::NotReady, - "Invalid action", - )); - } - }; - self.connection_sm = connection_sm; - self.cloud_agent_info = Some(new_cloud_agent_info); - Ok(()) - } - - pub async fn send_response(&mut self, wallet: &impl BaseWallet) -> VcxResult<()> { - trace!("MediatedConnection::send_response >>>"); - let connection_sm = match self.connection_sm.clone() { - SmMediatedConnection::Inviter(sm_inviter) => { - if let MediatedInviterFullState::Requested(_) = sm_inviter.state_object() { - let send_message = self.send_message_closure_connection(wallet); - sm_inviter.handle_send_response(send_message).await? - } else { - return Err(AriesVcxError::from_msg( - AriesVcxErrorKind::NotReady, - "Invalid action", - )); - } - } - SmMediatedConnection::Invitee(_) => { - return Err(AriesVcxError::from_msg( - AriesVcxErrorKind::NotReady, - "Invalid action", - )); - } - }; - self.connection_sm = SmMediatedConnection::Inviter(connection_sm); - Ok(()) - } - - pub fn get_invite_details(&self) -> Option<&AnyInvitation> { - trace!("MediatedConnection::get_invite_details >>>"); - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => sm_inviter.get_invitation(), - SmMediatedConnection::Invitee(_sm_invitee) => None, - } - } - - fn find_message_to_update_state( - &self, - messages: HashMap, - ) -> Option<(String, AriesMessage)> { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => { - sm_inviter.find_message_to_update_state(messages) - } - SmMediatedConnection::Invitee(sm_invitee) => { - sm_invitee.find_message_to_update_state(messages) - } - } - } - - // TODO:::: check usage of this method in regards to profile usage - // TODO:::: check usage of this method in regards to profile usage - // TODO:::: check usage of this method in regards to profile usage - pub fn update_state_with_message<'a>( - &'a mut self, - wallet: &'a impl BaseWallet, - agency_client: AgencyClient, - message: Option, - ) -> BoxFuture<'a, VcxResult<()>> { - Box::pin(async move { - let (new_connection_sm, can_autohop) = match &self.connection_sm { - SmMediatedConnection::Inviter(_) => { - self.step_inviter(wallet, message, &agency_client).await? - } - SmMediatedConnection::Invitee(_) => self.step_invitee(wallet, message).await?, - }; - *self = new_connection_sm; - if can_autohop && self.autohop_enabled { - self.update_state_with_message(wallet, agency_client, None) - .await - } else { - Ok(()) - } - }) - } - - pub async fn find_and_handle_message( - &mut self, - wallet: &impl BaseWallet, - agency_client: &AgencyClient, - ) -> VcxResult<()> { - if !self.is_in_final_state() { - warn!( - "MediatedConnection::find_and_handle_message >> connection is not in final state, \ - skipping" - ); - return Ok(()); - } - let messages = self.get_messages_noauth(agency_client).await?; - if let Some((uid, message)) = self.find_message_to_handle(messages) { - self.handle_message(message, wallet).await?; - self.update_message_status(&uid, agency_client).await?; - }; - Ok(()) - } - - fn find_message_to_handle( - &self, - messages: HashMap, - ) -> Option<(String, AriesMessage)> { - for (uid, message) in messages { - match message { - AriesMessage::TrustPing(TrustPing::Ping(_)) - | AriesMessage::TrustPing(TrustPing::PingResponse(_)) - | AriesMessage::OutOfBand(OutOfBand::HandshakeReuse(_)) - | AriesMessage::OutOfBand(OutOfBand::HandshakeReuseAccepted(_)) => { - return Some((uid, message)) - } - _ => {} - } - } - None - } - - pub async fn handle_message( - &mut self, - message: AriesMessage, - wallet: &impl BaseWallet, - ) -> VcxResult<()> { - let did_doc = self.their_did_doc().ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NotReady, - format!( - "Can't answer message {message:?} because counterparty did doc is not available" - ), - ))?; - let pw_vk = &self.pairwise_info().pw_vk; - match message { - AriesMessage::TrustPing(TrustPing::Ping(ping)) => { - let thread_id = ping - .decorators - .thread - .as_ref() - .map(|t| t.thid.as_str()) - .unwrap_or(ping.id.as_str()); - - info!("Answering TrustPing::Ping, thread: {}", thread_id); - - if ping.content.response_requested { - send_message( - wallet, - pw_vk.to_string(), - did_doc.clone(), - build_ping_response(&ping).into(), - ) - .await?; - } - } - AriesMessage::OutOfBand(OutOfBand::HandshakeReuse(handshake_reuse)) => { - let thread_id = handshake_reuse.decorators.thread.thid.as_str(); - - info!( - "Answering OutOfBand::HandshakeReuse message, thread: {}", - thread_id - ); - - let msg = build_handshake_reuse_accepted_msg(&handshake_reuse)?; - send_message(wallet, pw_vk.to_string(), did_doc.clone(), msg.into()).await?; - } - _ => { - // todo: implement to_string for A2AMessage, printing only type of the message, not - // entire payload todo: attempt to print @id / thread_id of the - // message - info!("Message of type {:?} will not be answered", message); - } - } - Ok(()) - } - - pub async fn find_message_and_update_state( - &mut self, - wallet: &impl BaseWallet, - agency_client: &AgencyClient, - ) -> VcxResult<()> { - if self.is_in_null_state() { - warn!( - "MediatedConnection::update_state :: update state on connection in null state is \ - ignored" - ); - return Ok(()); - } - if self.is_in_final_state() { - warn!( - "MediatedConnection::update_state :: update state on connection in final state is \ - ignored" - ); - return Ok(()); - } - trace!( - "MediatedConnection::update_state >>> before update_state {:?}", - self.get_state() - ); - - let messages = self.get_messages_noauth(agency_client).await?; - trace!( - "MediatedConnection::update_state >>> retrieved messages {:?}", - messages - ); - - match self.find_message_to_update_state(messages) { - Some((uid, message)) => { - trace!( - "MediatedConnection::update_state >>> handling message uid: {:?}", - uid - ); - self.update_state_with_message(wallet, agency_client.clone(), Some(message)) - .await?; - self.cloud_agent_info() - .ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NoAgentInformation, - "Missing cloud agent info", - ))? - .update_message_status(agency_client, self.pairwise_info(), uid) - .await?; - } - None => { - trace!( - "MediatedConnection::update_state >>> trying to update state without message" - ); - self.update_state_with_message(wallet, agency_client.clone(), None) - .await?; - } - } - - trace!( - "MediatedConnection::update_state >>> after update_state {:?}", - self.get_state() - ); - Ok(()) - } - - async fn step_inviter( - &self, - wallet: &impl BaseWallet, - message: Option, - agency_client: &AgencyClient, - ) -> VcxResult<(Self, bool)> { - match self.connection_sm.clone() { - SmMediatedConnection::Inviter(sm_inviter) => { - let (sm_inviter, new_cloud_agent_info, can_autohop) = match message { - Some(message) => match message { - AriesMessage::Connection(Connection::Request(request)) => { - let send_message = self.send_message_closure_connection(wallet); - let new_pairwise_info = PairwiseInfo::create(wallet).await?; - let new_cloud_agent = - CloudAgentInfo::create(agency_client, &new_pairwise_info).await?; - let new_routing_keys = new_cloud_agent.routing_keys(agency_client)?; - let new_service_endpoint = - new_cloud_agent.service_endpoint(agency_client)?; - - let sm_connection = sm_inviter - .handle_connection_request( - wallet, - request, - &new_pairwise_info, - new_routing_keys, - new_service_endpoint, - send_message, - ) - .await?; - (sm_connection, Some(new_cloud_agent), true) - } - msg @ AriesMessage::Notification(_) - | msg @ AriesMessage::TrustPing(TrustPing::Ping(_)) => ( - sm_inviter.handle_confirmation_message(&msg).await?, - None, - false, - ), - AriesMessage::Connection(Connection::ProblemReport(problem_report)) => ( - sm_inviter.handle_problem_report(problem_report)?, - None, - false, - ), - _ => (sm_inviter.clone(), None, false), - }, - None => { - if let MediatedInviterFullState::Requested(_) = sm_inviter.state_object() { - let send_message = self.send_message_closure_connection(wallet); - ( - sm_inviter.handle_send_response(send_message).await?, - None, - false, - ) - } else { - (sm_inviter.clone(), None, false) - } - } - }; - - let connection = Self { - cloud_agent_info: new_cloud_agent_info.or(self.cloud_agent_info.clone()), - connection_sm: SmMediatedConnection::Inviter(sm_inviter), - autohop_enabled: self.autohop_enabled, - }; - - Ok((connection, can_autohop)) - } - SmMediatedConnection::Invitee(_) => Err(AriesVcxError::from_msg( - AriesVcxErrorKind::NotReady, - "Invalid operation, called _step_inviter on Invitee connection.", - )), - } - } - - async fn step_invitee( - &self, - wallet: &impl BaseWallet, - message: Option, - ) -> VcxResult<(Self, bool)> { - match self.connection_sm.clone() { - SmMediatedConnection::Invitee(sm_invitee) => { - let (sm_invitee, can_autohop) = match message { - Some(message) => match message { - AriesMessage::Connection(Connection::Invitation(invitation)) - if matches!(invitation.content, InvitationContent::Public(_)) => - { - ( - sm_invitee.handle_invitation(AnyInvitation::Con(invitation))?, - false, - ) - } - AriesMessage::Connection(Connection::Invitation(invitation)) - if matches!(invitation.content, InvitationContent::Pairwise(_)) => - { - ( - sm_invitee.handle_invitation(AnyInvitation::Con(invitation))?, - false, - ) - } - AriesMessage::Connection(Connection::Response(response)) => { - let send_message = self.send_message_closure_connection(wallet); - ( - sm_invitee - .handle_connection_response(wallet, response, send_message) - .await?, - true, - ) - } - AriesMessage::Connection(Connection::ProblemReport(problem_report)) => { - (sm_invitee.handle_problem_report(problem_report)?, false) - } - _ => (sm_invitee, false), - }, - None => { - let send_message = self.send_message_closure_connection(wallet); - (sm_invitee.handle_send_ack(send_message).await?, false) - } - }; - let connection = Self { - connection_sm: SmMediatedConnection::Invitee(sm_invitee), - cloud_agent_info: self.cloud_agent_info.clone(), - autohop_enabled: self.autohop_enabled, - }; - Ok((connection, can_autohop)) - } - SmMediatedConnection::Inviter(_) => Err(AriesVcxError::from_msg( - AriesVcxErrorKind::NotReady, - "Invalid operation, called _step_invitee on Inviter connection.", - )), - } - } - - pub async fn connect<'a, 'b>( - &'a mut self, - wallet: &'b impl BaseWallet, - agency_client: &AgencyClient, - send_message: Option>, - ) -> VcxResult<()> - where - 'a: 'b, - { - trace!( - "MediatedConnection::connect >>> source_id: {}", - self.source_id() - ); - let cloud_agent_info = self - .cloud_agent_info - .clone() - .ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NoAgentInformation, - "Missing cloud agent info", - ))?; - let sm = match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => { - SmMediatedConnection::Inviter(sm_inviter.clone().create_invitation( - cloud_agent_info.routing_keys(agency_client)?, - cloud_agent_info.service_endpoint(agency_client)?, - )?) - } - SmMediatedConnection::Invitee(sm_invitee) => { - let send_message = - send_message.unwrap_or(self.send_message_closure_connection(wallet)); - - SmMediatedConnection::Invitee( - sm_invitee - .clone() - .send_connection_request( - cloud_agent_info.routing_keys(agency_client)?, - cloud_agent_info.service_endpoint(agency_client)?, - send_message, - ) - .await?, - ) - } - }; - - self.connection_sm = sm; - Ok(()) - } - - pub async fn update_message_status( - &self, - uid: &str, - agency_client: &AgencyClient, - ) -> VcxResult<()> { - trace!( - "MediatedConnection::update_message_status >>> uid: {:?}", - uid - ); - self.cloud_agent_info() - .ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NoAgentInformation, - "Missing cloud agent info", - ))? - .update_message_status(agency_client, self.pairwise_info(), uid.to_string()) - .await - } - - pub async fn get_messages_noauth( - &self, - agency_client: &AgencyClient, - ) -> VcxResult> { - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => { - let messages = self - .cloud_agent_info() - .ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NoAgentInformation, - "Missing cloud agent info", - ))? - .get_messages_noauth(agency_client, sm_inviter.pairwise_info(), None) - .await?; - Ok(messages) - } - SmMediatedConnection::Invitee(sm_invitee) => { - let messages = self - .cloud_agent_info() - .ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NoAgentInformation, - "Missing cloud agent info", - ))? - .get_messages_noauth(agency_client, sm_invitee.pairwise_info(), None) - .await?; - Ok(messages) - } - } - } - - pub async fn get_messages( - &self, - agency_client: &AgencyClient, - ) -> VcxResult> { - let expected_sender_vk = self.get_expected_sender_vk().await?; - match &self.connection_sm { - SmMediatedConnection::Inviter(sm_inviter) => Ok(self - .cloud_agent_info() - .ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NoAgentInformation, - "Missing cloud agent info", - ))? - .get_messages( - agency_client, - &expected_sender_vk, - sm_inviter.pairwise_info(), - ) - .await?), - SmMediatedConnection::Invitee(sm_invitee) => Ok(self - .cloud_agent_info() - .ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NoAgentInformation, - "Missing cloud agent info", - ))? - .get_messages( - agency_client, - &expected_sender_vk, - sm_invitee.pairwise_info(), - ) - .await?), - } - } - - async fn get_expected_sender_vk(&self) -> VcxResult { - self.remote_vk().map_err(|_err| { - AriesVcxError::from_msg( - AriesVcxErrorKind::NotReady, - "Verkey of Connection counterparty is not known, hence it would be impossible to \ - authenticate message downloaded by id.", - ) - }) - } - - pub async fn get_message_by_id( - &self, - msg_id: &str, - agency_client: &AgencyClient, - ) -> VcxResult { - trace!( - "MediatedConnection: get_message_by_id >>> msg_id: {}", - msg_id - ); - let expected_sender_vk = self.get_expected_sender_vk().await?; - self.cloud_agent_info() - .ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NoAgentInformation, - "Missing cloud agent info", - ))? - .get_message_by_id( - agency_client, - msg_id, - &expected_sender_vk, - self.pairwise_info(), - ) - .await - } - - pub async fn send_message_closure<'a>( - &self, - wallet: &'a impl BaseWallet, - ) -> VcxResult> { - trace!("send_message_closure >>>"); - let did_doc = self.their_did_doc().ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NotReady, - "Cannot send message: Remote Connection information is not set", - ))?; - let sender_vk = self.pairwise_info().pw_vk.clone(); - Ok(Box::new(move |message: AriesMessage| { - Box::pin(send_message(wallet, sender_vk.clone(), did_doc, message)) - })) - } - - fn send_message_closure_connection<'a>( - &self, - wallet: &'a impl BaseWallet, - ) -> SendClosureConnection<'a> { - trace!("send_message_closure_connection >>>"); - Box::new( - move |message: AriesMessage, sender_vk: String, did_doc: AriesDidDoc| { - Box::pin(send_message(wallet, sender_vk, did_doc, message)) - }, - ) - } - - fn build_basic_message(message: &str) -> AriesMessage { - match ::serde_json::from_str::(message) { - Ok(a2a_message) => a2a_message, - Err(_) => { - let now = Utc::now(); - - let content = BasicMessageContent::builder() - .content(message.to_owned()) - .sent_time(now) - .build(); - - let decorators = BasicMessageDecorators::builder() - .timing(Timing::builder().out_time(now).build()) - .build(); - - BasicMessage::builder() - .id(Uuid::new_v4().to_string()) - .content(content) - .decorators(decorators) - .build() - } - } - } - - pub async fn send_generic_message( - &self, - wallet: &impl BaseWallet, - message: &str, - ) -> VcxResult { - trace!( - "MediatedConnection::send_generic_message >>> message: {:?}", - message - ); - let message = Self::build_basic_message(message); - let send_message = self.send_message_closure(wallet).await?; - send_message(message).await.map(|_| String::new()) - } - - pub async fn send_a2a_message( - &self, - wallet: &impl BaseWallet, - message: &AriesMessage, - ) -> VcxResult { - trace!( - "MediatedConnection::send_a2a_message >>> message: {:?}", - message - ); - let send_message = self.send_message_closure(wallet).await?; - send_message(message.clone()).await.map(|_| String::new()) - } - - pub async fn send_ping( - &mut self, - wallet: &impl BaseWallet, - comment: Option, - ) -> VcxResult { - let mut trust_ping = TrustPingSender::build(true, comment); - trust_ping - .send_ping(self.send_message_closure(wallet).await?) - .await?; - Ok(trust_ping) - } - - pub async fn send_handshake_reuse( - &self, - wallet: &impl BaseWallet, - oob_msg: &str, - ) -> VcxResult<()> { - trace!("MediatedConnection::send_handshake_reuse >>>"); - // todo: oob_msg argument should be typed OutOfBandInvitation, not string - let oob = match serde_json::from_str::(oob_msg) { - Ok(a2a_msg) => match a2a_msg { - AriesMessage::OutOfBand(OutOfBand::Invitation(oob)) => oob, - a => { - return Err(AriesVcxError::from_msg( - AriesVcxErrorKind::SerializationError, - format!("Received invalid message type: {:?}", a), - )); - } - }, - Err(err) => { - return Err(AriesVcxError::from_msg( - AriesVcxErrorKind::SerializationError, - format!("Failed to deserialize message, err: {:?}", err), - )); - } - }; - let send_message = self.send_message_closure(wallet).await?; - send_message(build_handshake_reuse_msg(&oob).into()).await - } - - pub async fn delete(&self, agency_client: &AgencyClient) -> VcxResult<()> { - trace!("Connection: delete >>> {:?}", self.source_id()); - self.cloud_agent_info() - .ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NoAgentInformation, - "Missing cloud agent info", - ))? - .destroy(agency_client, self.pairwise_info()) - .await - } - - pub async fn get_connection_info(&self, agency_client: &AgencyClient) -> VcxResult { - trace!("MediatedConnection::get_connection_info >>>"); - - let agent_info = self.cloud_agent_info().ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NoAgentInformation, - "Missing cloud agent info", - ))?; - let pairwise_info = self.pairwise_info(); - let recipient_keys = vec![pairwise_info.pw_vk.clone()]; - - let current = SideDetails { - did: pairwise_info.pw_did.clone(), - recipient_keys, - routing_keys: agent_info.routing_keys(agency_client)?, - service_endpoint: agent_info.service_endpoint(agency_client)?, - }; - - let remote = match self.their_did_doc() { - Some(did_doc) => Some(SideDetails { - did: did_doc.id.clone(), - recipient_keys: did_doc.recipient_keys()?, - routing_keys: did_doc.routing_keys(), - service_endpoint: did_doc.get_endpoint().ok_or_else(|| { - AriesVcxError::from_msg(AriesVcxErrorKind::InvalidUrl, "No URL in DID Doc") - })?, - }), - None => None, - }; - - let connection_info = ConnectionInfo { - my: current, - their: remote, - }; - - let connection_info_json = serde_json::to_string(&connection_info).map_err(|err| { - AriesVcxError::from_msg( - AriesVcxErrorKind::InvalidState, - format!("Cannot serialize ConnectionInfo: {:?}", err), - ) - })?; - - Ok(connection_info_json) - } - - pub async fn download_messages( - &self, - agency_client: &AgencyClient, - status_codes: Option>, - uids: Option>, - ) -> VcxResult> { - match self.get_state() { - MediatedConnectionState::Invitee(MediatedInviteeState::Initial) - | MediatedConnectionState::Invitee(MediatedInviteeState::Requested) - | MediatedConnectionState::Inviter(MediatedInviterState::Initial) - | MediatedConnectionState::Inviter(MediatedInviterState::Invited) => { - let msgs = futures::stream::iter( - self.cloud_agent_info() - .ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NoAgentInformation, - "Missing cloud agent info", - ))? - .download_encrypted_messages( - agency_client, - uids, - status_codes, - self.pairwise_info(), - ) - .await?, - ) - .then(|msg| msg.decrypt_noauth(agency_client.get_wallet())) - .filter_map(|res| async { res.ok() }) - .collect::>() - .await; - Ok(msgs) - } - _ => { - let expected_sender_vk = self.remote_vk()?; - let msgs = futures::stream::iter( - self.cloud_agent_info() - .ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::NoAgentInformation, - "Missing cloud agent info", - ))? - .download_encrypted_messages( - agency_client, - uids, - status_codes, - self.pairwise_info(), - ) - .await?, - ) - .then(|msg| msg.decrypt_auth(agency_client.get_wallet(), &expected_sender_vk)) - .filter_map(|res| async { res.ok() }) - .collect::>() - .await; - Ok(msgs) - } - } - } - - pub fn to_string(&self) -> VcxResult { - serde_json::to_string(&self).map_err(|err| { - AriesVcxError::from_msg( - AriesVcxErrorKind::SerializationError, - format!("Cannot serialize Connection: {:?}", err), - ) - }) - } - - pub fn from_string(connection_data: &str) -> VcxResult { - serde_json::from_str(connection_data).map_err(|err| { - AriesVcxError::from_msg( - AriesVcxErrorKind::InvalidJson, - format!("Cannot deserialize Connection: {:?}", err), - ) - }) - } -} - -impl Serialize for MediatedConnection { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let (state, pairwise_info, cloud_agent_info, source_id, thread_id) = self.to_owned().into(); - let CloudAgentInfo { - agent_did, - agent_vk, - } = cloud_agent_info.unwrap_or_default(); - let data = LegacyAgentInfo { - pw_did: pairwise_info.pw_did, - pw_vk: pairwise_info.pw_vk, - agent_did, - agent_vk, - }; - let object = SerializableObjectWithState::V1 { - data, - state, - source_id, - thread_id, - }; - serializer.serialize_some(&object) - } -} - -struct ConnectionVisitor; - -impl<'de> Visitor<'de> for ConnectionVisitor { - type Value = MediatedConnection; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("serialized Connection object") - } - - fn visit_map(self, mut map: A) -> Result>::Error> - where - A: MapAccess<'de>, - { - let mut map_value = serde_json::Map::new(); - while let Some(key) = map.next_key()? { - let k: String = key; - let v: Value = map.next_value()?; - map_value.insert(k, v); - } - let obj = Value::from(map_value); - let ver: SerializableObjectWithState = - serde_json::from_value(obj).map_err(|err| A::Error::custom(err.to_string()))?; - match ver { - SerializableObjectWithState::V1 { - data, - state, - source_id, - thread_id, - } => { - let pairwise_info = PairwiseInfo { - pw_did: data.pw_did, - pw_vk: data.pw_vk, - }; - let cloud_agent_info = CloudAgentInfo { - agent_did: data.agent_did, - agent_vk: data.agent_vk, - }; - Ok(( - state, - pairwise_info, - Some(cloud_agent_info), - source_id, - thread_id, - ) - .into()) - } - } - } -} - -impl<'de> Deserialize<'de> for MediatedConnection { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - deserializer.deserialize_map(ConnectionVisitor) - } -} - -impl From - for ( - SmConnectionState, - PairwiseInfo, - Option, - String, - String, - ) -{ - fn from( - s: MediatedConnection, - ) -> ( - SmConnectionState, - PairwiseInfo, - Option, - String, - String, - ) { - ( - s.state_object(), - s.pairwise_info().to_owned(), - s.cloud_agent_info(), - s.source_id(), - s.get_thread_id(), - ) - } -} - -impl - From<( - SmConnectionState, - PairwiseInfo, - Option, - String, - String, - )> for MediatedConnection -{ - fn from( - (state, pairwise_info, cloud_agent_info, source_id, thread_id): ( - SmConnectionState, - PairwiseInfo, - Option, - String, - String, - ), - ) -> MediatedConnection { - MediatedConnection::from_parts( - source_id, - thread_id, - pairwise_info, - cloud_agent_info, - state, - true, - ) - } -} diff --git a/aries/aries_vcx/src/handlers/mediated_connection/util.rs b/aries/aries_vcx/src/handlers/mediated_connection/util.rs deleted file mode 100644 index 0bc113e5a4..0000000000 --- a/aries/aries_vcx/src/handlers/mediated_connection/util.rs +++ /dev/null @@ -1,40 +0,0 @@ -use aries_vcx_core::wallet::base_wallet::BaseWallet; -use diddoc_legacy::aries::diddoc::AriesDidDoc; -use messages::AriesMessage; -use shared::http_client::post_message; - -use crate::{ - errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, - utils::encryption_envelope::EncryptionEnvelope, -}; - -pub async fn send_message( - wallet: &impl BaseWallet, - sender_verkey: String, - did_doc: AriesDidDoc, - message: AriesMessage, -) -> VcxResult<()> { - trace!( - "send_message >>> message: {:?}, did_doc: {:?}", - message, - &did_doc - ); - - let EncryptionEnvelope(envelope) = EncryptionEnvelope::create( - wallet, - json!(message).to_string().as_bytes(), - Some(&sender_verkey), - &did_doc, - ) - .await?; - - post_message( - envelope, - did_doc.get_endpoint().ok_or_else(|| { - AriesVcxError::from_msg(AriesVcxErrorKind::InvalidUrl, "No URL in DID Doc") - })?, - ) - .await?; - - Ok(()) -} diff --git a/aries/aries_vcx/src/handlers/mod.rs b/aries/aries_vcx/src/handlers/mod.rs index 1f48dc6476..1602d5b66d 100644 --- a/aries/aries_vcx/src/handlers/mod.rs +++ b/aries/aries_vcx/src/handlers/mod.rs @@ -1,5 +1,4 @@ pub mod issuance; -pub mod mediated_connection; pub mod out_of_band; pub mod proof_presentation; pub mod revocation_notification; diff --git a/aries/aries_vcx/src/handlers/revocation_notification/mod.rs b/aries/aries_vcx/src/handlers/revocation_notification/mod.rs index 6ee13905fb..8db13a2dbf 100644 --- a/aries/aries_vcx/src/handlers/revocation_notification/mod.rs +++ b/aries/aries_vcx/src/handlers/revocation_notification/mod.rs @@ -40,55 +40,3 @@ pub async fn send_revocation_notification( )) } } - -pub mod test_utils { - use agency_client::agency_client::AgencyClient; - use messages::{ - msg_fields::protocols::revocation::{ack::AckRevoke, revoke::Revoke, Revocation}, - AriesMessage, - }; - - use crate::{errors::error::prelude::*, handlers::mediated_connection::MediatedConnection}; - - pub async fn get_revocation_notification_messages( - agency_client: &AgencyClient, - connection: &MediatedConnection, - ) -> VcxResult> { - let mut messages = Vec::::new(); - for (uid, message) in connection - .get_messages_noauth(agency_client) - .await? - .into_iter() - { - if let AriesMessage::Revocation(Revocation::Revoke(message)) = message { - connection - .update_message_status(&uid, agency_client) - .await - .ok(); - messages.push(message); - } - } - Ok(messages) - } - - pub async fn get_revocation_notification_ack_messages( - agency_client: &AgencyClient, - connection: &MediatedConnection, - ) -> VcxResult> { - let mut messages = Vec::::new(); - for (uid, message) in connection - .get_messages_noauth(agency_client) - .await? - .into_iter() - { - if let AriesMessage::Revocation(Revocation::Ack(message)) = message { - connection - .update_message_status(&uid, agency_client) - .await - .ok(); - messages.push(message); - } - } - Ok(messages) - } -} diff --git a/aries/aries_vcx/src/handlers/revocation_notification/receiver.rs b/aries/aries_vcx/src/handlers/revocation_notification/receiver.rs index a97efe3c10..74827dcc9b 100644 --- a/aries/aries_vcx/src/handlers/revocation_notification/receiver.rs +++ b/aries/aries_vcx/src/handlers/revocation_notification/receiver.rs @@ -24,14 +24,10 @@ impl RevocationNotificationReceiver { self.receiver_sm.get_thread_id() } - pub async fn handle_revocation_notification( - self, - notification: Revoke, - send_message: SendClosure<'_>, - ) -> VcxResult { + pub async fn handle_revocation_notification(self, notification: Revoke) -> VcxResult { let receiver_sm = self .receiver_sm - .handle_revocation_notification(notification, send_message) + .handle_revocation_notification(notification) .await?; Ok(Self { receiver_sm }) } diff --git a/aries/aries_vcx/src/lib.rs b/aries/aries_vcx/src/lib.rs index 27f586e805..ed7cf1da3a 100644 --- a/aries/aries_vcx/src/lib.rs +++ b/aries/aries_vcx/src/lib.rs @@ -4,8 +4,6 @@ //this is needed for some large json macro invocations #![recursion_limit = "128"] -pub extern crate agency_client; - #[macro_use] extern crate lazy_static; diff --git a/aries/aries_vcx/src/protocols/revocation_notification/receiver/state_machine.rs b/aries/aries_vcx/src/protocols/revocation_notification/receiver/state_machine.rs index f8c80e60b3..2c3c78239d 100644 --- a/aries/aries_vcx/src/protocols/revocation_notification/receiver/state_machine.rs +++ b/aries/aries_vcx/src/protocols/revocation_notification/receiver/state_machine.rs @@ -67,11 +67,7 @@ impl RevocationNotificationReceiverSM { } } - pub async fn handle_revocation_notification( - self, - notification: Revoke, - send_message: SendClosure<'_>, - ) -> VcxResult { + pub async fn handle_revocation_notification(self, notification: Revoke) -> VcxResult { let state = match self.state { ReceiverFullState::Initial(_) => { self.validate_revocation_notification(¬ification)?; @@ -81,37 +77,13 @@ impl RevocationNotificationReceiverSM { .as_ref() .map(|d| d.on.is_empty()) .unwrap_or(false) - { - ReceiverFullState::Finished(FinishedState::new(notification)) - } else if notification - .decorators - .please_ack - .as_ref() - .map(|d| d.on.contains(&AckOn::Receipt)) - .unwrap_or(false) - { - let id = Uuid::new_v4().to_string(); - let content = AckContent::builder().status(AckStatus::Ok).build(); - - let thread_id = notification + || notification .decorators - .thread + .please_ack .as_ref() - .map(|t| t.thid.clone()) - .unwrap_or(notification.id.clone()); - - let decorators = AckDecorators::builder() - .thread(Thread::builder().thid(thread_id).build()) - .timing(Timing::builder().out_time(Utc::now()).build()) - .build(); - - let ack = AckRevoke::builder() - .id(id) - .content(content) - .decorators(decorators) - .build(); - - send_message(ack).await?; + .map(|d| d.on.contains(&AckOn::Receipt)) + .unwrap_or(false) + { ReceiverFullState::Finished(FinishedState::new(notification)) } else { ReceiverFullState::NotificationReceived(NotificationReceivedState::new( diff --git a/aries/aries_vcx/src/utils/encryption_envelope.rs b/aries/aries_vcx/src/utils/encryption_envelope.rs index d4e7d16efc..cca14f4724 100644 --- a/aries/aries_vcx/src/utils/encryption_envelope.rs +++ b/aries/aries_vcx/src/utils/encryption_envelope.rs @@ -1,5 +1,4 @@ -use agency_client::testing::mocking::AgencyMockDecrypted; -use aries_vcx_core::{global::settings::VERKEY, wallet::base_wallet::BaseWallet}; +use aries_vcx_core::wallet::base_wallet::BaseWallet; use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::{ msg_fields::protocols::routing::{Forward, ForwardContent}, @@ -170,17 +169,7 @@ impl EncryptionEnvelope { "EncryptionEnvelope::anon_unpack >>> processing payload of {} bytes", encrypted_data.len() ); - let (message, sender_vk) = if AgencyMockDecrypted::has_decrypted_mock_messages() { - trace!("EncryptionEnvelope::anon_unpack >>> returning decrypted mock message"); - ( - AgencyMockDecrypted::get_next_decrypted_message(), - Some(VERKEY.to_string()), - ) - } else { - Self::_unpack_a2a_message(wallet, encrypted_data).await? - }; - - Ok((message, sender_vk)) + Self::_unpack_a2a_message(wallet, encrypted_data).await } pub async fn auth_unpack_aries_msg( @@ -209,47 +198,39 @@ impl EncryptionEnvelope { expected_vk ); - let message = if AgencyMockDecrypted::has_decrypted_mock_messages() { - trace!("EncryptionEnvelope::auth_unpack >>> returning decrypted mock message"); - AgencyMockDecrypted::get_next_decrypted_message() - } else { - let (a2a_message, sender_vk) = - Self::_unpack_a2a_message(wallet, encrypted_data).await?; - trace!( - "anon_unpack >> a2a_msg: {:?}, sender_vk: {:?}", - a2a_message, - sender_vk - ); + let (a2a_message, sender_vk) = Self::_unpack_a2a_message(wallet, encrypted_data).await?; + trace!( + "anon_unpack >> a2a_msg: {:?}, sender_vk: {:?}", + a2a_message, + sender_vk + ); - match sender_vk { - Some(sender_vk) => { - if sender_vk != expected_vk { - error!( - "auth_unpack sender_vk != expected_vk.... sender_vk: {}, \ - expected_vk: {}", - sender_vk, expected_vk - ); - return Err(AriesVcxError::from_msg( - AriesVcxErrorKind::AuthenticationError, - format!( - "Message did not pass authentication check. Expected sender \ - verkey was {}, but actually was {}", - expected_vk, sender_vk - ), - )); - } - } - None => { - error!("auth_unpack message was authcrypted"); + match sender_vk { + Some(sender_vk) => { + if sender_vk != expected_vk { + error!( + "auth_unpack sender_vk != expected_vk.... sender_vk: {}, expected_vk: {}", + sender_vk, expected_vk + ); return Err(AriesVcxError::from_msg( AriesVcxErrorKind::AuthenticationError, - "Can't authenticate message because it was anoncrypted.", + format!( + "Message did not pass authentication check. Expected sender verkey \ + was {}, but actually was {}", + expected_vk, sender_vk + ), )); } } - a2a_message - }; - Ok(message) + None => { + error!("auth_unpack message was authcrypted"); + return Err(AriesVcxError::from_msg( + AriesVcxErrorKind::AuthenticationError, + "Can't authenticate message because it was anoncrypted.", + )); + } + } + Ok(a2a_message) } } diff --git a/aries/aries_vcx_core/Cargo.toml b/aries/aries_vcx_core/Cargo.toml index ccfb4e3b5c..9b37410e86 100644 --- a/aries/aries_vcx_core/Cargo.toml +++ b/aries/aries_vcx_core/Cargo.toml @@ -16,7 +16,6 @@ legacy_proof = [] askar_wallet = ["dep:aries-askar", "dep:bs58"] [dependencies] -agency_client = { path = "../misc/legacy/agency_client" } aries-askar = { version = "=0.3.0", optional = true } bs58 = { version = "0.5", optional = true } indy-vdr = { git = "https://github.com/hyperledger/indy-vdr.git", rev = "c143268", default-features = false, features = ["log"] } diff --git a/aries/aries_vcx_core/src/errors/mapping_agency_client.rs b/aries/aries_vcx_core/src/errors/mapping_agency_client.rs deleted file mode 100644 index fc03030d51..0000000000 --- a/aries/aries_vcx_core/src/errors/mapping_agency_client.rs +++ /dev/null @@ -1,38 +0,0 @@ -use agency_client::errors::error::{AgencyClientError, AgencyClientErrorKind}; - -use crate::errors::error::{AriesVcxCoreError, AriesVcxCoreErrorKind}; - -impl From for AriesVcxCoreError { - fn from(agency_err: AgencyClientError) -> AriesVcxCoreError { - let vcx_error_kind: AriesVcxCoreErrorKind = agency_err.kind().into(); - AriesVcxCoreError::from_msg(vcx_error_kind, agency_err.to_string()) - } -} - -impl From for AriesVcxCoreErrorKind { - fn from(agency_err: AgencyClientErrorKind) -> AriesVcxCoreErrorKind { - match agency_err { - AgencyClientErrorKind::InvalidState => AriesVcxCoreErrorKind::InvalidState, - AgencyClientErrorKind::InvalidConfiguration => { - AriesVcxCoreErrorKind::InvalidConfiguration - } - AgencyClientErrorKind::InvalidJson => AriesVcxCoreErrorKind::InvalidJson, - AgencyClientErrorKind::InvalidOption => AriesVcxCoreErrorKind::InvalidOption, - AgencyClientErrorKind::InvalidMessagePack => AriesVcxCoreErrorKind::InvalidMessagePack, - AgencyClientErrorKind::IOError => AriesVcxCoreErrorKind::IOError, - AgencyClientErrorKind::PostMessageFailed => AriesVcxCoreErrorKind::PostMessageFailed, - AgencyClientErrorKind::InvalidWalletHandle => { - AriesVcxCoreErrorKind::InvalidWalletHandle - } - AgencyClientErrorKind::UnknownError => AriesVcxCoreErrorKind::UnknownError, - AgencyClientErrorKind::InvalidDid => AriesVcxCoreErrorKind::InvalidDid, - AgencyClientErrorKind::InvalidVerkey => AriesVcxCoreErrorKind::InvalidVerkey, - AgencyClientErrorKind::InvalidUrl => AriesVcxCoreErrorKind::InvalidUrl, - AgencyClientErrorKind::SerializationError => AriesVcxCoreErrorKind::SerializationError, - AgencyClientErrorKind::NotBase58 => AriesVcxCoreErrorKind::NotBase58, - AgencyClientErrorKind::InvalidHttpResponse => { - AriesVcxCoreErrorKind::InvalidHttpResponse - } - } - } -} diff --git a/aries/aries_vcx_core/src/errors/mod.rs b/aries/aries_vcx_core/src/errors/mod.rs index e9dee3a39b..3b4eb4b4b8 100644 --- a/aries/aries_vcx_core/src/errors/mod.rs +++ b/aries/aries_vcx_core/src/errors/mod.rs @@ -1,5 +1,4 @@ pub mod error; -mod mapping_agency_client; #[cfg(feature = "anoncreds")] mod mapping_anoncreds; #[cfg(feature = "askar_wallet")] diff --git a/aries/aries_vcx_core/src/wallet/agency_client_wallet.rs b/aries/aries_vcx_core/src/wallet/agency_client_wallet.rs deleted file mode 100644 index cd8dfbd26b..0000000000 --- a/aries/aries_vcx_core/src/wallet/agency_client_wallet.rs +++ /dev/null @@ -1,275 +0,0 @@ -use std::sync::Arc; - -use agency_client::{ - errors::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}, - wallet::base_agency_client_wallet::BaseAgencyClientWallet, -}; -use async_trait::async_trait; -use public_key::{Key, KeyType}; - -use super::{ - base_wallet::{ - did_data::DidData, - did_wallet::DidWallet, - issuer_config::IssuerConfig, - record::{AllRecords, Record}, - record_category::RecordCategory, - record_wallet::RecordWallet, - search_filter::SearchFilter, - BaseWallet, - }, - record_tags::RecordTags, - structs_io::UnpackMessageOutput, -}; -use crate::errors::error::{AriesVcxCoreError, AriesVcxCoreErrorKind, VcxCoreResult}; - -#[derive(Debug)] -pub struct AgencyClientWallet { - inner: Arc, -} - -#[allow(unused_variables)] -#[async_trait] -impl BaseWallet for AgencyClientWallet { - async fn export_wallet(&self, path: &str, backup_key: &str) -> VcxCoreResult<()> { - Err(unimplemented_agency_client_wallet_method("export_wallet")) - } - - async fn close_wallet(&self) -> VcxCoreResult<()> { - Err(unimplemented_agency_client_wallet_method("close_wallet")) - } - - async fn configure_issuer(&self, key_seed: &str) -> VcxCoreResult { - Err(unimplemented_agency_client_wallet_method( - "configure_issuer", - )) - } -} - -#[allow(unused_variables)] -#[async_trait] -impl RecordWallet for AgencyClientWallet { - async fn all_records(&self) -> VcxCoreResult> { - Err(unimplemented_agency_client_wallet_method("get_all")) - } - - async fn add_record(&self, record: Record) -> VcxCoreResult<()> { - Err(unimplemented_agency_client_wallet_method("add_record")) - } - - async fn get_record(&self, category: RecordCategory, name: &str) -> VcxCoreResult { - Err(unimplemented_agency_client_wallet_method("get_record")) - } - - async fn update_record_tags( - &self, - category: RecordCategory, - name: &str, - new_tags: RecordTags, - ) -> VcxCoreResult<()> { - Err(unimplemented_agency_client_wallet_method( - "update_record_tags", - )) - } - - async fn update_record_value( - &self, - category: RecordCategory, - name: &str, - new_value: &str, - ) -> VcxCoreResult<()> { - Err(unimplemented_agency_client_wallet_method( - "update_record_value", - )) - } - - async fn delete_record(&self, category: RecordCategory, name: &str) -> VcxCoreResult<()> { - Err(unimplemented_agency_client_wallet_method("delete_record")) - } - - async fn search_record( - &self, - category: RecordCategory, - search_filter: Option, - ) -> VcxCoreResult> { - Err(unimplemented_agency_client_wallet_method("search_record")) - } -} - -#[async_trait] -#[allow(unused_variables)] -impl DidWallet for AgencyClientWallet { - async fn create_and_store_my_did( - &self, - seed: Option<&str>, - method_name: Option<&str>, - ) -> VcxCoreResult { - Err(unimplemented_agency_client_wallet_method( - "create_and_store_my_did", - )) - } - - async fn key_count(&self) -> VcxCoreResult { - Err(unimplemented_agency_client_wallet_method("key_count")) - } - - async fn key_for_did(&self, name: &str) -> VcxCoreResult { - Err(unimplemented_agency_client_wallet_method("key_for_did")) - } - - async fn replace_did_key_start(&self, did: &str, seed: Option<&str>) -> VcxCoreResult { - Err(unimplemented_agency_client_wallet_method( - "replace_did_key_start", - )) - } - - async fn replace_did_key_apply(&self, did: &str) -> VcxCoreResult<()> { - Err(unimplemented_agency_client_wallet_method( - "replace_did_key_apply", - )) - } - - async fn sign(&self, key: &Key, msg: &[u8]) -> VcxCoreResult> { - Err(unimplemented_agency_client_wallet_method("sign")) - } - - async fn verify(&self, key: &Key, msg: &[u8], signature: &[u8]) -> VcxCoreResult { - Err(unimplemented_agency_client_wallet_method("verify")) - } - - async fn pack_message( - &self, - sender_vk: Option, - receiver_keys: Vec, - msg: &[u8], - ) -> VcxCoreResult> { - let receiver_list: Vec = - receiver_keys.into_iter().map(|key| key.base58()).collect(); - - let list_json = serde_json::to_string(&receiver_list)?; - - let res = self - .inner - .pack_message( - sender_vk.map(|key| key.base58()).as_deref(), - &list_json, - msg, - ) - .await?; - - Ok(res) - } - - async fn unpack_message(&self, msg: &[u8]) -> VcxCoreResult { - let unpack_json_bytes = self.inner.unpack_message(msg).await?; - serde_json::from_slice(&unpack_json_bytes[..]).map_err(|err| { - AriesVcxCoreError::from_msg(AriesVcxCoreErrorKind::ParsingError, err.to_string()) - }) - } -} - -pub trait ToBaseWallet { - fn to_base_wallet(&self) -> AgencyClientWallet; -} - -impl ToBaseWallet for Arc { - fn to_base_wallet(&self) -> AgencyClientWallet { - AgencyClientWallet { - inner: Arc::clone(self), - } - } -} - -fn unimplemented_agency_client_wallet_method(method_name: &str) -> AriesVcxCoreError { - // should not occur with proper internal usage - [AgencyClientWallet] is not public - AriesVcxCoreError::from_msg( - AriesVcxCoreErrorKind::UnimplementedFeature, - format!("AgencyClientWallet::{method_name} is not intended to be used."), - ) -} - -#[derive(Debug)] -pub(crate) struct BaseWalletAgencyClientWallet { - inner: Arc, -} - -/// Implementation of [BaseAgencyClientWallet] which wraps over an [BaseWallet] implementation -/// to allow conversion -#[async_trait] -impl BaseAgencyClientWallet for BaseWalletAgencyClientWallet { - async fn pack_message( - &self, - sender_vk: Option<&str>, - receiver_keys: &str, - msg: &[u8], - ) -> AgencyClientResult> { - let receiver_list = serde_json::from_str::>(receiver_keys).map_err(|e| { - AgencyClientError::from_msg( - AgencyClientErrorKind::UnknownError, - format!("A VCXError occured while calling pack_message: {e:?}"), - ) - })?; - - let keys = receiver_list - .into_iter() - .map(|item| { - Key::from_base58(&item, KeyType::Ed25519).map_err(|e| { - AgencyClientError::from_msg( - AgencyClientErrorKind::NotBase58, - format!("Invalid receiver key: {e:?}"), - ) - }) - }) - .collect::, _>>()?; - - let sender_key = sender_vk - .map(|item| { - Key::from_base58(item, KeyType::Ed25519).map_err(|e| { - AgencyClientError::from_msg( - AgencyClientErrorKind::NotBase58, - format!("Invalid receiver key: {e:?}"), - ) - }) - }) - .transpose()?; - - self.inner - .pack_message(sender_key, keys, msg) - .await - .map_err(|e| { - AgencyClientError::from_msg( - AgencyClientErrorKind::UnknownError, - format!("A VCXError occured while calling pack_message: {e:?}"), - ) - }) - } - - async fn unpack_message(&self, msg: &[u8]) -> AgencyClientResult> { - let unpack = self.inner.unpack_message(msg).await.map_err(|e| { - AgencyClientError::from_msg( - AgencyClientErrorKind::UnknownError, - format!("A VCXError occured while calling unpack_message: {e:?}"), - ) - })?; - serde_json::to_vec(&unpack).map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::UnknownError, - format!("A VCXError occured while calling unpack_message: {err:?}"), - ) - }) - } -} - -pub trait ToBaseAgencyClientWallet { - fn to_base_agency_client_wallet(&self) -> Arc; -} - -impl ToBaseAgencyClientWallet for Arc -where - T: BaseWallet + 'static, -{ - fn to_base_agency_client_wallet(&self) -> Arc { - let x = self.clone(); - Arc::new(BaseWalletAgencyClientWallet { inner: x }) - } -} diff --git a/aries/aries_vcx_core/src/wallet/mod.rs b/aries/aries_vcx_core/src/wallet/mod.rs index 3615cdc99b..75bc9946be 100644 --- a/aries/aries_vcx_core/src/wallet/mod.rs +++ b/aries/aries_vcx_core/src/wallet/mod.rs @@ -1,4 +1,3 @@ -pub mod agency_client_wallet; #[cfg(feature = "askar_wallet")] pub mod askar; pub mod base_wallet; diff --git a/aries/misc/legacy/agency_client/Cargo.toml b/aries/misc/legacy/agency_client/Cargo.toml deleted file mode 100644 index d546dd3e33..0000000000 --- a/aries/misc/legacy/agency_client/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "agency_client" -version.workspace = true -authors.workspace = true -license.workspace = true -edition.workspace = true - -[lib] -doctest = false - -[dependencies] -env_logger = "0.9.0" -log = "0.4.16" -lazy_static = "1.3" -serde = "1.0.97" -serde_json = "1.0.40" -serde_derive = "1.0.97" -regex = "1.1.0" -url = { version = "2.3", features = ["serde"] } -uuid = { version = "0.8", default-features = false, features = ["v4"]} -thiserror = "1.0.37" -async-trait = "0.1.73" -shared = { path = "../../shared" } diff --git a/aries/misc/legacy/agency_client/src/agency_client.rs b/aries/misc/legacy/agency_client/src/agency_client.rs deleted file mode 100644 index 9b626a326b..0000000000 --- a/aries/misc/legacy/agency_client/src/agency_client.rs +++ /dev/null @@ -1,156 +0,0 @@ -use std::sync::Arc; - -use shared::validation::{did::validate_did, verkey::validate_verkey}; -use url::Url; - -use crate::{ - configuration::AgencyClientConfig, - errors::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}, - wallet::base_agency_client_wallet::{BaseAgencyClientWallet, StubAgencyClientWallet}, -}; - -#[derive(Clone, Debug)] -pub struct AgencyClient { - pub wallet: Arc, - pub agency_url: Url, - pub agency_did: String, - pub agency_vk: String, - pub agent_pwdid: String, - pub agent_vk: String, - pub my_pwdid: String, - pub my_vk: String, -} - -impl AgencyClient { - pub fn get_wallet(&self) -> Arc { - Arc::clone(&self.wallet) - } - - pub fn get_agency_url_full(&self) -> AgencyClientResult { - self.agency_url.join("agency/msg").map_err(|_| { - AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidUrl, - format!("Agency URL not valid: {}", self.agency_url), - ) - }) - } - pub(crate) fn get_agency_url_config(&self) -> Url { - self.agency_url.clone() - } - - pub fn get_agency_did(&self) -> String { - self.agency_did.clone() - } - pub fn get_agency_vk(&self) -> String { - self.agency_vk.clone() - } - - pub fn get_agent_pwdid(&self) -> String { - self.agent_pwdid.clone() - } - pub fn get_agent_vk(&self) -> String { - self.agent_vk.clone() - } - - pub fn get_my_vk(&self) -> String { - self.my_vk.clone() - } - - pub fn set_wallet(&mut self, wallet: Arc) { - self.wallet = wallet - } - - pub(crate) fn set_agency_url(&mut self, url: Url) { - self.agency_url = url; - } - pub(crate) fn set_agency_did(&mut self, did: &str) { - self.agency_did = did.to_string(); - } - pub(crate) fn set_agency_vk(&mut self, vk: &str) { - self.agency_vk = vk.to_string(); - } - pub(crate) fn set_agent_pwdid(&mut self, pwdid: &str) { - self.agent_pwdid = pwdid.to_string(); - } - pub(crate) fn set_agent_vk(&mut self, vk: &str) { - self.agent_vk = vk.to_string(); - } - pub(crate) fn set_my_pwdid(&mut self, pwdid: &str) { - self.my_pwdid = pwdid.to_string(); - } - pub(crate) fn set_my_vk(&mut self, vk: &str) { - self.my_vk = vk.to_string(); - } - - pub fn configure( - mut self, - wallet: Arc, - config: &AgencyClientConfig, - ) -> AgencyClientResult { - info!("AgencyClient::configure >>> config {:?}", config); - - validate_did(&config.agency_did)?; - validate_verkey(&config.agency_verkey)?; - validate_did(&config.sdk_to_remote_did)?; - validate_verkey(&config.sdk_to_remote_verkey)?; - validate_did(&config.remote_to_sdk_did)?; - validate_verkey(&config.remote_to_sdk_verkey)?; - - self.set_agency_url(config.agency_endpoint.clone()); - self.set_agency_did(&config.agency_did); - self.set_agency_vk(&config.agency_verkey); - self.set_agent_pwdid(&config.remote_to_sdk_did); - self.set_agent_vk(&config.remote_to_sdk_verkey); - self.set_my_pwdid(&config.sdk_to_remote_did); - self.set_my_vk(&config.sdk_to_remote_verkey); - self.set_wallet(wallet); - - Ok(self) - } - - pub fn set_testing_defaults_agency(&mut self) { - trace!("set_testing_defaults_agency >>>"); - - let default_did = "VsKV7grR1BUE29mG2Fm2kX"; - let default_verkey = "Hezce2UWMZ3wUhVkh2LfKSs8nDzWwzs2Win7EzNN3YaR"; - let default_url = "http://127.0.0.1:8080" - .parse() - .expect("should be valid url"); - - self.set_agency_url(default_url); - self.set_agency_did(default_did); - self.set_agency_vk(default_verkey); - self.set_agent_pwdid(default_did); - self.set_agent_vk(default_verkey); - self.set_my_pwdid(default_did); - self.set_my_vk(default_verkey); - } - - pub fn new() -> Self { - Self::default() - } - - // todo: use this in favor of `fn new()` - // pub fn new(config: &str, wallet_handle: WalletHandle, validate: bool) -> - // AgencyClientResult { let mut agency_client = Self::default(); - // agency_client.process_config_string(config, wallet_handle, validate)?; - // Ok(agency_client) - // } -} - -impl Default for AgencyClient { - fn default() -> Self { - Self { - wallet: Arc::new(StubAgencyClientWallet {}), - agency_url: "http://127.0.0.1:8080" - .parse() - .expect("should be valid url"), - agency_did: "".to_string(), - agency_vk: "".to_string(), - agent_pwdid: "".to_string(), - agent_vk: "".to_string(), - my_pwdid: "".to_string(), - my_vk: "".to_string(), - } - } -} diff --git a/aries/misc/legacy/agency_client/src/api/agent.rs b/aries/misc/legacy/agency_client/src/api/agent.rs deleted file mode 100644 index 6adf8322ff..0000000000 --- a/aries/misc/legacy/agency_client/src/api/agent.rs +++ /dev/null @@ -1,121 +0,0 @@ -use crate::{ - agency_client::AgencyClient, - errors::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}, - messages::{ - a2a_message::Client2AgencyMessage, - create_key::CreateKeyBuilder, - update_com_method::{ComMethodType, UpdateComMethod}, - update_connection::DeleteConnectionBuilder, - }, - testing::{ - mocking, - mocking::{agency_mocks_enabled, AgencyMock}, - test_constants, - }, -}; - -impl AgencyClient { - pub async fn delete_connection_agent( - &self, - _pw_did: &str, - to_pw_vk: &str, - agent_did: &str, - agent_vk: &str, - ) -> AgencyClientResult<()> { - trace!("send_delete_connection_message >>>"); - let message = DeleteConnectionBuilder::create().build(); - - let data = self - .prepare_message_for_connection_agent( - vec![Client2AgencyMessage::UpdateConnection(message)], - to_pw_vk, - agent_did, - agent_vk, - ) - .await?; - let response = self.post_to_agency(data).await?; - let mut response = self.parse_response_from_agency(&response).await?; - - match response.remove(0) { - Client2AgencyMessage::UpdateConnectionResponse(_) => Ok(()), - _ => Err(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidHttpResponse, - "Message does not match any variant of UpdateConnectionResponse", - )), - } - } - - pub async fn create_connection_agent( - &self, - pw_did: &str, - pw_verkey: &str, - ) -> AgencyClientResult<(String, String)> { - trace!( - "create_keys >>> pw_did: {}, pw_verkey: {}", - pw_did, - pw_verkey - ); - - if mocking::agency_mocks_enabled() { - warn!( - "CreateKeyBuilder::send_secure >>> agency mocks enabled, setting next mocked \ - response" - ); - AgencyMock::set_next_response(test_constants::CREATE_KEYS_V2_RESPONSE.to_vec()); - } - - let message = CreateKeyBuilder::create() - .for_did(pw_did)? - .for_verkey(pw_verkey)? - .build(); - - let agent_pwdid = self.get_agent_pwdid(); - - let data = self - .prepare_message_for_agent(&Client2AgencyMessage::CreateKey(message), &agent_pwdid) - .await?; - let response = self.post_to_agency(data).await?; - let mut response = self.parse_response_from_agency(&response).await?; - - match response.remove(0) { - Client2AgencyMessage::CreateKeyResponse(res) => Ok((res.for_did, res.for_verkey)), - res => Err(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidHttpResponse, - format!( - "Expected to response of Client2AgencyMessage::CreateKeyResponse, but \ - received: {res:?}" - ), - )), - } - } - - pub async fn update_agent_webhook(&self, webhook_url: &str) -> AgencyClientResult<()> { - info!("update_agent_webhook >>> webhook_url: {:?}", webhook_url); - - if agency_mocks_enabled() { - warn!("update_agent_webhook ::: Indy mocks enabled, skipping updating webhook url."); - return Ok(()); - } - - let com_method: ComMethod = ComMethod { - id: String::from("123"), - e_type: ComMethodType::Webhook, - value: String::from(webhook_url), - }; - let agent_did = self.get_agent_pwdid(); - let message = Client2AgencyMessage::UpdateComMethod(UpdateComMethod::build(com_method)); - let data = self.prepare_message_for_agent(&message, &agent_did).await?; - let response = self.post_to_agency(data).await?; - self.parse_response_from_agency(&response).await?; - - Ok(()) - } -} - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct ComMethod { - id: String, - #[serde(rename = "type")] - e_type: ComMethodType, - value: String, -} diff --git a/aries/misc/legacy/agency_client/src/api/downloaded_message.rs b/aries/misc/legacy/agency_client/src/api/downloaded_message.rs deleted file mode 100644 index 65c749987c..0000000000 --- a/aries/misc/legacy/agency_client/src/api/downloaded_message.rs +++ /dev/null @@ -1,88 +0,0 @@ -use std::sync::Arc; - -use crate::{ - errors::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}, - utils::encryption_envelope::EncryptionEnvelope, - wallet::base_agency_client_wallet::BaseAgencyClientWallet, - MessageStatusCode, -}; - -#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] -#[serde(untagged)] -pub enum MessagePayload { - V2(::serde_json::Value), -} - -impl Default for MessagePayload { - fn default() -> Self { - Self::V2(::serde_json::Value::Null) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "camelCase")] -pub struct DownloadedMessageEncrypted { - pub status_code: MessageStatusCode, - pub payload: MessagePayload, - pub uid: String, -} - -#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] -#[serde(rename_all = "camelCase")] -pub struct DownloadedMessage { - pub status_code: MessageStatusCode, - pub uid: String, - pub decrypted_msg: String, -} - -impl DownloadedMessageEncrypted { - pub fn payload(&self) -> AgencyClientResult> { - match &self.payload { - MessagePayload::V2(payload) => serde_json::to_vec(payload).map_err(|err| { - AgencyClientError::from_msg(AgencyClientErrorKind::InvalidHttpResponse, err) - }), - } - } - - pub async fn decrypt_noauth( - self, - wallet: Arc, - ) -> AgencyClientResult { - let decrypted_payload = self._noauth_decrypt_v3_message(wallet).await?; - Ok(DownloadedMessage { - status_code: self.status_code.clone(), - uid: self.uid.clone(), - decrypted_msg: decrypted_payload, - }) - } - - pub async fn decrypt_auth( - self, - wallet: Arc, - expected_sender_vk: &str, - ) -> AgencyClientResult { - let decrypted_payload = self - ._auth_decrypt_v3_message(wallet, expected_sender_vk) - .await?; - Ok(DownloadedMessage { - status_code: self.status_code.clone(), - uid: self.uid.clone(), - decrypted_msg: decrypted_payload, - }) - } - - async fn _noauth_decrypt_v3_message( - &self, - wallet: Arc, - ) -> AgencyClientResult { - EncryptionEnvelope::anon_unpack(wallet, self.payload()?).await - } - - async fn _auth_decrypt_v3_message( - &self, - wallet: Arc, - expected_sender_vk: &str, - ) -> AgencyClientResult { - EncryptionEnvelope::auth_unpack(wallet, self.payload()?, expected_sender_vk).await - } -} diff --git a/aries/misc/legacy/agency_client/src/api/messaging.rs b/aries/misc/legacy/agency_client/src/api/messaging.rs deleted file mode 100644 index 839baeeea7..0000000000 --- a/aries/misc/legacy/agency_client/src/api/messaging.rs +++ /dev/null @@ -1,90 +0,0 @@ -use crate::{ - agency_client::AgencyClient, - api::downloaded_message::DownloadedMessageEncrypted, - errors::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}, - messages::{ - a2a_message::Client2AgencyMessage, - get_messages::GetMessagesBuilder, - update_message::{UIDsByConn, UpdateMessageStatusByConnectionsBuilder}, - }, - testing::{mocking, mocking::AgencyMock, test_constants}, - MessageStatusCode, -}; - -impl AgencyClient { - pub async fn update_messages( - &self, - status_code: MessageStatusCode, - uids_by_conns: Vec, - ) -> AgencyClientResult<()> { - trace!("update_messages >>> "); - if mocking::agency_mocks_enabled() { - trace!("update_messages >>> agency mocks enabled, returning empty response"); - return Ok(()); - }; - AgencyMock::set_next_response(test_constants::UPDATE_MESSAGES_RESPONSE.to_vec()); - - let message = UpdateMessageStatusByConnectionsBuilder::create() - .uids_by_conns(uids_by_conns)? - .status_code(status_code)? - .build(); - let agent_did = self.get_agent_pwdid(); - let data = self - .prepare_message_for_agent( - &Client2AgencyMessage::UpdateMessageStatusByConnections(message), - &agent_did, - ) - .await?; - let response = self.post_to_agency(data).await?; - let mut response = self.parse_response_from_agency(&response).await?; - - match response.remove(0) { - Client2AgencyMessage::UpdateMessageStatusByConnectionsResponse(_) => Ok(()), - _ => Err(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidHttpResponse, - "Message does not match any variant of UpdateMessageStatusByConnectionsResponse", - )), - } - } - - pub async fn get_encrypted_connection_messages( - &self, - _pw_did: &str, - to_pw_vk: &str, - agent_did: &str, - agent_vk: &str, - msg_uid: Option>, - status_codes: Option>, - ) -> AgencyClientResult> { - trace!( - "get_connection_messages >>> pw_vk: {}, agent_vk: {}, msg_uid: {:?}", - to_pw_vk, - agent_vk, - msg_uid - ); - - let message = Client2AgencyMessage::GetMessages( - GetMessagesBuilder::create() - .uid(msg_uid)? - .status_codes(status_codes)? - .build(), - ); - - let data = self - .prepare_message_for_connection_agent(vec![message], to_pw_vk, agent_did, agent_vk) - .await?; - let response = self.post_to_agency(data).await?; - let mut response = self.parse_response_from_agency(&response).await?; - - match response.remove(0) { - Client2AgencyMessage::GetMessagesResponse(res) => { - trace!("Interpreting response as V2"); - Ok(res.msgs) - } - _ => Err(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidHttpResponse, - "Message does not match any variant of GetMessagesResponse", - )), - } - } -} diff --git a/aries/misc/legacy/agency_client/src/api/mod.rs b/aries/misc/legacy/agency_client/src/api/mod.rs deleted file mode 100644 index 49c36cdb07..0000000000 --- a/aries/misc/legacy/agency_client/src/api/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -pub mod agent; -pub mod downloaded_message; -pub mod messaging; -pub mod onboarding; diff --git a/aries/misc/legacy/agency_client/src/api/onboarding.rs b/aries/misc/legacy/agency_client/src/api/onboarding.rs deleted file mode 100644 index f8c668524c..0000000000 --- a/aries/misc/legacy/agency_client/src/api/onboarding.rs +++ /dev/null @@ -1,158 +0,0 @@ -use std::sync::Arc; - -use url::Url; - -use crate::{ - agency_client::AgencyClient, - configuration::AgencyClientConfig, - errors::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}, - messages::{ - a2a_message::Client2AgencyMessage, - connect::{Connect, ConnectResponse}, - create_agent::{CreateAgent, CreateAgentResponse}, - sign_up::{SignUp, SignUpResponse}, - }, - testing::{mocking::AgencyMockDecrypted, test_constants}, - wallet::base_agency_client_wallet::BaseAgencyClientWallet, -}; - -impl AgencyClient { - async fn _connect( - &self, - my_did: &str, - my_vk: &str, - agency_did: &str, - agency_vk: &str, - ) -> AgencyClientResult<(String, String)> { - trace!( - "connect >>> my_did: {}, my_vk: {}, agency_did: {}", - my_did, - my_vk, - agency_did - ); - let message = Client2AgencyMessage::Connect(Connect::build(my_did, my_vk)); - - let mut response = self - .send_message_to_agency(&message, agency_did, agency_vk) - .await?; - - let ConnectResponse { - from_vk: agency_pw_vk, - from_did: agency_pw_did, - .. - } = match response.remove(0) { - Client2AgencyMessage::ConnectResponse(resp) => resp, - _ => { - return Err(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidHttpResponse, - "Message does not match any variant of ConnectResponse", - )) - } - }; - - trace!( - "connect <<< agency_pw_did: {}, agency_pw_vk: {}", - agency_pw_did, - agency_pw_vk - ); - Ok((agency_pw_did, agency_pw_vk)) - } - - async fn _register(&self, agency_pw_did: &str, agency_pw_vk: &str) -> AgencyClientResult<()> { - let message = Client2AgencyMessage::SignUp(SignUp::build()); - - AgencyMockDecrypted::set_next_decrypted_response( - test_constants::REGISTER_RESPONSE_DECRYPTED, - ); - let mut response = self - .send_message_to_agency(&message, agency_pw_did, agency_pw_vk) - .await?; - - let _response: SignUpResponse = match response.remove(0) { - Client2AgencyMessage::SignUpResponse(resp) => resp, - _ => { - return Err(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidHttpResponse, - "Message does not match any variant of SignUpResponse", - )) - } - }; - Ok(()) - } - - async fn _create_agent( - &self, - agency_pw_did: &str, - agency_pw_vk: &str, - ) -> AgencyClientResult { - let message = Client2AgencyMessage::CreateAgent(CreateAgent::build()); - AgencyMockDecrypted::set_next_decrypted_response(test_constants::AGENT_CREATED_DECRYPTED); - let mut response = self - .send_message_to_agency(&message, agency_pw_did, agency_pw_vk) - .await?; - - let response: CreateAgentResponse = match response.remove(0) { - Client2AgencyMessage::CreateAgentResponse(resp) => resp, - _ => { - return Err(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidHttpResponse, - "Message does not match any variant of CreateAgentResponse", - )) - } - }; - Ok(response) - } - - pub async fn provision_cloud_agent( - &mut self, - wallet: Arc, - my_did: &str, - my_vk: &str, - agency_did: &str, - agency_vk: &str, - agency_url: Url, - ) -> AgencyClientResult<()> { - info!( - "provision_cloud_agent >>> my_did: {}, my_vk: {}, agency_did: {}, agency_vk: {}, \ - agency_url: {}", - my_did, my_vk, agency_did, agency_vk, agency_url - ); - self.set_wallet(wallet); - self.set_agency_url(agency_url); - self.set_agency_vk(agency_vk); - self.set_agency_did(agency_did); - self.set_my_pwdid(my_did); - self.set_my_vk(my_vk); - - AgencyMockDecrypted::set_next_decrypted_response( - test_constants::CONNECTED_RESPONSE_DECRYPTED, - ); - let (agency_pw_did, agency_pw_vk) = - self._connect(my_did, my_vk, agency_did, agency_vk).await?; - self._register(&agency_pw_did, &agency_pw_vk).await?; - let create_agent_response = self._create_agent(&agency_pw_did, &agency_pw_vk).await?; - - let agent_did = create_agent_response.from_did; - let agent_vk = create_agent_response.from_vk; - trace!( - "provision_cloud_agent <<< agent_did: {}, agent_vk: {}", - agent_did, - agent_vk - ); - self.set_agent_pwdid(&agent_did); - self.set_agent_vk(&agent_vk); - Ok(()) - } - - pub fn get_config(&self) -> AgencyClientResult { - Ok(AgencyClientConfig { - agency_did: self.get_agency_did(), - agency_verkey: self.get_agency_vk(), - agency_endpoint: self.get_agency_url_config(), - remote_to_sdk_did: self.agent_pwdid.clone(), - remote_to_sdk_verkey: self.agent_vk.clone(), - sdk_to_remote_did: self.my_pwdid.clone(), - sdk_to_remote_verkey: self.my_vk.clone(), - }) - } -} diff --git a/aries/misc/legacy/agency_client/src/configuration.rs b/aries/misc/legacy/agency_client/src/configuration.rs deleted file mode 100644 index 1f09405a76..0000000000 --- a/aries/misc/legacy/agency_client/src/configuration.rs +++ /dev/null @@ -1,49 +0,0 @@ -use url::Url; - -#[derive(Serialize, Deserialize, Clone)] -pub struct AgentProvisionConfig { - pub agency_did: String, - pub agency_verkey: String, - pub agency_endpoint: Url, - pub agent_seed: Option, -} - -impl Default for AgentProvisionConfig { - fn default() -> Self { - Self { - agency_did: Default::default(), - agency_verkey: Default::default(), - agency_endpoint: "http://127.0.0.1:8080" - .parse() - .expect("should be valid url"), - agent_seed: Default::default(), - } - } -} - -#[derive(Serialize, Deserialize, Debug, Clone)] -pub struct AgencyClientConfig { - pub agency_did: String, - pub agency_endpoint: Url, - pub agency_verkey: String, - pub remote_to_sdk_did: String, - pub remote_to_sdk_verkey: String, - pub sdk_to_remote_did: String, - pub sdk_to_remote_verkey: String, -} - -impl Default for AgencyClientConfig { - fn default() -> Self { - Self { - agency_did: Default::default(), - agency_endpoint: "http://127.0.0.1:8080" - .parse() - .expect("should be valid url"), - agency_verkey: Default::default(), - remote_to_sdk_did: Default::default(), - remote_to_sdk_verkey: Default::default(), - sdk_to_remote_did: Default::default(), - sdk_to_remote_verkey: Default::default(), - } - } -} diff --git a/aries/misc/legacy/agency_client/src/errors/error.rs b/aries/misc/legacy/agency_client/src/errors/error.rs deleted file mode 100644 index 976f03fb00..0000000000 --- a/aries/misc/legacy/agency_client/src/errors/error.rs +++ /dev/null @@ -1,83 +0,0 @@ -use std::{error::Error, fmt}; - -pub mod prelude { - pub use crate::errors::error::*; -} - -#[derive(Copy, Clone, Eq, PartialEq, Debug, thiserror::Error)] -pub enum AgencyClientErrorKind { - // Common - #[error("Object is in invalid state for requested operation")] - InvalidState, - #[error("Invalid Configuration")] - InvalidConfiguration, - #[error("Obj was not found with handle")] - InvalidJson, - #[error("Invalid Option")] - InvalidOption, - #[error("Invalid MessagePack")] - InvalidMessagePack, - #[error("IO Error, possibly creating a backup wallet")] - IOError, - - #[error("Message failed in post")] - PostMessageFailed, - - // Wallet - #[error("Invalid Wallet or Search Handle")] - InvalidWalletHandle, - - // Validation - #[error("Unknown Error")] - UnknownError, - #[error("Invalid DID")] - InvalidDid, - #[error("Invalid VERKEY")] - InvalidVerkey, - #[error("Invalid URL")] - InvalidUrl, - #[error("Unable to serialize")] - SerializationError, - #[error("Value needs to be base58")] - NotBase58, - - // A2A - #[error("Invalid HTTP response.")] - InvalidHttpResponse, -} - -#[derive(Debug, thiserror::Error)] -pub struct AgencyClientError { - msg: String, - kind: AgencyClientErrorKind, -} - -impl fmt::Display for AgencyClientError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - writeln!(f, "Error: {}\n", self.msg)?; - let mut current = self.source(); - while let Some(cause) = current { - writeln!(f, "Caused by:\n\t{cause}")?; - current = cause.source(); - } - Ok(()) - } -} - -impl AgencyClientError { - pub fn from_msg(kind: AgencyClientErrorKind, msg: D) -> AgencyClientError - where - D: fmt::Display + fmt::Debug + Send + Sync + 'static, - { - AgencyClientError { - msg: msg.to_string(), - kind, - } - } - - pub fn kind(&self) -> AgencyClientErrorKind { - self.kind - } -} - -pub type AgencyClientResult = Result; diff --git a/aries/misc/legacy/agency_client/src/errors/mapping_sharedvcx.rs b/aries/misc/legacy/agency_client/src/errors/mapping_sharedvcx.rs deleted file mode 100644 index a5a206b97b..0000000000 --- a/aries/misc/legacy/agency_client/src/errors/mapping_sharedvcx.rs +++ /dev/null @@ -1,20 +0,0 @@ -use shared::errors::validation::{ValidationError, ValidationErrorKind}; - -use crate::errors::error::{AgencyClientError, AgencyClientErrorKind}; - -impl From for AgencyClientErrorKind { - fn from(error: ValidationErrorKind) -> Self { - match error { - ValidationErrorKind::InvalidDid => AgencyClientErrorKind::InvalidDid, - ValidationErrorKind::InvalidVerkey => AgencyClientErrorKind::InvalidVerkey, - ValidationErrorKind::NotBase58 => AgencyClientErrorKind::NotBase58, - } - } -} - -impl From for AgencyClientError { - fn from(error: ValidationError) -> Self { - let kind: AgencyClientErrorKind = error.kind().into(); - AgencyClientError::from_msg(kind, error.to_string()) - } -} diff --git a/aries/misc/legacy/agency_client/src/errors/mod.rs b/aries/misc/legacy/agency_client/src/errors/mod.rs deleted file mode 100644 index b3c765f4f1..0000000000 --- a/aries/misc/legacy/agency_client/src/errors/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod error; -mod mapping_sharedvcx; diff --git a/aries/misc/legacy/agency_client/src/internal/messaging.rs b/aries/misc/legacy/agency_client/src/internal/messaging.rs deleted file mode 100644 index be433873b2..0000000000 --- a/aries/misc/legacy/agency_client/src/internal/messaging.rs +++ /dev/null @@ -1,247 +0,0 @@ -use core::u8; - -use serde_json::Value; -use shared::http_client::post_message; - -use crate::{ - agency_client::AgencyClient, - errors::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}, - messages::{a2a_message::Client2AgencyMessage, forward::ForwardV2}, - testing::{ - mocking, - mocking::{AgencyMock, AgencyMockDecrypted, HttpClientMockResponse}, - }, -}; - -impl AgencyClient { - pub async fn post_to_agency(&self, body_content: Vec) -> AgencyClientResult> { - let url = self.get_agency_url_full()?; - if mocking::agency_mocks_enabled() { - if HttpClientMockResponse::has_response() { - warn!("post_message >> mocking response for POST {}", &url); - return HttpClientMockResponse::get_response(); - } - if AgencyMockDecrypted::has_decrypted_mock_responses() { - warn!( - "post_message >> will use mocked decrypted response for POST {}", - &url - ); - return Ok(vec![]); - } - let mocked_response = AgencyMock::get_response(); - warn!( - "post_message >> mocking response of length {} for POST {}", - mocked_response.len(), - &url - ); - return Ok(mocked_response); - } - post_message(body_content, url).await.map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::PostMessageFailed, - format!("Cannot send message to agency: {err}"), - ) - }) - } - - pub async fn prepare_message_for_agency( - &self, - message: &Client2AgencyMessage, - agent_did: &str, - agent_vk: &str, - ) -> AgencyClientResult> { - let my_vk = self.get_my_vk(); - info!( - "prepare_message_for_agency >>> agent_did: {}, agent_did: {}, message: {:?}", - agent_did, agent_vk, message - ); - let message = ::serde_json::to_string(&message).map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::SerializationError, - format!("Cannot serialize A2A message: {err}"), - ) - })?; - let receiver_keys = ::serde_json::to_string(&vec![&agent_vk]).map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::SerializationError, - format!("Cannot serialize receiver keys: {err}"), - ) - })?; - let message = self - .get_wallet() - .pack_message(Some(&my_vk), &receiver_keys, message.as_bytes()) - .await?; - - self.prepare_forward_message(message, agent_did).await - } - - pub async fn prepare_message_for_agent( - &self, - message: &Client2AgencyMessage, - agent_did: &str, - ) -> AgencyClientResult> { - info!("prepare_message_for_agent >>> {:?}", message); - let agent_vk = self.get_agent_vk(); - let my_vk = self.get_my_vk(); - let message = ::serde_json::to_string(&message).map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::SerializationError, - format!("Cannot serialize A2A message: {err}"), - ) - })?; - let receiver_keys = ::serde_json::to_string(&vec![&agent_vk]).map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::SerializationError, - format!("Cannot serialize receiver keys: {err}"), - ) - })?; - let message = self - .get_wallet() - .pack_message(Some(&my_vk), &receiver_keys, message.as_bytes()) - .await?; - - self.prepare_forward_message(message, agent_did).await - } - - pub async fn parse_message_from_response(&self, response: &[u8]) -> AgencyClientResult { - let unpacked_msg = self.get_wallet().unpack_message(response).await?; - let message: Value = ::serde_json::from_slice(unpacked_msg.as_slice()).map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidJson, - format!("Cannot deserialize response: {err}"), - ) - })?; - Ok(message["message"] - .as_str() - .ok_or(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidJson, - "Cannot find `message` field on response", - ))? - .to_string()) - } - - pub async fn parse_response_from_agency( - &self, - response: &Vec, - ) -> AgencyClientResult> { - trace!( - "parse_response_from_agency >>> processing payload of {} bytes", - response.len() - ); - - let message: String = if AgencyMockDecrypted::has_decrypted_mock_responses() { - warn!("parse_response_from_agency_v2 >> retrieving decrypted mock response"); - AgencyMockDecrypted::get_next_decrypted_response() - } else { - self.parse_message_from_response(response).await? - }; - trace!( - "parse_response_from_agency >> decrypted message: {}", - message - ); - let message: Client2AgencyMessage = serde_json::from_str(&message).map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidJson, - format!("Cannot deserialize A2A message: {err}"), - ) - })?; - - Ok(vec![message]) - } - - async fn prepare_forward_message( - &self, - message: Vec, - did: &str, - ) -> AgencyClientResult> { - trace!("prepare_forward_message >>>"); - let agency_vk = self.get_agency_vk(); - - let message = Client2AgencyMessage::Forward(ForwardV2::new(did.to_string(), message)?); - - match message { - Client2AgencyMessage::Forward(msg) => { - self.prepare_forward_message_for_agency_v2(&msg, &agency_vk) - .await - } - _ => Err(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidState, - "Invalid message type", - )), - } - } - - async fn prepare_forward_message_for_agency_v2( - &self, - message: &ForwardV2, - agency_vk: &str, - ) -> AgencyClientResult> { - let message = serde_json::to_string(message).map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::SerializationError, - format!("Cannot serialize Forward message: {err}"), - ) - })?; - - let receiver_keys = serde_json::to_string(&vec![agency_vk]).map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::SerializationError, - format!("Cannot serialize receiver keys: {err}"), - ) - })?; - - self.get_wallet() - .pack_message(None, &receiver_keys, message.as_bytes()) - .await - } - - pub async fn prepare_message_for_connection_agent( - &self, - messages: Vec, - pw_vk: &str, - agent_did: &str, - agent_vk: &str, - ) -> AgencyClientResult> { - debug!("prepare_message_for_connection_agent >> {:?}", messages); - let message = messages.first().ok_or(AgencyClientError::from_msg( - AgencyClientErrorKind::SerializationError, - "Cannot get message", - ))?; - let message = serde_json::to_string(message).map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::SerializationError, - format!("Cannot serialize A2A message: {err}"), - ) - })?; - let receiver_keys = serde_json::to_string(&vec![&agent_vk]).map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::SerializationError, - format!("Cannot receiver keys: {err}"), - ) - })?; - - let message = self - .get_wallet() - .pack_message(Some(pw_vk), &receiver_keys, message.as_bytes()) - .await?; - - let message = Client2AgencyMessage::Forward(ForwardV2::new(agent_did.to_owned(), message)?); - - let to_did = self.get_agent_pwdid(); - self.prepare_message_for_agent(&message, &to_did).await - } - - pub async fn send_message_to_agency( - &self, - message: &Client2AgencyMessage, - did: &str, - verkey: &str, - ) -> AgencyClientResult> { - trace!("send_message_to_agency >>> message: ..., did: {}", did); - let data = self - .prepare_message_for_agency(message, did, verkey) - .await?; - let response = self.post_to_agency(data).await?; - self.parse_response_from_agency(&response).await - } -} diff --git a/aries/misc/legacy/agency_client/src/internal/mod.rs b/aries/misc/legacy/agency_client/src/internal/mod.rs deleted file mode 100644 index 3e223d3857..0000000000 --- a/aries/misc/legacy/agency_client/src/internal/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub(super) mod messaging; diff --git a/aries/misc/legacy/agency_client/src/lib.rs b/aries/misc/legacy/agency_client/src/lib.rs deleted file mode 100644 index fc3c2d55b5..0000000000 --- a/aries/misc/legacy/agency_client/src/lib.rs +++ /dev/null @@ -1,65 +0,0 @@ -#[macro_use] -extern crate lazy_static; - -#[macro_use] -extern crate log; - -#[macro_use] -extern crate serde_derive; - -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; -use serde_json::Value; -mod utils; - -#[macro_use] -pub mod agency_client; - -pub mod api; -pub mod configuration; - -pub mod messages; -pub mod testing; -pub mod wallet; - -pub mod errors; -mod internal; - -#[derive(Clone, Debug, PartialEq)] -pub enum MessageStatusCode { - Received, - Reviewed, -} - -impl ToString for MessageStatusCode { - fn to_string(&self) -> String { - match self { - MessageStatusCode::Received => "MS-103", - MessageStatusCode::Reviewed => "MS-106", - } - .to_string() - } -} - -impl Serialize for MessageStatusCode { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let value = self.to_string(); - Value::String(value).serialize(serializer) - } -} - -impl<'de> Deserialize<'de> for MessageStatusCode { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let value = Value::deserialize(deserializer).map_err(de::Error::custom)?; - match value.as_str() { - Some("MS-103") => Ok(MessageStatusCode::Received), - Some("MS-106") => Ok(MessageStatusCode::Reviewed), - _ => Err(de::Error::custom("Unexpected message type.")), - } - } -} diff --git a/aries/misc/legacy/agency_client/src/messages/a2a_message.rs b/aries/misc/legacy/agency_client/src/messages/a2a_message.rs deleted file mode 100644 index 608738471d..0000000000 --- a/aries/misc/legacy/agency_client/src/messages/a2a_message.rs +++ /dev/null @@ -1,233 +0,0 @@ -use serde::{de, Deserialize, Deserializer}; -use serde_json::Value; - -use crate::messages::{ - connect::{Connect, ConnectResponse}, - create_agent::{CreateAgent, CreateAgentResponse}, - create_key::{CreateKey, CreateKeyResponse}, - forward::ForwardV2, - get_messages::{GetMessages, GetMessagesResponse}, - message_type::{MessageFamilies, MessageType}, - sign_up::{SignUp, SignUpResponse}, - update_com_method::{ComMethodUpdated, UpdateComMethod}, - update_connection::{UpdateConnection, UpdateConnectionResponse}, - update_message::{UpdateMessageStatusByConnections, UpdateMessageStatusByConnectionsResponse}, -}; - -#[derive(Debug, Serialize, PartialEq)] -#[serde(untagged)] -pub enum Client2AgencyMessage { - /// routing - Forward(ForwardV2), - - /// onbording - Connect(Connect), - ConnectResponse(ConnectResponse), - SignUp(SignUp), - SignUpResponse(SignUpResponse), - CreateAgent(CreateAgent), - CreateAgentResponse(CreateAgentResponse), - - /// PW Connection - CreateKey(CreateKey), - CreateKeyResponse(CreateKeyResponse), - - GetMessages(GetMessages), - GetMessagesResponse(GetMessagesResponse), - - UpdateConnection(UpdateConnection), - UpdateConnectionResponse(UpdateConnectionResponse), - UpdateMessageStatusByConnections(UpdateMessageStatusByConnections), - UpdateMessageStatusByConnectionsResponse(UpdateMessageStatusByConnectionsResponse), - - /// config - UpdateComMethod(UpdateComMethod), - ComMethodUpdated(ComMethodUpdated), -} - -impl<'de> Deserialize<'de> for Client2AgencyMessage { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let value = Value::deserialize(deserializer).map_err(de::Error::custom)?; - let message_type: MessageType = - serde_json::from_value(value["@type"].clone()).map_err(de::Error::custom)?; - - if log::log_enabled!(log::Level::Trace) { - let message_json = serde_json::ser::to_string(&value); - let message_type_json = serde_json::ser::to_string(&value["@type"].clone()); - - trace!("Deserializing A2AMessageV2 json: {:?}", &message_json); - trace!( - "Found A2AMessageV2 message type json {:?}", - &message_type_json - ); - trace!("Found A2AMessageV2 message type {:?}", &message_type); - }; - - match message_type.type_.as_str() { - "FWD" => ForwardV2::deserialize(value) - .map(Client2AgencyMessage::Forward) - .map_err(de::Error::custom), - "CONNECT" => Connect::deserialize(value) - .map(Client2AgencyMessage::Connect) - .map_err(de::Error::custom), - "CONNECTED" => ConnectResponse::deserialize(value) - .map(Client2AgencyMessage::ConnectResponse) - .map_err(de::Error::custom), - "SIGNUP" => SignUp::deserialize(value) - .map(Client2AgencyMessage::SignUp) - .map_err(de::Error::custom), - "SIGNED_UP" => SignUpResponse::deserialize(value) - .map(Client2AgencyMessage::SignUpResponse) - .map_err(de::Error::custom), - "CREATE_AGENT" => CreateAgent::deserialize(value) - .map(Client2AgencyMessage::CreateAgent) - .map_err(de::Error::custom), - "AGENT_CREATED" => CreateAgentResponse::deserialize(value) - .map(Client2AgencyMessage::CreateAgentResponse) - .map_err(de::Error::custom), - "CREATE_KEY" => CreateKey::deserialize(value) - .map(Client2AgencyMessage::CreateKey) - .map_err(de::Error::custom), - "KEY_CREATED" => CreateKeyResponse::deserialize(value) - .map(Client2AgencyMessage::CreateKeyResponse) - .map_err(de::Error::custom), - "GET_MSGS" => GetMessages::deserialize(value) - .map(Client2AgencyMessage::GetMessages) - .map_err(de::Error::custom), - "MSGS" => GetMessagesResponse::deserialize(value) - .map(Client2AgencyMessage::GetMessagesResponse) - .map_err(de::Error::custom), - "UPDATE_CONN_STATUS" => UpdateConnection::deserialize(value) - .map(Client2AgencyMessage::UpdateConnection) - .map_err(de::Error::custom), - "CONN_STATUS_UPDATED" => UpdateConnectionResponse::deserialize(value) - .map(Client2AgencyMessage::UpdateConnectionResponse) - .map_err(de::Error::custom), - "UPDATE_MSG_STATUS_BY_CONNS" => UpdateMessageStatusByConnections::deserialize(value) - .map(Client2AgencyMessage::UpdateMessageStatusByConnections) - .map_err(de::Error::custom), - "MSG_STATUS_UPDATED_BY_CONNS" => { - UpdateMessageStatusByConnectionsResponse::deserialize(value) - .map(Client2AgencyMessage::UpdateMessageStatusByConnectionsResponse) - .map_err(de::Error::custom) - } - "UPDATE_COM_METHOD" => UpdateComMethod::deserialize(value) - .map(Client2AgencyMessage::UpdateComMethod) - .map_err(de::Error::custom), - "COM_METHOD_UPDATED" => ComMethodUpdated::deserialize(value) - .map(Client2AgencyMessage::ComMethodUpdated) - .map_err(de::Error::custom), - _ => Err(de::Error::custom("Unexpected @type field structure.")), - } - } -} - -#[derive(Debug, Deserialize, Serialize)] -pub enum A2AMessageKinds { - Forward, - Connect, - Connected, - SignUp, - SignedUp, - - CreateAgent, - AgentCreated, - - CreateKey, - KeyCreated, - - GetMessages, - Messages, - UpdateMessageStatusByConnections, - MessageStatusUpdatedByConnections, - UpdateConnectionStatus, - UpdateComMethod, - ComMethodUpdated, -} - -impl A2AMessageKinds { - pub fn family(&self) -> MessageFamilies { - match self { - A2AMessageKinds::Forward => MessageFamilies::Routing, - A2AMessageKinds::Connect => MessageFamilies::Onboarding, - A2AMessageKinds::Connected => MessageFamilies::Onboarding, - A2AMessageKinds::CreateAgent => MessageFamilies::Onboarding, - A2AMessageKinds::AgentCreated => MessageFamilies::Onboarding, - A2AMessageKinds::SignUp => MessageFamilies::Onboarding, - A2AMessageKinds::SignedUp => MessageFamilies::Onboarding, - A2AMessageKinds::CreateKey => MessageFamilies::Pairwise, - A2AMessageKinds::KeyCreated => MessageFamilies::Pairwise, - A2AMessageKinds::GetMessages => MessageFamilies::Pairwise, - A2AMessageKinds::Messages => MessageFamilies::Pairwise, - A2AMessageKinds::UpdateConnectionStatus => MessageFamilies::Pairwise, - A2AMessageKinds::UpdateMessageStatusByConnections => MessageFamilies::Pairwise, - A2AMessageKinds::MessageStatusUpdatedByConnections => MessageFamilies::Pairwise, - A2AMessageKinds::UpdateComMethod => MessageFamilies::Configs, - A2AMessageKinds::ComMethodUpdated => MessageFamilies::Configs, - } - } - - pub fn name(&self) -> String { - match self { - A2AMessageKinds::Forward => "FWD".to_string(), - A2AMessageKinds::Connect => "CONNECT".to_string(), - A2AMessageKinds::Connected => "CONNECTED".to_string(), - A2AMessageKinds::CreateAgent => "CREATE_AGENT".to_string(), - A2AMessageKinds::AgentCreated => "AGENT_CREATED".to_string(), - A2AMessageKinds::SignUp => "SIGNUP".to_string(), - A2AMessageKinds::SignedUp => "SIGNED_UP".to_string(), - A2AMessageKinds::CreateKey => "CREATE_KEY".to_string(), - A2AMessageKinds::KeyCreated => "KEY_CREATED".to_string(), - A2AMessageKinds::GetMessages => "GET_MSGS".to_string(), - A2AMessageKinds::UpdateMessageStatusByConnections => { - "UPDATE_MSG_STATUS_BY_CONNS".to_string() - } - A2AMessageKinds::MessageStatusUpdatedByConnections => { - "MSG_STATUS_UPDATED_BY_CONNS".to_string() - } - A2AMessageKinds::Messages => "MSGS".to_string(), - A2AMessageKinds::UpdateConnectionStatus => "UPDATE_CONN_STATUS".to_string(), - A2AMessageKinds::UpdateComMethod => "UPDATE_COM_METHOD".to_string(), - A2AMessageKinds::ComMethodUpdated => "COM_METHOD_UPDATED".to_string(), - } - } -} - -#[cfg(test)] -mod test { - use serde_json::json; - - use crate::{ - messages::{ - a2a_message::{A2AMessageKinds, Client2AgencyMessage}, - get_messages::GetMessages, - }, - testing::test_utils::SetupMocks, - }; - - #[test] - fn test_serialize_deserialize_agency_message() { - let _setup = SetupMocks::init(); - let msg = Client2AgencyMessage::GetMessages(GetMessages::build( - A2AMessageKinds::GetMessages, - Some("foo".into()), - Some(vec!["abcd".into()]), - None, - None, - )); - let serialized = serde_json::to_string(&msg).unwrap(); - let expected = serde_json::to_string(&json!({ - "@type":"did:sov:123456789abcdefghi1234;spec/pairwise/1.0/GET_MSGS", - "excludePayload":"foo", - "uids":["abcd"] - })) - .unwrap(); - assert_eq!(serialized, expected); - - let deserialized: Client2AgencyMessage = serde_json::from_str(&serialized).unwrap(); - assert_eq!(deserialized, msg); - } -} diff --git a/aries/misc/legacy/agency_client/src/messages/connect.rs b/aries/misc/legacy/agency_client/src/messages/connect.rs deleted file mode 100644 index bc6261673d..0000000000 --- a/aries/misc/legacy/agency_client/src/messages/connect.rs +++ /dev/null @@ -1,31 +0,0 @@ -use crate::messages::{a2a_message::A2AMessageKinds, message_type::MessageType}; - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct Connect { - #[serde(rename = "@type")] - msg_type: MessageType, - #[serde(rename = "fromDID")] - from_did: String, - #[serde(rename = "fromDIDVerKey")] - from_vk: String, -} - -impl Connect { - pub fn build(from_did: &str, from_vk: &str) -> Connect { - Connect { - msg_type: MessageType::build_v2(A2AMessageKinds::Connect), - from_did: from_did.to_string(), - from_vk: from_vk.to_string(), - } - } -} - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct ConnectResponse { - #[serde(rename = "@type")] - pub msg_type: MessageType, - #[serde(rename = "withPairwiseDID")] - pub from_did: String, - #[serde(rename = "withPairwiseDIDVerKey")] - pub from_vk: String, -} diff --git a/aries/misc/legacy/agency_client/src/messages/create_agent.rs b/aries/misc/legacy/agency_client/src/messages/create_agent.rs deleted file mode 100644 index 1b6b65293c..0000000000 --- a/aries/misc/legacy/agency_client/src/messages/create_agent.rs +++ /dev/null @@ -1,25 +0,0 @@ -use crate::messages::{a2a_message::A2AMessageKinds, message_type::MessageType}; - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct CreateAgent { - #[serde(rename = "@type")] - msg_type: MessageType, -} - -impl CreateAgent { - pub fn build() -> CreateAgent { - CreateAgent { - msg_type: MessageType::build_v2(A2AMessageKinds::CreateAgent), - } - } -} - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct CreateAgentResponse { - #[serde(rename = "@type")] - pub msg_type: MessageType, - #[serde(rename = "withPairwiseDID")] - pub from_did: String, - #[serde(rename = "withPairwiseDIDVerKey")] - pub from_vk: String, -} diff --git a/aries/misc/legacy/agency_client/src/messages/create_key.rs b/aries/misc/legacy/agency_client/src/messages/create_key.rs deleted file mode 100644 index c74e09fcaf..0000000000 --- a/aries/misc/legacy/agency_client/src/messages/create_key.rs +++ /dev/null @@ -1,91 +0,0 @@ -use shared::validation::{did::validate_did, verkey::validate_verkey}; - -use crate::{ - errors::error::AgencyClientResult, - messages::{a2a_message::A2AMessageKinds, message_type::MessageType}, -}; - -#[derive(Deserialize, Serialize, Debug, PartialEq)] -#[serde(rename_all = "camelCase")] -pub struct CreateKey { - #[serde(rename = "@type")] - msg_type: MessageType, - #[serde(rename = "forDID")] - for_did: String, - #[serde(rename = "forDIDVerKey")] - for_verkey: String, -} - -#[derive(Debug, Serialize, Deserialize, PartialEq)] -pub struct CreateKeyResponse { - #[serde(rename = "@type")] - msg_type: MessageType, - #[serde(rename = "withPairwiseDID")] - pub(crate) for_did: String, - #[serde(rename = "withPairwiseDIDVerKey")] - pub(crate) for_verkey: String, -} - -#[derive(Debug)] -pub struct CreateKeyBuilder { - for_did: String, - for_verkey: String, -} - -impl CreateKeyBuilder { - pub fn create() -> CreateKeyBuilder { - trace!("CreateKeyBuilder::create_message >>>"); - - CreateKeyBuilder { - for_did: String::new(), - for_verkey: String::new(), - } - } - - pub fn for_did(&mut self, did: &str) -> AgencyClientResult<&mut Self> { - trace!("CreateKeyBuilder::for_did >>> did: {}", did); - validate_did(did)?; - self.for_did = did.to_string(); - Ok(self) - } - - pub fn for_verkey(&mut self, verkey: &str) -> AgencyClientResult<&mut Self> { - trace!("CreateKeyBuilder::for_verkey >>> verkey: {}", verkey); - validate_verkey(verkey)?; - self.for_verkey = verkey.to_string(); - Ok(self) - } - - pub fn build(&self) -> CreateKey { - CreateKey { - msg_type: MessageType::build_v2(A2AMessageKinds::CreateKey), - for_did: self.for_did.to_string(), - for_verkey: self.for_verkey.to_string(), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::errors::error::AgencyClientErrorKind; - - #[test] - fn test_create_key_set_values() { - let for_did = "11235yBzrpJQmNyZzgoTqB"; - let for_verkey = "EkVTa7SCJ5SntpYyX7CSb2pcBhiVGT9kWSagA8a9T69A"; - - CreateKeyBuilder::create() - .for_did(for_did) - .unwrap() - .for_verkey(for_verkey) - .unwrap(); - } - - #[test] - fn test_create_key_set_invalid_did_errors() { - let for_did = "11235yBzrpJQmNyZzgoT"; - let res = CreateKeyBuilder::create().for_did(for_did).unwrap_err(); - assert_eq!(res.kind(), AgencyClientErrorKind::InvalidDid); - } -} diff --git a/aries/misc/legacy/agency_client/src/messages/forward.rs b/aries/misc/legacy/agency_client/src/messages/forward.rs deleted file mode 100644 index c00c5b2fb3..0000000000 --- a/aries/misc/legacy/agency_client/src/messages/forward.rs +++ /dev/null @@ -1,34 +0,0 @@ -use core::u8; - -use serde_json::Value; -use uuid::Uuid; - -use crate::{ - errors::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}, - messages::{a2a_message::A2AMessageKinds, message_type::MessageType}, -}; - -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] -pub struct ForwardV2 { - #[serde(rename = "@type")] - msg_type: MessageType, - #[serde(rename = "@fwd")] - fwd: String, - #[serde(rename = "@msg")] - msg: Value, - #[serde(rename = "@id")] - id: String, -} - -impl ForwardV2 { - pub fn new(fwd: String, msg: Vec) -> AgencyClientResult { - let msg = serde_json::from_slice(msg.as_slice()) - .map_err(|err| AgencyClientError::from_msg(AgencyClientErrorKind::InvalidState, err))?; - Ok(Self { - msg_type: MessageType::build_v2(A2AMessageKinds::Forward), - fwd, - msg, - id: Uuid::new_v4().to_string(), - }) - } -} diff --git a/aries/misc/legacy/agency_client/src/messages/get_messages.rs b/aries/misc/legacy/agency_client/src/messages/get_messages.rs deleted file mode 100644 index 4959a871d3..0000000000 --- a/aries/misc/legacy/agency_client/src/messages/get_messages.rs +++ /dev/null @@ -1,94 +0,0 @@ -use crate::{ - api::downloaded_message::DownloadedMessageEncrypted, - errors::error::AgencyClientResult, - messages::{a2a_message::A2AMessageKinds, message_type::MessageType}, - MessageStatusCode, -}; - -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] -#[serde(rename_all = "camelCase")] -pub struct GetMessages { - #[serde(rename = "@type")] - msg_type: MessageType, - #[serde(rename = "excludePayload")] - #[serde(skip_serializing_if = "Option::is_none")] - exclude_payload: Option, - #[serde(skip_serializing_if = "Option::is_none")] - uids: Option>, - #[serde(rename = "statusCodes")] - #[serde(skip_serializing_if = "Option::is_none")] - status_codes: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(rename = "pairwiseDIDs")] - pairwise_dids: Option>, -} - -impl GetMessages { - pub(crate) fn build( - kind: A2AMessageKinds, - exclude_payload: Option, - uids: Option>, - status_codes: Option>, - pairwise_dids: Option>, - ) -> GetMessages { - GetMessages { - msg_type: MessageType::build_v2(kind), - exclude_payload, - uids, - status_codes, - pairwise_dids, - } - } -} - -#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)] -#[serde(rename_all = "camelCase")] -pub struct GetMessagesResponse { - #[serde(rename = "@type")] - pub msg_type: MessageType, - pub msgs: Vec, -} - -#[derive(Debug)] -pub struct GetMessagesBuilder { - exclude_payload: Option, - uids: Option>, - status_codes: Option>, - pairwise_dids: Option>, -} - -impl GetMessagesBuilder { - pub fn create() -> GetMessagesBuilder { - trace!("GetMessages::create_message >>>"); - - GetMessagesBuilder { - uids: None, - exclude_payload: None, - status_codes: None, - pairwise_dids: None, - } - } - - pub fn uid(&mut self, uids: Option>) -> AgencyClientResult<&mut Self> { - self.uids = uids; - Ok(self) - } - - pub fn status_codes( - &mut self, - status_codes: Option>, - ) -> AgencyClientResult<&mut Self> { - self.status_codes = status_codes; - Ok(self) - } - - pub fn build(&self) -> GetMessages { - GetMessages::build( - A2AMessageKinds::GetMessages, - self.exclude_payload.clone(), - self.uids.clone(), - self.status_codes.clone(), - self.pairwise_dids.clone(), - ) - } -} diff --git a/aries/misc/legacy/agency_client/src/messages/message_type.rs b/aries/misc/legacy/agency_client/src/messages/message_type.rs deleted file mode 100644 index fc6a6c5dbd..0000000000 --- a/aries/misc/legacy/agency_client/src/messages/message_type.rs +++ /dev/null @@ -1,151 +0,0 @@ -use regex::{Match, Regex}; -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; -use serde_json::Value; - -use crate::{ - errors::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}, - messages::a2a_message::A2AMessageKinds, -}; - -const DID: &str = "did:sov:123456789abcdefghi1234"; - -impl MessageType { - pub(crate) fn build_v2(kind: A2AMessageKinds) -> MessageType { - MessageType { - did: DID.to_string(), - family: kind.family(), - version: kind.family().version().to_string(), - type_: kind.name(), - } - } -} - -#[derive(Debug, Clone, PartialEq)] -pub struct MessageType { - did: String, - family: MessageFamilies, - version: String, - pub(crate) type_: String, -} - -#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] -pub enum MessageFamilies { - Routing, - Onboarding, - Pairwise, - Configs, - Unknown(String), -} - -impl MessageFamilies { - fn version(&self) -> &'static str { - match self { - MessageFamilies::Routing => "1.0", - MessageFamilies::Onboarding => "1.0", - MessageFamilies::Pairwise => "1.0", - MessageFamilies::Configs => "1.0", - _ => "1.0", - } - } -} - -impl From for MessageFamilies { - fn from(family: String) -> Self { - match family.as_str() { - "routing" => MessageFamilies::Routing, - "onboarding" => MessageFamilies::Onboarding, - "pairwise" => MessageFamilies::Pairwise, - "configs" => MessageFamilies::Configs, - family => MessageFamilies::Unknown(family.to_string()), - } - } -} - -impl ::std::string::ToString for MessageFamilies { - fn to_string(&self) -> String { - match self { - MessageFamilies::Routing => "routing".to_string(), - MessageFamilies::Onboarding => "onboarding".to_string(), - MessageFamilies::Pairwise => "pairwise".to_string(), - MessageFamilies::Configs => "configs".to_string(), - MessageFamilies::Unknown(family) => family.to_string(), - } - } -} - -pub(crate) fn parse_message_type( - message_type: &str, -) -> AgencyClientResult<(String, String, String, String)> { - lazy_static! { - static ref RE: Regex = Regex::new( - r"(?x) - (?P[\d\w:]*); - (?P.*)/ - (?P.*)/ - (?P.*)/ - (?P.*)" - ) - .expect("unexpected regex error occurred."); - } - - RE.captures(message_type) - .and_then(|cap| { - let did = cap.name("did").as_ref().map(Match::as_str); - let family = cap.name("family").as_ref().map(Match::as_str); - let version = cap.name("version").as_ref().map(Match::as_str); - let type_ = cap.name("type").as_ref().map(Match::as_str); - - match (did, family, version, type_) { - (Some(did), Some(family), Some(version), Some(type_)) => Some(( - did.to_string(), - family.to_string(), - version.to_string(), - type_.to_string(), - )), - _ => None, - } - }) - .ok_or(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidOption, - "Cannot parse @type", - )) -} - -impl<'de> Deserialize<'de> for MessageType { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let value = Value::deserialize(deserializer).map_err(de::Error::custom)?; - - match value.as_str() { - Some(type_) => { - let (did, family, version, type_) = - parse_message_type(type_).map_err(de::Error::custom)?; - Ok(MessageType { - did, - family: MessageFamilies::from(family), - version, - type_, - }) - } - _ => Err(de::Error::custom("Unexpected @type field structure.")), - } - } -} - -impl Serialize for MessageType { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let value = Value::String(format!( - "{};spec/{}/{}/{}", - self.did, - self.family.to_string(), - self.version, - self.type_ - )); - value.serialize(serializer) - } -} diff --git a/aries/misc/legacy/agency_client/src/messages/mod.rs b/aries/misc/legacy/agency_client/src/messages/mod.rs deleted file mode 100644 index 7041dd3b37..0000000000 --- a/aries/misc/legacy/agency_client/src/messages/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -pub mod a2a_message; -pub mod connect; -pub mod create_agent; -pub mod create_key; -pub mod forward; -pub mod get_messages; -pub mod message_type; -pub mod sign_up; -pub mod update_com_method; -pub mod update_connection; -pub mod update_message; diff --git a/aries/misc/legacy/agency_client/src/messages/sign_up.rs b/aries/misc/legacy/agency_client/src/messages/sign_up.rs deleted file mode 100644 index ebd9813f16..0000000000 --- a/aries/misc/legacy/agency_client/src/messages/sign_up.rs +++ /dev/null @@ -1,21 +0,0 @@ -use crate::messages::{a2a_message::A2AMessageKinds, message_type::MessageType}; - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct SignUp { - #[serde(rename = "@type")] - msg_type: MessageType, -} - -impl SignUp { - pub fn build() -> SignUp { - SignUp { - msg_type: MessageType::build_v2(A2AMessageKinds::SignUp), - } - } -} - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct SignUpResponse { - #[serde(rename = "@type")] - msg_type: MessageType, -} diff --git a/aries/misc/legacy/agency_client/src/messages/update_com_method.rs b/aries/misc/legacy/agency_client/src/messages/update_com_method.rs deleted file mode 100644 index 6cba921823..0000000000 --- a/aries/misc/legacy/agency_client/src/messages/update_com_method.rs +++ /dev/null @@ -1,93 +0,0 @@ -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; -use serde_json::Value; - -use crate::{ - api::agent::ComMethod, - messages::{a2a_message::A2AMessageKinds, message_type::MessageType}, -}; - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct ComMethodUpdated { - #[serde(rename = "@type")] - msg_type: MessageType, - id: String, -} - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct UpdateComMethod { - #[serde(rename = "@type")] - msg_type: MessageType, - #[serde(rename = "comMethod")] - com_method: ComMethod, -} - -#[derive(Debug, PartialEq)] -pub enum ComMethodType { - A2A, - Webhook, -} - -impl Serialize for ComMethodType { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let value = match self { - ComMethodType::A2A => "1", - ComMethodType::Webhook => "2", - }; - Value::String(value.to_string()).serialize(serializer) - } -} - -impl<'de> Deserialize<'de> for ComMethodType { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let value = Value::deserialize(deserializer).map_err(de::Error::custom)?; - match value.as_str() { - Some("1") => Ok(ComMethodType::A2A), - Some("2") => Ok(ComMethodType::Webhook), - _ => Err(de::Error::custom("Unexpected communication method type.")), - } - } -} - -impl UpdateComMethod { - pub fn build(com_method: ComMethod) -> UpdateComMethod { - UpdateComMethod { - msg_type: MessageType::build_v2(A2AMessageKinds::UpdateComMethod), - com_method, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_method_type_serialization() { - assert_eq!( - "\"1\"", - serde_json::to_string::(&ComMethodType::A2A).unwrap() - ); - assert_eq!( - "\"2\"", - serde_json::to_string::(&ComMethodType::Webhook).unwrap() - ); - } - - #[test] - fn test_method_type_deserialization() { - assert_eq!( - ComMethodType::A2A, - serde_json::from_str::("\"1\"").unwrap() - ); - assert_eq!( - ComMethodType::Webhook, - serde_json::from_str::("\"2\"").unwrap() - ); - } -} diff --git a/aries/misc/legacy/agency_client/src/messages/update_connection.rs b/aries/misc/legacy/agency_client/src/messages/update_connection.rs deleted file mode 100644 index aa017fa0dc..0000000000 --- a/aries/misc/legacy/agency_client/src/messages/update_connection.rs +++ /dev/null @@ -1,79 +0,0 @@ -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; -use serde_json::Value; - -use crate::messages::{a2a_message::A2AMessageKinds, message_type::MessageType}; - -#[derive(Clone, Deserialize, Serialize, Debug, PartialEq)] -#[serde(rename_all = "camelCase")] -pub struct UpdateConnection { - #[serde(rename = "@type")] - msg_type: MessageType, - #[serde(rename = "statusCode")] - status_code: ConnectionStatus, -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum ConnectionStatus { - AlreadyConnected, - NotConnected, - Deleted, -} - -impl Serialize for ConnectionStatus { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let value = match self { - ConnectionStatus::AlreadyConnected => "CS-101", - ConnectionStatus::NotConnected => "CS-102", - ConnectionStatus::Deleted => "CS-103", - }; - serde_json::Value::String(value.to_string()).serialize(serializer) - } -} - -impl<'de> Deserialize<'de> for ConnectionStatus { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let value = Value::deserialize(deserializer).map_err(de::Error::custom)?; - match value.as_str() { - Some("CS-101") => Ok(ConnectionStatus::AlreadyConnected), - Some("CS-102") => Ok(ConnectionStatus::NotConnected), - Some("CS-103") => Ok(ConnectionStatus::Deleted), - _ => Err(de::Error::custom("Unexpected message type.")), - } - } -} - -#[derive(Debug, Deserialize, Serialize, PartialEq)] -pub struct UpdateConnectionResponse { - #[serde(rename = "@type")] - msg_type: MessageType, - #[serde(rename = "statusCode")] - pub status_code: ConnectionStatus, -} - -#[derive(Debug)] -pub struct DeleteConnectionBuilder { - status_code: ConnectionStatus, -} - -impl DeleteConnectionBuilder { - pub fn create() -> DeleteConnectionBuilder { - trace!("DeleteConnection::create_message >>>"); - - DeleteConnectionBuilder { - status_code: ConnectionStatus::Deleted, - } - } - - pub fn build(&self) -> UpdateConnection { - UpdateConnection { - msg_type: MessageType::build_v2(A2AMessageKinds::UpdateConnectionStatus), - status_code: self.status_code.clone(), - } - } -} diff --git a/aries/misc/legacy/agency_client/src/messages/update_message.rs b/aries/misc/legacy/agency_client/src/messages/update_message.rs deleted file mode 100644 index 4f2808bd9b..0000000000 --- a/aries/misc/legacy/agency_client/src/messages/update_message.rs +++ /dev/null @@ -1,67 +0,0 @@ -use crate::{ - errors::error::AgencyClientResult, - messages::{a2a_message::A2AMessageKinds, message_type::MessageType}, - MessageStatusCode, -}; - -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] -#[serde(rename_all = "camelCase")] -pub struct UpdateMessageStatusByConnections { - #[serde(rename = "@type")] - msg_type: MessageType, - status_code: Option, - uids_by_conns: Vec, -} - -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] -#[serde(rename_all = "camelCase")] -pub struct UpdateMessageStatusByConnectionsResponse { - #[serde(rename = "@type")] - msg_type: MessageType, - status_code: Option, -} - -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] -#[serde(rename_all = "camelCase")] -pub struct UIDsByConn { - #[serde(rename = "pairwiseDID")] - pub pairwise_did: String, - pub uids: Vec, -} - -pub struct UpdateMessageStatusByConnectionsBuilder { - status_code: Option, - uids_by_conns: Vec, -} - -impl UpdateMessageStatusByConnectionsBuilder { - pub fn create() -> UpdateMessageStatusByConnectionsBuilder { - trace!("UpdateMessageStatusByConnectionsBuilder::create >>>"); - - UpdateMessageStatusByConnectionsBuilder { - status_code: None, - uids_by_conns: Vec::new(), - } - } - - pub fn uids_by_conns( - &mut self, - uids_by_conns: Vec, - ) -> AgencyClientResult<&mut Self> { - self.uids_by_conns = uids_by_conns; - Ok(self) - } - - pub fn status_code(&mut self, code: MessageStatusCode) -> AgencyClientResult<&mut Self> { - self.status_code = Some(code); - Ok(self) - } - - pub fn build(&self) -> UpdateMessageStatusByConnections { - UpdateMessageStatusByConnections { - msg_type: MessageType::build_v2(A2AMessageKinds::UpdateMessageStatusByConnections), - uids_by_conns: self.uids_by_conns.clone(), - status_code: self.status_code.clone(), - } - } -} diff --git a/aries/misc/legacy/agency_client/src/testing/mocking.rs b/aries/misc/legacy/agency_client/src/testing/mocking.rs deleted file mode 100644 index 169dee1685..0000000000 --- a/aries/misc/legacy/agency_client/src/testing/mocking.rs +++ /dev/null @@ -1,190 +0,0 @@ -use std::sync::Mutex; - -use crate::{ - errors::error::AgencyClientResult, - testing::test_settings::{ - disable_agency_test_mode, enable_agency_test_mode, get_config_agency_test_mode, - }, -}; - -lazy_static! { - static ref AGENCY_MOCK: Mutex = Mutex::new(AgencyMock::default()); - static ref AGENCY_MOCK_DECRYPTED_RESPONSES: Mutex = - Mutex::new(AgencyMockDecrypted::default()); - static ref AGENCY_MOCK_DECRYPTED_MESSAGES: Mutex = - Mutex::new(AgencyMockDecryptedMessages::default()); - static ref HTTPCLIENT_MOCK_RESPONSES: Mutex = - Mutex::new(HttpClientMockResponse::default()); -} - -#[derive(Default)] -pub struct HttpClientMockResponse { - responses: Vec>>, -} - -impl HttpClientMockResponse { - pub fn set_next_response(response: AgencyClientResult>) { - if agency_mocks_enabled() { - HTTPCLIENT_MOCK_RESPONSES - .lock() - .expect("Could not access HTTPCLIENT_MOCK_RESPONSES") - .responses - .push(response); - } - } - - pub fn has_response() -> bool { - !HTTPCLIENT_MOCK_RESPONSES - .lock() - .expect("Could not access HTTPCLIENT_MOCK_RESPONSES") - .responses - .is_empty() - } - - pub fn get_response() -> AgencyClientResult> { - HTTPCLIENT_MOCK_RESPONSES - .lock() - .expect("Could not access HTTPCLIENT_MOCK_RESPONSES") - .responses - .pop() - .expect("No message on HTTPCLIENT_MOCK_RESPONSES stack to pop") - } -} - -#[derive(Default)] -pub struct AgencyMockDecryptedMessages { - messages: Vec, -} - -#[derive(Default)] -pub struct AgencyMock { - responses: Vec>, -} - -#[derive(Default)] -pub struct AgencyMockDecrypted { - responses: Vec, -} - -impl AgencyMock { - pub fn set_next_response(body: Vec) { - if agency_mocks_enabled() { - AGENCY_MOCK - .lock() - .expect("Could not access AGENCY_MOCK") - .responses - .push(body); - } - } - - pub fn get_response() -> Vec { - AGENCY_MOCK - .lock() - .expect("Could not access AGENCY_MOCK") - .responses - .pop() - .unwrap_or_default() - } -} - -impl AgencyMockDecrypted { - pub fn set_next_decrypted_response(body: &str) { - if agency_mocks_enabled() { - trace!("Mocks enabled, setting next decrypted response"); - AGENCY_MOCK_DECRYPTED_RESPONSES - .lock() - .expect("Could not access AGENCY_MOCK_DECRYPTED_RESPONSES") - .responses - .push(body.into()); - } - } - - pub fn get_next_decrypted_response() -> String { - if Self::has_decrypted_mock_responses() { - trace!("Mocks enabled, getting next decrypted response"); - AGENCY_MOCK_DECRYPTED_RESPONSES - .lock() - .expect("Could not access AGENCY_MOCK_DECRYPTED_RESPONSES") - .responses - .pop() - .expect("No message on AGENCY_MOCK_DECRYPTED_MESSAGES stack to pop") - } else { - debug!( - "Attempting to obtain decrypted response when none were set, but decrypted \ - messages available - returning empty response..." - ); - String::new() - } - } - - pub fn has_decrypted_mock_responses() -> bool { - !AGENCY_MOCK_DECRYPTED_RESPONSES - .lock() - .expect("Could not access AGENCY_MOCK_DECRYPTED_RESPONSES") - .responses - .is_empty() - } - - pub fn set_next_decrypted_message(message: &str) { - if agency_mocks_enabled() { - trace!("Mocks enabled, getting next decrypted message"); - AGENCY_MOCK_DECRYPTED_MESSAGES - .lock() - .expect("Could not access AGENCY_MOCK_DECRYPTED_MESSAGES") - .messages - .push(message.into()); - } - } - - pub fn get_next_decrypted_message() -> String { - AGENCY_MOCK_DECRYPTED_MESSAGES - .lock() - .expect("Could not access AGENCY_MOCK_DECRYPTED_MESSAGES") - .messages - .pop() - .expect("No message on AGENCY_MOCK_DECRYPTED_MESSAGES stack to pop") - } - - pub fn has_decrypted_mock_messages() -> bool { - !AGENCY_MOCK_DECRYPTED_MESSAGES - .lock() - .expect("Could not access AGENCY_MOCK_DECRYPTED_MESSAGES") - .messages - .is_empty() - } - - pub fn clear_mocks() { - AGENCY_MOCK_DECRYPTED_MESSAGES - .lock() - .expect("Could not access AGENCY_MOCK_DECRYPTED_MESSAGES") - .messages - .clear(); - AGENCY_MOCK_DECRYPTED_RESPONSES - .lock() - .expect("Could not access AGENCY_MOCK_DECRYPTED_RESPONSES") - .responses - .clear(); - } -} - -pub fn agency_mocks_enabled() -> bool { - match get_config_agency_test_mode().ok() { - None => false, - Some(value) => value == "true" || value == "agency", - } -} - -pub fn agency_decrypted_mocks_enabled() -> bool { - match get_config_agency_test_mode().ok() { - None => false, - Some(value) => value == "true", - } -} - -pub fn enable_agency_mocks() { - enable_agency_test_mode() -} - -pub fn disable_agency_mocks() { - disable_agency_test_mode(); -} diff --git a/aries/misc/legacy/agency_client/src/testing/mod.rs b/aries/misc/legacy/agency_client/src/testing/mod.rs deleted file mode 100644 index b536c40c5e..0000000000 --- a/aries/misc/legacy/agency_client/src/testing/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -pub mod mocking; -#[rustfmt::skip] -pub mod test_constants; -pub mod test_settings; -pub mod test_utils; diff --git a/aries/misc/legacy/agency_client/src/testing/test_constants.rs b/aries/misc/legacy/agency_client/src/testing/test_constants.rs deleted file mode 100644 index 9a1ca6b874..0000000000 --- a/aries/misc/legacy/agency_client/src/testing/test_constants.rs +++ /dev/null @@ -1,5 +0,0 @@ -pub const CREATE_KEYS_V2_RESPONSE: &[u8; 343] = &[123, 34, 109, 101, 115, 115, 97, 103, 101, 34, 58, 34, 123, 92, 34, 64, 116, 121, 112, 101, 92, 34, 58, 92, 34, 100, 105, 100, 58, 115, 111, 118, 58, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 103, 104, 105, 49, 50, 51, 52, 59, 115, 112, 101, 99, 47, 99, 111, 110, 110, 101, 99, 116, 105, 110, 103, 47, 48, 46, 54, 47, 75, 69, 89, 95, 67, 82, 69, 65, 84, 69, 68, 92, 34, 44, 92, 34, 119, 105, 116, 104, 80, 97, 105, 114, 119, 105, 115, 101, 68, 73, 68, 92, 34, 58, 92, 34, 77, 78, 101, 112, 101, 83, 87, 116, 71, 102, 104, 110, 118, 56, 106, 76, 66, 49, 115, 70, 90, 67, 92, 34, 44, 92, 34, 119, 105, 116, 104, 80, 97, 105, 114, 119, 105, 115, 101, 68, 73, 68, 86, 101, 114, 75, 101, 121, 92, 34, 58, 92, 34, 67, 55, 51, 77, 82, 110, 110, 115, 52, 113, 85, 106, 82, 53, 78, 52, 76, 82, 119, 84, 121, 105, 88, 86, 80, 75, 80, 114, 65, 53, 113, 52, 76, 67, 84, 56, 80, 90, 122, 120, 86, 100, 116, 57, 92, 34, 125, 34, 44, 34, 114, 101, 99, 105, 112, 105, 101, 110, 116, 95, 118, 101, 114, 107, 101, 121, 34, 58, 34, 50, 112, 70, 109, 113, 97, 98, 119, 75, 82, 82, 109, 80, 54, 76, 117, 67, 99, 121, 65, 70, 101, 107, 56, 77, 109, 68, 75, 107, 107, 102, 100, 72, 111, 100, 116, 57, 103, 90, 49, 67, 88, 74, 52, 34, 44, 34, 115, 101, 110, 100, 101, 114, 95, 118, 101, 114, 107, 101, 121, 34, 58, 34, 65, 66, 117, 89, 121, 84, 87, 90, 120, 113, 53, 88, 98, 105, 54, 90, 69, 119, 119, 121, 49, 97, 51, 69, 88, 51, 90, 68, 56, 100, 105, 112, 115, 109, 102, 106, 81, 53, 75, 116, 71, 116, 115, 120, 34, 125]; -pub const UPDATE_MESSAGES_RESPONSE: &[u8; 147] = &[129, 167, 98, 117, 110, 100, 108, 101, 100, 145, 220, 0, 119, 208, 130, 208, 165, 64, 116, 121, 112, 101, 208, 130, 208, 164, 110, 97, 109, 101, 208, 187, 77, 83, 71, 95, 83, 84, 65, 84, 85, 83, 95, 85, 80, 68, 65, 84, 69, 68, 95, 66, 89, 95, 67, 79, 78, 78, 83, 208, 163, 118, 101, 114, 208, 163, 49, 46, 48, 208, 178, 117, 112, 100, 97, 116, 101, 100, 85, 105, 100, 115, 66, 121, 67, 111, 110, 110, 115, 208, 145, 208, 130, 208, 171, 112, 97, 105, 114, 119, 105, 115, 101, 68, 73, 68, 208, 182, 55, 57, 82, 78, 82, 113, 77, 87, 52, 72, 106, 107, 97, 111, 98, 101, 72, 105, 69, 77, 110, 101, 208, 164, 117, 105, 100, 115, 208, 145, 208, 167, 111, 103, 109, 49, 121, 50, 102]; -pub const CONNECTED_RESPONSE_DECRYPTED: &str = r#"{"@type":"did:sov:123456789abcdefghi1234;spec/onboarding/1.0/CONNECTED","withPairwiseDID":"XSasL1cESeSJ2v9wMYeXBf","withPairwiseDIDVerKey":"HbJb8uKp4mtjhnNknP66GgmUMYta6XArNaA4WJDEyyv9"}"#; -pub const REGISTER_RESPONSE_DECRYPTED: &str = r#"{"@type":"did:sov:123456789abcdefghi1234;spec/onboarding/1.0/SIGNED_UP"}"#; -pub const AGENT_CREATED_DECRYPTED: &str = r#"{"@type":"did:sov:123456789abcdefghi1234;spec/onboarding/1.0/AGENT_CREATED","withPairwiseDID":"DnEpUQJLupa5rKPkrKUpFd","withPairwiseDIDVerKey":"7y118tRW2EMJn18qs9MY5NJWYW2PLwV5QpaLyfoLHtgF"}"#; diff --git a/aries/misc/legacy/agency_client/src/testing/test_settings.rs b/aries/misc/legacy/agency_client/src/testing/test_settings.rs deleted file mode 100644 index 1d2e52c1c3..0000000000 --- a/aries/misc/legacy/agency_client/src/testing/test_settings.rs +++ /dev/null @@ -1,55 +0,0 @@ -use std::{collections::HashMap, sync::RwLock}; - -use crate::errors::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}; - -const CONFIG_AGENCY_TEST_MODE: &str = "enable_test_mode"; - -static VALID_AGENCY_CONFIG_KEYS: &[&str] = &[CONFIG_AGENCY_TEST_MODE]; - -lazy_static! { - static ref AGENCY_SETTINGS: RwLock> = RwLock::new(HashMap::new()); -} - -pub fn get_config_agency_test_mode() -> AgencyClientResult { - _get_config_value(CONFIG_AGENCY_TEST_MODE) -} - -pub fn enable_agency_test_mode() { - _set_test_config(CONFIG_AGENCY_TEST_MODE, "true"); -} - -pub fn disable_agency_test_mode() { - _set_test_config(CONFIG_AGENCY_TEST_MODE, "false"); -} - -fn _set_test_config(key: &str, value: &str) { - trace!("set_config_value >>> key: {}, value: {}", key, value); - if !VALID_AGENCY_CONFIG_KEYS.contains(&key) { - warn!( - "Agency settings do not recognize setting key {}. Will be ignored.", - key - ); - } else { - AGENCY_SETTINGS - .write() - .expect("Could not write to AGENCY_SETTINGS") - .insert(key.to_string(), value.to_string()); - } -} - -fn _get_config_value(key: &str) -> AgencyClientResult { - trace!("get_config_value >>> key: {}", key); - - AGENCY_SETTINGS - .read() - .or(Err(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidConfiguration, - "Cannot read AGENCY_SETTINGS", - )))? - .get(key) - .map(|v| v.to_string()) - .ok_or(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidConfiguration, - format!("Cannot read \"{}\" from AGENCY_SETTINGS", key), - )) -} diff --git a/aries/misc/legacy/agency_client/src/testing/test_utils.rs b/aries/misc/legacy/agency_client/src/testing/test_utils.rs deleted file mode 100644 index a8c35f41f8..0000000000 --- a/aries/misc/legacy/agency_client/src/testing/test_utils.rs +++ /dev/null @@ -1,46 +0,0 @@ -use std::sync::Once; - -use crate::testing::{mocking, mocking::AgencyMockDecrypted}; - -pub struct SetupMocks; - -pub struct SetupWallet; - -lazy_static! { - static ref TEST_LOGGING_INIT: Once = Once::new(); -} - -pub fn init_test_logging() { - TEST_LOGGING_INIT.call_once(|| { - env_logger::init(); - }) -} - -fn setup() { - init_test_logging(); -} - -impl SetupMocks { - pub fn init() -> SetupMocks { - setup(); - mocking::enable_agency_mocks(); - SetupMocks - } -} - -impl Drop for SetupMocks { - fn drop(&mut self) { - AgencyMockDecrypted::clear_mocks(); - mocking::disable_agency_mocks(); - } -} - -impl SetupWallet { - pub fn init() -> SetupWallet { - SetupWallet - } -} - -impl Drop for SetupWallet { - fn drop(&mut self) {} -} diff --git a/aries/misc/legacy/agency_client/src/utils/encryption_envelope.rs b/aries/misc/legacy/agency_client/src/utils/encryption_envelope.rs deleted file mode 100644 index 4da3f16cab..0000000000 --- a/aries/misc/legacy/agency_client/src/utils/encryption_envelope.rs +++ /dev/null @@ -1,134 +0,0 @@ -use std::sync::Arc; - -use crate::{ - errors::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}, - testing::mocking::AgencyMockDecrypted, - wallet::base_agency_client_wallet::BaseAgencyClientWallet, -}; - -#[derive(Debug)] -pub struct EncryptionEnvelope(pub Vec); - -impl EncryptionEnvelope { - async fn _unpack_a2a_message( - wallet: Arc, - payload: Vec, - ) -> AgencyClientResult<(String, Option)> { - trace!( - "EncryptionEnvelope::_unpack_a2a_message >>> processing payload of {} bytes", - payload.len() - ); - - let unpacked_msg = wallet.unpack_message(&payload).await?; - - let msg_value: ::serde_json::Value = ::serde_json::from_slice(unpacked_msg.as_slice()) - .map_err(|err| { - AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidJson, - format!("Cannot deserialize message: {}", err), - ) - })?; - trace!( - "EncryptionEnvelope::_unpack_a2a_message >>> msg_value: {:?}", - msg_value - ); - - let sender_vk = msg_value["sender_verkey"].as_str().map(String::from); - trace!( - "EncryptionEnvelope::_unpack_a2a_message >>> sender_vk: {:?}", - sender_vk - ); - - let msg_string = msg_value["message"] - .as_str() - .ok_or(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidJson, - "Cannot find `message` field", - ))? - .to_string(); - - trace!( - "EncryptionEnvelope::_unpack_a2a_message >>> msg_string: {:?}", - msg_string - ); - - Ok((msg_string, sender_vk)) - } - - pub async fn anon_unpack( - wallet: Arc, - payload: Vec, - ) -> AgencyClientResult { - trace!( - "EncryptionEnvelope::anon_unpack >>> processing payload of {} bytes", - payload.len() - ); - if AgencyMockDecrypted::has_decrypted_mock_messages() { - trace!("EncryptionEnvelope::anon_unpack >>> returning decrypted mock message"); - Ok(AgencyMockDecrypted::get_next_decrypted_message()) - } else { - let (a2a_message, _sender_vk) = Self::_unpack_a2a_message(wallet, payload).await?; - trace!( - "EncryptionEnvelope::anon_unpack >>> a2a_message: {:?}", - a2a_message - ); - Ok(a2a_message) - } - } - - pub async fn auth_unpack( - wallet: Arc, - payload: Vec, - expected_vk: &str, - ) -> AgencyClientResult { - trace!( - "EncryptionEnvelope::auth_unpack >>> processing payload of {} bytes, expected_vk={}", - payload.len(), - expected_vk - ); - - if AgencyMockDecrypted::has_decrypted_mock_messages() { - trace!("EncryptionEnvelope::auth_unpack >>> returning decrypted mock message"); - Ok(AgencyMockDecrypted::get_next_decrypted_message()) - } else { - let (a2a_message, sender_vk) = Self::_unpack_a2a_message(wallet, payload).await?; - trace!( - "EncryptionEnvelope::auth_unpack >>> a2a_message: {:?}, sender_vk: {:?}", - a2a_message, - sender_vk - ); - - match sender_vk { - Some(sender_vk) => { - if sender_vk != expected_vk { - error!( - "auth_unpack :: sender_vk != expected_vk.... sender_vk={}, \ - expected_vk={}", - sender_vk, expected_vk - ); - return Err(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidJson, - format!( - "Message did not pass authentication check. Expected sender \ - verkey was {}, but actually was {}", - expected_vk, sender_vk - ), - )); - } - } - None => { - error!("auth_unpack :: message was authcrypted"); - return Err(AgencyClientError::from_msg( - AgencyClientErrorKind::InvalidJson, - "Can't authenticate message because it was anoncrypted.", - )); - } - } - trace!( - "EncryptionEnvelope::auth_unpack >>> a2a_message: {:?}", - a2a_message - ); - Ok(a2a_message) - } - } -} diff --git a/aries/misc/legacy/agency_client/src/utils/mod.rs b/aries/misc/legacy/agency_client/src/utils/mod.rs deleted file mode 100644 index 422fb7a293..0000000000 --- a/aries/misc/legacy/agency_client/src/utils/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod encryption_envelope; diff --git a/aries/misc/legacy/agency_client/src/wallet/base_agency_client_wallet.rs b/aries/misc/legacy/agency_client/src/wallet/base_agency_client_wallet.rs deleted file mode 100644 index b9c554ebcd..0000000000 --- a/aries/misc/legacy/agency_client/src/wallet/base_agency_client_wallet.rs +++ /dev/null @@ -1,54 +0,0 @@ -use async_trait::async_trait; - -use crate::{ - errors::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}, - testing::mocking::agency_mocks_enabled, -}; - -#[async_trait] -pub trait BaseAgencyClientWallet: std::fmt::Debug + Send + Sync { - async fn pack_message( - &self, - sender_vk: Option<&str>, - receiver_keys: &str, - msg: &[u8], - ) -> AgencyClientResult>; - - async fn unpack_message(&self, msg: &[u8]) -> AgencyClientResult>; -} - -// Stub of [BaseAgencyClientWallet] used by [AgencyClient::new] when creating a stub [AgencyClient] -// Should never be used, and should be overwritten with a proper [BaseAgencyClientWallet] -// implementation. -#[derive(Debug)] -pub(crate) struct StubAgencyClientWallet; - -#[async_trait] -impl BaseAgencyClientWallet for StubAgencyClientWallet { - async fn pack_message( - &self, - _sender_vk: Option<&str>, - _receiver_keys: &str, - msg: &[u8], - ) -> AgencyClientResult> { - if agency_mocks_enabled() { - trace!("pack_message >>> mocks enabled, returning message"); - return Ok(msg.to_vec()); - } - Err(AgencyClientError::from_msg( - AgencyClientErrorKind::UnknownError, - "Error - using a stub method: StubAgencyClientWallet::pack_message", - )) - } - - async fn unpack_message(&self, msg: &[u8]) -> AgencyClientResult> { - if agency_mocks_enabled() { - trace!("pack_message >>> mocks enabled, returning message"); - return Ok(msg.to_vec()); - } - Err(AgencyClientError::from_msg( - AgencyClientErrorKind::UnknownError, - "Error - using a stub method: StubAgencyClientWallet::unpack_message", - )) - } -} diff --git a/aries/misc/legacy/agency_client/src/wallet/mod.rs b/aries/misc/legacy/agency_client/src/wallet/mod.rs deleted file mode 100644 index 8e3286a7d2..0000000000 --- a/aries/misc/legacy/agency_client/src/wallet/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod base_agency_client_wallet; diff --git a/aries/misc/test_utils/Cargo.toml b/aries/misc/test_utils/Cargo.toml index dba1e20c20..b1604ead2d 100644 --- a/aries/misc/test_utils/Cargo.toml +++ b/aries/misc/test_utils/Cargo.toml @@ -17,7 +17,6 @@ anoncreds = ["aries_vcx_core/anoncreds"] [dependencies] anoncreds_types = { path = "../../misc/anoncreds_types" } aries_vcx_core = { path = "../../aries_vcx_core" } -agency_client = { path = "../legacy/agency_client" } libvcx_logger = { path = "../legacy/libvcx_logger" } did_parser = { path = "../../../did_core/did_parser" } public_key = { path = "../../../did_core/public_key" } diff --git a/aries/misc/test_utils/src/devsetup.rs b/aries/misc/test_utils/src/devsetup.rs index 2a03a0a305..6c0dc91092 100644 --- a/aries/misc/test_utils/src/devsetup.rs +++ b/aries/misc/test_utils/src/devsetup.rs @@ -4,7 +4,6 @@ use std::{ path::{Path, PathBuf}, }; -use agency_client::testing::mocking::{enable_agency_mocks, AgencyMockDecrypted}; use aries_vcx_core::{ anoncreds::base_anoncreds::BaseAnonCreds, errors::error::{AriesVcxCoreError, AriesVcxCoreErrorKind, VcxCoreResult}, @@ -24,7 +23,7 @@ use aries_vcx_core::{ use chrono::{DateTime, Duration, Utc}; use did_parser::Did; use libvcx_logger::init_test_logging; -use log::{debug, info, warn}; +use log::{debug, info}; use crate::constants::{POOL1_TXN, TRUSTEE_SEED}; @@ -130,25 +129,13 @@ pub struct SetupPoolDirectory { pub genesis_file_path: String, } -pub fn reset_global_state() { - warn!("reset_global_state >>"); - AgencyMockDecrypted::clear_mocks(); -} - impl SetupMocks { pub fn init() -> SetupMocks { init_test_logging(); - enable_agency_mocks(); SetupMocks } } -impl Drop for SetupMocks { - fn drop(&mut self) { - reset_global_state(); - } -} - pub fn dev_build_profile_vdr_ledger( genesis_file_path: String, ) -> (DefaultIndyLedgerRead, DefaultIndyLedgerWrite) {