repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/entry_tags.rs | aries/aries_vcx_wallet/src/wallet/askar/entry_tags.rs | use aries_askar::entry::EntryTag;
use crate::wallet::record_tags::{RecordTag, RecordTags};
impl From<EntryTag> for RecordTag {
fn from(askar_tag: EntryTag) -> Self {
match askar_tag {
EntryTag::Encrypted(key, val) => RecordTag::new(&key, &val),
EntryTag::Plaintext(key, val) => RecordTag::new(&format!("~{key}"), &val),
}
}
}
impl From<RecordTag> for EntryTag {
fn from(entry_tag: RecordTag) -> Self {
if entry_tag.key().starts_with('~') {
Self::Plaintext(
entry_tag.key().to_string().trim_start_matches('~').into(),
entry_tag.value().into(),
)
} else {
Self::Encrypted(entry_tag.key().into(), entry_tag.value().into())
}
}
}
impl From<RecordTags> for Vec<EntryTag> {
fn from(tags: RecordTags) -> Self {
let tags_vec: Vec<RecordTag> = tags.into();
tags_vec.into_iter().map(Into::into).collect()
}
}
impl From<Vec<EntryTag>> for RecordTags {
fn from(askar_tags: Vec<EntryTag>) -> Self {
askar_tags.into_iter().map(Into::into).collect()
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/askar_record_wallet.rs | aries/aries_vcx_wallet/src/wallet/askar/askar_record_wallet.rs | use std::str::FromStr;
use aries_askar::entry::{EntryTag, TagFilter};
use async_trait::async_trait;
use super::{all_askar_records::AllAskarRecords, AskarWallet};
use crate::{
errors::error::{VcxWalletError, VcxWalletResult},
wallet::{
base_wallet::{
record::{AllRecords, PartialRecord, Record},
record_category::RecordCategory,
record_wallet::RecordWallet,
},
record_tags::RecordTags,
},
};
#[async_trait]
impl RecordWallet for AskarWallet {
async fn add_record(&self, record: Record) -> VcxWalletResult<()> {
let tags: Option<Vec<EntryTag>> = Some(record.tags().clone().into());
Ok(self
.session()
.await?
.insert(
&record.category().to_string(),
record.name(),
record.value().as_bytes(),
tags.as_deref(),
None,
)
.await?)
}
async fn get_record(&self, category: RecordCategory, name: &str) -> VcxWalletResult<Record> {
let mut session = self.session().await?;
Ok(self
.fetch(&mut session, category, name, false)
.await
.map(TryFrom::try_from)??)
}
async fn update_record_tags(
&self,
category: RecordCategory,
name: &str,
new_tags: RecordTags,
) -> VcxWalletResult<()> {
let mut session = self.session().await?;
let askar_tags: Vec<EntryTag> = new_tags.into();
let entry = self.fetch(&mut session, category, name, true).await?;
Ok(session
.replace(
&category.to_string(),
name,
&entry.value,
Some(&askar_tags),
None,
)
.await?)
}
async fn update_record_value(
&self,
category: RecordCategory,
name: &str,
new_value: &str,
) -> VcxWalletResult<()> {
let mut session = self.session().await?;
let entry = self.fetch(&mut session, category, name, true).await?;
Ok(session
.replace(
&category.to_string(),
name,
new_value.as_bytes(),
Some(&entry.tags),
None,
)
.await?)
}
async fn delete_record(&self, category: RecordCategory, name: &str) -> VcxWalletResult<()> {
Ok(self
.session()
.await?
.remove(&category.to_string(), name)
.await?)
}
#[allow(unreachable_patterns)]
async fn search_record(
&self,
category: RecordCategory,
search_filter: Option<String>,
) -> VcxWalletResult<Vec<Record>> {
let filter = search_filter
.map(|inner| TagFilter::from_str(&inner))
.transpose()
.map_err(|err| VcxWalletError::InvalidInput(err.to_string()))?;
Ok(self
.session()
.await?
.fetch_all(Some(&category.to_string()), filter, None, None, true, false)
.await?
.into_iter()
.map(TryFrom::try_from)
.collect::<Vec<Result<Record, _>>>()
.into_iter()
.collect::<Result<_, _>>()?)
}
async fn all_records(&self) -> VcxWalletResult<Box<dyn AllRecords + Send>> {
let mut session = self.session().await?;
let recs = session
.fetch_all(None, None, None, None, true, false)
.await?;
let mut recs = recs
.into_iter()
.map(PartialRecord::from_askar_entry)
.collect::<Result<Vec<_>, _>>()?;
let keys = session
.fetch_all_keys(None, None, None, None, false)
.await?;
let mut local_keys = keys
.into_iter()
.map(PartialRecord::from_askar_key_entry)
.collect::<Result<Vec<_>, _>>()?;
recs.append(&mut local_keys);
let total_count = recs.len();
Ok(Box::new(AllAskarRecords::new(
recs.into_iter(),
Some(total_count),
)))
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/pack.rs | aries/aries_vcx_wallet/src/wallet/askar/pack.rs | use aries_askar::kms::{
crypto_box, crypto_box_random_nonce, crypto_box_seal, KeyAlg::Ed25519, LocalKey,
};
use public_key::Key;
use super::{
askar_utils::ed25519_to_x25519,
packing_types::{
Jwe, JweAlg, ProtectedData, ProtectedHeaderEnc, ProtectedHeaderTyp, Recipient,
},
};
use crate::{
errors::error::{VcxWalletError, VcxWalletResult},
wallet::{
base_wallet::base64_string::Base64String,
utils::{bs58_to_bytes, bytes_to_bs58},
},
};
fn check_supported_key_alg(key: &LocalKey) -> VcxWalletResult<()> {
let supported_algs = vec![Ed25519];
if !supported_algs.contains(&key.algorithm()) {
let msg = format!(
"Unsupported key algorithm, expected one of: {}",
supported_algs
.into_iter()
.map(|alg| alg.to_string())
.collect::<Vec<_>>()
.join(", ")
);
Err(VcxWalletError::InvalidInput(msg))
} else {
Ok(())
}
}
fn encode_protected_data(
encrypted_recipients: Vec<Recipient>,
jwe_alg: JweAlg,
) -> VcxWalletResult<Base64String> {
let protected_data = ProtectedData {
enc: ProtectedHeaderEnc::XChaCha20Poly1305,
typ: ProtectedHeaderTyp::Jwm,
alg: jwe_alg,
recipients: encrypted_recipients,
};
let protected_encoded = serde_json::to_string(&protected_data)?;
Ok(Base64String::from_bytes(protected_encoded.as_bytes()))
}
fn pack_authcrypt_recipients(
enc_key: &LocalKey,
recipient_keys: Vec<Key>,
sender_local_key: LocalKey,
) -> VcxWalletResult<Vec<Recipient>> {
let mut encrypted_recipients = Vec::with_capacity(recipient_keys.len());
let sender_converted_key = ed25519_to_x25519(&sender_local_key)?;
for recipient_key in recipient_keys {
let recipient_public_key = &LocalKey::from_public_bytes(Ed25519, recipient_key.key())?;
let nonce = crypto_box_random_nonce()?;
let recipient_converted_key = ed25519_to_x25519(recipient_public_key)?;
let enc_cek = crypto_box(
&recipient_converted_key,
&sender_converted_key,
&enc_key.to_secret_bytes()?,
&nonce,
)?;
let sender_ed25519_pk = sender_local_key.to_public_bytes()?;
let enc_sender = crypto_box_seal(
&recipient_converted_key,
bytes_to_bs58(&sender_ed25519_pk).as_bytes(),
)?;
encrypted_recipients.push(Recipient::new_authcrypt(
Base64String::from_bytes(&enc_cek),
&recipient_key.base58(),
Base64String::from_bytes(&nonce),
Base64String::from_bytes(&enc_sender),
));
}
Ok(encrypted_recipients)
}
fn pack_anoncrypt_recipients(
enc_key: &LocalKey,
recipient_keys: Vec<Key>,
) -> VcxWalletResult<Vec<Recipient>> {
let mut encrypted_recipients = Vec::with_capacity(recipient_keys.len());
let enc_key_secret = &enc_key.to_secret_bytes()?;
for recipient_key in recipient_keys {
let recipient_pubkey = bs58_to_bytes(recipient_key.base58().as_bytes())?;
let recipient_local_key = LocalKey::from_public_bytes(Ed25519, &recipient_pubkey)?;
let enc_cek = crypto_box_seal(&ed25519_to_x25519(&recipient_local_key)?, enc_key_secret)?;
let kid = bytes_to_bs58(&recipient_pubkey);
encrypted_recipients.push(Recipient::new_anoncrypt(
Base64String::from_bytes(&enc_cek),
&kid,
));
}
Ok(encrypted_recipients)
}
pub trait Pack {
fn pack_authcrypt(
&self,
recipient_keys: Vec<Key>,
sender_local_key: LocalKey,
) -> VcxWalletResult<Base64String>;
fn pack_anoncrypt(&self, recipient_keys: Vec<Key>) -> VcxWalletResult<Base64String>;
fn pack_all(&self, base64_data: Base64String, msg: &[u8]) -> VcxWalletResult<Vec<u8>>;
}
impl Pack for LocalKey {
fn pack_authcrypt(
&self,
recipient_keys: Vec<Key>,
sender_local_key: LocalKey,
) -> VcxWalletResult<Base64String> {
check_supported_key_alg(&sender_local_key)?;
encode_protected_data(
pack_authcrypt_recipients(self, recipient_keys, sender_local_key)?,
JweAlg::Authcrypt,
)
}
fn pack_anoncrypt(&self, recipient_keys: Vec<Key>) -> VcxWalletResult<Base64String> {
let encrypted_recipients = pack_anoncrypt_recipients(self, recipient_keys)?;
encode_protected_data(encrypted_recipients, JweAlg::Anoncrypt)
}
fn pack_all(&self, base64_data: Base64String, msg: &[u8]) -> VcxWalletResult<Vec<u8>> {
let enc = self.aead_encrypt(msg, &self.aead_random_nonce()?, &base64_data.as_bytes())?;
Ok(serde_json::to_vec(&Jwe {
protected: base64_data,
iv: Base64String::from_bytes(enc.nonce()),
ciphertext: Base64String::from_bytes(enc.ciphertext()),
tag: Base64String::from_bytes(enc.tag()),
})?)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/packing_types.rs | aries/aries_vcx_wallet/src/wallet/askar/packing_types.rs | use serde::{de::Unexpected, Deserialize, Serialize};
use crate::wallet::base_wallet::base64_string::Base64String;
pub const PROTECTED_HEADER_ENC: &str = "xchacha20poly1305_ietf";
pub const PROTECTED_HEADER_TYP: &str = "JWM/1.0";
#[derive(Debug)]
pub enum ProtectedHeaderEnc {
XChaCha20Poly1305,
}
impl Serialize for ProtectedHeaderEnc {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(match self {
Self::XChaCha20Poly1305 => PROTECTED_HEADER_ENC,
})
}
}
impl<'de> Deserialize<'de> for ProtectedHeaderEnc {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
match value.as_str() {
PROTECTED_HEADER_ENC => Ok(Self::XChaCha20Poly1305),
_ => Err(serde::de::Error::invalid_value(
Unexpected::Str(value.as_str()),
&PROTECTED_HEADER_ENC,
)),
}
}
}
#[derive(Debug)]
pub enum ProtectedHeaderTyp {
Jwm,
}
impl Serialize for ProtectedHeaderTyp {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(match self {
Self::Jwm => PROTECTED_HEADER_TYP,
})
}
}
impl<'de> Deserialize<'de> for ProtectedHeaderTyp {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
match value.as_str() {
PROTECTED_HEADER_TYP => Ok(Self::Jwm),
_ => Err(serde::de::Error::invalid_value(
Unexpected::Str(value.as_str()),
&PROTECTED_HEADER_TYP,
)),
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Jwe {
pub protected: Base64String,
pub iv: Base64String,
pub ciphertext: Base64String,
pub tag: Base64String,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum JweAlg {
Authcrypt,
Anoncrypt,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ProtectedData {
pub enc: ProtectedHeaderEnc,
pub typ: ProtectedHeaderTyp,
pub alg: JweAlg,
pub recipients: Vec<Recipient>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum Recipient {
Authcrypt(AuthcryptRecipient),
Anoncrypt(AnoncryptRecipient),
}
impl Recipient {
pub fn new_authcrypt(
encrypted_key: Base64String,
kid: &str,
iv: Base64String,
sender: Base64String,
) -> Self {
Self::Authcrypt(AuthcryptRecipient {
encrypted_key,
header: AuthcryptHeader {
kid: kid.into(),
iv,
sender,
},
})
}
pub fn new_anoncrypt(encrypted_key: Base64String, kid: &str) -> Self {
Self::Anoncrypt(AnoncryptRecipient {
encrypted_key,
header: AnoncryptHeader { kid: kid.into() },
})
}
pub fn unwrap_kid(&self) -> &str {
match self {
Self::Anoncrypt(inner) => &inner.header.kid,
Self::Authcrypt(inner) => &inner.header.kid,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct AuthcryptRecipient {
pub encrypted_key: Base64String,
pub header: AuthcryptHeader,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct AnoncryptRecipient {
pub encrypted_key: Base64String,
pub header: AnoncryptHeader,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct AuthcryptHeader {
pub kid: String,
pub iv: Base64String,
pub sender: Base64String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct AnoncryptHeader {
pub kid: String,
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/sig_type.rs | aries/aries_vcx_wallet/src/wallet/askar/sig_type.rs | use aries_askar::{crypto::alg::EcCurves, kms::KeyAlg};
use crate::errors::error::{VcxWalletError, VcxWalletResult};
#[derive(Debug, Copy, Clone)]
pub enum SigType {
EdDSA,
ES256,
ES256K,
ES384,
}
impl From<SigType> for &str {
fn from(value: SigType) -> Self {
match value {
SigType::EdDSA => "eddsa",
SigType::ES256 => "es256",
SigType::ES256K => "es256k",
SigType::ES384 => "es384",
}
}
}
impl SigType {
pub fn try_from_key_alg(key_alg: KeyAlg) -> VcxWalletResult<Self> {
match key_alg {
KeyAlg::Ed25519 => Ok(SigType::EdDSA),
KeyAlg::EcCurve(item) => match item {
EcCurves::Secp256r1 => Ok(SigType::ES256),
EcCurves::Secp256k1 => Ok(SigType::ES256K),
EcCurves::Secp384r1 => Ok(SigType::ES384),
},
alg => Err(VcxWalletError::InvalidInput(format!(
"{alg} does not support signing"
))),
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/rng_method.rs | aries/aries_vcx_wallet/src/wallet/askar/rng_method.rs | #[derive(Clone, Default, Copy, Debug)]
pub enum RngMethod {
#[default]
RandomDet,
Bls,
}
impl From<RngMethod> for Option<&str> {
fn from(value: RngMethod) -> Self {
match value {
RngMethod::RandomDet => None,
RngMethod::Bls => Some("bls_keygen"),
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/partial_record.rs | aries/aries_vcx_wallet/src/wallet/askar/partial_record.rs | use super::askar_utils::value_from_entry;
use crate::{
errors::error::VcxWalletResult,
wallet::{
askar::askar_utils::{local_key_to_bs58_private_key, local_key_to_bs58_public_key},
base_wallet::{
key_value::KeyValue, record::PartialRecord, record_category::RecordCategory,
},
},
};
impl PartialRecord {
pub fn from_askar_entry(entry: aries_askar::entry::Entry) -> VcxWalletResult<Self> {
Ok(Self::builder()
.name(entry.name.clone())
.category(Some(entry.category.clone()))
.value(Some(value_from_entry(entry.clone())?))
.tags(Some(entry.tags.into()))
.build())
}
pub fn from_askar_key_entry(key_entry: aries_askar::kms::KeyEntry) -> VcxWalletResult<Self> {
let local_key = key_entry.load_local_key()?;
let name = key_entry.name();
let tags = key_entry.tags_as_slice();
let value = KeyValue::new(
local_key_to_bs58_private_key(&local_key)?,
local_key_to_bs58_public_key(&local_key)?,
);
let value = serde_json::to_string(&value)?;
Ok(Self::builder()
.name(name.into())
.category(Some(RecordCategory::Key.to_string()))
.value(Some(value))
.tags(Some(tags.to_vec().into()))
.build())
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/mod.rs | aries/aries_vcx_wallet/src/wallet/askar/mod.rs | use aries_askar::{
entry::{Entry, EntryTag},
kms::{KeyAlg, KeyEntry, LocalKey},
Session, Store,
};
use async_trait::async_trait;
use public_key::Key;
use self::{askar_utils::local_key_to_bs58_public_key, askar_wallet_config::AskarWalletConfig};
use super::{
base_wallet::{
did_value::DidValue, key_value::KeyValue, record_category::RecordCategory, BaseWallet,
},
record_tags::RecordTags,
};
use crate::errors::error::{VcxWalletError, VcxWalletResult};
mod all_askar_records;
mod askar_did_wallet;
pub mod askar_import_config;
mod askar_record_wallet;
mod askar_utils;
pub mod askar_wallet_config;
mod entry;
mod entry_tags;
pub mod key_method;
mod pack;
mod packing_types;
mod partial_record;
mod rng_method;
mod sig_type;
mod unpack;
#[derive(Debug)]
pub struct AskarWallet {
backend: Store,
profile: String,
}
#[async_trait]
impl BaseWallet for AskarWallet {
async fn export_wallet(&self, _path: &str, _backup_key: &str) -> VcxWalletResult<()> {
todo!()
}
async fn close_wallet(&self) -> VcxWalletResult<()> {
todo!()
}
async fn create_key(
&self,
name: &str,
value: KeyValue,
tags: &RecordTags,
) -> VcxWalletResult<()> {
let mut session = self.session().await?;
let tg: Vec<_> = tags.clone().into();
let key = LocalKey::from_secret_bytes(KeyAlg::Ed25519, &value.signkey().decode()?[0..32])?;
Ok(session
.insert_key(name, &key, None, None, Some(&tg), None)
.await?)
}
}
impl AskarWallet {
pub async fn create(
wallet_config: &AskarWalletConfig,
recreate: bool,
) -> VcxWalletResult<Self> {
let backend = Store::provision(
wallet_config.db_url(),
(*wallet_config.key_method()).into(),
wallet_config.pass_key().into(),
Some(wallet_config.profile().to_owned()),
recreate,
)
.await?;
Ok(Self {
backend,
profile: wallet_config.profile().into(),
})
}
pub async fn open(wallet_config: &AskarWalletConfig) -> VcxWalletResult<Self> {
Ok(Self {
backend: Store::open(
wallet_config.db_url(),
Some((*wallet_config.key_method()).into()),
wallet_config.pass_key().into(),
Some(wallet_config.profile().into()),
)
.await?,
profile: wallet_config.profile().into(),
})
}
async fn fetch(
&self,
session: &mut Session,
category: RecordCategory,
name: &str,
for_update: bool,
) -> VcxWalletResult<Entry> {
let maybe_entry = session
.fetch(&category.to_string(), name, for_update)
.await
.map_err(|err| match err.kind() {
aries_askar::ErrorKind::NotFound => {
VcxWalletError::record_not_found_from_details(category, name)
}
_ => err.into(),
})?;
maybe_entry.ok_or_else(|| VcxWalletError::record_not_found_from_details(category, name))
}
async fn fetch_local_key(
&self,
session: &mut Session,
key_name: &str,
) -> VcxWalletResult<LocalKey> {
Ok(self
.fetch_key_entry(session, key_name)
.await?
.load_local_key()?)
}
async fn fetch_key_entry(
&self,
session: &mut Session,
key_name: &str,
) -> VcxWalletResult<KeyEntry> {
session.fetch_key(key_name, false).await?.ok_or_else(|| {
VcxWalletError::record_not_found_from_details(RecordCategory::Key, key_name)
})
}
async fn insert_key(
&self,
session: &mut Session,
alg: KeyAlg,
seed: &[u8],
) -> VcxWalletResult<(String, LocalKey)> {
let key = LocalKey::from_secret_bytes(alg, seed)?;
let key_name = local_key_to_bs58_public_key(&key)?.into_inner();
session
.insert_key(&key_name, &key, None, None, None, None)
.await?;
Ok((key_name, key))
}
async fn find_did(
&self,
session: &mut Session,
did: &str,
category: RecordCategory,
) -> VcxWalletResult<Option<DidValue>> {
let entry = self.fetch(session, category, did, false).await?;
if let Some(val) = entry.value.as_opt_str() {
Ok(serde_json::from_str(val)?)
} else {
Err(VcxWalletError::InvalidInput(
"wallet entry value is not a valid character sequence".into(),
))
}
}
async fn find_current_did(
&self,
session: &mut Session,
did: &str,
) -> VcxWalletResult<Option<DidValue>> {
self.find_did(session, did, RecordCategory::Did).await
}
async fn insert_did(
&self,
session: &mut Session,
did: &str,
category: &str,
verkey: &Key,
tags: Option<&[EntryTag]>,
) -> VcxWalletResult<()> {
if (session.fetch(did, category, false).await?).is_some() {
Err(VcxWalletError::DuplicateRecord(format!(
"category: {}, name: {}",
RecordCategory::Did,
category
)))
} else {
Ok(session
.insert(
category,
did,
serde_json::to_string(&DidValue::new(verkey))?.as_bytes(),
tags,
None,
)
.await?)
}
}
async fn update_did(
&self,
session: &mut Session,
did: &str,
category: &str,
verkey: &Key,
tags: Option<&[EntryTag]>,
) -> VcxWalletResult<()> {
session
.replace(
category,
did,
serde_json::to_string(&DidValue::new(verkey))?.as_bytes(),
tags,
None,
)
.await?;
Ok(())
}
async fn session(&self) -> VcxWalletResult<Session> {
Ok(self.backend.session(Some(self.profile.clone())).await?)
}
async fn transaction(&self) -> VcxWalletResult<Session> {
Ok(self.backend.transaction(Some(self.profile.clone())).await?)
}
}
#[cfg(test)]
pub mod tests {
use super::AskarWallet;
use crate::wallet::{
askar::{askar_wallet_config::AskarWalletConfig, key_method::KeyMethod},
base_wallet::ManageWallet,
};
pub async fn dev_setup_askar_wallet() -> AskarWallet {
use uuid::Uuid;
let config = AskarWalletConfig::new(
"sqlite://:memory:",
KeyMethod::Unprotected,
"",
&Uuid::new_v4().to_string(),
);
config.create_wallet().await.unwrap()
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/all_askar_records.rs | aries/aries_vcx_wallet/src/wallet/askar/all_askar_records.rs | use async_trait::async_trait;
use crate::{
errors::error::VcxWalletResult,
wallet::base_wallet::record::{AllRecords, PartialRecord},
};
pub struct AllAskarRecords {
iterator: std::vec::IntoIter<PartialRecord>,
total_count: Option<usize>,
}
impl AllAskarRecords {
pub fn new(iterator: std::vec::IntoIter<PartialRecord>, total_count: Option<usize>) -> Self {
Self {
iterator,
total_count,
}
}
}
#[async_trait]
impl AllRecords for AllAskarRecords {
fn total_count(&self) -> VcxWalletResult<Option<usize>> {
Ok(self.total_count)
}
async fn next(&mut self) -> VcxWalletResult<Option<PartialRecord>> {
Ok(self.iterator.next())
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/askar_utils.rs | aries/aries_vcx_wallet/src/wallet/askar/askar_utils.rs | use aries_askar::{
crypto::alg::{BlsCurves, EcCurves, KeyAlg},
entry::Entry,
kms::LocalKey,
};
use public_key::{Key, KeyType};
use serde::Deserialize;
use crate::{
errors::error::{VcxWalletError, VcxWalletResult},
wallet::{base_wallet::base58_string::Base58String, utils::random_seed},
};
pub fn local_key_to_bs58_public_key(local_key: &LocalKey) -> VcxWalletResult<Base58String> {
Ok(Base58String::from_bytes(&local_key.to_public_bytes()?))
}
pub fn local_key_to_bs58_private_key(local_key: &LocalKey) -> VcxWalletResult<Base58String> {
Ok(Base58String::from_bytes(&local_key.to_secret_bytes()?))
}
pub fn local_key_to_public_key(local_key: &LocalKey) -> VcxWalletResult<Key> {
Ok(Key::new(
local_key.to_public_bytes()?.to_vec(),
KeyType::Ed25519,
)?)
}
pub fn public_key_to_local_key(key: &Key) -> VcxWalletResult<LocalKey> {
let alg = public_key_type_to_askar_key_alg(key.key_type())?;
Ok(LocalKey::from_public_bytes(alg, key.key())?)
}
pub fn public_key_type_to_askar_key_alg(value: &KeyType) -> VcxWalletResult<KeyAlg> {
let alg = match value {
KeyType::Ed25519 => KeyAlg::Ed25519,
KeyType::X25519 => KeyAlg::X25519,
KeyType::Bls12381g1 => KeyAlg::Bls12_381(BlsCurves::G1),
KeyType::Bls12381g2 => KeyAlg::Bls12_381(BlsCurves::G2),
KeyType::P256 => KeyAlg::EcCurve(EcCurves::Secp256r1),
KeyType::P384 => KeyAlg::EcCurve(EcCurves::Secp384r1),
_ => {
return Err(VcxWalletError::Unimplemented(format!(
"Unsupported key type: {value:?}"
)))
}
};
Ok(alg)
}
pub fn ed25519_to_x25519(local_key: &LocalKey) -> VcxWalletResult<LocalKey> {
Ok(local_key.convert_key(KeyAlg::X25519)?)
}
pub fn seed_from_opt(maybe_seed: Option<&str>) -> String {
match maybe_seed {
Some(val) => val.into(),
None => random_seed(),
}
}
pub fn from_json_str<T: for<'a> Deserialize<'a>>(json: &str) -> VcxWalletResult<T> {
Ok(serde_json::from_str::<T>(json)?)
}
pub fn value_from_entry(entry: Entry) -> VcxWalletResult<String> {
Ok(String::from_utf8(entry.value.to_vec())?)
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/askar_import_config.rs | aries/aries_vcx_wallet/src/wallet/askar/askar_import_config.rs | use serde::Deserialize;
use crate::errors::error::VcxWalletResult;
#[derive(Deserialize, Clone, Copy, Debug)]
pub struct AskarImportConfig {}
impl AskarImportConfig {
pub async fn import_wallet(&self) -> VcxWalletResult<()> {
todo!()
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/key_method.rs | aries/aries_vcx_wallet/src/wallet/askar/key_method.rs | use aries_askar::{
storage::{Argon2Level, KdfMethod},
StoreKeyMethod,
};
use serde::Deserialize;
#[derive(Debug, Copy, Clone, Deserialize)]
pub enum KeyMethod {
DeriveKey { inner: AskarKdfMethod },
RawKey,
Unprotected,
}
impl From<KeyMethod> for StoreKeyMethod {
fn from(value: KeyMethod) -> Self {
match value {
KeyMethod::DeriveKey { inner: payload } => StoreKeyMethod::DeriveKey(payload.into()),
KeyMethod::RawKey => StoreKeyMethod::RawKey,
KeyMethod::Unprotected => StoreKeyMethod::Unprotected,
}
}
}
#[derive(Copy, Clone, Debug, Deserialize)]
pub enum AskarKdfMethod {
Argon2i { inner: ArgonLevel },
}
impl From<AskarKdfMethod> for KdfMethod {
fn from(value: AskarKdfMethod) -> Self {
match value {
AskarKdfMethod::Argon2i { inner: payload } => KdfMethod::Argon2i(payload.into()),
}
}
}
#[derive(Copy, Clone, Debug, Deserialize)]
pub enum ArgonLevel {
Interactive,
Moderate,
}
impl From<ArgonLevel> for Argon2Level {
fn from(value: ArgonLevel) -> Self {
match value {
ArgonLevel::Interactive => Argon2Level::Interactive,
ArgonLevel::Moderate => Argon2Level::Moderate,
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/askar_wallet_config.rs | aries/aries_vcx_wallet/src/wallet/askar/askar_wallet_config.rs | use async_trait::async_trait;
use serde::Deserialize;
use super::{key_method::KeyMethod, AskarWallet};
use crate::{errors::error::VcxWalletResult, wallet::base_wallet::ManageWallet};
#[derive(Clone, Debug, Deserialize)]
pub struct AskarWalletConfig {
pub db_url: String,
pub key_method: KeyMethod,
pub pass_key: String,
pub profile: String,
}
impl AskarWalletConfig {
pub fn new(db_url: &str, key_method: KeyMethod, pass_key: &str, profile: &str) -> Self {
Self {
db_url: db_url.into(),
key_method,
pass_key: pass_key.into(),
profile: profile.into(),
}
}
pub fn db_url(&self) -> &str {
&self.db_url
}
pub fn key_method(&self) -> &KeyMethod {
&self.key_method
}
pub fn pass_key(&self) -> &str {
&self.pass_key
}
pub fn profile(&self) -> &str {
&self.profile
}
}
#[async_trait]
impl ManageWallet for AskarWalletConfig {
type ManagedWalletType = AskarWallet;
async fn create_wallet(&self) -> VcxWalletResult<Self::ManagedWalletType> {
let askar_wallet = AskarWallet::create(self, false).await?;
Ok(askar_wallet)
}
async fn open_wallet(&self) -> VcxWalletResult<Self::ManagedWalletType> {
Ok(AskarWallet::open(self).await?)
}
async fn delete_wallet(&self) -> VcxWalletResult<()> {
todo!();
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/unpack.rs | aries/aries_vcx_wallet/src/wallet/askar/unpack.rs | use aries_askar::{
crypto::alg::Chacha20Types,
kms::{
crypto_box_open, crypto_box_seal_open,
KeyAlg::{self, Ed25519},
KeyEntry, LocalKey, ToDecrypt,
},
Session,
};
use public_key::{Key, KeyType};
use super::{
askar_utils::{ed25519_to_x25519, from_json_str},
packing_types::{AnoncryptRecipient, AuthcryptRecipient, Jwe, ProtectedData, Recipient},
};
use crate::{
errors::error::{VcxWalletError, VcxWalletResult},
wallet::{
structs_io::UnpackMessageOutput,
utils::{bs58_to_bytes, bytes_to_string},
},
};
trait Unpack {
fn unpack(&self, recipient: &Recipient, jwe: Jwe) -> VcxWalletResult<UnpackMessageOutput>;
}
impl Unpack for LocalKey {
fn unpack(&self, recipient: &Recipient, jwe: Jwe) -> VcxWalletResult<UnpackMessageOutput> {
let (enc_key, sender_verkey) = unpack_recipient(recipient, self)?;
Ok(UnpackMessageOutput {
message: unpack_msg(&jwe, enc_key)?,
recipient_verkey: recipient.unwrap_kid().to_owned(),
sender_verkey: sender_verkey.map(|key| key.base58()),
})
}
}
pub async fn unpack(jwe: Jwe, session: &mut Session) -> VcxWalletResult<UnpackMessageOutput> {
let protected_data = unpack_protected_data(&jwe)?;
let (recipient, key_entry) = find_recipient_key(&protected_data, session).await?;
let local_key = key_entry.load_local_key()?;
local_key.unpack(recipient, jwe)
}
/// Returns the shared encryption key, and the sender key (if any)
fn unpack_recipient(
recipient: &Recipient,
local_key: &LocalKey,
) -> VcxWalletResult<(LocalKey, Option<Key>)> {
match recipient {
Recipient::Authcrypt(auth_recipient) => unpack_authcrypt(local_key, auth_recipient),
Recipient::Anoncrypt(anon_recipient) => unpack_anoncrypt(local_key, anon_recipient),
}
}
fn unpack_protected_data(jwe: &Jwe) -> VcxWalletResult<ProtectedData> {
from_json_str(&jwe.protected.decode_to_string()?)
}
fn unpack_msg(jwe: &Jwe, enc_key: LocalKey) -> VcxWalletResult<String> {
let ciphertext = &jwe.ciphertext.decode()?;
let tag = &jwe.tag.decode()?;
bytes_to_string(
enc_key
.aead_decrypt(
ToDecrypt::from((ciphertext.as_ref(), tag.as_ref())),
&jwe.iv.decode()?,
&jwe.protected.as_bytes(),
)?
.to_vec(),
)
}
/// Returns the shared encryption key, and the sender key
fn unpack_authcrypt(
local_key: &LocalKey,
recipient: &AuthcryptRecipient,
) -> VcxWalletResult<(LocalKey, Option<Key>)> {
let recipient_x25519_key = ed25519_to_x25519(local_key)?;
// "sender" : base64URLencode(libsodium.crypto_box_seal(their_vk, base58encode(sender_vk)),
let encrypted_sender_vk = recipient.header.sender.decode()?;
let sender_vk = bs58_to_bytes(&crypto_box_seal_open(
&recipient_x25519_key,
&encrypted_sender_vk,
)?)?;
let sender_x25519_key = ed25519_to_x25519(&LocalKey::from_public_bytes(Ed25519, &sender_vk)?)?;
let secret = crypto_box_open(
&recipient_x25519_key,
&sender_x25519_key,
&recipient.encrypted_key.decode()?,
&recipient.header.iv.decode()?,
)?;
let shared_enc_key =
LocalKey::from_secret_bytes(KeyAlg::Chacha20(Chacha20Types::C20P), &secret)?;
let sender_ed25519_pk = Key::new(sender_vk, KeyType::Ed25519)?;
Ok((shared_enc_key, Some(sender_ed25519_pk)))
}
fn unpack_anoncrypt(
local_key: &LocalKey,
recipient: &AnoncryptRecipient,
) -> VcxWalletResult<(LocalKey, Option<Key>)> {
let recipient_key = ed25519_to_x25519(local_key)?;
let key = crypto_box_seal_open(&recipient_key, &recipient.encrypted_key.decode()?)?;
let shared_enc_key = LocalKey::from_secret_bytes(KeyAlg::Chacha20(Chacha20Types::C20P), &key)?;
Ok((shared_enc_key, None))
}
async fn find_recipient_key<'a>(
protected_data: &'a ProtectedData,
session: &mut Session,
) -> VcxWalletResult<(&'a Recipient, KeyEntry)> {
for recipient in protected_data.recipients.iter() {
if let Some(key_entry) = session.fetch_key(recipient.unwrap_kid(), false).await? {
return Ok((recipient, key_entry));
};
}
Err(VcxWalletError::NoRecipientKeyFound)
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/askar_did_wallet.rs | aries/aries_vcx_wallet/src/wallet/askar/askar_did_wallet.rs | use aries_askar::{
crypto::alg::Chacha20Types,
kms::{KeyAlg, LocalKey},
};
use async_trait::async_trait;
use public_key::Key;
use super::{
askar_utils::{local_key_to_public_key, public_key_to_local_key, seed_from_opt},
pack::Pack,
sig_type::SigType,
unpack::unpack,
AskarWallet,
};
use crate::{
errors::error::{VcxWalletError, VcxWalletResult},
wallet::{
base_wallet::{did_data::DidData, did_wallet::DidWallet, record_category::RecordCategory},
structs_io::UnpackMessageOutput,
},
};
#[async_trait]
impl DidWallet for AskarWallet {
async fn key_count(&self) -> VcxWalletResult<usize> {
let mut session = self.session().await?;
Ok(session
.fetch_all_keys(None, None, None, None, false)
.await?
.len())
}
async fn create_and_store_my_did(
&self,
seed: Option<&str>,
_did_method_name: Option<&str>,
) -> VcxWalletResult<DidData> {
let mut tx = self.transaction().await?;
let (_vk, local_key) = self
.insert_key(&mut tx, KeyAlg::Ed25519, seed_from_opt(seed).as_bytes())
.await?;
let verkey = local_key_to_public_key(&local_key)?;
// construct NYM from first half of verkey as expected output from this method
let nym = {
let pk = verkey.key();
if pk.len() != 32 {
return Err(VcxWalletError::InvalidInput(format!(
"Invalid key length: {}",
pk.len()
)));
}
bs58::encode(&pk[0..16]).into_string()
};
self.insert_did(
&mut tx,
&nym,
&RecordCategory::Did.to_string(),
&verkey,
None,
)
.await?;
tx.commit().await?;
Ok(DidData::new(&nym, &verkey))
}
async fn key_for_did(&self, did: &str) -> VcxWalletResult<Key> {
let data = self
.find_current_did(&mut self.session().await?, did)
.await?;
if let Some(did_data) = data {
Ok(did_data.verkey().to_owned())
} else {
Err(VcxWalletError::record_not_found_from_details(
RecordCategory::Did,
did,
))
}
}
async fn replace_did_key_start(&self, did: &str, seed: Option<&str>) -> VcxWalletResult<Key> {
let mut tx = self.transaction().await?;
if self.find_current_did(&mut tx, did).await?.is_some() {
let (_, local_key) = self
.insert_key(&mut tx, KeyAlg::Ed25519, seed_from_opt(seed).as_bytes())
.await?;
let verkey = local_key_to_public_key(&local_key)?;
self.insert_did(
&mut tx,
did,
&RecordCategory::TmpDid.to_string(),
&verkey,
None,
)
.await?;
tx.commit().await?;
Ok(verkey)
} else {
Err(VcxWalletError::record_not_found_from_details(
RecordCategory::Did,
did,
))
}
}
async fn replace_did_key_apply(&self, did: &str) -> VcxWalletResult<()> {
let mut tx = self.transaction().await?;
if let Some(did_value) = self.find_did(&mut tx, did, RecordCategory::TmpDid).await? {
tx.remove(&RecordCategory::TmpDid.to_string(), did).await?;
tx.remove_key(&did_value.verkey().base58()).await?;
self.update_did(
&mut tx,
did,
&RecordCategory::Did.to_string(),
did_value.verkey(),
None,
)
.await?;
tx.commit().await?;
return Ok(());
} else {
return Err(VcxWalletError::record_not_found_from_details(
RecordCategory::TmpDid,
did,
));
}
}
async fn sign(&self, key: &Key, msg: &[u8]) -> VcxWalletResult<Vec<u8>> {
let Some(key) = self
.session()
.await?
.fetch_key(&key.base58(), false)
.await?
else {
return Err(VcxWalletError::record_not_found_from_details(
RecordCategory::Key,
&key.base58(),
));
};
let local_key = key.load_local_key()?;
let key_alg = SigType::try_from_key_alg(local_key.algorithm())?;
Ok(local_key.sign_message(msg, Some(key_alg.into()))?)
}
async fn verify(&self, key: &Key, msg: &[u8], signature: &[u8]) -> VcxWalletResult<bool> {
let local_key = public_key_to_local_key(key)?;
let sig_alg = SigType::try_from_key_alg(local_key.algorithm())?;
Ok(local_key.verify_signature(msg, signature, Some(sig_alg.into()))?)
}
async fn pack_message(
&self,
sender_vk: Option<Key>,
recipient_keys: Vec<Key>,
msg: &[u8],
) -> VcxWalletResult<Vec<u8>> {
if recipient_keys.is_empty() {
Err(VcxWalletError::InvalidInput(
"recipient keys should not be empty for 'pack_message'".into(),
))
} else {
let enc_key = LocalKey::generate_with_rng(KeyAlg::Chacha20(Chacha20Types::C20P), true)?;
let base64_data = if let Some(sender_verkey) = sender_vk {
let mut session = self.session().await?;
let my_key = self
.fetch_local_key(&mut session, &sender_verkey.base58())
.await?;
enc_key.pack_authcrypt(recipient_keys, my_key)?
} else {
enc_key.pack_anoncrypt(recipient_keys)?
};
Ok(enc_key.pack_all(base64_data, msg)?)
}
}
async fn unpack_message(&self, msg: &[u8]) -> VcxWalletResult<UnpackMessageOutput> {
Ok(unpack(serde_json::from_slice(msg)?, &mut self.session().await?).await?)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/wallet/askar/entry.rs | aries/aries_vcx_wallet/src/wallet/askar/entry.rs | use std::str::FromStr;
use aries_askar::entry::{Entry, EntryKind};
use crate::{
errors::error::VcxWalletError,
wallet::base_wallet::{record::Record, record_category::RecordCategory},
};
impl TryFrom<Entry> for Record {
type Error = VcxWalletError;
fn try_from(entry: Entry) -> Result<Self, Self::Error> {
Ok(Self::builder()
.category(RecordCategory::from_str(&entry.category)?)
.name(entry.name)
.value(String::from_utf8(entry.value.to_vec())?)
.tags(entry.tags.into())
.build())
}
}
impl From<Record> for Entry {
fn from(record: Record) -> Self {
Self {
category: record.category().to_string(),
name: record.name().to_string(),
value: record.value().into(),
kind: EntryKind::Item,
tags: record.tags().clone().into_iter().map(From::from).collect(),
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/errors/error.rs | aries/aries_vcx_wallet/src/errors/error.rs | use std::{
fmt::{self, Display},
string::FromUtf8Error,
};
use thiserror::Error as ThisError;
use crate::wallet::base_wallet::record_category::RecordCategory;
pub type VcxWalletResult<T> = Result<T, VcxWalletError>;
pub struct NotFoundInfo(Option<String>);
impl NotFoundInfo {
pub fn new_with_details(category: RecordCategory, name: &str) -> Self {
Self(Some(format!(
"Not found, category: {category}, name {name}"
)))
}
pub fn new_from_str(info: &str) -> Self {
Self(Some(info.to_string()))
}
pub fn new_without_details() -> Self {
Self(None)
}
}
impl fmt::Debug for NotFoundInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
None => write!(f, "no details provided"),
Some(payload) => write!(f, "{payload}"),
}
}
}
impl fmt::Display for NotFoundInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt::Debug::fmt(self, f)
}
}
#[derive(Debug)]
pub enum VcxWalletError {
DuplicateRecord(String),
NotUtf8(FromUtf8Error),
NotBase58(bs58::decode::Error),
NotBase64(base64::DecodeError),
RecordNotFound(NotFoundInfo),
UnknownRecordCategory(String),
InvalidInput(String),
NoRecipientKeyFound,
InvalidJson(serde_json::Error),
PublicKeyError(public_key::PublicKeyError),
Unimplemented(String),
Unknown(OpaqueError),
WalletCreate(OpaqueError),
}
#[derive(ThisError, Debug)]
pub struct OpaqueError(anyhow::Error);
impl Display for OpaqueError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Display for VcxWalletError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
VcxWalletError::DuplicateRecord(inner) => write!(f, "Duplicate record: {inner}"),
VcxWalletError::NotUtf8(inner) => write!(f, "Not UTF-8: {inner}"),
VcxWalletError::NotBase58(inner) => write!(f, "Not Base58: {inner}"),
VcxWalletError::NotBase64(inner) => write!(f, "Not Base64: {inner}"),
VcxWalletError::RecordNotFound(inner) => write!(f, "Record not found: {inner}"),
VcxWalletError::UnknownRecordCategory(inner) => {
write!(f, "Unknown RecordCategory: {inner}")
}
VcxWalletError::InvalidInput(inner) => write!(f, "Invalid input: {inner}"),
VcxWalletError::NoRecipientKeyFound => write!(f, "No recipient key found"),
VcxWalletError::InvalidJson(inner) => write!(f, "Invalid JSON: {inner}"),
VcxWalletError::PublicKeyError(inner) => write!(f, "Public key error: {inner}"),
VcxWalletError::Unimplemented(inner) => write!(f, "Not implemented: {inner}"),
VcxWalletError::Unknown(inner) => write!(f, "Unknown error: {inner}"),
VcxWalletError::WalletCreate(inner) => write!(f, "Error creating a wallet: {inner}"),
}
}
}
impl std::error::Error for VcxWalletError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
VcxWalletError::DuplicateRecord(_) => None,
VcxWalletError::NotUtf8(inner) => Some(inner),
VcxWalletError::NotBase58(inner) => Some(inner),
VcxWalletError::NotBase64(inner) => Some(inner),
VcxWalletError::RecordNotFound(_) => None,
VcxWalletError::UnknownRecordCategory(_) => None,
VcxWalletError::InvalidInput(_) => None,
VcxWalletError::NoRecipientKeyFound => None,
VcxWalletError::InvalidJson(inner) => Some(inner),
VcxWalletError::PublicKeyError(inner) => Some(inner),
VcxWalletError::Unimplemented(_) => None,
VcxWalletError::Unknown(inner) => Some(inner),
VcxWalletError::WalletCreate(inner) => Some(inner),
}
}
fn description(&self) -> &str {
"description() is deprecated; use Display"
}
fn cause(&self) -> Option<&dyn std::error::Error> {
self.source()
}
}
impl VcxWalletError {
pub fn create_wallet_error(err: impl std::error::Error + Send + Sync + 'static) -> Self {
Self::WalletCreate(OpaqueError(err.into()))
}
pub fn unknown_error(err: impl std::error::Error + Send + Sync + 'static) -> Self {
Self::Unknown(OpaqueError(err.into()))
}
pub fn record_not_found_from_details(category: RecordCategory, name: &str) -> Self {
Self::RecordNotFound(NotFoundInfo::new_with_details(category, name))
}
pub fn record_not_found_from_str(info: &str) -> Self {
Self::RecordNotFound(NotFoundInfo::new_from_str(info))
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/errors/mapping_others.rs | aries/aries_vcx_wallet/src/errors/mapping_others.rs | use std::string::FromUtf8Error;
use super::error::VcxWalletError;
impl From<bs58::decode::Error> for VcxWalletError {
fn from(value: bs58::decode::Error) -> Self {
Self::NotBase58(value)
}
}
impl From<base64::DecodeError> for VcxWalletError {
fn from(value: base64::DecodeError) -> Self {
Self::NotBase64(value)
}
}
impl From<FromUtf8Error> for VcxWalletError {
fn from(value: FromUtf8Error) -> Self {
Self::NotUtf8(value)
}
}
impl From<serde_json::Error> for VcxWalletError {
fn from(value: serde_json::Error) -> Self {
Self::InvalidJson(value)
}
}
impl From<public_key::PublicKeyError> for VcxWalletError {
fn from(value: public_key::PublicKeyError) -> Self {
Self::PublicKeyError(value)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/errors/mod.rs | aries/aries_vcx_wallet/src/errors/mod.rs | pub mod error;
#[cfg(feature = "askar_wallet")]
mod mapping_askar;
mod mapping_others;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx_wallet/src/errors/mapping_askar.rs | aries/aries_vcx_wallet/src/errors/mapping_askar.rs | use aries_askar::ErrorKind;
use super::error::{NotFoundInfo, VcxWalletError};
impl From<aries_askar::Error> for VcxWalletError {
fn from(err: aries_askar::Error) -> Self {
match err.kind() {
ErrorKind::Backend
| ErrorKind::Custom
| ErrorKind::Encryption
| ErrorKind::Input
| ErrorKind::Unexpected
| ErrorKind::Unsupported
| ErrorKind::Busy => VcxWalletError::unknown_error(err),
ErrorKind::Duplicate => VcxWalletError::DuplicateRecord(err.to_string()),
ErrorKind::NotFound => {
VcxWalletError::RecordNotFound(NotFoundInfo::new_without_details())
}
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/setup.rs | aries/agents/aath-backchannel/src/setup.rs | use std::{io::prelude::*, sync::Arc};
use aries_vcx_agent::{
aries_vcx::aries_vcx_wallet::wallet::askar::AskarWallet, build_askar_wallet,
Agent as AriesAgent, WalletInitConfig,
};
use rand::{rng, Rng};
use reqwest::Url;
#[derive(Debug, Deserialize)]
struct SeedResponse {
seed: String,
}
struct WriterSeed {
pub seed: String,
pub is_trustee: bool,
}
/// If a ledger URL is available, then use it to register a new endorser, then return this
/// endorser's DID seed.
/// If not available, then default to using the local ledger Trustee seed.
async fn get_writer_seed() -> WriterSeed {
if let Ok(ledger_url) = std::env::var("LEDGER_URL") {
let url = format!("{ledger_url}/register");
let mut rng = rng();
let client = reqwest::Client::new();
let body = json!({
"role": "TRUST_ANCHOR",
"seed": format!("my_seed_000000000000000000{}", rng.random_range(100000..1000000))
})
.to_string();
let seed = client
.post(&url)
.body(body)
.send()
.await
.expect("Failed to send message")
.json::<SeedResponse>()
.await
.expect("Failed to deserialize response")
.seed;
WriterSeed {
seed,
is_trustee: false,
}
} else {
WriterSeed {
seed: "000000000000000000000000Trustee1".to_string(),
is_trustee: true,
}
}
}
async fn download_genesis_file() -> std::result::Result<String, String> {
match std::env::var("GENESIS_FILE").ok() {
Some(genesis_file) => {
if !std::path::Path::new(&genesis_file).exists() {
Err(format!("The file {genesis_file} does not exist"))
} else {
info!("Using genesis file {genesis_file}");
Ok(genesis_file)
}
}
None => match std::env::var("LEDGER_URL").ok() {
Some(ledger_url) => {
info!("Downloading genesis file from {ledger_url}");
let genesis_url = format!("{ledger_url}/genesis");
let body = reqwest::get(&genesis_url)
.await
.expect("Failed to get genesis file from ledger")
.text()
.await
.expect("Failed to get the response text");
let path = std::env::current_dir()
.expect("Failed to obtain the current directory path")
.join("resource")
.join("genesis_file.txn");
info!("Storing genesis file to {path:?}");
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path.clone())
.expect("Unable to open file");
f.write_all(body.as_bytes()).expect("Unable to write data");
debug!("Genesis file downloaded and saved to {path:?}");
path.to_str()
.map(|s| s.to_string())
.ok_or("Failed to convert genesis file path to string".to_string())
}
None => std::env::current_dir()
.expect("Failed to obtain the current directory path")
.join("resource")
.join("indypool.txn")
.to_str()
.map(|s| s.to_string())
.ok_or("Failed to convert genesis file path to string".to_string()),
},
}
}
pub async fn initialize(port: u32) -> AriesAgent<AskarWallet> {
let register_nym_res = get_writer_seed().await;
let genesis_path = download_genesis_file()
.await
.expect("Failed to download the genesis file");
let dockerhost = std::env::var("DOCKERHOST").unwrap_or("localhost".to_string());
let service_endpoint = Url::parse(&format!("http://{dockerhost}:{port}/didcomm")).unwrap();
let wallet_config = WalletInitConfig {
wallet_name: format!("rust_agent_{}", uuid::Uuid::new_v4()),
wallet_key: "8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY".to_string(),
wallet_kdf: "RAW".to_string(),
};
let (wallet, issuer_config) = build_askar_wallet(wallet_config, register_nym_res.seed).await;
let wallet = Arc::new(wallet);
let issuer_did = AriesAgent::setup_ledger(
genesis_path.clone(),
wallet.clone(),
service_endpoint.clone(),
issuer_config.institution_did.parse().unwrap(),
register_nym_res.is_trustee,
)
.await
.unwrap();
AriesAgent::initialize(
genesis_path,
wallet.clone(),
service_endpoint.clone(),
issuer_did,
)
.await
.unwrap()
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/error.rs | aries/agents/aath-backchannel/src/error.rs | use actix_web::{error, http::StatusCode, HttpResponse, HttpResponseBuilder};
use aries_vcx_agent::{
aries_vcx,
aries_vcx::{did_parser_nom::ParseError, messages::error::MsgTypeError},
AgentError,
};
use derive_more::{Display, Error};
pub type HarnessResult<T> = Result<T, HarnessError>;
#[derive(Debug, Display, Error, Clone)]
pub enum HarnessErrorType {
#[display("Internal server error")]
InternalServerError,
#[display("Request not accepted")]
RequestNotAcceptedError,
#[display("Request not received")]
RequestNotReceived,
#[display("Not found")]
NotFoundError,
#[display("Invalid JSON")]
InvalidJson,
#[display("Protocol error")]
ProtocolError,
#[display("Invalid state for requested operation")]
InvalidState,
#[display("Encryption error")]
EncryptionError,
#[display("Multiple credential definitions found")]
MultipleCredDefinitions,
}
#[derive(Debug, Display, Error, Clone)]
#[display("Error: {}", message)]
pub struct HarnessError {
pub message: String,
pub kind: HarnessErrorType,
}
impl error::ResponseError for HarnessError {
fn error_response(&self) -> HttpResponse {
error!("{self}");
HttpResponseBuilder::new(self.status_code()).body(self.to_string())
}
fn status_code(&self) -> StatusCode {
match self.kind {
HarnessErrorType::RequestNotAcceptedError
| HarnessErrorType::RequestNotReceived
| HarnessErrorType::InvalidJson => StatusCode::NOT_ACCEPTABLE,
HarnessErrorType::NotFoundError => StatusCode::NOT_FOUND,
HarnessErrorType::InvalidState => StatusCode::BAD_REQUEST,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
impl HarnessError {
pub fn from_msg(kind: HarnessErrorType, msg: &str) -> Self {
HarnessError {
kind,
message: msg.to_string(),
}
}
pub fn from_kind(kind: HarnessErrorType) -> Self {
let message = kind.to_string();
HarnessError { kind, message }
}
}
impl std::convert::From<aries_vcx::errors::error::AriesVcxError> for HarnessError {
fn from(vcx_err: aries_vcx::errors::error::AriesVcxError) -> HarnessError {
let kind = HarnessErrorType::InternalServerError;
HarnessError {
message: vcx_err.to_string(),
kind,
}
}
}
impl std::convert::From<aries_vcx::aries_vcx_anoncreds::errors::error::VcxAnoncredsError>
for HarnessError
{
fn from(
vcx_err: aries_vcx::aries_vcx_anoncreds::errors::error::VcxAnoncredsError,
) -> HarnessError {
let kind = HarnessErrorType::InternalServerError;
HarnessError {
message: vcx_err.to_string(),
kind,
}
}
}
impl std::convert::From<serde_json::Error> for HarnessError {
fn from(serde_err: serde_json::Error) -> HarnessError {
let kind = HarnessErrorType::InternalServerError;
let message = format!("(De)serialization failed; err: {serde_err}");
HarnessError { message, kind }
}
}
impl std::convert::From<std::io::Error> for HarnessError {
fn from(io_err: std::io::Error) -> HarnessError {
let kind = HarnessErrorType::InternalServerError;
let message = format!("I/O error: {io_err}");
HarnessError { message, kind }
}
}
impl std::convert::From<reqwest::Error> for HarnessError {
fn from(rw_err: reqwest::Error) -> HarnessError {
let kind = HarnessErrorType::InternalServerError;
let message = format!("Reqwest error: {rw_err}");
HarnessError { message, kind }
}
}
impl std::convert::From<AgentError> for HarnessError {
fn from(err: AgentError) -> HarnessError {
let kind = HarnessErrorType::InternalServerError;
let message = format!("AgentError: {err}");
HarnessError { message, kind }
}
}
impl std::convert::From<MsgTypeError> for HarnessError {
fn from(err: MsgTypeError) -> HarnessError {
let kind = HarnessErrorType::InternalServerError;
let message = format!("MsgTypeError: {err}");
HarnessError { message, kind }
}
}
impl std::convert::From<ParseError> for HarnessError {
fn from(err: ParseError) -> HarnessError {
let kind = HarnessErrorType::InternalServerError;
let message = format!("MsgTypeError: {err}");
HarnessError { message, kind }
}
}
impl std::convert::From<anoncreds_types::Error> for HarnessError {
fn from(err: anoncreds_types::Error) -> HarnessError {
let kind = HarnessErrorType::InternalServerError;
let message = format!("MsgTypeError: {err}");
HarnessError { message, kind }
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/main.rs | aries/agents/aath-backchannel/src/main.rs | #[allow(clippy::await_holding_lock)]
mod controllers;
mod error;
mod setup;
#[macro_use]
extern crate serde;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate log;
extern crate aries_vcx_agent;
extern crate clap;
extern crate reqwest;
extern crate uuid;
use std::{
collections::HashMap,
sync::{Mutex, RwLock},
};
use actix_web::{middleware, web, App, HttpServer};
use aries_vcx_agent::{
aries_vcx::{aries_vcx_wallet::wallet::askar::AskarWallet, messages::AriesMessage},
Agent as AriesAgent,
};
use clap::Parser;
use controllers::out_of_band;
use crate::controllers::{
connection, credential_definition, did_exchange, didcomm, general, issuance, presentation,
revocation, schema,
};
#[derive(Parser)]
struct Opts {
#[clap(short, long, default_value = "9020")]
port: u32,
#[clap(short, long, default_value = "false")]
interactive: String,
}
#[derive(Copy, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
enum State {
Initial,
Invited,
Requested,
RequestSet,
Responded,
Complete,
Failure,
Unknown,
ProposalSent,
ProposalReceived,
RequestReceived,
CredentialSent,
OfferReceived,
RequestSent,
PresentationSent,
Done,
}
#[derive(Copy, Clone, Serialize)]
#[serde(rename_all = "lowercase")]
enum Status {
Active,
}
pub struct HarnessAgent {
aries_agent: AriesAgent<AskarWallet>,
status: Status,
// did-exchange specific
// todo: extra didx specific AATH service
didx_msg_buffer: RwLock<Vec<AriesMessage>>,
didx_pthid_to_thid: Mutex<HashMap<String, String>>,
// A map of DIDExchange thread IDs to the intended recipient
didx_thid_to_request_recipient_verkey: Mutex<HashMap<String, String>>,
}
#[macro_export]
macro_rules! soft_assert_eq {
($left:expr, $right:expr) => {{
match (&$left, &$right) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
return Err(HarnessError::from_msg(
HarnessErrorType::InternalServerError,
&format!(
r#"assertion failed: `(left == right)`
left: `{:?}`,
right: `{:?}`"#,
left_val, right_val
),
));
}
}
}
}};
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(
env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info"),
);
let opts: Opts = Opts::parse();
let host = std::env::var("HOST").unwrap_or("0.0.0.0".to_string());
let aries_agent = setup::initialize(opts.port).await;
info!("Starting aries back-channel on port {}", opts.port);
HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
.wrap(middleware::NormalizePath::new(
middleware::TrailingSlash::Trim,
))
.app_data(web::Data::new(RwLock::new(HarnessAgent {
aries_agent: aries_agent.clone(),
status: Status::Active,
didx_msg_buffer: Default::default(),
didx_pthid_to_thid: Default::default(),
didx_thid_to_request_recipient_verkey: Default::default(),
})))
.app_data(web::Data::new(RwLock::new(Vec::<AriesMessage>::new())))
.service(
web::scope("/agent")
.configure(connection::config)
.configure(did_exchange::config)
.configure(schema::config)
.configure(credential_definition::config)
.configure(issuance::config)
.configure(revocation::config)
.configure(presentation::config)
.configure(out_of_band::config)
.configure(general::config),
)
.service(web::scope("/didcomm").route("", web::post().to(didcomm::receive_message)))
})
.keep_alive(std::time::Duration::from_secs(30))
.client_request_timeout(std::time::Duration::from_secs(30))
.workers(1)
.bind(format!("{}:{}", host, opts.port))?
.run()
.await
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/controllers/presentation.rs | aries/agents/aath-backchannel/src/controllers/presentation.rs | use std::{collections::HashMap, sync::RwLock};
use actix_web::{get, post, web, Responder};
use anoncreds_types::data_types::messages::pres_request::{
AttributeInfo, NonRevokedInterval, PredicateInfo, PresentationRequestPayload,
};
use aries_vcx_agent::aries_vcx::{
aries_vcx_anoncreds::anoncreds::base_anoncreds::BaseAnonCreds,
handlers::util::PresentationProposalData,
messages::msg_fields::protocols::present_proof::v1::propose::{Predicate, PresentationAttr},
protocols::proof_presentation::{
prover::state_machine::ProverState,
verifier::{
state_machine::VerifierState, verification_status::PresentationVerificationStatus,
},
},
};
use crate::{
controllers::AathRequest,
error::{HarnessError, HarnessErrorType, HarnessResult},
soft_assert_eq, HarnessAgent, State,
};
#[derive(Serialize, Deserialize, Default, Debug)]
pub struct PresentationRequestWrapper {
connection_id: String,
presentation_request: PresentationRequest,
}
#[derive(Serialize, Deserialize, Default, Debug)]
pub struct PresentationProposalWrapper {
connection_id: String,
presentation_proposal: PresentationProposal,
}
// TODO: Remove these structs
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Default)]
pub struct PresentationRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
pub proof_request: ProofRequestDataWrapper,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)]
pub struct ProofRequestDataWrapper {
pub data: ProofRequestData,
}
#[derive(Serialize, Deserialize, Default, Debug)]
pub struct PresentationProposal {
comment: String,
attributes: Vec<PresentationAttr>,
predicates: Vec<Predicate>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)]
pub struct ProofRequestData {
pub requested_attributes: Option<HashMap<String, AttributeInfo>>,
pub requested_predicates: Option<HashMap<String, PredicateInfo>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub non_revoked: Option<NonRevokedInterval>,
}
fn to_backchannel_state_prover(state: ProverState) -> State {
match state {
ProverState::Initial => State::Initial,
ProverState::PresentationRequestReceived => State::RequestReceived,
ProverState::PresentationProposalSent => State::ProposalSent,
ProverState::PresentationSent => State::PresentationSent,
ProverState::PresentationPreparationFailed
| ProverState::Finished
| ProverState::Failed => State::Done,
_ => State::Unknown,
}
}
fn to_backchannel_state_verifier(state: VerifierState) -> State {
match state {
VerifierState::Initial => State::Initial,
VerifierState::PresentationRequestSet => State::RequestSet,
VerifierState::PresentationProposalReceived => State::ProposalReceived,
VerifierState::PresentationRequestSent => State::RequestSent,
VerifierState::Finished | VerifierState::Failed => State::Done,
}
}
impl HarnessAgent {
pub async fn send_proof_request(
&self,
presentation_request: &PresentationRequestWrapper,
) -> HarnessResult<String> {
let req_data = presentation_request
.presentation_request
.proof_request
.data
.clone();
let nonce = self.aries_agent.anoncreds().generate_nonce().await?;
let request = PresentationRequestPayload::builder()
.requested_attributes(req_data.requested_attributes.unwrap_or_default())
.requested_predicates(req_data.requested_predicates.unwrap_or_default())
.non_revoked(req_data.non_revoked)
.nonce(nonce)
.name("test proof".to_string())
.build();
let id = self
.aries_agent
.verifier()
.send_proof_request(&presentation_request.connection_id, request.into_v1(), None)
.await?;
let state = self.aries_agent.verifier().get_state(&id)?;
Ok(json!({ "state": to_backchannel_state_verifier(state), "thread_id": id }).to_string())
}
pub async fn send_proof_proposal(
&self,
presentation_proposal: &PresentationProposalWrapper,
) -> HarnessResult<String> {
let mut proposal_data = PresentationProposalData::default();
for attr in presentation_proposal
.presentation_proposal
.attributes
.clone()
.into_iter()
{
proposal_data.attributes.push(attr.clone());
}
let id = self
.aries_agent
.prover()
.send_proof_proposal(&presentation_proposal.connection_id, proposal_data)
.await?;
let state = self.aries_agent.prover().get_state(&id)?;
Ok(json!({ "state": to_backchannel_state_prover(state), "thread_id": id }).to_string())
}
pub async fn send_presentation(&self, id: &str) -> HarnessResult<String> {
let state = self.aries_agent.prover().get_state(id)?;
soft_assert_eq!(state, ProverState::PresentationRequestReceived);
let tails_dir = if self.aries_agent.prover().is_secondary_proof_requested(id)? {
Some(
std::env::current_dir()
.unwrap()
.join("resource")
.join("tails")
.to_str()
.unwrap()
.to_string(),
)
} else {
None
};
self.aries_agent
.prover()
.send_proof_prentation(id, tails_dir.as_deref())
.await?;
let state = self.aries_agent.prover().get_state(id)?;
Ok(json!({"state": to_backchannel_state_prover(state), "thread_id": id}).to_string())
}
pub async fn verify_presentation(&self, id: &str) -> HarnessResult<String> {
let verified = self.aries_agent.verifier().get_presentation_status(id)?
== PresentationVerificationStatus::Valid;
let state = self.aries_agent.verifier().get_state(id)?;
Ok(
json!({ "state": to_backchannel_state_verifier(state), "verified": verified })
.to_string(),
)
}
pub async fn get_proof_state(&self, id: &str) -> HarnessResult<String> {
let state = if self.aries_agent.verifier().exists_by_id(id) {
to_backchannel_state_verifier(self.aries_agent.verifier().get_state(id)?)
} else if self.aries_agent.prover().exists_by_id(id) {
to_backchannel_state_prover(self.aries_agent.prover().get_state(id)?)
} else {
return Err(HarnessError::from_kind(HarnessErrorType::NotFoundError));
};
Ok(json!({ "state": state }).to_string())
}
}
#[post("/send-request")]
pub async fn send_proof_request(
req: web::Json<AathRequest<PresentationRequestWrapper>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent.read().unwrap().send_proof_request(&req.data).await
}
#[post("/send-proposal")]
pub async fn send_proof_proposal(
req: web::Json<AathRequest<PresentationProposalWrapper>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent.read().unwrap().send_proof_proposal(&req.data).await
}
#[post("/send-presentation")]
pub async fn send_presentation(
req: web::Json<AathRequest<serde_json::Value>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent.read().unwrap().send_presentation(&req.id).await
}
#[post("/verify-presentation")]
pub async fn verify_presentation(
req: web::Json<AathRequest<serde_json::Value>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent.read().unwrap().verify_presentation(&req.id).await
}
#[get("/{proof_id}")]
pub async fn get_proof_state(
agent: web::Data<RwLock<HarnessAgent>>,
path: web::Path<String>,
) -> impl Responder {
agent
.read()
.unwrap()
.get_proof_state(&path.into_inner())
.await
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/command/proof")
.service(send_proof_request)
.service(send_proof_proposal)
.service(send_presentation)
.service(verify_presentation)
.service(get_proof_state),
);
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/controllers/general.rs | aries/agents/aath-backchannel/src/controllers/general.rs | use std::sync::RwLock;
use actix_web::{get, post, web, HttpResponse, Responder};
use serde_json::Value;
use crate::{error::HarnessResult, HarnessAgent};
impl HarnessAgent {
pub fn get_status_json(&self) -> HarnessResult<String> {
Ok(json!({ "status": self.status }).to_string())
}
pub fn get_public_did(&self) -> HarnessResult<String> {
let public_did = self.aries_agent.public_did();
Ok(json!({ "did": format!("did:sov:{public_did}") }).to_string())
}
pub fn get_start(&self) -> HarnessResult<String> {
Ok(json!({ "foo": "bar-agent-start" }).to_string())
}
}
#[get("/status")]
pub async fn get_status(agent: web::Data<RwLock<HarnessAgent>>) -> impl Responder {
HttpResponse::Ok().body(agent.read().unwrap().get_status_json().unwrap())
}
#[get("/version")]
pub async fn get_version() -> impl Responder {
// Update this with aries-vcx
HttpResponse::Ok().body("0.67.0")
}
#[get("/did")]
pub async fn get_public_did(agent: web::Data<RwLock<HarnessAgent>>) -> impl Responder {
HttpResponse::Ok().body(agent.read().unwrap().get_public_did().unwrap())
}
#[post("/agent/start")]
pub async fn get_start(
agent: web::Data<RwLock<HarnessAgent>>,
payload: web::Json<Value>,
) -> impl Responder {
info!("Payload: {payload:?}");
HttpResponse::Ok().body(agent.read().unwrap().get_start().unwrap())
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/command")
.service(get_status)
.service(get_version)
.service(get_start)
.service(get_public_did),
);
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/controllers/connection.rs | aries/agents/aath-backchannel/src/controllers/connection.rs | use std::sync::RwLock;
use actix_web::{get, post, web, Responder};
use aries_vcx_agent::aries_vcx::{
handlers::util::AnyInvitation,
messages::msg_fields::protocols::{connection::invitation::Invitation, notification::ack::Ack},
protocols::connection::{State as ConnectionState, ThinState},
};
use crate::{
controllers::AathRequest,
error::{HarnessError, HarnessErrorType, HarnessResult},
soft_assert_eq, HarnessAgent, State,
};
#[allow(dead_code)]
#[derive(Deserialize, Default)]
pub struct Comment {
comment: String,
}
fn to_backchannel_state(state: ThinState) -> State {
match state {
ThinState::Invitee(state) => match state {
ConnectionState::Initial => State::Initial,
ConnectionState::Invited => State::Invited,
ConnectionState::Requested => State::Requested,
ConnectionState::Responded => State::Responded,
ConnectionState::Completed => State::Complete,
},
ThinState::Inviter(state) => match state {
ConnectionState::Initial => State::Initial,
ConnectionState::Invited => State::Invited,
ConnectionState::Requested => State::Requested,
ConnectionState::Responded => State::Responded,
ConnectionState::Completed => State::Complete,
},
}
}
impl HarnessAgent {
pub async fn create_connection_invitation(&self) -> HarnessResult<String> {
let invitation = self
.aries_agent
.connections()
.create_invitation(None)
.await?;
let id = invitation.id();
Ok(json!({ "connection_id": id, "invitation": invitation }).to_string())
}
pub async fn receive_connection_invitation(&self, invite: Invitation) -> HarnessResult<String> {
let id = self
.aries_agent
.connections()
.receive_invitation(AnyInvitation::Con(invite))
.await?;
Ok(json!({ "connection_id": id }).to_string())
}
pub async fn send_connection_request(&self, id: &str) -> HarnessResult<String> {
self.aries_agent.connections().send_request(id).await?;
Ok(json!({ "connection_id": id }).to_string())
}
pub async fn accept_connection_request(&self, id: &str) -> HarnessResult<String> {
// TODO: Handle case of multiple requests received
if !matches!(
self.aries_agent.connections().get_state(id)?,
ThinState::Inviter(ConnectionState::Requested)
) {
return Err(HarnessError::from_kind(
HarnessErrorType::RequestNotReceived,
));
}
self.aries_agent.connections().send_response(id).await?;
Ok(json!({ "connection_id": id }).to_string())
}
pub async fn send_connection_ack(&self, id: &str) -> HarnessResult<String> {
self.aries_agent.connections().send_ack(id).await?;
Ok(json!({ "connection_id": id }).to_string())
}
pub async fn process_connection_ack(&self, ack: Ack) -> HarnessResult<String> {
let thid = ack.decorators.thread.thid.to_string();
self.aries_agent.connections().process_ack(ack).await?;
Ok(json!({ "connection_id": thid }).to_string())
}
pub async fn get_connection_state(&self, id: &str) -> HarnessResult<String> {
let state = to_backchannel_state(self.aries_agent.connections().get_state(id)?);
Ok(json!({ "state": state }).to_string())
}
pub async fn get_connection(&self, id: &str) -> HarnessResult<String> {
soft_assert_eq!(self.aries_agent.connections().exists_by_id(id), true);
Ok(json!({ "connection_id": id }).to_string())
}
}
#[post("/create-invitation")]
pub async fn create_invitation(agent: web::Data<RwLock<HarnessAgent>>) -> impl Responder {
agent.read().unwrap().create_connection_invitation().await
}
#[post("/receive-invitation")]
pub async fn receive_invitation(
req: web::Json<AathRequest<Option<Invitation>>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent
.read()
.unwrap()
.receive_connection_invitation(
req.data
.as_ref()
.ok_or(HarnessError::from_msg(
HarnessErrorType::InvalidJson,
"Failed to deserialize pairwise invitation",
))?
.clone(),
)
.await
}
#[post("/accept-invitation")]
pub async fn send_request(
req: web::Json<AathRequest<()>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent.read().unwrap().send_connection_request(&req.id).await
}
#[post("/accept-request")]
pub async fn accept_request(
req: web::Json<AathRequest<()>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent
.read()
.unwrap()
.accept_connection_request(&req.id)
.await
}
#[get("/{connection_id}")]
pub async fn get_connection_state(
agent: web::Data<RwLock<HarnessAgent>>,
path: web::Path<String>,
) -> impl Responder {
let connection_state = agent
.read()
.unwrap()
.get_connection_state(&path.into_inner())
.await;
info!("Connection state: {connection_state:?}");
connection_state
}
#[get("/{thread_id}")]
pub async fn get_connection(
agent: web::Data<RwLock<HarnessAgent>>,
path: web::Path<String>,
) -> impl Responder {
agent
.read()
.unwrap()
.get_connection(&path.into_inner())
.await
}
#[post("/send-ping")]
pub async fn send_ack(
req: web::Json<AathRequest<Comment>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent.read().unwrap().send_connection_ack(&req.id).await
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/command/connection")
.service(create_invitation)
.service(receive_invitation)
.service(send_request)
.service(accept_request)
.service(send_ack)
.service(get_connection_state),
)
.service(web::scope("/response/connection").service(get_connection));
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/controllers/out_of_band.rs | aries/agents/aath-backchannel/src/controllers/out_of_band.rs | use std::sync::RwLock;
use actix_web::{get, post, web, Responder};
use aries_vcx_agent::aries_vcx::messages::AriesMessage;
use crate::{
controllers::AathRequest,
error::{HarnessError, HarnessErrorType, HarnessResult},
soft_assert_eq, HarnessAgent,
};
impl HarnessAgent {
pub async fn create_oob_invitation(&self) -> HarnessResult<String> {
let invitation = self.aries_agent.out_of_band().create_invitation().await?;
info!("Created out-of-band invitation: {invitation}");
Ok(json!({ "invitation": invitation, "state": "invitation-sent" }).to_string())
}
pub async fn receive_oob_invitation(&self, invitation: AriesMessage) -> HarnessResult<String> {
info!("Received out-of-band invitation: {invitation}");
let id = self
.aries_agent
.out_of_band()
.receive_invitation(invitation)?;
Ok(json!({ "connection_id": id, "state": "invitation-received" }).to_string())
}
pub async fn get_oob(&self, id: &str) -> HarnessResult<String> {
soft_assert_eq!(self.aries_agent.out_of_band().exists_by_id(id), true);
Ok(json!({ "connection_id": id }).to_string())
}
}
#[post("/send-invitation-message")]
async fn send_invitation_message(agent: web::Data<RwLock<HarnessAgent>>) -> impl Responder {
agent.read().unwrap().create_oob_invitation().await
}
#[post("/receive-invitation")]
async fn receive_invitation_message(
req: web::Json<AathRequest<Option<AriesMessage>>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent
.read()
.unwrap()
.receive_oob_invitation(req.data.clone().ok_or_else(|| {
HarnessError::from_msg(
HarnessErrorType::InvalidJson,
"Missing invitation in request body",
)
})?)
.await
}
#[get("/{thread_id}")]
async fn get_oob(
agent: web::Data<RwLock<HarnessAgent>>,
path: web::Path<String>,
) -> impl Responder {
agent.read().unwrap().get_oob(&path.into_inner()).await
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/command/out-of-band")
.service(send_invitation_message)
.service(receive_invitation_message),
)
.service(web::scope("/response/out-of-band").service(get_oob));
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/controllers/schema.rs | aries/agents/aath-backchannel/src/controllers/schema.rs | use std::sync::RwLock;
use actix_web::{get, post, web, Responder};
use crate::{
controllers::AathRequest,
error::{HarnessError, HarnessErrorType, HarnessResult},
soft_assert_eq, HarnessAgent,
};
#[derive(Serialize, Deserialize, Default)]
pub struct Schema {
schema_name: String,
schema_version: String,
attributes: Vec<String>,
}
impl HarnessAgent {
fn schema_id(&self, schema: &Schema) -> String {
let did = self.aries_agent.issuer_did();
let &Schema {
schema_name,
schema_version,
..
} = &schema;
format!("{did}:2:{schema_name}:{schema_version}")
}
async fn schema_published(&self, id: &str) -> bool {
self.aries_agent.schemas().schema_json(id).await.is_ok()
}
pub async fn create_schema(&self, schema: &Schema) -> HarnessResult<String> {
let id = self.schema_id(schema);
if !self.schema_published(&id).await {
soft_assert_eq!(
self.aries_agent
.schemas()
.create_schema(
&schema.schema_name,
&schema.schema_version,
schema.attributes.clone(),
)
.await?,
id
);
self.aries_agent.schemas().publish_schema(&id).await?;
};
Ok(json!({ "schema_id": id }).to_string())
}
pub async fn get_schema(&self, id: &str) -> HarnessResult<String> {
self.aries_agent
.schemas()
.schema_json(id)
.await
.map_err(|err| err.into())
}
}
#[post("")]
pub async fn create_schema(
req: web::Json<AathRequest<Schema>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent.read().unwrap().create_schema(&req.data).await
}
#[get("/{schema_id}")]
pub async fn get_schema(
agent: web::Data<RwLock<HarnessAgent>>,
path: web::Path<String>,
) -> impl Responder {
agent.read().unwrap().get_schema(&path.into_inner()).await
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/command/schema")
.service(create_schema)
.service(get_schema),
);
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/controllers/did_exchange.rs | aries/agents/aath-backchannel/src/controllers/did_exchange.rs | use std::sync::RwLock;
use actix_web::{get, post, web, Responder};
use aries_vcx_agent::aries_vcx::{
did_parser_nom::Did,
messages::{
msg_fields::protocols::did_exchange::{
v1_0::DidExchangeV1_0, v1_1::DidExchangeV1_1, v1_x::request::AnyRequest, DidExchange,
},
AriesMessage,
},
protocols::did_exchange::state_machine::requester::helpers::{
invitation_get_acceptable_did_exchange_version, invitation_get_first_did_service,
},
};
use serde_json::Value;
use crate::{
controllers::AathRequest,
error::{HarnessError, HarnessErrorType, HarnessResult},
HarnessAgent,
};
#[derive(Deserialize)]
#[allow(dead_code)]
pub struct CreateResolvableDidRequest {
their_public_did: String,
their_did: String,
}
impl HarnessAgent {
pub async fn didx_requester_send_request(
&self,
invitation_id: String,
) -> HarnessResult<String> {
let invitation = self
.aries_agent
.out_of_band()
.get_invitation(&invitation_id)?;
let version = invitation_get_acceptable_did_exchange_version(&invitation)?;
let did_inviter: Did = invitation_get_first_did_service(&invitation)?;
let (thid, pthid, my_did) = self
.aries_agent
.did_exchange()
.handle_msg_invitation(did_inviter.to_string(), Some(invitation_id), version)
.await?;
if let Some(ref pthid) = pthid {
self.store_mapping_pthid_thid(pthid.clone(), thid.clone());
} else {
warn!(
"didx_requester_send_request >> No storing pthid->this mapping; no pthid available"
);
}
let connection_id = pthid.unwrap_or(thid);
Ok(json!({
"connection_id" : connection_id,
"my_did": my_did
})
.to_string())
}
pub fn queue_didexchange_request(
&self,
request: AnyRequest,
recipient_verkey: String,
) -> HarnessResult<()> {
info!("queue_didexchange_request >> request: {request:?} for recipient {recipient_verkey}");
let thid = request
.inner()
.decorators
.thread
.clone()
.ok_or(HarnessError::from_msg(
HarnessErrorType::InvalidState,
"DID Exchange request is missing a thread",
))?;
let mut msg_buffer = self.didx_msg_buffer.write().map_err(|_| {
HarnessError::from_msg(
HarnessErrorType::InvalidState,
"Failed to lock message buffer",
)
})?;
let m = AriesMessage::from(request);
msg_buffer.push(m);
let mut recipients = self
.didx_thid_to_request_recipient_verkey
.lock()
.map_err(|_| {
HarnessError::from_msg(
HarnessErrorType::InvalidState,
"Failed to lock DIDExchange ",
)
})?;
recipients.insert(thid.thid, recipient_verkey);
Ok(())
}
// Note: used by test-case did-exchange @T005-RFC0023
pub async fn didx_requester_send_request_from_resolvable_did(
&self,
req: &CreateResolvableDidRequest,
) -> HarnessResult<String> {
let (thid, pthid, my_did) = self
.aries_agent
.did_exchange()
.handle_msg_invitation(req.their_public_did.clone(), None, Default::default()) // todo: separate the case with/without invitation on did_exchange handler
.await?;
let connection_id = pthid.unwrap_or(thid);
Ok(json!({
"connection_id": connection_id,
"my_did": my_did
})
.to_string())
}
// Looks up an oldest unprocessed did-exchange request message
// Messages received via didcomm are unprocessed
pub async fn didx_responder_receive_request_from_resolvable_did(
&self,
) -> HarnessResult<String> {
let request = {
debug!("receive_did_exchange_request_resolvable_did >>");
let msgs = self.didx_msg_buffer.write().map_err(|_| {
HarnessError::from_msg(
HarnessErrorType::InvalidState,
"Failed to lock message buffer",
)
})?;
msgs.first()
.ok_or_else(|| {
HarnessError::from_msg(
HarnessErrorType::InvalidState,
"receive_did_exchange_request_resolvable_did >> Expected to find \
DidExchange request message in buffer, found nothing.",
)
})?
.clone()
};
let request = match request {
AriesMessage::DidExchange(DidExchange::V1_0(DidExchangeV1_0::Request(request)))
| AriesMessage::DidExchange(DidExchange::V1_1(DidExchangeV1_1::Request(request))) => {
request
}
_ => {
return Err(HarnessError::from_msg(
HarnessErrorType::InvalidState,
"Message is not a request",
))
}
};
let thid = request.decorators.thread.clone().unwrap().thid;
Ok(json!({ "connection_id": thid }).to_string())
}
// Note: AVF identifies protocols by thid, but AATH sometimes tracks identifies did-exchange
// connection using pthread_id instead (if one exists; eg. connection was bootstrapped
// from invitation) That's why we need pthid -> thid translation on AATH layer.
fn store_mapping_pthid_thid(&self, pthid: String, thid: String) {
info!("store_mapping_pthid_thid >> pthid: {pthid}, thid: {thid}");
self.didx_pthid_to_thid
.lock()
.unwrap()
.insert(pthid, thid.clone());
}
pub async fn didx_responder_send_did_exchange_response(&self) -> HarnessResult<String> {
let request = {
let mut request_guard = self.didx_msg_buffer.write().map_err(|_| {
HarnessError::from_msg(
HarnessErrorType::InvalidState,
"Failed to lock message buffer",
)
})?;
request_guard.pop().ok_or_else(|| {
HarnessError::from_msg(
HarnessErrorType::InvalidState,
"send_did_exchange_response >> Expected to find DidExchange request message \
in buffer, found nothing.",
)
})?
};
let request = match request {
AriesMessage::DidExchange(DidExchange::V1_0(DidExchangeV1_0::Request(r))) => {
AnyRequest::V1_0(r)
}
AriesMessage::DidExchange(DidExchange::V1_1(DidExchangeV1_1::Request(r))) => {
AnyRequest::V1_1(r)
}
_ => {
return Err(HarnessError::from_msg(
HarnessErrorType::InvalidState,
"Message is not a request",
))
}
};
let request_thread = &request.inner().decorators.thread;
let recipient_key = request_thread
.as_ref()
.and_then(|th| {
self.didx_thid_to_request_recipient_verkey
.lock()
.unwrap()
.get(&th.thid)
.cloned()
})
.ok_or_else(|| {
HarnessError::from_msg(HarnessErrorType::InvalidState, "Inviter key not found")
})?;
let opt_invitation = match request_thread.as_ref().and_then(|th| th.pthid.as_ref()) {
Some(pthid) => {
let invitation = self.aries_agent.out_of_band().get_invitation(pthid)?;
Some(invitation)
}
None => None,
};
let (thid, pthid, my_did, their_did) = self
.aries_agent
.did_exchange()
.handle_msg_request(request, recipient_key, opt_invitation)
.await?;
if let Some(pthid) = pthid {
self.store_mapping_pthid_thid(pthid, thid.clone());
} else {
warn!("No storing pthid->this mapping; no pthid available");
}
self.aries_agent
.did_exchange()
.send_response(thid.clone())
.await?;
Ok(json!({
"connection_id": thid,
"my_did": my_did,
"their_did": their_did
})
.to_string())
}
pub async fn didx_get_state(&self, connection_id: &str) -> HarnessResult<String> {
let thid = match self.didx_pthid_to_thid.lock().unwrap().get(connection_id) {
Some(thid) => {
debug!(
"didx_get_state >> connection_id {connection_id} (pthid) was mapped to {thid} (thid)"
);
thid.clone() // connection_id was in fact pthread_id, mapping pthid -> thid exists
}
None => {
connection_id.to_string() // connection_id was thid already, no mapping exists
}
};
let state = self.aries_agent.did_exchange().get_state(&thid)?;
Ok(json!({ "state": state }).to_string())
}
pub async fn didx_get_invitation_id(&self, connection_id: &str) -> HarnessResult<String> {
// note: old implementation:
// let invitation_id = self.aries_agent.did_exchange().invitation_id(id)?;
// note: thread_id is handle for our protocol on harness level, no need to resolve anything
Ok(json!({ "connection_id": connection_id }).to_string())
}
}
#[post("/send-request")]
async fn send_did_exchange_request(
req: web::Json<AathRequest<Value>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent
.read()
.unwrap()
.didx_requester_send_request(req.id.clone())
.await
}
#[post("/create-request-resolvable-did")]
async fn send_did_exchange_request_resolvable_did(
req: web::Json<AathRequest<Option<CreateResolvableDidRequest>>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent
.read()
.unwrap()
.didx_requester_send_request_from_resolvable_did(req.data.as_ref().ok_or(
HarnessError::from_msg(
HarnessErrorType::InvalidJson,
"Failed to deserialize pairwise invitation",
),
)?)
.await
}
// Note: AATH expects us to identify connection-request we should have received prior to this call
// and assign connection_id to that communication (returned from this function)
#[post("/receive-request-resolvable-did")]
async fn receive_did_exchange_request_resolvable_did(
agent: web::Data<RwLock<HarnessAgent>>,
_msg_buffer: web::Data<RwLock<Vec<AriesMessage>>>,
) -> impl Responder {
agent
.read()
.unwrap()
.didx_responder_receive_request_from_resolvable_did()
.await
}
#[post("/send-response")]
async fn send_did_exchange_response(
_req: web::Json<AathRequest<()>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent
.read()
.unwrap()
.didx_responder_send_did_exchange_response()
.await
}
#[get("/{thread_id}")]
async fn get_invitation_id(
agent: web::Data<RwLock<HarnessAgent>>,
path: web::Path<String>,
) -> impl Responder {
agent
.read()
.unwrap()
.didx_get_invitation_id(&path.into_inner())
.await
}
#[get("/{thread_id}")]
pub async fn get_did_exchange_state(
agent: web::Data<RwLock<HarnessAgent>>,
path: web::Path<String>,
) -> impl Responder {
agent
.read()
.unwrap()
.didx_get_state(&path.into_inner())
.await
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/command/did-exchange")
.service(send_did_exchange_request)
.service(send_did_exchange_response)
.service(receive_did_exchange_request_resolvable_did)
.service(send_did_exchange_request_resolvable_did)
.service(get_did_exchange_state),
)
.service(web::scope("/response/did-exchange").service(get_invitation_id));
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/controllers/mod.rs | aries/agents/aath-backchannel/src/controllers/mod.rs | use serde::Deserialize;
pub mod connection;
pub mod credential_definition;
pub mod did_exchange;
pub mod didcomm;
pub mod general;
pub mod issuance;
pub mod out_of_band;
pub mod presentation;
pub mod revocation;
pub mod schema;
#[derive(Deserialize)]
pub struct AathRequest<T> {
#[serde(default)]
pub id: String,
#[serde(default)]
pub data: T,
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/controllers/didcomm.rs | aries/agents/aath-backchannel/src/controllers/didcomm.rs | use std::sync::RwLock;
use actix_web::{web, HttpResponse, Responder};
use aries_vcx_agent::aries_vcx::{
messages::{
msg_fields::protocols::{
connection::Connection,
cred_issuance::{v1::CredentialIssuanceV1, CredentialIssuance},
did_exchange::{
v1_0::DidExchangeV1_0, v1_1::DidExchangeV1_1, v1_x::request::AnyRequest,
DidExchange,
},
notification::Notification,
present_proof::{v1::PresentProofV1, PresentProof},
trust_ping::TrustPing,
},
AriesMessage,
},
utils::encryption_envelope::EncryptionEnvelope,
};
use crate::{
error::{HarnessError, HarnessErrorType, HarnessResult},
HarnessAgent,
};
impl HarnessAgent {
async fn handle_connection_msg(&self, msg: Connection) -> HarnessResult<()> {
match msg {
Connection::Request(request) => {
let thread_id = request
.decorators
.thread
.clone()
.map_or(request.id.clone(), |thread| thread.thid.clone());
let connection_id = match self.aries_agent.connections().exists_by_id(&thread_id) {
true => thread_id,
false => {
if let Some(thread) = &request.decorators.thread {
if let Some(pthid) = &thread.pthid {
pthid.clone()
} else {
return Err(HarnessError::from_msg(
HarnessErrorType::InvalidState,
"Connection request does not contain parent thread id",
));
}
} else {
return Err(HarnessError::from_msg(
HarnessErrorType::InvalidState,
"Connection request does not contain thread info decorator",
));
}
}
};
self.aries_agent
.connections()
.accept_request(&connection_id, request)
.await
.ok();
}
Connection::Response(response) => {
let thread_id = response.decorators.thread.thid.clone();
self.aries_agent
.connections()
.accept_response(&thread_id, response)
.await?;
}
m => {
warn!("Received unexpected connection protocol message: {m:?}");
}
};
Ok(())
}
async fn handle_issuance_msg(
&self,
msg: CredentialIssuance,
connection_id: &str,
) -> HarnessResult<()> {
match msg {
CredentialIssuance::V1(msg) => self.handle_issuance_msg_v1(msg, connection_id).await,
CredentialIssuance::V2(_) => {
unimplemented!("V2 issuance is not implemented for aries-vcx aath")
}
}
}
async fn handle_issuance_msg_v1(
&self,
msg: CredentialIssuanceV1,
connection_id: &str,
) -> HarnessResult<()> {
match msg {
CredentialIssuanceV1::OfferCredential(offer) => {
self.aries_agent
.holder()
.create_from_offer(connection_id, offer.clone())?;
}
CredentialIssuanceV1::ProposeCredential(proposal) => {
self.aries_agent
.issuer()
.accept_proposal(connection_id, &proposal)
.await?;
}
CredentialIssuanceV1::RequestCredential(request) => {
let thread_id = request
.decorators
.thread
.clone()
.map_or(request.id.clone(), |thread| thread.thid.clone());
self.aries_agent
.issuer()
.process_credential_request(&thread_id, request)?;
}
CredentialIssuanceV1::IssueCredential(credential) => {
let thread_id = credential.decorators.thread.thid.clone();
self.aries_agent
.holder()
.process_credential(&thread_id, credential)
.await?;
}
m => {
warn!("Received unexpected issuance protocol message: {m:?}");
}
};
Ok(())
}
async fn handle_presentation_msg(
&self,
msg: PresentProof,
connection_id: &str,
) -> HarnessResult<()> {
match msg {
PresentProof::V1(msg) => self.handle_presentation_msg_v1(msg, connection_id).await,
PresentProof::V2(_) => {
unimplemented!("V2 issuance is not implemented for aries-vcx aath")
}
}
}
async fn handle_presentation_msg_v1(
&self,
msg: PresentProofV1,
connection_id: &str,
) -> HarnessResult<()> {
match msg {
PresentProofV1::RequestPresentation(request) => {
self.aries_agent
.prover()
.create_from_request(connection_id, request)?;
}
PresentProofV1::Presentation(presentation) => {
let thread_id = presentation.decorators.thread.thid.clone();
self.aries_agent
.verifier()
.verify_presentation(&thread_id, presentation)
.await?;
}
m => {
// todo: use {} display formatter
warn!("Received unexpected presentation protocol message: {m:?}");
}
};
Ok(())
}
async fn handle_did_exchange_msg(
&self,
msg: DidExchange,
recipient_verkey: String,
) -> HarnessResult<()> {
match msg {
DidExchange::V1_0(DidExchangeV1_0::Request(request)) => {
self.queue_didexchange_request(AnyRequest::V1_0(request), recipient_verkey)?;
}
DidExchange::V1_1(DidExchangeV1_1::Request(request)) => {
self.queue_didexchange_request(AnyRequest::V1_1(request), recipient_verkey)?;
}
DidExchange::V1_0(DidExchangeV1_0::Response(response)) => {
let res = self
.aries_agent
.did_exchange()
.handle_msg_response(response.into())
.await;
if let Err(err) = res {
error!("Error sending complete: {err:?}");
};
}
DidExchange::V1_1(DidExchangeV1_1::Response(response)) => {
let res = self
.aries_agent
.did_exchange()
.handle_msg_response(response.into())
.await;
if let Err(err) = res {
error!("Error sending complete: {err:?}");
};
}
DidExchange::V1_0(DidExchangeV1_0::Complete(complete))
| DidExchange::V1_1(DidExchangeV1_1::Complete(complete)) => {
self.aries_agent
.did_exchange()
.handle_msg_complete(complete)?;
}
DidExchange::V1_0(DidExchangeV1_0::ProblemReport(problem_report))
| DidExchange::V1_1(DidExchangeV1_1::ProblemReport(problem_report)) => {
self.aries_agent
.did_exchange()
.receive_problem_report(problem_report)?;
}
};
Ok(())
}
pub async fn receive_message(&self, payload: Vec<u8>) -> HarnessResult<HttpResponse> {
let (message, sender_vk, recipient_vk) = EncryptionEnvelope::unpack_aries_msg(
self.aries_agent.wallet().as_ref(),
&payload,
&None,
)
.await?;
let sender_vk = sender_vk.ok_or_else(|| {
HarnessError::from_msg(
HarnessErrorType::EncryptionError,
"Received anoncrypted message",
)
})?;
info!("Received message: {message}");
match message {
AriesMessage::Notification(msg) => {
match msg {
Notification::Ack(ack) => {
self.aries_agent
.connections()
.process_ack(ack.clone())
.await?;
}
Notification::ProblemReport(err) => {
error!("Received problem report: {err:?}");
// todo: we should reflect this in the status of connection so aath won't
// keep polling
}
}
}
AriesMessage::TrustPing(TrustPing::Ping(msg)) => {
let connection_id = self
.aries_agent
.connections()
.get_by_sender_vk(sender_vk.base58())?;
self.aries_agent
.connections()
.process_trust_ping(msg, &connection_id)
.await?
}
AriesMessage::Connection(msg) => self.handle_connection_msg(msg).await?,
AriesMessage::CredentialIssuance(msg) => {
let connection_id = self
.aries_agent
.connections()
.get_by_sender_vk(sender_vk.base58())?;
self.handle_issuance_msg(msg, &connection_id).await?
}
AriesMessage::DidExchange(msg) => {
self.handle_did_exchange_msg(msg, recipient_vk.base58())
.await?
}
AriesMessage::PresentProof(msg) => {
let connection_id = self
.aries_agent
.connections()
.get_by_sender_vk(sender_vk.base58())?;
self.handle_presentation_msg(msg, &connection_id).await?
}
m => {
warn!("Received message of unexpected type: {m}");
}
};
Ok(HttpResponse::Ok().finish())
}
}
pub async fn receive_message(
req: web::Bytes,
agent: web::Data<RwLock<HarnessAgent>>,
_msg_buffer: web::Data<RwLock<Vec<AriesMessage>>>,
) -> impl Responder {
agent.read().unwrap().receive_message(req.to_vec()).await
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/controllers/credential_definition.rs | aries/agents/aath-backchannel/src/controllers/credential_definition.rs | use std::sync::RwLock;
use actix_web::{get, post, web, Responder};
use anoncreds_types::data_types::identifiers::{
cred_def_id::CredentialDefinitionId, schema_id::SchemaId,
};
use aries_vcx_agent::aries_vcx::did_parser_nom::Did;
use reqwest::multipart;
use crate::{
controllers::AathRequest,
error::{HarnessError, HarnessErrorType, HarnessResult},
soft_assert_eq, HarnessAgent,
};
#[derive(Serialize, Deserialize, Default, Debug)]
pub struct CredentialDefinition {
support_revocation: bool,
schema_id: String,
tag: String,
}
async fn upload_tails_file(tails_url: &str, tails_file: &str) -> HarnessResult<()> {
info!("Going to upload tails file {tails_file} to {tails_url}");
let client = reqwest::Client::new();
let genesis_file = std::env::var("GENESIS_FILE").unwrap_or(
std::env::current_dir()
.expect("Failed to obtain the current directory path")
.join("resource")
.join("genesis_file.txn")
.to_str()
.ok_or(HarnessError::from_msg(
HarnessErrorType::InternalServerError,
"Failed to convert path to str",
))?
.to_string(),
);
let genesis_file_data = std::fs::read(genesis_file)?;
let tails_file_data = std::fs::read(tails_file)?;
let genesis_part = multipart::Part::bytes(genesis_file_data);
let tails_part = multipart::Part::bytes(tails_file_data);
let form = multipart::Form::new()
.part("genesis", genesis_part)
.part("tails", tails_part);
let res = client.put(tails_url).multipart(form).send().await?;
soft_assert_eq!(res.status(), reqwest::StatusCode::OK);
Ok(())
}
impl HarnessAgent {
pub async fn create_credential_definition(
&self,
cred_def: &CredentialDefinition,
) -> HarnessResult<String> {
let tails_base_url = std::env::var("TAILS_SERVER_URL")
.unwrap_or("https://tails-server-test.pathfinder.gov.bc.ca".to_string());
let cred_def_ids = self
.aries_agent
.cred_defs()
.find_by_schema_id(&cred_def.schema_id)?;
let cred_def_id = if cred_def_ids.is_empty() {
let cred_def_id = self
.aries_agent
.cred_defs()
.create_cred_def(
Did::parse(self.aries_agent.issuer_did())?,
SchemaId::new(&cred_def.schema_id)?,
cred_def.tag.clone(),
)
.await?;
self.aries_agent
.cred_defs()
.publish_cred_def(&cred_def_id)
.await?;
if cred_def.support_revocation {
let rev_reg_id = self
.aries_agent
.rev_regs()
.create_rev_reg(&CredentialDefinitionId::new(cred_def_id.clone())?, 50)
.await?;
let tails_url = format!("{tails_base_url}/{rev_reg_id}");
self.aries_agent
.rev_regs()
.publish_rev_reg(&rev_reg_id, &tails_url)
.await?;
let tails_file = self.aries_agent.rev_regs().tails_file_path(&rev_reg_id)?;
upload_tails_file(&tails_url, &tails_file).await?;
}
cred_def_id
} else if cred_def_ids.len() == 1 {
cred_def_ids.last().unwrap().clone()
} else {
return Err(HarnessError::from_kind(
HarnessErrorType::MultipleCredDefinitions,
));
};
Ok(json!({ "credential_definition_id": cred_def_id }).to_string())
}
pub fn get_credential_definition(&self, id: &str) -> HarnessResult<String> {
self.aries_agent
.cred_defs()
.cred_def_json(id)
.map_err(|err| err.into())
}
}
#[post("")]
pub async fn create_credential_definition(
req: web::Json<AathRequest<CredentialDefinition>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent
.read()
.unwrap()
.create_credential_definition(&req.data)
.await
}
#[get("/{cred_def_id}")]
pub async fn get_credential_definition(
agent: web::Data<RwLock<HarnessAgent>>,
path: web::Path<String>,
) -> impl Responder {
agent
.read()
.unwrap()
.get_credential_definition(&path.into_inner())
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/command/credential-definition")
.service(create_credential_definition)
.service(get_credential_definition),
);
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/controllers/revocation.rs | aries/agents/aath-backchannel/src/controllers/revocation.rs | use std::sync::RwLock;
use actix_web::{get, post, web, Responder};
use crate::{controllers::AathRequest, error::HarnessResult, HarnessAgent};
#[derive(Serialize, Deserialize, Default, Clone, Debug)]
pub struct CredentialRevocationData {
cred_rev_id: String,
rev_registry_id: String,
publish_immediately: bool,
notify_connection_id: String,
}
impl HarnessAgent {
pub async fn revoke_credential(
&self,
revocation_data: &CredentialRevocationData,
) -> HarnessResult<String> {
let CredentialRevocationData {
rev_registry_id,
cred_rev_id,
publish_immediately,
..
} = revocation_data;
self.aries_agent
.rev_regs()
.revoke_credential_locally(rev_registry_id, cred_rev_id)
.await?;
if *publish_immediately {
self.aries_agent
.rev_regs()
.publish_local_revocations(rev_registry_id)
.await?;
};
Ok("".to_string())
}
pub fn get_rev_reg_info_for_credential(&self, id: &str) -> HarnessResult<String> {
let rev_reg_id = self.aries_agent.issuer().get_rev_reg_id(id)?;
let rev_id = self.aries_agent.issuer().get_rev_id(id)?;
Ok(json!({ "revoc_reg_id": rev_reg_id, "revocation_id": rev_id }).to_string())
}
}
#[post("/revoke")]
pub async fn revoke_credential(
agent: web::Data<RwLock<HarnessAgent>>,
req: web::Json<AathRequest<CredentialRevocationData>>,
) -> impl Responder {
agent.read().unwrap().revoke_credential(&req.data).await
}
#[get("/{cred_id}")]
pub async fn get_rev_reg_info_for_credential(
agent: web::Data<RwLock<HarnessAgent>>,
path: web::Path<String>,
) -> impl Responder {
agent
.read()
.unwrap()
.get_rev_reg_info_for_credential(&path.into_inner())
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/response/revocation-registry").service(get_rev_reg_info_for_credential),
)
.service(web::scope("/command/revocation").service(revoke_credential));
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aath-backchannel/src/controllers/issuance.rs | aries/agents/aath-backchannel/src/controllers/issuance.rs | use std::sync::RwLock;
use actix_web::{get, post, web, Responder};
use anoncreds_types::data_types::identifiers::cred_def_id::CredentialDefinitionId;
use aries_vcx_agent::aries_vcx::{
handlers::util::OfferInfo,
messages::msg_fields::protocols::cred_issuance::v1::{
propose_credential::{ProposeCredentialV1, ProposeCredentialV1Content},
CredentialPreviewV1 as VcxCredentialPreview, CredentialPreviewV1,
},
protocols::issuance::{holder::state_machine::HolderState, issuer::state_machine::IssuerState},
};
use display_as_json::Display;
use uuid::Uuid;
use crate::{
controllers::AathRequest,
error::{HarnessError, HarnessErrorType, HarnessResult},
soft_assert_eq, HarnessAgent, State,
};
#[derive(Serialize, Deserialize, Clone, Debug)]
struct CredentialPreview(VcxCredentialPreview);
impl Default for CredentialPreview {
fn default() -> Self {
CredentialPreview(VcxCredentialPreview::new(vec![]))
}
}
#[derive(Serialize, Deserialize, Default, Debug, Display)]
pub struct CredentialOffer {
cred_def_id: String,
credential_preview: CredentialPreview,
connection_id: String,
}
#[derive(Serialize, Deserialize, Default, Clone, Debug, Display)]
pub struct CredentialProposal {
schema_issuer_did: String,
issuer_did: String,
schema_name: String,
cred_def_id: String,
schema_version: String,
credential_proposal: CredentialPreview,
connection_id: String,
schema_id: String,
}
#[derive(Serialize, Deserialize, Default)]
pub struct Credential {
credential_preview: CredentialPreview,
#[serde(default)]
comment: Option<String>,
}
#[derive(Serialize, Deserialize, Default)]
pub struct CredentialId {
credential_id: String,
}
fn to_backchannel_state_issuer(state: IssuerState) -> State {
match state {
IssuerState::Initial => State::Initial,
IssuerState::ProposalReceived | IssuerState::OfferSet => State::ProposalReceived,
// IssuerState::OfferSent => State::OfferSent, // todo: we used to track "io state" in vcx,
// now we don't - will this fail some AATH cases?
IssuerState::RequestReceived => State::RequestReceived,
IssuerState::CredentialSet => State::CredentialSent,
IssuerState::Finished => State::Done,
IssuerState::Failed => State::Failure,
}
}
fn to_backchannel_state_holder(state: HolderState) -> State {
match state {
HolderState::Initial => State::Initial,
HolderState::ProposalSet => State::ProposalSent,
HolderState::OfferReceived => State::OfferReceived,
HolderState::RequestSet => State::RequestSent,
HolderState::Finished => State::Done,
HolderState::Failed => State::Failure,
}
}
async fn download_tails_file(
tails_base_url: &str,
rev_reg_id: &str,
tails_hash: &str,
) -> HarnessResult<()> {
info!(
"issuance::download_tails_file >> tails_base_url: {tails_base_url:?}, rev_reg_id: {rev_reg_id:?}, tails_hash: {tails_hash:?}"
);
let url = match tails_base_url.to_string().matches('/').count() {
0 => format!("{tails_base_url}/{rev_reg_id}"),
1.. => tails_base_url.to_string(),
};
let client = reqwest::Client::new();
let tails_folder_path = std::env::current_dir()
.expect("Failed to obtain the current directory path")
.join("resource")
.join("tails");
std::fs::create_dir_all(&tails_folder_path).map_err(|_| {
HarnessError::from_msg(
HarnessErrorType::InternalServerError,
"Failed to create tails folder",
)
})?;
let tails_file_path = tails_folder_path
.join(tails_hash)
.to_str()
.ok_or(HarnessError::from_msg(
HarnessErrorType::InternalServerError,
"Failed to convert tails hash to str",
))?
.to_string();
let res = client.get(&url).send().await?;
soft_assert_eq!(res.status(), reqwest::StatusCode::OK);
std::fs::write(tails_file_path, res.bytes().await?)?;
Ok(())
}
impl HarnessAgent {
pub async fn send_credential_proposal(
&self,
cred_proposal: &CredentialProposal,
) -> HarnessResult<String> {
info!("issuance::send_credential_proposal >>");
let proposal_id = Uuid::new_v4().to_string();
let attrs = cred_proposal.credential_proposal.0.attributes.clone();
let content = ProposeCredentialV1Content::builder()
.schema_id(cred_proposal.schema_id.clone())
.cred_def_id(cred_proposal.cred_def_id.clone())
.credential_proposal(CredentialPreviewV1::new(attrs.clone()))
.build();
let proposal_data = ProposeCredentialV1::builder()
.id(proposal_id.clone())
.content(content)
.build();
let id = self
.aries_agent
.holder()
.send_credential_proposal(&cred_proposal.connection_id, proposal_data)
.await?;
let state = to_backchannel_state_holder(self.aries_agent.holder().get_state(&id)?);
info!("issuance::send_credential_proposal << id: {id:?}");
// todo: we are not saving (or creating) the holder
Ok(json!({ "state": state, "thread_id": id }).to_string())
}
pub async fn send_credential_request(&self, thread_id: &str) -> HarnessResult<String> {
info!("issuance::send_credential_request >> id: {thread_id:?}");
self.aries_agent
.holder()
.send_credential_request(thread_id)
.await?;
let state = to_backchannel_state_holder(self.aries_agent.holder().get_state(thread_id)?);
Ok(json!({ "state": state, "thread_id": thread_id }).to_string())
}
pub async fn send_credential_offer(
&self,
cred_offer: &CredentialOffer,
thread_id: &str,
) -> HarnessResult<String> {
info!(
"issuance::send_credential_offer >> cred_offer: {cred_offer}, thread_id: {thread_id}"
);
let get_tails_rev_id =
|cred_def_id: &str| -> HarnessResult<(Option<String>, Option<String>)> {
Ok(
if let Some(rev_reg_id) = self
.aries_agent
.rev_regs()
.find_by_cred_def_id(cred_def_id)?
.pop()
{
(
Some(self.aries_agent.rev_regs().get_tails_dir(&rev_reg_id)?),
Some(rev_reg_id),
)
} else {
(None, None)
},
)
};
let connection_id = if cred_offer.connection_id.is_empty() {
None
} else {
Some(cred_offer.connection_id.as_str())
};
let (offer_info, id) = if thread_id.is_empty() {
let credential_preview =
serde_json::to_string(&cred_offer.credential_preview.0.attributes)?;
info!(
"issuance::send_credential_offer >> no thread_id provided, this offer initiates \
new didcomm conversation, using credential_preview: {credential_preview:?}"
);
let (tails_file, rev_reg_id) = get_tails_rev_id(&cred_offer.cred_def_id)?;
(
OfferInfo {
credential_json: credential_preview,
cred_def_id: CredentialDefinitionId::new(&cred_offer.cred_def_id)?,
rev_reg_id,
tails_file,
},
None,
)
} else {
let proposal = self.aries_agent.issuer().get_proposal(thread_id)?;
info!(
"issuance::send_credential_offer >> thread_id is available, this offer will be \
built based on previous proposal: {proposal:?}"
);
let (tails_file, rev_reg_id) = get_tails_rev_id(&proposal.content.cred_def_id)?;
(
OfferInfo {
credential_json: serde_json::to_string(
&proposal.content.credential_proposal.attributes,
)
.unwrap(),
cred_def_id: CredentialDefinitionId::new(&proposal.content.cred_def_id)?,
rev_reg_id,
tails_file,
},
Some(thread_id),
)
};
info!("issuance::send_credential_offer >> offer_info: {offer_info:?}");
let id = self
.aries_agent
.issuer()
.send_credential_offer(id, connection_id, offer_info)
.await?;
let state = to_backchannel_state_issuer(self.aries_agent.issuer().get_state(&id)?);
Ok(json!({ "state": state, "thread_id": id }).to_string())
}
pub async fn issue_credential(
&self,
id: &str,
_credential: &Credential,
) -> HarnessResult<String> {
info!("issuance::issue_credential >> id: {id:?}");
self.aries_agent.issuer().send_credential(id).await?;
let state = to_backchannel_state_issuer(self.aries_agent.issuer().get_state(id)?);
Ok(json!({ "state": state }).to_string())
}
pub async fn store_credential(&self, id: &str) -> HarnessResult<String> {
info!("issuance::store_credential >> id: {id:?}");
let state = self.aries_agent.holder().get_state(id)?;
if self.aries_agent.holder().is_revokable(id).await? {
let rev_reg_id = self.aries_agent.holder().get_rev_reg_id(id).await?;
let tails_hash = self.aries_agent.holder().get_tails_hash(id).await?;
let tails_location = self.aries_agent.holder().get_tails_location(id).await?;
download_tails_file(&tails_location, &rev_reg_id, &tails_hash).await?;
};
Ok(json!({ "state": to_backchannel_state_holder(state), "credential_id": id }).to_string())
}
pub async fn get_issuer_state(&self, id: &str) -> HarnessResult<String> {
info!("issuance::get_issuer_state >> id: {id:?}");
let state = if self.aries_agent.issuer().exists_by_id(id) {
to_backchannel_state_issuer(self.aries_agent.issuer().get_state(id)?)
} else if self.aries_agent.holder().exists_by_id(id) {
to_backchannel_state_holder(self.aries_agent.holder().get_state(id)?)
} else {
return Err(HarnessError::from_kind(HarnessErrorType::NotFoundError));
};
Ok(json!({ "state": state }).to_string())
}
pub async fn get_credential(&self, id: &str) -> HarnessResult<String> {
Ok(json!({ "referent": id }).to_string())
}
}
#[post("/send-proposal")]
pub async fn send_credential_proposal(
req: web::Json<AathRequest<CredentialProposal>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent
.read()
.unwrap()
.send_credential_proposal(&req.data)
.await
}
#[post("/send-offer")]
pub async fn send_credential_offer(
req: web::Json<AathRequest<CredentialOffer>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent
.read()
.unwrap()
.send_credential_offer(&req.data, &req.id)
.await
}
#[post("/send-request")]
pub async fn send_credential_request(
req: web::Json<AathRequest<String>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent.read().unwrap().send_credential_request(&req.id).await
}
#[get("/{issuer_id}")]
pub async fn get_issuer_state(
agent: web::Data<RwLock<HarnessAgent>>,
path: web::Path<String>,
) -> impl Responder {
agent
.read()
.unwrap()
.get_issuer_state(&path.into_inner())
.await
}
#[post("/issue")]
pub async fn issue_credential(
req: web::Json<AathRequest<Credential>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent
.read()
.unwrap()
.issue_credential(&req.id, &req.data)
.await
}
#[post("/store")]
pub async fn store_credential(
req: web::Json<AathRequest<CredentialId>>,
agent: web::Data<RwLock<HarnessAgent>>,
) -> impl Responder {
agent.read().unwrap().store_credential(&req.id).await
}
#[get("/{cred_id}")]
pub async fn get_credential(
agent: web::Data<RwLock<HarnessAgent>>,
path: web::Path<String>,
) -> impl Responder {
agent
.read()
.unwrap()
.get_credential(&path.into_inner())
.await
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/command/issue-credential")
.service(send_credential_proposal)
.service(send_credential_offer)
.service(get_issuer_state)
.service(send_credential_request)
.service(issue_credential)
.service(store_credential),
)
.service(web::scope("/command/credential").service(get_credential));
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/build.rs | aries/agents/mediator/build.rs | // generated by `sqlx migrate build-script`
fn main() {
// trigger recompilation when a new migration is added
println!("cargo:rerun-if-changed=migrations");
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/lib.rs | aries/agents/mediator/src/lib.rs | pub mod aries_agent;
pub mod didcomm_handlers;
pub mod http_routes;
pub mod mediation;
pub mod persistence;
pub mod utils;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/http_routes/mod.rs | aries/agents/mediator/src/http_routes/mod.rs | use std::sync::Arc;
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use axum::{
body::Bytes,
extract::State,
http::header::{HeaderMap, ACCEPT},
response::{Html, IntoResponse, Response},
routing::get,
Json, Router,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
aries_agent::{Agent, ArcAgent},
didcomm_handlers,
persistence::MediatorPersistence,
};
fn detect_mime_type(headers: &HeaderMap) -> &str {
headers
.get(ACCEPT)
.map(|s| s.to_str().unwrap_or_default())
.unwrap_or_default()
}
pub async fn oob_invite_json(
State(agent): State<ArcAgent<impl BaseWallet, impl MediatorPersistence>>,
) -> Json<Value> {
let oob = agent.get_oob_invite().unwrap();
Json(serde_json::to_value(oob).unwrap())
}
pub async fn handle_didcomm(
State(agent): State<ArcAgent<impl BaseWallet, impl MediatorPersistence>>,
didcomm_msg: Bytes,
) -> Result<Json<Value>, String> {
didcomm_handlers::handle_aries(State(agent), didcomm_msg).await
}
#[derive(Serialize, Deserialize)]
pub struct ReadmeInfo {
message: String,
}
pub async fn readme(headers: HeaderMap) -> Response {
match detect_mime_type(&headers) {
"application/json" => Json(ReadmeInfo {
message: "Please refer to the API section of a readme for usage. Thanks.".into(),
})
.into_response(),
_ => Html(
"<p>Please refer to the API section of <a>readme</a> for usage. Thanks. </p>"
.to_string(),
)
.into_response(),
}
}
pub async fn build_router(
agent: Agent<impl BaseWallet + 'static, impl MediatorPersistence>,
) -> Router {
Router::default()
.route("/", get(readme))
.route("/invitation", get(oob_invite_json))
.route("/didcomm", get(handle_didcomm).post(handle_didcomm))
.layer(tower_http::catch_panic::CatchPanicLayer::new())
.with_state(Arc::new(agent))
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/aries_agent/utils.rs | aries/agents/mediator/src/aries_agent/utils.rs | use aries_vcx::{
common::signing::sign_connection_response, errors::error::VcxResult, transport::Transport,
};
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use async_trait::async_trait;
use diddoc_legacy::aries::diddoc::AriesDidDoc;
use messages::{
decorators::thread::Thread,
msg_fields::protocols::connection::{
response::{Response, ResponseContent, ResponseDecorators},
ConnectionData,
},
};
use uuid::Uuid;
use crate::utils::structs::VerKey;
pub async fn build_response_content(
wallet: &impl BaseWallet,
thread_id: String,
old_recipient_vk: VerKey,
new_recipient_did: String,
new_recipient_vk: VerKey,
new_service_endpoint: url::Url,
new_routing_keys: Vec<String>,
) -> VcxResult<Response> {
let mut did_doc = AriesDidDoc::default();
let did = new_recipient_did.clone();
did_doc.set_id(new_recipient_did);
did_doc.set_service_endpoint(new_service_endpoint);
did_doc.set_routing_keys(new_routing_keys);
did_doc.set_recipient_keys(vec![new_recipient_vk]);
let con_data = ConnectionData::new(did, did_doc);
let id = Uuid::new_v4().to_string();
let con_sig = sign_connection_response(wallet, &old_recipient_vk, &con_data).await?;
let content = ResponseContent::builder().connection_sig(con_sig).build();
let decorators = ResponseDecorators::builder()
.thread(Thread::builder().thid(thread_id).build())
.build();
Ok(Response::builder()
.id(id)
.content(content)
.decorators(decorators)
.build())
}
pub struct MockTransport;
#[async_trait]
impl Transport for MockTransport {
async fn send_message(&self, _msg: Vec<u8>, _service_endpoint: &url::Url) -> VcxResult<()> {
Ok(())
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/aries_agent/mod.rs | aries/agents/mediator/src/aries_agent/mod.rs | use std::{marker::PhantomData, sync::Arc};
use aries_vcx::{
handlers::out_of_band::sender::OutOfBandSender,
messages::msg_fields::protocols::out_of_band::invitation::OobService,
utils::encryption_envelope::EncryptionEnvelope,
};
use aries_vcx_wallet::{
errors::error::VcxWalletError,
wallet::{
askar::{askar_wallet_config::AskarWalletConfig, key_method::KeyMethod},
base_wallet::{BaseWallet, ManageWallet},
structs_io::UnpackMessageOutput,
},
};
use diddoc_legacy::aries::{diddoc::AriesDidDoc, service::AriesService};
use messages::{
msg_fields::protocols::{
connection::{request::Request, response::Response, Connection},
out_of_band::invitation::Invitation as OOBInvitation,
},
AriesMessage,
};
use serde_json::json;
use uuid::Uuid;
use crate::{
persistence::{get_persistence, AccountDetails, MediatorPersistence},
utils::{prelude::*, structs::VerKey},
};
#[cfg(any(test, feature = "client"))]
pub mod client;
pub mod utils;
#[derive(Clone)]
pub struct Agent<T: BaseWallet, P: MediatorPersistence> {
wallet: Arc<T>,
persistence: Arc<P>,
service: Option<AriesService>,
}
pub type ArcAgent<T, P> = Arc<Agent<T, P>>;
pub struct AgentBuilder<T: BaseWallet> {
_type_wallet: PhantomData<T>,
}
/// Constructors
impl<T: BaseWallet> AgentBuilder<T> {
pub async fn new_from_wallet_config(
config: impl ManageWallet,
) -> Result<Agent<impl BaseWallet, sqlx::MySqlPool>, VcxWalletError> {
let wallet = Arc::new(config.create_wallet().await?);
info!("Connecting to persistence layer");
let persistence = Arc::new(get_persistence().await);
Ok(Agent {
wallet,
persistence,
service: None,
})
}
pub async fn new_demo_agent() -> Result<Agent<impl BaseWallet, sqlx::MySqlPool>, VcxWalletError>
{
let config = AskarWalletConfig::new(
"sqlite://:memory:",
KeyMethod::Unprotected,
"",
&Uuid::new_v4().to_string(),
);
Self::new_from_wallet_config(config).await
}
}
// Utils
impl<T: BaseWallet, P: MediatorPersistence> Agent<T, P> {
pub fn get_wallet_ref(&self) -> Arc<T> {
self.wallet.clone()
}
pub fn get_persistence_ref(&self) -> Arc<impl MediatorPersistence> {
self.persistence.clone()
}
pub fn get_service_ref(&self) -> Option<&AriesService> {
self.service.as_ref()
}
pub async fn reset_service(
&mut self,
routing_keys: Vec<String>,
service_endpoint: url::Url,
) -> Result<(), VcxWalletError> {
let did_data = self.wallet.create_and_store_my_did(None, None).await?;
let service = AriesService {
id: "#inline".to_owned(),
type_: "did-communication".to_owned(),
priority: 0,
recipient_keys: vec![did_data.verkey().base58()],
routing_keys,
service_endpoint,
};
self.service = Some(service);
Ok(())
}
pub async fn init_service(
&mut self,
routing_keys: Vec<String>,
service_endpoint: url::Url,
) -> Result<(), VcxWalletError> {
self.reset_service(routing_keys, service_endpoint).await
}
pub fn get_oob_invite(&self) -> Result<OOBInvitation, String> {
if let Some(service) = &self.service {
let invitation = OutOfBandSender::create()
.append_service(&OobService::AriesService(service.clone()))
.oob;
Ok(invitation)
} else {
Err("No service to create invite for".to_owned())
}
}
pub async fn unpack_didcomm(&self, didcomm_msg: &[u8]) -> Result<UnpackMessageOutput, String> {
let unpacked = self
.wallet
.unpack_message(didcomm_msg)
.await
.expect("Valid didcomm?");
info!("{unpacked:#?}");
Ok(unpacked)
}
pub async fn pack_didcomm(
&self,
message: &[u8],
our_vk: &VerKey,
their_diddoc: &AriesDidDoc,
) -> Result<EncryptionEnvelope, String> {
EncryptionEnvelope::create_from_legacy(
self.wallet.as_ref(),
message,
Some(our_vk),
their_diddoc,
)
.await
.map_err(string_from_std_error)
}
pub async fn auth_and_get_details(
&self,
sender_verkey: &Option<VerKey>,
) -> Result<AccountDetails, String> {
let auth_pubkey = sender_verkey
.as_deref()
.ok_or("Anonymous sender can't be authenticated")?
.to_owned();
let account_details = self
.persistence
.get_account_details(&auth_pubkey)
.await
.map_err(string_from_std_error)?;
Ok(account_details)
}
pub async fn handle_connection_req(
&self,
request: Request,
) -> Result<EncryptionEnvelope, String> {
if let Err(err) = request.content.connection.did_doc.validate() {
return Err(format!("Request DidDoc validation failed! {err:?}"));
}
let thread_id = request
.decorators
.thread
.map(|t| t.thid)
.unwrap_or(request.id);
let did_data = self
.wallet
.create_and_store_my_did(None, None)
.await
.map_err(|e| e.to_string())?;
let old_vk = self
.service
.as_ref()
.unwrap()
.recipient_keys
.first()
.unwrap()
.to_owned();
let response: Response = utils::build_response_content(
self.wallet.as_ref(),
thread_id,
old_vk.clone(),
did_data.did().into(),
did_data.verkey().base58(),
self.service.as_ref().unwrap().service_endpoint.clone(),
self.service.as_ref().unwrap().routing_keys.clone(),
)
.await
.map_err(|e| e.to_string())?;
let aries_response = AriesMessage::Connection(Connection::Response(response));
let their_diddoc = request.content.connection.did_doc;
let packed_response_envelope = EncryptionEnvelope::create_from_legacy(
self.wallet.as_ref(),
json!(aries_response).to_string().as_bytes(),
Some(&old_vk),
&their_diddoc,
)
.await
.map_err(|e| e.to_string())?;
let their_keys = their_diddoc.recipient_keys().map_err(|e| e.to_string())?;
let auth_pubkey = their_keys
.first()
.ok_or("No recipient key for client :/ ?".to_owned())?;
self.create_account(auth_pubkey, &did_data.verkey().base58(), &their_diddoc)
.await?;
Ok(packed_response_envelope)
}
pub async fn create_account(
&self,
their_vk: &VerKey,
our_vk: &VerKey,
did_doc: &AriesDidDoc,
) -> Result<(), String> {
self.persistence
.create_account(their_vk, our_vk, &json!(did_doc).to_string())
.await
.map_err(string_from_std_error)?;
Ok(())
}
}
#[cfg(test)]
mod test {
use aries_vcx::{
protocols::oob::oob_invitation_to_legacy_did_doc,
utils::encryption_envelope::EncryptionEnvelope,
};
use aries_vcx_wallet::wallet::askar::AskarWallet;
use log::info;
use serde_json::Value;
use test_utils::mockdata::mock_ledger::MockLedger;
use super::AgentBuilder;
#[tokio::test]
pub async fn test_pack_unpack() {
let message: Value = serde_json::from_str("{}").unwrap();
let message_bytes = serde_json::to_vec(&message).unwrap();
let mut agent = AgentBuilder::<AskarWallet>::new_demo_agent().await.unwrap();
agent
.init_service(
vec![],
"http://127.0.0.1:8005/aries".to_string().parse().unwrap(),
)
.await
.unwrap();
let mock_ledger = MockLedger {}; // not good. to be dealt later
let their_diddoc =
oob_invitation_to_legacy_did_doc(&mock_ledger, &agent.get_oob_invite().unwrap())
.await
.unwrap();
let our_service = agent.service.as_ref().unwrap();
let our_vk = our_service.recipient_keys.first().unwrap();
let EncryptionEnvelope(packed) = agent
.pack_didcomm(&message_bytes, our_vk, &their_diddoc)
.await
.unwrap();
let unpacked = agent.unpack_didcomm(&packed).await.unwrap();
info!("{unpacked:?}");
print!("{unpacked:?}");
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/aries_agent/client/transports.rs | aries/agents/mediator/src/aries_agent/client/transports.rs | use async_trait::async_trait;
use diddoc_legacy::aries::diddoc::AriesDidDoc;
use log::debug;
use serde_json::Value;
#[derive(thiserror::Error, Debug)]
#[error("{msg}")]
pub struct AriesTransportError {
pub msg: String,
}
impl AriesTransportError {
fn from_std_error(err: impl std::error::Error) -> Self {
AriesTransportError {
msg: err.to_string(),
}
}
}
#[async_trait]
pub trait AriesTransport {
/// Send envelope to destination (defined in AriesDidDoc) and return response
async fn send_aries_envelope(
&mut self,
envelope_json: Value,
destination: &AriesDidDoc,
) -> Result<Value, AriesTransportError>;
}
#[async_trait]
impl AriesTransport for reqwest::Client {
async fn send_aries_envelope(
&mut self,
envelope_json: Value,
destination: &AriesDidDoc,
) -> 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
.post(oob_invited_endpoint)
.json(&envelope_json)
.send()
.await
.map_err(AriesTransportError::from_std_error)?
.error_for_status()
.map_err(AriesTransportError::from_std_error)?;
let res_json: Value = res
.json()
.await
.map_err(AriesTransportError::from_std_error)?;
debug!("Received response envelope {res_json:?}");
Ok(res_json)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/aries_agent/client/mod.rs | aries/agents/mediator/src/aries_agent/client/mod.rs | use aries_vcx::{
handlers::util::AnyInvitation,
protocols::{
connection::invitee::{
states::{
completed::Completed, initial::Initial as ClientInit,
requested::Requested as ClientRequestSent,
},
InviteeConnection,
},
mediated_connection::pairwise_info::PairwiseInfo,
oob::oob_invitation_to_legacy_did_doc,
},
utils::encryption_envelope::EncryptionEnvelope,
};
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use messages::{
msg_fields::protocols::{
connection::{response::Response, Connection},
out_of_band::invitation::Invitation as OOBInvitation,
},
AriesMessage,
};
use test_utils::mockdata::mock_ledger::MockLedger;
use crate::persistence::MediatorPersistence;
pub mod transports;
use self::transports::AriesTransport;
use super::Agent;
use crate::utils::prelude::*;
// client role utilities
impl<T: BaseWallet, P: MediatorPersistence> Agent<T, P> {
/// Starting from a new connection object, tries to create connection request object for the
/// specified OOB invite endpoint
pub async fn gen_connection_request(
&self,
oob_invite: OOBInvitation,
) -> Result<(InviteeConnection<ClientRequestSent>, EncryptionEnvelope), String> {
// Generate keys
let did_data = self
.wallet
.create_and_store_my_did(None, None)
.await
.unwrap();
// Create fresh connection object and transform step wise to requested state
let mock_ledger = MockLedger {}; // not good. to be dealt later
let client_conn = InviteeConnection::<ClientInit>::new_invitee(
"foo".into(),
PairwiseInfo {
pw_did: did_data.did().into(),
pw_vk: did_data.verkey().base58(),
},
)
.accept_invitation(&mock_ledger, AnyInvitation::Oob(oob_invite.clone()))
.await
.unwrap();
let client_conn = client_conn
.prepare_request("didcomm:transport/queue".parse().unwrap(), vec![])
.await
.unwrap();
// Extract the actual connection request message to be sent
let msg_connection_request = client_conn.get_request().clone();
info!("Client Connection Request: {msg_connection_request:#?}");
let req_msg = client_conn.get_request();
debug!(
"Connection Request: {},",
serde_json::to_string_pretty(&req_msg).unwrap()
);
// encrypt/pack the connection request message
let EncryptionEnvelope(packed_aries_msg_bytes) = client_conn
.encrypt_message(
self.wallet.as_ref(),
&AriesMessage::Connection(Connection::Request(req_msg.clone())),
)
.await
.unwrap();
Ok((client_conn, EncryptionEnvelope(packed_aries_msg_bytes)))
}
pub async fn handle_connection_response(
&self,
state: InviteeConnection<ClientRequestSent>,
response: Response,
) -> Result<InviteeConnection<Completed>, String> {
state
.handle_response(self.wallet.as_ref(), response)
.await
.map_err(|err| err.to_string())
}
pub async fn save_completed_connection_as_contact(
&self,
state: &InviteeConnection<Completed>,
) -> Result<(), String> {
let their_vk = state.remote_vk().map_err(|e| e.to_string())?;
let our_vk = &state.pairwise_info().pw_vk;
self.create_account(&their_vk, our_vk, state.their_did_doc())
.await?;
Ok(())
}
pub async fn list_contacts(&self) -> Result<Vec<(String, String)>, String> {
self.persistence
.list_accounts()
.await
.map_err(string_from_std_error)
}
/// Workflow method to establish DidComm connection with Aries peer, given OOB invite.
pub async fn establish_connection(
&self,
oob_invite: OOBInvitation,
aries_transport: &mut impl AriesTransport,
) -> Result<InviteeConnection<Completed>, anyhow::Error> {
let (state, EncryptionEnvelope(packed_aries_msg_bytes)) = self
.gen_connection_request(oob_invite.clone())
.await
.map_err(|err| GenericStringError { msg: err })?;
let packed_aries_msg_json = serde_json::from_slice(&packed_aries_msg_bytes)?;
info!(
"Sending Connection Request Envelope: {},",
serde_json::to_string_pretty(&packed_aries_msg_json).unwrap()
);
let mock_ledger = MockLedger {}; // not good. to be dealt later
let legacy_did_doc = oob_invitation_to_legacy_did_doc(&mock_ledger, &oob_invite).await?;
let response_envelope = aries_transport
.send_aries_envelope(packed_aries_msg_json, &legacy_did_doc)
.await?;
info!(
"Received Response envelope {:#?}, unpacking",
serde_json::to_string_pretty(&response_envelope).unwrap()
);
let response_envelope_bytes = serde_json::to_vec(&response_envelope)?;
let response_unpacked = self
.unpack_didcomm(&response_envelope_bytes)
.await
.map_err(|err| GenericStringError { msg: err })?;
let response_message: AriesMessage = serde_json::from_str(&response_unpacked.message)?;
let AriesMessage::Connection(Connection::Response(connection_response)) = response_message
else {
return Err(GenericStringError {
msg: format!("Expected connection response, got {response_message:?}"),
}
.into());
};
let state = self
.handle_connection_response(state, connection_response)
.await
.map_err(|err| GenericStringError { msg: err })?;
info!(
"Completed Connection {:?}, saving as contact",
serde_json::to_value(&state).unwrap()
);
self.save_completed_connection_as_contact(&state)
.await
.map_err(|err| GenericStringError { msg: err })?;
Ok(state)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/didcomm_handlers/connection.rs | aries/agents/mediator/src/didcomm_handlers/connection.rs | use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use messages::msg_fields::protocols::connection::Connection;
use super::{unhandled_aries_message, utils::prelude::*, ArcAgent};
pub async fn handle_aries_connection<T: BaseWallet, P: MediatorPersistence>(
agent: ArcAgent<T, P>,
connection: Connection,
) -> Result<EncryptionEnvelope, String> {
match connection {
Connection::Invitation(_invite) => {
Err("Mediator does not handle random invites. Sorry.".to_owned())
}
Connection::Request(register_request) => {
agent.handle_connection_req(register_request).await
}
_ => Err(unhandled_aries_message(connection)),
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/didcomm_handlers/pickup.rs | aries/agents/mediator/src/didcomm_handlers/pickup.rs | use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use messages::msg_fields::protocols::pickup::Pickup;
use super::utils::prelude::*;
pub async fn handle_pickup_protocol(
agent: &ArcAgent<impl BaseWallet, impl MediatorPersistence>,
pickup_message: Pickup,
auth_pubkey: &str,
) -> Result<Pickup, String> {
let pickup_response = crate::mediation::pickup::handle_pickup_authenticated(
agent.get_persistence_ref(),
pickup_message,
auth_pubkey,
)
.await;
Ok(pickup_response)
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/didcomm_handlers/utils.rs | aries/agents/mediator/src/didcomm_handlers/utils.rs | pub mod prelude {
pub use aries_vcx::utils::encryption_envelope::EncryptionEnvelope;
pub use crate::{aries_agent::ArcAgent, persistence::MediatorPersistence, utils::prelude::*};
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/didcomm_handlers/mod.rs | aries/agents/mediator/src/didcomm_handlers/mod.rs | use std::fmt::Debug;
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use axum::{body::Bytes, extract::State, Json};
use messages::AriesMessage;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use utils::prelude::*;
mod connection;
mod forward;
mod mediator_coord;
mod pickup;
mod utils;
use connection::handle_aries_connection;
use forward::handle_routing_forward;
use mediator_coord::handle_mediation_coord;
use pickup::handle_pickup_protocol;
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
enum GeneralAriesMessage {
AriesVCXSupported(AriesMessage),
}
pub fn unhandled_aries_message(message: impl Debug) -> String {
format!("Don't know how to handle this message type {message:#?}")
}
pub async fn handle_aries<T: BaseWallet, P: MediatorPersistence>(
State(agent): State<ArcAgent<T, P>>,
didcomm_msg: Bytes,
) -> Result<Json<Value>, String> {
log::info!("processing message {:?}", &didcomm_msg);
let unpacked = agent.unpack_didcomm(&didcomm_msg).await.unwrap();
let aries_message: GeneralAriesMessage =
serde_json::from_str(&unpacked.message).map_err(|e| e.to_string())?;
let packed_response =
if let GeneralAriesMessage::AriesVCXSupported(AriesMessage::Connection(conn)) =
aries_message
{
handle_aries_connection(agent.clone(), conn).await?
} else if let GeneralAriesMessage::AriesVCXSupported(AriesMessage::Routing(forward)) =
aries_message
{
handle_routing_forward(agent.clone(), forward).await?;
return Ok(Json(json!({})));
} else {
// Authenticated flow: Auth known VerKey then process account related messages
let account_details = agent.auth_and_get_details(&unpacked.sender_verkey).await?;
log::info!("Processing message for {:?}", account_details.account_name);
let aries_response = match aries_message {
GeneralAriesMessage::AriesVCXSupported(AriesMessage::Pickup(pickup_message)) => {
let pickup_response = handle_pickup_protocol(
&agent,
pickup_message,
&account_details.auth_pubkey,
)
.await?;
AriesMessage::Pickup(pickup_response)
}
GeneralAriesMessage::AriesVCXSupported(AriesMessage::CoordinateMediation(
coord_message,
)) => {
let coord_response =
handle_mediation_coord(&agent, coord_message, &account_details.auth_pubkey)
.await?;
AriesMessage::CoordinateMediation(coord_response)
}
GeneralAriesMessage::AriesVCXSupported(aries_message) => {
Err(unhandled_aries_message(aries_message))?
}
};
let aries_response_bytes =
serde_json::to_vec(&aries_response).map_err(string_from_std_error)?;
agent
.pack_didcomm(
&aries_response_bytes,
&account_details.our_signing_key,
&account_details.their_did_doc,
)
.await?
};
let EncryptionEnvelope(packed_message_bytes) = packed_response;
let packed_json = serde_json::from_slice(&packed_message_bytes[..]).unwrap();
Ok(Json(packed_json))
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/didcomm_handlers/mediator_coord.rs | aries/agents/mediator/src/didcomm_handlers/mediator_coord.rs | use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use messages::msg_fields::protocols::coordinate_mediation::{
CoordinateMediation, MediateGrant, MediateGrantContent, MediateGrantDecorators,
};
use uuid::Uuid;
use super::utils::prelude::*;
pub async fn handle_mediation_coord(
agent: &ArcAgent<impl BaseWallet, impl MediatorPersistence>,
coord_msg: CoordinateMediation,
auth_pubkey: &str,
) -> Result<CoordinateMediation, String> {
if let CoordinateMediation::MediateRequest(_mediate_request) = coord_msg {
let service = agent
.get_service_ref()
.ok_or("Mediation agent must have service defined.")?;
let mut routing_keys = Vec::new();
routing_keys.extend_from_slice(&service.routing_keys);
routing_keys.push(
service
.recipient_keys
.first()
.expect("Service must have recipient key")
.to_owned(),
);
let mediate_grant_content = MediateGrantContent {
endpoint: service.service_endpoint.to_string(),
routing_keys,
};
let mediate_grant = MediateGrant::builder()
.content(mediate_grant_content)
.decorators(MediateGrantDecorators::default())
.id(Uuid::new_v4().to_string())
.build();
let coord_response = CoordinateMediation::MediateGrant(mediate_grant);
return Ok(coord_response);
};
let coord_response = crate::mediation::coordination::handle_coord_authenticated(
agent.get_persistence_ref(),
coord_msg,
auth_pubkey,
)
.await;
Ok(coord_response)
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/didcomm_handlers/forward.rs | aries/agents/mediator/src/didcomm_handlers/forward.rs | use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use messages::msg_fields::protocols::{notification::ack::Ack, routing::Forward};
use super::{utils::prelude::*, ArcAgent};
use crate::mediation::forward::handle_forward;
pub async fn handle_routing_forward(
agent: ArcAgent<impl BaseWallet, impl MediatorPersistence>,
forward: Forward,
) -> Result<Ack, String> {
info!("{forward:?}");
let ack = handle_forward(agent.get_persistence_ref(), forward).await;
Ok(ack)
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/utils/prelude.rs | aries/agents/mediator/src/utils/prelude.rs | pub use log::{debug, error, info};
// Generic Wrapper struct for newtype pattern
// for implementing external trait on external types
// pub struct Wrapper<T>(pub T);
// Generic Result
// pub type Result_<T> = Result<T, Box<dyn Error>>;
pub fn string_from_std_error(err: impl std::error::Error) -> String {
err.to_string()
}
#[derive(thiserror::Error, Debug)]
#[error("{msg}")]
pub struct GenericStringError {
pub msg: String,
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/utils/structs.rs | aries/agents/mediator/src/utils/structs.rs | pub type VerKey = String;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/utils/mod.rs | aries/agents/mediator/src/utils/mod.rs | pub use prelude::*;
pub mod binary_utils;
pub mod prelude;
pub mod structs;
///// Utility function for mapping any error into a `500 Internal Server Error`
///// response.
// fn internal_error<E>(err: E) -> (axum::http::StatusCode, String)
// where
// E: std::error::Error,
// {
// (axum::http::StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
// }
// impl From<AriesVcxCoreError> for String {}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/utils/binary_utils.rs | aries/agents/mediator/src/utils/binary_utils.rs | pub fn setup_logging() {
let env = env_logger::Env::default().default_filter_or("info");
env_logger::init_from_env(env);
}
pub fn load_dot_env() {
let _ = dotenvy::dotenv();
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/bin/mediator.rs | aries/agents/mediator/src/bin/mediator.rs | use aries_vcx_wallet::wallet::askar::{
askar_wallet_config::AskarWalletConfig, key_method::KeyMethod, AskarWallet,
};
use log::info;
use mediator::aries_agent::AgentBuilder;
use uuid::Uuid;
#[tokio::main]
async fn main() {
load_dot_env();
setup_logging();
info!("Starting up mediator! ⚙️⚙️");
let endpoint_root = std::env::var("ENDPOINT_ROOT").unwrap_or("127.0.0.1:8005".into());
info!("Mediator endpoint root address: {endpoint_root}");
// default wallet config for a dummy in-memory wallet
let default_wallet_config = AskarWalletConfig::new(
"sqlite://:memory:",
KeyMethod::Unprotected,
"",
&Uuid::new_v4().to_string(),
);
let wallet_config_json = std::env::var("INDY_WALLET_CONFIG");
let wallet_config = wallet_config_json
.ok()
.map_or(default_wallet_config, |json| {
serde_json::from_str(&json).unwrap()
});
info!("Wallet Config: {wallet_config:?}");
let mut agent = AgentBuilder::<AskarWallet>::new_from_wallet_config(wallet_config)
.await
.unwrap();
agent
.init_service(
vec![],
format!("http://{endpoint_root}/didcomm").parse().unwrap(),
)
.await
.unwrap();
let app_router = mediator::http_routes::build_router(agent).await;
info!("Starting server");
let listener = tokio::net::TcpListener::bind(&endpoint_root).await.unwrap();
axum::serve(listener, app_router.into_make_service())
.await
.unwrap();
}
fn setup_logging() {
let env = env_logger::Env::default().default_filter_or("info");
env_logger::init_from_env(env);
}
fn load_dot_env() {
let _ = dotenvy::dotenv();
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/persistence/errors.rs | aries/agents/mediator/src/persistence/errors.rs | use thiserror::Error;
#[derive(Error, Debug)]
#[error("No account found matching given input: {0}")]
pub struct AccountNotFound(pub String);
/// Error closely related to the storage backend
#[derive(Error, Debug)]
#[error(transparent)]
pub struct StorageBackendError {
#[from]
pub source: Box<dyn std::error::Error>,
}
/// Error parsing values from backend into expected structures
#[derive(Error, Debug)]
#[error("Couldn't retrieve or decode expected data: {0}")]
pub struct DecodeError(#[from] pub Box<dyn std::error::Error>);
/// Creates an error enum composed of individual error items given as list.
/// The enum variants are named identically to the error variants provided.
/// From<> impls (to the composition) and Display are automatically derived
/// with the help of thiserror.
/// Usage:
/// errorset!(ComposedError\[ErrorVariant1, ErrorVariant2\]);
macro_rules! error_compose {
($errorset_name:ident[$($error_name: ident),*]) => {
#[derive(Error, Debug)]
pub enum $errorset_name {
$(
#[error(transparent)]
$error_name(#[from] $error_name),
)*
/// Generic error variant - display, backtrace passed onto source anyhow::Error
/// Useful for chucking in errors from random sources. See usage of anyhow! macro.
#[error(transparent)]
ZFhOt01Rdb0Error(#[from] anyhow::Error),
}
};
}
// Manual declaration example
#[derive(Error, Debug)]
pub enum CreateAccountError {
#[error("Failed to create account in storage layer")]
StorageBackendError(#[from] StorageBackendError),
#[error(transparent)]
ZFhOt01Rdb0Error(#[from] anyhow::Error),
}
// Composed
error_compose!(GetAccountIdError[StorageBackendError, AccountNotFound]);
error_compose!(GetAccountDetailsError[StorageBackendError, AccountNotFound, DecodeError]);
error_compose!(ListAccountsError[StorageBackendError, DecodeError]);
error_compose!(AddRecipientError[StorageBackendError, AccountNotFound]);
// Expected to fail similarly
pub type RemoveRecipientError = AddRecipientError;
error_compose!(ListRecipientKeysError[StorageBackendError, AccountNotFound]);
error_compose!(PersistForwardMessageError[StorageBackendError, AccountNotFound]);
error_compose!(RetrievePendingMessageCountError[StorageBackendError, AccountNotFound]);
error_compose!(RetrievePendingMessagesError[StorageBackendError, AccountNotFound]);
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/persistence/mod.rs | aries/agents/mediator/src/persistence/mod.rs | // Copyright 2023 Naian G.
// SPDX-License-Identifier: Apache-2.0
pub mod database;
pub mod errors;
use async_trait::async_trait;
/// Database backend is used for default implementation of MediatorPersistence trait
pub use database::get_db_pool as get_persistence;
use diddoc_legacy::aries::diddoc::AriesDidDoc;
use self::errors::{
AddRecipientError, CreateAccountError, GetAccountDetailsError, GetAccountIdError,
ListAccountsError, ListRecipientKeysError, PersistForwardMessageError, RemoveRecipientError,
RetrievePendingMessageCountError, RetrievePendingMessagesError,
};
use crate::utils::structs::VerKey;
#[async_trait]
pub trait MediatorPersistence: Send + Sync + 'static {
async fn create_account(
&self,
auth_pubkey: &str,
our_signing_key: &str,
did_doc: &str,
) -> Result<(), CreateAccountError>;
async fn get_account_id(&self, auth_pubkey: &str) -> Result<Vec<u8>, GetAccountIdError>;
// async fn vaporize_account(&self, auth_pubkey: String);
async fn add_recipient(
&self,
auth_pubkey: &str,
recipient_key: &str,
) -> Result<(), AddRecipientError>;
async fn remove_recipient(
&self,
auth_pubkey: &str,
recipient_key: &str,
) -> Result<(), RemoveRecipientError>;
async fn list_recipient_keys(
&self,
auth_pubkey: &str,
) -> Result<Vec<String>, ListRecipientKeysError>;
async fn persist_forward_message(
&self,
recipient_key: &str,
message_data: &str,
) -> Result<(), PersistForwardMessageError>;
async fn retrieve_pending_message_count(
&self,
auth_pubkey: &str,
recipient_key: Option<&String>,
) -> Result<u32, RetrievePendingMessageCountError>;
async fn retrieve_pending_messages(
&self,
auth_pubkey: &str,
limit: u32,
recipient_key: Option<&String>,
) -> Result<Vec<(String, Vec<u8>)>, RetrievePendingMessagesError>;
// async fn mark_messages_received(&self, message_id: Vec<u32>);
/// Returns vector of (account_name, auth_pubkey)
async fn list_accounts(&self) -> Result<Vec<(String, String)>, ListAccountsError>;
/// Returns account details (sr.no, account_name, our_signing_key, did_doc)
async fn get_account_details(
&self,
auth_pubkey: &str,
) -> Result<AccountDetails, GetAccountDetailsError>;
}
#[derive(Debug)]
pub struct AccountDetails {
// Unique ID for account
pub account_id: Vec<u8>,
// A human readable string name for the account
// (not to be used for any other purpose)
pub account_name: String,
pub auth_pubkey: VerKey,
pub our_signing_key: VerKey,
pub their_did_doc: AriesDidDoc,
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/persistence/database/mod.rs | aries/agents/mediator/src/persistence/database/mod.rs | // Copyright 2023 Naian G.
// SPDX-License-Identifier: Apache-2.0
mod mysql;
pub use mysql::get_db_pool;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/persistence/database/mysql.rs | aries/agents/mediator/src/persistence/database/mysql.rs | // Copyright 2023 Naian G.
// SPDX-License-Identifier: Apache-2.0
use anyhow::anyhow;
use async_trait::async_trait;
use diddoc_legacy::aries::diddoc::AriesDidDoc;
use futures::TryStreamExt;
use log::info;
use sqlx::{
mysql::{MySqlPoolOptions, MySqlRow},
MySqlPool, Row,
};
use super::super::MediatorPersistence;
use crate::{
persistence::{
errors::{
AccountNotFound, AddRecipientError, CreateAccountError, DecodeError,
GetAccountDetailsError, GetAccountIdError, ListAccountsError, ListRecipientKeysError,
PersistForwardMessageError, RemoveRecipientError, RetrievePendingMessageCountError,
RetrievePendingMessagesError, StorageBackendError,
},
AccountDetails,
},
utils::structs::VerKey,
};
pub async fn get_db_pool() -> MySqlPool {
let _ = dotenvy::dotenv();
let database_url = std::env::var("MYSQL_URL")
.expect("Required environment variable MYSQL_URL on command line or in .env!");
MySqlPoolOptions::new()
.connect(&database_url)
.await
.expect("Failed to connect to database!")
}
/// MediatorPersistence trait implementation for MySql Database
#[async_trait]
impl MediatorPersistence for sqlx::MySqlPool {
async fn create_account(
&self,
auth_pubkey: &str,
our_signing_key: &str,
did_doc: &str,
) -> Result<(), CreateAccountError> {
info!(
"Adding new account to database with auth_pubkey {:#?}",
&auth_pubkey
);
let insert_result = sqlx::query(
"INSERT INTO accounts (auth_pubkey, our_signing_key, did_doc) VALUES (?, ?, ?);",
)
.bind(auth_pubkey)
.bind(our_signing_key)
.bind(did_doc)
.execute(self)
.await;
if let Err(err) = insert_result {
info!("Error during creating new account, {err:#?}");
return Err(StorageBackendError {
source: Box::new(err),
}
.into());
};
let account_details = self.get_account_details(auth_pubkey).await.map_err(|e| {
anyhow!(e.to_string())
.context("Possibly created account, but failed to retrieve created account's ID")
})?;
info!(
"Created account {:?} for auth_pubkey {:#?}",
&account_details, &auth_pubkey
);
Ok(())
}
/// Get account id associated with auth_pubkey
async fn get_account_id(&self, auth_pubkey: &str) -> Result<Vec<u8>, GetAccountIdError> {
let account_id: Vec<u8> =
sqlx::query("SELECT (account_id) FROM accounts WHERE auth_pubkey = ?;")
.bind(auth_pubkey)
.fetch_one(self)
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => GetAccountIdError::AccountNotFound(
AccountNotFound(format!("auth_pubkey={}", auth_pubkey.to_owned())),
),
_ => StorageBackendError { source: e.into() }.into(),
})?
.get("account_id");
Ok(account_id)
}
/// Returns list of accounts in form of tuples containing
/// account_name and associated auth_pubkey
async fn list_accounts(&self) -> Result<Vec<(String, VerKey)>, ListAccountsError> {
let accounts_rows: Vec<MySqlRow> =
sqlx::query("SELECT account_name, auth_pubkey FROM accounts;")
.fetch_all(self)
.await
.map_err(|e| StorageBackendError { source: e.into() })?;
let mut vec_tup = vec![];
for row in accounts_rows {
vec_tup.push((
row.try_get("account_name")
.map_err(|e| DecodeError(e.into()))?,
row.try_get("auth_pubkey")
.map_err(|e| DecodeError(e.into()))?,
))
}
Ok(vec_tup)
}
async fn get_account_details(
&self,
auth_pubkey: &str,
) -> Result<AccountDetails, GetAccountDetailsError> {
let row = sqlx::query("SELECT * FROM accounts WHERE auth_pubkey = ?;")
.bind(auth_pubkey)
.fetch_one(self)
.await
.map_err(|e| match e {
sqlx::error::Error::RowNotFound => GetAccountDetailsError::AccountNotFound(
AccountNotFound(format!("auth_pubkey={}", auth_pubkey.to_owned())),
),
_ => StorageBackendError { source: e.into() }.into(),
})?;
let account_id = row
.try_get("account_id")
.map_err(|e| DecodeError(e.into()))?;
let account_name = row
.try_get("account_name")
.map_err(|e| DecodeError(e.into()))?;
let auth_pubkey = row
.try_get("auth_pubkey")
.map_err(|e| DecodeError(e.into()))?;
let our_signing_key = row
.try_get("our_signing_key")
.map_err(|e| DecodeError(e.into()))?;
let did_doc_json = row
.try_get::<serde_json::Value, &str>("did_doc")
.map_err(|e| DecodeError(e.into()))?;
let account_details = AccountDetails {
account_id,
account_name,
auth_pubkey,
our_signing_key,
their_did_doc: serde_json::from_value::<AriesDidDoc>(did_doc_json)
.map_err(|e| DecodeError(e.into()))?,
};
Ok(account_details)
}
// async fn vaporize_account(&self, auth_pubkey: String) {
// let account: Vec<u8> = self.get_account(auth_pubkey).await?;
// let mut recipient_rows = sqlx::query(
// "SELECT * FROM recipients WHERE account = ?;"
// )
// .bind(&account)
// .fetch(self);
// while let Some(recipient_row) = recipient_rows.try_next().await.unwrap() {
// // map the row into a user-defined domain type
// let recipient: Vec<u8> = recipient_row.get("recipient"); // binary decode
// info!("Recipient {:x?}", recipient);
// sqlx::query("DROP (*) FROM messages WHERE recipient = ?;")
// .bind(&recipient)
// .execute(self)
// .await
// .unwrap();
// sqlx::query("DROP (*) FROM recipients WHERE recipient = ?;")
// .bind(&recipient)
// .execute(self)
// .await
// .unwrap();
// }
// }
async fn persist_forward_message(
&self,
recipient_key: &str,
message_data: &str,
) -> Result<(), PersistForwardMessageError> {
// Fetch recipient with given recipient_key
info!("Fetching recipient with recipient_key {recipient_key:#?}");
let recipient_row = sqlx::query("SELECT * FROM recipients WHERE recipient_key = ?")
.bind(recipient_key)
.fetch_one(self)
.await;
if let Err(err) = recipient_row {
info!("Error while finding target recipient, {err:#}");
let mapped_err = match err {
sqlx::Error::RowNotFound => PersistForwardMessageError::AccountNotFound(
AccountNotFound(format!("reipient_key={}", recipient_key.to_owned())),
),
_ => StorageBackendError { source: err.into() }.into(),
};
return Err(mapped_err);
}
let account_id: Vec<u8> = recipient_row.unwrap().get("account_id");
// Save message for recipient
info!("Persisting message for account {account_id:x?}");
let insert_result = sqlx::query(
"INSERT INTO messages (account_id, recipient_key, message_data) VALUES (?, ?, ?)",
)
.bind(&account_id)
.bind(recipient_key)
.bind(message_data)
.execute(self)
.await;
if let Err(err) = insert_result {
info!("Error while saving message for recipient {recipient_key:x?}, {err:#}");
return Err(PersistForwardMessageError::StorageBackendError(
StorageBackendError { source: err.into() },
));
}
Ok(())
}
async fn retrieve_pending_message_count(
&self,
auth_pubkey: &str,
recipient_key: Option<&String>,
) -> Result<u32, RetrievePendingMessageCountError> {
let account_id: Vec<u8> = self
.get_account_id(auth_pubkey)
.await
.map_err(|e| match e {
GetAccountIdError::AccountNotFound(anf) => anf.into(),
GetAccountIdError::StorageBackendError(s) => s.into(),
GetAccountIdError::ZFhOt01Rdb0Error(anye) => {
RetrievePendingMessageCountError::ZFhOt01Rdb0Error(
anye.context(format!("Couldn't get account id of pubkey {auth_pubkey}")),
)
}
})?;
let message_count_result = if let Some(recipient_key) = recipient_key {
sqlx::query(
"SELECT COUNT(*) FROM messages
WHERE (account_id = ?) AND (recipient_key = ?)",
)
.bind(&account_id)
.bind(recipient_key)
.fetch_one(self)
.await
} else {
sqlx::query(
"SELECT COUNT(*) FROM messages
WHERE (account_id = ?)",
)
.bind(&account_id)
.fetch_one(self)
.await
};
// MySQL BIGINT can be converted to i32 only, not u32
let message_count: i32 = message_count_result
.map_err(|e| anyhow!(e))?
.get::<i32, &str>("COUNT(*)");
let message_count: u32 = message_count.try_into().unwrap();
info!(
"Total message count of all requested recipients: {:#?}",
&message_count
);
Ok(message_count)
}
async fn retrieve_pending_messages(
&self,
auth_pubkey: &str,
limit: u32,
recipient_key: Option<&VerKey>,
) -> Result<Vec<(String, Vec<u8>)>, RetrievePendingMessagesError> {
info!(
"Processing retrieve for messages to recipient_key {recipient_key:#?} of auth_pubkey {auth_pubkey:#?}"
);
let account_id: Vec<u8> = self
.get_account_id(auth_pubkey)
.await
.map_err(|e| match e {
GetAccountIdError::AccountNotFound(anf) => anf.into(),
GetAccountIdError::StorageBackendError(s) => s.into(),
GetAccountIdError::ZFhOt01Rdb0Error(anye) => {
RetrievePendingMessagesError::ZFhOt01Rdb0Error(
anye.context(format!("Couldn't get account id of pubkey {auth_pubkey}")),
)
}
})?;
let mut messages: Vec<(String, Vec<u8>)> = Vec::new();
let mut message_rows = if let Some(recipient_key) = recipient_key {
sqlx::query("SELECT * FROM messages WHERE (account_id = ?) AND (recipient_key = ?)")
.bind(&account_id)
.bind(recipient_key)
.fetch(self)
} else {
sqlx::query("SELECT * FROM messages WHERE (account_id = ?)")
.bind(&account_id)
.fetch(self)
};
while let Some(message_row) = message_rows.try_next().await.unwrap() {
let id: String = message_row.get("message_id");
let msg: Vec<u8> = message_row.get("message_data");
// debug!("id {:#?}", id);
// debug!("recipient {:x?}", recipient);
// debug!("message {:x?}", msg);
messages.push((id, msg));
if u32::try_from(messages.len()).map_err(|e| anyhow!(e))? >= limit {
info!("Found enough messages {limit:#?}");
break;
}
}
info!(
"Found total of {:#?} messages, returning them",
messages.len()
);
Ok(messages)
}
async fn add_recipient(
&self,
auth_pubkey: &str,
recipient_key: &str,
) -> Result<(), AddRecipientError> {
info!("Adding recipient_key to account with auth_pubkey {auth_pubkey:#?}");
let account_id: Vec<u8> = self
.get_account_id(auth_pubkey)
.await
.map_err(|e| match e {
GetAccountIdError::AccountNotFound(anf) => anf.into(),
GetAccountIdError::StorageBackendError(s) => s.into(),
GetAccountIdError::ZFhOt01Rdb0Error(anye) => AddRecipientError::ZFhOt01Rdb0Error(
anye.context(format!("Couldn't get account id of pubkey {auth_pubkey}")),
),
})?;
info!(
"Found matching account {account_id:x?}. Proceeding with attempt to add recipient recipient_key \
{recipient_key:#?} "
);
sqlx::query("INSERT INTO recipients (account_id, recipient_key) VALUES (?, ?);")
.bind(&account_id)
.bind(recipient_key)
.execute(self)
.await
.map_err(|e| {
anyhow!(e).context("Error while inserting recipient entry into the database")
})?;
Ok(())
}
async fn remove_recipient(
&self,
auth_pubkey: &str,
recipient_key: &str,
) -> Result<(), RemoveRecipientError> {
info!("Removing recipient_key from account with auth_pubkey {auth_pubkey:#?}");
let account_id: Vec<u8> = self
.get_account_id(auth_pubkey)
.await
.map_err(|e| match e {
GetAccountIdError::AccountNotFound(anf) => anf.into(),
GetAccountIdError::StorageBackendError(s) => s.into(),
GetAccountIdError::ZFhOt01Rdb0Error(anye) => {
RemoveRecipientError::ZFhOt01Rdb0Error(
anye.context(format!("Couldn't get account id of pubkey {auth_pubkey}")),
)
}
})?;
info!(
"Found matching account {account_id:x?}. Proceeding with attempt to remove recipient \
recipient_key {recipient_key:#?} "
);
sqlx::query("DELETE FROM recipients WHERE (account_id = ?) AND (recipient_key = ?);")
.bind(&account_id)
.bind(recipient_key)
.execute(self)
.await
.map_err(|e| {
anyhow!(e).context("Error while deleting recipient entry from the database")
})?;
Ok(())
}
async fn list_recipient_keys(
&self,
auth_pubkey: &str,
) -> Result<Vec<VerKey>, ListRecipientKeysError> {
info!("Retrieving recipient_keys for account with auth_pubkey {auth_pubkey:#?}");
let account_id: Vec<u8> = self
.get_account_id(auth_pubkey)
.await
.map_err(|e| match e {
GetAccountIdError::AccountNotFound(anf) => anf.into(),
GetAccountIdError::StorageBackendError(s) => s.into(),
GetAccountIdError::ZFhOt01Rdb0Error(anye) => {
ListRecipientKeysError::ZFhOt01Rdb0Error(
anye.context(format!("Couldn't get account id of pubkey {auth_pubkey}")),
)
}
})?;
let recipient_keys: Vec<VerKey> =
sqlx::query("SELECT (recipient_key) FROM recipients WHERE account_id = ?;")
.bind(&account_id)
.fetch_all(self)
.await
.map_err(|e| {
anyhow!(e).context("Error while fetching recipient_keys from database")
})?
.into_iter()
.map(|row| row.get("recipient_key"))
.collect();
Ok(recipient_keys)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/mediation/pickup.rs | aries/agents/mediator/src/mediation/pickup.rs | // Copyright 2023 Naian G.
// SPDX-License-Identifier: Apache-2.0
use std::sync::Arc;
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use log::info;
use messages::{
decorators::attachment::{Attachment, AttachmentData, AttachmentType},
msg_fields::protocols::pickup::{
Delivery, DeliveryContent, DeliveryRequestContent, Pickup, Status, StatusContent,
StatusDecorators, StatusRequestContent,
},
};
use uuid::Uuid;
use crate::persistence::MediatorPersistence;
pub async fn handle_pickup_authenticated<T: MediatorPersistence>(
storage: Arc<T>,
pickup_message: Pickup,
auth_pubkey: &str,
) -> Pickup {
match &pickup_message {
Pickup::StatusRequest(status_request) => {
handle_pickup_status_req(&status_request.content, storage, auth_pubkey).await
}
// Why is client sending us status? That's server's job.
Pickup::Status(_status) =>
// StatusCode::BAD_REQUEST,
{
handle_pickup_default_status(storage, auth_pubkey).await
}
Pickup::DeliveryRequest(delivery_request) => {
handle_pickup_delivery_req(&delivery_request.content, storage, auth_pubkey).await
}
_ => {
info!("Received {:#?}", &pickup_message);
// StatusCode::NOT_IMPLEMENTED,
handle_pickup_default_status(storage, auth_pubkey).await
}
}
}
async fn handle_pickup_status_req<T: MediatorPersistence>(
status_request: &StatusRequestContent,
storage: Arc<T>,
auth_pubkey: &str,
) -> Pickup {
info!("Received {:#?}", &status_request);
let message_count = storage
.retrieve_pending_message_count(auth_pubkey, status_request.recipient_key.as_ref())
.await
.unwrap();
let status_content = if let Some(recipient_key) = status_request.recipient_key.clone() {
StatusContent::builder()
.message_count(message_count)
.recipient_key(recipient_key)
.build()
} else {
StatusContent::builder()
.message_count(message_count)
.build()
};
let status = Status::builder()
.content(status_content)
.decorators(StatusDecorators::default())
.id(Uuid::new_v4().to_string())
.build();
info!("Sending {:#?}", &status);
Pickup::Status(status)
}
async fn handle_pickup_delivery_req<T: MediatorPersistence>(
delivery_request: &DeliveryRequestContent,
storage: Arc<T>,
auth_pubkey: &str,
) -> Pickup {
info!("Received {:#?}", &delivery_request);
let messages = storage
.retrieve_pending_messages(
auth_pubkey,
delivery_request.limit,
delivery_request.recipient_key.as_ref(),
)
.await
.unwrap();
// for (message_id, message_content) in messages.into_iter() {
// info!("Message {:#?} {:#?}", message_id, String::from_utf8(message_content).unwrap())
// }
let attach: Vec<Attachment> = messages
.into_iter()
.map(|(message_id, message_content)| {
Attachment::builder()
.id(message_id)
.data(
AttachmentData::builder()
.content(AttachmentType::Base64(
URL_SAFE_NO_PAD.encode(&message_content),
))
.build(),
)
.build()
})
.collect();
if !attach.is_empty() {
Pickup::Delivery(
Delivery::builder()
.content(DeliveryContent {
recipient_key: delivery_request.recipient_key.to_owned(),
attach,
})
.id(Uuid::new_v4().to_string())
.build(),
)
} else {
// send default status message instead
handle_pickup_default_status(storage, auth_pubkey).await
}
}
// Returns global status message for user (not restricted to recipient key)
// async fn handle_pickup_default<T: MediatorPersistence>(
// storage: Arc<T>,
// ) -> Json<PickupMsgEnum> {
// let message_count = storage
// .retrieve_pending_message_count(None)
// .await;
// let status = PickupStatusMsg {
// message_count,
// recipient_key: None
// };
// info!("Sending {:#?}", &status);
// Json(PickupMsgEnum::PickupStatusMsg(status))
// }
/// Return status by default
async fn handle_pickup_default_status(
storage: Arc<impl MediatorPersistence>,
auth_pubkey: &str,
) -> Pickup {
info!("Default behavior: responding with status");
let status_request = StatusRequestContent::builder().build();
handle_pickup_status_req(&status_request, storage, auth_pubkey).await
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/mediation/mod.rs | aries/agents/mediator/src/mediation/mod.rs | pub mod coordination;
pub mod forward;
pub mod pickup;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/mediation/coordination.rs | aries/agents/mediator/src/mediation/coordination.rs | // Copyright 2023 Naian G.
// SPDX-License-Identifier: Apache-2.0
use std::sync::Arc;
use messages::msg_fields::protocols::coordinate_mediation::{
keylist::KeylistItem,
keylist_update::{KeylistUpdateItem, KeylistUpdateItemAction},
keylist_update_response::{KeylistUpdateItemResult, KeylistUpdateResponseItem},
CoordinateMediation, Keylist, KeylistContent, KeylistDecorators, KeylistQueryContent,
KeylistUpdateContent, KeylistUpdateResponse, KeylistUpdateResponseContent,
KeylistUpdateResponseDecorators, MediateDeny, MediateDenyContent, MediateDenyDecorators,
MediateGrant, MediateGrantContent, MediateGrantDecorators,
};
use uuid::Uuid;
use crate::persistence::MediatorPersistence;
pub async fn handle_coord_authenticated(
storage: Arc<impl MediatorPersistence>,
message: CoordinateMediation,
auth_pubkey: &str,
) -> CoordinateMediation {
match message {
CoordinateMediation::MediateRequest(_mediate_request) => {
panic!(
"Use handle_mediate_request directly. This handler is for preregistered clients."
);
}
CoordinateMediation::KeylistUpdate(keylist_update) => {
handle_keylist_update(storage, keylist_update.content, auth_pubkey).await
}
CoordinateMediation::KeylistQuery(keylist_query) => {
handle_keylist_query(storage, keylist_query.content, auth_pubkey).await
}
_ => handle_unimplemented().await,
}
}
pub async fn handle_unimplemented() -> CoordinateMediation {
todo!("This error should ideally be handled on outer layer. Panicking for now.")
}
pub async fn handle_mediate_request<T: MediatorPersistence>(
storage: Arc<T>,
auth_pubkey: &str,
did_doc: &str,
our_signing_key: &str,
grant_content: MediateGrantContent,
) -> CoordinateMediation {
match storage
.create_account(auth_pubkey, our_signing_key, did_doc)
.await
{
Ok(()) => {
let mediate_grant_msg = MediateGrant::builder()
.content(grant_content)
.decorators(MediateGrantDecorators::default())
.id(Uuid::new_v4().to_string())
.build();
CoordinateMediation::MediateGrant(mediate_grant_msg)
}
Err(_msg) => {
let mediate_deny_msg = MediateDeny::builder()
.content(MediateDenyContent::default())
.decorators(MediateDenyDecorators::default())
.id(Uuid::new_v4().to_string())
.build();
CoordinateMediation::MediateDeny(mediate_deny_msg)
}
}
}
pub async fn handle_keylist_query<T: MediatorPersistence>(
storage: Arc<T>,
//todo: use the limits mentioned in the KeylistQueryData to modify response
_keylist_query_data: KeylistQueryContent,
auth_pubkey: &str,
) -> CoordinateMediation {
let keylist_items: Vec<KeylistItem> = match storage.list_recipient_keys(auth_pubkey).await {
Ok(recipient_keys) => recipient_keys
.into_iter()
.map(|recipient_key| KeylistItem { recipient_key })
.collect(),
Err(err) => todo!(
"This error should ideally be handled on outer layer. Panicking for now{}",
err
),
};
let keylist = Keylist::builder()
.content(KeylistContent {
keys: keylist_items,
pagination: None,
})
.decorators(KeylistDecorators::default())
.id(Uuid::new_v4().to_string())
.build();
CoordinateMediation::Keylist(keylist)
}
pub async fn handle_keylist_update<T: MediatorPersistence>(
storage: Arc<T>,
keylist_update_data: KeylistUpdateContent,
auth_pubkey: &str,
) -> CoordinateMediation {
let updates: Vec<KeylistUpdateItem> = keylist_update_data.updates;
let mut updated: Vec<KeylistUpdateResponseItem> = Vec::new();
for update_item in updates.into_iter() {
let result = match &update_item.action {
KeylistUpdateItemAction::Add => {
storage
.add_recipient(auth_pubkey, &update_item.recipient_key)
.await
}
KeylistUpdateItemAction::Remove => {
storage
.remove_recipient(auth_pubkey, &update_item.recipient_key)
.await
}
};
let update_item_result = match result {
Ok(()) => KeylistUpdateItemResult::Success,
Err(_msg) => KeylistUpdateItemResult::ServerError,
};
updated.push(KeylistUpdateResponseItem {
recipient_key: update_item.recipient_key,
action: update_item.action,
result: update_item_result,
});
}
let keylist_update_response = KeylistUpdateResponse::builder()
.content(KeylistUpdateResponseContent { updated })
.decorators(KeylistUpdateResponseDecorators::default())
.id(Uuid::new_v4().to_string())
.build();
CoordinateMediation::KeylistUpdateResponse(keylist_update_response)
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/src/mediation/forward.rs | aries/agents/mediator/src/mediation/forward.rs | // Copyright 2023 Naian G.
// SPDX-License-Identifier: Apache-2.0
use std::sync::Arc;
use log::{debug, info};
use messages::{
decorators::thread::Thread,
msg_fields::protocols::{
notification::ack::{Ack, AckContent, AckDecorators, AckStatus},
routing::Forward,
},
};
use uuid::Uuid;
use crate::persistence::MediatorPersistence;
pub async fn handle_forward<T>(storage: Arc<T>, forward_msg: Forward) -> Ack
where
T: MediatorPersistence,
{
info!("Persisting forward message");
debug!("{forward_msg:#?}");
let _ack_status = match storage
.persist_forward_message(
&forward_msg.content.to,
&serde_json::to_string(&forward_msg.content.msg).unwrap(),
)
.await
{
Ok(_) => {
info!("Persisted forward");
AckStatus::Ok
}
Err(e) => {
info!("Error when persisting forward: {e}");
AckStatus::Pending
}
};
let ack_content = AckContent::builder().status(AckStatus::Ok).build();
let ack_deco = AckDecorators::builder()
.thread(Thread::builder().thid(forward_msg.id).build())
.build();
Ack::builder()
.content(ack_content)
.decorators(ack_deco)
.id(Uuid::new_v4().to_string())
.build()
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/tests/mediator-readme.rs | aries/agents/mediator/tests/mediator-readme.rs | mod common;
use anyhow::Result;
use log::info;
use mediator::http_routes::ReadmeInfo;
use reqwest::header::ACCEPT;
use url::Url;
use crate::common::test_setup::setup_env_logging;
static LOGGING_INIT: std::sync::Once = std::sync::Once::new();
const ENDPOINT_ROOT: &str = "http://localhost:8005";
#[tokio::test]
async fn base_path_returns_readme() -> Result<()> {
LOGGING_INIT.call_once(setup_env_logging);
let client = reqwest::Client::new();
let endpoint: Url = ENDPOINT_ROOT.parse().unwrap();
let res = client
.get(endpoint)
.header(ACCEPT, "application/json")
.send()
.await?
.error_for_status()?;
info!("{res:?}");
let _: ReadmeInfo = res.json().await?;
Ok(())
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/tests/mediator-oob-invitation.rs | aries/agents/mediator/tests/mediator-oob-invitation.rs | mod common;
use anyhow::Result;
use messages::msg_fields::protocols::out_of_band::invitation::Invitation as OOBInvitation;
use url::Url;
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";
#[tokio::test]
async fn endpoint_invitation_returns_oob() -> Result<()> {
LOGGING_INIT.call_once(setup_env_logging);
let client = reqwest::Client::new();
let base: Url = ENDPOINT_ROOT.parse().unwrap();
let endpoint_register_json = base.join("/invitation").unwrap();
let res = client
.get(endpoint_register_json)
.send()
.await?
.error_for_status()?;
info!("{res:?}");
let _oob: OOBInvitation = res.json().await?;
Ok(())
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/tests/mediator-routing-forward.rs | aries/agents/mediator/tests/mediator-routing-forward.rs | mod common;
use aries_vcx::utils::encryption_envelope::EncryptionEnvelope;
use mediator::aries_agent::client::transports::AriesTransport;
use messages::msg_fields::protocols::basic_message::{
BasicMessage, BasicMessageContent, BasicMessageDecorators,
};
use crate::common::{
agent_and_transport_utils::{
gen_and_register_recipient_key, gen_mediator_connected_agent, get_mediator_grant_data,
},
prelude::*,
test_setup::setup_env_logging,
};
static LOGGING_INIT: std::sync::Once = std::sync::Once::new();
#[tokio::test]
async fn test_forward_flow() -> Result<()> {
LOGGING_INIT.call_once(setup_env_logging);
// prepare receiver connection parameters
let (mut agent, mut agent_aries_transport, agent_verkey, mediator_diddoc) =
gen_mediator_connected_agent().await?;
// setup receiver routing
let grant_data = get_mediator_grant_data(
&agent,
&mut agent_aries_transport,
&agent_verkey,
&mediator_diddoc,
)
.await;
agent
.init_service(grant_data.routing_keys, grant_data.endpoint.parse()?)
.await?;
// register recipient key with mediator
let (_agent_recipient_key, agent_diddoc) = gen_and_register_recipient_key(
&mut agent,
&mut agent_aries_transport,
&agent_verkey,
&mediator_diddoc,
)
.await?;
// Prepare forwarding agent transport
let mut agent_f_aries_transport = reqwest::Client::new();
// Prepare message and wrap into anoncrypt forward message
let message: BasicMessage = BasicMessage::builder()
.content(
BasicMessageContent::builder()
.content("Hi, for AgentF".to_string())
.sent_time(chrono::DateTime::default())
.build(),
)
.decorators(BasicMessageDecorators::default())
.id("JustHello".to_string())
.build();
info!(
"Prepared message {:?}, proceeding to anoncrypt wrap",
serde_json::to_string(&message).unwrap()
);
let EncryptionEnvelope(packed_message) = EncryptionEnvelope::create_from_legacy(
agent.get_wallet_ref().as_ref(),
&serde_json::to_vec(&message)?,
None,
&agent_diddoc,
)
.await?;
// Send forward message to provided endpoint
let packed_json = serde_json::from_slice(&packed_message)?;
let response = agent_f_aries_transport
.send_aries_envelope(packed_json, &agent_diddoc)
.await?;
info!("Response of forward{response:?}");
Ok(())
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/tests/mediator-aries-connection.rs | aries/agents/mediator/tests/mediator-aries-connection.rs | mod common;
use aries_vcx_wallet::wallet::askar::AskarWallet;
use messages::msg_fields::protocols::out_of_band::invitation::Invitation as OOBInvitation;
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";
#[tokio::test]
async fn didcomm_connection_succeeds() -> Result<()> {
LOGGING_INIT.call_once(setup_env_logging);
let client = reqwest::Client::new();
let base: Url = ENDPOINT_ROOT.parse().unwrap();
let endpoint_invitation = base.join("invitation").unwrap();
let oobi: OOBInvitation = client
.get(endpoint_invitation)
.send()
.await?
.error_for_status()?
.json()
.await?;
info!(
"Got invitation {}",
serde_json::to_string_pretty(&oobi.clone()).unwrap()
);
let agent = mediator::aries_agent::AgentBuilder::<AskarWallet>::new_demo_agent().await?;
let mut aries_transport = reqwest::Client::new();
let _state = agent
.establish_connection(oobi, &mut aries_transport)
.await?;
Ok(())
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/tests/mediator-coord-protocol.rs | aries/agents/mediator/tests/mediator-coord-protocol.rs | mod common;
use aries_vcx_wallet::wallet::base_wallet::did_wallet::DidWallet;
use messages::{
msg_fields::protocols::coordinate_mediation::{
keylist_update::{KeylistUpdateItem, KeylistUpdateItemAction},
CoordinateMediation, KeylistQuery, KeylistQueryContent, KeylistUpdate,
KeylistUpdateContent, MediateRequest, MediateRequestContent,
},
AriesMessage,
};
use crate::common::{
agent_and_transport_utils::{
gen_mediator_connected_agent, send_message_and_pop_response_message,
},
prelude::*,
test_setup::setup_env_logging,
};
static LOGGING_INIT: std::sync::Once = std::sync::Once::new();
#[tokio::test]
async fn test_mediate_grant() -> Result<()> {
LOGGING_INIT.call_once(setup_env_logging);
// prepare connection parameters
let (agent, mut aries_transport, our_verkey, their_diddoc) =
gen_mediator_connected_agent().await?;
// prepare request message
let mediate_request = CoordinateMediation::MediateRequest(
MediateRequest::builder()
.content(MediateRequestContent::default())
.id("mediate-request-test".to_owned())
.build(),
);
let message_bytes = serde_json::to_vec(&AriesMessage::CoordinateMediation(mediate_request))?;
// send message and get response
let response_message = send_message_and_pop_response_message(
&message_bytes,
&agent,
&mut aries_transport,
&our_verkey,
&their_diddoc,
)
.await?;
// verify response
if let AriesMessage::CoordinateMediation(CoordinateMediation::MediateGrant(grant_data)) =
serde_json::from_str(&response_message).unwrap()
{
info!("Grant Data {grant_data:?}");
} else if let AriesMessage::CoordinateMediation(CoordinateMediation::MediateDeny(deny_data)) =
serde_json::from_str(&response_message).unwrap()
{
info!("Deny Data {deny_data:?}");
} else {
panic!(
"Should get response that is of type Mediator Grant / Deny. Found {response_message:?}"
)
};
Ok(())
}
#[tokio::test]
async fn test_mediate_keylist_update_add() -> Result<()> {
LOGGING_INIT.call_once(setup_env_logging);
// prepare connection parameters
let (agent, mut aries_transport, our_verkey, their_diddoc) =
gen_mediator_connected_agent().await?;
// prepare request message
let did_data = agent
.get_wallet_ref()
.create_and_store_my_did(None, None)
.await?;
let keylist_update_request = KeylistUpdate::builder()
.content(KeylistUpdateContent {
updates: vec![KeylistUpdateItem {
recipient_key: did_data.verkey().base58(),
action: KeylistUpdateItemAction::Add,
}],
})
.id("key-add".to_owned())
.build();
let message = AriesMessage::CoordinateMediation(CoordinateMediation::KeylistUpdate(
keylist_update_request,
));
info!("Sending {:?}", serde_json::to_string(&message).unwrap());
let message_bytes = serde_json::to_vec(&message)?;
// send message and get response
let response_message = send_message_and_pop_response_message(
&message_bytes,
&agent,
&mut aries_transport,
&our_verkey,
&their_diddoc,
)
.await?;
// verify response
if let AriesMessage::CoordinateMediation(CoordinateMediation::KeylistUpdateResponse(
update_response_data,
)) = serde_json::from_str(&response_message)?
{
info!("Received update response {update_response_data:?}");
} else {
panic!("Expected message of type KeylistUpdateResponse. Found {response_message:?}")
}
Ok(())
}
#[tokio::test]
async fn test_mediate_keylist_query() -> Result<()> {
LOGGING_INIT.call_once(setup_env_logging);
// prepare connection parameters
let (agent, mut aries_transport, our_verkey, their_diddoc) =
gen_mediator_connected_agent().await?;
// prepare request message: add key
let did_data = agent
.get_wallet_ref()
.create_and_store_my_did(None, None)
.await?;
let keylist_update_request = KeylistUpdate::builder()
.content(KeylistUpdateContent {
updates: vec![KeylistUpdateItem {
recipient_key: did_data.verkey().base58(),
action: KeylistUpdateItemAction::Add,
}],
})
.id("key-add".to_owned())
.build();
let message = AriesMessage::CoordinateMediation(CoordinateMediation::KeylistUpdate(
keylist_update_request,
));
let message_bytes = serde_json::to_vec(&message)?;
// send message and get response
let _ = send_message_and_pop_response_message(
&message_bytes,
&agent,
&mut aries_transport,
&our_verkey,
&their_diddoc,
)
.await?;
info!("Proceeding to keylist query");
//prepare request message: list keys
let keylist_query = KeylistQuery::builder()
.content(KeylistQueryContent::default())
.id("keylist-query".to_owned())
.build();
let message =
AriesMessage::CoordinateMediation(CoordinateMediation::KeylistQuery(keylist_query));
info!("Sending {:?}", serde_json::to_string(&message).unwrap());
let message_bytes = serde_json::to_vec(&message)?;
// send message and get response
let response_message = send_message_and_pop_response_message(
&message_bytes,
&agent,
&mut aries_transport,
&our_verkey,
&their_diddoc,
)
.await?;
// verify
if let AriesMessage::CoordinateMediation(CoordinateMediation::Keylist(keylist)) =
serde_json::from_str(&response_message)?
{
info!("Keylist mediator sent {:?}", keylist.content)
} else {
panic!("Expected message of type Keylist. Found {response_message:?}")
}
Ok(())
}
#[tokio::test]
async fn test_mediate_keylist_update_remove() -> Result<()> {
LOGGING_INIT.call_once(setup_env_logging);
// prepare connection parameters
let (agent, mut aries_transport, our_verkey, their_diddoc) =
gen_mediator_connected_agent().await?;
// prepare request message: add key
let did_data = agent
.get_wallet_ref()
.create_and_store_my_did(None, None)
.await?;
let keylist_update_request = KeylistUpdate::builder()
.content(KeylistUpdateContent {
updates: vec![KeylistUpdateItem {
recipient_key: did_data.verkey().base58(),
action: KeylistUpdateItemAction::Add,
}],
})
.id("key-add".to_owned())
.build();
let message = AriesMessage::CoordinateMediation(CoordinateMediation::KeylistUpdate(
keylist_update_request,
));
let message_bytes = serde_json::to_vec(&message)?;
// send message and get response
let _ = send_message_and_pop_response_message(
&message_bytes,
&agent,
&mut aries_transport,
&our_verkey,
&their_diddoc,
)
.await?;
info!("Proceeding to delete");
// prepare request message: delete key
let keylist_update_request = KeylistUpdate::builder()
.content(KeylistUpdateContent {
updates: vec![KeylistUpdateItem {
recipient_key: did_data.verkey().base58(),
action: KeylistUpdateItemAction::Remove,
}],
})
.id("key-remove".to_owned())
.build();
let message = AriesMessage::CoordinateMediation(CoordinateMediation::KeylistUpdate(
keylist_update_request,
));
info!("Sending {:?}", serde_json::to_string(&message).unwrap());
let message_bytes = serde_json::to_vec(&message)?;
// send message and get response
let response_message = send_message_and_pop_response_message(
&message_bytes,
&agent,
&mut aries_transport,
&our_verkey,
&their_diddoc,
)
.await?;
if let AriesMessage::CoordinateMediation(CoordinateMediation::KeylistUpdateResponse(
update_response_data,
)) = serde_json::from_str(&response_message)?
{
info!("Received update response {update_response_data:?}");
} else {
panic!("Expected message of type KeylistUpdateResponse. Found {response_message:?}")
}
Ok(())
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/tests/mediator-protocol-pickup.rs | aries/agents/mediator/tests/mediator-protocol-pickup.rs | mod common;
use aries_vcx::utils::encryption_envelope::EncryptionEnvelope;
use aries_vcx_wallet::wallet::askar::AskarWallet;
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use diddoc_legacy::aries::diddoc::AriesDidDoc;
use mediator::aries_agent::client::transports::AriesTransport;
use messages::{
decorators::attachment::AttachmentType,
msg_fields::protocols::{
basic_message::{BasicMessage, BasicMessageContent, BasicMessageDecorators},
pickup::{
DeliveryRequest, DeliveryRequestContent, DeliveryRequestDecorators, Pickup,
StatusRequest, StatusRequestContent, StatusRequestDecorators,
},
},
AriesMessage,
};
use crate::common::{
agent_and_transport_utils::{
gen_and_register_recipient_key, gen_mediator_connected_agent, get_mediator_grant_data,
send_message_and_pop_response_message,
},
prelude::*,
test_setup::setup_env_logging,
};
static LOGGING_INIT: std::sync::Once = std::sync::Once::new();
async fn forward_basic_anoncrypt_message(
agent_diddoc: &AriesDidDoc,
message_text: &str,
) -> Result<()> {
// Prepare forwarding agent
let agent_f = mediator::aries_agent::AgentBuilder::<AskarWallet>::new_demo_agent().await?;
// Prepare forwarding agent transport
let mut agent_f_aries_transport = reqwest::Client::new();
// Prepare message and wrap into anoncrypt forward message
let message: BasicMessage = BasicMessage::builder()
.content(
BasicMessageContent::builder()
.content(message_text.to_string())
.sent_time(chrono::DateTime::default())
.build(),
)
.decorators(BasicMessageDecorators::default())
.id("JustHello".to_string())
.build();
let EncryptionEnvelope(packed_message) = EncryptionEnvelope::create_from_legacy(
agent_f.get_wallet_ref().as_ref(),
&serde_json::to_vec(&message)?,
None,
agent_diddoc,
)
.await?;
// Send forward message to provided endpoint
let packed_json = serde_json::from_slice(&packed_message)?;
info!("Sending anoncrypt packed message{packed_json}");
let response_envelope = agent_f_aries_transport
.send_aries_envelope(packed_json, agent_diddoc)
.await?;
info!("Response of forward{response_envelope:?}");
Ok(())
}
#[tokio::test]
async fn test_pickup_flow() -> Result<()> {
LOGGING_INIT.call_once(setup_env_logging);
// prepare receiver connection parameters
let (mut agent, mut agent_aries_transport, agent_verkey, mediator_diddoc) =
gen_mediator_connected_agent().await?;
// setup receiver routing
let grant_data = get_mediator_grant_data(
&agent,
&mut agent_aries_transport,
&agent_verkey,
&mediator_diddoc,
)
.await;
agent
.init_service(grant_data.routing_keys, grant_data.endpoint.parse()?)
.await?;
// register recipient key with mediator
let (_agent_recipient_key, agent_diddoc) = gen_and_register_recipient_key(
&mut agent,
&mut agent_aries_transport,
&agent_verkey,
&mediator_diddoc,
)
.await?;
// forward some messages.
forward_basic_anoncrypt_message(&agent_diddoc, "Hi, from AgentF").await?;
forward_basic_anoncrypt_message(&agent_diddoc, "Hi again, from AgentF").await?;
// Pickup flow
// // Status
let pickup_status_req = Pickup::StatusRequest(
StatusRequest::builder()
.content(StatusRequestContent::builder().build())
.decorators(StatusRequestDecorators::default())
.id("request-status".to_owned())
.build(),
);
let aries_message = AriesMessage::Pickup(pickup_status_req);
let message_bytes = serde_json::to_vec(&aries_message)?;
// send message and get response
let response_message = send_message_and_pop_response_message(
&message_bytes,
&agent,
&mut agent_aries_transport,
&agent_verkey,
&mediator_diddoc,
)
.await?;
// Verify expected
if let AriesMessage::Pickup(Pickup::Status(status)) = serde_json::from_str(&response_message)? {
info!("Received status as expected {status:?}");
assert_eq!(status.content.message_count, 2)
} else {
panic!("Expected status with message count = 2, received {response_message:?}")
}
// // Delivery
let pickup_delivery_req = Pickup::DeliveryRequest(
DeliveryRequest::builder()
.content(DeliveryRequestContent::builder().limit(10).build())
.decorators(DeliveryRequestDecorators::builder().build())
.id("request-delivery".to_owned())
.build(),
);
let aries_message = AriesMessage::Pickup(pickup_delivery_req);
let message_bytes = serde_json::to_vec(&aries_message)?;
// send message and get response
let response_message = send_message_and_pop_response_message(
&message_bytes,
&agent,
&mut agent_aries_transport,
&agent_verkey,
&mediator_diddoc,
)
.await?;
// Verify expected
let delivery = if let AriesMessage::Pickup(Pickup::Delivery(delivery)) =
serde_json::from_str(&response_message)?
{
info!("Received delivery as expected {delivery:?}");
assert_eq!(delivery.content.attach.len(), 2);
delivery
} else {
panic!("Expected delivery with num_attachment = 2, received {response_message:?}")
};
// verify valid attachment
if let AttachmentType::Base64(base64message) =
&delivery.content.attach.first().unwrap().data.content
{
let encrypted_message_bytes = URL_SAFE_NO_PAD.decode(base64message)?;
info!(
"Decoding attachment to packed_message {}",
String::from_utf8(message_bytes.clone())?
);
let unpack = agent.unpack_didcomm(&encrypted_message_bytes).await;
info!("Decoded attachment 1 {unpack:?}");
}
Ok(())
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/tests/common/mod.rs | aries/agents/mediator/tests/common/mod.rs | #![allow(dead_code)]
pub mod agent_and_transport_utils;
pub mod test_setup {
// inspired by
// https://stackoverflow.com/questions/58006033/how-to-run-setup-code-before-any-tests-run-in-rust
static INIT: std::sync::Once = std::sync::Once::new();
pub trait OneTimeInit {
// runs the initialization code if it hasn't been run yet, else does nothing
fn init(&self) {
INIT.call_once(|| self.one_time_setup_code());
}
// your custom initialization code goes here
fn one_time_setup_code(&self);
}
pub fn setup_env_logging() {
// default test setup code
let _ = dotenvy::dotenv();
let env = env_logger::Env::default().default_filter_or("info");
env_logger::init_from_env(env);
}
}
pub mod prelude {
pub use anyhow::Result;
pub use log::info;
pub use url::Url;
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/tests/common/agent_and_transport_utils.rs | aries/agents/mediator/tests/common/agent_and_transport_utils.rs | use aries_vcx::{
protocols::{
connection::invitee::{states::completed::Completed, InviteeConnection},
oob::oob_invitation_to_legacy_did_doc,
},
utils::encryption_envelope::EncryptionEnvelope,
};
use aries_vcx_wallet::wallet::{askar::AskarWallet, base_wallet::BaseWallet};
use diddoc_legacy::aries::diddoc::AriesDidDoc;
use mediator::{
aries_agent::{client::transports::AriesTransport, Agent},
persistence::MediatorPersistence,
utils::{structs::VerKey, GenericStringError},
};
use messages::{
msg_fields::protocols::{
coordinate_mediation::{
keylist_update::{KeylistUpdateItem, KeylistUpdateItemAction},
CoordinateMediation, KeylistUpdate, KeylistUpdateContent, MediateGrantContent,
MediateRequest, MediateRequestContent,
},
out_of_band::invitation::Invitation as OOBInvitation,
},
AriesMessage,
};
use test_utils::mockdata::mock_ledger::MockLedger;
use super::prelude::*;
const ENDPOINT_ROOT: &str = "http://localhost:8005";
pub async fn didcomm_connection(
agent: &Agent<impl BaseWallet, 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("invitation").unwrap();
let oobi: OOBInvitation = client
.get(endpoint_register)
.send()
.await?
.error_for_status()?
.json()
.await?;
info!("Got invitation {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.
pub async fn gen_mediator_connected_agent() -> Result<(
Agent<impl BaseWallet, impl MediatorPersistence>,
impl AriesTransport,
VerKey,
AriesDidDoc,
)> {
let agent = mediator::aries_agent::AgentBuilder::<AskarWallet>::new_demo_agent().await?;
let mut aries_transport = 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
pub async fn send_message_and_pop_response_message(
message_bytes: &[u8],
agent: &Agent<impl BaseWallet, impl MediatorPersistence>,
aries_transport: &mut impl AriesTransport,
our_verkey: &VerKey,
their_diddoc: &AriesDidDoc,
) -> Result<String> {
// Wrap message in encrypted envelope
let EncryptionEnvelope(packed_message) = agent
.pack_didcomm(message_bytes, our_verkey, their_diddoc)
.await
.map_err(|e| GenericStringError { msg: e })?;
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 unpacked_response = agent
.unpack_didcomm(&serde_json::to_vec(&response_envelope).unwrap())
.await
.unwrap();
Ok(unpacked_response.message)
}
/// Register recipient keys with mediator
pub async fn gen_and_register_recipient_key(
agent: &mut Agent<impl BaseWallet, impl MediatorPersistence>,
agent_aries_transport: &mut impl AriesTransport,
agent_verkey: &VerKey,
mediator_diddoc: &AriesDidDoc,
) -> Result<(VerKey, AriesDidDoc)> {
let agent_invite: OOBInvitation = agent
.get_oob_invite()
.map_err(|e| GenericStringError { msg: e })?;
let mock_ledger = MockLedger {};
let agent_diddoc = oob_invitation_to_legacy_did_doc(&mock_ledger, &agent_invite)
.await
.unwrap();
let agent_recipient_key = agent_diddoc
.recipient_keys()
.unwrap()
.first()
.unwrap()
.clone();
// register recipient key with mediator
let key_update = KeylistUpdate::builder()
.content(
KeylistUpdateContent::builder()
.updates(vec![KeylistUpdateItem {
recipient_key: agent_recipient_key.clone(),
action: KeylistUpdateItemAction::Add,
}])
.build(),
)
.id("register-key-with-mediator".to_owned())
.build();
let message = AriesMessage::CoordinateMediation(CoordinateMediation::KeylistUpdate(key_update));
info!("Sending {:?}", serde_json::to_string(&message).unwrap());
let message_bytes = serde_json::to_vec(&message)?;
let _response_message = send_message_and_pop_response_message(
&message_bytes,
agent,
agent_aries_transport,
agent_verkey,
mediator_diddoc,
)
.await?;
Ok((agent_recipient_key, agent_diddoc))
}
pub async fn get_mediator_grant_data(
agent: &Agent<impl BaseWallet, impl MediatorPersistence>,
agent_aries_transport: &mut impl AriesTransport,
agent_verkey: &VerKey,
mediator_diddoc: &AriesDidDoc,
) -> MediateGrantContent {
// prepare request message
let message = AriesMessage::CoordinateMediation(CoordinateMediation::MediateRequest(
MediateRequest::builder()
.content(MediateRequestContent::default())
.id("mediate-requets".to_owned())
.build(),
));
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 AriesMessage::CoordinateMediation(CoordinateMediation::MediateGrant(grant_data)) =
serde_json::from_str(&response_message).unwrap()
{
info!("Grant Data {grant_data:?}");
grant_data.content
} else {
panic!("Should get response that is of type Mediator Grant. Found {response_message:?}")
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/client-tui/src/lib.rs | aries/agents/mediator/client-tui/src/lib.rs | use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use mediator::{aries_agent::ArcAgent, persistence::MediatorPersistence};
use messages::msg_fields::protocols::out_of_band::invitation::Invitation as OOBInvitation;
use serde_json::{json, Value};
pub async fn handle_register(
agent: ArcAgent<impl BaseWallet, impl MediatorPersistence>,
oob_invite: OOBInvitation,
) -> Result<Value, String> {
let mut aries_transport = reqwest::Client::new();
let state = agent
.establish_connection(oob_invite, &mut aries_transport)
.await
.map_err(|err| format!("{err:?}"))?;
Ok(json!({
"status": "success",
"connection_completed": state
}))
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/client-tui/src/main.rs | aries/agents/mediator/client-tui/src/main.rs | use aries_vcx_wallet::wallet::askar::AskarWallet;
mod tui;
/// Aries Agent TUI
#[tokio::main]
async fn main() {
use mediator::{
aries_agent::AgentBuilder,
utils::binary_utils::{load_dot_env, setup_logging},
};
load_dot_env();
setup_logging();
log::info!("TUI initializing!");
let agent = AgentBuilder::<AskarWallet>::new_demo_agent().await.unwrap();
tui::init_tui(agent).await;
}
// fn main() {
// print!(
// "This is a placeholder binary. Please enable \"client_tui\" feature to to build the \
// functional client_tui binary."
// )
// }
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/mediator/client-tui/src/tui.rs | aries/agents/mediator/client-tui/src/tui.rs | use std::sync::Arc;
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use client_tui::handle_register;
use cursive::{
direction::Orientation,
event::Key,
view::{Nameable, SizeConstraint},
views::{
Dialog, DummyView, LinearLayout, Panel, ResizedView, ScrollView, SelectView, TextArea,
TextView,
},
Cursive, CursiveExt, View,
};
use futures::executor::block_on;
use log::info;
use mediator::{aries_agent::Agent, persistence::MediatorPersistence};
use messages::msg_fields::protocols::out_of_band::invitation::Invitation as OOBInvitation;
pub async fn init_tui<T: BaseWallet + 'static, P: MediatorPersistence>(agent: Agent<T, P>) {
let mut cursive = Cursive::new();
cursive.add_global_callback(Key::Esc, |s| s.quit());
cursive.set_user_data(Arc::new(agent));
let mut main = LinearLayout::horizontal().with_name("main");
let endpoint_selector = endpoints_ui::<T, P>();
main.get_mut().add_child(endpoint_selector);
cursive.add_layer(main);
cursive.run()
}
pub fn endpoints_ui<T: BaseWallet + 'static, P: MediatorPersistence>() -> Panel<LinearLayout> {
let mut endpoint_selector = SelectView::new();
// Set available endpoints
endpoint_selector.add_item_str("/client/register");
endpoint_selector.add_item_str("/client/trustping");
endpoint_selector.set_on_submit(|s, endpoint: &str| {
// Match ui generators for available endpoints
let view = match endpoint {
"/client/register" => client_register_ui::<T, P>(),
"/client/contacts" => contact_selector_ui::<T, P>(s),
_ => dummy_ui(),
};
// Replace previously exposed ui
s.find_name::<LinearLayout>("main").unwrap().remove_child(1);
s.find_name::<LinearLayout>("main")
.unwrap()
.insert_child(1, view);
});
make_standard(endpoint_selector, Orientation::Vertical).title("Select endpoint")
}
pub fn client_register_ui<T: BaseWallet + 'static, P: MediatorPersistence>() -> Panel<LinearLayout>
{
let input = TextArea::new().with_name("oob_text_area");
let input = ResizedView::new(
SizeConstraint::AtLeast(20),
SizeConstraint::AtLeast(5),
input,
);
let input = Dialog::around(input)
.button("Clear", |s| {
s.find_name::<TextArea>("oob_text_area")
.unwrap()
.set_content("");
})
.button("Connect", client_register_connect_cb::<T, P>)
.title("OOB Invite");
let input = Panel::new(input);
let output = ScrollView::new(ResizedView::new(
SizeConstraint::AtLeast(20),
SizeConstraint::Free,
TextView::new("").with_name("client_register_result"),
));
let output = Panel::new(output).title("Result");
let ui = LinearLayout::horizontal().child(input).child(output);
make_standard(ui, Orientation::Horizontal).title("Register client using Out Of Band Invitation")
}
pub fn client_register_connect_cb<T: BaseWallet + 'static, P: MediatorPersistence>(
s: &mut Cursive,
) {
let oob_text_area = s.find_name::<TextArea>("oob_text_area").unwrap();
let mut output = s.find_name::<TextView>("client_register_result").unwrap();
let oob_text = oob_text_area.get_content();
info!("{oob_text:#?}");
let oob_invite = match serde_json::from_str::<OOBInvitation>(oob_text) {
Ok(oob_invite) => oob_invite,
Err(err) => {
output.set_content(format!("{err:?}"));
return;
}
};
info!("{oob_invite:#?}");
let agent: &mut Arc<Agent<T, P>> = s.user_data().expect("Userdata should contain Agent");
output.set_content(format!("{oob_invite:#?}"));
match block_on(handle_register(agent.to_owned(), oob_invite)) {
Ok(res_json) => output.set_content(serde_json::to_string_pretty(&res_json).unwrap()),
Err(err) => output.set_content(err),
};
}
fn dummy_ui() -> Panel<LinearLayout> {
let ui = DummyView;
make_standard(ui, Orientation::Horizontal)
}
fn make_standard(view: impl View, orientation: Orientation) -> Panel<LinearLayout> {
Panel::new(LinearLayout::new(orientation).child(view))
}
// fn client_trustping_ui(s: &mut Cursive) -> Panel<LinearLayout> {
// contact_selector_ui(s)
// }
pub fn contact_selector_ui<T: BaseWallet + 'static, P: MediatorPersistence>(
s: &mut Cursive,
) -> Panel<LinearLayout> {
let mut contact_selector = SelectView::new();
// Set available contacts
let agent: &mut Arc<Agent<T, P>> = s
.user_data()
.expect("cursive must be initialised with state arc agent ");
let contact_list_maybe = block_on(agent.list_contacts());
let contact_list = contact_list_maybe.unwrap_or_default();
for (acc_name, auth_pubkey) in contact_list.iter() {
contact_selector.add_item(acc_name.clone(), auth_pubkey.clone())
}
make_standard(contact_selector, Orientation::Vertical).title("Select contact")
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/lib.rs | aries/agents/aries-vcx-agent/src/lib.rs | extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate log;
pub extern crate aries_vcx;
extern crate uuid;
mod agent;
mod error;
mod handlers;
mod http;
mod storage;
pub use agent::*;
pub use error::*;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/http.rs | aries/agents/aries-vcx-agent/src/http.rs | use aries_vcx::{errors::error::VcxResult, transport::Transport};
use async_trait::async_trait;
use url::Url;
pub struct VcxHttpClient;
#[async_trait]
impl Transport for VcxHttpClient {
async fn send_message(&self, msg: Vec<u8>, service_endpoint: &Url) -> VcxResult<()> {
shared::http_client::post_message(msg, service_endpoint).await?;
Ok(())
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/storage/mod.rs | aries/agents/aries-vcx-agent/src/storage/mod.rs | use crate::AgentResult;
pub(crate) mod agent_storage_inmem;
pub trait AgentStorage<T> {
type Value;
fn get(&self, id: &str) -> AgentResult<T>;
fn insert(&self, id: &str, obj: T) -> AgentResult<String>;
fn contains_key(&self, id: &str) -> bool;
fn find_by<F>(&self, closure: F) -> AgentResult<Vec<String>>
where
F: FnMut((&String, &Self::Value)) -> Option<String>;
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/storage/agent_storage_inmem.rs | aries/agents/aries-vcx-agent/src/storage/agent_storage_inmem.rs | use std::{
collections::HashMap,
ops::Deref,
sync::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard},
};
use super::AgentStorage;
use crate::error::*;
pub struct AgentStorageInMem<T>
where
T: Clone,
{
pub name: String,
pub store: RwLock<HashMap<String, Mutex<T>>>,
}
impl<T> AgentStorageInMem<T>
where
T: Clone,
{
pub fn new(name: &str) -> Self {
Self {
store: Default::default(),
name: name.to_string(),
}
}
fn lock_store_read(&self) -> AgentResult<RwLockReadGuard<HashMap<String, Mutex<T>>>> {
match self.store.read() {
Ok(g) => Ok(g),
Err(e) => Err(AgentError::from_msg(
AgentErrorKind::LockError,
&format!(
"Unable to obtain read lock for in-memory protocol store {} due to error: {:?}",
self.name, e
),
)),
}
}
fn lock_store_write(&self) -> AgentResult<RwLockWriteGuard<HashMap<String, Mutex<T>>>> {
match self.store.write() {
Ok(g) => Ok(g),
Err(e) => {
error!("Unable to write-lock Object Store: {e:?}");
Err(AgentError::from_msg(
AgentErrorKind::LockError,
&format!(
"Unable to obtain write lock for in-memory protocol store {} due to \
error: {:?}",
self.name, e
),
))
}
}
}
}
impl<T> AgentStorage<T> for AgentStorageInMem<T>
where
T: Clone,
{
type Value = Mutex<T>;
fn get(&self, id: &str) -> AgentResult<T> {
let store = self.lock_store_read()?;
match store.get(id) {
Some(m) => match m.lock() {
Ok(obj) => Ok((*obj.deref()).clone()),
Err(_) => Err(AgentError::from_msg(
AgentErrorKind::LockError,
&format!(
"Unable to obtain lock for object {} in in-memory store {}",
id, self.name
),
)), //TODO better error
},
None => Err(AgentError::from_msg(
AgentErrorKind::NotFound,
&format!("Object {} not found in in-memory store {}", id, self.name),
)),
}
}
fn insert(&self, id: &str, obj: T) -> AgentResult<String> {
info!("Inserting object {} into in-memory store {}", id, self.name);
let mut store = self.lock_store_write()?;
match store.insert(id.to_string(), Mutex::new(obj)) {
Some(_) => Ok(id.to_string()),
None => Ok(id.to_string()),
}
}
fn contains_key(&self, id: &str) -> bool {
let store = match self.lock_store_read() {
Ok(g) => g,
Err(_) => return false,
};
store.contains_key(id)
}
fn find_by<F>(&self, closure: F) -> AgentResult<Vec<String>>
where
F: FnMut((&String, &Self::Value)) -> Option<String>,
{
let store = self.lock_store_read()?;
Ok(store.iter().filter_map(closure).collect())
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/error/error_struct.rs | aries/agents/aries-vcx-agent/src/error/error_struct.rs | use crate::error::AgentErrorKind;
#[derive(Debug)]
pub struct AgentError {
pub message: String,
pub kind: AgentErrorKind,
}
impl std::fmt::Display for AgentError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {
f.write_str(&format!("{}: {}", self.kind, self.message))
}
}
impl AgentError {
pub fn from_msg(kind: AgentErrorKind, msg: &str) -> Self {
AgentError {
kind,
message: msg.to_string(),
}
}
pub fn from_kind(kind: AgentErrorKind) -> Self {
let message = kind.to_string();
AgentError { kind, message }
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/error/error_kind.rs | aries/agents/aries-vcx-agent/src/error/error_kind.rs | #[derive(Copy, Clone, Eq, PartialEq, Debug, thiserror::Error)]
pub enum AgentErrorKind {
#[error("AriesVCX error")]
GenericAriesVcxError,
#[error("Failed to get invite details")]
InviteDetails,
#[error("No object found with specified ID")]
NotFound,
#[error("Unable to lock storage")]
LockError,
#[error("Serialization error")]
SerializationError,
#[error("Invalid arguments passed")]
InvalidArguments,
#[error("Credential definition already exists on the ledger")]
CredDefAlreadyCreated,
#[error("Mediated connections not configured")]
MediatedConnectionServiceUnavailable,
#[error("Failed to submit http request")]
PostMessageFailed,
#[error("Invalid state")]
InvalidState,
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/error/result.rs | aries/agents/aries-vcx-agent/src/error/result.rs | use crate::error::*;
pub type AgentResult<T> = Result<T, AgentError>;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/error/mod.rs | aries/agents/aries-vcx-agent/src/error/mod.rs | mod convertors;
mod error_kind;
mod error_struct;
mod result;
pub use error_kind::AgentErrorKind;
pub use error_struct::AgentError;
pub use result::AgentResult;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/error/convertors.rs | aries/agents/aries-vcx-agent/src/error/convertors.rs | use std::{convert::From, num::ParseIntError};
use aries_vcx::{
did_doc::error::DidDocumentBuilderError,
errors::error::{AriesVcxError, AriesVcxErrorKind},
protocols::did_exchange::state_machine::generic::GenericDidExchange,
};
use aries_vcx_ledger::errors::error::VcxLedgerError;
use did_resolver_sov::did_resolver::did_doc::schema::utils::error::DidDocumentLookupError;
use crate::error::*;
impl From<AriesVcxError> for AgentError {
fn from(err: AriesVcxError) -> AgentError {
let kind = match err.kind() {
AriesVcxErrorKind::CredDefAlreadyCreated => AgentErrorKind::CredDefAlreadyCreated,
_ => AgentErrorKind::GenericAriesVcxError,
};
error!("AriesVCX Error: {err}");
let message = format!("AriesVCX Error: {err}");
AgentError { message, kind }
}
}
impl From<serde_json::Error> for AgentError {
fn from(serde_err: serde_json::Error) -> AgentError {
let kind = AgentErrorKind::SerializationError;
let message = format!("(De)serialization failed; err: {:?}", serde_err.to_string());
AgentError { message, kind }
}
}
impl From<VcxLedgerError> for AgentError {
fn from(err: VcxLedgerError) -> Self {
let kind = AgentErrorKind::GenericAriesVcxError;
let message = format!("VcxLedgerCore Error; err: {:?}", err.to_string());
AgentError { message, kind }
}
}
impl From<DidDocumentBuilderError> for AgentError {
fn from(err: DidDocumentBuilderError) -> Self {
let kind = AgentErrorKind::GenericAriesVcxError;
let message = format!("DidDocumentBuilderError; err: {:?}", err.to_string());
AgentError { message, kind }
}
}
impl From<aries_vcx::did_parser_nom::ParseError> for AgentError {
fn from(err: aries_vcx::did_parser_nom::ParseError) -> Self {
let kind = AgentErrorKind::GenericAriesVcxError;
let message = format!("DidParseError; err: {:?}", err.to_string());
AgentError { message, kind }
}
}
impl From<did_peer::error::DidPeerError> for AgentError {
fn from(err: did_peer::error::DidPeerError) -> Self {
let kind = AgentErrorKind::GenericAriesVcxError;
let message = format!("DidPeerError; err: {:?}", err.to_string());
AgentError { message, kind }
}
}
impl From<public_key::PublicKeyError> for AgentError {
fn from(err: public_key::PublicKeyError) -> Self {
let kind = AgentErrorKind::GenericAriesVcxError;
let message = format!("PublicKeyError; err: {:?}", err.to_string());
AgentError { message, kind }
}
}
impl From<did_key::error::DidKeyError> for AgentError {
fn from(err: did_key::error::DidKeyError) -> Self {
let kind = AgentErrorKind::GenericAriesVcxError;
let message = format!("DidKeyError; err: {:?}", err.to_string());
AgentError { message, kind }
}
}
impl From<(GenericDidExchange, AriesVcxError)> for AgentError {
fn from(err: (GenericDidExchange, AriesVcxError)) -> Self {
let kind = AgentErrorKind::GenericAriesVcxError;
let message = format!("GenericDidExchange; err: {:?}", err.1.to_string());
AgentError { message, kind }
}
}
impl From<DidDocumentLookupError> for AgentError {
fn from(err: DidDocumentLookupError) -> Self {
let kind = AgentErrorKind::GenericAriesVcxError;
let message = format!("DidDocumentLookupError; err: {:?}", err.to_string());
AgentError { message, kind }
}
}
impl From<anoncreds_types::Error> for AgentError {
fn from(err: anoncreds_types::Error) -> Self {
let kind = AgentErrorKind::GenericAriesVcxError;
let message = format!("AnoncredsTypesError; err: {:?}", err.to_string());
AgentError { message, kind }
}
}
impl From<ParseIntError> for AgentError {
fn from(err: ParseIntError) -> Self {
let kind = AgentErrorKind::GenericAriesVcxError;
let message = format!("ParseIntError; err: {:?}", err.to_string());
AgentError { message, kind }
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/handlers/revocation_registry.rs | aries/agents/aries-vcx-agent/src/handlers/revocation_registry.rs | use std::{
path::Path,
sync::{Arc, Mutex},
};
use anoncreds_types::data_types::identifiers::cred_def_id::CredentialDefinitionId;
use aries_vcx::{common::primitives::revocation_registry::RevocationRegistry, did_parser_nom::Did};
use aries_vcx_anoncreds::anoncreds::anoncreds::Anoncreds;
use aries_vcx_ledger::ledger::indy_vdr_ledger::{DefaultIndyLedgerRead, DefaultIndyLedgerWrite};
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use crate::{
error::*,
storage::{agent_storage_inmem::AgentStorageInMem, AgentStorage},
};
pub struct ServiceRevocationRegistries<T> {
ledger_write: Arc<DefaultIndyLedgerWrite>,
ledger_read: Arc<DefaultIndyLedgerRead>,
anoncreds: Anoncreds,
wallet: Arc<T>,
issuer_did: Did,
rev_regs: AgentStorageInMem<RevocationRegistry>,
}
impl<T: BaseWallet> ServiceRevocationRegistries<T> {
pub fn new(
ledger_write: Arc<DefaultIndyLedgerWrite>,
ledger_read: Arc<DefaultIndyLedgerRead>,
anoncreds: Anoncreds,
wallet: Arc<T>,
issuer_did: String,
) -> Self {
Self {
issuer_did: Did::parse(issuer_did).unwrap(), // TODO
rev_regs: AgentStorageInMem::new("rev-regs"),
ledger_write,
ledger_read,
anoncreds,
wallet,
}
}
fn get_tails_hash(&self, thread_id: &str) -> AgentResult<String> {
let rev_reg = self.rev_regs.get(thread_id)?;
Ok(rev_reg.get_rev_reg_def().value.tails_hash)
}
pub fn get_tails_dir(&self, thread_id: &str) -> AgentResult<String> {
let rev_reg = self.rev_regs.get(thread_id)?;
Ok(rev_reg.get_tails_dir())
}
pub async fn create_rev_reg(
&self,
cred_def_id: &CredentialDefinitionId,
max_creds: u32,
) -> AgentResult<String> {
let rev_reg = RevocationRegistry::create(
self.wallet.as_ref(),
&self.anoncreds,
&self.issuer_did,
cred_def_id,
"/tmp",
max_creds,
1,
)
.await?;
self.rev_regs.insert(&rev_reg.get_rev_reg_id(), rev_reg)
}
pub fn tails_file_path(&self, thread_id: &str) -> AgentResult<String> {
Ok(Path::new(&self.get_tails_dir(thread_id)?)
.join(self.get_tails_hash(thread_id)?)
.to_str()
.ok_or_else(|| {
AgentError::from_msg(
AgentErrorKind::SerializationError,
"Failed to serialize tails file path",
)
})?
.to_string())
}
pub async fn publish_rev_reg(&self, thread_id: &str, tails_url: &str) -> AgentResult<()> {
let mut rev_reg = self.rev_regs.get(thread_id)?;
rev_reg
.publish_revocation_primitives(
self.wallet.as_ref(),
self.ledger_write.as_ref(),
tails_url,
)
.await?;
self.rev_regs.insert(thread_id, rev_reg)?;
Ok(())
}
pub async fn revoke_credential_locally(&self, id: &str, cred_rev_id: &str) -> AgentResult<()> {
let rev_reg = self.rev_regs.get(id)?;
rev_reg
.revoke_credential_local(
self.wallet.as_ref(),
&self.anoncreds,
self.ledger_read.as_ref(),
cred_rev_id.parse()?,
)
.await?;
Ok(())
}
pub async fn publish_local_revocations(&self, id: &str) -> AgentResult<()> {
let rev_reg = self.rev_regs.get(id)?;
rev_reg
.publish_local_revocations(
self.wallet.as_ref(),
&self.anoncreds,
self.ledger_write.as_ref(),
&self.issuer_did,
)
.await?;
Ok(())
}
pub fn find_by_cred_def_id(&self, cred_def_id: &str) -> AgentResult<Vec<String>> {
let cred_def_id = cred_def_id.to_string();
let f = |(id, m): (&String, &Mutex<RevocationRegistry>)| -> Option<String> {
let rev_reg = m.lock().unwrap();
if rev_reg.get_cred_def_id() == cred_def_id {
Some(id.clone())
} else {
None
}
};
self.rev_regs.find_by(f)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/handlers/prover.rs | aries/agents/aries-vcx-agent/src/handlers/prover.rs | use std::{collections::HashMap, sync::Arc};
use anoncreds_types::data_types::messages::cred_selection::SelectedCredentials;
use aries_vcx::{
handlers::{proof_presentation::prover::Prover, util::PresentationProposalData},
messages::{
msg_fields::protocols::present_proof::v1::{
ack::AckPresentationV1, request::RequestPresentationV1,
},
AriesMessage,
},
protocols::{proof_presentation::prover::state_machine::ProverState, SendClosure},
};
use aries_vcx_anoncreds::anoncreds::anoncreds::Anoncreds;
use aries_vcx_ledger::ledger::indy_vdr_ledger::DefaultIndyLedgerRead;
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use serde_json::Value;
use super::connection::ServiceConnections;
use crate::{
error::*,
http::VcxHttpClient,
storage::{agent_storage_inmem::AgentStorageInMem, AgentStorage},
};
#[derive(Clone)]
struct ProverWrapper {
prover: Prover,
connection_id: String,
}
impl ProverWrapper {
pub fn new(prover: Prover, connection_id: &str) -> Self {
Self {
prover,
connection_id: connection_id.to_string(),
}
}
}
pub struct ServiceProver<T> {
ledger_read: Arc<DefaultIndyLedgerRead>,
anoncreds: Anoncreds,
wallet: Arc<T>,
provers: AgentStorageInMem<ProverWrapper>,
service_connections: Arc<ServiceConnections<T>>,
}
impl<T: BaseWallet> ServiceProver<T> {
pub fn new(
ledger_read: Arc<DefaultIndyLedgerRead>,
anoncreds: Anoncreds,
wallet: Arc<T>,
service_connections: Arc<ServiceConnections<T>>,
) -> Self {
Self {
service_connections,
provers: AgentStorageInMem::new("provers"),
ledger_read,
anoncreds,
wallet,
}
}
pub fn get_prover(&self, thread_id: &str) -> AgentResult<Prover> {
let ProverWrapper { prover, .. } = self.provers.get(thread_id)?;
Ok(prover)
}
pub fn get_connection_id(&self, thread_id: &str) -> AgentResult<String> {
let ProverWrapper { connection_id, .. } = self.provers.get(thread_id)?;
Ok(connection_id)
}
async fn get_credentials_for_presentation(
&self,
prover: &Prover,
tails_dir: Option<&str>,
) -> AgentResult<SelectedCredentials> {
let credentials = prover
.retrieve_credentials(self.wallet.as_ref(), &self.anoncreds)
.await?;
let mut res_credentials = SelectedCredentials::default();
for (referent, cred_array) in credentials.credentials_by_referent.into_iter() {
if !cred_array.is_empty() {
let first_cred = cred_array[0].clone();
let tails_dir = tails_dir.map(|x| x.to_owned());
res_credentials
.select_credential_for_referent_from_retrieved(referent, first_cred, tails_dir);
}
}
Ok(res_credentials)
}
pub fn create_from_request(
&self,
connection_id: &str,
request: RequestPresentationV1,
) -> AgentResult<String> {
self.service_connections.get_by_id(connection_id)?;
let prover = Prover::create_from_request("", request)?;
self.provers.insert(
&prover.get_thread_id()?,
ProverWrapper::new(prover, connection_id),
)
}
pub async fn send_proof_proposal(
&self,
connection_id: &str,
proposal: PresentationProposalData,
) -> AgentResult<String> {
let connection = self.service_connections.get_by_id(connection_id)?;
let mut prover = Prover::create("")?;
let wallet = &self.wallet;
let send_closure: SendClosure = Box::new(|msg: AriesMessage| {
Box::pin(async move {
connection
.send_message(wallet.as_ref(), &msg, &VcxHttpClient)
.await
})
});
let proposal = prover.build_presentation_proposal(proposal).await?;
send_closure(proposal.into()).await?;
self.provers.insert(
&prover.get_thread_id()?,
ProverWrapper::new(prover, connection_id),
)
}
pub fn is_secondary_proof_requested(&self, thread_id: &str) -> AgentResult<bool> {
let prover = self.get_prover(thread_id)?;
let attach = prover.get_proof_request_attachment()?;
let attach: Value = serde_json::from_str(&attach)?;
Ok(!attach["non_revoked"].is_null())
}
pub async fn send_proof_prentation(
&self,
thread_id: &str,
tails_dir: Option<&str>,
) -> AgentResult<()> {
let ProverWrapper {
mut prover,
connection_id,
} = self.provers.get(thread_id)?;
let connection = self.service_connections.get_by_id(&connection_id)?;
let credentials = self
.get_credentials_for_presentation(&prover, tails_dir)
.await?;
prover
.generate_presentation(
self.wallet.as_ref(),
self.ledger_read.as_ref(),
&self.anoncreds,
credentials,
HashMap::new(),
)
.await?;
let wallet = &self.wallet;
let send_closure: SendClosure = Box::new(|msg: AriesMessage| {
Box::pin(async move {
connection
.send_message(wallet.as_ref(), &msg, &VcxHttpClient)
.await
})
});
let message = prover.mark_presentation_sent()?;
send_closure(message).await?;
self.provers.insert(
&prover.get_thread_id()?,
ProverWrapper::new(prover, &connection_id),
)?;
Ok(())
}
pub fn process_presentation_ack(
&self,
thread_id: &str,
ack: AckPresentationV1,
) -> AgentResult<String> {
let ProverWrapper {
mut prover,
connection_id,
} = self.provers.get(thread_id)?;
prover.process_presentation_ack(ack)?;
self.provers.insert(
&prover.get_thread_id()?,
ProverWrapper::new(prover, &connection_id),
)
}
pub fn get_state(&self, thread_id: &str) -> AgentResult<ProverState> {
let ProverWrapper { prover, .. } = self.provers.get(thread_id)?;
Ok(prover.get_state())
}
pub fn exists_by_id(&self, thread_id: &str) -> bool {
self.provers.contains_key(thread_id)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/handlers/connection.rs | aries/agents/aries-vcx-agent/src/handlers/connection.rs | use std::sync::{Arc, Mutex};
use aries_vcx::{
handlers::util::AnyInvitation,
messages::{
msg_fields::protocols::{
connection::{request::Request, response::Response},
notification::ack::Ack,
trust_ping::ping::Ping,
},
AriesMessage,
},
protocols::{
connection::{
inviter::states::completed::Completed, pairwise_info::PairwiseInfo, Connection,
GenericConnection, State, ThinState,
},
trustping::build_ping_response,
},
};
use aries_vcx_ledger::ledger::indy_vdr_ledger::DefaultIndyLedgerRead;
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use url::Url;
use crate::{
error::*,
http::VcxHttpClient,
storage::{agent_storage_inmem::AgentStorageInMem, AgentStorage},
};
pub struct ServiceConnections<T> {
ledger_read: Arc<DefaultIndyLedgerRead>,
wallet: Arc<T>,
service_endpoint: Url,
connections: Arc<AgentStorageInMem<GenericConnection>>,
}
impl<T: BaseWallet> ServiceConnections<T> {
pub fn new(
ledger_read: Arc<DefaultIndyLedgerRead>,
wallet: Arc<T>,
service_endpoint: Url,
) -> Self {
Self {
service_endpoint,
connections: Arc::new(AgentStorageInMem::new("connections")),
ledger_read,
wallet,
}
}
pub async fn send_message(
&self,
connection_id: &str,
message: &AriesMessage,
) -> AgentResult<()> {
let connection = self.get_by_id(connection_id)?;
let wallet = self.wallet.as_ref();
info!(
"Sending message to connection identified by id {connection_id}. Plaintext message payload: {message}"
);
connection
.send_message(wallet, message, &VcxHttpClient)
.await?;
Ok(())
}
pub async fn create_invitation(
&self,
pw_info: Option<PairwiseInfo>,
) -> AgentResult<AnyInvitation> {
let pw_info = pw_info.unwrap_or(PairwiseInfo::create(self.wallet.as_ref()).await?);
let inviter = Connection::new_inviter("".to_owned(), pw_info)
.create_invitation(vec![], self.service_endpoint.clone());
let invite = inviter.get_invitation().clone();
let thread_id = inviter.thread_id().to_owned();
self.connections.insert(&thread_id, inviter.into())?;
Ok(invite)
}
pub async fn receive_invitation(&self, invite: AnyInvitation) -> AgentResult<String> {
let pairwise_info = PairwiseInfo::create(self.wallet.as_ref()).await?;
let invitee = Connection::new_invitee("".to_owned(), pairwise_info)
.accept_invitation(self.ledger_read.as_ref(), invite)
.await?;
let thread_id = invitee.thread_id().to_owned();
self.connections.insert(&thread_id, invitee.into())
}
pub async fn send_request(&self, thread_id: &str) -> AgentResult<()> {
let invitee: Connection<_, _> = self.connections.get(thread_id)?.try_into()?;
let invitee = invitee
.prepare_request(self.service_endpoint.clone(), vec![])
.await?;
let request = invitee.get_request().clone();
invitee
.send_message(self.wallet.as_ref(), &request.into(), &VcxHttpClient)
.await?;
self.connections.insert(thread_id, invitee.into())?;
Ok(())
}
pub async fn accept_request(&self, thread_id: &str, request: Request) -> AgentResult<()> {
let inviter = self.connections.get(thread_id)?;
let inviter = match inviter.state() {
ThinState::Inviter(State::Initial) => Connection::try_from(inviter)
.map_err(From::from)
.map(|c| c.into_invited(&request.id)),
ThinState::Inviter(State::Invited) => Connection::try_from(inviter).map_err(From::from),
s => Err(AgentError::from_msg(
AgentErrorKind::GenericAriesVcxError,
&format!(
"Connection with handle {thread_id} cannot process a request; State: {s:?}"
),
)),
}?;
let inviter = inviter
.handle_request(
self.wallet.as_ref(),
request,
self.service_endpoint.clone(),
vec![],
)
.await?;
self.connections.insert(thread_id, inviter.into())?;
Ok(())
}
pub async fn send_response(&self, thread_id: &str) -> AgentResult<()> {
let inviter: Connection<_, _> = self.connections.get(thread_id)?.try_into()?;
let response = inviter.get_connection_response_msg();
inviter
.send_message(self.wallet.as_ref(), &response.into(), &VcxHttpClient)
.await?;
self.connections.insert(thread_id, inviter.into())?;
Ok(())
}
pub async fn accept_response(&self, thread_id: &str, response: Response) -> AgentResult<()> {
let invitee: Connection<_, _> = self.connections.get(thread_id)?.try_into()?;
let invitee = invitee
.handle_response(self.wallet.as_ref(), response)
.await?;
self.connections.insert(thread_id, invitee.into())?;
Ok(())
}
pub async fn send_ack(&self, thread_id: &str) -> AgentResult<()> {
let invitee: Connection<_, _> = self.connections.get(thread_id)?.try_into()?;
invitee
.send_message(
self.wallet.as_ref(),
&invitee.get_ack().into(),
&VcxHttpClient,
)
.await?;
self.connections.insert(thread_id, invitee.into())?;
Ok(())
}
pub async fn process_ack(&self, ack: Ack) -> AgentResult<()> {
let thread_id = ack.decorators.thread.thid.clone();
let inviter: Connection<_, _> = self.connections.get(&thread_id)?.try_into()?;
let inviter = inviter.acknowledge_connection(&ack.into())?;
self.connections.insert(&thread_id, inviter.into())?;
Ok(())
}
/// Process a trust ping and send a pong. Also bump the connection state (ack) if needed.
pub async fn process_trust_ping(&self, ping: Ping, connection_id: &str) -> AgentResult<()> {
let generic_inviter = self.connections.get(connection_id)?;
let inviter: Connection<_, Completed> = match generic_inviter.state() {
ThinState::Inviter(State::Requested) => {
// bump state. requested -> complete
let inviter: Connection<_, _> = generic_inviter.try_into()?;
inviter.acknowledge_connection(&ping.clone().into())?
}
ThinState::Inviter(State::Completed) => generic_inviter.try_into()?,
s => {
return Err(AgentError::from_msg(
AgentErrorKind::GenericAriesVcxError,
&format!(
"Connection with handle {connection_id} cannot process a trust ping; State: {s:?}"
),
))
}
};
// send pong if desired
if ping.content.response_requested {
let response = build_ping_response(&ping);
inviter
.send_message(self.wallet.as_ref(), &response.into(), &VcxHttpClient)
.await?;
}
// update state
self.connections.insert(connection_id, inviter.into())?;
Ok(())
}
pub fn get_state(&self, thread_id: &str) -> AgentResult<ThinState> {
Ok(self.connections.get(thread_id)?.state())
}
pub(in crate::handlers) fn get_by_id(&self, thread_id: &str) -> AgentResult<GenericConnection> {
self.connections.get(thread_id)
}
pub fn get_by_sender_vk(&self, sender_vk: String) -> AgentResult<String> {
let f = |(id, m): (&String, &Mutex<GenericConnection>)| -> Option<String> {
let connection = m.lock().unwrap();
match connection.remote_vk() {
Ok(remote_vk) if remote_vk == sender_vk => Some(id.to_string()),
_ => None,
}
};
let conns = self.connections.find_by(f)?;
if conns.len() > 1 {
return Err(AgentError::from_msg(
AgentErrorKind::InvalidState,
&format!("Found multiple connections by sender's verkey {sender_vk}"),
));
}
conns.into_iter().next().ok_or(AgentError::from_msg(
AgentErrorKind::InvalidState,
&format!("Found no connections by sender's verkey {sender_vk}"),
))
}
pub fn exists_by_id(&self, thread_id: &str) -> bool {
self.connections.contains_key(thread_id)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/handlers/out_of_band.rs | aries/agents/aries-vcx-agent/src/handlers/out_of_band.rs | use std::sync::Arc;
use aries_vcx::{
handlers::out_of_band::{
receiver::OutOfBandReceiver, sender::OutOfBandSender, GenericOutOfBand,
},
messages::{
msg_fields::protocols::out_of_band::invitation::{Invitation as OobInvitation, OobService},
msg_types::{
protocols::did_exchange::{DidExchangeType, DidExchangeTypeV1},
Protocol,
},
AriesMessage,
},
protocols::did_exchange::state_machine::helpers::create_peer_did_4,
};
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use url::Url;
use crate::{
storage::{agent_storage_inmem::AgentStorageInMem, AgentStorage},
AgentResult,
};
pub struct ServiceOutOfBand<T> {
wallet: Arc<T>,
service_endpoint: Url,
out_of_band: Arc<AgentStorageInMem<GenericOutOfBand>>,
}
impl<T: BaseWallet> ServiceOutOfBand<T> {
pub fn new(wallet: Arc<T>, service_endpoint: Url) -> Self {
Self {
wallet,
service_endpoint,
out_of_band: Arc::new(AgentStorageInMem::new("out-of-band")),
}
}
pub async fn create_invitation(&self) -> AgentResult<AriesMessage> {
let (peer_did, _our_verkey) =
create_peer_did_4(self.wallet.as_ref(), self.service_endpoint.clone(), vec![]).await?;
let sender = OutOfBandSender::create()
.append_service(&OobService::Did(peer_did.to_string()))
.append_handshake_protocol(Protocol::DidExchangeType(DidExchangeType::V1(
DidExchangeTypeV1::new_v1_1(),
)))?;
self.out_of_band.insert(
&sender.get_id(),
GenericOutOfBand::Sender(sender.to_owned()),
)?;
Ok(sender.invitation_to_aries_message())
}
pub fn receive_invitation(&self, invitation: AriesMessage) -> AgentResult<String> {
let receiver = OutOfBandReceiver::create_from_a2a_msg(&invitation)?;
self.out_of_band
.insert(&receiver.get_id(), GenericOutOfBand::Receiver(receiver))
}
pub fn get_invitation(&self, invitation_id: &str) -> AgentResult<OobInvitation> {
let out_of_band = self.out_of_band.get(invitation_id)?;
match out_of_band {
GenericOutOfBand::Sender(sender) => Ok(sender.oob),
GenericOutOfBand::Receiver(receiver) => Ok(receiver.oob),
}
}
pub fn exists_by_id(&self, thread_id: &str) -> bool {
self.out_of_band.contains_key(thread_id)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/handlers/schema.rs | aries/agents/aries-vcx-agent/src/handlers/schema.rs | use std::sync::{Arc, Mutex};
use aries_vcx::{common::primitives::credential_schema::Schema, did_parser_nom::Did};
use aries_vcx_anoncreds::anoncreds::anoncreds::Anoncreds;
use aries_vcx_ledger::ledger::{
base_ledger::AnoncredsLedgerRead,
indy_vdr_ledger::{DefaultIndyLedgerRead, DefaultIndyLedgerWrite},
};
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use crate::{
error::*,
storage::{agent_storage_inmem::AgentStorageInMem, AgentStorage},
};
pub struct ServiceSchemas<T> {
ledger_read: Arc<DefaultIndyLedgerRead>,
ledger_write: Arc<DefaultIndyLedgerWrite>,
anoncreds: Anoncreds,
wallet: Arc<T>,
issuer_did: Did,
schemas: AgentStorageInMem<Schema>,
}
impl<T: BaseWallet> ServiceSchemas<T> {
pub fn new(
ledger_read: Arc<DefaultIndyLedgerRead>,
ledger_write: Arc<DefaultIndyLedgerWrite>,
anoncreds: Anoncreds,
wallet: Arc<T>,
issuer_did: String,
) -> Self {
Self {
issuer_did: Did::parse(issuer_did).unwrap(), // TODO
schemas: AgentStorageInMem::new("schemas"),
ledger_read,
ledger_write,
anoncreds,
wallet,
}
}
pub async fn create_schema(
&self,
name: &str,
version: &str,
attributes: Vec<String>,
) -> AgentResult<String> {
let schema = Schema::create(
&self.anoncreds,
"",
&self.issuer_did,
name,
version,
attributes,
)
.await?;
self.schemas
.insert(&schema.get_schema_id().to_string(), schema)
}
pub async fn publish_schema(&self, thread_id: &str) -> AgentResult<()> {
let schema = self.schemas.get(thread_id)?;
let schema = schema
.publish(self.wallet.as_ref(), self.ledger_write.as_ref())
.await?;
self.schemas.insert(thread_id, schema)?;
Ok(())
}
pub async fn schema_json(&self, thread_id: &str) -> AgentResult<String> {
let ledger = self.ledger_read.as_ref();
Ok(serde_json::to_string(
&ledger
.get_schema(&thread_id.to_string().try_into()?, None)
.await?,
)?)
}
pub fn find_by_name_and_version(&self, name: &str, version: &str) -> AgentResult<Vec<String>> {
let name = name.to_string();
let version = version.to_string();
let f = |(id, m): (&String, &Mutex<Schema>)| -> Option<String> {
let schema = m.lock().unwrap();
if schema.name == name && schema.version == version {
Some(id.to_string())
} else {
None
}
};
self.schemas.find_by(f)
}
pub fn get_by_id(&self, thread_id: &str) -> AgentResult<Schema> {
self.schemas.get(thread_id)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/handlers/did_exchange.rs | aries/agents/aries-vcx-agent/src/handlers/did_exchange.rs | use std::sync::Arc;
use aries_vcx::{
did_doc::schema::{service::typed::ServiceType, types::uri::Uri},
did_parser_nom::Did,
messages::{
msg_fields::protocols::{
did_exchange::v1_x::{
complete::Complete, problem_report::ProblemReport, request::AnyRequest,
response::AnyResponse,
},
out_of_band::invitation::Invitation as OobInvitation,
},
msg_types::protocols::did_exchange::DidExchangeTypeV1,
AriesMessage,
},
protocols::did_exchange::{
resolve_enc_key_from_did_doc, resolve_enc_key_from_invitation,
state_machine::{
generic::{GenericDidExchange, ThinState},
helpers::create_peer_did_4,
},
},
transport::Transport,
utils::encryption_envelope::EncryptionEnvelope,
};
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use did_resolver_registry::ResolverRegistry;
use did_resolver_sov::did_resolver::did_doc::schema::did_doc::DidDocument;
use public_key::{Key, KeyType};
use url::Url;
use crate::{
http::VcxHttpClient,
storage::{agent_storage_inmem::AgentStorageInMem, AgentStorage},
AgentError, AgentErrorKind, AgentResult,
};
// todo: break down into requester and responder services?
pub struct DidcommHandlerDidExchange<T> {
wallet: Arc<T>,
resolver_registry: Arc<ResolverRegistry>,
service_endpoint: Url,
did_exchange: Arc<AgentStorageInMem<(GenericDidExchange, Option<AriesMessage>)>>,
public_did: String,
}
impl<T: BaseWallet> DidcommHandlerDidExchange<T> {
pub fn new(
wallet: Arc<T>,
resolver_registry: Arc<ResolverRegistry>,
service_endpoint: Url,
public_did: String,
) -> Self {
Self {
wallet,
service_endpoint,
resolver_registry,
did_exchange: Arc::new(AgentStorageInMem::new("did-exchange")),
public_did,
}
}
pub async fn handle_msg_invitation(
&self,
their_did: String,
invitation_id: Option<String>,
version: DidExchangeTypeV1,
) -> AgentResult<(String, Option<String>, String)> {
// todo: type the return type
let (our_peer_did, _our_verkey) =
create_peer_did_4(self.wallet.as_ref(), self.service_endpoint.clone(), vec![]).await?;
let our_did = our_peer_did.did().to_string();
let their_did: Did = their_did.parse()?;
let (requester, request) = GenericDidExchange::construct_request(
&self.resolver_registry,
invitation_id,
&their_did,
&our_peer_did,
"".to_owned(),
version,
)
.await?;
// TODO: decouple this from AATH. The reason why we identify the requester's did-exchange
// protocol with pthid is because that's what AATH expects when calling GET
// /agent/command/did-exchange/{id} where {id} is actually {pthid}.
// We should have internal strategy to manage threads ourselves, and build necessary
// extensions/mappings/accommodations in AATH backchannel
warn!("send_request >>> request: {request:?}");
let req_thread = request.inner().decorators.thread.as_ref().ok_or_else(|| {
AgentError::from_msg(
AgentErrorKind::InvalidState,
"Request did not contain a thread",
)
})?;
let pthid = req_thread.pthid.clone();
// todo: messages must provide easier way to access this without all the shenanigans
let thid = req_thread.thid.clone();
let ddo_their = requester.their_did_doc();
let ddo_our = requester.our_did_document();
let service = ddo_their.get_service_of_type(&ServiceType::DIDCommV1)?;
let encryption_envelope = pairwise_encrypt(
ddo_our,
ddo_their,
self.wallet.as_ref(),
&request.into(),
service.id(),
)
.await?;
// todo: hack; There's issue on AATH level https://github.com/openwallet-foundation/owl-agent-test-harness/issues/784
// but if AATH can not be changed and both thid and pthid are used to track instance
// of protocol then we need to update storage to enable identification by
// multiple IDs (both thid, pthid (or arbitrary other))
self.did_exchange.insert(&thid, (requester.clone(), None))?;
VcxHttpClient
.send_message(encryption_envelope.0, service.service_endpoint())
.await?;
Ok((thid, pthid, our_did))
}
// todo: whether invitation exists should handle the framework based on (p)thread matching
// rather than being supplied by upper layers
pub async fn handle_msg_request(
&self,
request: AnyRequest,
inviter_key: String,
invitation: Option<OobInvitation>,
) -> AgentResult<(String, Option<String>, String, String)> {
// todo: type the return type
// Todo: messages should expose fallible API to get thid (for any aries msg). It's common
// pattern
let thread = request.inner().decorators.thread.as_ref();
let thid = thread
.ok_or_else(|| {
AgentError::from_msg(
AgentErrorKind::InvalidState,
"Request did not contain a thread id",
)
})?
.thid
.clone();
let inviter_key = Key::from_base58(&inviter_key, KeyType::Ed25519)?;
let invitation_key = match invitation {
None => inviter_key,
Some(invitation) => {
resolve_enc_key_from_invitation(&invitation, &self.resolver_registry).await?
}
};
let (our_peer_did, _our_verkey) =
create_peer_did_4(self.wallet.as_ref(), self.service_endpoint.clone(), vec![]).await?;
let pthid = thread
.ok_or_else(|| {
AgentError::from_msg(
AgentErrorKind::InvalidState,
"Request did not contain a thread",
)
})?
.pthid
.clone();
let (responder, response) = GenericDidExchange::handle_request(
self.wallet.as_ref(),
&self.resolver_registry,
request,
&our_peer_did,
invitation_key,
)
.await?;
self.did_exchange
.insert(&thid, (responder.clone(), Some(response.into())))?;
let our_did = responder.our_did_document().id().to_string();
let their_did = responder.their_did_doc().id().to_string();
Ok((thid, pthid, our_did, their_did))
}
// todo: perhaps injectable transports? Or just return the message let the caller send it?
// The transports abstraction could understand https, wss, didcomm etc.
pub async fn send_response(&self, thid: String) -> AgentResult<String> {
info!("ServiceDidExchange::send_response >>> thid: {thid}");
let (responder, aries_msg) = self.did_exchange.get(&thid)?;
let aries_msg: AriesMessage = aries_msg.unwrap();
debug!(
"ServiceDidExchange::send_response >>> successfully found state machine and a message \
to be send"
);
let ddo_their = responder.their_did_doc();
let ddo_our = responder.our_did_document();
let service = ddo_their.get_service_of_type(&ServiceType::DIDCommV1)?;
let encryption_envelope = pairwise_encrypt(
ddo_our,
ddo_their,
self.wallet.as_ref(),
&aries_msg,
service.id(),
)
.await?;
VcxHttpClient
.send_message(encryption_envelope.0, service.service_endpoint())
.await?;
info!("ServiceDidExchange::send_response <<< successfully sent response");
Ok(thid)
}
// todo: break down into "process_response" and "send_complete"
pub async fn handle_msg_response(&self, response: AnyResponse) -> AgentResult<String> {
let thread = match response {
AnyResponse::V1_0(ref inner) => &inner.decorators.thread,
AnyResponse::V1_1(ref inner) => &inner.decorators.thread,
};
let thid = thread.thid.clone();
let (requester, _) = self.did_exchange.get(&thid)?;
let inviter_ddo = requester.their_did_doc();
let inviter_key = resolve_enc_key_from_did_doc(inviter_ddo)?;
let (requester, complete) = requester
.handle_response(
self.wallet.as_ref(),
&inviter_key,
response,
&self.resolver_registry,
)
.await?;
let ddo_their = requester.their_did_doc();
let ddo_our = requester.our_did_document();
let service = ddo_their.get_service_of_type(&ServiceType::DIDCommV1)?;
let encryption_envelope = pairwise_encrypt(
ddo_our,
ddo_their,
self.wallet.as_ref(),
&complete.into(),
service.id(),
)
.await?;
self.did_exchange.insert(&thid, (requester.clone(), None))?;
VcxHttpClient
.send_message(encryption_envelope.0, service.service_endpoint())
.await?;
Ok(thid)
}
pub fn handle_msg_complete(&self, complete: Complete) -> AgentResult<String> {
let thread_id = complete.decorators.thread.thid.clone();
let (requester, _) = self.did_exchange.get(&thread_id)?;
let requester = requester.handle_complete(complete)?;
self.did_exchange.insert(&thread_id, (requester, None))
}
pub fn receive_problem_report(&self, problem_report: ProblemReport) -> AgentResult<String> {
let thread_id = problem_report.decorators.thread.thid.clone();
let (requester, _) = self.did_exchange.get(&thread_id)?;
let requester = requester.handle_problem_report(problem_report)?;
self.did_exchange.insert(&thread_id, (requester, None))
}
pub fn exists_by_id(&self, thread_id: &str) -> bool {
self.did_exchange.contains_key(thread_id)
}
pub fn invitation_id(&self, _thread_id: &str) -> AgentResult<String> {
unimplemented!()
}
pub fn public_did(&self) -> &str {
self.public_did.as_ref()
}
pub fn get_state(&self, thid: &str) -> AgentResult<ThinState> {
let (protocol, _) = self.did_exchange.get(thid)?;
Ok(protocol.get_state())
}
}
pub async fn pairwise_encrypt(
our_did_doc: &DidDocument,
their_did_doc: &DidDocument,
wallet: &impl BaseWallet,
message: &AriesMessage,
their_service_id: &Uri,
) -> AgentResult<EncryptionEnvelope> {
EncryptionEnvelope::create(
wallet,
serde_json::json!(message).to_string().as_bytes(),
our_did_doc,
their_did_doc,
their_service_id,
)
.await
.map_err(|err| {
AgentError::from_msg(
AgentErrorKind::InvalidState,
&format!("Failed to pairwise encrypt message due err: {err}"),
)
})
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/handlers/mod.rs | aries/agents/aries-vcx-agent/src/handlers/mod.rs | pub(crate) mod connection;
pub(crate) mod credential_definition;
pub(crate) mod did_exchange;
pub(crate) mod holder;
pub(crate) mod issuer;
pub(crate) mod out_of_band;
pub(crate) mod prover;
pub(crate) mod revocation_registry;
pub(crate) mod schema;
pub(crate) mod verifier;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/handlers/holder.rs | aries/agents/aries-vcx-agent/src/handlers/holder.rs | use std::sync::Arc;
use aries_vcx::{
did_parser_nom::Did,
handlers::issuance::holder::Holder,
messages::{
msg_fields::protocols::cred_issuance::v1::{
issue_credential::IssueCredentialV1, offer_credential::OfferCredentialV1,
propose_credential::ProposeCredentialV1,
},
AriesMessage,
},
protocols::{issuance::holder::state_machine::HolderState, SendClosure},
};
use aries_vcx_anoncreds::anoncreds::anoncreds::Anoncreds;
use aries_vcx_ledger::ledger::indy_vdr_ledger::DefaultIndyLedgerRead;
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use crate::{
error::*,
handlers::connection::ServiceConnections,
http::VcxHttpClient,
storage::{agent_storage_inmem::AgentStorageInMem, AgentStorage},
};
#[derive(Clone)]
struct HolderWrapper {
holder: Holder,
connection_id: String,
}
impl HolderWrapper {
pub fn new(holder: Holder, connection_id: &str) -> Self {
Self {
holder,
connection_id: connection_id.to_string(),
}
}
}
pub struct ServiceCredentialsHolder<T> {
ledger_read: Arc<DefaultIndyLedgerRead>,
anoncreds: Anoncreds,
wallet: Arc<T>,
creds_holder: AgentStorageInMem<HolderWrapper>,
service_connections: Arc<ServiceConnections<T>>,
}
impl<T: BaseWallet> ServiceCredentialsHolder<T> {
pub fn new(
ledger_read: Arc<DefaultIndyLedgerRead>,
anoncreds: Anoncreds,
wallet: Arc<T>,
service_connections: Arc<ServiceConnections<T>>,
) -> Self {
Self {
service_connections,
creds_holder: AgentStorageInMem::new("creds-holder"),
ledger_read,
anoncreds,
wallet,
}
}
fn get_holder(&self, thread_id: &str) -> AgentResult<Holder> {
let HolderWrapper { holder, .. } = self.creds_holder.get(thread_id)?;
Ok(holder)
}
pub fn get_connection_id(&self, thread_id: &str) -> AgentResult<String> {
let HolderWrapper { connection_id, .. } = self.creds_holder.get(thread_id)?;
Ok(connection_id)
}
pub async fn send_credential_proposal(
&self,
connection_id: &str,
propose_credential: ProposeCredentialV1,
) -> AgentResult<String> {
let holder = Holder::create_with_proposal("foobar", propose_credential)?;
let aries_msg: AriesMessage = holder.get_proposal()?.into();
self.service_connections
.send_message(connection_id, &aries_msg)
.await?;
self.creds_holder.insert(
&holder.get_thread_id()?,
HolderWrapper::new(holder, connection_id),
)
}
pub fn create_from_offer(
&self,
connection_id: &str,
offer: OfferCredentialV1,
) -> AgentResult<String> {
self.service_connections.get_by_id(connection_id)?;
let holder = Holder::create_from_offer("foobar", offer)?;
self.creds_holder.insert(
&holder.get_thread_id()?,
HolderWrapper::new(holder, connection_id),
)
}
pub async fn send_credential_request(&self, thread_id: &str) -> AgentResult<String> {
let connection_id = self.get_connection_id(thread_id)?;
let connection = self.service_connections.get_by_id(&connection_id)?;
// todo: technically doesn't need to be DID at all, and definitely need not to be pairwise
// DID
let pw_did_as_entropy = connection.pairwise_info().pw_did.to_string();
let mut holder = self.get_holder(thread_id)?;
let message = holder
.prepare_credential_request(
self.wallet.as_ref(),
self.ledger_read.as_ref(),
&self.anoncreds,
Did::parse(pw_did_as_entropy)?,
)
.await?;
self.service_connections
.send_message(&connection_id, &message)
.await?;
self.creds_holder.insert(
&holder.get_thread_id()?,
HolderWrapper::new(holder, &connection_id),
)
}
pub async fn process_credential(
&self,
thread_id: &str,
msg_issue_credential: IssueCredentialV1,
) -> AgentResult<String> {
let mut holder = self.get_holder(thread_id)?;
let connection_id = self.get_connection_id(thread_id)?;
let connection = self.service_connections.get_by_id(&connection_id)?;
holder
.process_credential(
self.wallet.as_ref(),
self.ledger_read.as_ref(),
&self.anoncreds,
msg_issue_credential.clone(),
)
.await?;
match holder.get_final_message()? {
None => {}
Some(msg_response) => {
let send_closure: SendClosure = Box::new(|msg: AriesMessage| {
Box::pin(async move {
connection
.send_message(self.wallet.as_ref(), &msg, &VcxHttpClient)
.await
})
});
send_closure(msg_response).await?;
}
}
self.creds_holder.insert(
&holder.get_thread_id()?,
HolderWrapper::new(holder, &connection_id),
)
}
pub fn get_state(&self, thread_id: &str) -> AgentResult<HolderState> {
Ok(self.get_holder(thread_id)?.get_state())
}
pub async fn is_revokable(&self, thread_id: &str) -> AgentResult<bool> {
self.get_holder(thread_id)?
.is_revokable(self.ledger_read.as_ref())
.await
.map_err(|err| err.into())
}
pub async fn get_rev_reg_id(&self, thread_id: &str) -> AgentResult<String> {
self.get_holder(thread_id)?
.get_rev_reg_id()
.map_err(|err| err.into())
}
pub async fn get_tails_hash(&self, thread_id: &str) -> AgentResult<String> {
self.get_holder(thread_id)?
.get_tails_hash()
.map_err(|err| err.into())
}
pub async fn get_tails_location(&self, thread_id: &str) -> AgentResult<String> {
self.get_holder(thread_id)?
.get_tails_location()
.map_err(|err| err.into())
}
pub fn exists_by_id(&self, thread_id: &str) -> bool {
self.creds_holder.contains_key(thread_id)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/handlers/verifier.rs | aries/agents/aries-vcx-agent/src/handlers/verifier.rs | use std::sync::Arc;
use anoncreds_types::data_types::messages::pres_request::PresentationRequest;
use aries_vcx::{
handlers::proof_presentation::verifier::Verifier,
messages::{
msg_fields::protocols::present_proof::v1::{
present::PresentationV1, propose::ProposePresentationV1,
},
AriesMessage,
},
protocols::{
proof_presentation::verifier::{
state_machine::VerifierState, verification_status::PresentationVerificationStatus,
},
SendClosure,
},
};
use aries_vcx_anoncreds::anoncreds::anoncreds::Anoncreds;
use aries_vcx_ledger::ledger::indy_vdr_ledger::DefaultIndyLedgerRead;
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use super::connection::ServiceConnections;
use crate::{
error::*,
http::VcxHttpClient,
storage::{agent_storage_inmem::AgentStorageInMem, AgentStorage},
};
#[derive(Clone)]
struct VerifierWrapper {
verifier: Verifier,
connection_id: String,
}
impl VerifierWrapper {
pub fn new(verifier: Verifier, connection_id: &str) -> Self {
Self {
verifier,
connection_id: connection_id.to_string(),
}
}
}
pub struct ServiceVerifier<T> {
ledger_read: Arc<DefaultIndyLedgerRead>,
anoncreds: Anoncreds,
wallet: Arc<T>,
verifiers: AgentStorageInMem<VerifierWrapper>,
service_connections: Arc<ServiceConnections<T>>,
}
impl<T: BaseWallet> ServiceVerifier<T> {
pub fn new(
ledger_read: Arc<DefaultIndyLedgerRead>,
anoncreds: Anoncreds,
wallet: Arc<T>,
service_connections: Arc<ServiceConnections<T>>,
) -> Self {
Self {
service_connections,
verifiers: AgentStorageInMem::new("verifiers"),
ledger_read,
anoncreds,
wallet,
}
}
pub async fn send_proof_request(
&self,
connection_id: &str,
request: PresentationRequest,
proposal: Option<ProposePresentationV1>,
) -> AgentResult<String> {
let connection = self.service_connections.get_by_id(connection_id)?;
let mut verifier = if let Some(proposal) = proposal {
Verifier::create_from_proposal("", &proposal)?
} else {
Verifier::create_from_request("".to_string(), &request)?
};
let send_closure: SendClosure = Box::new(|msg: AriesMessage| {
Box::pin(async move {
connection
.send_message(self.wallet.as_ref(), &msg, &VcxHttpClient)
.await
})
});
let message = verifier.mark_presentation_request_sent()?;
send_closure(message.into()).await?;
self.verifiers.insert(
&verifier.get_thread_id()?,
VerifierWrapper::new(verifier, connection_id),
)
}
pub fn get_presentation_status(
&self,
thread_id: &str,
) -> AgentResult<PresentationVerificationStatus> {
let VerifierWrapper { verifier, .. } = self.verifiers.get(thread_id)?;
Ok(verifier.get_verification_status())
}
pub async fn verify_presentation(
&self,
thread_id: &str,
presentation: PresentationV1,
) -> AgentResult<()> {
let VerifierWrapper {
mut verifier,
connection_id,
} = self.verifiers.get(thread_id)?;
let connection = self.service_connections.get_by_id(&connection_id)?;
let send_closure: SendClosure = Box::new(|msg: AriesMessage| {
Box::pin(async move {
connection
.send_message(self.wallet.as_ref(), &msg, &VcxHttpClient)
.await
})
});
let message = verifier
.verify_presentation(self.ledger_read.as_ref(), &self.anoncreds, presentation)
.await?;
send_closure(message).await?;
self.verifiers
.insert(thread_id, VerifierWrapper::new(verifier, &connection_id))?;
Ok(())
}
pub fn get_state(&self, thread_id: &str) -> AgentResult<VerifierState> {
let VerifierWrapper { verifier, .. } = self.verifiers.get(thread_id)?;
Ok(verifier.get_state())
}
pub fn exists_by_id(&self, thread_id: &str) -> bool {
self.verifiers.contains_key(thread_id)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/handlers/issuer.rs | aries/agents/aries-vcx-agent/src/handlers/issuer.rs | use std::sync::Arc;
use aries_vcx::{
handlers::{issuance::issuer::Issuer, util::OfferInfo},
messages::{
msg_fields::protocols::cred_issuance::v1::{
ack::AckCredentialV1, propose_credential::ProposeCredentialV1,
request_credential::RequestCredentialV1,
},
AriesMessage,
},
protocols::{issuance::issuer::state_machine::IssuerState, SendClosure},
};
use aries_vcx_anoncreds::anoncreds::anoncreds::Anoncreds;
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use crate::{
error::*,
handlers::connection::ServiceConnections,
http::VcxHttpClient,
storage::{agent_storage_inmem::AgentStorageInMem, AgentStorage},
};
#[derive(Clone)]
struct IssuerWrapper {
issuer: Issuer,
connection_id: String,
}
impl IssuerWrapper {
pub fn new(issuer: Issuer, connection_id: &str) -> Self {
Self {
issuer,
connection_id: connection_id.to_string(),
}
}
}
pub struct ServiceCredentialsIssuer<T> {
anoncreds: Anoncreds,
wallet: Arc<T>,
creds_issuer: AgentStorageInMem<IssuerWrapper>,
service_connections: Arc<ServiceConnections<T>>,
}
impl<T: BaseWallet> ServiceCredentialsIssuer<T> {
pub fn new(
anoncreds: Anoncreds,
wallet: Arc<T>,
service_connections: Arc<ServiceConnections<T>>,
) -> Self {
Self {
service_connections,
creds_issuer: AgentStorageInMem::new("creds-issuer"),
anoncreds,
wallet,
}
}
fn get_issuer(&self, thread_id: &str) -> AgentResult<Issuer> {
let IssuerWrapper { issuer, .. } = self.creds_issuer.get(thread_id)?;
Ok(issuer)
}
pub fn get_connection_id(&self, thread_id: &str) -> AgentResult<String> {
let IssuerWrapper { connection_id, .. } = self.creds_issuer.get(thread_id)?;
Ok(connection_id)
}
pub async fn accept_proposal(
&self,
connection_id: &str,
proposal: &ProposeCredentialV1,
) -> AgentResult<String> {
let issuer = Issuer::create_from_proposal("", proposal)?;
let thread_id = issuer.get_thread_id()?;
self.creds_issuer
.insert(&thread_id, IssuerWrapper::new(issuer, connection_id))?;
info!("Created new IssuerCredential with resource id: {thread_id}");
Ok(thread_id)
}
pub async fn send_credential_offer(
&self,
thread_id: Option<&str>,
connection_id: Option<&str>,
offer_info: OfferInfo,
) -> AgentResult<String> {
let (mut issuer, connection_id) = match (thread_id, connection_id) {
(Some(id), Some(connection_id)) => (self.get_issuer(id)?, connection_id.to_string()),
(Some(id), None) => (self.get_issuer(id)?, self.get_connection_id(id)?),
(None, Some(connection_id)) => (Issuer::create("")?, connection_id.to_string()),
(None, None) => return Err(AgentError::from_kind(AgentErrorKind::InvalidArguments)),
};
let connection = self.service_connections.get_by_id(&connection_id)?;
issuer
.build_credential_offer_msg(self.wallet.as_ref(), &self.anoncreds, offer_info, None)
.await?;
let send_closure: SendClosure = Box::new(|msg: AriesMessage| {
Box::pin(async move {
connection
.send_message(self.wallet.as_ref(), &msg, &VcxHttpClient)
.await
})
});
let credential_offer = issuer.get_credential_offer_msg()?;
send_closure(credential_offer).await?;
self.creds_issuer.insert(
&issuer.get_thread_id()?,
IssuerWrapper::new(issuer, &connection_id),
)
}
pub fn process_credential_request(
&self,
thread_id: &str,
request: RequestCredentialV1,
) -> AgentResult<()> {
let IssuerWrapper {
mut issuer,
connection_id,
} = self.creds_issuer.get(thread_id)?;
issuer.process_credential_request(request)?;
self.creds_issuer.insert(
&issuer.get_thread_id()?,
IssuerWrapper::new(issuer, &connection_id),
)?;
Ok(())
}
pub fn process_credential_ack(&self, thread_id: &str, ack: AckCredentialV1) -> AgentResult<()> {
let IssuerWrapper {
mut issuer,
connection_id,
} = self.creds_issuer.get(thread_id)?;
issuer.process_credential_ack(ack)?;
self.creds_issuer.insert(
&issuer.get_thread_id()?,
IssuerWrapper::new(issuer, &connection_id),
)?;
Ok(())
}
pub async fn send_credential(&self, thread_id: &str) -> AgentResult<()> {
let IssuerWrapper {
mut issuer,
connection_id,
} = self.creds_issuer.get(thread_id)?;
let connection = self.service_connections.get_by_id(&connection_id)?;
let send_closure: SendClosure = Box::new(|msg: AriesMessage| {
Box::pin(async move {
connection
.send_message(self.wallet.as_ref(), &msg, &VcxHttpClient)
.await
})
});
issuer
.build_credential(self.wallet.as_ref(), &self.anoncreds)
.await?;
match issuer.get_state() {
IssuerState::Failed => {
let problem_report = issuer.get_problem_report()?;
send_closure(problem_report.into()).await?;
}
_ => {
let msg_issue_credential = issuer.get_msg_issue_credential()?;
send_closure(msg_issue_credential.into()).await?;
}
}
self.creds_issuer.insert(
&issuer.get_thread_id()?,
IssuerWrapper::new(issuer, &connection_id),
)?;
Ok(())
}
pub fn get_state(&self, thread_id: &str) -> AgentResult<IssuerState> {
Ok(self.get_issuer(thread_id)?.get_state())
}
pub fn get_rev_reg_id(&self, thread_id: &str) -> AgentResult<String> {
let issuer = self.get_issuer(thread_id)?;
issuer.get_rev_reg_id().map_err(|err| err.into())
}
pub fn get_rev_id(&self, thread_id: &str) -> AgentResult<u32> {
let issuer = self.get_issuer(thread_id)?;
issuer.get_rev_id().map_err(|err| err.into())
}
pub fn get_proposal(&self, thread_id: &str) -> AgentResult<ProposeCredentialV1> {
let issuer = self.get_issuer(thread_id)?;
issuer.get_proposal().map_err(|err| err.into())
}
pub fn exists_by_id(&self, thread_id: &str) -> bool {
self.creds_issuer.contains_key(thread_id)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/handlers/credential_definition.rs | aries/agents/aries-vcx-agent/src/handlers/credential_definition.rs | use std::sync::{Arc, Mutex};
use anoncreds_types::data_types::identifiers::schema_id::SchemaId;
use aries_vcx::{common::primitives::credential_definition::CredentialDef, did_parser_nom::Did};
use aries_vcx_anoncreds::anoncreds::anoncreds::Anoncreds;
use aries_vcx_ledger::ledger::indy_vdr_ledger::{DefaultIndyLedgerRead, DefaultIndyLedgerWrite};
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use crate::{
error::*,
storage::{agent_storage_inmem::AgentStorageInMem, AgentStorage},
};
pub struct ServiceCredentialDefinitions<T> {
ledger_read: Arc<DefaultIndyLedgerRead>,
ledger_write: Arc<DefaultIndyLedgerWrite>,
anoncreds: Anoncreds,
wallet: Arc<T>,
cred_defs: AgentStorageInMem<CredentialDef>,
}
impl<T: BaseWallet> ServiceCredentialDefinitions<T> {
pub fn new(
ledger_read: Arc<DefaultIndyLedgerRead>,
ledger_write: Arc<DefaultIndyLedgerWrite>,
anoncreds: Anoncreds,
wallet: Arc<T>,
) -> Self {
Self {
cred_defs: AgentStorageInMem::new("cred-defs"),
ledger_read,
ledger_write,
anoncreds,
wallet,
}
}
pub async fn create_cred_def(
&self,
issuer_did: Did,
schema_id: SchemaId,
tag: String,
) -> AgentResult<String> {
let cd = CredentialDef::create(
self.wallet.as_ref(),
self.ledger_read.as_ref(),
&self.anoncreds,
"".to_string(),
issuer_did,
schema_id,
tag,
true,
)
.await?;
self.cred_defs.insert(&cd.get_cred_def_id().to_string(), cd)
}
pub async fn publish_cred_def(&self, thread_id: &str) -> AgentResult<()> {
let cred_def = self.cred_defs.get(thread_id)?;
let cred_def = cred_def
.publish_cred_def(
self.wallet.as_ref(),
self.ledger_read.as_ref(),
self.ledger_write.as_ref(),
)
.await?;
self.cred_defs.insert(thread_id, cred_def)?;
Ok(())
}
pub fn cred_def_json(&self, thread_id: &str) -> AgentResult<String> {
self.cred_defs
.get(thread_id)?
.get_data_json()
.map_err(|err| err.into())
}
pub fn find_by_schema_id(&self, schema_id: &str) -> AgentResult<Vec<String>> {
let schema_id = schema_id.to_string();
let f = |(id, m): (&String, &Mutex<CredentialDef>)| -> Option<String> {
let cred_def = m.lock().unwrap();
if cred_def.get_schema_id().to_string() == schema_id {
Some(id.clone())
} else {
None
}
};
self.cred_defs.find_by(f)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/agent/agent_struct.rs | aries/agents/aries-vcx-agent/src/agent/agent_struct.rs | use std::sync::Arc;
use aries_vcx_anoncreds::anoncreds::anoncreds::Anoncreds;
use aries_vcx_ledger::ledger::indy_vdr_ledger::{DefaultIndyLedgerRead, DefaultIndyLedgerWrite};
use aries_vcx_wallet::wallet::base_wallet::BaseWallet;
use crate::handlers::{
connection::ServiceConnections, credential_definition::ServiceCredentialDefinitions,
did_exchange::DidcommHandlerDidExchange, holder::ServiceCredentialsHolder,
issuer::ServiceCredentialsIssuer, out_of_band::ServiceOutOfBand, prover::ServiceProver,
revocation_registry::ServiceRevocationRegistries, schema::ServiceSchemas,
verifier::ServiceVerifier,
};
pub struct Agent<W> {
pub(super) issuer_did: String,
pub(super) ledger_read: Arc<DefaultIndyLedgerRead>,
pub(super) ledger_write: Arc<DefaultIndyLedgerWrite>,
pub(super) anoncreds: Anoncreds,
pub(super) wallet: Arc<W>,
pub(super) connections: Arc<ServiceConnections<W>>,
pub(super) schemas: Arc<ServiceSchemas<W>>,
pub(super) cred_defs: Arc<ServiceCredentialDefinitions<W>>,
pub(super) rev_regs: Arc<ServiceRevocationRegistries<W>>,
pub(super) holder: Arc<ServiceCredentialsHolder<W>>,
pub(super) issuer: Arc<ServiceCredentialsIssuer<W>>,
pub(super) verifier: Arc<ServiceVerifier<W>>,
pub(super) prover: Arc<ServiceProver<W>>,
pub(super) out_of_band: Arc<ServiceOutOfBand<W>>,
pub(super) did_exchange: Arc<DidcommHandlerDidExchange<W>>,
}
// Note: We do this manually, otherwise compiler is requesting us to implement Clone for generic
// type W, which is not in fact needed - W is wrapped in Arc. Underlying W has no reason to be
// cloned.
impl<W> Clone for Agent<W> {
fn clone(&self) -> Self {
Self {
issuer_did: self.issuer_did.clone(),
ledger_read: self.ledger_read.clone(),
ledger_write: self.ledger_write.clone(),
anoncreds: self.anoncreds,
wallet: self.wallet.clone(),
connections: self.connections.clone(),
schemas: self.schemas.clone(),
cred_defs: self.cred_defs.clone(),
rev_regs: self.rev_regs.clone(),
holder: self.holder.clone(),
issuer: self.issuer.clone(),
verifier: self.verifier.clone(),
prover: self.prover.clone(),
out_of_band: self.out_of_band.clone(),
did_exchange: self.did_exchange.clone(),
}
}
}
impl<T: BaseWallet> Agent<T> {
pub fn ledger_read(&self) -> &DefaultIndyLedgerRead {
&self.ledger_read
}
pub fn ledger_write(&self) -> &DefaultIndyLedgerWrite {
&self.ledger_write
}
pub fn anoncreds(&self) -> &Anoncreds {
&self.anoncreds
}
pub fn wallet(&self) -> Arc<T> {
self.wallet.clone()
}
pub fn issuer_did(&self) -> String {
self.issuer_did.clone()
}
pub fn connections(&self) -> Arc<ServiceConnections<T>> {
self.connections.clone()
}
pub fn out_of_band(&self) -> Arc<ServiceOutOfBand<T>> {
self.out_of_band.clone()
}
pub fn did_exchange(&self) -> Arc<DidcommHandlerDidExchange<T>> {
self.did_exchange.clone()
}
pub fn schemas(&self) -> Arc<ServiceSchemas<T>> {
self.schemas.clone()
}
pub fn cred_defs(&self) -> Arc<ServiceCredentialDefinitions<T>> {
self.cred_defs.clone()
}
pub fn rev_regs(&self) -> Arc<ServiceRevocationRegistries<T>> {
self.rev_regs.clone()
}
pub fn issuer(&self) -> Arc<ServiceCredentialsIssuer<T>> {
self.issuer.clone()
}
pub fn holder(&self) -> Arc<ServiceCredentialsHolder<T>> {
self.holder.clone()
}
pub fn verifier(&self) -> Arc<ServiceVerifier<T>> {
self.verifier.clone()
}
pub fn prover(&self) -> Arc<ServiceProver<T>> {
self.prover.clone()
}
pub fn public_did(&self) -> &str {
self.did_exchange.public_did()
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/agent/mod.rs | aries/agents/aries-vcx-agent/src/agent/mod.rs | mod agent_struct;
mod init;
pub use agent_struct::Agent;
pub use init::{build_askar_wallet, WalletInitConfig};
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/agents/aries-vcx-agent/src/agent/init.rs | aries/agents/aries-vcx-agent/src/agent/init.rs | use std::sync::Arc;
use aries_vcx::{
common::ledger::{
service_didsov::EndpointDidSov,
transactions::{add_new_did, write_endpoint},
},
did_doc::schema::service::typed::ServiceType,
did_parser_nom::Did,
global::settings::DEFAULT_LINK_SECRET_ALIAS,
};
use aries_vcx_anoncreds::{
self,
anoncreds::{anoncreds::Anoncreds, base_anoncreds::BaseAnonCreds},
errors::error::VcxAnoncredsError,
};
use aries_vcx_ledger::ledger::indy_vdr_ledger::{
build_ledger_components, DefaultIndyLedgerRead, VcxPoolConfig,
};
use aries_vcx_wallet::wallet::{
askar::{askar_wallet_config::AskarWalletConfig, key_method::KeyMethod, AskarWallet},
base_wallet::{issuer_config::IssuerConfig, BaseWallet, ManageWallet},
};
use did_peer::resolver::PeerDidResolver;
use did_resolver_registry::ResolverRegistry;
use did_resolver_sov::resolution::DidSovResolver;
use display_as_json::Display;
use serde::Serialize;
use url::Url;
use uuid::Uuid;
use crate::{
agent::agent_struct::Agent,
error::AgentResult,
handlers::{
connection::ServiceConnections, credential_definition::ServiceCredentialDefinitions,
did_exchange::DidcommHandlerDidExchange, holder::ServiceCredentialsHolder,
issuer::ServiceCredentialsIssuer, out_of_band::ServiceOutOfBand, prover::ServiceProver,
revocation_registry::ServiceRevocationRegistries, schema::ServiceSchemas,
verifier::ServiceVerifier,
},
};
#[derive(Serialize, Display)]
pub struct WalletInitConfig {
pub wallet_name: String,
pub wallet_key: String,
pub wallet_kdf: String,
}
pub async fn build_askar_wallet(
_wallet_config: WalletInitConfig,
issuer_seed: String,
) -> (AskarWallet, IssuerConfig) {
// TODO - use actual config with storage path etc
// simple in-memory wallet
let config_wallet = AskarWalletConfig::new(
"sqlite://:memory:",
KeyMethod::Unprotected,
"",
&Uuid::new_v4().to_string(),
);
let wallet = config_wallet.create_wallet().await.unwrap();
let config_issuer = wallet.configure_issuer(&issuer_seed).await.unwrap();
let anoncreds = Anoncreds;
if let Err(err) = anoncreds
.prover_create_link_secret(&wallet, &DEFAULT_LINK_SECRET_ALIAS.to_string())
.await
{
match err {
VcxAnoncredsError::DuplicationMasterSecret(_) => {} // ignore
_ => panic!("{}", err),
};
}
(wallet, config_issuer)
}
impl<W: BaseWallet> Agent<W> {
pub async fn setup_ledger(
genesis_path: String,
wallet: Arc<W>,
service_endpoint: Url,
submitter_did: Did,
create_new_issuer: bool,
) -> AgentResult<Did> {
let vcx_pool_config = VcxPoolConfig {
indy_vdr_config: None,
response_cache_config: None,
genesis_file_path: genesis_path,
};
let (_, ledger_write) = build_ledger_components(vcx_pool_config.clone()).unwrap();
let public_did = match create_new_issuer {
true => {
add_new_did(wallet.as_ref(), &ledger_write, &submitter_did, None)
.await?
.0
}
false => submitter_did,
};
let endpoint = EndpointDidSov::create()
.set_service_endpoint(service_endpoint.clone())
.set_types(Some(vec![ServiceType::DIDCommV1.to_string()]));
write_endpoint(wallet.as_ref(), &ledger_write, &public_did, &endpoint).await?;
info!(
"Agent::setup_ledger >> wrote data on ledger, public_did: {public_did}, endpoint: {service_endpoint}"
);
Ok(public_did)
}
pub async fn initialize(
genesis_path: String,
wallet: Arc<W>,
service_endpoint: Url,
issuer_did: Did,
) -> AgentResult<Agent<W>> {
info!("dev_build_profile_modular >>");
let vcx_pool_config = VcxPoolConfig {
indy_vdr_config: None,
response_cache_config: None,
genesis_file_path: genesis_path,
};
let anoncreds = Anoncreds;
let (ledger_read, ledger_write) = build_ledger_components(vcx_pool_config.clone()).unwrap();
let ledger_read = Arc::new(ledger_read);
let ledger_write = Arc::new(ledger_write);
let did_peer_resolver = PeerDidResolver::new();
let did_sov_resolver: DidSovResolver<Arc<DefaultIndyLedgerRead>, DefaultIndyLedgerRead> =
DidSovResolver::new(ledger_read.clone());
let did_resolver_registry = Arc::new(
ResolverRegistry::new()
.register_resolver("peer".into(), did_peer_resolver)
.register_resolver("sov".into(), did_sov_resolver),
);
let connections = Arc::new(ServiceConnections::new(
ledger_read.clone(),
wallet.clone(),
service_endpoint.clone(),
));
let did_exchange = Arc::new(DidcommHandlerDidExchange::new(
wallet.clone(),
did_resolver_registry,
service_endpoint.clone(),
issuer_did.to_string(),
));
let out_of_band = Arc::new(ServiceOutOfBand::new(wallet.clone(), service_endpoint));
let schemas = Arc::new(ServiceSchemas::new(
ledger_read.clone(),
ledger_write.clone(),
anoncreds,
wallet.clone(),
issuer_did.to_string(),
));
let cred_defs = Arc::new(ServiceCredentialDefinitions::new(
ledger_read.clone(),
ledger_write.clone(),
anoncreds,
wallet.clone(),
));
let rev_regs = Arc::new(ServiceRevocationRegistries::new(
ledger_write.clone(),
ledger_read.clone(),
anoncreds,
wallet.clone(),
issuer_did.to_string(),
));
let issuer = Arc::new(ServiceCredentialsIssuer::new(
anoncreds,
wallet.clone(),
connections.clone(),
));
let holder = Arc::new(ServiceCredentialsHolder::new(
ledger_read.clone(),
anoncreds,
wallet.clone(),
connections.clone(),
));
let verifier = Arc::new(ServiceVerifier::new(
ledger_read.clone(),
anoncreds,
wallet.clone(),
connections.clone(),
));
let prover = Arc::new(ServiceProver::new(
ledger_read.clone(),
anoncreds,
wallet.clone(),
connections.clone(),
));
Ok(Self {
ledger_read,
ledger_write,
anoncreds,
wallet,
connections,
did_exchange,
out_of_band,
schemas,
cred_defs,
rev_regs,
issuer,
holder,
verifier,
prover,
issuer_did: issuer_did.to_string(),
})
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/lib.rs | aries/aries_vcx/src/lib.rs | #![allow(clippy::result_large_err)]
#![allow(clippy::large_enum_variant)]
#![allow(clippy::diverging_sub_expression)]
//this is needed for some large json macro invocations
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate derive_builder;
pub extern crate did_doc;
pub extern crate did_parser_nom;
pub extern crate did_peer;
pub extern crate messages;
pub use aries_vcx_anoncreds;
pub use aries_vcx_wallet;
#[macro_use]
pub mod utils;
#[macro_use]
pub mod handlers;
pub mod global;
pub mod protocols;
pub mod common;
pub mod errors;
pub mod transport;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/transport.rs | aries/aries_vcx/src/transport.rs | use async_trait::async_trait;
use url::Url;
use crate::errors::error::VcxResult;
/// Trait used for implementing a mechanism to send a message, used by
/// [`crate::protocols::connection::Connection`].
#[async_trait]
pub trait Transport: Send + Sync {
async fn send_message(&self, msg: Vec<u8>, service_endpoint: &Url) -> VcxResult<()>;
}
// While in many cases the auto-dereferencing does the trick,
// this implementation aids in using things such as a trait object
// when a generic parameter is expected.
#[async_trait]
impl<T> Transport for &T
where
T: Transport + ?Sized,
{
async fn send_message(&self, msg: Vec<u8>, service_endpoint: &Url) -> VcxResult<()> {
self.send_message(msg, service_endpoint).await
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/global/settings.rs | aries/aries_vcx/src/global/settings.rs | pub static DEFAULT_GENESIS_PATH: &str = "genesis.txn";
pub static DEFAULT_LINK_SECRET_ALIAS: &str = "main";
pub static DEFAULT_DID: &str = "2hoqvcwupRTUNkXn6ArYzs";
pub static DEFAULT_WALLET_BACKUP_KEY: &str = "backup_wallet_key";
pub static DEFAULT_WALLET_KEY: &str = "8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY";
pub static WALLET_KDF_RAW: &str = "RAW";
pub static WALLET_KDF_ARGON2I_INT: &str = "ARGON2I_INT";
pub static WALLET_KDF_ARGON2I_MOD: &str = "ARGON2I_MOD";
pub static WALLET_KDF_DEFAULT: &str = WALLET_KDF_ARGON2I_MOD;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/global/mod.rs | aries/aries_vcx/src/global/mod.rs | pub mod settings;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/errors/mapping_wallet.rs | aries/aries_vcx/src/errors/mapping_wallet.rs | use aries_vcx_wallet::errors::error::VcxWalletError;
use super::error::{AriesVcxError, AriesVcxErrorKind};
impl From<VcxWalletError> for AriesVcxError {
fn from(value: VcxWalletError) -> Self {
match value {
VcxWalletError::DuplicateRecord(_) => Self::from_msg(
AriesVcxErrorKind::DuplicationWalletRecord,
value.to_string(),
),
VcxWalletError::RecordNotFound { .. } => {
Self::from_msg(AriesVcxErrorKind::WalletRecordNotFound, value.to_string())
}
VcxWalletError::UnknownRecordCategory(_) => {
Self::from_msg(AriesVcxErrorKind::InvalidInput, value.to_string())
}
VcxWalletError::InvalidInput(_) => {
Self::from_msg(AriesVcxErrorKind::InvalidInput, value.to_string())
}
VcxWalletError::NoRecipientKeyFound => {
Self::from_msg(AriesVcxErrorKind::WalletRecordNotFound, value.to_string())
}
VcxWalletError::InvalidJson(_) => {
Self::from_msg(AriesVcxErrorKind::InvalidJson, value.to_string())
}
VcxWalletError::PublicKeyError(_) => {
Self::from_msg(AriesVcxErrorKind::InvalidInput, value.to_string())
}
VcxWalletError::Unimplemented(_) => {
Self::from_msg(AriesVcxErrorKind::UnimplementedFeature, value.to_string())
}
VcxWalletError::Unknown(_) => {
Self::from_msg(AriesVcxErrorKind::UnknownError, value.to_string())
}
VcxWalletError::WalletCreate(_) => {
Self::from_msg(AriesVcxErrorKind::WalletCreate, value.to_string())
}
VcxWalletError::NotUtf8(_) => {
Self::from_msg(AriesVcxErrorKind::ParsingError, value.to_string())
}
VcxWalletError::NotBase58(_) => {
Self::from_msg(AriesVcxErrorKind::NotBase58, value.to_string())
}
VcxWalletError::NotBase64(_) => {
Self::from_msg(AriesVcxErrorKind::ParsingError, value.to_string())
}
// can be
#[allow(unreachable_patterns)]
_ => Self::from_msg(AriesVcxErrorKind::UnknownError, value.to_string()),
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/aries_vcx/src/errors/mapping_anoncreds.rs | aries/aries_vcx/src/errors/mapping_anoncreds.rs | use aries_vcx_anoncreds::errors::error::VcxAnoncredsError;
use super::error::{AriesVcxError, AriesVcxErrorKind};
impl From<VcxAnoncredsError> for AriesVcxError {
fn from(err: VcxAnoncredsError) -> Self {
match err {
VcxAnoncredsError::InvalidJson(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::InvalidJson, err)
}
VcxAnoncredsError::InvalidInput(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::InvalidInput, err)
}
VcxAnoncredsError::InvalidState(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::InvalidState, err)
}
VcxAnoncredsError::WalletError(inner) => inner.into(),
VcxAnoncredsError::UrsaError(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::UrsaError, err)
}
VcxAnoncredsError::IOError(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::IOError, err)
}
VcxAnoncredsError::UnknownError(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::UnknownError, err)
}
VcxAnoncredsError::ProofRejected(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::ProofRejected, err)
}
VcxAnoncredsError::ActionNotSupported(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::ActionNotSupported, err)
}
VcxAnoncredsError::InvalidProofRequest(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::InvalidProofRequest, err)
}
VcxAnoncredsError::InvalidAttributesStructure(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::InvalidAttributesStructure, err)
}
VcxAnoncredsError::InvalidOption(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::InvalidOption, err)
}
VcxAnoncredsError::InvalidSchema(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::InvalidSchema, err)
}
VcxAnoncredsError::DuplicationMasterSecret(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::DuplicationMasterSecret, err)
}
VcxAnoncredsError::UnimplementedFeature(_) => {
AriesVcxError::from_msg(AriesVcxErrorKind::UnimplementedFeature, err)
}
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.