Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor NetworkName #375

Merged
merged 7 commits into from Sep 2, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 7 additions & 5 deletions bindings/wasm/docs/api-reference.md
Expand Up @@ -1492,11 +1492,11 @@ Deserializes a `KeyPair` object from a JSON object.
* [Network](#Network)
* _instance_
* [.defaultNodeURL](#Network+defaultNodeURL) ⇒ <code>string</code> \| <code>undefined</code>
* [.explorerURL](#Network+explorerURL) ⇒ <code>string</code>
* [.explorerURL](#Network+explorerURL) ⇒ <code>string</code> \| <code>undefined</code>
* [.messageURL(message_id)](#Network+messageURL) ⇒ <code>string</code>
* [.toString()](#Network+toString) ⇒ <code>string</code>
* _static_
* [.from_name(string)](#Network.from_name) ⇒ [<code>Network</code>](#Network)
* [.from_name(name)](#Network.from_name) ⇒ [<code>Network</code>](#Network)
* [.mainnet()](#Network.mainnet) ⇒ [<code>Network</code>](#Network)
* [.testnet()](#Network.testnet) ⇒ [<code>Network</code>](#Network)

Expand All @@ -1508,7 +1508,7 @@ Returns the node URL of the Tangle network.
**Kind**: instance property of [<code>Network</code>](#Network)
<a name="Network+explorerURL"></a>

### network.explorerURL ⇒ <code>string</code>
### network.explorerURL ⇒ <code>string</code> \| <code>undefined</code>
Returns the web explorer URL of the Tangle network.

**Kind**: instance property of [<code>Network</code>](#Network)
Expand All @@ -1529,12 +1529,14 @@ Returns the web explorer URL of the given `message`.
**Kind**: instance method of [<code>Network</code>](#Network)
<a name="Network.from_name"></a>

### Network.from\_name(string) ⇒ [<code>Network</code>](#Network)
### Network.from\_name(name) ⇒ [<code>Network</code>](#Network)
Parses the provided string to a [`WasmNetwork`].

**Kind**: static method of [<code>Network</code>](#Network)

| Param | Type |
| --- | --- |
| string | <code>string</code> |
| name | <code>string</code> |

<a name="Network.mainnet"></a>

Expand Down
2 changes: 1 addition & 1 deletion bindings/wasm/src/did/wasm_document.rs
Expand Up @@ -67,7 +67,7 @@ impl WasmDocument {
let public: &PublicKey = keypair.0.public();

let did: IotaDID = if let Some(network) = network.as_deref() {
IotaDID::with_network(public.as_ref(), network).wasm_result()?
IotaDID::new_with_network(public.as_ref(), network).wasm_result()?
} else {
IotaDID::new(public.as_ref()).wasm_result()?
};
Expand Down
23 changes: 9 additions & 14 deletions bindings/wasm/src/tangle/network.rs
Expand Up @@ -2,21 +2,20 @@
// SPDX-License-Identifier: Apache-2.0

use identity::iota::Network as IotaNetwork;

use wasm_bindgen::prelude::*;

use crate::error::wasm_error;
use crate::error::{Result, WasmResult};

#[wasm_bindgen(js_name = Network)]
#[derive(Clone, Debug)]
pub struct WasmNetwork(IotaNetwork);

#[wasm_bindgen(js_class = Network)]
impl WasmNetwork {
/// Parses the provided string to a [`WasmNetwork`].
#[wasm_bindgen]
pub fn from_name(string: &str) -> Result<WasmNetwork, JsValue> {
let network = IotaNetwork::from_name(string).map_err(wasm_error)?;
Ok(Self(network))
pub fn from_name(name: String) -> Result<WasmNetwork> {
IotaNetwork::from_name(name).map(Self).wasm_result()
}

#[wasm_bindgen]
Expand All @@ -37,24 +36,20 @@ impl WasmNetwork {

/// Returns the web explorer URL of the Tangle network.
#[wasm_bindgen(getter = explorerURL)]
pub fn explorer_url(&self) -> Result<String, JsValue> {
self.0.explorer_url().map(|url| url.to_string()).map_err(wasm_error)
pub fn explorer_url(&self) -> Option<String> {
self.0.explorer_url().map(ToString::to_string)
}

/// Returns the web explorer URL of the given `message`.
#[wasm_bindgen(js_name = messageURL)]
pub fn message_url(&self, message_id: &str) -> Result<String, JsValue> {
self
.0
.message_url(message_id)
.map(|url| url.to_string())
.map_err(wasm_error)
pub fn message_url(&self, message_id: &str) -> Result<String> {
self.0.message_url(message_id).map(|url| url.to_string()).wasm_result()
}

#[allow(clippy::inherent_to_string, clippy::wrong_self_convention)]
#[wasm_bindgen(js_name = toString)]
pub fn to_string(&self) -> String {
self.0.name().into()
self.0.name_str().to_owned()
}
}

Expand Down
5 changes: 3 additions & 2 deletions identity-account/src/account/builder.rs
Expand Up @@ -4,6 +4,7 @@
use hashbrown::HashMap;
use identity_iota::tangle::ClientBuilder;
use identity_iota::tangle::Network;
use identity_iota::tangle::NetworkName;
#[cfg(feature = "stronghold")]
use std::path::PathBuf;
#[cfg(feature = "stronghold")]
Expand Down Expand Up @@ -35,7 +36,7 @@ pub enum AccountStorage {
pub struct AccountBuilder {
config: Config,
storage: AccountStorage,
clients: Option<HashMap<Network, ClientBuilder>>,
clients: Option<HashMap<NetworkName, ClientBuilder>>,
}

impl AccountBuilder {
Expand Down Expand Up @@ -80,7 +81,7 @@ impl AccountBuilder {
self
.clients
.get_or_insert_with(HashMap::new)
.insert(network.clone(), f(ClientBuilder::new().network(network)));
.insert(network.name(), f(ClientBuilder::new().network(network)));
self
}

Expand Down
37 changes: 36 additions & 1 deletion identity-account/tests/commands.rs
Expand Up @@ -7,12 +7,13 @@ use identity_account::error::Error;
use identity_account::error::Result;
use identity_account::events::Command;
use identity_account::events::CommandError;
use identity_account::identity::IdentityId;
use identity_account::identity::IdentitySnapshot;
use identity_account::identity::TinyMethod;
use identity_account::identity::{IdentityCreate, IdentityId};
use identity_account::storage::MemStore;
use identity_account::types::Generation;
use identity_core::common::UnixTimestamp;
use identity_core::crypto::KeyType;
use identity_did::verification::MethodType;

async fn new_account() -> Result<Account> {
Expand Down Expand Up @@ -78,6 +79,40 @@ async fn test_create_identity_invalid_method() -> Result<()> {
Ok(())
}

#[tokio::test]
async fn test_create_identity_network() -> Result<()> {
let account: Account = new_account().await?;

// Create an identity with a valid network string
let create_identity: IdentityCreate = IdentityCreate::new().network("test").key_type(KeyType::Ed25519);
let snapshot: IdentitySnapshot = account.create_identity(create_identity).await?;

// Ensure the identity creation was successful
assert!(snapshot.identity().did().is_some());
assert!(snapshot.identity().authentication().is_ok());

Ok(())
}

#[tokio::test]
async fn test_create_identity_invalid_network() -> Result<()> {
let account: Account = new_account().await?;

// Attempt to create an identity with an invalid network string
let create_identity: IdentityCreate = IdentityCreate::new()
.network("Invalid=Network!")
.key_type(KeyType::Ed25519);
let result = account.create_identity(create_identity).await;

// Ensure an `InvalidNetworkName` error is thrown
assert!(matches!(
result.unwrap_err(),
Error::IotaError(identity_iota::Error::InvalidNetworkName(_)),
));

Ok(())
}

#[tokio::test]
async fn test_create_identity_already_exists() -> Result<()> {
let account: Account = new_account().await?;
Expand Down
2 changes: 1 addition & 1 deletion identity-iota/src/did/doc/iota_verification_method.rs
Expand Up @@ -78,7 +78,7 @@ impl IotaVerificationMethod {
F: Into<Option<&'a str>>,
{
let key: &[u8] = keypair.public().as_ref();
let did: IotaDID = IotaDID::with_network(key, network)?;
let did: IotaDID = IotaDID::new_with_network(key, network)?;

Self::from_did(did, keypair, fragment)
}
Expand Down
26 changes: 6 additions & 20 deletions identity-iota/src/did/macros.rs
Expand Up @@ -3,41 +3,27 @@

/// Creates a new IOTA DID from a `public` key and optional `network`.
///
/// # Panics
/// # Errors
///
/// Panics if the DID format is not valid.
/// Errors if the [`IotaDID`][crate::did::IotaDID] is invalid.
///
/// # Example
///
/// ```
/// # use identity_iota::did;
/// # use identity_iota::try_did;
/// #
/// let did = did!(b"public-key");
/// let did = try_did!(b"public-key").unwrap();
/// assert_eq!(did.as_str(), "did:iota:2xQiiGHDq5gCi1H7utY1ni7cf65fTay3G11S4xKp1vkS");
///
/// let did = did!(b"public-key", "com");
/// let did = try_did!(b"public-key", "com").unwrap();
/// assert_eq!(
/// did.as_str(),
/// "did:iota:com:2xQiiGHDq5gCi1H7utY1ni7cf65fTay3G11S4xKp1vkS"
/// );
/// ```
#[macro_export]
macro_rules! did {
cycraig marked this conversation as resolved.
Show resolved Hide resolved
// Defining explicit branches rather than `$($tt:tt)+` gives much better docs.
($public:expr, $network:expr) => {
$crate::try_did!($public, $network).unwrap()
};
($public:expr, $network:expr) => {
$crate::try_did!($public, $network).unwrap()
};
($public:expr) => {
$crate::try_did!($public).unwrap()
};
}

/// A fallible version of the [did] macro.
#[macro_export]
macro_rules! try_did {
// Defining explicit branches rather than `$($tt:tt)+` gives much better docs.
($public:expr, $network:expr) => {
$crate::did::IotaDID::parse(format!(
"{}:{}:{}:{}",
Expand Down