Skip to content

Commit

Permalink
feat: new examples added (#28)
Browse files Browse the repository at this point in the history
* feat: add new exanples

* fix: make fmt happy

* fix: correct readme

* fix: refactor some examples
  • Loading branch information
anton-iskryzhytskyi authored Sep 17, 2024
1 parent f3a2c28 commit 37b8317
Show file tree
Hide file tree
Showing 8 changed files with 276 additions and 218 deletions.
13 changes: 10 additions & 3 deletions affinidi-messaging-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Use `<MEDIATOR_DID>` from [affinidi-messaging-mediator - Running affinidi-messag

```bash
# enable logging for examples,
export RUST_LOG=none,affinidi_messaging_sdk=debug,ping=debug,demo=debug
export RUST_LOG=none,affinidi_messaging_sdk=debug,ping=debug,demo=debug,send_message_to_me=debug,send_message_to_bob=debug,fetch_message_as_bob=debug

# no "did://" prefix for examples
export MEDIATOR_DID=<MEDIATOR_DID>
Expand All @@ -36,13 +36,20 @@ cargo run --example message_pickup -- \
--ssl-certificates $MEDIATOR_TLS_CERTIFICATES \
--mediator-did $MEDIATOR_DID

# send message to another DID
# send a message to the same recipient as sender
cargo run --example send_message_to_me -- \
--network-address $MEDIATOR_ENDPOINT \
--ssl-certificates $MEDIATOR_TLS_CERTIFICATES \
--mediator-did $MEDIATOR_DID

cargo run --example send_message -- \
# send a message to another recipient Bob
cargo run --example send_message_to_bob -- \
--network-address $MEDIATOR_ENDPOINT \
--ssl-certificates $MEDIATOR_TLS_CERTIFICATES \
--mediator-did $MEDIATOR_DID

# pickup a message from another sender Alice
cargo run --example fetch_message_as_bob -- \
--network-address $MEDIATOR_ENDPOINT \
--ssl-certificates $MEDIATOR_TLS_CERTIFICATES \
--mediator-did $MEDIATOR_DID
Expand Down
126 changes: 126 additions & 0 deletions affinidi-messaging-sdk/examples/common.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
use affinidi_messaging_sdk::{config::Config, conversions::secret_from_str, errors::ATMError, ATM};
use clap::{command, Parser};
use serde_json::{json, Value};
use tracing::info;
use tracing_subscriber::filter;

pub struct ExampleActorConfiguration {
pub verification_key: Value,
pub encryption_key: Value,
pub did: String,
}

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
#[arg(short, long)]
network_address: String,
#[arg(short, long)]
ssl_certificates: String,
#[arg(short, long)]
mediator_did: String,
}

pub struct ConfigureAtmResult {
pub atm: ATM<'static>,
pub atm_did: String,
pub actor_did: String,
}

pub fn alice_configuration() -> ExampleActorConfiguration {
ExampleActorConfiguration {
verification_key: json!({
"crv": "Ed25519",
"d": "LLWCf83n8VsUYq31zlZRe0NNMCcn1N4Dh85dGpIqSFw",
"kty": "OKP",
"x": "Hn8T4ZjjT0oJ6rjhqox8AykwC3GDFsJF6KkaYZExwQo"
}),
encryption_key: json!({
"crv": "secp256k1",
"d": "oi-dXG4EqfNODFPjv2vkieoLdbQZH9k6dwPDV8HDoms",
"kty": "EC",
"x": "DhfaXbhwo0KkOiyA5V1K1RZx6Ikr86h_lX5GOwxjmjE",
"y": "PpYqybOwMsm64vftt-7gBCQPIUbglMmyy_6rloSSAPk"
}),
did: String::from("did:peer:2.Vz6MkgWJfVmPELozq6aCycK3CpxHN8Upphn3WSuQkWY6iqsjF.EzQ3shfb7vwQaTJqFkt8nRfo7Nu98tmeYpdDfWgrqQitDaqXRz"),
}
}

pub fn bob_configuration() -> ExampleActorConfiguration {
ExampleActorConfiguration {
verification_key: json!({
"crv": "Ed25519",
"d": "FZMJijqdcp7PCQShgtFj6Ud3vjZY7jFZBVvahziaMMM",
"kty": "OKP",
"x": "PybG95kyeSfGRebp4T7hzA7JQuysc6mZ97nM2ety6Vo"
}),
encryption_key: json!({
"crv": "secp256k1",
"d": "ai7B5fgT3pCBHec0I4Y1xXpSyrEHlTy0hivSlddWHZE",
"kty": "EC",
"x": "k2FhEi8WMxr4Ztr4u2xjKzDESqVnGg_WKrN1820wPeA",
"y": "fq0DnZ_duPWyeFK0k93bAzjNJVVHEjHFRlGOJXKDS18"
}),
did: String::from("did:peer:2.Vz6Mkihn2R3M8nY62EFJ7MAVXu7YxsTnuS5iAhmn3qKJbkdFf.EzQ3shpZRBUtewwzYiueXgDqs1bvGNkSyGoRgsbZJXt3TTb9jD.SeyJ0IjoiZG0iLCJzIjp7InVyaSI6Imh0dHBzOi8vbG9jYWxob3N0OjcwMzcvIiwiYWNjZXB0IjpbImRpZGNvbW0vdjIiXSwicm91dGluZ19rZXlzIjpbXX0sImlkIjpudWxsfQ"),
}
}

pub async fn configure_atm(
example_configuration: ExampleActorConfiguration,
) -> Result<ConfigureAtmResult, ATMError> {
// **************************************************************
// *** Initial setup
// **************************************************************
let args = Args::parse();

// construct a subscriber that prints formatted traces to stdout
let subscriber = tracing_subscriber::fmt()
// Use a more compact, abbreviated log format
.with_env_filter(filter::EnvFilter::from_default_env())
.finish();
// use that subscriber to process traces emitted after this point
tracing::subscriber::set_global_default(subscriber).expect("Logging failed, exiting...");

info!("Running with address: {}", &args.network_address);
info!("Running with mediator_did: {}", &args.mediator_did);
info!("Running with ssl_certificates: {}", &args.ssl_certificates);

let atm_did = &args.mediator_did;

// TODO: in the future we likely want to pull this from the DID itself
let mut config = Config::builder()
.with_my_did(&example_configuration.did)
.with_atm_did(atm_did)
.with_websocket_disabled();

config = config
.with_atm_api(&args.network_address)
.with_ssl_certificates(&mut vec![args.ssl_certificates.into()]);

// Create a new ATM Client
let mut atm = ATM::new(config.build()?).await?;

// Add our secrets to ATM Client - stays local.
atm.add_secret(secret_from_str(
&format!("{}#key-1", &example_configuration.did),
&example_configuration.verification_key,
));
atm.add_secret(secret_from_str(
&format!("{}#key-2", &example_configuration.did),
&example_configuration.encryption_key,
));

Ok(ConfigureAtmResult {
atm,
atm_did: atm_did.clone(),
actor_did: example_configuration.did,
})
}

pub async fn configure_alice_atm() -> Result<ConfigureAtmResult, ATMError> {
configure_atm(alice_configuration()).await
}

pub async fn configure_bob_atm() -> Result<ConfigureAtmResult, ATMError> {
configure_atm(bob_configuration()).await
}
33 changes: 33 additions & 0 deletions affinidi-messaging-sdk/examples/fetch_message_as_bob.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use affinidi_messaging_sdk::messages::{fetch::FetchOptions, FetchDeletePolicy};
use std::error::Error;
use tracing::info;

mod common;

use common::{configure_bob_atm, ConfigureAtmResult};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let ConfigureAtmResult {
mut atm,
atm_did: _,
actor_did: _,
} = configure_bob_atm().await?;
// Get the messages from ATM
let msgs = atm
.fetch_messages(&FetchOptions {
limit: 10,
start_id: None,
delete_policy: FetchDeletePolicy::OnReceive,
})
.await?;

for msg in msgs.success {
let (received_msg_unpacked, _) = atm.unpack(&msg.msg.unwrap()).await?;
info!("Message received: {:?}", received_msg_unpacked);
}

info!("Ok");

Ok(())
}
7 changes: 5 additions & 2 deletions affinidi-messaging-sdk/examples/ping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ async fn main() -> Result<(), ATMError> {
// use that subscriber to process traces emitted after this point
tracing::subscriber::set_global_default(subscriber).expect("Logging failed, exiting...");

info!("Running with address: {}", &args.network_address);
info!("Running with mediator_did: {}", &args.mediator_did);
info!("Running with ssl_certificates: {}", &args.ssl_certificates);

let my_did = "did:peer:2.Vz6MkgWJfVmPELozq6aCycK3CpxHN8Upphn3WSuQkWY6iqsjF.EzQ3shfb7vwQaTJqFkt8nRfo7Nu98tmeYpdDfWgrqQitDaqXRz";
// Signing and verification key
let v1 = json!({
Expand Down Expand Up @@ -63,7 +67,6 @@ async fn main() -> Result<(), ATMError> {
.with_websocket_disabled()
.with_external_did_resolver(&did_resolver);

println!("Running with address: {}", &args.network_address);
config = config
.with_atm_api(&args.network_address)
.with_ssl_certificates(&mut vec![args.ssl_certificates.into()]);
Expand All @@ -80,7 +83,7 @@ async fn main() -> Result<(), ATMError> {
let start = SystemTime::now();

let well_know_res = atm.well_known_did_json().await?;
println!("DID: {}", well_know_res);
println!("did resolved: {:?}", well_know_res.data);

// You normally don't need to call authenticate() as it is called automatically
// We do this here so we can time the auth cycle
Expand Down
134 changes: 0 additions & 134 deletions affinidi-messaging-sdk/examples/send_message.rs

This file was deleted.

Loading

0 comments on commit 37b8317

Please sign in to comment.