Skip to content

Commit

Permalink
implement fetching all records for askar
Browse files Browse the repository at this point in the history
Signed-off-by: Ondrej Prazak <ondrej.prazak@absa.africa>
  • Loading branch information
Ondrej Prazak committed Feb 28, 2024
1 parent ed3c8c7 commit ea4a137
Show file tree
Hide file tree
Showing 16 changed files with 379 additions and 237 deletions.
3 changes: 1 addition & 2 deletions aries/agents/rust/aries-vcx-agent/src/agent/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,7 @@ impl Agent {
let ledger_write = Arc::new(ledger_write);

anoncreds
// .prover_create_link_secret(wallet.as_ref(), &DEFAULT_LINK_SECRET_ALIAS.to_string())
.prover_create_link_secret(&wallet, DEFAULT_LINK_SECRET_ALIAS)
.prover_create_link_secret(&wallet, &DEFAULT_LINK_SECRET_ALIAS.to_string())
.await
.unwrap();

Expand Down
31 changes: 31 additions & 0 deletions aries/aries_vcx_core/src/wallet/askar/all_askar_records.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use async_trait::async_trait;

use crate::{
errors::error::VcxCoreResult,
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) -> VcxCoreResult<Option<usize>> {
Ok(self.total_count)
}

async fn next(&mut self) -> VcxCoreResult<Option<PartialRecord>> {
Ok(self.iterator.next())
}
}
35 changes: 33 additions & 2 deletions aries/aries_vcx_core/src/wallet/askar/askar_record_wallet.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use aries_askar::entry::EntryTag;
use async_trait::async_trait;

use super::AskarWallet;
use super::{all_askar_records::AllAskarRecords, AskarWallet};
use crate::{
errors::error::{AriesVcxCoreError, AriesVcxCoreErrorKind, VcxCoreResult},
wallet::{
base_wallet::{
record::Record, record_category::RecordCategory, record_wallet::RecordWallet,
record::{AllRecords, PartialRecord, Record},
record_category::RecordCategory,
record_wallet::RecordWallet,
search_filter::SearchFilter,
},
record_tags::RecordTags,
Expand Down Expand Up @@ -132,4 +134,33 @@ impl RecordWallet for AskarWallet {
.into_iter()
.collect::<Result<_, _>>()?)
}

async fn all_records(&self) -> VcxCoreResult<Box<dyn AllRecords + Send>> {
let mut session = self.session().await?;

let recs = session.fetch_all(None, None, None, 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),
)))
}
}
16 changes: 15 additions & 1 deletion aries/aries_vcx_core/src/wallet/askar/askar_utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use aries_askar::kms::{KeyAlg, LocalKey};
use aries_askar::{
entry::Entry,
kms::{KeyAlg, LocalKey},
};
use public_key::{Key, KeyType};

use serde::Deserialize;

use crate::{
Expand All @@ -16,6 +20,10 @@ pub fn local_key_to_bs58_public_key(local_key: &LocalKey) -> VcxCoreResult<Strin
Ok(bs58::encode(local_key.to_public_bytes()?).into_string())
}

pub fn local_key_to_bs58_private_key(local_key: &LocalKey) -> VcxCoreResult<String> {
Ok(bs58::encode(local_key.to_secret_bytes()?).into_string())
}

