Skip to content

Commit

Permalink
chore: refactor a little
Browse files Browse the repository at this point in the history
TODO:
* refactor and rename a a few things

Signed-off-by: Moriarty <[email protected]>
  • Loading branch information
Moriarty committed Dec 13, 2022
1 parent bb3d00f commit 2583dfa
Show file tree
Hide file tree
Showing 8 changed files with 129 additions and 48 deletions.
2 changes: 1 addition & 1 deletion crates/afj-rest/src/cloudagent/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use siera_agent::modules::connection::{
};

/// Create invitation response
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Response {
/// Invitation url
Expand Down
4 changes: 2 additions & 2 deletions crates/agent/src/modules/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub struct ConnectionGetAllOptions {
}

/// Create invitation response
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct Invitation {
/// Invitation url
#[serde(alias = "invitationUrl")]
Expand All @@ -46,7 +46,7 @@ pub struct Invitation {
}

/// A single connection structure
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Connection {
/// The connection id used for further functionality
#[serde(alias = "connection_id")]
Expand Down
29 changes: 17 additions & 12 deletions crates/agent/src/modules/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,43 +4,48 @@ use serde::{Deserialize, Serialize};

/// Options that are supplied when querying a wallet for DIDs
#[derive(Debug, Deserialize, Serialize)]
pub struct ListWalletOptions {
pub struct DidSpec {
/// The DID of interest
pub did: String,
pub did: Option<String>,

// TODO: enum
/// The key type to query for eg. ed25519, bls1238g2
pub key_type: String,
pub key_type: Option<String>,

// TODO: enum
/// DID method to query for. e.g. sov to only fetch indy/sov DIDs Available values : key, sov
pub method: String,
pub method: Option<String>,

// TODO: enum
/// Whether DID is current public DID, posted to ledger but current public DID, or local to the wallet
/// Available values : public, posted, wallet_only
pub posture: String,
pub posture: Option<String>,

/// The verification key of interest
pub verkey: String,
pub verkey: Option<String>,
}

/// Response from the cloudagent when requesting info about dids
/// of a wallet
#[derive(Debug, Deserialize, Serialize)]
pub struct DidList {
/// List of all the ids of every schema that the cloudagent has registered
pub results: Vec<ListWalletOptions>,
pub results: Vec<DidSpec>,
}

/// Response from the cloudagent when requesting info about dids
/// of a wallet
#[derive(Debug, Deserialize, Serialize)]
pub struct SingleDidResultResponse {
/// Single definition information about a DID of a wallet
pub result: ListWalletOptions,
pub result: DidSpec,
}

/// Key type in a JSON format k,v pair
#[derive(Debug, Deserialize, Serialize)]
pub struct KeyType {
// TODO: enum
/// The key type to query for eg. ed25519, bls1238g2
pub key_type: String,
}

Expand Down Expand Up @@ -81,7 +86,7 @@ pub struct SetDidEndpointOptions {
#[async_trait]
pub trait WalletModule {
/// Query a wallet for DIDs
async fn get_wallet_dids(&self, options: ListWalletOptions) -> Result<DidList>;
async fn get_wallet_dids(&self, options: DidSpec) -> Result<DidList>;

/// Create a local DID
async fn create_local_did(
Expand All @@ -93,13 +98,13 @@ pub trait WalletModule {
async fn rotate_keypair(&self, did: String) -> Result<()>;

/// Fetch public did
async fn fetch_public_did(&self) -> Result<SingleDidResultResponse>;
async fn fetch_public_did(&self) -> Result<DidSpec>;

/// Assign the current public DID
async fn assign_public(&self, did: String) -> Result<SingleDidResultResponse>;
async fn assign_public_did(&self, did: String) -> Result<DidSpec>;

/// Query DID endpoint of wallet
async fn get_did_endpoint(&self, did: String) -> Result<DidEndpointResult>;
async fn fetch_did_endpoint(&self, did: String) -> Result<DidEndpointResult>;

/// Set DID endpoint of wallet
async fn set_did_endpoint(&self, options: SetDidEndpointOptions) -> Result<()>;
Expand Down
2 changes: 1 addition & 1 deletion crates/cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ pub enum Commands {
/// Multitenancy subcommands
Multitenancy(MultitenancyOptions),

//? Wallet subcommands
/// Wallet subcommands
Wallet(WalletOptions),
}

Expand Down
6 changes: 3 additions & 3 deletions crates/cli/src/help_strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ pub enum HelpStrings {
WalletCreateOptions,
WalletEndpoint,
WalletEndpointType,
WalletGetEndpoint,
WalletFetchDidEndpoint,
WalletGetPublic,
WalletList,
WalletListDid,
Expand Down Expand Up @@ -273,11 +273,11 @@ impl HelpStrings {

Self::Wallet => "Interacts with a wallet",
Self::WalletCreate => "Create a local DID",
Self::WalletCreateMethod => "The did method. One of key or sov",
Self::WalletCreateMethod => "The did method. One of 'key' or 'sov'",
Self::WalletCreateOptions => "Key types are e.g. ed25519, bls1238g2",
Self::WalletEndpoint => "The endpoint url",
Self::WalletEndpointType => "The endpoint type",
Self::WalletGetEndpoint => "Get the endpoint information associated with a DID",
Self::WalletFetchDidEndpoint => "Get the endpoint information associated with a DID",
Self::WalletGetPublic => "Get the public DID of the wallet",
Self::WalletList => "Query for DID associated with a wallet",
Self::WalletListDid => "A DID to query for",
Expand Down
28 changes: 14 additions & 14 deletions crates/cli/src/modules/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::help_strings::HelpStrings;
use crate::utils::loader::{Loader, LoaderVariant};
use clap::{Args, Subcommand};
use siera_agent::modules::wallet::{
CreateLocalDidOptions, KeyType, ListWalletOptions, SetDidEndpointOptions, WalletModule,
CreateLocalDidOptions, DidSpec, KeyType, SetDidEndpointOptions, WalletModule,
};
use siera_logger::pretty_stringify_obj;

Expand Down Expand Up @@ -76,8 +76,8 @@ pub enum WalletSubcommands {
},

/// Get the DID endpoint
#[clap(about = HelpStrings::WalletGetEndpoint)]
GetDidEndpoint {
#[clap(about = HelpStrings::WalletFetchDidEndpoint)]
FetchDidEndpoint {
/// The DID to assign
#[clap(long, short, help=HelpStrings::WalletListDid)]
did: String,
Expand Down Expand Up @@ -114,12 +114,12 @@ pub async fn parse_wallet_args(
posture,
verkey,
} => {
let options = ListWalletOptions {
did: did.clone(),
key_type: key_type.clone(),
method: method.clone(),
posture: posture.clone(),
verkey: verkey.clone(),
let options = DidSpec {
did: did.clone().into(),
key_type: key_type.clone().into(),
method: method.clone().into(),
posture: posture.clone().into(),
verkey: verkey.clone().into(),
};
agent.get_wallet_dids(options).await.map(|response| {
loader.stop();
Expand Down Expand Up @@ -149,7 +149,7 @@ pub async fn parse_wallet_args(
agent.rotate_keypair(did.clone()).await.map(|response| {
loader.stop();
log_info!("Successfully rotated keypair for did DID {}: ", did);
copy!("{}", pretty_stringify_obj(&response));
copy!("{}", pretty_stringify_obj(response));
log!("{}", pretty_stringify_obj(response));
})
}
Expand All @@ -160,15 +160,15 @@ pub async fn parse_wallet_args(
log!("{}", pretty_stringify_obj(response));
}),
WalletSubcommands::AssignPublicDid { did } => {
agent.assign_public(did.clone()).await.map(|response| {
agent.assign_public_did(did.clone()).await.map(|response| {
loader.stop();
log_info!("Successfully assigned public DID: ");
copy!("{}", pretty_stringify_obj(&response));
log!("{}", pretty_stringify_obj(response));
})
}
WalletSubcommands::GetDidEndpoint { did } => {
agent.get_did_endpoint(did.clone()).await.map(|response| {
WalletSubcommands::FetchDidEndpoint { did } => {
agent.fetch_did_endpoint(did.clone()).await.map(|response| {
loader.stop();
log_info!("DID endpoint for DID {}: ", did);
copy!("{}", pretty_stringify_obj(&response));
Expand All @@ -189,7 +189,7 @@ pub async fn parse_wallet_args(
loader.stop();
log_info!("Set DID endpoint for DID {}: ", did);
log!("{}", pretty_stringify_obj(response));
copy!("{}", pretty_stringify_obj(&response));
copy!("{}", pretty_stringify_obj(response));
})
}
}
Expand Down
85 changes: 70 additions & 15 deletions crates/cloudagent-python/src/cloudagent/wallet.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,93 @@
use crate::agent::CloudAgentPython;
use crate::fill_query;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::json;
use siera_agent::error::Result;
use siera_agent::modules::wallet::{WalletCreate, WalletCreateOptions, WalletModule};
use siera_agent::modules::wallet::{
CreateLocalDidOptions, DidEndpointResult, DidList, DidSpec, SetDidEndpointOptions,
SingleDidResultResponse, WalletModule,
};

/// Response from the cloudagent that contains the wrapped schema
#[derive(Serialize, Deserialize, Debug)]
struct Response {
/// Schema wrapper
schema: Schema,
/// Wallet wrapper
result: DidSpec,
}

#[async_trait]
impl WalletModule for CloudAgentPython {
async fn create(&self, options: SchemaCreateOptions) -> Result<Schema> {
let url = self.create_url(&["schemas"])?;
async fn get_wallet_dids(&self, options: DidSpec) -> Result<DidList> {
let url = self.create_url(&["wallet", "did"])?;

let query = fill_query!(options, did, key_type, method, posture, verkey);

let did_list: DidList = self.get(url, Some(query)).await?;

Ok(did_list)
}

async fn create_local_did(
&self,
options: CreateLocalDidOptions,
) -> Result<SingleDidResultResponse> {
let url = self.create_url(&["wallet", "did", "create"])?;

let body = json!({
"attributes": options.attributes,
"schema_name": options.name,
"schema_version": options.version

"method": options.method,
"options": options.options
});

Ok(self.post::<Response>(url, None, Some(body)).await?.schema)
self.post(url, None, Some(body)).await
}

async fn rotate_keypair(&self, did: String) -> Result<()> {
let url = self.create_url(&["wallet", "did", "local", "rotate-keypair"])?;

let _rotated_keypair: SingleDidResultResponse =
self.patch(url, Some(Vec::from([("did", did)]))).await?;

Ok(())
}

async fn fetch_public_did(&self) -> Result<DidSpec> {
let url = self.create_url(&["wallet", "did", "public"])?;

let public_did: SingleDidResultResponse = self.get(url, None).await?;

Ok(public_did.result)
}

async fn assign_public_did(&self, did: String) -> Result<DidSpec> {
let url = self.create_url(&["wallet", "did", "public"])?;

let public_did_assign_result: SingleDidResultResponse = self
.post(url, Some(Vec::from([("did", did)])), None)
.await?;

Ok(public_did_assign_result.result)
}

async fn get_by_id(&self, id: String) -> Result<Schema> {
let url = self.create_url(&["schemas", &id])?;
Ok(self.get::<Response>(url, None).await?.schema)
async fn fetch_did_endpoint(&self, did: String) -> Result<DidEndpointResult> {
let url = self.create_url(&["wallet", "fetch-did-endpoint"])?;

let did_endpoint: DidEndpointResult =
self.get(url, Some(Vec::from([("did", did)]))).await?;

Ok(did_endpoint)
}

async fn get_all(&self) -> Result<SchemasGetAllResponse> {
let url = self.create_url(&["schemas", "created"])?;
self.get(url, None).await
async fn set_did_endpoint(&self, options: SetDidEndpointOptions) -> Result<()> {
let url = self.create_url(&["wallet", "set-did-endpoint"])?;

let body = json!({
"did": options.did,
"endpoint": options.endpoint,
"endpoint_type": options.endpoint_type
});

self.post(url, None, Some(body)).await
}
}
21 changes: 21 additions & 0 deletions crates/cloudagent-python/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,27 @@ impl CloudAgentPython {
self.send::<T>(client).await
}

/// Builds a patch request and calls the sender
///
/// # Errors
///
/// When it could not fulfill a PATCH request
pub async fn patch<T: DeserializeOwned + Debug>(
&self,
url: Url,
query: Option<Vec<(&str, String)>>,
) -> Result<T> {
let client = match &query {
Some(q) => Client::new().patch(url).query(&q),
None => Client::new().patch(url),
};

log_trace!("Patch request query:");
log_trace!("{:#?}", query);

self.send::<T>(client).await
}

/// Builds a post request and calls the sender
///
/// # Errors
Expand Down

0 comments on commit 2583dfa

Please sign in to comment.