From 236c40c9609c0962edb4f05bb262fae6e6553672 Mon Sep 17 00:00:00 2001 From: Moriarty Date: Thu, 15 Dec 2022 17:32:39 +0100 Subject: [PATCH] chore: refactor and code review feedback Signed-off-by: Moriarty --- crates/agent/src/modules/wallet.rs | 24 +---- .../create_credential_definition.rs | 12 +-- .../src/automations/credential_offer.rs | 7 +- crates/cli/src/cli.rs | 6 +- crates/cli/src/help_strings.rs | 4 +- crates/cli/src/modules/basic_message.rs | 7 +- crates/cli/src/modules/connection.rs | 14 ++- crates/cli/src/modules/credential.rs | 3 +- .../cli/src/modules/credential_definition.rs | 15 +-- crates/cli/src/modules/feature.rs | 5 +- crates/cli/src/modules/multitenancy.rs | 8 +- crates/cli/src/modules/oob.rs | 6 +- crates/cli/src/modules/proof.rs | 3 +- crates/cli/src/modules/schema.rs | 6 +- crates/cli/src/modules/wallet.rs | 30 +++--- crates/cli/src/register.rs | 3 +- .../src/cloudagent/json_ld.rs | 91 +++++++++++++++++++ .../src/cloudagent/wallet.rs | 28 ++++-- crates/logger/src/lib.rs | 17 +++- crates/logger/src/macros.rs | 12 ++- 20 files changed, 215 insertions(+), 86 deletions(-) create mode 100644 crates/cloudagent-python/src/cloudagent/json_ld.rs diff --git a/crates/agent/src/modules/wallet.rs b/crates/agent/src/modules/wallet.rs index f165703b..80854520 100644 --- a/crates/agent/src/modules/wallet.rs +++ b/crates/agent/src/modules/wallet.rs @@ -9,7 +9,7 @@ pub struct Did { pub did: Option, // TODO: enum - /// The key type to query for eg. ed25519, bls1238g2 + /// The key type to query for eg. ed25519, bls12381g2 pub key_type: Option, // TODO: enum @@ -25,27 +25,11 @@ pub struct Did { pub verkey: Option, } -/// 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, -} - -/// Response from the cloudagent when requesting info about dids -/// of a wallet -#[derive(Debug, Deserialize, Serialize)] -pub struct DidResult { - /// Single definition information about a DID of a wallet - pub result: Did, -} - /// 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 + /// The key type to query for eg. ed25519, bls12381g2 pub key_type: String, } @@ -55,7 +39,7 @@ pub struct CreateLocalDidOptions { /// DID method to query for. e.g. sov to only fetch indy/sov DIDs Available values : key, sov pub method: String, - /// The key type to query for eg. ed25519, bls1238g2 + /// The key type to query for eg. ed25519, bls12381g2 pub options: KeyType, } @@ -66,7 +50,7 @@ pub struct DidEndpoint { pub did: String, /// The endpoint url - pub endpoint: String, + pub endpoint: Option, } /// Options that are supplied when querying a wallet for DIDs diff --git a/crates/automations/src/automations/create_credential_definition.rs b/crates/automations/src/automations/create_credential_definition.rs index bf7cc3d5..7c1e37cb 100644 --- a/crates/automations/src/automations/create_credential_definition.rs +++ b/crates/automations/src/automations/create_credential_definition.rs @@ -4,7 +4,6 @@ use siera_agent::modules::credential_definition::CredentialDefinitionModule; use siera_agent::modules::schema::{SchemaCreateOptions, SchemaModule}; use colored::Colorize; -use siera_logger::pretty_stringify_obj; use crate::error::Result; @@ -52,20 +51,19 @@ impl<'a> CreateCredentialDefinition<'a> { ..CredentialDefinitionCreateOptions::default() }; - log_info!("{} the credential definition...", "Registering".cyan()); + log!("{} the credential definition...", "Registering".cyan()); // Create or fetch the credential definition let credential_definition = CredentialDefinitionModule::create(agent, options).await?; - log_info!( + log!( "{} credential definition with id {}", "Created".green(), String::from(&credential_definition.credential_definition_id).green() ); - log!( - "{}", - pretty_stringify_obj(&credential_definition.credential_definition_id) + copy!("{}", &credential_definition.credential_definition_id); + log_json!( + {"credential_definition_id": &credential_definition.credential_definition_id} ); - copy!("{}", credential_definition.credential_definition_id); Ok(credential_definition) } } diff --git a/crates/automations/src/automations/credential_offer.rs b/crates/automations/src/automations/credential_offer.rs index 75ee8cea..9bb998e3 100644 --- a/crates/automations/src/automations/credential_offer.rs +++ b/crates/automations/src/automations/credential_offer.rs @@ -9,7 +9,6 @@ use siera_agent::modules::{ credential_definition::CredentialDefinitionModule, schema::SchemaModule, }; -use siera_logger::pretty_stringify_obj; use std::collections::HashMap; /// Credential offer Automation which offers an prebuilt credential to a connection @@ -52,7 +51,7 @@ impl CredentialOfferAutomation { let attribute_values: Vec = self.attributes.values().cloned().collect(); // Check if it as a valid connection - log_info!("{} the connection...", "Fetching".cyan()); + log!("{} the connection...", "Fetching".cyan()); let connection = ConnectionModule::get_by_id(&agent, self.connection_id.clone()).await?; if connection.state != "active" && connection.state != "response" { return Err(Error::ConnectionNotReady.into()); @@ -66,7 +65,7 @@ impl CredentialOfferAutomation { let credential_definition = create_credential_definition.execute(&agent).await?; - log_info!("{} the credential...", "Offering".cyan()); + log!("{} the credential...", "Offering".cyan()); let credential_offer_response = agent .send_offer(CredentialOfferOptions { keys: attribute_keys.iter().map(|x| String::from(*x)).collect(), @@ -78,7 +77,7 @@ impl CredentialOfferAutomation { log_trace!("Automation completed and offered a credential"); log_trace!("{:#?}", credential_offer_response); - log!("{}", pretty_stringify_obj(credential_offer_response)); + log_json!(credential_offer_response); Ok(()) } } diff --git a/crates/cli/src/cli.rs b/crates/cli/src/cli.rs index 616aaa68..27e02d21 100644 --- a/crates/cli/src/cli.rs +++ b/crates/cli/src/cli.rs @@ -42,6 +42,10 @@ pub struct Cli { #[clap(long, short, help = HelpStrings::Quiet, conflicts_with = "verbose", conflicts_with = "json")] pub quiet: bool, + /// Whether the output should be quiet + #[clap(long, short = 'j', help = HelpStrings::Quiet, conflicts_with = "verbose", conflicts_with = "quiet")] + pub json: bool, + /// Which config path to use instead of the default one #[clap(long, short = 'o', help = HelpStrings::Config)] pub config: Option, @@ -51,7 +55,7 @@ pub struct Cli { pub environment: String, /// Whether more verbose output should be printed - #[clap(long, short='v', help = HelpStrings::Verbose, parse(from_occurrences), conflicts_with = "quiet")] + #[clap(long, short='v', help = HelpStrings::Verbose, parse(from_occurrences), conflicts_with = "quiet", conflicts_with = "json")] pub verbose: usize, /// The main cli subcommands diff --git a/crates/cli/src/help_strings.rs b/crates/cli/src/help_strings.rs index 5703c7a5..ef75e41f 100644 --- a/crates/cli/src/help_strings.rs +++ b/crates/cli/src/help_strings.rs @@ -274,14 +274,14 @@ 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::WalletCreateOptions => "Key types are e.g. ed25519, bls1238g2", + Self::WalletCreateOptions => "Key types are e.g. ed25519, bls12381g2", Self::WalletEndpoint => "The endpoint url", Self::WalletEndpointType => "The endpoint type", 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", - Self::WalletListKeyType => "Key types are e.g. ed25519, bls1238g2", + Self::WalletListKeyType => "Key types are e.g. ed25519, bls12381g2", Self::WalletListMethod => "DID method to query for. e.g. sov to only fetch indy/sov DIDs Available values : key, sov", Self::WalletListPosture => "Whether DID is current public DID, posted to ledger but current public DID, or local to the wallet. Available values : public, posted, wallet_only", Self::WalletListVerkey => "The verification key of interest", diff --git a/crates/cli/src/modules/basic_message.rs b/crates/cli/src/modules/basic_message.rs index a4c08ee2..c79a13ed 100644 --- a/crates/cli/src/modules/basic_message.rs +++ b/crates/cli/src/modules/basic_message.rs @@ -3,7 +3,6 @@ use crate::help_strings::HelpStrings; use crate::utils::loader::{Loader, LoaderVariant}; use clap::Args; use siera_agent::modules::basic_message::{BasicMessageModule, SendBasicMessageOptions}; -use siera_logger::pretty_stringify_obj; /// Basic Message options and flags #[derive(Args)] @@ -28,9 +27,9 @@ pub async fn parse_basic_message_args( connection_id: options.connection_id.clone(), message: options.message.clone(), }; - agent.send_message(send_options).await.map(|response| { + agent.send_message(send_options).await.map(|_| { loader.stop(); - log_info!("Successfully sent message"); - log!("{}", pretty_stringify_obj(response)); + log!("Successfully sent message"); + log_json!({"status": "success"}); }) } diff --git a/crates/cli/src/modules/connection.rs b/crates/cli/src/modules/connection.rs index 1ec8cbc8..f2bd9b0e 100644 --- a/crates/cli/src/modules/connection.rs +++ b/crates/cli/src/modules/connection.rs @@ -117,13 +117,14 @@ pub async fn parse_connection_args( agent.create_invitation(options).await.map(|response| { loader.stop(); log_info!("Created invite with connection id:"); - log_info!("{}", response.id); + log!("{}", response.id); if *qr { log_info!("Scan this QR code to accept the invitation:\n"); print_qr_code(&response.invitation_url).unwrap(); } else { log_info!("Another agent can use this URL to accept your invitation:"); - log!("{}", pretty_stringify_obj(&response.invitation_url)); + log!("{}", &response.invitation_url); + log_json!({ "invitation_url": &response.invitation_url }); } copy!("{}", response.invitation_url); }) @@ -136,7 +137,8 @@ pub async fn parse_connection_args( .map(|connection| { log_debug!("{}", pretty_stringify_obj(&connection)); log_info!("Fetched connection id:"); - log!("{}", pretty_stringify_obj(connection.id)); + log!("{}", connection.id); + log_json!({ "connection_id": connection.id }); }) } ConnectionSubcommands::List { @@ -152,7 +154,8 @@ pub async fn parse_connection_args( Some(i) => agent.get_by_id(i.clone()).await.map(|connection| { loader.stop(); copy!("{}", pretty_stringify_obj(&connection)); - log!("{}", pretty_stringify_obj(connection)); + log!("{}", pretty_stringify_obj(&connection)); + log_json!({ "connection": connection }) }), None => { let options = ConnectionGetAllOptions { @@ -171,7 +174,8 @@ pub async fn parse_connection_args( agent.get_all(options).await.map(|connections| { loader.stop(); copy!("{}", pretty_stringify_obj(&connections)); - log!("{}", pretty_stringify_obj(connections)); + log!("{}", pretty_stringify_obj(&connections)); + log_json!({ "connections": connections }) }) } }, diff --git a/crates/cli/src/modules/credential.rs b/crates/cli/src/modules/credential.rs index ce26f6f2..bb95f57c 100644 --- a/crates/cli/src/modules/credential.rs +++ b/crates/cli/src/modules/credential.rs @@ -67,7 +67,8 @@ pub async fn parse_credentials_args( loader.stop(); log_debug!("{}", pretty_stringify_obj(&cred)); log_info!("Successfully offered a credential. Credential exchange id: ",); - log!("{}", pretty_stringify_obj(cred.credential_exchange_id)); + copy!("{}", cred.credential_exchange_id); + log_json!({ "credential_exchange_id": cred.credential_exchange_id }); }) } } diff --git a/crates/cli/src/modules/credential_definition.rs b/crates/cli/src/modules/credential_definition.rs index 4547147a..5a494133 100644 --- a/crates/cli/src/modules/credential_definition.rs +++ b/crates/cli/src/modules/credential_definition.rs @@ -74,10 +74,8 @@ pub async fn parse_credential_definition_args( loader.stop(); copy!("{}", cred_def.credential_definition_id); log_info!("Created credential definition with id:"); - log!( - "{}", - pretty_stringify_obj(cred_def.credential_definition_id) - ); + log!("{}", cred_def.credential_definition_id); + log_json!({ "credential_definition_id": cred_def.credential_definition_id }) }) } CredentialDefinitionSubcommands::List { id } => match id { @@ -92,13 +90,18 @@ pub async fn parse_credential_definition_args( }); log_debug!("{}", pretty_stringify_obj(&cred_def)); copy!("{}", pretty_stringify_obj(&loggable)); - log!("{}", pretty_stringify_obj(loggable)); + log!("{}", pretty_stringify_obj(&loggable)); + log_json!({ "credential_definition": loggable }) }), None => agent.get_all().await.map(|cred_defs| { loader.stop(); + cred_defs + .credential_definition_ids + .iter() + .for_each(|x| log!("{}", x)); log_info!("Successfully fetched credential definition IDs",); - log!("{}", pretty_stringify_obj(cred_defs)); + log_json!({ "credential_definitions": cred_defs }); }), }, } diff --git a/crates/cli/src/modules/feature.rs b/crates/cli/src/modules/feature.rs index 21dafd2b..0e07c7f0 100644 --- a/crates/cli/src/modules/feature.rs +++ b/crates/cli/src/modules/feature.rs @@ -16,6 +16,9 @@ pub async fn parse_features_args(agent: impl FeatureModule + Send + Sync) -> Res agent.discover_features().await.map(|features| { loader.stop(); log_debug!("{}", pretty_stringify_obj(&features)); - log!("{}", pretty_stringify_obj(&features.disclose.protocols)); + features.disclose.protocols.iter().for_each(|p| { + log!("{}", p.pid); + }); + log_json!({ "features": features.disclose.protocols }); }) } diff --git a/crates/cli/src/modules/multitenancy.rs b/crates/cli/src/modules/multitenancy.rs index b599d64b..5e04c1df 100644 --- a/crates/cli/src/modules/multitenancy.rs +++ b/crates/cli/src/modules/multitenancy.rs @@ -40,13 +40,15 @@ pub async fn parse_multitenancy_args( match &options.commands { MultitenancySubcommands::Create {} => agent.create().await.map(|response| { loader.stop(); - log!("{}", pretty_stringify_obj(response)); + copy!("{}", response.wallet_id); + log!("{}", pretty_stringify_obj(&response)); + log_json!(response); }), MultitenancySubcommands::Remove { wallet_id } => { agent.remove(wallet_id.clone()).await?; loader.stop(); - log_info!("Successfully removed wallet with id: {}", wallet_id); - log!("{}", pretty_stringify_obj(wallet_id)); + log!("Successfully removed wallet with id: {}", &wallet_id); + log_json!({ "wallet_id": wallet_id }); Ok(()) } } diff --git a/crates/cli/src/modules/oob.rs b/crates/cli/src/modules/oob.rs index 8d697fb2..2fc7e450 100644 --- a/crates/cli/src/modules/oob.rs +++ b/crates/cli/src/modules/oob.rs @@ -85,7 +85,8 @@ pub async fn parse_oob_args( print_qr_code(&response.invitation_url).unwrap(); } else { log_info!("Another agent can use this URL to accept your invitation:\n"); - log!("{}", pretty_stringify_obj(&response.invitation_url)); + log!("{}", &response.invitation_url); + log_json!({ "invitation_url": response.invitation_url }) } copy!("{}", response.invitation_url); }) @@ -98,7 +99,8 @@ pub async fn parse_oob_args( .map(|connection| { log_debug!("{}", pretty_stringify_obj(&connection)); log_info!("Fetched connection id:"); - log!("{}", pretty_stringify_obj(connection.connection_id)); + log!("{}", &connection.connection_id); + log_json!({ "connection_id": connection.connection_id}) }) } } diff --git a/crates/cli/src/modules/proof.rs b/crates/cli/src/modules/proof.rs index 480026cd..f719aaf4 100644 --- a/crates/cli/src/modules/proof.rs +++ b/crates/cli/src/modules/proof.rs @@ -76,7 +76,8 @@ pub async fn parse_proof_args( .map(|proof| { log_debug!("{}", pretty_stringify_obj(&proof)); log_info!("Successfully requested a proof. proof exchange id: ",); - log!("{}", pretty_stringify_obj(&proof.presentation_exchange_id)); + log!("{}", &proof.presentation_exchange_id); + log_json!({ "presentation_exchange_id": &proof.presentation_exchange_id }); copy!("{}", &proof.presentation_exchange_id); })?; loader.stop(); diff --git a/crates/cli/src/modules/schema.rs b/crates/cli/src/modules/schema.rs index 74813a0d..f42b1dd9 100644 --- a/crates/cli/src/modules/schema.rs +++ b/crates/cli/src/modules/schema.rs @@ -71,7 +71,8 @@ pub async fn parse_schema_args( .into_iter() .for_each(|name| log_info!("- {}", name)); log_info!("Schema id:"); - log!("{}", pretty_stringify_obj(&schema.id)); + log!("{}", &schema.id); + log_json!({ "schema_id": &schema.id }); copy!("{}", schema.id); }) } @@ -83,8 +84,9 @@ pub async fn parse_schema_args( }), None => agent.get_all().await.map(|schemas| { loader.stop(); + schemas.schema_ids.iter().for_each(|x| log!("{}", x)); log_info!("Successfully fetched schema IDs"); - log!("{}", pretty_stringify_obj(schemas.schema_ids)) + log_json!({ "schema_ids": schemas.schema_ids }) }), }, } diff --git a/crates/cli/src/modules/wallet.rs b/crates/cli/src/modules/wallet.rs index 6b4cd21a..e357adca 100644 --- a/crates/cli/src/modules/wallet.rs +++ b/crates/cli/src/modules/wallet.rs @@ -27,15 +27,15 @@ pub enum WalletSubcommands { did: Option, /// The key type of the wallet - #[clap(short, long, help=HelpStrings::WalletListKeyType, required = false)] + #[clap(short, long, help=HelpStrings::WalletListKeyType, required = false, possible_values=&["ed25519", "bls12381g2"])] key_type: Option, - /// The did method to query for - #[clap(short, long, help=HelpStrings::WalletListMethod, required = false)] + /// The did method to query for either 'key' or 'sov' + #[clap(short, long, help=HelpStrings::WalletListMethod, required = false, possible_values=&["key", "sov"])] method: Option, /// Available values : public, posted, wallet_only - #[clap(short, long, help=HelpStrings::WalletListPosture, required = false)] + #[clap(short, long, help=HelpStrings::WalletListPosture, required = false, possible_values=&["posted", "public", "wallet_only"])] posture: Option, /// The verification key of interest @@ -46,12 +46,12 @@ pub enum WalletSubcommands { /// Create a local DID #[clap(about = HelpStrings::WalletCreate)] CreateLocalDid { - /// The method to be used did or sov - #[clap(long, short, help=HelpStrings::WalletCreateMethod, required = true)] + /// The method to be used key or sov + #[clap(long, short, help=HelpStrings::WalletCreateMethod, required = true, possible_values=&["key", "sov"])] method: String, - /// The method to be used did or sov - #[clap(long, short, help=HelpStrings::WalletListKeyType, required = true)] + /// The key_type to be used ed25519 or bls12381g2 + #[clap(long, short, help=HelpStrings::WalletListKeyType, required = true, possible_values=&["ed25519", "bls12381g2"])] key_type: String, }, @@ -128,6 +128,7 @@ pub async fn parse_wallet_args( .iter() .for_each(|x| log!("{}", pretty_stringify_obj(x))); copy!("{}", pretty_stringify_obj(&response)); + log_json!(&response) }) } WalletSubcommands::CreateLocalDid { method, key_type } => { @@ -141,22 +142,24 @@ pub async fn parse_wallet_args( loader.stop(); log_info!("Successfully created local DID: ",); copy!("{}", pretty_stringify_obj(&response)); - log!("{}", pretty_stringify_obj(response)); + log!("{}", pretty_stringify_obj(&response)); + log_json!(response) }) } WalletSubcommands::RotateKeyPair { did } => { agent.rotate_keypair(did.clone()).await.map(|response| { loader.stop(); log_info!("Successfully rotated keypair for did DID {}: ", did); - copy!("{}", pretty_stringify_obj(response)); log!("{}", pretty_stringify_obj(response)); + log_json!(response) }) } WalletSubcommands::FetchPublicDid {} => agent.fetch_public_did().await.map(|response| { loader.stop(); log_info!("Wallet public DID: "); - copy!("{}", pretty_stringify_obj(&response)); - log!("{}", pretty_stringify_obj(&response)); + copy!("{}", pretty_stringify_obj(&response.did)); + log!("{}", pretty_stringify_obj(&response.did)); + log_json!(response) }), WalletSubcommands::AssignPublicDid { did } => { agent.assign_public_did(did.clone()).await.map(|response| { @@ -164,6 +167,7 @@ pub async fn parse_wallet_args( log_info!("Successfully assigned public DID: "); copy!("{}", pretty_stringify_obj(&response)); log!("{}", pretty_stringify_obj(&response)); + log_json!({"public_did": response.did }); }) } WalletSubcommands::FetchDidEndpoint { did } => { @@ -172,6 +176,7 @@ pub async fn parse_wallet_args( log_info!("DID endpoint for DID {}: ", did); copy!("{}", pretty_stringify_obj(&response)); log!("{}", pretty_stringify_obj(&response)); + log_json!(response) }) } WalletSubcommands::SetDidEndpoint { @@ -188,7 +193,6 @@ 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)); }) } } diff --git a/crates/cli/src/register.rs b/crates/cli/src/register.rs index c60365f1..c0185986 100644 --- a/crates/cli/src/register.rs +++ b/crates/cli/src/register.rs @@ -33,7 +33,8 @@ pub async fn register() -> Result<()> { _ => LogLevel::Warn, } }; - siera_logger::init(level, cli.copy); + + siera_logger::init(level, cli.copy, cli.json); log_trace!("Parsed CLI options and initialized logger"); diff --git a/crates/cloudagent-python/src/cloudagent/json_ld.rs b/crates/cloudagent-python/src/cloudagent/json_ld.rs new file mode 100644 index 00000000..9ac51663 --- /dev/null +++ b/crates/cloudagent-python/src/cloudagent/json_ld.rs @@ -0,0 +1,91 @@ +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; + +/// 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, +} + +/// Response from the cloudagent when requesting info about dids +/// of a wallet +#[derive(Debug, Deserialize, Serialize)] +pub struct DidResult { + /// Single definition information about a DID of a wallet + pub result: Did, +} + +#[async_trait] +impl WalletModule for CloudAgentPython { + async fn get_wallet_dids(&self, options: Did) -> Result> { + 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.results) + } + + async fn create_local_did(&self, options: CreateLocalDidOptions) -> Result { + let url = self.create_url(&["wallet", "did", "create"])?; + + let body = json!({ + + "method": options.method, + "options": options.options + }); + + let did_result: DidResult = self.post(url, None, Some(body)).await?; + + Ok(did_result.result) + } + + async fn rotate_keypair(&self, did: String) -> Result<()> { + let url = self.create_url(&["wallet", "did", "local", "rotate-keypair"])?; + + self.patch(url, Some(Vec::from([("did", did)]))).await + } + + async fn fetch_public_did(&self) -> Result { + let url = self.create_url(&["wallet", "did", "public"])?; + + let public_did: DidResult = self.get(url, None).await?; + + Ok(public_did.result) + } + + async fn assign_public_did(&self, did: String) -> Result { + let url = self.create_url(&["wallet", "did", "public"])?; + + let public_did_assign_result: DidResult = self + .post(url, Some(Vec::from([("did", did)])), None) + .await?; + + Ok(public_did_assign_result.result) + } + + async fn fetch_did_endpoint(&self, did: String) -> Result { + let url = self.create_url(&["wallet", "get-did-endpoint"])?; + + self.get(url, Some(Vec::from([("did", did)]))).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 + } +} diff --git a/crates/cloudagent-python/src/cloudagent/wallet.rs b/crates/cloudagent-python/src/cloudagent/wallet.rs index 075f94cd..82c7bd85 100644 --- a/crates/cloudagent-python/src/cloudagent/wallet.rs +++ b/crates/cloudagent-python/src/cloudagent/wallet.rs @@ -5,10 +5,24 @@ use serde::{Deserialize, Serialize}; use serde_json::json; use siera_agent::error::Result; use siera_agent::modules::wallet::{ - CreateLocalDidOptions, Did, DidEndpoint, DidList, DidResult, SetDidEndpointOptions, - WalletModule, + CreateLocalDidOptions, Did, DidEndpoint, SetDidEndpointOptions, WalletModule, }; +/// 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, +} + +/// Response from the cloudagent when requesting info about dids +/// of a wallet +#[derive(Debug, Deserialize, Serialize)] +pub struct DidResult { + /// Single definition information about a DID of a wallet + pub result: Did, +} /// Response from the cloudagent that contains the wrapped schema #[derive(Serialize, Deserialize, Debug)] struct Response { @@ -45,9 +59,7 @@ impl WalletModule for CloudAgentPython { async fn rotate_keypair(&self, did: String) -> Result<()> { let url = self.create_url(&["wallet", "did", "local", "rotate-keypair"])?; - let _rotated_keypair: DidResult = self.patch(url, Some(Vec::from([("did", did)]))).await?; - - Ok(()) + self.patch(url, Some(Vec::from([("did", did)]))).await } async fn fetch_public_did(&self) -> Result { @@ -69,11 +81,9 @@ impl WalletModule for CloudAgentPython { } async fn fetch_did_endpoint(&self, did: String) -> Result { - let url = self.create_url(&["wallet", "fetch-did-endpoint"])?; - - let did_endpoint: DidEndpoint = self.get(url, Some(Vec::from([("did", did)]))).await?; + let url = self.create_url(&["wallet", "get-did-endpoint"])?; - Ok(did_endpoint) + self.get(url, Some(Vec::from([("did", did)]))).await } async fn set_did_endpoint(&self, options: SetDidEndpointOptions) -> Result<()> { diff --git a/crates/logger/src/lib.rs b/crates/logger/src/lib.rs index cada9236..e18da145 100644 --- a/crates/logger/src/lib.rs +++ b/crates/logger/src/lib.rs @@ -3,6 +3,7 @@ #![deny(clippy::missing_docs_in_private_items)] +pub extern crate serde_json; use clipboard::{ClipboardContext, ClipboardProvider}; use colored::Colorize; use serde::Serialize; @@ -60,6 +61,9 @@ pub struct LoggerState { /// Whether the output that is being logged should also be copied pub should_copy: bool, + /// Whether the logger should log json (only) + pub should_json: bool, + /// The log level at the cli pub level: LogLevel, } @@ -67,10 +71,16 @@ pub struct LoggerState { impl LoggerState { /// Initialize the logger state #[must_use] - pub const fn new(init: bool, should_copy: bool, log_level: LogLevel) -> Self { + pub const fn new( + init: bool, + should_copy: bool, + should_json: bool, + log_level: LogLevel, + ) -> Self { Self { init, should_copy, + should_json, level: log_level, } } @@ -78,7 +88,7 @@ impl LoggerState { lazy_static! { /// Initialization of the state with default - pub static ref STATE: RwLock = RwLock::new(LoggerState::new(false, false, LogLevel::Off)); + pub static ref STATE: RwLock = RwLock::new(LoggerState::new(false, false, false, LogLevel::Off)); } /// Initialize the logger @@ -86,7 +96,7 @@ lazy_static! { /// # Panics /// /// When the logger is already initialized -pub fn init(level: LogLevel, should_copy: bool) { +pub fn init(level: LogLevel, should_copy: bool, should_json: bool) { assert!( !STATE.read().unwrap().init, "Logger should only be initialized once!" @@ -95,6 +105,7 @@ pub fn init(level: LogLevel, should_copy: bool) { let mut state = STATE.write().unwrap(); state.init = true; state.level = level; + state.should_json = should_json; state.should_copy = should_copy; } diff --git a/crates/logger/src/macros.rs b/crates/logger/src/macros.rs index e7f5ea1e..680af58d 100644 --- a/crates/logger/src/macros.rs +++ b/crates/logger/src/macros.rs @@ -28,12 +28,22 @@ macro_rules! elog { #[macro_export] macro_rules! log { ($($arg:tt)*) => { - if ::siera_logger::STATE.read().unwrap().level != ::siera_logger::LogLevel::Off { + if ::siera_logger::STATE.read().unwrap().level != ::siera_logger::LogLevel::Off && !::siera_logger::STATE.read().unwrap().should_json { println!($($arg)*); } }; } +/// Simple JSON logger +#[macro_export] +macro_rules! log_json { + ($($json:tt)+) => { + if ::siera_logger::STATE.read().unwrap().should_json { + println!("{}", ::siera_logger::pretty_stringify_obj(::siera_logger::serde_json::json!($($json)+))); + } + } +} + /// Generic logger. Should not be used outside of this file #[macro_export] macro_rules! internal_log {