Skip to content

Commit

Permalink
Refactor and strip down Aries transport abstraction and further code …
Browse files Browse the repository at this point in the history
…trimming (#1040)

* Refactor and strip down Aries transport abstraction and further code trimming (#1040)

Signed-off-by: Naian <[email protected]>
  • Loading branch information
nain-F49FF806 authored Nov 2, 2023
1 parent ad26ecf commit fee4076
Show file tree
Hide file tree
Showing 9 changed files with 103 additions and 247 deletions.
2 changes: 1 addition & 1 deletion agents/rust/mediator/client-tui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::collections::VecDeque;

use aries_vcx_core::wallet::base_wallet::BaseWallet;
use mediation::storage::MediatorPersistence;
use mediator::aries_agent::{transports::AriesReqwest, ArcAgent};
use mediator::aries_agent::{client::transports::AriesReqwest, ArcAgent};
use messages::msg_fields::protocols::out_of_band::invitation::Invitation as OOBInvitation;
use serde_json::{json, Value};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ use messages::{
AriesMessage,
};
use test_utils::mockdata::mock_ledger::MockLedger;
pub mod transports;

use super::{transports::AriesTransport, Agent};
use self::transports::AriesTransport;
use super::Agent;
use crate::{aries_agent::utils::oob2did, utils::prelude::*};

// client role utilities
Expand Down Expand Up @@ -112,10 +114,9 @@ impl<T: BaseWallet + 'static, P: MediatorPersistence> Agent<T, P> {
"Sending Connection Request Envelope: {},",
serde_json::to_string_pretty(&packed_aries_msg_json).unwrap()
);
aries_transport
.push_aries_envelope(packed_aries_msg_json, &oob2did(oob_invite))
let response_envelope = aries_transport
.send_aries_envelope(packed_aries_msg_json, &oob2did(oob_invite))
.await?;
let response_envelope = aries_transport.pop_aries_envelope()?;
info!(
"Received Response envelope {:#?}, unpacking",
serde_json::to_string_pretty(&response_envelope).unwrap()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::collections::VecDeque;

use async_trait::async_trait;
use diddoc_legacy::aries::diddoc::AriesDidDoc;
use log::info;
use log::debug;
use serde_json::Value;

#[derive(thiserror::Error, Debug)]
Expand All @@ -21,12 +21,12 @@ impl AriesTransportError {

#[async_trait]
pub trait AriesTransport {
fn pop_aries_envelope(&mut self) -> Result<Value, AriesTransportError>;
async fn push_aries_envelope(
/// Send envelope to destination (defined in AriesDidDoc) and return response
async fn send_aries_envelope(
&mut self,
envelope_json: Value,
destination: &AriesDidDoc,
) -> Result<(), AriesTransportError>;
) -> Result<Value, AriesTransportError>;
}

pub struct AriesReqwest {
Expand All @@ -36,14 +36,18 @@ pub struct AriesReqwest {

#[async_trait]
impl AriesTransport for AriesReqwest {
async fn push_aries_envelope(
async fn send_aries_envelope(
&mut self,
envelope_json: Value,
destination: &AriesDidDoc,
) -> Result<(), AriesTransportError> {
) -> Result<Value, AriesTransportError> {
let oob_invited_endpoint = destination
.get_endpoint()
.expect("Service needs an endpoint");
debug!(
"Packed: {:?}, sending",
serde_json::to_string(&envelope_json).unwrap()
);
let res = self
.client
.post(oob_invited_endpoint)
Expand All @@ -57,13 +61,7 @@ impl AriesTransport for AriesReqwest {
.json()
.await
.map_err(AriesTransportError::from_std_error)?;
info!("Received aries response{:?}", res_json);
self.response_queue.push_back(res_json);
Ok(())
}
fn pop_aries_envelope(&mut self) -> Result<Value, AriesTransportError> {
self.response_queue.pop_front().ok_or(AriesTransportError {
msg: "No messages in queue".to_owned(),
})
debug!("Received response envelope {:?}", res_json);
Ok(res_json)
}
}
21 changes: 0 additions & 21 deletions agents/rust/mediator/src/aries_agent/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,10 @@ use messages::{
};
use serde_json::json;

use self::transports::AriesTransport;
use crate::utils::{prelude::*, structs::VerKey};

#[cfg(any(test, feature = "client"))]
pub mod client;
pub mod transports;
pub mod utils;

#[derive(Clone)]
Expand Down Expand Up @@ -143,25 +141,6 @@ impl<T: BaseWallet + 'static, P: MediatorPersistence> Agent<T, P> {
.await
.map_err(string_from_std_error)
}
pub async fn pack_and_send_didcomm(
&self,
message: &[u8],
our_vk: &VerKey,
their_diddoc: &AriesDidDoc,
aries_transport: &mut impl AriesTransport,
) -> Result<(), String> {
let EncryptionEnvelope(packed_message) =
self.pack_didcomm(message, our_vk, their_diddoc).await?;
let packed_json = serde_json::from_slice(&packed_message).map_err(string_from_std_error)?;
info!(
"Packed: {:?}, sending",
serde_json::to_string(&packed_json).unwrap()
);
aries_transport
.push_aries_envelope(packed_json, their_diddoc)
.await
.map_err(string_from_std_error)
}

pub async fn auth_and_get_details(
&self,
Expand Down
60 changes: 52 additions & 8 deletions agents/rust/mediator/tests/common/agent_and_transport_utils.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
use std::collections::VecDeque;

use aries_vcx::protocols::connection::invitee::{states::completed::Completed, InviteeConnection};
use aries_vcx::{
protocols::connection::invitee::{states::completed::Completed, InviteeConnection},
utils::encryption_envelope::EncryptionEnvelope,
};
use aries_vcx_core::wallet::base_wallet::BaseWallet;
use diddoc_legacy::aries::diddoc::AriesDidDoc;
use mediation::storage::MediatorPersistence;
use mediation::{
didcomm_types::mediator_coord_structs::{MediateGrantData, MediatorCoordMsgEnum},
storage::MediatorPersistence,
};
use mediator::{
aries_agent::{
transports::{AriesReqwest, AriesTransport},
client::transports::{AriesReqwest, AriesTransport},
Agent,
},
utils::{structs::VerKey, GenericStringError},
Expand Down Expand Up @@ -68,15 +74,53 @@ pub async fn send_message_and_pop_response_message(
our_verkey: &VerKey,
their_diddoc: &AriesDidDoc,
) -> Result<String> {
agent
.pack_and_send_didcomm(message_bytes, our_verkey, their_diddoc, aries_transport)
// Wrap message in encrypted envelope
let EncryptionEnvelope(packed_message) = agent
.pack_didcomm(message_bytes, our_verkey, their_diddoc)
.await
.map_err(|err| GenericStringError { msg: err })?;
.map_err(|e| GenericStringError { msg: e.to_string() })?;
let packed_json = serde_json::from_slice(&packed_message)?;
// Send serialized envelope over transport
let response_envelope = aries_transport
.send_aries_envelope(packed_json, their_diddoc)
.await?;
// unpack
let response = aries_transport.pop_aries_envelope()?;
let unpacked_response = agent
.unpack_didcomm(&serde_json::to_vec(&response).unwrap())
.unpack_didcomm(&serde_json::to_vec(&response_envelope).unwrap())
.await
.unwrap();
Ok(unpacked_response.message)
}

pub async fn get_mediator_grant_data(
agent: &Agent<impl BaseWallet + 'static, impl MediatorPersistence>,
agent_aries_transport: &mut impl AriesTransport,
agent_verkey: &VerKey,
mediator_diddoc: &AriesDidDoc,
) -> MediateGrantData {
// prepare request message
let message = MediatorCoordMsgEnum::MediateRequest;
let message_bytes = serde_json::to_vec(&message).unwrap();
// send message and get response
let response_message = send_message_and_pop_response_message(
&message_bytes,
agent,
agent_aries_transport,
agent_verkey,
mediator_diddoc,
)
.await
.unwrap();
// extract routing parameters
if let MediatorCoordMsgEnum::MediateGrant(grant_data) =
serde_json::from_str(&response_message).unwrap()
{
info!("Grant Data {:?}", grant_data);
grant_data
} else {
panic!(
"Should get response that is of type Mediator Grant. Found {:?}",
response_message
)
}
}
2 changes: 1 addition & 1 deletion agents/rust/mediator/tests/mediator-aries-connection.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mod common;
use std::collections::VecDeque;

use mediator::aries_agent::transports::AriesReqwest;
use mediator::aries_agent::client::transports::AriesReqwest;
use messages::msg_fields::protocols::out_of_band::invitation::Invitation as OOBInvitation;
use reqwest::header::ACCEPT;

Expand Down
107 changes: 9 additions & 98 deletions agents/rust/mediator/tests/mediator-coord-protocol.rs
Original file line number Diff line number Diff line change
@@ -1,110 +1,21 @@
mod common;
use std::collections::VecDeque;

use aries_vcx::protocols::connection::invitee::{states::completed::Completed, InviteeConnection};
use aries_vcx_core::wallet::base_wallet::BaseWallet;
use diddoc_legacy::aries::diddoc::AriesDidDoc;
use mediation::{
didcomm_types::mediator_coord_structs::{
KeylistData, KeylistQueryData, KeylistUpdateItem, KeylistUpdateItemAction,
KeylistUpdateRequestData, MediatorCoordMsgEnum,
},
storage::MediatorPersistence,
use mediation::didcomm_types::mediator_coord_structs::{
KeylistData, KeylistQueryData, KeylistUpdateItem, KeylistUpdateItemAction,
KeylistUpdateRequestData, MediatorCoordMsgEnum,
};
use mediator::{
aries_agent::{
transports::{AriesReqwest, AriesTransport},
Agent,

use crate::common::{
agent_and_transport_utils::{
gen_mediator_connected_agent, send_message_and_pop_response_message,
},
utils::{structs::VerKey, GenericStringError},
prelude::*,
test_setup::setup_env_logging,
};
use messages::msg_fields::protocols::out_of_band::invitation::Invitation as OOBInvitation;
use reqwest::header::ACCEPT;

use crate::common::{prelude::*, test_setup::setup_env_logging};

static LOGGING_INIT: std::sync::Once = std::sync::Once::new();

const ENDPOINT_ROOT: &str = "http://localhost:8005";

async fn didcomm_connection(
agent: &Agent<impl BaseWallet + 'static, impl MediatorPersistence>,
aries_transport: &mut impl AriesTransport,
) -> Result<InviteeConnection<Completed>> {
let client = reqwest::Client::new();
let base: Url = ENDPOINT_ROOT.parse().unwrap();
let endpoint_register = base.join("register").unwrap();

let oobi: OOBInvitation = client
.get(endpoint_register)
.header(ACCEPT, "application/json")
.send()
.await?
.error_for_status()?
.json()
.await?;
info!("Got invitation from register endpoint {:?}", oobi);

let state: InviteeConnection<Completed> =
agent.establish_connection(oobi, aries_transport).await?;

Ok(state)
}

/// Returns agent, aries transport for agent, agent's verkey, and mediator's diddoc.
async fn gen_mediator_connected_agent() -> Result<(
Agent<impl BaseWallet + 'static, impl MediatorPersistence>,
impl AriesTransport,
VerKey,
AriesDidDoc,
)> {
let agent = mediator::aries_agent::AgentBuilder::new_demo_agent().await?;
let mut aries_transport = AriesReqwest {
response_queue: VecDeque::new(),
client: reqwest::Client::new(),
};
let completed_connection = didcomm_connection(&agent, &mut aries_transport).await?;
let our_verkey: VerKey = completed_connection.pairwise_info().pw_vk.clone();
let their_diddoc = completed_connection.their_did_doc().clone();
Ok((agent, aries_transport, our_verkey, their_diddoc))
}

/// Sends message over didcomm connection and returns unpacked response message
async fn send_message_and_pop_response_message(
message_bytes: &[u8],
agent: &Agent<impl BaseWallet + 'static, impl MediatorPersistence>,
aries_transport: &mut impl AriesTransport,
our_verkey: &VerKey,
their_diddoc: &AriesDidDoc,
) -> Result<String> {
agent
.pack_and_send_didcomm(message_bytes, our_verkey, their_diddoc, aries_transport)
.await
.map_err(|err| GenericStringError { msg: err })?;
// unpack
let response = aries_transport.pop_aries_envelope()?;
let unpacked_response = agent
.unpack_didcomm(&serde_json::to_vec(&response).unwrap())
.await
.unwrap();
Ok(unpacked_response.message)
}

#[tokio::test]
#[ignore]
async fn test_init() {
LOGGING_INIT.call_once(setup_env_logging);
let agent = mediator::aries_agent::AgentBuilder::new_demo_agent()
.await
.unwrap();
let mut aries_transport = AriesReqwest {
response_queue: VecDeque::new(),
client: reqwest::Client::new(),
};
let _ = didcomm_connection(&agent, &mut aries_transport).await;
let _ = didcomm_connection(&agent, &mut aries_transport).await;
}

#[tokio::test]
async fn test_mediate_grant() -> Result<()> {
LOGGING_INIT.call_once(setup_env_logging);
Expand Down
Loading

0 comments on commit fee4076

Please sign in to comment.