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

Create and resolve did:key #25

Merged
merged 2 commits into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/dids/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ license-file.workspace = true
async-trait = "0.1.74"
crypto = { path = "../crypto" }
did-jwk = "0.1.1"
did-method-key = "0.2.2"
did-web = "0.2.2"
serde = { workspace = true }
serde_json = { workspace = true }
Expand Down
124 changes: 124 additions & 0 deletions crates/dids/src/method/key.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
use crate::did::Did;
use crate::method::{DidMethod, DidMethodError, DidResolutionResult};
use async_trait::async_trait;
use crypto::key::{Key, KeyType};
use crypto::key_manager::KeyManager;
use did_method_key::DIDKey as SpruceDidKeyMethod;
use ssi_dids::did_resolve::{DIDResolver, ResolutionInputMetadata};
use ssi_dids::{DIDMethod, Source};
use std::sync::Arc;

/// Concrete implementation for a did:key DID
pub struct DidKey {
uri: String,
key_manager: Arc<dyn KeyManager>,
}

pub struct DidKeyCreateOptions {
pub key_type: KeyType,
}

impl Did for DidKey {
fn uri(&self) -> &str {
&self.uri
}

fn key_manager(&self) -> &Arc<dyn KeyManager> {
&self.key_manager
}
}

#[async_trait]
impl DidMethod<DidKey, DidKeyCreateOptions> for DidKey {
const NAME: &'static str = "key";

fn create(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it make sense to add documentation to public facing functions?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't public. DidMethod is public, and it is documented here: https://github.com/TBD54566975/web5-rs/blob/main/crates/dids/src/method/mod.rs#L21-L42

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't public.

The implementation of DidMethod::create is being done via DidKey::create. Since the former is public, I thought that meant this method is public as well....

Anyways, I don't think it's important. My main concern is that there is no place in documentation that describes to consumers of the crate how to use DidKeyCreateOptions when creating a did of type key. While this is obvious for DidKey, it will become not so obvious for DidDht in the future.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can address this when we implement DidDht

key_manager: Arc<dyn KeyManager>,
options: DidKeyCreateOptions,
) -> Result<DidKey, DidMethodError> {
let key_alias = key_manager.generate_private_key(options.key_type)?;
let public_key =
key_manager
.get_public_key(&key_alias)?
.ok_or(DidMethodError::DidCreationFailure(
"PublicKey not found".to_string(),
))?;

let uri = SpruceDidKeyMethod
.generate(&Source::Key(public_key.jwk()))
.ok_or(DidMethodError::DidCreationFailure(
"Failed to generate did:key".to_string(),
))?;

Ok(DidKey { uri, key_manager })
}

async fn resolve_uri(did_uri: &str) -> DidResolutionResult {
let input_metadata = ResolutionInputMetadata::default();
let (did_resolution_metadata, did_document, did_document_metadata) =
SpruceDidKeyMethod.resolve(did_uri, &input_metadata).await;

DidResolutionResult {
did_resolution_metadata,
did_document,
did_document_metadata,
..Default::default()
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use crypto::key_manager::local_key_manager::LocalKeyManager;
use ssi_dids::did_resolve::ERROR_INVALID_DID;

fn create_did_key(key_type: KeyType) -> DidKey {
let key_manager = Arc::new(LocalKeyManager::new_in_memory());

DidKey::create(key_manager, DidKeyCreateOptions { key_type })
.expect("DidKey creation failed")
}

#[test]
fn create_produces_correct_uri() {
let did = create_did_key(KeyType::Ed25519);
assert!(did.uri.starts_with("did:key:"));
}

#[test]
fn create_each_key_type() {
create_did_key(KeyType::Ed25519);
create_did_key(KeyType::Secp256k1);
create_did_key(KeyType::Secp256r1);
}

#[tokio::test]
async fn instance_resolve() {
let did = create_did_key(KeyType::Ed25519);
let result = did.resolve().await;
assert!(result.did_resolution_metadata.error.is_none());

let did_document = result.did_document.unwrap();
assert_eq!(did_document.id, did.uri);
}

#[tokio::test]
async fn resolve_uri_success() {
let did = create_did_key(KeyType::Ed25519);
let result = DidKey::resolve_uri(&did.uri).await;
assert!(result.did_resolution_metadata.error.is_none());

let did_document = result.did_document.expect("did_document not found");
KendallWeihe marked this conversation as resolved.
Show resolved Hide resolved
assert_eq!(did_document.id, did.uri);
}

#[tokio::test]
async fn resolve_uri_failure() {
let result = DidKey::resolve_uri("did:key:does-not-exist").await;
assert_eq!(
result.did_resolution_metadata.error,
Some(ERROR_INVALID_DID.to_string())
);
}
}
1 change: 1 addition & 0 deletions crates/dids/src/method/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod jwk;
pub mod key;
pub mod web;

use crate::did::Did;
Expand Down
12 changes: 12 additions & 0 deletions crates/dids/src/resolver.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::method::jwk::DidJwk;
use crate::method::key::DidKey;
use crate::method::web::DidWeb;
use crate::method::DidMethod;
use serde::{Deserialize, Serialize};
Expand All @@ -19,6 +20,7 @@ impl DidResolver {

match method_name {
DidJwk::NAME => DidJwk::resolve_uri(did_uri).await,
DidKey::NAME => DidKey::resolve_uri(did_uri).await,
DidWeb::NAME => DidWeb::resolve_uri(did_uri).await,
_ => DidResolutionResult::from_error(ERROR_METHOD_NOT_SUPPORTED),
}
Expand Down Expand Up @@ -89,6 +91,16 @@ mod tests {
assert_eq!(did_document.id, did_uri);
}

#[tokio::test]
async fn resolve_did_key() {
let did_uri = "did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme";
let result = DidResolver::resolve_uri(did_uri).await;
assert!(result.did_resolution_metadata.error.is_none());

let did_document = result.did_document.unwrap();
assert_eq!(did_document.id, did_uri);
}

#[tokio::test]
async fn resolve_did_web() {
let did_uri = "did:web:tbd.website";
Expand Down