Skip to content

Commit

Permalink
Fix test
Browse files Browse the repository at this point in the history
Signed-off-by: Patrik Stas <patrik.stas@absa.africa>
  • Loading branch information
Patrik-Stas committed Jan 4, 2024
1 parent 004e629 commit 946d775
Show file tree
Hide file tree
Showing 10 changed files with 127 additions and 128 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,13 @@ pub async fn create_our_did_document(
service_endpoint: Url,
routing_keys: Vec<String>,
) -> Result<(DidDocument, Key), AriesVcxError> {
let key_ver = generate_keypair(wallet, KeyType::Ed25519).await?;
let key_enc = generate_keypair(wallet, KeyType::Ed25519).await?;

let service: Service = ServiceDidCommV1::new(
Uri::new("#0")?,
service_endpoint,
0,
vec![ServiceKeyKind::DidKey(key_enc.clone().try_into()?)],
vec![],
routing_keys
.into_iter()
.map(ServiceKeyKind::Value)
Expand All @@ -84,12 +83,7 @@ pub async fn create_our_did_document(
.try_into()?;

info!("Prepared service for peer:did:2 generation: {} ", service);
let mut did_document = did_doc_from_keys(
Default::default(),
key_ver.clone(),
key_enc.clone(),
service,
)?;
let mut did_document = did_doc_from_keys(Default::default(), key_enc.clone(), service)?;
info!(
"Created did document for peer:did:2 generation: {} ",
did_document
Expand All @@ -101,19 +95,10 @@ pub async fn create_our_did_document(

fn did_doc_from_keys(
did: Did,
key_ver: Key,
key_enc: Key,
service: Service,
) -> Result<DidDocument, AriesVcxError> {
let vm_ver_id = DidUrl::from_fragment(key_ver.short_prefixless_fingerprint())?;
let vm_ka_id = DidUrl::from_fragment(key_enc.short_prefixless_fingerprint())?;
let vm_ver = VerificationMethod::builder(
vm_ver_id,
did.clone(),
VerificationMethodType::Ed25519VerificationKey2020,
)
.add_public_key_base58(key_ver.base58())
.build();
let vm_ka = VerificationMethod::builder(
vm_ka_id,
did.clone(),
Expand All @@ -123,8 +108,6 @@ fn did_doc_from_keys(
.build();
Ok(DidDocument::builder(did)
.add_service(service)
.add_verification_method(vm_ver)
// TODO: Include just reference
.add_key_agreement(vm_ka)
.build())
}
Expand Down Expand Up @@ -230,18 +213,12 @@ mod tests {

#[tokio::test]
async fn test_did_doc_from_keys() {
let key_ver = Key::new(
"7MV7mTpzQekW39mXdPXKnRJn79kkzMvmtaSHZWUSbvt5".into(),
KeyType::Ed25519,
)
.unwrap();
let key_enc = Key::new(
"tyntrez7bCthPqvZUDGwhYB1bSe9HzpLdSeHFpuSwst".into(),
KeyType::Ed25519,
)
.unwrap();

let recipient_keys = vec![ServiceKeyKind::DidKey(key_enc.clone().try_into().unwrap())];
let service_endpoint = Url::parse("http://example.com").unwrap();
let routing_keys = vec![
ServiceKeyKind::Value("routing_key1".into()),
Expand All @@ -251,15 +228,15 @@ mod tests {
Uri::new("#service-0").unwrap(),
service_endpoint.clone(),
0,
recipient_keys,
vec![],
routing_keys,
)
.try_into()
.unwrap();

let did = Did::default();

let result = did_doc_from_keys(did, key_ver.clone(), key_enc.clone(), service);
let result = did_doc_from_keys(did, key_enc.clone(), service);

assert!(result.is_ok());
let did_doc = result.unwrap();
Expand All @@ -280,10 +257,6 @@ mod tests {
.collect::<Vec<_>>()
})
.unwrap();
assert_eq!(
recipient_keys,
vec!["did:key:z6s8D3GAEHVteQMfhS4qBibNXjqS5D79NykfpGdF2VLmAtEysDRs6PEVBChSTTZ"]
);
assert_eq!(
ddo_service.extra_field_routing_keys().unwrap(),
vec![
Expand All @@ -292,10 +265,7 @@ mod tests {
]
);

assert_eq!(did_doc.verification_method().len(), 1);
let verification_method = did_doc.verification_method().first().unwrap();
assert_eq!(verification_method.public_key().unwrap(), key_ver);

println!("did_doc: {}", did_doc);
assert_eq!(did_doc.key_agreement().len(), 1);
match did_doc.key_agreement().first().unwrap() {
VerificationMethodKind::Resolved(key_agreement) => {
Expand Down
105 changes: 58 additions & 47 deletions aries/aries_vcx/src/utils/didcomm_utils.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
use did_doc::schema::{did_doc::DidDocument, service::extra_fields::ServiceKeyKind};
use did_doc::schema::{
did_doc::{diddoc_resolve_first_key_agreement, DidDocument},
service::extra_fields::ServiceKeyKind,
};
use public_key::Key;

use crate::errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult};

fn service_key_to_naked_key(key: &ServiceKeyKind, did_document: &DidDocument) -> VcxResult<String> {
fn resolve_service_key_to_typed_key(
key: &ServiceKeyKind,
did_document: &DidDocument,
) -> VcxResult<Key> {
match key {
ServiceKeyKind::DidKey(did_key) => Ok(did_key.key().base58()),
ServiceKeyKind::DidKey(did_key) => Ok(did_key.key().clone()),
ServiceKeyKind::Reference(reference) => {
let verification_method = did_document.dereference_key(reference).ok_or_else(|| {
AriesVcxError::from_msg(
Expand All @@ -18,44 +25,48 @@ fn service_key_to_naked_key(key: &ServiceKeyKind, did_document: &DidDocument) ->
format!("Unable to get public key from verification method: {}", err),
)
})?;
Ok(key.base58())
Ok(key)
}
ServiceKeyKind::Value(value) => Ok(String::from(value)),
ServiceKeyKind::Value(value) => Ok(Key::new(
value.as_bytes().to_vec(),
public_key::KeyType::Ed25519,
)?),
}
}

pub fn get_sender_verkey(did_document: &DidDocument) -> VcxResult<String> {
let service = did_document
.service()
.first()
.ok_or_else(|| {
AriesVcxError::from_msg(
AriesVcxErrorKind::InvalidState,
"No Service object found on our did document",
)
})?
.clone();
let sender_vk = service
.extra_field_recipient_keys()
.map_err(|err| {
AriesVcxError::from_msg(
AriesVcxErrorKind::InvalidState,
format!(
"Recipient key field found in our did document but had unexpected format, \
err: {err:?}"
),
)
})?
.first()
.ok_or_else(|| {
AriesVcxError::from_msg(
AriesVcxErrorKind::InvalidState,
"Recipient key field but did not have any keys",
)
})?
.clone();
let naked_sender_vk = service_key_to_naked_key(&sender_vk, did_document)?;
Ok(naked_sender_vk)
pub fn resolve_base58_key_agreement(did_document: &DidDocument) -> VcxResult<String> {
// note: we possibly don't want to support this, instead rely on key_agreement field
// let service = did_document
// .service()
// .first()
// .ok_or_else(|| {
// AriesVcxError::from_msg(
// AriesVcxErrorKind::InvalidState,
// "No Service object found on our did document",
// )
// })?
// .clone();
// let key_base58 = match service.extra_field_recipient_keys() {
// Ok(recipient_keys) => {
// match recipient_keys.first() {
// None => {
// return Err(AriesVcxError::from_msg(
// AriesVcxErrorKind::InvalidState,
// "Recipient key field but did not have any keys",
// ))
// }
// Some(key) => {
// // service_key_to_naked_key(&key, did_document)?
// unimplemented!("Support for 'recipientKeys' has been dropped")
// }
// }
// }
// Err(_err) => {
//
// }
// };
let key_base58 = diddoc_resolve_first_key_agreement(did_document)?;
Ok(key_base58.base58())
}

pub fn get_routing_keys(our_did_doc: &DidDocument) -> VcxResult<Vec<String>> {
Expand All @@ -69,15 +80,15 @@ pub fn get_routing_keys(our_did_doc: &DidDocument) -> VcxResult<Vec<String>> {
)
})?
.clone();
let routing_keys = service.extra_field_routing_keys().map_err(|err| {
AriesVcxError::from_msg(
AriesVcxErrorKind::InvalidState,
format!("No routing_keys found: {}", err),
)
})?;
let mut naked_routing_keys = Vec::new();
for key in routing_keys.iter() {
naked_routing_keys.push(service_key_to_naked_key(key, our_did_doc)?);
match service.extra_field_routing_keys() {
Ok(routing_keys) => {
let mut naked_routing_keys = Vec::new();
for key in routing_keys.iter() {
naked_routing_keys
.push(resolve_service_key_to_typed_key(key, our_did_doc)?.base58());
}
Ok(naked_routing_keys)
}
Err(_err) => Ok(Vec::new()),
}
Ok(naked_routing_keys)
}
6 changes: 3 additions & 3 deletions aries/aries_vcx/src/utils/encryption_envelope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use uuid::Uuid;

use crate::{
errors::error::prelude::*,
utils::didcomm_utils::{get_routing_keys, get_sender_verkey},
utils::didcomm_utils::{get_routing_keys, resolve_base58_key_agreement},
};

#[derive(Debug)]
Expand Down Expand Up @@ -50,8 +50,8 @@ impl EncryptionEnvelope {
their_did_doc: &DidDocument,
) -> VcxResult<EncryptionEnvelope> {
// get first service, from service get (possibly resolve) recipient key and routing keys
let sender_vk = get_sender_verkey(our_did_doc)?;
let recipient_key = get_sender_verkey(their_did_doc)?;
let sender_vk = resolve_base58_key_agreement(our_did_doc)?;
let recipient_key = resolve_base58_key_agreement(their_did_doc)?;
let routing_keys = get_routing_keys(their_did_doc)?;

EncryptionEnvelope::create_from_keys(
Expand Down
2 changes: 1 addition & 1 deletion aries/aries_vcx/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ pub mod qualifier;

#[macro_use]
pub mod encryption_envelope;
mod didcomm_utils;
pub mod didcomm_utils;
pub mod serialization;
pub mod validation;
62 changes: 28 additions & 34 deletions aries/aries_vcx/tests/test_did_exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@ use aries_vcx::{
},
states::{requester::request_sent::RequestSent, responder::response_sent::ResponseSent},
transition::transition_result::TransitionResult,
}
},
utils::{didcomm_utils::resolve_base58_key_agreement, encryption_envelope::EncryptionEnvelope},
};
use aries_vcx_core::ledger::indy_vdr_ledger::DefaultIndyLedgerRead;
use did_doc::schema::{
did_doc::DidDocument, service::typed::didcommv1::ServiceDidCommV1, types::uri::Uri,
did_doc::{diddoc_resolve_first_key_agreement, DidDocument},
service::typed::didcommv1::ServiceDidCommV1,
types::uri::Uri,
};
use did_parser::Did;
use did_peer::{
Expand All @@ -39,21 +42,9 @@ use crate::utils::test_agent::{

pub mod utils;

fn assert_verification_method(a: DidDocument, b: DidDocument) {
let a_key = a
.verification_method()
.first()
.unwrap()
.public_key()
.unwrap()
.base58();
let b_key = b
.verification_method()
.first()
.unwrap()
.public_key()
.unwrap()
.base58();
fn assert_key_agreement(a: DidDocument, b: DidDocument) {
let a_key = diddoc_resolve_first_key_agreement(&a).unwrap();
let b_key = diddoc_resolve_first_key_agreement(&b).unwrap();
assert_eq!(a_key, b_key);
}

Expand Down Expand Up @@ -171,11 +162,13 @@ async fn did_exchange_test() -> Result<(), Box<dyn Error>> {

let responder = responder.receive_complete(complete).unwrap();

assert_verification_method(
info!("Asserting did document of requester");
assert_key_agreement(
requester.our_did_doc().clone(),
responder.their_did_doc().clone(),
);
assert_verification_method(
info!("Asserting did document of responder");
assert_key_agreement(
responder.our_did_doc().clone(),
requester.their_did_doc().clone(),
);
Expand All @@ -189,21 +182,22 @@ async fn did_exchange_test() -> Result<(), Box<dyn Error>> {
requester.their_did_doc()
);

// let data= "Hello world";
// let m = EncryptionEnvelope::create(
// &agent_invitee.wallet,
// data.as_bytes(),
// &requester.our_did_doc(),
// &requester.their_did_doc()
// ).await?;
//
// info!("Encrypted message: {:?}", m);
//
// let unpacked = EncryptionEnvelope::auth_unpack(
// &agent_invitee.wallet,
// m.0,
// "disabled"
// ).await?;
let data = "Hello world";
let m = EncryptionEnvelope::create(
&agent_invitee.wallet,
data.as_bytes(),
requester.our_did_doc(),
requester.their_did_doc(),
)
.await?;

info!("Encrypted message: {:?}", m);

let expected_sender_vk = resolve_base58_key_agreement(&requesters_did_document)?;
let unpacked =
EncryptionEnvelope::auth_unpack(&agent_invitee.wallet, m.0, &expected_sender_vk).await?;

info!("Unpacked message: {:?}", unpacked);

Ok(())
}
Loading

0 comments on commit 946d775

Please sign in to comment.