pub fn local_key_to_public_key(local_key: &LocalKey) -> VcxCoreResult<Key> {
Ok(Key::new(
local_key.to_public_bytes()?.to_vec(),
Expand Down Expand Up @@ -53,3 +61,9 @@ pub fn bytes_to_string(vec: Vec<u8>) -> VcxCoreResult<String> {
String::from_utf8(vec)
.map_err(|err| AriesVcxCoreError::from_msg(AriesVcxCoreErrorKind::InvalidInput, err))
}

pub fn value_from_entry(entry: Entry) -> VcxCoreResult<String> {
Ok(std::str::from_utf8(&entry.value)
.map_err(|err| AriesVcxCoreError::from_msg(AriesVcxCoreErrorKind::WalletError, err))?
.to_string())
}
13 changes: 13 additions & 0 deletions aries/aries_vcx_core/src/wallet/askar/key_value.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
pub struct KeyValue {
verkey: String,
signkey: String,
}

impl KeyValue {
pub fn new(signkey: String, verkey: String) -> Self {
Self { signkey, verkey }
}
}
16 changes: 15 additions & 1 deletion aries/aries_vcx_core/src/wallet/askar/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,24 @@ use aries_askar::{
kms::{KeyAlg, KeyEntry, LocalKey},
PassKey, Session, Store, StoreKeyMethod,
};
use async_trait::async_trait;
use public_key::Key;

use self::{askar_utils::local_key_to_bs58_name, rng_method::RngMethod};
use super::base_wallet::{did_value::DidValue, record_category::RecordCategory, BaseWallet};

use crate::errors::error::{AriesVcxCoreError, AriesVcxCoreErrorKind, VcxCoreResult};

mod all_askar_records;
mod askar_did_wallet;
mod askar_record_wallet;
mod askar_utils;
mod entry;
mod entry_tags;
mod key_value;
mod pack;
mod packing_types;
mod partial_record;
mod rng_method;
mod sig_type;
mod unpack;
Expand All @@ -26,7 +31,16 @@ pub struct AskarWallet {
profile: String,
}

impl BaseWallet for AskarWallet {}
#[async_trait]
impl BaseWallet for AskarWallet {
async fn export_wallet(&self, _path: &str, _backup_key: &str) -> VcxCoreResult<()> {
todo!()
}

async fn close_wallet(&self) -> VcxCoreResult<()> {
todo!()
}
}

impl AskarWallet {
pub async fn create(
Expand Down
40 changes: 40 additions & 0 deletions aries/aries_vcx_core/src/wallet/askar/partial_record.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use crate::{
errors::error::VcxCoreResult,
wallet::{
askar::askar_utils::{local_key_to_bs58_private_key, local_key_to_bs58_public_key},
base_wallet::{record::PartialRecord, record_category::RecordCategory},
},
};

use super::{askar_utils::value_from_entry, key_value::KeyValue};

impl PartialRecord {
pub fn from_askar_entry(entry: aries_askar::entry::Entry) -> VcxCoreResult<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) -> VcxCoreResult<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())
}
}
48 changes: 47 additions & 1 deletion aries/aries_vcx_core/src/wallet/base_wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,15 @@ pub trait BaseWallet: RecordWallet + DidWallet + Send + Sync + std::fmt::Debug {

async fn close_wallet(&self) -> VcxCoreResult<()>;

async fn configure_issuer(&self, key_seed: &str) -> VcxCoreResult<IssuerConfig>;
async fn configure_issuer(&self, key_seed: &str) -> VcxCoreResult<IssuerConfig> {
Ok(IssuerConfig {
institution_did: self
.create_and_store_my_did(Some(key_seed), None)
.await?
.did()
.to_string(),
})
}
}

#[async_trait]
Expand All @@ -55,6 +63,8 @@ impl BaseWallet for Arc<dyn BaseWallet> {

#[cfg(test)]
mod tests {
use std::str::FromStr;

use super::BaseWallet;
use crate::{
errors::error::AriesVcxCoreErrorKind,
Expand Down Expand Up @@ -438,6 +448,42 @@ mod tests {
assert_eq!(value, res.value());
assert_eq!(&tags2, res.tags());
}

#[tokio::test]
async fn record_wallet_should_fetch_all() {
let wallet = build_test_wallet().await;

wallet
.create_and_store_my_did(Some(&random_seed()), None)
.await
.unwrap();

let mut res = wallet.all_records().await.unwrap();

if let Some(total_count) = res.total_count().unwrap() {
assert_eq!(2, total_count);
} else {
panic!("expected total count when fetching all records");
}

let mut key_count = 0;
let mut did_count = 0;

while let Some(record) = res.next().await.unwrap() {
if let Some(category) = record.category() {
match RecordCategory::from_str(&category).unwrap() {
RecordCategory::Did => did_count += 1,
RecordCategory::Key => key_count += 1,
_ => (),
}
} else {
panic!("expected record to have a category");
}
}

assert_eq!(1, key_count);
assert_eq!(1, did_count);
}
}

#[cfg(test)]
Expand Down
52 changes: 35 additions & 17 deletions aries/aries_vcx_core/src/wallet/base_wallet/record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,23 +58,41 @@ impl PartialRecord {
&self.tags
}

#[cfg(feature = "vdrtools_wallet")]
pub fn from_wallet_record(wallet_record: WalletRecord) -> Self {
use crate::wallet::indy::indy_tags::IndyTags;

let name = wallet_record.get_id().into();
let category = wallet_record.get_type();
let value = wallet_record.get_value();

let found_tags = wallet_record.get_tags();

Self::builder()
.name(name)
.category(category.map(Into::into))
.value(value.map(Into::into))
.tags(found_tags.map(|tags| IndyTags::new(tags.clone()).into_record_tags()))
.build()
}
// #[cfg(feature = "askar_wallet")]
// pub fn from_askar_entry(entry: aries_askar::entry::Entry) -> VcxCoreResult<Self> {
// use crate::wallet::askar::askar_utils::value_from_entry;

// 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())
// }

// #[cfg(feature = "askar_wallet")]
// pub fn from_askar_key_entry(key_entry: aries_askar::kms::KeyEntry) -> VcxCoreResult<Self> {
// use crate::wallet::askar::KeyValue;

// let local_key = key_entry.load_local_key()?;
// let name = key_entry.name();
// let tags = key_entry.tags_as_slice();

// // check for private key length!!!!
// 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(INDY_KEY.into()))
// .value(Some(value))
// .tags(Some(tags.to_vec().into()))
// .build())
// }
}

#[async_trait]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const REV_REG_DEF: &str = "VCX_REV_REG_DEF";
const REV_REG_DEF_PRIV: &str = "VCX_REV_REG_DEF_PRIV";
const DID: &str = "Indy::Did";
const TMP_DID: &str = "Indy::TemporaryDid";
const KEY: &str = "Indy::Key";

#[derive(Clone, Copy, Debug, Default)]
pub enum RecordCategory {
Expand All @@ -37,6 +38,7 @@ pub enum RecordCategory {
RevRegDefPriv,
Did,
TmpDid,
Key,
}

impl FromStr for RecordCategory {
Expand All @@ -58,6 +60,7 @@ impl FromStr for RecordCategory {
REV_REG_DEF_PRIV => Ok(RecordCategory::RevRegDefPriv),
DID => Ok(RecordCategory::Did),
TMP_DID => Ok(RecordCategory::TmpDid),
KEY => Ok(RecordCategory::Key),
_ => Err(Self::Err::from_msg(
AriesVcxCoreErrorKind::InvalidInput,
format!("unknown category: {}", s),
Expand All @@ -83,6 +86,7 @@ impl Display for RecordCategory {
RecordCategory::RevRegDefPriv => REV_REG_DEF_PRIV,
RecordCategory::Did => DID,
RecordCategory::TmpDid => TMP_DID,
RecordCategory::Key => KEY,
};

write!(f, "{}", value)
Expand Down
2 changes: 0 additions & 2 deletions aries/aries_vcx_core/src/wallet/constants.rs

This file was deleted.

2 changes: 1 addition & 1 deletion aries/aries_vcx_core/src/wallet/indy/indy_wallet_record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl IndyWalletRecord {

Ok(Self {
id: Some(record.name().into()),
record_type: Some(record.category().into()),
record_type: Some(record.category().to_string()),
value: Some(record.value().into()),
tags,
})
Expand Down
Loading

0 comments on commit ea4a137

Please sign in to comment.