repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_jwk/src/lib.rs | did_core/did_methods/did_jwk/src/lib.rs | use std::fmt::{self, Display};
use base64::{
alphabet,
engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig},
Engine,
};
use did_doc::schema::types::jsonwebkey::JsonWebKey;
use did_parser_nom::Did;
use error::DidJwkError;
use public_key::{Key, KeyType};
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use serde_json::json;
pub mod error;
pub mod resolver;
const USE: &str = "use";
const USE_SIG: &str = "sig";
const USE_ENC: &str = "enc";
/// A default [GeneralPurposeConfig] configuration with a [decode_padding_mode] of
/// [DecodePaddingMode::Indifferent]
const LENIENT_PAD: GeneralPurposeConfig = GeneralPurposeConfig::new()
.with_encode_padding(false)
.with_decode_padding_mode(DecodePaddingMode::Indifferent);
/// A [GeneralPurpose] engine using the [alphabet::URL_SAFE] base64 alphabet and
/// [DecodePaddingMode::Indifferent] config to decode both padded and unpadded.
const URL_SAFE_LENIENT: GeneralPurpose = GeneralPurpose::new(&alphabet::URL_SAFE, LENIENT_PAD);
/// Represents did:key where the DID ID is JWK public key itself
/// See the spec: https://github.com/quartzjer/did-jwk/blob/main/spec.md
#[derive(Clone, Debug, PartialEq)]
pub struct DidJwk {
jwk: JsonWebKey,
did: Did,
}
impl DidJwk {
pub fn parse<T>(did: T) -> Result<DidJwk, DidJwkError>
where
Did: TryFrom<T>,
<Did as TryFrom<T>>::Error: Into<DidJwkError>,
{
let did: Did = did.try_into().map_err(Into::into)?;
Self::try_from(did)
}
pub fn try_from_serialized_jwk(jwk: &str) -> Result<DidJwk, DidJwkError> {
let jwk: JsonWebKey = serde_json::from_str(jwk)?;
Self::try_from(jwk)
}
pub fn jwk(&self) -> &JsonWebKey {
&self.jwk
}
pub fn did(&self) -> &Did {
&self.did
}
pub fn key(&self) -> Result<Key, DidJwkError> {
Ok(Key::from_jwk(&serde_json::to_string(&self.jwk)?)?)
}
}
impl TryFrom<Did> for DidJwk {
type Error = DidJwkError;
fn try_from(did: Did) -> Result<Self, Self::Error> {
match did.method() {
Some("jwk") => {}
other => return Err(DidJwkError::MethodNotSupported(format!("{other:?}"))),
}
let jwk = decode_jwk(did.id())?;
Ok(Self { jwk, did })
}
}
impl TryFrom<JsonWebKey> for DidJwk {
type Error = DidJwkError;
fn try_from(jwk: JsonWebKey) -> Result<Self, Self::Error> {
let encoded_jwk = encode_jwk(&jwk)?;
let did = Did::parse(format!("did:jwk:{encoded_jwk}",))?;
Ok(Self { jwk, did })
}
}
impl TryFrom<Key> for DidJwk {
type Error = DidJwkError;
fn try_from(key: Key) -> Result<Self, Self::Error> {
let jwk = key.to_jwk()?;
let mut jwk: JsonWebKey = serde_json::from_str(&jwk)?;
match key.key_type() {
KeyType::Ed25519
| KeyType::Bls12381g1g2
| KeyType::Bls12381g1
| KeyType::Bls12381g2
| KeyType::P256
| KeyType::P384
| KeyType::P521 => {
jwk.extra.insert(String::from(USE), json!(USE_SIG));
}
KeyType::X25519 => {
jwk.extra.insert(String::from(USE), json!(USE_ENC));
}
}
Self::try_from(jwk)
}
}
impl Display for DidJwk {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.did)
}
}
impl Serialize for DidJwk {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.did.did())
}
}
impl<'de> Deserialize<'de> for DidJwk {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
DidJwk::parse(s).map_err(de::Error::custom)
}
}
fn encode_jwk(jwk: &JsonWebKey) -> Result<String, DidJwkError> {
let jwk_bytes = serde_json::to_vec(jwk)?;
Ok(URL_SAFE_LENIENT.encode(jwk_bytes))
}
fn decode_jwk(encoded_jwk: &str) -> Result<JsonWebKey, DidJwkError> {
let jwk_bytes = URL_SAFE_LENIENT.decode(encoded_jwk)?;
Ok(serde_json::from_slice(&jwk_bytes)?)
}
#[cfg(test)]
mod tests {
use super::*;
fn valid_key_base58_fingerprint() -> String {
"z6MkeWVt6dndY6EbFwEvb3VQU6ksQXKTeorkQ9sU29DY7yRX".to_string()
}
fn valid_key() -> Key {
Key::from_fingerprint(&valid_key_base58_fingerprint()).unwrap()
}
fn valid_serialized_jwk() -> String {
r#"{
"kty": "OKP",
"crv": "Ed25519",
"x": "ANRjH_zxcKBxsjRPUtzRbp7FSVLKJXQ9APX9MP1j7k4",
"use": "sig"
}"#
.to_string()
}
fn valid_jwk() -> JsonWebKey {
serde_json::from_str(&valid_serialized_jwk()).unwrap()
}
fn valid_encoded_jwk() -> String {
URL_SAFE_LENIENT.encode(serde_json::to_vec(&valid_jwk()).unwrap())
}
fn valid_did_jwk_string() -> String {
format!("did:jwk:{}", valid_encoded_jwk())
}
fn invalid_did_jwk_string_wrong_method() -> String {
format!("did:sov:{}", valid_encoded_jwk())
}
fn invalid_did_jwk_string_invalid_id() -> String {
"did:jwk:somenonsense".to_string()
}
fn valid_did_jwk() -> DidJwk {
DidJwk {
jwk: valid_jwk(),
did: Did::parse(valid_did_jwk_string()).unwrap(),
}
}
#[test]
fn test_serialize() {
assert_eq!(
format!("\"{}\"", valid_did_jwk_string()),
serde_json::to_string(&valid_did_jwk()).unwrap(),
);
}
#[test]
fn test_deserialize() {
assert_eq!(
valid_did_jwk(),
serde_json::from_str::<DidJwk>(&format!("\"{}\"", valid_did_jwk_string())).unwrap(),
);
}
#[test]
fn test_deserialize_error_wrong_method() {
assert!(serde_json::from_str::<DidJwk>(&invalid_did_jwk_string_wrong_method()).is_err());
}
#[test]
fn test_deserialize_error_invalid_id() {
assert!(serde_json::from_str::<DidJwk>(&invalid_did_jwk_string_invalid_id()).is_err());
}
#[test]
fn test_parse() {
assert_eq!(
valid_did_jwk(),
DidJwk::parse(valid_did_jwk_string()).unwrap(),
);
}
#[test]
fn test_parse_error_wrong_method() {
assert!(DidJwk::parse(invalid_did_jwk_string_wrong_method()).is_err());
}
#[test]
fn test_parse_error_invalid_id() {
assert!(DidJwk::parse(invalid_did_jwk_string_invalid_id()).is_err());
}
#[test]
fn test_to_key() {
assert_eq!(valid_did_jwk().key().unwrap(), valid_key());
}
#[test]
fn test_try_from_serialized_jwk() {
assert_eq!(
valid_did_jwk(),
DidJwk::try_from_serialized_jwk(&valid_serialized_jwk()).unwrap(),
);
}
#[test]
fn test_try_from_jwk() {
assert_eq!(valid_did_jwk(), DidJwk::try_from(valid_jwk()).unwrap(),);
}
#[test]
fn test_try_from_key() {
assert_eq!(valid_did_jwk(), DidJwk::try_from(valid_key()).unwrap(),);
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_jwk/src/error.rs | did_core/did_methods/did_jwk/src/error.rs | use thiserror::Error;
#[derive(Debug, Error)]
pub enum DidJwkError {
#[error("DID method not supported: {0}")]
MethodNotSupported(String),
#[error("Base64 encoding error: {0}")]
Base64Error(#[from] base64::DecodeError),
#[error("Serde JSON error: {0}")]
SerdeJsonError(#[from] serde_json::Error),
#[error("Public key error: {0}")]
PublicKeyError(#[from] public_key::PublicKeyError),
#[error("DID parser error: {0}")]
DidParserError(#[from] did_parser_nom::ParseError),
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_jwk/src/resolver.rs | did_core/did_methods/did_jwk/src/resolver.rs | use async_trait::async_trait;
use did_doc::schema::{
did_doc::DidDocument,
verification_method::{PublicKeyField, VerificationMethod, VerificationMethodType},
};
use did_parser_nom::{Did, DidUrl};
use did_resolver::{
error::GenericError,
traits::resolvable::{resolution_output::DidResolutionOutput, DidResolvable},
};
use serde_json::Value;
use crate::DidJwk;
#[derive(Default)]
pub struct DidJwkResolver;
impl DidJwkResolver {
pub fn new() -> Self {
Self
}
}
#[async_trait]
impl DidResolvable for DidJwkResolver {
type DidResolutionOptions = ();
async fn resolve(
&self,
did: &Did,
_options: &Self::DidResolutionOptions,
) -> Result<DidResolutionOutput, GenericError> {
let did_jwk = DidJwk::try_from(did.to_owned())?;
let jwk = did_jwk.jwk();
let jwk_use = jwk.extra.get("use").and_then(Value::as_str);
let mut did_doc = DidDocument::new(did.to_owned());
let vm_id = DidUrl::parse(format!("{did}#0"))?;
let vm = VerificationMethod::builder()
.id(vm_id.clone())
.controller(did.clone())
.verification_method_type(VerificationMethodType::JsonWebKey2020)
.public_key(PublicKeyField::Jwk {
public_key_jwk: jwk.clone(),
})
.build();
did_doc.add_verification_method(vm);
match jwk_use {
Some("enc") => did_doc.add_key_agreement_ref(vm_id),
Some("sig") => {
did_doc.add_assertion_method_ref(vm_id.clone());
did_doc.add_authentication_ref(vm_id.clone());
did_doc.add_capability_invocation_ref(vm_id.clone());
did_doc.add_capability_delegation_ref(vm_id.clone());
}
_ => {
did_doc.add_assertion_method_ref(vm_id.clone());
did_doc.add_authentication_ref(vm_id.clone());
did_doc.add_capability_invocation_ref(vm_id.clone());
did_doc.add_capability_delegation_ref(vm_id.clone());
did_doc.add_key_agreement_ref(vm_id.clone());
}
};
Ok(DidResolutionOutput::builder(did_doc).build())
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_jwk/tests/resolution.rs | did_core/did_methods/did_jwk/tests/resolution.rs | use did_doc::schema::did_doc::DidDocument;
use did_jwk::resolver::DidJwkResolver;
use did_parser_nom::Did;
use did_resolver::traits::resolvable::DidResolvable;
use serde_json::json;
// https://github.com/quartzjer/did-jwk/blob/main/spec.md#p-256
#[tokio::test]
async fn test_p256_spec_vector_resolution() {
let did = Did::parse("did:jwk:eyJjcnYiOiJQLTI1NiIsImt0eSI6IkVDIiwieCI6ImFjYklRaXVNczNpOF91c3pFakoydHBUdFJNNEVVM3l6OTFQSDZDZEgyVjAiLCJ5IjoiX0tjeUxqOXZXTXB0bm1LdG00NkdxRHo4d2Y3NEk1TEtncmwyR3pIM25TRSJ9".to_string()).unwrap();
let spec_json = json!({
"id": "did:jwk:eyJjcnYiOiJQLTI1NiIsImt0eSI6IkVDIiwieCI6ImFjYklRaXVNczNpOF91c3pFakoydHBUdFJNNEVVM3l6OTFQSDZDZEgyVjAiLCJ5IjoiX0tjeUxqOXZXTXB0bm1LdG00NkdxRHo4d2Y3NEk1TEtncmwyR3pIM25TRSJ9",
"verificationMethod": [
{
"id": "did:jwk:eyJjcnYiOiJQLTI1NiIsImt0eSI6IkVDIiwieCI6ImFjYklRaXVNczNpOF91c3pFakoydHBUdFJNNEVVM3l6OTFQSDZDZEgyVjAiLCJ5IjoiX0tjeUxqOXZXTXB0bm1LdG00NkdxRHo4d2Y3NEk1TEtncmwyR3pIM25TRSJ9#0",
"type": "JsonWebKey2020",
"controller": "did:jwk:eyJjcnYiOiJQLTI1NiIsImt0eSI6IkVDIiwieCI6ImFjYklRaXVNczNpOF91c3pFakoydHBUdFJNNEVVM3l6OTFQSDZDZEgyVjAiLCJ5IjoiX0tjeUxqOXZXTXB0bm1LdG00NkdxRHo4d2Y3NEk1TEtncmwyR3pIM25TRSJ9",
"publicKeyJwk": {
"crv": "P-256",
"kty": "EC",
"x": "acbIQiuMs3i8_uszEjJ2tpTtRM4EU3yz91PH6CdH2V0",
"y": "_KcyLj9vWMptnmKtm46GqDz8wf74I5LKgrl2GzH3nSE"
}
}
],
"assertionMethod": ["did:jwk:eyJjcnYiOiJQLTI1NiIsImt0eSI6IkVDIiwieCI6ImFjYklRaXVNczNpOF91c3pFakoydHBUdFJNNEVVM3l6OTFQSDZDZEgyVjAiLCJ5IjoiX0tjeUxqOXZXTXB0bm1LdG00NkdxRHo4d2Y3NEk1TEtncmwyR3pIM25TRSJ9#0"],
"authentication": ["did:jwk:eyJjcnYiOiJQLTI1NiIsImt0eSI6IkVDIiwieCI6ImFjYklRaXVNczNpOF91c3pFakoydHBUdFJNNEVVM3l6OTFQSDZDZEgyVjAiLCJ5IjoiX0tjeUxqOXZXTXB0bm1LdG00NkdxRHo4d2Y3NEk1TEtncmwyR3pIM25TRSJ9#0"],
"capabilityInvocation": ["did:jwk:eyJjcnYiOiJQLTI1NiIsImt0eSI6IkVDIiwieCI6ImFjYklRaXVNczNpOF91c3pFakoydHBUdFJNNEVVM3l6OTFQSDZDZEgyVjAiLCJ5IjoiX0tjeUxqOXZXTXB0bm1LdG00NkdxRHo4d2Y3NEk1TEtncmwyR3pIM25TRSJ9#0"],
"capabilityDelegation": ["did:jwk:eyJjcnYiOiJQLTI1NiIsImt0eSI6IkVDIiwieCI6ImFjYklRaXVNczNpOF91c3pFakoydHBUdFJNNEVVM3l6OTFQSDZDZEgyVjAiLCJ5IjoiX0tjeUxqOXZXTXB0bm1LdG00NkdxRHo4d2Y3NEk1TEtncmwyR3pIM25TRSJ9#0"],
"keyAgreement": ["did:jwk:eyJjcnYiOiJQLTI1NiIsImt0eSI6IkVDIiwieCI6ImFjYklRaXVNczNpOF91c3pFakoydHBUdFJNNEVVM3l6OTFQSDZDZEgyVjAiLCJ5IjoiX0tjeUxqOXZXTXB0bm1LdG00NkdxRHo4d2Y3NEk1TEtncmwyR3pIM25TRSJ9#0"]
});
let expected_did_doc: DidDocument = serde_json::from_value(spec_json).unwrap();
let resolver = DidJwkResolver::new();
let output = resolver.resolve(&did, &()).await.unwrap();
let actual_did_doc = output.did_document;
assert_eq!(actual_did_doc, expected_did_doc);
}
// https://github.com/quartzjer/did-jwk/blob/main/spec.md#x25519
#[tokio::test]
async fn test_x25519_spec_vector_resolution() {
let did = Did::parse("did:jwk:eyJrdHkiOiJPS1AiLCJjcnYiOiJYMjU1MTkiLCJ1c2UiOiJlbmMiLCJ4IjoiM3A3YmZYdDl3YlRUVzJIQzdPUTFOei1EUThoYmVHZE5yZngtRkctSUswOCJ9".to_string()).unwrap();
let spec_json = json!({
"id": "did:jwk:eyJrdHkiOiJPS1AiLCJjcnYiOiJYMjU1MTkiLCJ1c2UiOiJlbmMiLCJ4IjoiM3A3YmZYdDl3YlRUVzJIQzdPUTFOei1EUThoYmVHZE5yZngtRkctSUswOCJ9",
"verificationMethod": [
{
"id": "did:jwk:eyJrdHkiOiJPS1AiLCJjcnYiOiJYMjU1MTkiLCJ1c2UiOiJlbmMiLCJ4IjoiM3A3YmZYdDl3YlRUVzJIQzdPUTFOei1EUThoYmVHZE5yZngtRkctSUswOCJ9#0",
"type": "JsonWebKey2020",
"controller": "did:jwk:eyJrdHkiOiJPS1AiLCJjcnYiOiJYMjU1MTkiLCJ1c2UiOiJlbmMiLCJ4IjoiM3A3YmZYdDl3YlRUVzJIQzdPUTFOei1EUThoYmVHZE5yZngtRkctSUswOCJ9",
"publicKeyJwk": {
"kty":"OKP",
"crv":"X25519",
"use":"enc",
"x":"3p7bfXt9wbTTW2HC7OQ1Nz-DQ8hbeGdNrfx-FG-IK08"
}
}
],
"keyAgreement": ["did:jwk:eyJrdHkiOiJPS1AiLCJjcnYiOiJYMjU1MTkiLCJ1c2UiOiJlbmMiLCJ4IjoiM3A3YmZYdDl3YlRUVzJIQzdPUTFOei1EUThoYmVHZE5yZngtRkctSUswOCJ9#0"]
});
let expected_did_doc: DidDocument = serde_json::from_value(spec_json).unwrap();
let resolver = DidJwkResolver::new();
let output = resolver.resolve(&did, &()).await.unwrap();
let actual_did_doc = output.did_document;
assert_eq!(actual_did_doc, expected_did_doc);
}
#[tokio::test]
async fn test_ed25519_vector_resolution() {
// reference vectors from universal resolver
let did = Did::parse("did:jwk:eyJraWQiOiJ1cm46aWV0ZjpwYXJhbXM6b2F1dGg6andrLXRodW1icHJpbnQ6c2hhLTI1NjpGZk1iek9qTW1RNGVmVDZrdndUSUpqZWxUcWpsMHhqRUlXUTJxb2JzUk1NIiwia3R5IjoiT0tQIiwiY3J2IjoiRWQyNTUxOSIsImFsZyI6IkVkRFNBIiwieCI6IkFOUmpIX3p4Y0tCeHNqUlBVdHpSYnA3RlNWTEtKWFE5QVBYOU1QMWo3azQifQ".to_string()).unwrap();
let json = json!({
"id": "did:jwk:eyJraWQiOiJ1cm46aWV0ZjpwYXJhbXM6b2F1dGg6andrLXRodW1icHJpbnQ6c2hhLTI1NjpGZk1iek9qTW1RNGVmVDZrdndUSUpqZWxUcWpsMHhqRUlXUTJxb2JzUk1NIiwia3R5IjoiT0tQIiwiY3J2IjoiRWQyNTUxOSIsImFsZyI6IkVkRFNBIiwieCI6IkFOUmpIX3p4Y0tCeHNqUlBVdHpSYnA3RlNWTEtKWFE5QVBYOU1QMWo3azQifQ",
"verificationMethod": [
{
"id": "did:jwk:eyJraWQiOiJ1cm46aWV0ZjpwYXJhbXM6b2F1dGg6andrLXRodW1icHJpbnQ6c2hhLTI1NjpGZk1iek9qTW1RNGVmVDZrdndUSUpqZWxUcWpsMHhqRUlXUTJxb2JzUk1NIiwia3R5IjoiT0tQIiwiY3J2IjoiRWQyNTUxOSIsImFsZyI6IkVkRFNBIiwieCI6IkFOUmpIX3p4Y0tCeHNqUlBVdHpSYnA3RlNWTEtKWFE5QVBYOU1QMWo3azQifQ#0",
"type": "JsonWebKey2020",
"controller": "did:jwk:eyJraWQiOiJ1cm46aWV0ZjpwYXJhbXM6b2F1dGg6andrLXRodW1icHJpbnQ6c2hhLTI1NjpGZk1iek9qTW1RNGVmVDZrdndUSUpqZWxUcWpsMHhqRUlXUTJxb2JzUk1NIiwia3R5IjoiT0tQIiwiY3J2IjoiRWQyNTUxOSIsImFsZyI6IkVkRFNBIiwieCI6IkFOUmpIX3p4Y0tCeHNqUlBVdHpSYnA3RlNWTEtKWFE5QVBYOU1QMWo3azQifQ",
"publicKeyJwk": {
"kid": "urn:ietf:params:oauth:jwk-thumbprint:sha-256:FfMbzOjMmQ4efT6kvwTIJjelTqjl0xjEIWQ2qobsRMM",
"kty": "OKP",
"crv": "Ed25519",
"alg": "EdDSA",
"x": "ANRjH_zxcKBxsjRPUtzRbp7FSVLKJXQ9APX9MP1j7k4"
}
}
],
"authentication": ["did:jwk:eyJraWQiOiJ1cm46aWV0ZjpwYXJhbXM6b2F1dGg6andrLXRodW1icHJpbnQ6c2hhLTI1NjpGZk1iek9qTW1RNGVmVDZrdndUSUpqZWxUcWpsMHhqRUlXUTJxb2JzUk1NIiwia3R5IjoiT0tQIiwiY3J2IjoiRWQyNTUxOSIsImFsZyI6IkVkRFNBIiwieCI6IkFOUmpIX3p4Y0tCeHNqUlBVdHpSYnA3RlNWTEtKWFE5QVBYOU1QMWo3azQifQ#0"],
"assertionMethod": ["did:jwk:eyJraWQiOiJ1cm46aWV0ZjpwYXJhbXM6b2F1dGg6andrLXRodW1icHJpbnQ6c2hhLTI1NjpGZk1iek9qTW1RNGVmVDZrdndUSUpqZWxUcWpsMHhqRUlXUTJxb2JzUk1NIiwia3R5IjoiT0tQIiwiY3J2IjoiRWQyNTUxOSIsImFsZyI6IkVkRFNBIiwieCI6IkFOUmpIX3p4Y0tCeHNqUlBVdHpSYnA3RlNWTEtKWFE5QVBYOU1QMWo3azQifQ#0"],
"capabilityInvocation": ["did:jwk:eyJraWQiOiJ1cm46aWV0ZjpwYXJhbXM6b2F1dGg6andrLXRodW1icHJpbnQ6c2hhLTI1NjpGZk1iek9qTW1RNGVmVDZrdndUSUpqZWxUcWpsMHhqRUlXUTJxb2JzUk1NIiwia3R5IjoiT0tQIiwiY3J2IjoiRWQyNTUxOSIsImFsZyI6IkVkRFNBIiwieCI6IkFOUmpIX3p4Y0tCeHNqUlBVdHpSYnA3RlNWTEtKWFE5QVBYOU1QMWo3azQifQ#0"],
"capabilityDelegation": ["did:jwk:eyJraWQiOiJ1cm46aWV0ZjpwYXJhbXM6b2F1dGg6andrLXRodW1icHJpbnQ6c2hhLTI1NjpGZk1iek9qTW1RNGVmVDZrdndUSUpqZWxUcWpsMHhqRUlXUTJxb2JzUk1NIiwia3R5IjoiT0tQIiwiY3J2IjoiRWQyNTUxOSIsImFsZyI6IkVkRFNBIiwieCI6IkFOUmpIX3p4Y0tCeHNqUlBVdHpSYnA3RlNWTEtKWFE5QVBYOU1QMWo3azQifQ#0"],
"keyAgreement": ["did:jwk:eyJraWQiOiJ1cm46aWV0ZjpwYXJhbXM6b2F1dGg6andrLXRodW1icHJpbnQ6c2hhLTI1NjpGZk1iek9qTW1RNGVmVDZrdndUSUpqZWxUcWpsMHhqRUlXUTJxb2JzUk1NIiwia3R5IjoiT0tQIiwiY3J2IjoiRWQyNTUxOSIsImFsZyI6IkVkRFNBIiwieCI6IkFOUmpIX3p4Y0tCeHNqUlBVdHpSYnA3RlNWTEtKWFE5QVBYOU1QMWo3azQifQ#0"],
});
let expected_did_doc: DidDocument = serde_json::from_value(json).unwrap();
let resolver = DidJwkResolver::new();
let output = resolver.resolve(&did, &()).await.unwrap();
let actual_did_doc = output.did_document;
assert_eq!(actual_did_doc, expected_did_doc);
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/cheqd_proto_gen/src/main.rs | did_core/did_methods/did_cheqd/cheqd_proto_gen/src/main.rs | //! Binary for re-generating the cheqd proto types
fn main() -> Result<(), Box<dyn std::error::Error>> {
let crate_dir = env!("CARGO_MANIFEST_DIR").to_string();
tonic_build::configure()
.build_server(false)
.out_dir(crate_dir.clone() + "/../src/proto")
.compile_protos(
&[
crate_dir.clone() + "/proto/cheqd/did/v2/query.proto",
crate_dir.clone() + "/proto/cheqd/resource/v2/query.proto",
],
&[crate_dir + "/proto"],
)?;
Ok(())
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/src/lib.rs | did_core/did_methods/did_cheqd/src/lib.rs | pub mod error;
pub mod proto;
pub mod resolution;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/src/proto/google.api.rs | did_core/did_methods/did_cheqd/src/proto/google.api.rs | // This file is @generated by prost-build.
/// Defines the HTTP configuration for an API service. It contains a list of
/// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
/// to one or more HTTP REST API methods.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Http {
/// A list of HTTP configuration rules that apply to individual API methods.
///
/// **NOTE:** All service configuration rules follow "last one wins" order.
#[prost(message, repeated, tag = "1")]
pub rules: ::prost::alloc::vec::Vec<HttpRule>,
/// When set to true, URL path parameters will be fully URI-decoded except in
/// cases of single segment matches in reserved expansion, where "%2F" will be
/// left encoded.
///
/// The default behavior is to not decode RFC 6570 reserved characters in multi
/// segment matches.
#[prost(bool, tag = "2")]
pub fully_decode_reserved_expansion: bool,
}
/// gRPC Transcoding
///
/// gRPC Transcoding is a feature for mapping between a gRPC method and one or
/// more HTTP REST endpoints. It allows developers to build a single API service
/// that supports both gRPC APIs and REST APIs. Many systems, including [Google
/// APIs](<https://github.com/googleapis/googleapis>),
/// [Cloud Endpoints](<https://cloud.google.com/endpoints>), [gRPC
/// Gateway](<https://github.com/grpc-ecosystem/grpc-gateway>),
/// and [Envoy](<https://github.com/envoyproxy/envoy>) proxy support this feature
/// and use it for large scale production services.
///
/// `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies
/// how different portions of the gRPC request message are mapped to the URL
/// path, URL query parameters, and HTTP request body. It also controls how the
/// gRPC response message is mapped to the HTTP response body. `HttpRule` is
/// typically specified as an `google.api.http` annotation on the gRPC method.
///
/// Each mapping specifies a URL path template and an HTTP method. The path
/// template may refer to one or more fields in the gRPC request message, as long
/// as each field is a non-repeated field with a primitive (non-message) type.
/// The path template controls how fields of the request message are mapped to
/// the URL path.
///
/// Example:
///
/// service Messaging {
/// rpc GetMessage(GetMessageRequest) returns (Message) {
/// option (google.api.http) = {
/// get: "/v1/{name=messages/*}"
/// };
/// }
/// }
/// message GetMessageRequest {
/// string name = 1; // Mapped to URL path.
/// }
/// message Message {
/// string text = 1; // The resource content.
/// }
///
/// This enables an HTTP REST to gRPC mapping as below:
///
/// - HTTP: `GET /v1/messages/123456`
/// - gRPC: `GetMessage(name: "messages/123456")`
///
/// Any fields in the request message which are not bound by the path template
/// automatically become HTTP query parameters if there is no HTTP request body.
/// For example:
///
/// service Messaging {
/// rpc GetMessage(GetMessageRequest) returns (Message) {
/// option (google.api.http) = {
/// get:"/v1/messages/{message_id}"
/// };
/// }
/// }
/// message GetMessageRequest {
/// message SubMessage {
/// string subfield = 1;
/// }
/// string message_id = 1; // Mapped to URL path.
/// int64 revision = 2; // Mapped to URL query parameter `revision`.
/// SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`.
/// }
///
/// This enables a HTTP JSON to RPC mapping as below:
///
/// - HTTP: `GET /v1/messages/123456?revision=2&sub.subfield=foo`
/// - gRPC: `GetMessage(message_id: "123456" revision: 2 sub:
/// SubMessage(subfield: "foo"))`
///
/// Note that fields which are mapped to URL query parameters must have a
/// primitive type or a repeated primitive type or a non-repeated message type.
/// In the case of a repeated type, the parameter can be repeated in the URL
/// as `...?param=A¶m=B`. In the case of a message type, each field of the
/// message is mapped to a separate parameter, such as
/// `...?foo.a=A&foo.b=B&foo.c=C`.
///
/// For HTTP methods that allow a request body, the `body` field
/// specifies the mapping. Consider a REST update method on the
/// message resource collection:
///
/// service Messaging {
/// rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
/// option (google.api.http) = {
/// patch: "/v1/messages/{message_id}"
/// body: "message"
/// };
/// }
/// }
/// message UpdateMessageRequest {
/// string message_id = 1; // mapped to the URL
/// Message message = 2; // mapped to the body
/// }
///
/// The following HTTP JSON to RPC mapping is enabled, where the
/// representation of the JSON in the request body is determined by
/// protos JSON encoding:
///
/// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }`
/// - gRPC: `UpdateMessage(message_id: "123456" message { text: "Hi!" })`
///
/// The special name `*` can be used in the body mapping to define that
/// every field not bound by the path template should be mapped to the
/// request body. This enables the following alternative definition of
/// the update method:
///
/// service Messaging {
/// rpc UpdateMessage(Message) returns (Message) {
/// option (google.api.http) = {
/// patch: "/v1/messages/{message_id}"
/// body: "*"
/// };
/// }
/// }
/// message Message {
/// string message_id = 1;
/// string text = 2;
/// }
///
///
/// The following HTTP JSON to RPC mapping is enabled:
///
/// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }`
/// - gRPC: `UpdateMessage(message_id: "123456" text: "Hi!")`
///
/// Note that when using `*` in the body mapping, it is not possible to
/// have HTTP parameters, as all fields not bound by the path end in
/// the body. This makes this option more rarely used in practice when
/// defining REST APIs. The common usage of `*` is in custom methods
/// which don't use the URL at all for transferring data.
///
/// It is possible to define multiple HTTP methods for one RPC by using
/// the `additional_bindings` option. Example:
///
/// service Messaging {
/// rpc GetMessage(GetMessageRequest) returns (Message) {
/// option (google.api.http) = {
/// get: "/v1/messages/{message_id}"
/// additional_bindings {
/// get: "/v1/users/{user_id}/messages/{message_id}"
/// }
/// };
/// }
/// }
/// message GetMessageRequest {
/// string message_id = 1;
/// string user_id = 2;
/// }
///
/// This enables the following two alternative HTTP JSON to RPC mappings:
///
/// - HTTP: `GET /v1/messages/123456`
/// - gRPC: `GetMessage(message_id: "123456")`
///
/// - HTTP: `GET /v1/users/me/messages/123456`
/// - gRPC: `GetMessage(user_id: "me" message_id: "123456")`
///
/// Rules for HTTP mapping
///
/// 1. Leaf request fields (recursive expansion nested messages in the request
/// message) are classified into three categories:
/// - Fields referred by the path template. They are passed via the URL path.
/// - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They
/// are passed via the HTTP
/// request body.
/// - All other fields are passed via the URL query parameters, and the
/// parameter name is the field path in the request message. A repeated
/// field can be represented as multiple query parameters under the same
/// name.
/// 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL
/// query parameter, all fields
/// are passed via URL path and HTTP request body.
/// 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP
/// request body, all
/// fields are passed via URL path and URL query parameters.
///
/// Path template syntax
///
/// Template = "/" Segments \[ Verb \] ;
/// Segments = Segment { "/" Segment } ;
/// Segment = "*" | "**" | LITERAL | Variable ;
/// Variable = "{" FieldPath \[ "=" Segments \] "}" ;
/// FieldPath = IDENT { "." IDENT } ;
/// Verb = ":" LITERAL ;
///
/// The syntax `*` matches a single URL path segment. The syntax `**` matches
/// zero or more URL path segments, which must be the last part of the URL path
/// except the `Verb`.
///
/// The syntax `Variable` matches part of the URL path as specified by its
/// template. A variable template must not contain other variables. If a variable
/// matches a single path segment, its template may be omitted, e.g. `{var}`
/// is equivalent to `{var=*}`.
///
/// The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL`
/// contains any reserved character, such characters should be percent-encoded
/// before the matching.
///
/// If a variable contains exactly one path segment, such as `"{var}"` or
/// `"{var=*}"`, when such a variable is expanded into a URL path on the client
/// side, all characters except `\[-_.~0-9a-zA-Z\]` are percent-encoded. The
/// server side does the reverse decoding. Such variables show up in the
/// [Discovery
/// Document](<https://developers.google.com/discovery/v1/reference/apis>) as
/// `{var}`.
///
/// If a variable contains multiple path segments, such as `"{var=foo/*}"`
/// or `"{var=**}"`, when such a variable is expanded into a URL path on the
/// client side, all characters except `\[-_.~/0-9a-zA-Z\]` are percent-encoded.
/// The server side does the reverse decoding, except "%2F" and "%2f" are left
/// unchanged. Such variables show up in the
/// [Discovery
/// Document](<https://developers.google.com/discovery/v1/reference/apis>) as
/// `{+var}`.
///
/// Using gRPC API Service Configuration
///
/// gRPC API Service Configuration (service config) is a configuration language
/// for configuring a gRPC service to become a user-facing product. The
/// service config is simply the YAML representation of the `google.api.Service`
/// proto message.
///
/// As an alternative to annotating your proto file, you can configure gRPC
/// transcoding in your service config YAML files. You do this by specifying a
/// `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same
/// effect as the proto annotation. This can be particularly useful if you
/// have a proto that is reused in multiple services. Note that any transcoding
/// specified in the service config will override any matching transcoding
/// configuration in the proto.
///
/// The following example selects a gRPC method and applies an `HttpRule` to it:
///
/// http:
/// rules:
/// - selector: example.v1.Messaging.GetMessage
/// get: /v1/messages/{message_id}/{sub.subfield}
///
/// Special notes
///
/// When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the
/// proto to JSON conversion must follow the [proto3
/// specification](<https://developers.google.com/protocol-buffers/docs/proto3#json>).
///
/// While the single segment variable follows the semantics of
/// [RFC 6570](<https://tools.ietf.org/html/rfc6570>) Section 3.2.2 Simple String
/// Expansion, the multi segment variable **does not** follow RFC 6570 Section
/// 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion
/// does not expand special characters like `?` and `#`, which would lead
/// to invalid URLs. As the result, gRPC Transcoding uses a custom encoding
/// for multi segment variables.
///
/// The path variables **must not** refer to any repeated or mapped field,
/// because client libraries are not capable of handling such variable expansion.
///
/// The path variables **must not** capture the leading "/" character. The reason
/// is that the most common use case "{var}" does not capture the leading "/"
/// character. For consistency, all path variables must share the same behavior.
///
/// Repeated message fields must not be mapped to URL query parameters, because
/// no client library can support such complicated mapping.
///
/// If an API needs to use a JSON array for request or response body, it can map
/// the request or response body to a repeated field. However, some gRPC
/// Transcoding implementations may not support this feature.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct HttpRule {
/// Selects a method to which this rule applies.
///
/// Refer to [selector][google.api.DocumentationRule.selector] for syntax
/// details.
#[prost(string, tag = "1")]
pub selector: ::prost::alloc::string::String,
/// The name of the request field whose value is mapped to the HTTP request
/// body, or `*` for mapping all request fields not captured by the path
/// pattern to the HTTP body, or omitted for not having any HTTP request body.
///
/// NOTE: the referred field must be present at the top-level of the request
/// message type.
#[prost(string, tag = "7")]
pub body: ::prost::alloc::string::String,
/// Optional. The name of the response field whose value is mapped to the HTTP
/// response body. When omitted, the entire response message will be used
/// as the HTTP response body.
///
/// NOTE: The referred field must be present at the top-level of the response
/// message type.
#[prost(string, tag = "12")]
pub response_body: ::prost::alloc::string::String,
/// Additional HTTP bindings for the selector. Nested bindings must
/// not contain an `additional_bindings` field themselves (that is,
/// the nesting may only be one level deep).
#[prost(message, repeated, tag = "11")]
pub additional_bindings: ::prost::alloc::vec::Vec<HttpRule>,
/// Determines the URL pattern is matched by this rules. This pattern can be
/// used with any of the {get|put|post|delete|patch} methods. A custom method
/// can be defined using the 'custom' field.
#[prost(oneof = "http_rule::Pattern", tags = "2, 3, 4, 5, 6, 8")]
pub pattern: ::core::option::Option<http_rule::Pattern>,
}
/// Nested message and enum types in `HttpRule`.
pub mod http_rule {
/// Determines the URL pattern is matched by this rules. This pattern can be
/// used with any of the {get|put|post|delete|patch} methods. A custom method
/// can be defined using the 'custom' field.
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Pattern {
/// Maps to HTTP GET. Used for listing and getting information about
/// resources.
#[prost(string, tag = "2")]
Get(::prost::alloc::string::String),
/// Maps to HTTP PUT. Used for replacing a resource.
#[prost(string, tag = "3")]
Put(::prost::alloc::string::String),
/// Maps to HTTP POST. Used for creating a resource or performing an action.
#[prost(string, tag = "4")]
Post(::prost::alloc::string::String),
/// Maps to HTTP DELETE. Used for deleting a resource.
#[prost(string, tag = "5")]
Delete(::prost::alloc::string::String),
/// Maps to HTTP PATCH. Used for updating a resource.
#[prost(string, tag = "6")]
Patch(::prost::alloc::string::String),
/// The custom pattern is used for specifying an HTTP method that is not
/// included in the `pattern` field, such as HEAD, or "*" to leave the
/// HTTP method unspecified for this rule. The wild-card rule is useful
/// for services that provide content to Web (HTML) clients.
#[prost(message, tag = "8")]
Custom(super::CustomHttpPattern),
}
}
/// A custom pattern is used for defining custom HTTP verb.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CustomHttpPattern {
/// The name of this custom HTTP verb.
#[prost(string, tag = "1")]
pub kind: ::prost::alloc::string::String,
/// The path matched by this custom verb.
#[prost(string, tag = "2")]
pub path: ::prost::alloc::string::String,
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/src/proto/cosmos.base.query.v1beta1.rs | did_core/did_methods/did_cheqd/src/proto/cosmos.base.query.v1beta1.rs | // This file is @generated by prost-build.
/// PageRequest is to be embedded in gRPC request messages for efficient
/// pagination. Ex:
///
/// message SomeRequest {
/// Foo some_parameter = 1;
/// PageRequest pagination = 2;
/// }
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PageRequest {
/// key is a value returned in PageResponse.next_key to begin
/// querying the next page most efficiently. Only one of offset or key
/// should be set.
#[prost(bytes = "vec", tag = "1")]
pub key: ::prost::alloc::vec::Vec<u8>,
/// offset is a numeric offset that can be used when key is unavailable.
/// It is less efficient than using key. Only one of offset or key should
/// be set.
#[prost(uint64, tag = "2")]
pub offset: u64,
/// limit is the total number of results to be returned in the result page.
/// If left empty it will default to a value to be set by each app.
#[prost(uint64, tag = "3")]
pub limit: u64,
/// count_total is set to true to indicate that the result set should include
/// a count of the total number of items available for pagination in UIs.
/// count_total is only respected when offset is used. It is ignored when key
/// is set.
#[prost(bool, tag = "4")]
pub count_total: bool,
/// reverse is set to true if results are to be returned in the descending order.
///
/// Since: cosmos-sdk 0.43
#[prost(bool, tag = "5")]
pub reverse: bool,
}
/// PageResponse is to be embedded in gRPC response messages where the
/// corresponding request message has used PageRequest.
///
/// message SomeResponse {
/// repeated Bar results = 1;
/// PageResponse page = 2;
/// }
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PageResponse {
/// next_key is the key to be passed to PageRequest.key to
/// query the next page most efficiently. It will be empty if
/// there are no more results.
#[prost(bytes = "vec", tag = "1")]
pub next_key: ::prost::alloc::vec::Vec<u8>,
/// total is total number of results available if PageRequest.count_total
/// was set, its value is undefined otherwise
#[prost(uint64, tag = "2")]
pub total: u64,
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/src/proto/mod.rs | did_core/did_methods/did_cheqd/src/proto/mod.rs | //! module structure wrapper over the generated proto types
pub mod cheqd {
pub mod did {
pub mod v2 {
include!("cheqd.did.v2.rs");
}
}
pub mod resource {
pub mod v2 {
include!("cheqd.resource.v2.rs");
}
}
}
pub mod cosmos {
pub mod base {
pub mod query {
pub mod v1beta1 {
include!("cosmos.base.query.v1beta1.rs");
}
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/src/proto/cheqd.did.v2.rs | did_core/did_methods/did_cheqd/src/proto/cheqd.did.v2.rs | // This file is @generated by prost-build.
/// DidDoc defines a DID Document, as defined in the DID Core specification.
/// Documentation: <https://www.w3.org/TR/did-core/>
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DidDoc {
/// context is a list of URIs used to identify the context of the DID document.
/// Default: <https://www.w3.org/ns/did/v1>
#[prost(string, repeated, tag = "1")]
pub context: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
/// id is the DID of the DID document.
/// Format: did:cheqd:<namespace>:<unique-identifier>
#[prost(string, tag = "2")]
pub id: ::prost::alloc::string::String,
/// controller is a list of DIDs that are allowed to control the DID document.
#[prost(string, repeated, tag = "3")]
pub controller: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
/// verificationMethod is a list of verification methods that can be used to
/// verify a digital signature or cryptographic proof.
#[prost(message, repeated, tag = "4")]
pub verification_method: ::prost::alloc::vec::Vec<VerificationMethod>,
/// authentication is a list of verification methods that can be used to
/// authenticate as the DID subject.
#[prost(string, repeated, tag = "5")]
pub authentication: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
/// assertionMethod is a list of verification methods that can be used to
/// assert statements as the DID subject.
#[prost(string, repeated, tag = "6")]
pub assertion_method: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
/// capabilityInvocation is a list of verification methods that can be used to
/// invoke capabilities as the DID subject.
#[prost(string, repeated, tag = "7")]
pub capability_invocation: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
/// capabilityDelegation is a list of verification methods that can be used to
/// delegate capabilities as the DID subject.
#[prost(string, repeated, tag = "8")]
pub capability_delegation: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
/// keyAgreement is a list of verification methods that can be used to perform
/// key agreement as the DID subject.
#[prost(string, repeated, tag = "9")]
pub key_agreement: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
/// service is a list of services that can be used to interact with the DID subject.
#[prost(message, repeated, tag = "10")]
pub service: ::prost::alloc::vec::Vec<Service>,
/// alsoKnownAs is a list of DIDs that are known to refer to the same DID subject.
#[prost(string, repeated, tag = "11")]
pub also_known_as: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
}
/// VerificationMethod defines a verification method, as defined in the DID Core specification.
/// Documentation: <https://www.w3.org/TR/did-core/#verification-methods>
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct VerificationMethod {
/// id is the unique identifier of the verification method.
/// Format: did:cheqd:<namespace>:<unique-identifier>#<key-id>
#[prost(string, tag = "1")]
pub id: ::prost::alloc::string::String,
/// type is the type of the verification method.
/// Example: Ed25519VerificationKey2020
#[prost(string, tag = "2")]
pub verification_method_type: ::prost::alloc::string::String,
/// controller is the DID of the controller of the verification method.
/// Format: did:cheqd:<namespace>:<unique-identifier>
#[prost(string, tag = "3")]
pub controller: ::prost::alloc::string::String,
/// verification_material is the public key of the verification method.
/// Commonly used verification material types: publicJwk, publicKeyBase58, publicKeyMultibase
#[prost(string, tag = "4")]
pub verification_material: ::prost::alloc::string::String,
}
/// Service defines a service, as defined in the DID Core specification.
/// Documentation: <https://www.w3.org/TR/did-core/#services>
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Service {
/// id is the unique identifier of the service.
/// Format: did:cheqd:<namespace>:<unique-identifier>#<service-id>
#[prost(string, tag = "1")]
pub id: ::prost::alloc::string::String,
/// type is the type of the service.
/// Example: LinkedResource
#[prost(string, tag = "2")]
pub service_type: ::prost::alloc::string::String,
/// serviceEndpoint is the endpoint of the service.
/// Example: <https://example.com/endpoint>
#[prost(string, repeated, tag = "3")]
pub service_endpoint: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
}
/// DidDocWithMetadata defines a DID Document with metadata, as defined in the DID Core specification.
/// Contains the DID Document, as well as DID Document metadata.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DidDocWithMetadata {
/// didDocument is the DID Document.
#[prost(message, optional, tag = "1")]
pub did_doc: ::core::option::Option<DidDoc>,
/// didDocumentMetadata is the DID Document metadata.
#[prost(message, optional, tag = "2")]
pub metadata: ::core::option::Option<Metadata>,
}
/// Metadata defines DID Document metadata, as defined in the DID Core specification.
/// Documentation: <https://www.w3.org/TR/did-core/#did-document-metadata-properties>
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Metadata {
/// created is the timestamp of the creation of the DID Document.
/// Format: RFC3339
/// Example: 2021-03-10T15:16:17Z
#[prost(message, optional, tag = "1")]
pub created: ::core::option::Option<::prost_types::Timestamp>,
/// updated is the timestamp of the last update of the DID Document.
/// Format: RFC3339
/// Example: 2021-03-10T15:16:17Z
#[prost(message, optional, tag = "2")]
pub updated: ::core::option::Option<::prost_types::Timestamp>,
/// deactivated is a flag that indicates whether the DID Document is deactivated.
/// Default: false
#[prost(bool, tag = "3")]
pub deactivated: bool,
/// version_id is the version identifier of the DID Document.
/// Format: UUID
/// Example: 123e4567-e89b-12d3-a456-426655440000
#[prost(string, tag = "4")]
pub version_id: ::prost::alloc::string::String,
/// next_version_id is the version identifier of the next version of the DID Document.
/// Format: UUID
/// Example: 123e4567-e89b-12d3-a456-426655440000
#[prost(string, tag = "5")]
pub next_version_id: ::prost::alloc::string::String,
/// previous_version_id is the version identifier of the previous version of the DID Document.
/// Format: UUID
/// Example: 123e4567-e89b-12d3-a456-426655440000
#[prost(string, tag = "6")]
pub previous_version_id: ::prost::alloc::string::String,
}
/// QueryDidDocRequest is the request type for the Query/DidDoc method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryDidDocRequest {
/// DID unique identifier of the DID Document to fetch.
/// UUID-style DIDs as well as Indy-style DID are supported.
///
/// Format: did:cheqd:<namespace>:<unique-identifier>
///
/// Examples:
/// - did:cheqd:mainnet:c82f2b02-bdab-4dd7-b833-3e143745d612
/// - did:cheqd:testnet:wGHEXrZvJxR8vw5P3UWH1j
#[prost(string, tag = "1")]
pub id: ::prost::alloc::string::String,
}
/// QueryDidDocResponse is the response type for the Query/DidDoc method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryDidDocResponse {
/// Successful resolution of the DID Document returns the following:
/// - did_doc is the latest version of the DID Document
/// - metadata is is the DID Document metadata associated with the latest version of the DID Document
#[prost(message, optional, tag = "1")]
pub value: ::core::option::Option<DidDocWithMetadata>,
}
/// QueryDidDocVersionRequest is the request type for the Query/DidDocVersion method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryDidDocVersionRequest {
/// DID unique identifier of the DID Document to fetch.
/// UUID-style DIDs as well as Indy-style DID are supported.
///
/// Format: did:cheqd:<namespace>:<unique-identifier>
///
/// Examples:
/// - did:cheqd:mainnet:c82f2b02-bdab-4dd7-b833-3e143745d612
/// - did:cheqd:testnet:wGHEXrZvJxR8vw5P3UWH1j
#[prost(string, tag = "1")]
pub id: ::prost::alloc::string::String,
/// Unique version identifier of the DID Document to fetch.
/// Returns the specified version of the DID Document.
///
/// Format: <uuid>
///
/// Example: 93f2573c-eca9-4098-96cb-a1ec676a29ed
#[prost(string, tag = "2")]
pub version: ::prost::alloc::string::String,
}
/// QueryDidDocVersionResponse is the response type for the Query/DidDocVersion method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryDidDocVersionResponse {
/// Successful resolution of the DID Document returns the following:
/// - did_doc is the requested version of the DID Document
/// - metadata is DID Document metadata associated with the requested version of the DID Document
#[prost(message, optional, tag = "1")]
pub value: ::core::option::Option<DidDocWithMetadata>,
}
/// QueryAllDidDocVersionsMetadataRequest is the request type for the Query/AllDidDocVersionsMetadata method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryAllDidDocVersionsMetadataRequest {
/// DID unique identifier of the DID Document to fetch version metadata.
/// UUID-style DIDs as well as Indy-style DID are supported.
///
/// Format: did:cheqd:<namespace>:<unique-identifier>
///
/// Examples:
/// - did:cheqd:mainnet:c82f2b02-bdab-4dd7-b833-3e143745d612
/// - did:cheqd:testnet:wGHEXrZvJxR8vw5P3UWH1j
#[prost(string, tag = "1")]
pub id: ::prost::alloc::string::String,
/// pagination defines an optional pagination for the request.
#[prost(message, optional, tag = "2")]
pub pagination: ::core::option::Option<
super::super::super::cosmos::base::query::v1beta1::PageRequest,
>,
}
/// QueryAllDidDocVersionsMetadataResponse is the response type for the Query/AllDidDocVersionsMetadata method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryAllDidDocVersionsMetadataResponse {
/// versions is the list of all versions of the requested DID Document
#[prost(message, repeated, tag = "1")]
pub versions: ::prost::alloc::vec::Vec<Metadata>,
/// pagination defines the pagination in the response.
#[prost(message, optional, tag = "2")]
pub pagination: ::core::option::Option<
super::super::super::cosmos::base::query::v1beta1::PageResponse,
>,
}
/// Generated client implementations.
pub mod query_client {
#![allow(
unused_variables,
dead_code,
missing_docs,
clippy::wildcard_imports,
clippy::let_unit_value,
)]
use tonic::codegen::*;
use tonic::codegen::http::Uri;
/// Query defines the gRPC querier service for the DID module
#[derive(Debug, Clone)]
pub struct QueryClient<T> {
inner: tonic::client::Grpc<T>,
}
impl QueryClient<tonic::transport::Channel> {
/// Attempt to create a new client by connecting to a given endpoint.
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
where
D: TryInto<tonic::transport::Endpoint>,
D::Error: Into<StdError>,
{
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
Ok(Self::new(conn))
}
}
impl<T> QueryClient<T>
where
T: tonic::client::GrpcService<tonic::body::BoxBody>,
T::Error: Into<StdError>,
T::ResponseBody: Body<Data = Bytes> + std::marker::Send + 'static,
<T::ResponseBody as Body>::Error: Into<StdError> + std::marker::Send,
{
pub fn new(inner: T) -> Self {
let inner = tonic::client::Grpc::new(inner);
Self { inner }
}
pub fn with_origin(inner: T, origin: Uri) -> Self {
let inner = tonic::client::Grpc::with_origin(inner, origin);
Self { inner }
}
pub fn with_interceptor<F>(
inner: T,
interceptor: F,
) -> QueryClient<InterceptedService<T, F>>
where
F: tonic::service::Interceptor,
T::ResponseBody: Default,
T: tonic::codegen::Service<
http::Request<tonic::body::BoxBody>,
Response = http::Response<
<T as tonic::client::GrpcService<tonic::body::BoxBody>>::ResponseBody,
>,
>,
<T as tonic::codegen::Service<
http::Request<tonic::body::BoxBody>,
>>::Error: Into<StdError> + std::marker::Send + std::marker::Sync,
{
QueryClient::new(InterceptedService::new(inner, interceptor))
}
/// Compress requests with the given encoding.
///
/// This requires the server to support it otherwise it might respond with an
/// error.
#[must_use]
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
self.inner = self.inner.send_compressed(encoding);
self
}
/// Enable decompressing responses.
#[must_use]
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
self.inner = self.inner.accept_compressed(encoding);
self
}
/// Limits the maximum size of a decoded message.
///
/// Default: `4MB`
#[must_use]
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
self.inner = self.inner.max_decoding_message_size(limit);
self
}
/// Limits the maximum size of an encoded message.
///
/// Default: `usize::MAX`
#[must_use]
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
self.inner = self.inner.max_encoding_message_size(limit);
self
}
/// Fetch latest version of a DID Document for a given DID
pub async fn did_doc(
&mut self,
request: impl tonic::IntoRequest<super::QueryDidDocRequest>,
) -> std::result::Result<
tonic::Response<super::QueryDidDocResponse>,
tonic::Status,
> {
self.inner
.ready()
.await
.map_err(|e| {
tonic::Status::unknown(
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cheqd.did.v2.Query/DidDoc",
);
let mut req = request.into_request();
req.extensions_mut().insert(GrpcMethod::new("cheqd.did.v2.Query", "DidDoc"));
self.inner.unary(req, path, codec).await
}
/// Fetch specific version of a DID Document for a given DID
pub async fn did_doc_version(
&mut self,
request: impl tonic::IntoRequest<super::QueryDidDocVersionRequest>,
) -> std::result::Result<
tonic::Response<super::QueryDidDocVersionResponse>,
tonic::Status,
> {
self.inner
.ready()
.await
.map_err(|e| {
tonic::Status::unknown(
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cheqd.did.v2.Query/DidDocVersion",
);
let mut req = request.into_request();
req.extensions_mut()
.insert(GrpcMethod::new("cheqd.did.v2.Query", "DidDocVersion"));
self.inner.unary(req, path, codec).await
}
/// Fetch list of all versions of DID Documents for a given DID
pub async fn all_did_doc_versions_metadata(
&mut self,
request: impl tonic::IntoRequest<
super::QueryAllDidDocVersionsMetadataRequest,
>,
) -> std::result::Result<
tonic::Response<super::QueryAllDidDocVersionsMetadataResponse>,
tonic::Status,
> {
self.inner
.ready()
.await
.map_err(|e| {
tonic::Status::unknown(
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cheqd.did.v2.Query/AllDidDocVersionsMetadata",
);
let mut req = request.into_request();
req.extensions_mut()
.insert(
GrpcMethod::new("cheqd.did.v2.Query", "AllDidDocVersionsMetadata"),
);
self.inner.unary(req, path, codec).await
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/src/proto/cheqd.resource.v2.rs | did_core/did_methods/did_cheqd/src/proto/cheqd.resource.v2.rs | // This file is @generated by prost-build.
/// Resource stores the contents of a DID-Linked Resource
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Resource {
/// bytes is the raw data of the Resource
#[prost(bytes = "vec", tag = "1")]
pub data: ::prost::alloc::vec::Vec<u8>,
}
/// Metadata stores the metadata of a DID-Linked Resource
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Metadata {
/// collection_id is the ID of the collection that the Resource belongs to. Defined client-side.
/// This field is the unique identifier of the DID linked to this Resource
/// Format: <unique-identifier>
///
/// Examples:
/// - c82f2b02-bdab-4dd7-b833-3e143745d612
/// - wGHEXrZvJxR8vw5P3UWH1j
#[prost(string, tag = "1")]
pub collection_id: ::prost::alloc::string::String,
/// id is the ID of the Resource. Defined client-side.
/// This field is a unique identifier for this specific version of the Resource.
/// Format: <uuid>
#[prost(string, tag = "2")]
pub id: ::prost::alloc::string::String,
/// name is a human-readable name for the Resource. Defined client-side.
/// Does not change between different versions.
/// Example: PassportSchema, EducationTrustRegistry
#[prost(string, tag = "3")]
pub name: ::prost::alloc::string::String,
/// version is a human-readable semantic version for the Resource. Defined client-side.
/// Stored as a string. OPTIONAL.
/// Example: 1.0.0, v2.1.0
#[prost(string, tag = "4")]
pub version: ::prost::alloc::string::String,
/// resource_type is a Resource type that identifies what the Resource is. Defined client-side.
/// This is NOT the same as the resource's media type.
/// Example: AnonCredsSchema, StatusList2021
#[prost(string, tag = "5")]
pub resource_type: ::prost::alloc::string::String,
/// List of alternative URIs for the SAME Resource.
#[prost(message, repeated, tag = "6")]
pub also_known_as: ::prost::alloc::vec::Vec<AlternativeUri>,
/// media_type is IANA media type of the Resource. Defined ledger-side.
/// Example: application/json, image/png
#[prost(string, tag = "7")]
pub media_type: ::prost::alloc::string::String,
/// created is the time at which the Resource was created. Defined ledger-side.
/// Format: RFC3339
/// Example: 2021-01-01T00:00:00Z
#[prost(message, optional, tag = "8")]
pub created: ::core::option::Option<::prost_types::Timestamp>,
/// checksum is a SHA-256 checksum hash of the Resource. Defined ledger-side.
/// Example: d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f
#[prost(string, tag = "9")]
pub checksum: ::prost::alloc::string::String,
/// previous_version_id is the ID of the previous version of the Resource. Defined ledger-side.
/// This is based on the Resource's name and Resource type to determine whether it's the same Resource.
/// Format: <uuid>
#[prost(string, tag = "10")]
pub previous_version_id: ::prost::alloc::string::String,
/// next_version_id is the ID of the next version of the Resource. Defined ledger-side.
/// This is based on the Resource's name and Resource type to determine whether it's the same Resource.
/// Format: <uuid>
#[prost(string, tag = "11")]
pub next_version_id: ::prost::alloc::string::String,
}
/// AlternativeUri are alternative URIs that can be used to access the Resource.
/// By default, at least the DID URI equivalent of the Resource is populated.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct AlternativeUri {
/// uri is the URI of the Resource.
/// Examples:
/// - did:cheqd:testnet:MjYxNzYKMjYxNzYK/resources/4600ea35-8916-4ac4-b412-55b8f49dd94e
/// - <https://resolver..cheqd.net/1.0/identifiers/did:cheqd:testnet:MjYxNzYKMjYxNzYK/resources/4600ea35-8916-4ac4-b412-55b8f49dd94e>
/// - <https://example.com/example.json>
/// - <https://gateway.ipfs.io/ipfs/bafybeihetj2ng3d74k7t754atv2s5dk76pcqtvxls6dntef3xa6rax25xe>
/// - ipfs://bafybeihetj2ng3d74k7t754atv2s5dk76pcqtvxls6dntef3xa6rax25xe
#[prost(string, tag = "1")]
pub uri: ::prost::alloc::string::String,
/// description is a human-readable description of the URI. Defined client-side.
/// Examples:
/// - did-uri
/// - http-uri
/// - ipfs-uri
#[prost(string, tag = "2")]
pub description: ::prost::alloc::string::String,
}
/// ResourceWithMetadata describes the overall structure of a DID-Linked Resource
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ResourceWithMetadata {
#[prost(message, optional, tag = "1")]
pub resource: ::core::option::Option<Resource>,
#[prost(message, optional, tag = "2")]
pub metadata: ::core::option::Option<Metadata>,
}
/// QueryResourceRequest is the request type for the Query/Resource RPC method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryResourceRequest {
/// collection_id is an identifier of the DidDocument the resource belongs to.
/// Format: <unique-identifier>
///
/// Examples:
/// - c82f2b02-bdab-4dd7-b833-3e143745d612
/// - wGHEXrZvJxR8vw5P3UWH1j
#[prost(string, tag = "1")]
pub collection_id: ::prost::alloc::string::String,
/// id is a unique id of the resource.
/// Format: <uuid>
#[prost(string, tag = "2")]
pub id: ::prost::alloc::string::String,
}
/// QueryResourceResponse is the response type for the Query/Resource RPC method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryResourceResponse {
/// Successful resolution of the resource returns the following:
/// - resource is the requested resource
/// - metadata is the resource metadata associated with the requested resource
#[prost(message, optional, tag = "1")]
pub resource: ::core::option::Option<ResourceWithMetadata>,
}
/// QueryResourceMetadataRequest is the request type for the Query/ResourceMetadata RPC method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryResourceMetadataRequest {
/// collection_id is an identifier of the DidDocument the resource belongs to.
/// Format: <unique-identifier>
///
/// Examples:
/// - c82f2b02-bdab-4dd7-b833-3e143745d612
/// - wGHEXrZvJxR8vw5P3UWH1j
#[prost(string, tag = "1")]
pub collection_id: ::prost::alloc::string::String,
/// id is a unique id of the resource.
/// Format: <uuid>
#[prost(string, tag = "2")]
pub id: ::prost::alloc::string::String,
}
/// QueryResourceMetadataResponse is the response type for the Query/ResourceMetadata RPC method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryResourceMetadataResponse {
/// resource is the requested resource metadata
#[prost(message, optional, tag = "1")]
pub resource: ::core::option::Option<Metadata>,
}
/// QueryCollectionResourcesRequest is the request type for the Query/CollectionResources RPC method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryCollectionResourcesRequest {
/// collection_id is an identifier of the DidDocument the resource belongs to.
/// Format: <unique-identifier>
///
/// Examples:
/// - c82f2b02-bdab-4dd7-b833-3e143745d612
/// - wGHEXrZvJxR8vw5P3UWH1j
#[prost(string, tag = "1")]
pub collection_id: ::prost::alloc::string::String,
/// pagination defines an optional pagination for the request.
#[prost(message, optional, tag = "2")]
pub pagination: ::core::option::Option<
super::super::super::cosmos::base::query::v1beta1::PageRequest,
>,
}
/// QueryCollectionResourcesResponse is the response type for the Query/CollectionResources RPC method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryCollectionResourcesResponse {
/// resources is the requested collection of resource metadata
#[prost(message, repeated, tag = "1")]
pub resources: ::prost::alloc::vec::Vec<Metadata>,
/// pagination defines the pagination in the response.
#[prost(message, optional, tag = "2")]
pub pagination: ::core::option::Option<
super::super::super::cosmos::base::query::v1beta1::PageResponse,
>,
}
/// Generated client implementations.
pub mod query_client {
#![allow(
unused_variables,
dead_code,
missing_docs,
clippy::wildcard_imports,
clippy::let_unit_value,
)]
use tonic::codegen::*;
use tonic::codegen::http::Uri;
/// Query defines the gRPC querier service for the resource module
#[derive(Debug, Clone)]
pub struct QueryClient<T> {
inner: tonic::client::Grpc<T>,
}
impl QueryClient<tonic::transport::Channel> {
/// Attempt to create a new client by connecting to a given endpoint.
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
where
D: TryInto<tonic::transport::Endpoint>,
D::Error: Into<StdError>,
{
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
Ok(Self::new(conn))
}
}
impl<T> QueryClient<T>
where
T: tonic::client::GrpcService<tonic::body::BoxBody>,
T::Error: Into<StdError>,
T::ResponseBody: Body<Data = Bytes> + std::marker::Send + 'static,
<T::ResponseBody as Body>::Error: Into<StdError> + std::marker::Send,
{
pub fn new(inner: T) -> Self {
let inner = tonic::client::Grpc::new(inner);
Self { inner }
}
pub fn with_origin(inner: T, origin: Uri) -> Self {
let inner = tonic::client::Grpc::with_origin(inner, origin);
Self { inner }
}
pub fn with_interceptor<F>(
inner: T,
interceptor: F,
) -> QueryClient<InterceptedService<T, F>>
where
F: tonic::service::Interceptor,
T::ResponseBody: Default,
T: tonic::codegen::Service<
http::Request<tonic::body::BoxBody>,
Response = http::Response<
<T as tonic::client::GrpcService<tonic::body::BoxBody>>::ResponseBody,
>,
>,
<T as tonic::codegen::Service<
http::Request<tonic::body::BoxBody>,
>>::Error: Into<StdError> + std::marker::Send + std::marker::Sync,
{
QueryClient::new(InterceptedService::new(inner, interceptor))
}
/// Compress requests with the given encoding.
///
/// This requires the server to support it otherwise it might respond with an
/// error.
#[must_use]
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
self.inner = self.inner.send_compressed(encoding);
self
}
/// Enable decompressing responses.
#[must_use]
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
self.inner = self.inner.accept_compressed(encoding);
self
}
/// Limits the maximum size of a decoded message.
///
/// Default: `4MB`
#[must_use]
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
self.inner = self.inner.max_decoding_message_size(limit);
self
}
/// Limits the maximum size of an encoded message.
///
/// Default: `usize::MAX`
#[must_use]
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
self.inner = self.inner.max_encoding_message_size(limit);
self
}
/// Fetch data/payload for a specific resource (without metadata)
pub async fn resource(
&mut self,
request: impl tonic::IntoRequest<super::QueryResourceRequest>,
) -> std::result::Result<
tonic::Response<super::QueryResourceResponse>,
tonic::Status,
> {
self.inner
.ready()
.await
.map_err(|e| {
tonic::Status::unknown(
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cheqd.resource.v2.Query/Resource",
);
let mut req = request.into_request();
req.extensions_mut()
.insert(GrpcMethod::new("cheqd.resource.v2.Query", "Resource"));
self.inner.unary(req, path, codec).await
}
/// Fetch only metadata for a specific resource
pub async fn resource_metadata(
&mut self,
request: impl tonic::IntoRequest<super::QueryResourceMetadataRequest>,
) -> std::result::Result<
tonic::Response<super::QueryResourceMetadataResponse>,
tonic::Status,
> {
self.inner
.ready()
.await
.map_err(|e| {
tonic::Status::unknown(
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cheqd.resource.v2.Query/ResourceMetadata",
);
let mut req = request.into_request();
req.extensions_mut()
.insert(GrpcMethod::new("cheqd.resource.v2.Query", "ResourceMetadata"));
self.inner.unary(req, path, codec).await
}
/// Fetch metadata for all resources in a collection
pub async fn collection_resources(
&mut self,
request: impl tonic::IntoRequest<super::QueryCollectionResourcesRequest>,
) -> std::result::Result<
tonic::Response<super::QueryCollectionResourcesResponse>,
tonic::Status,
> {
self.inner
.ready()
.await
.map_err(|e| {
tonic::Status::unknown(
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cheqd.resource.v2.Query/CollectionResources",
);
let mut req = request.into_request();
req.extensions_mut()
.insert(
GrpcMethod::new("cheqd.resource.v2.Query", "CollectionResources"),
);
self.inner.unary(req, path, codec).await
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/src/error/mod.rs | did_core/did_methods/did_cheqd/src/error/mod.rs | use parsing::ParsingErrorSource;
use thiserror::Error;
pub mod parsing;
pub type DidCheqdResult<T> = Result<T, DidCheqdError>;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum DidCheqdError {
#[error("DID method not supported: {0}")]
MethodNotSupported(String),
#[error("Cheqd network not supported: {0}")]
NetworkNotSupported(String),
#[error("Bad configuration: {0}")]
BadConfiguration(String),
#[error("Transport error: {0}")]
TransportError(#[from] tonic::transport::Error),
#[error("Non-success resolver response: {0}")]
NonSuccessResponse(#[from] tonic::Status),
#[error("Response from resolver is invalid: {0}")]
InvalidResponse(String),
#[error("Invalid DID Document structure resolved: {0}")]
InvalidDidDocument(String),
#[error("Invalid DID Url: {0}")]
InvalidDidUrl(String),
#[error("Resource could not be found: {0}")]
ResourceNotFound(String),
#[error("Parsing error: {0}")]
ParsingError(#[from] ParsingErrorSource),
#[error(transparent)]
Other(#[from] Box<dyn std::error::Error + Send + Sync>),
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/src/error/parsing.rs | did_core/did_methods/did_cheqd/src/error/parsing.rs | use did_resolver::{did_doc::schema::types::uri::UriWrapperError, did_parser_nom};
use thiserror::Error;
use super::DidCheqdError;
#[derive(Error, Debug)]
pub enum ParsingErrorSource {
#[error("DID document parsing error: {0}")]
DidDocumentParsingError(#[from] did_parser_nom::ParseError),
#[error("DID document parsing URI error: {0}")]
DidDocumentParsingUriError(#[from] UriWrapperError),
#[error("JSON parsing error: {0}")]
JsonError(#[from] serde_json::Error),
#[error("Invalid URL: {0}")]
UrlParsingError(url::ParseError),
#[error("Invalid encoding: {0}")]
Utf8Error(#[from] std::string::FromUtf8Error),
#[error("Invalid encoding: {0}")]
IntConversionError(#[from] std::num::TryFromIntError),
}
impl From<did_parser_nom::ParseError> for DidCheqdError {
fn from(error: did_parser_nom::ParseError) -> Self {
DidCheqdError::ParsingError(ParsingErrorSource::DidDocumentParsingError(error))
}
}
impl From<UriWrapperError> for DidCheqdError {
fn from(error: UriWrapperError) -> Self {
DidCheqdError::ParsingError(ParsingErrorSource::DidDocumentParsingUriError(error))
}
}
impl From<serde_json::Error> for DidCheqdError {
fn from(error: serde_json::Error) -> Self {
DidCheqdError::ParsingError(ParsingErrorSource::JsonError(error))
}
}
impl From<url::ParseError> for DidCheqdError {
fn from(error: url::ParseError) -> Self {
DidCheqdError::ParsingError(ParsingErrorSource::UrlParsingError(error))
}
}
impl From<std::string::FromUtf8Error> for DidCheqdError {
fn from(error: std::string::FromUtf8Error) -> Self {
DidCheqdError::ParsingError(ParsingErrorSource::Utf8Error(error))
}
}
impl From<std::num::TryFromIntError> for DidCheqdError {
fn from(error: std::num::TryFromIntError) -> Self {
DidCheqdError::ParsingError(ParsingErrorSource::IntConversionError(error))
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/src/resolution/mod.rs | did_core/did_methods/did_cheqd/src/resolution/mod.rs | pub mod resolver;
pub mod transformer;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/src/resolution/resolver.rs | did_core/did_methods/did_cheqd/src/resolution/resolver.rs | use std::{cmp::Ordering, collections::HashMap};
use async_trait::async_trait;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use did_resolver::{
did_doc::schema::did_doc::DidDocument,
did_parser_nom::{Did, DidUrl},
error::GenericError,
shared_types::{
did_document_metadata::DidDocumentMetadata,
did_resource::{DidResource, DidResourceMetadata},
},
traits::resolvable::{resolution_output::DidResolutionOutput, DidResolvable},
};
use http_body_util::combinators::UnsyncBoxBody;
use hyper_tls::HttpsConnector;
use hyper_util::{
client::legacy::{connect::HttpConnector, Client},
rt::TokioExecutor,
};
use tokio::sync::Mutex;
use tonic::{transport::Uri, Status};
use super::transformer::CheqdResourceMetadataWithUri;
use crate::{
error::{DidCheqdError, DidCheqdResult},
proto::cheqd::{
did::v2::{query_client::QueryClient as DidQueryClient, QueryDidDocRequest},
resource::v2::{
query_client::QueryClient as ResourceQueryClient, Metadata as CheqdResourceMetadata,
QueryCollectionResourcesRequest, QueryResourceRequest,
},
},
};
/// default namespace for the cheqd "mainnet". as it would appear in a DID.
pub const MAINNET_NAMESPACE: &str = "mainnet";
/// default gRPC URL for the cheqd "mainnet".
pub const MAINNET_DEFAULT_GRPC: &str = "https://grpc.cheqd.net:443";
/// default namespace for the cheqd "testnet". as it would appear in a DID.
pub const TESTNET_NAMESPACE: &str = "testnet";
/// default gRPC URL for the cheqd "testnet".
pub const TESTNET_DEFAULT_GRPC: &str = "https://grpc.cheqd.network:443";
/// Configuration for the [DidCheqdResolver] resolver
pub struct DidCheqdResolverConfiguration {
/// Configuration for which networks are resolvable
pub networks: Vec<NetworkConfiguration>,
}
impl Default for DidCheqdResolverConfiguration {
fn default() -> Self {
Self {
networks: vec![
NetworkConfiguration::mainnet(),
NetworkConfiguration::testnet(),
],
}
}
}
/// Configuration for a cheqd network. Defining details such as where to resolve DIDs from.
pub struct NetworkConfiguration {
/// the cheqd nodes gRPC URL
pub grpc_url: String,
/// the namespace of the network - as it would appear in a DID (did:cheqd:namespace:123)
pub namespace: String,
}
impl NetworkConfiguration {
/// default configuration for cheqd mainnet
pub fn mainnet() -> Self {
Self {
grpc_url: String::from(MAINNET_DEFAULT_GRPC),
namespace: String::from(MAINNET_NAMESPACE),
}
}
/// default configuration for cheqd testnet
pub fn testnet() -> Self {
Self {
grpc_url: String::from(TESTNET_DEFAULT_GRPC),
namespace: String::from(TESTNET_NAMESPACE),
}
}
}
type HyperClient = Client<HttpsConnector<HttpConnector>, UnsyncBoxBody<Bytes, Status>>;
#[derive(Clone)]
struct CheqdGrpcClient {
did: DidQueryClient<HyperClient>,
resources: ResourceQueryClient<HyperClient>,
}
pub struct DidCheqdResolver {
networks: Vec<NetworkConfiguration>,
network_clients: Mutex<HashMap<String, CheqdGrpcClient>>,
}
#[async_trait]
impl DidResolvable for DidCheqdResolver {
type DidResolutionOptions = ();
async fn resolve(
&self,
did: &Did,
_: &Self::DidResolutionOptions,
) -> Result<DidResolutionOutput, GenericError> {
Ok(self.resolve_did(did).await?)
}
}
impl DidCheqdResolver {
/// Assemble a new resolver with the given config.
///
/// [DidCheqdResolverConfiguration::default] can be used if default mainnet & testnet
/// configurations are suitable.
pub fn new(configuration: DidCheqdResolverConfiguration) -> Self {
Self {
networks: configuration.networks,
network_clients: Default::default(),
}
}
/// lazily get the client, initializing if not already
async fn client_for_network(&self, network: &str) -> DidCheqdResult<CheqdGrpcClient> {
let mut lock = self.network_clients.lock().await;
if let Some(client) = lock.get(network) {
return Ok(client.clone());
}
let network_config = self
.networks
.iter()
.find(|n| n.namespace == network)
.ok_or(DidCheqdError::NetworkNotSupported(network.to_owned()))?;
let client = native_tls_hyper_client()?;
let origin: Uri = network_config.grpc_url.parse().map_err(|e| {
DidCheqdError::BadConfiguration(format!(
"GRPC URL is not a URI: {} {e}",
network_config.grpc_url
))
})?;
let did_client = DidQueryClient::with_origin(client.clone(), origin.clone());
let resource_client = ResourceQueryClient::with_origin(client, origin);
let client = CheqdGrpcClient {
did: did_client,
resources: resource_client,
};
lock.insert(network.to_owned(), client.clone());
Ok(client)
}
/// Resolve a cheqd DID.
pub async fn resolve_did(&self, did: &Did) -> DidCheqdResult<DidResolutionOutput> {
let method = did.method();
if method != Some("cheqd") {
return Err(DidCheqdError::MethodNotSupported(format!("{method:?}")));
}
let network = did.namespace().unwrap_or(MAINNET_NAMESPACE);
let mut client = self.client_for_network(network).await?;
let did = did.did().to_owned();
let request = tonic::Request::new(QueryDidDocRequest { id: did });
let response = client.did.did_doc(request).await?;
let query_response = response.into_inner();
let query_doc_res = query_response.value.ok_or(DidCheqdError::InvalidResponse(
"DIDDoc query did not return a value".into(),
))?;
let query_doc = query_doc_res.did_doc.ok_or(DidCheqdError::InvalidResponse(
"DIDDoc query did not return a DIDDoc".into(),
))?;
let mut output_builder = DidResolutionOutput::builder(DidDocument::try_from(query_doc)?);
if let Some(query_metadata) = query_doc_res.metadata {
// FUTURE - append linked resources to metadata
output_builder = output_builder
.did_document_metadata(DidDocumentMetadata::try_from(query_metadata)?);
}
Ok(output_builder.build())
}
/// Resolve a cheqd DID resource & associated metadata from the given [DidUrl].
/// Resolution is done according to the [DID-Linked Resources](https://w3c-ccg.github.io/DID-Linked-Resources/)
/// specification, however only a subset of query types are supported currently:
/// * by resource path: `did:example:<unique-identifier>/resources/<unique-identifier>`
/// * by name & type: `did:cheqd:mainnet:zF7rhDBfUt9d1gJPjx7s1J?resourceName=universityDegree&
/// resourceType=anonCredsStatusList`
/// * by name & type & time:
/// `did:cheqd:mainnet:zF7rhDBfUt9d1gJPjx7s1J?resourceName=universityDegree&
/// resourceType=anonCredsStatusList&versionTime=2022-08-21T08:40:00Z`
pub async fn resolve_resource(&self, url: &DidUrl) -> DidCheqdResult<DidResource> {
let method = url.method();
if method != Some("cheqd") {
return Err(DidCheqdError::MethodNotSupported(format!("{method:?}")));
}
let network = url.namespace().unwrap_or(MAINNET_NAMESPACE);
let did_id = url
.id()
.ok_or(DidCheqdError::InvalidDidUrl(format!("missing ID {url}")))?;
// 1. resolve by exact reference: /resources/asdf
if let Some(path) = url.path() {
let Some(resource_id) = path.strip_prefix("/resources/") else {
return Err(DidCheqdError::InvalidDidUrl(format!(
"DID Resource URL has a path without `/resources/`: {path}"
)));
};
return self
.resolve_resource_by_id(did_id, resource_id, network)
.await;
}
// 2. resolve by name & type & time (if any)
let params = url.queries();
let resource_name = params.get("resourceName");
let resource_type = params.get("resourceType");
let version_time = params.get("resourceVersionTime");
let (Some(resource_name), Some(resource_type)) = (resource_name, resource_type) else {
return Err(DidCheqdError::InvalidDidUrl(format!(
"Resolver can only resolve by exact resource ID or name+type combination {url}"
)))?;
};
// determine desired version_time, either from param, or *now*
let version_time = match version_time {
Some(v) => DateTime::parse_from_rfc3339(v)
.map_err(|e| DidCheqdError::InvalidDidUrl(e.to_string()))?
.to_utc(),
None => Utc::now(),
};
self.resolve_resource_by_name_type_and_time(
did_id,
resource_name,
resource_type,
version_time,
network,
)
.await
}
/// Resolve a resource from a collection (did_id) and network by an exact id.
async fn resolve_resource_by_id(
&self,
did_id: &str,
resource_id: &str,
network: &str,
) -> DidCheqdResult<DidResource> {
let mut client = self.client_for_network(network).await?;
let request = QueryResourceRequest {
collection_id: did_id.to_owned(),
id: resource_id.to_owned(),
};
let response = client.resources.resource(request).await?;
let query_response = response.into_inner();
let query_response = query_response
.resource
.ok_or(DidCheqdError::InvalidResponse(
"Resource query did not return a value".into(),
))?;
let query_resource = query_response
.resource
.ok_or(DidCheqdError::InvalidResponse(
"Resource query did not return a resource".into(),
))?;
let query_metadata = query_response
.metadata
.ok_or(DidCheqdError::InvalidResponse(
"Resource query did not return metadata".into(),
))?;
let metadata = DidResourceMetadata::try_from(CheqdResourceMetadataWithUri {
uri: format!(
"did:cheqd:{network}:{}/resources/{}",
query_metadata.collection_id, query_metadata.id
),
meta: query_metadata,
})?;
Ok(DidResource {
content: query_resource.data,
metadata,
})
}
/// Resolve a resource from a given collection (did_id) & network, that has a given name & type,
/// as of a given time.
async fn resolve_resource_by_name_type_and_time(
&self,
did_id: &str,
name: &str,
rtyp: &str,
time: DateTime<Utc>,
network: &str,
) -> DidCheqdResult<DidResource> {
let mut client = self.client_for_network(network).await?;
let response = client
.resources
.collection_resources(QueryCollectionResourcesRequest {
collection_id: did_id.to_owned(),
// FUTURE - pagination
pagination: None,
})
.await?;
let query_response = response.into_inner();
let resources = query_response.resources;
let mut filtered: Vec<_> =
filter_resources_by_name_and_type(resources.iter(), name, rtyp).collect();
filtered.sort_by(|a, b| desc_chronological_sort_resources(a, b));
let resource_meta = find_resource_just_before_time(filtered.into_iter(), time);
let Some(meta) = resource_meta else {
return Err(DidCheqdError::ResourceNotFound(format!(
"network: {network}, collection: {did_id}, name: {name}, type: {rtyp}, time: \
{time}"
)));
};
self.resolve_resource_by_id(did_id, &meta.id, network).await
}
}
/// Assembles a hyper client which:
/// * uses native TLS
/// * supports HTTP2 only (gRPC)
#[allow(clippy::result_large_err)]
fn native_tls_hyper_client() -> DidCheqdResult<HyperClient> {
let tls = native_tls::TlsConnector::builder()
.request_alpns(&["h2"])
.build()
.map_err(|e| {
DidCheqdError::BadConfiguration(format!("Failed to build TlsConnector: {e}"))
})?;
let mut http = HttpConnector::new();
http.enforce_http(false);
let connector = HttpsConnector::from((http, tls.into()));
Ok(Client::builder(TokioExecutor::new())
.http2_only(true)
.build(connector))
}
/// Filter for resources which have a matching name and type
fn filter_resources_by_name_and_type<'a>(
resources: impl Iterator<Item = &'a CheqdResourceMetadata> + 'a,
name: &'a str,
rtyp: &'a str,
) -> impl Iterator<Item = &'a CheqdResourceMetadata> + 'a {
resources.filter(move |r| r.name == name && r.resource_type == rtyp)
}
/// Sort resources chronologically by their created timestamps
fn desc_chronological_sort_resources(
b: &CheqdResourceMetadata,
a: &CheqdResourceMetadata,
) -> Ordering {
let (a_secs, a_ns) = a
.created
.map(|v| {
let v = v.normalized();
(v.seconds, v.nanos)
})
.unwrap_or((0, 0));
let (b_secs, b_ns) = b
.created
.map(|v| {
let v = v.normalized();
(v.seconds, v.nanos)
})
.unwrap_or((0, 0));
match a_secs.cmp(&b_secs) {
Ordering::Equal => a_ns.cmp(&b_ns),
res => res,
}
}
/// assuming `resources` is sorted by `.created` time in descending order, find
/// the resource which is closest to `before_time`, but NOT after.
///
/// Returns a reference to this resource if it exists.
///
/// e.g.:
/// resources: [{created: 20}, {created: 15}, {created: 10}, {created: 5}]
/// before_time: 14
/// returns: {created: 10}
///
/// resources: [{created: 20}, {created: 15}, {created: 10}, {created: 5}]
/// before_time: 4
/// returns: None
fn find_resource_just_before_time<'a>(
resources: impl Iterator<Item = &'a CheqdResourceMetadata>,
before_time: DateTime<Utc>,
) -> Option<&'a CheqdResourceMetadata> {
let before_epoch = before_time.timestamp();
for r in resources {
let Some(created) = r.created else {
continue;
};
let created_epoch = created.normalized().seconds;
if created_epoch < before_epoch {
return Some(r);
}
}
None
}
#[cfg(test)]
mod unit_tests {
use super::*;
#[tokio::test]
async fn test_resolve_fails_if_wrong_method() {
let did = "did:notcheqd:abc".parse().unwrap();
let resolver = DidCheqdResolver::new(Default::default());
let e = resolver.resolve_did(&did).await.unwrap_err();
assert!(matches!(e, DidCheqdError::MethodNotSupported(_)));
}
#[tokio::test]
async fn test_resolve_fails_if_no_network_config() {
let did = "did:cheqd:devnet:Ps1ysXP2Ae6GBfxNhNQNKN".parse().unwrap();
let resolver = DidCheqdResolver::new(Default::default());
let e = resolver.resolve_did(&did).await.unwrap_err();
assert!(matches!(e, DidCheqdError::NetworkNotSupported(_)));
}
#[tokio::test]
async fn test_resolve_fails_if_bad_network_uri() {
let did = "did:cheqd:devnet:Ps1ysXP2Ae6GBfxNhNQNKN".parse().unwrap();
let config = DidCheqdResolverConfiguration {
networks: vec![NetworkConfiguration {
grpc_url: "@baduri://.".into(),
namespace: "devnet".into(),
}],
};
let resolver = DidCheqdResolver::new(config);
let e = resolver.resolve_did(&did).await.unwrap_err();
assert!(matches!(e, DidCheqdError::BadConfiguration(_)));
}
#[tokio::test]
async fn test_resolve_resource_fails_if_wrong_method() {
let url = "did:notcheqd:zF7rhDBfUt9d1gJPjx7s1J/resources/123"
.parse()
.unwrap();
let resolver = DidCheqdResolver::new(Default::default());
let e = resolver.resolve_resource(&url).await.unwrap_err();
assert!(matches!(e, DidCheqdError::MethodNotSupported(_)));
}
#[tokio::test]
async fn test_resolve_resource_fails_if_wrong_path() {
let url = "did:cheqd:mainnet:zF7rhDBfUt9d1gJPjx7s1J/resource/123"
.parse()
.unwrap();
let resolver = DidCheqdResolver::new(Default::default());
let e = resolver.resolve_resource(&url).await.unwrap_err();
assert!(matches!(e, DidCheqdError::InvalidDidUrl(_)));
}
#[tokio::test]
async fn test_resolve_resource_fails_if_no_query() {
let url = "did:cheqd:mainnet:zF7rhDBfUt9d1gJPjx7s1J".parse().unwrap();
let resolver = DidCheqdResolver::new(Default::default());
let e = resolver.resolve_resource(&url).await.unwrap_err();
assert!(matches!(e, DidCheqdError::InvalidDidUrl(_)));
}
#[tokio::test]
async fn test_resolve_resource_fails_if_incomplete_query() {
let url = "did:cheqd:mainnet:zF7rhDBfUt9d1gJPjx7s1J?resourceName=asdf"
.parse()
.unwrap();
let resolver = DidCheqdResolver::new(Default::default());
let e = resolver.resolve_resource(&url).await.unwrap_err();
assert!(matches!(e, DidCheqdError::InvalidDidUrl(_)));
}
#[tokio::test]
async fn test_resolve_resource_fails_if_invalid_resource_time() {
// use epoch instead of XML DateTime
let url = "did:cheqd:mainnet:zF7rhDBfUt9d1gJPjx7s1J?resourceName=asdf&resourceType=fdsa&\
resourceVersionTime=12341234"
.parse()
.unwrap();
let resolver = DidCheqdResolver::new(Default::default());
let e = resolver.resolve_resource(&url).await.unwrap_err();
assert!(matches!(e, DidCheqdError::InvalidDidUrl(_)));
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/src/resolution/transformer.rs | did_core/did_methods/did_cheqd/src/resolution/transformer.rs | use std::str::FromStr;
use chrono::{DateTime, Utc};
use did_resolver::{
did_doc::schema::{
contexts,
did_doc::DidDocument,
service::Service,
types::uri::Uri,
utils::OneOrList,
verification_method::{PublicKeyField, VerificationMethod, VerificationMethodType},
},
did_parser_nom::{Did, DidUrl},
shared_types::{did_document_metadata::DidDocumentMetadata, did_resource::DidResourceMetadata},
};
use serde_json::{json, Value};
use crate::{
error::{DidCheqdError, DidCheqdResult},
proto::cheqd::{
did::v2::{
DidDoc as CheqdDidDoc, Metadata as CheqdDidDocMetadata, Service as CheqdService,
VerificationMethod as CheqdVerificationMethod,
},
resource::v2::Metadata as CheqdResourceMetadata,
},
};
impl TryFrom<CheqdDidDoc> for DidDocument {
type Error = DidCheqdError;
fn try_from(value: CheqdDidDoc) -> Result<Self, Self::Error> {
let mut doc = DidDocument::new(value.id.parse()?);
let mut context = value.context;
// insert default context
if !context
.iter()
.any(|ctx| ctx == contexts::W3C_DID_V1 || ctx == contexts::W3C_DID_V1_ALT)
{
context.push(contexts::W3C_DID_V1.to_owned());
}
let controller: Vec<_> = value
.controller
.into_iter()
.map(Did::parse)
.collect::<Result<_, _>>()?;
if !controller.is_empty() {
doc.set_controller(OneOrList::from(controller));
}
for vm in value.verification_method {
let vm = VerificationMethod::try_from(vm)?;
let vm_ctx = vm.verification_method_type().context_for_type();
if !context.iter().any(|ctx| ctx == vm_ctx) {
context.push(vm_ctx.to_owned());
}
doc.add_verification_method(vm);
}
for vm_id in value.authentication {
doc.add_authentication_ref(vm_id.parse()?);
}
for vm_id in value.assertion_method {
// try assertionMethod string as did:url
if let Ok(vm_did_url) = vm_id.parse::<DidUrl>() {
doc.add_assertion_method_ref(vm_did_url);
continue;
}
// try assertionMethod as JSON
let vm: VerificationMethod = match serde_json::from_str::<Value>(&vm_id)? {
Value::String(vm_str) => {
// it's possible that a JSON string JSON obj is returned
serde_json::from_str(&vm_str)?
}
Value::Object(vm_obj) => {
serde_json::from_value(Value::Object(vm_obj))?
}
other_json => return Err(DidCheqdError::InvalidDidDocument(format!("DID Document assertionMethod was not a valid JSON type. expected JSON string or object, found: {other_json}")))
};
doc.add_assertion_method_object(vm);
}
for vm_id in value.capability_invocation {
doc.add_capability_invocation_ref(vm_id.parse()?);
}
for vm_id in value.capability_delegation {
doc.add_capability_delegation_ref(vm_id.parse()?);
}
for vm_id in value.key_agreement {
doc.add_key_agreement_ref(vm_id.parse()?);
}
for svc in value.service {
let svc = Service::try_from(svc)?;
doc.add_service(svc);
}
let aka: Vec<_> = value
.also_known_as
.iter()
.map(|aka| Uri::from_str(aka))
.collect::<Result<_, _>>()?;
doc.set_also_known_as(aka);
// add in all contexts
doc.set_extra_field(String::from("@context"), json!(context));
Ok(doc)
}
}
impl TryFrom<CheqdVerificationMethod> for VerificationMethod {
type Error = DidCheqdError;
fn try_from(value: CheqdVerificationMethod) -> Result<Self, Self::Error> {
let vm_type: VerificationMethodType =
serde_json::from_value(json!(value.verification_method_type))?;
let vm_key_encoded = value.verification_material;
let pk = match vm_type {
VerificationMethodType::Ed25519VerificationKey2020 => PublicKeyField::Multibase {
public_key_multibase: vm_key_encoded,
},
VerificationMethodType::JsonWebKey2020 => PublicKeyField::Jwk {
public_key_jwk: serde_json::from_str(&vm_key_encoded)?,
},
VerificationMethodType::Ed25519VerificationKey2018 => PublicKeyField::Base58 {
public_key_base58: vm_key_encoded,
},
// https://w3c.github.io/vc-di-bbs/contexts/v1/
VerificationMethodType::Bls12381G1Key2020 => PublicKeyField::Base58 {
public_key_base58: vm_key_encoded,
},
// https://w3c.github.io/vc-di-bbs/contexts/v1/
VerificationMethodType::Bls12381G2Key2020 => PublicKeyField::Base58 {
public_key_base58: vm_key_encoded,
},
// https://ns.did.ai/suites/x25519-2019/v1/
VerificationMethodType::X25519KeyAgreementKey2019 => PublicKeyField::Base58 {
public_key_base58: vm_key_encoded,
},
// https://ns.did.ai/suites/x25519-2020/v1/
VerificationMethodType::X25519KeyAgreementKey2020 => PublicKeyField::Multibase {
public_key_multibase: vm_key_encoded,
},
// https://w3c.github.io/vc-data-integrity/contexts/multikey/v1.jsonld
VerificationMethodType::Multikey => PublicKeyField::Multibase {
public_key_multibase: vm_key_encoded,
},
// https://w3id.org/pgp/v1
VerificationMethodType::PgpVerificationKey2021 => PublicKeyField::Pgp {
public_key_pgp: vm_key_encoded,
},
// cannot infer encoding type from vm type, as multiple are supported: https://ns.did.ai/suites/secp256k1-2019/v1/
VerificationMethodType::EcdsaSecp256k1VerificationKey2019 => {
return Err(DidCheqdError::InvalidDidDocument(
"DidDocument uses VM type of EcdsaSecp256k1VerificationKey2019, cannot process"
.into(),
))
}
// cannot infer encoding type from vm type: https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld
VerificationMethodType::EcdsaSecp256k1RecoveryMethod2020 => {
return Err(DidCheqdError::InvalidDidDocument(
"DidDocument uses VM type of EcdsaSecp256k1RecoveryMethod2020, cannot process"
.into(),
))
}
};
let vm = VerificationMethod::builder()
.id(value.id.parse()?)
.verification_method_type(vm_type)
.controller(value.controller.parse()?)
.public_key(pk)
.build();
Ok(vm)
}
}
impl TryFrom<CheqdService> for Service {
type Error = DidCheqdError;
fn try_from(value: CheqdService) -> Result<Self, Self::Error> {
// TODO #1301 - fix mapping: https://github.com/openwallet-foundation/vcx/issues/1301
let endpoint =
value
.service_endpoint
.into_iter()
.next()
.ok_or(DidCheqdError::InvalidDidDocument(
"DID Document Service is missing an endpoint".into(),
))?;
let svc = Service::new(
Uri::from_str(&value.id)?,
endpoint.parse()?,
serde_json::from_value(json!(value.service_type))?,
Default::default(),
);
Ok(svc)
}
}
impl TryFrom<CheqdDidDocMetadata> for DidDocumentMetadata {
type Error = DidCheqdError;
fn try_from(value: CheqdDidDocMetadata) -> Result<Self, Self::Error> {
let mut builder = DidDocumentMetadata::builder();
if let Some(timestamp) = value.created {
builder = builder.created(prost_timestamp_to_dt(timestamp)?);
}
if let Some(timestamp) = value.updated {
builder = builder.updated(prost_timestamp_to_dt(timestamp)?);
}
builder = builder
.deactivated(value.deactivated)
.version_id(value.version_id)
.next_version_id(value.next_version_id);
Ok(builder.build())
}
}
pub(super) struct CheqdResourceMetadataWithUri {
pub uri: String,
pub meta: CheqdResourceMetadata,
}
impl TryFrom<CheqdResourceMetadataWithUri> for DidResourceMetadata {
type Error = DidCheqdError;
fn try_from(value: CheqdResourceMetadataWithUri) -> Result<Self, Self::Error> {
let uri = value.uri;
let value = value.meta;
let Some(created) = value.created else {
return Err(DidCheqdError::InvalidDidDocument(format!(
"created field missing from resource: {value:?}"
)))?;
};
let version = (!value.version.trim().is_empty()).then_some(value.version);
let previous_version_id =
(!value.previous_version_id.trim().is_empty()).then_some(value.previous_version_id);
let next_version_id =
(!value.next_version_id.trim().is_empty()).then_some(value.next_version_id);
let also_known_as = value
.also_known_as
.into_iter()
.map(|aka| {
json!({
"uri": aka.uri,
"description": aka.description
})
})
.collect();
Ok(DidResourceMetadata::builder()
.resource_uri(uri)
.resource_collection_id(value.collection_id)
.resource_id(value.id)
.resource_name(value.name)
.resource_type(value.resource_type)
.resource_version(version)
.also_known_as(Some(also_known_as))
.media_type(value.media_type)
.created(prost_timestamp_to_dt(created)?)
.updated(None)
.checksum(value.checksum)
.previous_version_id(previous_version_id)
.next_version_id(next_version_id)
.build())
}
}
#[allow(clippy::result_large_err)]
fn prost_timestamp_to_dt(mut timestamp: prost_types::Timestamp) -> DidCheqdResult<DateTime<Utc>> {
timestamp.normalize();
DateTime::from_timestamp(timestamp.seconds, timestamp.nanos.try_into()?).ok_or(
DidCheqdError::Other(format!("Unknown error, bad timestamp: {timestamp:?}").into()),
)
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_cheqd/tests/resolution.rs | did_core/did_methods/did_cheqd/tests/resolution.rs | use did_cheqd::resolution::resolver::{DidCheqdResolver, DidCheqdResolverConfiguration};
use did_resolver::{did_parser_nom::Did, traits::resolvable::DidResolvable};
use serde_json::{json, Value};
#[tokio::test]
async fn test_resolve_known_mainnet_did_vector() {
// sample from https://dev.uniresolver.io/
let did = "did:cheqd:mainnet:Ps1ysXP2Ae6GBfxNhNQNKN".parse().unwrap();
// NOTE: modifications from uni-resolver:
// make serviceEndpoints into single item (not array)
let expected_doc = json!({
"@context": [
"https://www.w3.org/ns/did/v1",
"https://w3id.org/security/suites/ed25519-2020/v1"
],
"id": "did:cheqd:mainnet:Ps1ysXP2Ae6GBfxNhNQNKN",
"verificationMethod": [
{
"id": "did:cheqd:mainnet:Ps1ysXP2Ae6GBfxNhNQNKN#key1",
"type": "Ed25519VerificationKey2020",
"controller": "did:cheqd:mainnet:Ps1ysXP2Ae6GBfxNhNQNKN",
"publicKeyMultibase": "z6Mkta7joRuvDh7UnoESdgpr9dDUMh5LvdoECDi3WGrJoscA"
}
],
"authentication": [
"did:cheqd:mainnet:Ps1ysXP2Ae6GBfxNhNQNKN#key1"
],
"service": [
{
"id": "did:cheqd:mainnet:Ps1ysXP2Ae6GBfxNhNQNKN#website",
"type": "LinkedDomains",
"serviceEndpoint": "https://www.cheqd.io/"
},
{
"id": "did:cheqd:mainnet:Ps1ysXP2Ae6GBfxNhNQNKN#non-fungible-image",
"type": "LinkedDomains",
"serviceEndpoint": "https://gateway.ipfs.io/ipfs/bafybeihetj2ng3d74k7t754atv2s5dk76pcqtvxls6dntef3xa6rax25xe"
},
{
"id": "did:cheqd:mainnet:Ps1ysXP2Ae6GBfxNhNQNKN#twitter",
"type": "LinkedDomains",
"serviceEndpoint": "https://twitter.com/cheqd_io"
},
{
"id": "did:cheqd:mainnet:Ps1ysXP2Ae6GBfxNhNQNKN#linkedin",
"type": "LinkedDomains",
"serviceEndpoint": "https://www.linkedin.com/company/cheqd-identity/"
}
]
});
let resolver = DidCheqdResolver::new(DidCheqdResolverConfiguration::default());
let output = resolver.resolve(&did, &()).await.unwrap();
let doc = output.did_document;
assert_eq!(serde_json::to_value(doc.clone()).unwrap(), expected_doc);
assert_eq!(doc, serde_json::from_value(expected_doc).unwrap());
}
#[tokio::test]
async fn test_resolve_known_testnet_did_vector() {
// sample from https://dev.uniresolver.io/
let did = "did:cheqd:testnet:55dbc8bf-fba3-4117-855c-1e0dc1d3bb47"
.parse()
.unwrap();
// NOTE: modifications from uni-resolver:
// * made controller a single item
let expected_doc = json!({
"@context": [
"https://www.w3.org/ns/did/v1",
"https://w3id.org/security/suites/ed25519-2020/v1"
],
"id": "did:cheqd:testnet:55dbc8bf-fba3-4117-855c-1e0dc1d3bb47",
"controller": "did:cheqd:testnet:55dbc8bf-fba3-4117-855c-1e0dc1d3bb47",
"verificationMethod": [
{
"id": "did:cheqd:testnet:55dbc8bf-fba3-4117-855c-1e0dc1d3bb47#key-1",
"type": "Ed25519VerificationKey2020",
"controller": "did:cheqd:testnet:55dbc8bf-fba3-4117-855c-1e0dc1d3bb47",
"publicKeyMultibase": "z6MkkVbyHJLLjdjU5B62DaJ4mkdMdUkttf9UqySSkA9bVTeZ"
}
],
"authentication": [
"did:cheqd:testnet:55dbc8bf-fba3-4117-855c-1e0dc1d3bb47#key-1"
]
});
let resolver = DidCheqdResolver::new(DidCheqdResolverConfiguration::default());
let output = resolver.resolve(&did, &()).await.unwrap();
let doc = output.did_document;
assert_eq!(serde_json::to_value(doc.clone()).unwrap(), expected_doc);
assert_eq!(doc, serde_json::from_value(expected_doc).unwrap());
}
#[tokio::test]
async fn test_resolve_known_mainnet_resource_vector() {
let url = "did:cheqd:mainnet:e18756b4-25e6-42bb-b1e9-ea48cbe3c360/resources/\
e8af40f9-3df2-40dc-b50d-d1a7e764b52d"
.parse()
.unwrap();
let expected_content = json!({
"name": "Test cheqd anoncreds",
"version": "1.0",
"attrNames": ["test"]
});
let expected_meta = json!({
"alsoKnownAs": [{ "description": "did-url", "uri": "did:cheqd:mainnet:e18756b4-25e6-42bb-b1e9-ea48cbe3c360/resources/e8af40f9-3df2-40dc-b50d-d1a7e764b52d" }],
"resourceUri": "did:cheqd:mainnet:e18756b4-25e6-42bb-b1e9-ea48cbe3c360/resources/e8af40f9-3df2-40dc-b50d-d1a7e764b52d",
"resourceCollectionId": "e18756b4-25e6-42bb-b1e9-ea48cbe3c360",
"resourceId": "e8af40f9-3df2-40dc-b50d-d1a7e764b52d",
"resourceName": "Test cheqd anoncreds-Schema",
"resourceType": "anonCredsSchema",
"mediaType": "application/json",
"resourceVersion": "1.0",
"created": "2024-09-26T10:25:07Z",
"checksum": "01a38743e6f482c998ee8a5b84e1c7e116623a6c9b58c16125eebdf254d24da5"
});
let resolver = DidCheqdResolver::new(DidCheqdResolverConfiguration::default());
let output = resolver.resolve_resource(&url).await.unwrap();
let json_content: Value = serde_json::from_slice(&output.content).unwrap();
assert_eq!(json_content, expected_content);
let json_meta = serde_json::to_value(output.metadata).unwrap();
assert_eq!(json_meta, expected_meta);
}
#[tokio::test]
async fn test_resolve_known_testnet_resource_query() {
// https://testnet-explorer.cheqd.io/transactions/222FF2D023C2C9A097BB38F3875F072DF8DEC7B0CBD46AC3459C9B4C3C74382F
let name = "275990cc056b46176a7122cfd888f46a2bd8e3d45a71d5ff20764a874ed02edd";
let typ = "anonCredsStatusList";
let time = "2024-12-04T22:15:20Z";
let url = format!(
"did:cheqd:testnet:8bbd2026-03f5-42c7-bf80-09f46fc4d67b?resourceName={name}&\
resourceType={typ}&resourceVersionTime={time}"
)
.parse()
.unwrap();
let expected_content = json!({
"currentAccumulator": "21 125DF938B3B772619CB43E561D69004CF09667376E9CD53C818D84860BAE3D1D9 21 11ECFC5F9B469AC74E2A0E329F86C6E60B423A53CAC5AE7A4DBE7A978BFFC0DA1 6 6FAD628FED470FF640BF2C5DB57C2C18D009645DBEF15D4AF710739D2AD93E2D 4 22093A3300411B059B8BB7A8C3296A2ED9C4C8E00106C3B2BAD76E25AC792063 6 71D70ECA81BCE610D1C22CADE688AF4A122C8258E8B306635A111D0A35A7238A 4 1E80F38ABA3A966B8657D722D4E956F076BB2F5CCF36AA8942E65500F8898FF3",
"revRegDefId": "did:cheqd:testnet:8bbd2026-03f5-42c7-bf80-09f46fc4d67b/resources/4f265d83-4657-4c37-ba80-c66cc399457e",
"revocationList": [1,1,1,0,0]
});
let expected_meta = json!({
"alsoKnownAs": [{ "description": "did-url", "uri": "did:cheqd:testnet:8bbd2026-03f5-42c7-bf80-09f46fc4d67b/resources/d08596a8-c655-45cd-88d7-ac27e8f7d183" }],
"resourceUri": "did:cheqd:testnet:8bbd2026-03f5-42c7-bf80-09f46fc4d67b/resources/d08596a8-c655-45cd-88d7-ac27e8f7d183",
"resourceCollectionId": "8bbd2026-03f5-42c7-bf80-09f46fc4d67b",
"resourceId": "d08596a8-c655-45cd-88d7-ac27e8f7d183",
"resourceName": name,
"resourceType": typ,
"mediaType": "application/json",
"resourceVersion": "1669c51f-a382-4a35-a3cc-10f6a278950e",
"created": "2024-12-04T22:15:18Z",
"checksum": "0c9b32ad86c21001fb158e0b19ef6ade10f054d8b0a63cc49f12efc46bcd6ce4",
"nextVersionId": "8e93fa1c-6ee8-4416-8aeb-8ff52cc676ab",
"previousVersionId": "942f1817-a592-44c2-b5c2-bb6579527da5"
});
let resolver = DidCheqdResolver::new(DidCheqdResolverConfiguration::default());
let output = resolver.resolve_resource(&url).await.unwrap();
let json_content: Value = serde_json::from_slice(&output.content).unwrap();
assert_eq!(json_content, expected_content);
let json_meta = serde_json::to_value(output.metadata).unwrap();
assert_eq!(json_meta, expected_meta);
}
/// Regression test for: https://github.com/openwallet-foundation/vcx/issues/1333
/// Ensure that inline assertionMethods are expanded from JSON Stringified
#[tokio::test]
async fn test_resolve_known_testnet_did_vector_with_stringified_assertion_method() {
let did: Did = "did:cheqd:testnet:2ed9518e-301a-4977-8a85-17779d5b4369"
.parse()
.unwrap();
let expected_doc = json!({
"@context": [
"https://w3id.org/did/v1",
"https://w3id.org/security/suites/ed25519-2018/v1"
],
"id": "did:cheqd:testnet:2ed9518e-301a-4977-8a85-17779d5b4369",
"controller": "did:cheqd:testnet:2ed9518e-301a-4977-8a85-17779d5b4369",
"verificationMethod": [
{
"id": "did:cheqd:testnet:2ed9518e-301a-4977-8a85-17779d5b4369#auth",
"type": "Ed25519VerificationKey2018",
"controller": "did:cheqd:testnet:2ed9518e-301a-4977-8a85-17779d5b4369",
"publicKeyBase58": "AyBW3mFr5uHNkxrwW191nNBySWRTY1e6vDnzrQ3JfbpY"
}
],
"authentication": [
"did:cheqd:testnet:2ed9518e-301a-4977-8a85-17779d5b4369#auth"
],
"assertionMethod": [
{
"id": "did:cheqd:testnet:2ed9518e-301a-4977-8a85-17779d5b4369#key-1",
"type": "Bls12381G2Key2020",
"controller": "did:cheqd:testnet:2ed9518e-301a-4977-8a85-17779d5b4369",
"publicKeyBase58": "248ZvAYDLDjwSVkRZ562R7FBcwZYJj8noBHk5Ny3Vs3SyoY48YgVZYY3KLhyUpD6BLE57eRmFzesVZ5kaDXdEG7HzZsCA5PWkDgZj39ExoZPLDnDr2UstJ6PhZmXocQUaTZr"
}
]
});
let resolver = DidCheqdResolver::new(DidCheqdResolverConfiguration::default());
let output = resolver.resolve(&did, &()).await.unwrap();
let doc = output.did_document;
assert_eq!(serde_json::to_value(doc.clone()).unwrap(), expected_doc);
assert_eq!(doc, serde_json::from_value(expected_doc).unwrap());
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_key/src/lib.rs | did_core/did_methods/did_key/src/lib.rs | pub mod error;
use core::fmt;
use std::fmt::Display;
use did_parser_nom::Did;
use error::DidKeyError;
use public_key::Key;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
/// Represents did:key where the DID ID is public key itself
/// See the spec: https://w3c-ccg.github.io/did-method-key/
#[derive(Clone, Debug, PartialEq)]
pub struct DidKey {
key: Key,
did: Did,
}
impl DidKey {
pub fn parse<T>(did: T) -> Result<DidKey, DidKeyError>
where
Did: TryFrom<T>,
<Did as TryFrom<T>>::Error: Into<DidKeyError>,
{
let did: Did = did.try_into().map_err(Into::into)?;
let key = Key::from_fingerprint(did.id())?;
Ok(Self { key, did })
}
pub fn key(&self) -> &Key {
&self.key
}
pub fn did(&self) -> &Did {
&self.did
}
}
impl TryFrom<Key> for DidKey {
type Error = DidKeyError;
fn try_from(key: Key) -> Result<Self, Self::Error> {
let did = Did::parse(format!("did:key:{}", key.fingerprint()))?;
Ok(Self { key, did })
}
}
impl Display for DidKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.did)
}
}
impl Serialize for DidKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.did.did())
}
}
impl<'de> Deserialize<'de> for DidKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
DidKey::parse(s).map_err(de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn _valid_key_base58_fingerprint() -> String {
"z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK".to_string()
}
fn _valid_did_key_string() -> String {
format!("did:key:{}", _valid_key_base58_fingerprint())
}
fn _invalid_did_key_string() -> String {
"did:key:somenonsense".to_string()
}
fn _valid_did_key() -> DidKey {
DidKey {
key: Key::from_fingerprint(&_valid_key_base58_fingerprint()).unwrap(),
did: Did::parse(_valid_did_key_string()).unwrap(),
}
}
#[test]
fn test_serialize() {
assert_eq!(
format!("\"{}\"", _valid_did_key_string()),
serde_json::to_string(&_valid_did_key()).unwrap(),
);
}
#[test]
fn test_deserialize() {
assert_eq!(
_valid_did_key(),
serde_json::from_str::<DidKey>(&format!("\"{}\"", _valid_did_key_string())).unwrap(),
);
}
#[test]
fn test_deserialize_error() {
assert!(serde_json::from_str::<DidKey>(&_invalid_did_key_string()).is_err());
}
#[test]
fn test_parse() {
assert_eq!(
_valid_did_key(),
DidKey::parse(_valid_did_key_string()).unwrap(),
);
}
#[test]
fn test_parse_error() {
assert!(DidKey::parse(_invalid_did_key_string()).is_err());
}
#[test]
fn test_try_from_key() {
assert_eq!(
_valid_did_key(),
DidKey::try_from(Key::from_fingerprint(&_valid_key_base58_fingerprint()).unwrap())
.unwrap(),
);
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_key/src/error.rs | did_core/did_methods/did_key/src/error.rs | use thiserror::Error;
#[derive(Debug, Error)]
pub enum DidKeyError {
#[error("Public key error: {0}")]
PublicKeyError(#[from] public_key::PublicKeyError),
#[error("DID parser error: {0}")]
DidParserError(#[from] did_parser_nom::ParseError),
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/lib.rs | did_core/did_methods/did_peer/src/lib.rs | extern crate display_as_json;
pub mod error;
pub mod helpers;
pub mod peer_did;
pub mod resolver;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/helpers.rs | did_core/did_methods/did_peer/src/helpers.rs | use std::collections::HashMap;
use did_doc::error::DidDocumentBuilderError;
use serde::Serialize;
use serde_json::Value;
pub fn convert_to_hashmap<T: Serialize>(
value: &T,
) -> Result<HashMap<String, Value>, DidDocumentBuilderError> {
let serialized_value = serde_json::to_value(value)?;
match serialized_value {
Value::Object(map) => Ok(map.into_iter().collect()),
_ => Err(DidDocumentBuilderError::CustomError(
"Expected JSON object".to_string(),
)),
}
}
// https://multiformats.io/multihash/
// 0x12 - multihash/multicodec "Sha2-256"
// 0x20 - length of 32 bytes (256 bits)
pub(crate) const MULTIHASH_SHA2_256: [u8; 2] = [0x12u8, 0x20u8];
// https://github.com/multiformats/multicodec/blob/master/table.csv
// multicodec JSON (0x0200) as a varint
pub(crate) const MULTICODEC_JSON_VARINT: [u8; 2] = [0x80u8, 0x04u8];
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/error.rs | did_core/did_methods/did_peer/src/error.rs | use std::convert::Infallible;
use did_doc::schema::{
types::uri::UriWrapperError,
verification_method::{error::KeyDecodingError, VerificationMethodType},
};
use crate::peer_did::numalgos::kind::NumalgoKind;
#[derive(Debug, thiserror::Error)]
pub enum DidPeerError {
#[error("DID parser error: {0}")]
DidParserError(#[from] did_parser_nom::ParseError),
#[error("Parsing error: {0}")]
ParsingError(String),
#[error("DID validation error: {0}")]
DidValidationError(String),
#[error("DID document builder error: {0}")]
DidDocumentBuilderError(#[from] did_doc::error::DidDocumentBuilderError),
#[error("Invalid key reference: {0}")]
InvalidKeyReference(String),
#[error("Invalid service: {0}")]
InvalidService(String),
#[error("Unsupported numalgo: {0}")]
UnsupportedNumalgo(NumalgoKind),
#[error("Invalid numalgo character: {0}")]
InvalidNumalgoCharacter(char),
#[error("Unsupported purpose character: {0}")]
UnsupportedPurpose(char),
#[error("Unsupported verification method type: {0}")]
UnsupportedVerificationMethodType(VerificationMethodType),
#[error("Base 64 decoding error")]
Base64DecodingError(#[from] base64::DecodeError),
#[error("Key decoding error")]
KeyDecodingError(#[from] KeyDecodingError),
#[error("JSON error: {0}")]
JsonError(#[from] serde_json::Error),
#[error("Regex error: {0}")]
RegexError(#[from] regex::Error),
#[error("Public key error: {0}")]
PublicKeyError(#[from] public_key::PublicKeyError),
#[error("General error: {0}")]
GeneralError(String),
}
impl From<Infallible> for DidPeerError {
fn from(_: Infallible) -> Self {
panic!("Attempted to convert an Infallible error")
}
}
impl From<UriWrapperError> for DidPeerError {
fn from(error: UriWrapperError) -> Self {
DidPeerError::ParsingError(error.to_string())
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/parse.rs | did_core/did_methods/did_peer/src/peer_did/parse.rs | use did_parser_nom::Did;
use crate::{error::DidPeerError, peer_did::numalgos::kind::NumalgoKind};
pub fn parse_numalgo(did: &Did) -> Result<NumalgoKind, DidPeerError> {
log::info!("did.id() >> {}", did.id());
did.id()
.chars()
.next()
.ok_or_else(|| {
DidPeerError::DidValidationError(format!(
"Invalid peer did: {} because numalgo couldn't be parsed",
did.did()
))
})?
.try_into()
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/mod.rs | did_core/did_methods/did_peer/src/peer_did/mod.rs | pub mod numalgos;
mod parse;
pub mod generic;
use core::fmt;
use std::{fmt::Display, marker::PhantomData};
use did_doc::schema::did_doc::DidDocument;
use did_parser_nom::Did;
use serde::{
de::{self, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
use crate::{error::DidPeerError, peer_did::numalgos::Numalgo};
#[derive(Clone, Debug, PartialEq)]
pub struct PeerDid<N: Numalgo> {
did: Did,
numalgo: N,
}
impl<N: Numalgo> PeerDid<N> {
pub fn parse<T>(did: T) -> Result<PeerDid<N>, DidPeerError>
where
Did: TryFrom<T>,
<Did as TryFrom<T>>::Error: Into<DidPeerError>,
{
N::parse(did)
}
pub fn did(&self) -> &Did {
&self.did
}
pub(crate) fn from_parts(did: Did, numalgo: N) -> PeerDid<N> {
Self { did, numalgo }
}
}
pub trait FromDidDoc: Numalgo {
fn from_did_doc(did_document: DidDocument) -> Result<PeerDid<Self>, DidPeerError>
where
Self: Sized;
}
impl<N: Numalgo + FromDidDoc> PeerDid<N> {
pub fn from_did_doc(did_document: DidDocument) -> Result<PeerDid<N>, DidPeerError> {
N::from_did_doc(did_document)
}
}
impl<N: Numalgo> Serialize for PeerDid<N> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.did.did())
}
}
impl<'de, N: Numalgo> Deserialize<'de> for PeerDid<N> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct PeerDidVisitor<N: Numalgo>(PhantomData<N>);
impl<N: Numalgo> Visitor<'_> for PeerDidVisitor<N> {
type Value = PeerDid<N>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string representing a DID")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
match N::parse(value.to_string()) {
Ok(peer_did) => Ok(peer_did),
Err(err) => Err(E::custom(format!("Failed to parse numalgo: {err}"))),
}
}
}
deserializer.deserialize_str(PeerDidVisitor(PhantomData))
}
}
impl<N: Numalgo> Display for PeerDid<N> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.did)
}
}
impl<N: Numalgo> From<PeerDid<N>> for Did {
fn from(peer_did: PeerDid<N>) -> Self {
peer_did.did
}
}
impl<N: Numalgo> AsRef<Did> for PeerDid<N> {
fn as_ref(&self) -> &Did {
self.did()
}
}
#[cfg(test)]
mod tests {
use crate::{
error::DidPeerError,
peer_did::{
numalgos::{numalgo2::Numalgo2, numalgo3::Numalgo3},
PeerDid,
},
};
const VALID_PEER_DID_NUMALGO2: &str = "did:peer:2\
.Ez6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH\
.VzXwpBnMdCm1cLmKuzgESn29nqnonp1ioqrQMRHNsmjMyppzx8xB2pv7cw8q1PdDacSrdWE3dtB9f7Nxk886mdzNFoPtY\
.SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXSwiYSI6WyJkaWRjb21tL3YyIiwiZGlkY29tbS9haXAyO2Vudj1yZmM1ODciXX0";
const VALID_PEER_DID_NUMALGO3: &str =
"did:peer:3zQmfUHk2UkVZwkMwXLRCJrTmEkxpNdfare68fLo3YUwWryp";
fn peer_did_numalgo2() -> PeerDid<Numalgo2> {
PeerDid {
did: VALID_PEER_DID_NUMALGO2.parse().unwrap(),
numalgo: Numalgo2,
}
}
fn peer_did_numalgo3() -> PeerDid<Numalgo3> {
PeerDid {
did: VALID_PEER_DID_NUMALGO3.parse().unwrap(),
numalgo: Numalgo3,
}
}
mod parse {
use pretty_assertions::assert_eq;
use super::*;
macro_rules! generate_negative_parse_test {
($test_name:ident, $input:expr, $error_pattern:pat) => {
#[test]
fn $test_name() {
let result = PeerDid::<Numalgo2>::parse($input.to_string());
assert!(matches!(result, Err($error_pattern)));
}
};
}
generate_negative_parse_test!(
malformed_base58_encoding_encryption,
"did:peer:2\
.Ez6LSbysY2xFMRpG0hb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc\
.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V\
.SeyJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXX0=",
DidPeerError::DidParserError(_)
);
#[test]
fn numalgo3() {
let expected = PeerDid {
did: VALID_PEER_DID_NUMALGO3.parse().unwrap(),
numalgo: Numalgo3,
};
assert_eq!(
expected,
PeerDid::<Numalgo3>::parse(VALID_PEER_DID_NUMALGO3.to_string()).unwrap()
);
}
}
mod to_numalgo3 {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn numalgo2() {
assert_eq!(
peer_did_numalgo3(),
peer_did_numalgo2().to_numalgo3().unwrap()
);
}
}
mod serialize {
use super::*;
#[test]
fn numalgo2() {
assert_eq!(
serde_json::to_string(&peer_did_numalgo2()).unwrap(),
format!("\"{VALID_PEER_DID_NUMALGO2}\"")
);
}
#[test]
fn numalgo3() {
assert_eq!(
serde_json::to_string(&peer_did_numalgo3()).unwrap(),
format!("\"{VALID_PEER_DID_NUMALGO3}\"")
);
}
}
mod deserialize {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn numalgo2() {
let deserialized: PeerDid<Numalgo2> =
serde_json::from_str(&format!("\"{VALID_PEER_DID_NUMALGO2}\"")).unwrap();
assert_eq!(peer_did_numalgo2(), deserialized);
}
#[test]
fn numalgo3() {
let deserialized: PeerDid<Numalgo3> =
serde_json::from_str(&format!("\"{VALID_PEER_DID_NUMALGO3}\"")).unwrap();
assert_eq!(peer_did_numalgo3(), deserialized);
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/generic.rs | did_core/did_methods/did_peer/src/peer_did/generic.rs | use std::fmt::Display;
use did_parser_nom::Did;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::PeerDid;
use crate::{
error::DidPeerError,
peer_did::{
numalgos::{kind::NumalgoKind, numalgo2::Numalgo2, numalgo3::Numalgo3, numalgo4::Numalgo4},
parse::parse_numalgo,
},
};
#[derive(Clone, Debug, PartialEq)]
pub enum AnyPeerDid {
Numalgo2(PeerDid<Numalgo2>),
Numalgo3(PeerDid<Numalgo3>),
Numalgo4(PeerDid<Numalgo4>),
}
impl AnyPeerDid {
pub fn parse<T>(did: T) -> Result<AnyPeerDid, DidPeerError>
where
T: Display,
Did: TryFrom<T>,
<Did as TryFrom<T>>::Error: Into<DidPeerError>,
{
log::info!("AnyPeerDid >> parsing input {did} as peer:did");
let did: Did = did.try_into().map_err(Into::into)?;
log::info!("AnyPeerDid >> parsed did {did}");
let numalgo = parse_numalgo(&did)?;
log::info!("AnyPeerDid >> parsed numalgo {}", numalgo.to_char());
let parsed = match numalgo {
NumalgoKind::MultipleInceptionKeys(numalgo2) => AnyPeerDid::Numalgo2(PeerDid {
did,
numalgo: numalgo2,
}),
NumalgoKind::DidShortening(numalgo3) => AnyPeerDid::Numalgo3(PeerDid {
did,
numalgo: numalgo3,
}),
NumalgoKind::DidPeer4(numalgo4) => AnyPeerDid::Numalgo4(PeerDid {
did,
numalgo: numalgo4,
}),
o => unimplemented!("Parsing numalgo {} is not supported", o.to_char()),
};
Ok(parsed)
}
pub fn numalgo(&self) -> NumalgoKind {
match self {
AnyPeerDid::Numalgo2(peer_did) => NumalgoKind::MultipleInceptionKeys(peer_did.numalgo),
AnyPeerDid::Numalgo3(peer_did) => NumalgoKind::DidShortening(peer_did.numalgo),
AnyPeerDid::Numalgo4(peer_did) => NumalgoKind::DidPeer4(peer_did.numalgo),
}
}
}
impl Serialize for AnyPeerDid {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match &self {
AnyPeerDid::Numalgo2(peer_did) => serializer.serialize_str(peer_did.did().did()),
AnyPeerDid::Numalgo3(peer_did) => serializer.serialize_str(peer_did.did().did()),
AnyPeerDid::Numalgo4(peer_did) => serializer.serialize_str(peer_did.did().did()),
}
}
}
impl<'de> Deserialize<'de> for AnyPeerDid {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let did = String::deserialize(deserializer)?;
Self::parse(did).map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
const VALID_PEER_DID_NUMALGO2: &str = "did:peer:2\
.Ez6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH\
.VzXwpBnMdCm1cLmKuzgESn29nqnonp1ioqrQMRHNsmjMyppzx8xB2pv7cw8q1PdDacSrdWE3dtB9f7Nxk886mdzNFoPtY\
.SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXSwiYSI6WyJkaWRjb21tL3YyIiwiZGlkY29tbS9haXAyO2Vudj1yZmM1ODciXX0";
// https://identity.foundation/peer-did-method-spec/index.html#method-3-did-shortening-with-sha-256-hash
const VALID_PEER_DID_NUMALGO3: &str =
"did:peer:3zQmS19jtYDvGtKVrJhQnRFpBQAx3pJ9omx2HpNrcXFuRCz9";
fn generic_peer_did_numalgo2() -> AnyPeerDid {
AnyPeerDid::Numalgo2(PeerDid {
did: VALID_PEER_DID_NUMALGO2.parse().unwrap(),
numalgo: Numalgo2,
})
}
fn generic_peer_did_numalgo3() -> AnyPeerDid {
AnyPeerDid::Numalgo3(PeerDid {
did: VALID_PEER_DID_NUMALGO3.parse().unwrap(),
numalgo: Numalgo3,
})
}
mod serialize {
use super::*;
#[test]
fn numalgo2() {
let serialized = serde_json::to_string(&generic_peer_did_numalgo2()).unwrap();
assert_eq!(serialized, format!("\"{VALID_PEER_DID_NUMALGO2}\""));
}
#[test]
fn numalgo3() {
let serialized = serde_json::to_string(&generic_peer_did_numalgo3()).unwrap();
assert_eq!(serialized, format!("\"{VALID_PEER_DID_NUMALGO3}\""));
}
}
mod deserialize {
use super::*;
#[test]
fn numalgo2() {
let deserialized: AnyPeerDid =
serde_json::from_str(&format!("\"{VALID_PEER_DID_NUMALGO2}\"")).unwrap();
assert_eq!(deserialized, generic_peer_did_numalgo2());
}
#[test]
fn numalgo3() {
let deserialized: AnyPeerDid =
serde_json::from_str(&format!("\"{VALID_PEER_DID_NUMALGO3}\"")).unwrap();
assert_eq!(deserialized, generic_peer_did_numalgo3());
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/kind.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/kind.rs | use std::fmt::Display;
use crate::{
error::DidPeerError,
peer_did::numalgos::{
numalgo0::Numalgo0, numalgo1::Numalgo1, numalgo2::Numalgo2, numalgo3::Numalgo3,
numalgo4::Numalgo4, Numalgo,
},
};
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum NumalgoKind {
InceptionKeyWithoutDoc(Numalgo0),
GenesisDoc(Numalgo1),
MultipleInceptionKeys(Numalgo2),
DidShortening(Numalgo3),
DidPeer4(Numalgo4),
}
impl NumalgoKind {
pub fn to_char(&self) -> char {
match self {
NumalgoKind::InceptionKeyWithoutDoc(_) => Numalgo0::NUMALGO_CHAR,
NumalgoKind::GenesisDoc(_) => Numalgo1::NUMALGO_CHAR,
NumalgoKind::MultipleInceptionKeys(_) => Numalgo2::NUMALGO_CHAR,
NumalgoKind::DidShortening(_) => Numalgo3::NUMALGO_CHAR,
NumalgoKind::DidPeer4(_) => Numalgo4::NUMALGO_CHAR,
}
}
}
impl Display for NumalgoKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_char().fmt(f)
}
}
impl TryFrom<char> for NumalgoKind {
type Error = DidPeerError;
fn try_from(value: char) -> Result<Self, Self::Error> {
match value {
Numalgo0::NUMALGO_CHAR => Ok(NumalgoKind::InceptionKeyWithoutDoc(Numalgo0)),
Numalgo1::NUMALGO_CHAR => Ok(NumalgoKind::GenesisDoc(Numalgo1)),
Numalgo2::NUMALGO_CHAR => Ok(NumalgoKind::MultipleInceptionKeys(Numalgo2)),
Numalgo3::NUMALGO_CHAR => Ok(NumalgoKind::DidShortening(Numalgo3)),
Numalgo4::NUMALGO_CHAR => Ok(NumalgoKind::DidPeer4(Numalgo4)),
c => Err(DidPeerError::InvalidNumalgoCharacter(c)),
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/mod.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/mod.rs | pub mod kind;
pub mod numalgo0;
pub mod numalgo1;
pub mod numalgo2;
pub mod numalgo3;
pub mod numalgo4;
use did_doc::schema::did_doc::DidDocument;
use did_parser_nom::Did;
use crate::{
error::DidPeerError,
peer_did::{parse::parse_numalgo, PeerDid},
resolver::options::PublicKeyEncoding,
};
pub trait Numalgo: Sized + Default {
const NUMALGO_CHAR: char;
fn parse<T>(did: T) -> Result<PeerDid<Self>, DidPeerError>
where
Did: TryFrom<T>,
<Did as TryFrom<T>>::Error: Into<DidPeerError>,
{
let did: Did = did.try_into().map_err(Into::into)?;
let numalgo_char = parse_numalgo(&did)?.to_char();
if numalgo_char != Self::NUMALGO_CHAR {
return Err(DidPeerError::InvalidNumalgoCharacter(numalgo_char));
}
Ok(PeerDid::from_parts(did, Self::default()))
}
}
pub trait ResolvableNumalgo: Numalgo {
fn resolve(
&self,
did: &Did,
public_key_encoding: PublicKeyEncoding,
) -> Result<DidDocument, DidPeerError>;
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/traits.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/traits.rs | use did_doc::schema::did_doc::DidDocument;
use did_parser_nom::Did;
use crate::{
error::DidPeerError,
peer_did::{parse::parse_numalgo, validate::validate, PeerDid},
peer_did_resolver::options::PublicKeyEncoding,
};
pub trait Numalgo: Sized + Default {
const NUMALGO_CHAR: char;
fn parse<T>(did: T) -> Result<PeerDid<Self>, DidPeerError>
where
Did: TryFrom<T>,
<Did as TryFrom<T>>::Error: Into<DidPeerError>,
{
let did: Did = did.try_into().map_err(Into::into)?;
let numalgo_char = parse_numalgo(&did)?.to_char();
if numalgo_char != Self::NUMALGO_CHAR {
return Err(DidPeerError::InvalidNumalgoCharacter(numalgo_char));
}
validate(&did)?;
Ok(PeerDid::from_parts(did, Self::default()))
}
}
pub trait ResolvableNumalgo: Numalgo {
fn resolve(
&self,
did: &Did,
public_key_encoding: PublicKeyEncoding,
) -> Result<DidDocument, DidPeerError>;
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo0/mod.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo0/mod.rs | use crate::peer_did::numalgos::Numalgo;
#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub struct Numalgo0;
impl Numalgo for Numalgo0 {
const NUMALGO_CHAR: char = '0';
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo2/helpers.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo2/helpers.rs | use base64::{engine::general_purpose::STANDARD_NO_PAD, Engine};
use did_doc::schema::did_doc::DidDocument;
use did_parser_nom::Did;
use public_key::Key;
use crate::{
error::DidPeerError,
peer_did::numalgos::numalgo2::{
purpose::ElementPurpose,
service_abbreviation::{deabbreviate_service, ServiceAbbreviatedDidPeer2},
verification_method::get_verification_methods_by_key,
},
resolver::options::PublicKeyEncoding,
};
pub fn diddoc_from_peerdid2_elements(
mut did_doc: DidDocument,
did: &Did,
public_key_encoding: PublicKeyEncoding,
) -> Result<DidDocument, DidPeerError> {
let mut service_index: usize = 0;
let mut vm_index: usize = 1;
// Skipping one here because the first element is empty string
for element in did.id()[1..].split('.').skip(1) {
did_doc = add_attributes_from_element(
element,
did_doc,
&mut service_index,
&mut vm_index,
did,
public_key_encoding,
)?;
}
Ok(did_doc)
}
fn add_attributes_from_element(
element: &str,
mut did_doc: DidDocument,
service_index: &mut usize,
vm_index: &mut usize,
did: &Did,
public_key_encoding: PublicKeyEncoding,
) -> Result<DidDocument, DidPeerError> {
let purpose: ElementPurpose = element
.chars()
.next()
.ok_or(DidPeerError::DidValidationError(format!(
"No purpose code following element separator in '{element}'"
)))?
.try_into()?;
let purposeless_element = &element[1..];
if purpose == ElementPurpose::Service {
did_doc = add_service_from_element(purposeless_element, did_doc, service_index)?;
} else {
did_doc = add_key_from_element(
purposeless_element,
did_doc,
vm_index,
did,
public_key_encoding,
purpose,
)?;
}
Ok(did_doc)
}
fn add_service_from_element(
element: &str,
mut did_doc: DidDocument,
service_index: &mut usize,
) -> Result<DidDocument, DidPeerError> {
let decoded = STANDARD_NO_PAD.decode(element)?;
let service: ServiceAbbreviatedDidPeer2 = serde_json::from_slice(&decoded)?;
did_doc.add_service(deabbreviate_service(service, *service_index)?);
*service_index += 1;
Ok(did_doc)
}
fn add_key_from_element(
element: &str,
mut did_doc: DidDocument,
vm_index: &mut usize,
did: &Did,
public_key_encoding: PublicKeyEncoding,
purpose: ElementPurpose,
) -> Result<DidDocument, DidPeerError> {
let key = Key::from_fingerprint(element)?;
let vms = get_verification_methods_by_key(&key, did, public_key_encoding, vm_index)?;
for vm in vms.into_iter() {
let vm_reference = vm.id().to_owned();
did_doc.add_verification_method(vm);
// https://identity.foundation/peer-did-method-spec/#purpose-codes
match purpose {
ElementPurpose::Assertion => {
did_doc.add_assertion_method_ref(vm_reference);
}
ElementPurpose::Encryption => {
did_doc.add_key_agreement_ref(vm_reference);
}
ElementPurpose::Verification => {
did_doc.add_authentication_ref(vm_reference);
}
ElementPurpose::CapabilityInvocation => {
did_doc.add_capability_invocation_ref(vm_reference)
}
ElementPurpose::CapabilityDelegation => {
did_doc.add_capability_delegation_ref(vm_reference)
}
_ => return Err(DidPeerError::UnsupportedPurpose(purpose.into())),
}
}
Ok(did_doc)
}
#[cfg(test)]
mod tests {
use did_doc::schema::service::typed::ServiceType;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn test_process_elements_empty_did() {
let did: Did = "did:peer:2".parse().unwrap();
let did_doc = diddoc_from_peerdid2_elements(
DidDocument::new(did.clone()),
&did,
PublicKeyEncoding::Base58,
)
.unwrap();
assert_eq!(did_doc.id().to_string(), did.to_string());
}
#[test]
fn test_process_elements_with_multiple_elements() {
let did: Did = "did:peer:2.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.\
SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCJ9"
.parse()
.unwrap();
let did_doc = diddoc_from_peerdid2_elements(
DidDocument::new(did.clone()),
&did,
PublicKeyEncoding::Multibase,
)
.unwrap();
assert_eq!(did_doc.id().to_string(), did.to_string());
assert_eq!(did_doc.verification_method().len(), 1);
assert_eq!(did_doc.service().len(), 1);
}
#[test]
fn test_process_elements_error_on_invalid_element() {
let did: Did = "did:peer:2.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.\
SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCJ9.\
Xinvalid"
.parse()
.unwrap();
match diddoc_from_peerdid2_elements(
DidDocument::new(did.clone()),
&did,
PublicKeyEncoding::Multibase,
) {
Ok(_) => panic!("Expected Err, got Ok"),
Err(e) => {
assert!(matches!(e, DidPeerError::UnsupportedPurpose('X')));
}
}
}
#[test]
fn test_process_service_element_one_service() {
let purposeless_service_element =
"eyJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCJ9";
let did: Did = format!("did:peer:2.S{purposeless_service_element}")
.parse()
.unwrap();
let mut index = 0;
let ddo_builder = DidDocument::new(did);
let did_doc =
add_service_from_element(purposeless_service_element, ddo_builder, &mut index).unwrap();
assert_eq!(did_doc.service().len(), 1);
let service = did_doc.service().first().unwrap();
assert_eq!(service.id().to_string(), "#service-0".to_string());
assert_eq!(service.service_types(), vec!(ServiceType::DIDCommV2));
assert_eq!(
service.service_endpoint().to_string(),
"https://example.com/endpoint".to_string()
);
}
#[test]
fn test_process_key_element() {
let purposeless_key_element = "z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V";
let did: Did = format!("did:peer:2.V{purposeless_key_element}")
.parse()
.unwrap();
let ddo_builder = DidDocument::new(did.clone());
let public_key_encoding = PublicKeyEncoding::Multibase;
let did_doc = add_key_from_element(
purposeless_key_element,
ddo_builder,
&mut 0,
&did,
public_key_encoding,
ElementPurpose::Verification,
)
.unwrap();
assert_eq!(did_doc.verification_method().len(), 1);
let vm = did_doc.verification_method().first().unwrap();
assert_eq!(vm.id().to_string(), "#key-0");
assert_eq!(vm.controller().to_string(), did.to_string());
}
#[test]
fn test_process_key_element_negative() {
let did: Did = "did:peer:2".parse().unwrap();
assert!(add_key_from_element(
"z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V",
DidDocument::new(did.clone()),
&mut 0,
&did,
PublicKeyEncoding::Multibase,
ElementPurpose::Service
)
.is_err());
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo2/verification_method.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo2/verification_method.rs | use did_doc::schema::verification_method::{
PublicKeyField, VerificationMethod, VerificationMethodType,
};
use did_parser_nom::{Did, DidUrl};
use public_key::{Key, KeyType};
use crate::{error::DidPeerError, resolver::options::PublicKeyEncoding};
pub fn get_verification_methods_by_key(
key: &Key,
did: &Did,
public_key_encoding: PublicKeyEncoding,
vm_index: &mut usize,
) -> Result<Vec<VerificationMethod>, DidPeerError> {
let vm_type = match key.key_type() {
KeyType::Ed25519 => VerificationMethodType::Ed25519VerificationKey2020,
KeyType::Bls12381g1 => VerificationMethodType::Bls12381G1Key2020,
KeyType::Bls12381g2 => VerificationMethodType::Bls12381G2Key2020,
KeyType::X25519 => VerificationMethodType::X25519KeyAgreementKey2020,
KeyType::P256 => VerificationMethodType::JsonWebKey2020,
KeyType::P384 => VerificationMethodType::JsonWebKey2020,
KeyType::P521 => VerificationMethodType::JsonWebKey2020,
KeyType::Bls12381g1g2 => {
return Ok(build_verification_methods_from_bls_multikey(
&Key::new(key.key()[..48].to_vec(), KeyType::Bls12381g1)?,
&Key::new(key.key()[48..].to_vec(), KeyType::Bls12381g2)?,
did.to_owned(),
public_key_encoding,
vm_index,
));
}
};
build_verification_methods_from_type_and_key(
vm_type,
key,
did.to_owned(),
public_key_encoding,
vm_index,
)
}
pub fn get_key_by_verification_method(vm: &VerificationMethod) -> Result<Key, DidPeerError> {
let key_type = match vm.verification_method_type() {
VerificationMethodType::Ed25519VerificationKey2018
| VerificationMethodType::Ed25519VerificationKey2020 => KeyType::Ed25519,
VerificationMethodType::Bls12381G1Key2020 => KeyType::Bls12381g1,
VerificationMethodType::Bls12381G2Key2020 => KeyType::Bls12381g2,
VerificationMethodType::X25519KeyAgreementKey2019
| VerificationMethodType::X25519KeyAgreementKey2020 => KeyType::X25519,
t => {
return Err(DidPeerError::UnsupportedVerificationMethodType(
t.to_owned(),
));
}
};
Ok(Key::new(vm.public_key_field().key_decoded()?, key_type)?)
}
fn build_verification_methods_from_type_and_key(
vm_type: VerificationMethodType,
key: &Key,
did: Did,
public_key_encoding: PublicKeyEncoding,
vm_index: &mut usize,
) -> Result<Vec<VerificationMethod>, DidPeerError> {
let id = nth_key_did_url_reference(*vm_index)?;
*vm_index += 1;
let vm = VerificationMethod::builder()
.id(id)
.controller(did)
.verification_method_type(vm_type)
.public_key(key_to_key_field(key, public_key_encoding))
.build();
Ok(vec![vm])
}
fn build_verification_methods_from_bls_multikey(
g1_key: &Key,
g2_key: &Key,
did: Did,
public_key_encoding: PublicKeyEncoding,
vm_index: &mut usize,
) -> Vec<VerificationMethod> {
let id1 = nth_key_did_url_reference(*vm_index).unwrap();
*vm_index += 1;
let id2 = nth_key_did_url_reference(*vm_index).unwrap();
*vm_index += 1;
let vm1 = VerificationMethod::builder()
.id(id1)
.controller(did.to_owned())
.verification_method_type(VerificationMethodType::Bls12381G1Key2020)
.public_key(key_to_key_field(g1_key, public_key_encoding))
.build();
let vm2 = VerificationMethod::builder()
.id(id2)
.controller(did.to_owned())
.verification_method_type(VerificationMethodType::Bls12381G2Key2020)
.public_key(key_to_key_field(g2_key, public_key_encoding))
.build();
vec![vm1, vm2]
}
fn key_to_key_field(key: &Key, public_key_encoding: PublicKeyEncoding) -> PublicKeyField {
match public_key_encoding {
PublicKeyEncoding::Base58 => PublicKeyField::Base58 {
public_key_base58: key.base58(),
},
PublicKeyEncoding::Multibase => PublicKeyField::Multibase {
public_key_multibase: key.fingerprint(),
},
}
}
fn nth_key_did_url_reference(n: usize) -> Result<DidUrl, DidPeerError> {
DidUrl::from_fragment(format!("key-{n}")).map_err(Into::into)
}
#[cfg(test)]
mod tests {
use did_doc::schema::verification_method::{
PublicKeyField, VerificationMethod, VerificationMethodType,
};
use did_parser_nom::Did;
use public_key::Key;
fn did() -> Did {
"did:peer:2.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc.\
Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.\
Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg"
.parse()
.unwrap()
}
fn key_0() -> Key {
Key::from_fingerprint("z6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc").unwrap()
}
fn key_1() -> Key {
Key::from_fingerprint("z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V").unwrap()
}
fn key_2() -> Key {
Key::from_fingerprint("z6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg").unwrap()
}
fn verification_method_0() -> VerificationMethod {
VerificationMethod::builder()
.id(did().into())
.controller(did())
.verification_method_type(VerificationMethodType::X25519KeyAgreementKey2020)
.public_key(PublicKeyField::Multibase {
public_key_multibase: key_0().fingerprint(),
})
.build()
}
fn verification_method_1() -> VerificationMethod {
VerificationMethod::builder()
.id(did().into())
.controller(did())
.verification_method_type(VerificationMethodType::Ed25519VerificationKey2020)
.public_key(PublicKeyField::Multibase {
public_key_multibase: key_1().fingerprint(),
})
.build()
}
fn verification_method_2() -> VerificationMethod {
VerificationMethod::builder()
.id(did().into())
.controller(did())
.verification_method_type(VerificationMethodType::Ed25519VerificationKey2020)
.public_key(PublicKeyField::Multibase {
public_key_multibase: key_2().fingerprint(),
})
.build()
}
mod get_verification_methods_by_key {
use super::*;
use crate::{
peer_did::numalgos::numalgo2::verification_method, resolver::options::PublicKeyEncoding,
};
// Multibase encoded keys are multicodec-prefixed by their encoding type ...
fn test_get_verification_methods_by_key_multibase(key: &Key) {
let vms = verification_method::get_verification_methods_by_key(
key,
&did(),
PublicKeyEncoding::Multibase,
&mut 0,
)
.unwrap();
assert_eq!(vms.len(), 1);
let vm = &vms[0];
assert!(matches!(
vm.public_key_field(),
PublicKeyField::Multibase { .. }
));
assert_eq!(vm.public_key_field().key_decoded().unwrap(), key.key());
}
// ... and base58 encoded keys are not
fn test_get_verification_methods_by_key_base58(key: &Key) {
let vms = verification_method::get_verification_methods_by_key(
key,
&did(),
PublicKeyEncoding::Base58,
&mut 0,
)
.unwrap();
assert_eq!(vms.len(), 1);
let vm = &vms[0];
assert!(matches!(
vm.public_key_field(),
PublicKeyField::Base58 { .. }
));
assert_eq!(vm.public_key_field().key_decoded().unwrap(), key.key());
}
#[test]
fn test_get_verification_methods_by_key_multibase_0() {
test_get_verification_methods_by_key_multibase(&key_0());
}
#[test]
fn test_get_verification_methods_by_key_multibase_1() {
test_get_verification_methods_by_key_multibase(&key_1());
}
#[test]
fn test_get_verification_methods_by_key_multibase_2() {
test_get_verification_methods_by_key_multibase(&key_2());
}
#[test]
fn test_get_verification_methods_by_key_base58_0() {
test_get_verification_methods_by_key_base58(&key_0());
}
#[test]
fn test_get_verification_methods_by_key_base58_1() {
test_get_verification_methods_by_key_base58(&key_1());
}
#[test]
fn test_get_verification_methods_by_key_base58_2() {
test_get_verification_methods_by_key_base58(&key_2());
}
}
mod get_key_by_verification_method {
use super::*;
use crate::peer_did::numalgos::numalgo2::verification_method;
#[test]
fn test_get_key_by_verification_method_0() {
assert_eq!(
verification_method::get_key_by_verification_method(&verification_method_0())
.unwrap(),
key_0()
);
}
#[test]
fn test_get_key_by_verification_method_1() {
assert_eq!(
verification_method::get_key_by_verification_method(&verification_method_1())
.unwrap(),
key_1()
);
}
#[test]
fn test_get_key_by_verification_method_2() {
assert_eq!(
verification_method::get_key_by_verification_method(&verification_method_2())
.unwrap(),
key_2()
);
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo2/purpose.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo2/purpose.rs | use std::fmt::Display;
use crate::error::DidPeerError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElementPurpose {
Assertion,
Encryption,
Verification,
CapabilityInvocation,
CapabilityDelegation,
Service,
}
impl Display for ElementPurpose {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let c: char = (*self).into();
write!(f, "{c}")
}
}
impl TryFrom<char> for ElementPurpose {
type Error = DidPeerError;
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'A' => Ok(ElementPurpose::Assertion),
'E' => Ok(ElementPurpose::Encryption),
'V' => Ok(ElementPurpose::Verification),
'I' => Ok(ElementPurpose::CapabilityInvocation),
'D' => Ok(ElementPurpose::CapabilityDelegation),
'S' => Ok(ElementPurpose::Service),
c => Err(DidPeerError::UnsupportedPurpose(c)),
}
}
}
impl From<ElementPurpose> for char {
fn from(purpose: ElementPurpose) -> Self {
match purpose {
ElementPurpose::Assertion => 'A',
ElementPurpose::Encryption => 'E',
ElementPurpose::Verification => 'V',
ElementPurpose::CapabilityInvocation => 'I',
ElementPurpose::CapabilityDelegation => 'D',
ElementPurpose::Service => 'S',
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo2/mod.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo2/mod.rs | use did_doc::schema::did_doc::DidDocument;
use encoding::{append_encoded_key_segments, append_encoded_service_segment};
use sha2::{Digest, Sha256};
use crate::{
error::DidPeerError,
helpers::MULTIHASH_SHA2_256,
peer_did::{
numalgos::{numalgo2::helpers::diddoc_from_peerdid2_elements, numalgo3::Numalgo3, Numalgo},
FromDidDoc, PeerDid,
},
resolver::options::PublicKeyEncoding,
};
mod encoding;
mod helpers;
mod purpose;
mod service_abbreviation;
mod verification_method;
impl FromDidDoc for Numalgo2 {
fn from_did_doc(did_document: DidDocument) -> Result<PeerDid<Numalgo2>, DidPeerError> {
let mut did = String::from("did:peer:2");
did = append_encoded_key_segments(did, &did_document)?;
did = append_encoded_service_segment(did, &did_document)?;
PeerDid::<Numalgo2>::parse(did)
}
}
impl PeerDid<Numalgo2> {
pub fn to_numalgo3(&self) -> Result<PeerDid<Numalgo3>, DidPeerError> {
let numalgoless_id = self.did().id().chars().skip(1).collect::<String>();
let numalgoless_id_hashed = {
let mut hasher = Sha256::new();
hasher.update(numalgoless_id.as_bytes());
hasher.finalize()
};
let bytes = [MULTIHASH_SHA2_256.as_slice(), &numalgoless_id_hashed[..]].concat();
let multibase_hash = multibase::encode(multibase::Base::Base58Btc, bytes);
PeerDid::<Numalgo3>::parse(format!("did:peer:3{multibase_hash}"))
}
pub(crate) fn to_did_doc_builder(
&self,
public_key_encoding: PublicKeyEncoding,
) -> Result<DidDocument, DidPeerError> {
let mut did_doc_builder: DidDocument = DidDocument::new(self.did().clone());
did_doc_builder =
diddoc_from_peerdid2_elements(did_doc_builder, self.did(), public_key_encoding)?;
Ok(did_doc_builder)
}
}
#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub struct Numalgo2;
impl Numalgo for Numalgo2 {
const NUMALGO_CHAR: char = '2';
}
#[cfg(test)]
mod test {
use did_doc::schema::{
did_doc::DidDocument, service::service_key_kind::ServiceKeyKind,
verification_method::PublicKeyField,
};
use did_parser_nom::DidUrl;
use pretty_assertions::assert_eq;
use serde_json::{from_value, json};
use crate::{
peer_did::{numalgos::numalgo2::Numalgo2, PeerDid},
resolver::options::PublicKeyEncoding,
};
#[test]
fn test_peer_did_2_encode_decode() {
// NOTE 20/6/24: universal resolver resolves an additional "assertionMethod" key for the "V"
// key despite the spec not saying to do this.
let expected_did_peer = "did:peer:2.Ez6MkkukgyKAdBN46UAHvia2nxmioo74F6YdvW1nBT1wfKKha.Vz6MkfoapUdLHHgSMq5PYhdHYCoqGuRku2i17cQ9zAoR5cLSm.SeyJpZCI6IiNmb29iYXIiLCJ0IjpbImRpZC1jb21tdW5pY2F0aW9uIl0sInMiOiJodHRwOi8vZHVtbXl1cmwub3JnLyIsInIiOlsiIzZNa2t1a2d5Il0sImEiOlsiZGlkY29tbS9haXAyO2Vudj1yZmMxOSJdfQ";
let value = json!({
"id": expected_did_peer,
"verificationMethod": [
{
"id": "#key-1",
"controller": expected_did_peer,
"type": "Ed25519VerificationKey2020",
"publicKeyMultibase": "z6MkkukgyKAdBN46UAHvia2nxmioo74F6YdvW1nBT1wfKKha"
},
{
"id": "#key-2",
"controller": expected_did_peer,
"type": "Ed25519VerificationKey2020",
"publicKeyMultibase": "z6MkfoapUdLHHgSMq5PYhdHYCoqGuRku2i17cQ9zAoR5cLSm"
}
],
"keyAgreement": [
"#key-1"
],
"authentication": [
"#key-2"
],
"service": [
{
"id": "#foobar",
"type": [
"did-communication"
],
"serviceEndpoint": "http://dummyurl.org/",
"routingKeys": ["#6Mkkukgy"],
"accept": [
"didcomm/aip2;env=rfc19"
],
}
]
});
let ddo_original: DidDocument = from_value(value).unwrap();
let did_peer: PeerDid<Numalgo2> = PeerDid::from_did_doc(ddo_original.clone()).unwrap();
assert_eq!(did_peer.to_string(), expected_did_peer);
let ddo_decoded: DidDocument = did_peer
.to_did_doc_builder(PublicKeyEncoding::Multibase)
.unwrap();
assert_eq!(ddo_original, ddo_decoded);
}
#[test]
fn test_acapy_did_peer_2() {
// test vector from AATH testing with acapy 0.12.1
let did = "did:peer:2.Vz6MkqY3gWxHEp47gCXBmnc5k7sAQChwV76YpZAHZ8erDHatK.SeyJpZCI6IiNkaWRjb21tLTAiLCJ0IjoiZGlkLWNvbW11bmljYXRpb24iLCJwcmlvcml0eSI6MCwicmVjaXBpZW50S2V5cyI6WyIja2V5LTEiXSwiciI6W10sInMiOiJodHRwOi8vaG9zdC5kb2NrZXIuaW50ZXJuYWw6OTAzMSJ9";
let did = PeerDid::<Numalgo2>::parse(did).unwrap();
let doc = did
.to_did_doc_builder(PublicKeyEncoding::Multibase)
.unwrap();
assert_eq!(doc.verification_method().len(), 1);
let vm = doc.verification_method_by_id("key-1").unwrap();
assert_eq!(
vm.public_key().unwrap().fingerprint(),
"z6MkqY3gWxHEp47gCXBmnc5k7sAQChwV76YpZAHZ8erDHatK"
);
assert_eq!(
vm.public_key_field(),
&PublicKeyField::Multibase {
public_key_multibase: String::from(
"z6MkqY3gWxHEp47gCXBmnc5k7sAQChwV76YpZAHZ8erDHatK"
)
}
);
assert_eq!(doc.service().len(), 1);
let service = doc
.get_service_by_id(&"#didcomm-0".parse().unwrap())
.unwrap();
assert_eq!(
service.service_endpoint().to_string(),
"http://host.docker.internal:9031/"
);
let recips = service.extra_field_recipient_keys().unwrap();
assert_eq!(recips.len(), 1);
assert_eq!(
recips[0],
ServiceKeyKind::Reference(DidUrl::parse("#key-1".to_string()).unwrap())
);
}
#[test]
fn test_resolving_spec_defined_example() {
// https://identity.foundation/peer-did-method-spec/#example-peer-did-2
// NOTE: excluding the services, as they use a different type of service to the typical
// service DIDDoc structure
let did = "did:peer:2.Vz6Mkj3PUd1WjvaDhNZhhhXQdz5UnZXmS7ehtx8bsPpD47kKc.\
Ez6LSg8zQom395jKLrGiBNruB9MM6V8PWuf2FpEy4uRFiqQBR";
let did = PeerDid::<Numalgo2>::parse(did).unwrap();
let doc = did
.to_did_doc_builder(PublicKeyEncoding::Multibase)
.unwrap();
let expected_doc: DidDocument = serde_json::from_value(json!({
"id": "did:peer:2.Vz6Mkj3PUd1WjvaDhNZhhhXQdz5UnZXmS7ehtx8bsPpD47kKc.Ez6LSg8zQom395jKLrGiBNruB9MM6V8PWuf2FpEy4uRFiqQBR",
"verificationMethod": [
{
"id": "#key-1",
"controller": "did:peer:2.Vz6Mkj3PUd1WjvaDhNZhhhXQdz5UnZXmS7ehtx8bsPpD47kKc.Ez6LSg8zQom395jKLrGiBNruB9MM6V8PWuf2FpEy4uRFiqQBR",
"type": "Ed25519VerificationKey2020",
"publicKeyMultibase": "z6Mkj3PUd1WjvaDhNZhhhXQdz5UnZXmS7ehtx8bsPpD47kKc"
},
{
"id": "#key-2",
"controller": "did:peer:2.Vz6Mkj3PUd1WjvaDhNZhhhXQdz5UnZXmS7ehtx8bsPpD47kKc.Ez6LSg8zQom395jKLrGiBNruB9MM6V8PWuf2FpEy4uRFiqQBR",
"type": "X25519KeyAgreementKey2020",
"publicKeyMultibase": "z6LSg8zQom395jKLrGiBNruB9MM6V8PWuf2FpEy4uRFiqQBR"
}
],
"authentication": [
"#key-1"
],
"keyAgreement": [
"#key-2"
]
})).unwrap();
assert_eq!(doc, expected_doc);
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo2/service_abbreviation.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo2/service_abbreviation.rs | use std::{collections::HashMap, str::FromStr};
use did_doc::schema::{
service::{
service_accept_type::ServiceAcceptType, service_key_kind::ServiceKeyKind,
typed::ServiceType, Service,
},
types::uri::Uri,
utils::OneOrList,
};
use serde::{Deserialize, Serialize};
use serde_json::{from_value, Value};
use url::Url;
use crate::error::DidPeerError;
#[derive(Serialize, Deserialize, Debug)]
pub struct ServiceAbbreviatedDidPeer2 {
// https://identity.foundation/peer-did-method-spec/#generating-a-didpeer2
// > For use with did:peer:2, service id attributes MUST be relative.
// > The service MAY omit the id; however, this is NOT RECOMMEDED (clarified).
id: Option<Uri>,
#[serde(rename = "t")]
service_type: OneOrList<String>,
#[serde(rename = "s")]
service_endpoint: Url,
#[serde(rename = "r")]
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
routing_keys: Vec<ServiceKeyKind>,
#[serde(rename = "a")]
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
accept: Vec<ServiceAcceptType>,
#[serde(flatten)]
#[serde(skip_serializing_if = "HashMap::is_empty")]
extra: HashMap<String, Value>,
}
impl ServiceAbbreviatedDidPeer2 {
pub fn new(
id: Option<Uri>,
service_type: OneOrList<String>,
service_endpoint: Url,
routing_keys: Vec<ServiceKeyKind>,
accept: Vec<ServiceAcceptType>,
) -> Self {
Self {
id,
service_type,
service_endpoint,
routing_keys,
accept,
extra: Default::default(),
}
}
}
// todo: This is encoding is lossy but shouldn't be.
// Right now any unrecognized field will not be included in the abbreviated form
pub(crate) fn abbreviate_service(
service: &Service,
) -> Result<ServiceAbbreviatedDidPeer2, DidPeerError> {
let service_endpoint = service.service_endpoint().clone();
let routing_keys = {
service
.extra()
.get("routingKeys")
.map(|value| {
from_value::<Vec<ServiceKeyKind>>(value.clone()).map_err(|_| {
DidPeerError::ParsingError(format!(
"Could not parse routing keys as Vector of Strings. Value of \
routing_keys: {value}"
))
})
})
.unwrap_or_else(|| Ok(vec![]))
}?;
let accept = {
service
.extra()
.get("accept")
.map(|value| {
from_value::<Vec<ServiceAcceptType>>(value.clone()).map_err(|_| {
DidPeerError::ParsingError(format!(
"Could not parse accept as Vector of Strings. Value of accept: {value}"
))
})
})
.unwrap_or_else(|| Ok(vec![]))
}?;
let service_type = service.service_type().clone();
let service_types_abbreviated = match service_type {
OneOrList::List(service_types) => {
let abbreviated_list = service_types
.iter()
.map(|value| {
if value == &ServiceType::DIDCommV2 {
"dm".to_string()
} else {
value.to_string()
}
})
.collect();
OneOrList::List(abbreviated_list)
}
OneOrList::One(service_type) => {
if service_type == ServiceType::DIDCommV2 {
OneOrList::One("dm".to_string())
} else {
OneOrList::One(service_type.to_string())
}
}
};
Ok(ServiceAbbreviatedDidPeer2::new(
Some(service.id().clone()),
service_types_abbreviated,
service_endpoint,
routing_keys,
accept,
))
}
pub(crate) fn deabbreviate_service(
abbreviated: ServiceAbbreviatedDidPeer2,
index: usize,
) -> Result<Service, DidPeerError> {
let service_type = match abbreviated.service_type {
OneOrList::One(service_type) => {
let typed = match service_type.as_str() {
"dm" => ServiceType::DIDCommV2,
_ => ServiceType::from_str(&service_type)?,
};
OneOrList::One(typed)
}
OneOrList::List(service_types) => {
let mut typed = Vec::new();
for service_type in service_types.iter() {
let service = match service_type.as_str() {
"dm" => ServiceType::DIDCommV2,
_ => ServiceType::from_str(service_type)?,
};
typed.push(service);
}
OneOrList::List(typed)
}
};
let id = abbreviated
.id
.clone()
.unwrap_or(format!("#service-{index}").parse()?);
let mut service = Service::new(
id,
abbreviated.service_endpoint,
service_type,
abbreviated.extra,
);
let routing_keys = abbreviated.routing_keys;
if !routing_keys.is_empty() {
service.add_extra_field_routing_keys(routing_keys)?;
}
let accept = abbreviated.accept;
if !accept.is_empty() {
service.add_extra_field_accept(accept)?;
}
Ok(service)
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use did_doc::schema::{
service::{
service_accept_type::ServiceAcceptType, service_key_kind::ServiceKeyKind,
typed::ServiceType, Service,
},
types::uri::Uri,
utils::OneOrList,
};
use serde_json::json;
use url::Url;
use crate::peer_did::numalgos::numalgo2::service_abbreviation::{
abbreviate_service, deabbreviate_service, ServiceAbbreviatedDidPeer2,
};
#[test]
fn test_deabbreviate_service_type_value_dm() {
let service_abbreviated = ServiceAbbreviatedDidPeer2 {
id: Some(Uri::new("#service-0").unwrap()),
service_type: OneOrList::One("dm".to_string()),
service_endpoint: Url::parse("https://example.org").unwrap(),
routing_keys: vec![],
accept: vec![],
extra: HashMap::new(),
};
let index = 0;
let service = deabbreviate_service(service_abbreviated, index).unwrap();
assert_eq!(
service.service_type().clone(),
OneOrList::One(ServiceType::DIDCommV2)
);
}
#[test]
fn test_deabbreviate_service() {
let routing_keys = vec![ServiceKeyKind::Value("key1".to_string())];
let accept = vec![ServiceAcceptType::DIDCommV1];
let service_endpoint = Url::parse("https://example.com/endpoint").unwrap();
let service_type = OneOrList::One(ServiceType::Other("foobar".to_string()));
let service_id = Uri::new("#service-0").unwrap();
let service_abbreviated = ServiceAbbreviatedDidPeer2 {
id: Some(service_id),
service_type: OneOrList::One("foobar".to_string()),
service_endpoint: service_endpoint.clone(),
routing_keys: routing_keys.clone(),
accept: accept.clone(),
extra: HashMap::new(),
};
let index = 0;
let service = deabbreviate_service(service_abbreviated, index).unwrap();
assert_eq!(service.service_type().clone(), service_type);
assert_eq!(service.service_endpoint().clone(), service_endpoint);
assert_eq!(service.extra_field_routing_keys().unwrap(), routing_keys);
assert_eq!(service.extra_field_accept().unwrap(), accept);
}
#[test]
fn test_abbreviate_deabbreviate_service() {
let service: Service = serde_json::from_value(json!({
"id": "#0",
"type": [
"did-communication"
],
"serviceEndpoint": "http://dummyurl.org/",
"routingKeys": [],
"accept": [
"didcomm/aip2;env=rfc19"
],
"priority": 0,
"recipientKeys": [
"did:key:z6MkkukgyKAdBN46UAHvia2nxmioo74F6YdvW1nBT1wfKKha"
]
}))
.unwrap();
let abbreviated = serde_json::to_value(abbreviate_service(&service).unwrap()).unwrap();
// Note: the abbreviation is lossy! "recipient_keys", "priority" are legacy concept, we
// shouldn't mind
let expected = json!(
{
"id": "#0",
"t": ["did-communication"],
"s": "http://dummyurl.org/",
"a": ["didcomm/aip2;env=rfc19"]
}
);
assert_eq!(abbreviated, expected);
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo2/encoding.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo2/encoding.rs | use std::cmp::Ordering;
use base64::{engine::general_purpose::STANDARD_NO_PAD, Engine};
use did_doc::schema::{
did_doc::DidDocument,
verification_method::{VerificationMethod, VerificationMethodKind},
};
use public_key::Key;
use crate::{
error::DidPeerError,
peer_did::numalgos::numalgo2::{
purpose::ElementPurpose,
service_abbreviation::{abbreviate_service, ServiceAbbreviatedDidPeer2},
verification_method::get_key_by_verification_method,
},
};
pub(crate) fn append_encoded_key_segments(
mut did: String,
did_document: &DidDocument,
) -> Result<String, DidPeerError> {
for am in did_document.assertion_method() {
did = append_encoded_key_segment(did, did_document, am, ElementPurpose::Assertion)?;
}
for ka in did_document.key_agreement() {
did = append_encoded_key_segment(did, did_document, ka, ElementPurpose::Encryption)?;
}
for a in did_document.authentication() {
did = append_encoded_key_segment(did, did_document, a, ElementPurpose::Verification)?;
}
for ci in did_document.capability_invocation() {
did = append_encoded_key_segment(
did,
did_document,
ci,
ElementPurpose::CapabilityInvocation,
)?;
}
for cd in did_document.capability_delegation() {
did = append_encoded_key_segment(
did,
did_document,
cd,
ElementPurpose::CapabilityDelegation,
)?;
}
Ok(did)
}
pub(crate) fn append_encoded_service_segment(
mut did: String,
did_document: &DidDocument,
) -> Result<String, DidPeerError> {
let services_abbreviated = did_document
.service()
.iter()
.map(abbreviate_service)
.collect::<Result<Vec<ServiceAbbreviatedDidPeer2>, _>>()?;
let service_encoded = match services_abbreviated.len().cmp(&1) {
Ordering::Less => None,
Ordering::Equal => {
let service_abbreviated = services_abbreviated.first().unwrap();
Some(STANDARD_NO_PAD.encode(serde_json::to_vec(&service_abbreviated)?))
}
Ordering::Greater => {
// todo: Easy fix; this should be implemented by iterating over each service and then
// appending the services in peer did, separated by a dot.
// See https://identity.foundation/peer-did-method-spec/
unimplemented!("Multiple services are not supported yet")
}
};
if let Some(service_encoded) = service_encoded {
let encoded = format!(".{}{}", ElementPurpose::Service, service_encoded);
did.push_str(&encoded);
}
Ok(did)
}
fn append_encoded_key_segment(
did: String,
did_document: &DidDocument,
vm: &VerificationMethodKind,
purpose: ElementPurpose,
) -> Result<String, DidPeerError> {
let vm = resolve_verification_method(did_document, vm)?;
let key = get_key_by_verification_method(vm)?;
Ok(append_key_to_did(did, key, purpose))
}
fn resolve_verification_method<'a>(
did_document: &'a DidDocument,
vm: &'a VerificationMethodKind,
) -> Result<&'a VerificationMethod, DidPeerError> {
match vm {
VerificationMethodKind::Resolved(vm) => Ok(vm),
VerificationMethodKind::Resolvable(did_url) => {
did_document
.dereference_key(did_url)
.ok_or(DidPeerError::InvalidKeyReference(format!(
"Could not resolve verification method: {did_url} on DID document: {did_document}"
)))
}
}
}
fn append_key_to_did(mut did: String, key: Key, purpose: ElementPurpose) -> String {
let encoded = format!(".{}{}", purpose, key.fingerprint());
did.push_str(&encoded);
did
}
#[cfg(test)]
mod tests {
use did_doc::schema::{
service::{
service_key_kind::ServiceKeyKind,
typed::{didcommv2::ExtraFieldsDidCommV2, ServiceType},
Service,
},
types::uri::Uri,
utils::OneOrList,
verification_method::{PublicKeyField, VerificationMethod, VerificationMethodType},
};
use did_parser_nom::{Did, DidUrl};
use pretty_assertions::assert_eq;
use super::*;
use crate::{
helpers::convert_to_hashmap,
peer_did::{numalgos::numalgo2::Numalgo2, PeerDid},
resolver::options::PublicKeyEncoding,
};
fn create_verification_method(
verification_method_id: String,
controller_did: String,
key: String,
verification_type: VerificationMethodType,
) -> VerificationMethod {
VerificationMethod::builder()
.id(verification_method_id.parse().unwrap())
.controller(Did::parse(controller_did).unwrap())
.verification_method_type(verification_type)
.public_key(PublicKeyField::Multibase {
public_key_multibase: key,
})
.build()
}
#[test]
fn test_append_encoded_key_segments() {
let did = "did:peer:2";
let key_0 = "z6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc";
let key_1 = "z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V";
let did_full = format!("{did}.E{key_0}.V{key_1}");
let vm_0 = create_verification_method(
"#key-1".to_string(),
did_full.to_string(),
key_0.to_string(),
VerificationMethodType::X25519KeyAgreementKey2020,
);
let vm_1 = create_verification_method(
"#key-2".to_string(),
did_full.to_string(),
key_1.to_string(),
VerificationMethodType::Ed25519VerificationKey2020,
);
let mut did_document = DidDocument::new(Did::parse(did_full.clone()).unwrap());
did_document.add_key_agreement_ref(vm_0.id().to_owned());
did_document.add_verification_method(vm_0);
did_document.add_authentication_ref(vm_1.id().to_owned());
did_document.add_verification_method(vm_1);
let did = append_encoded_key_segments(did.to_string(), &did_document).unwrap();
assert_eq!(did, did_full);
}
#[tokio::test]
async fn test_append_encoded_service_segment() {
let did = "did:peer:2";
let service = "eyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXSwiYSI6WyJkaWRjb21tL3YyIiwiZGlkY29tbS9haXAyO2Vudj1yZmM1ODciXX0";
let did_expected = format!("{did}.S{service}");
let extra = ExtraFieldsDidCommV2::builder()
.routing_keys(vec![ServiceKeyKind::Reference(
"did:example:somemediator#somekey".parse().unwrap(),
)])
.accept(vec!["didcomm/v2".into(), "didcomm/aip2;env=rfc587".into()])
.build();
let service = Service::new(
Uri::new("#service-0").unwrap(),
"https://example.com/endpoint".parse().unwrap(),
OneOrList::One(ServiceType::DIDCommV2),
convert_to_hashmap(&extra).unwrap(),
);
let mut did_document = DidDocument::new(did_expected.parse().unwrap());
did_document.add_service(service);
let did = append_encoded_service_segment(did.to_string(), &did_document).unwrap();
let did_parsed = PeerDid::<Numalgo2>::parse(did.clone()).unwrap();
let ddo = did_parsed
.to_did_doc_builder(PublicKeyEncoding::Base58)
.unwrap();
let did_expected_parsed = PeerDid::<Numalgo2>::parse(did_expected.clone()).unwrap();
let ddo_expected = did_expected_parsed
.to_did_doc_builder(PublicKeyEncoding::Base58)
.unwrap();
assert_eq!(ddo, ddo_expected);
assert_eq!(did, did_expected);
}
#[test]
fn test_append_encoded_segments_error() {
let did = "did:peer:2";
let key = "invalid_key";
let did_full = format!("{did}.E{key}");
let vm = create_verification_method(
"#key-1".to_string(),
did_full.to_string(),
key.to_string(),
VerificationMethodType::X25519KeyAgreementKey2020,
);
let mut did_document = DidDocument::new(did_full.parse().unwrap());
did_document.add_key_agreement_object(vm);
let result = append_encoded_key_segments(did.to_string(), &did_document);
assert!(result.is_err());
}
#[test]
fn test_append_encoded_key_segments_multiple_keys() {
let did = "did:peer:2";
let key_0 = "z6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc";
let key_1 = "z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V";
let key_2 = "z6Mkumaf3DZPAw8CN8r7vqA4UbW5b6hFfpq6nM4xud1MBZ9n";
let did_full = format!("{did}.A{key_0}.E{key_1}.V{key_2}");
let vm_0 = create_verification_method(
"#key-1".to_string(),
did_full.to_string(),
key_0.to_string(),
VerificationMethodType::X25519KeyAgreementKey2020,
);
let vm_1 = create_verification_method(
"#key-2".to_string(),
did_full.to_string(),
key_1.to_string(),
VerificationMethodType::Ed25519VerificationKey2020,
);
let vm_2 = create_verification_method(
"#key-3".to_string(),
did_full.to_string(),
key_2.to_string(),
VerificationMethodType::Ed25519VerificationKey2020,
);
let mut did_document = DidDocument::new(did_full.parse().unwrap());
did_document.add_assertion_method_object(vm_0);
did_document.add_key_agreement_object(vm_1);
did_document.add_authentication_object(vm_2);
let did = append_encoded_key_segments(did.to_string(), &did_document).unwrap();
assert_eq!(did, did_full);
}
#[test]
fn test_append_encoded_key_segments_resolvable_key() {
let env = env_logger::Env::default().default_filter_or("info");
env_logger::init_from_env(env);
let did = "did:peer:2";
let key = "z6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc";
let did_full = format!("{did}.E{key}.V{key}");
let reference = "key-1";
let vm = create_verification_method(
format!("#{reference}"),
did_full.to_string(),
key.to_string(),
VerificationMethodType::X25519KeyAgreementKey2020,
);
let mut did_document = DidDocument::new(did_full.parse().unwrap());
did_document.add_verification_method(vm);
did_document.add_authentication_ref(DidUrl::from_fragment(reference.to_string()).unwrap());
did_document.add_key_agreement_ref(DidUrl::from_fragment(reference.to_string()).unwrap());
let did = append_encoded_key_segments(did.to_string(), &did_document).unwrap();
assert_eq!(did, did_full);
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo1/mod.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo1/mod.rs | use crate::peer_did::numalgos::Numalgo;
#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub struct Numalgo1;
impl Numalgo for Numalgo1 {
const NUMALGO_CHAR: char = '1';
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo4/mod.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo4/mod.rs | use did_doc::schema::did_doc::DidDocument;
use did_parser_nom::Did;
use sha2::{Digest, Sha256};
use crate::{
error::DidPeerError,
helpers::{MULTICODEC_JSON_VARINT, MULTIHASH_SHA2_256},
peer_did::{
numalgos::{numalgo4::construction_did_doc::DidPeer4ConstructionDidDocument, Numalgo},
PeerDid,
},
};
pub mod construction_did_doc;
#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub struct Numalgo4;
impl Numalgo for Numalgo4 {
const NUMALGO_CHAR: char = '4';
}
impl PeerDid<Numalgo4> {
/// Implementation of did:peer:4 creation spec:
/// https://identity.foundation/peer-did-method-spec/#creating-a-did
pub fn new(encoded_document: DidPeer4ConstructionDidDocument) -> Result<Self, DidPeerError> {
let serialized = serde_json::to_vec(&encoded_document)?;
let encoded_document = multibase::encode(
multibase::Base::Base58Btc,
[MULTICODEC_JSON_VARINT.as_slice(), &serialized].concat(),
);
let encoded_doc_digest = {
let mut hasher = Sha256::new();
hasher.update(encoded_document.as_bytes());
hasher.finalize()
};
let hash = multibase::encode(
multibase::Base::Base58Btc,
[MULTIHASH_SHA2_256.as_slice(), &encoded_doc_digest].concat(),
);
let did = Did::parse(format!("did:peer:4{hash}:{encoded_document}"))?;
Ok(Self {
did,
numalgo: Numalgo4,
})
}
pub fn long_form(&self) -> Result<Did, DidPeerError> {
self.encoded_did_peer_4_document()
.ok_or(DidPeerError::GeneralError(format!(
"Long form is not available for peer did: {}",
self.did
)))?;
Ok(self.did().clone())
}
pub fn short_form(&self) -> Did {
let parts = self.did().id().split(':').collect::<Vec<&str>>();
let short_form_id = match parts.first() {
None => {
return self.did().clone(); // the DID was short form already
}
Some(hash_part) => hash_part,
};
let short_form_did = format!("did:peer:{short_form_id}");
let parse_result = Did::parse(short_form_did).map_err(|e| {
DidPeerError::GeneralError(format!("Failed to parse short form of PeerDid: {e}"))
});
// ** safety note (panic) **
// This should only panic if the parser is inherently buggy. We rely on following
// assumptions:
// - `did:peer:` is a valid DID prefix
// - `short_form_did` is substring/prefix of `self.id()`, without colons, and therefore
// valid DID ID
// - every peer-did includes hash component followed prefix "did:peer:"
parse_result.expect("Failed to parse short form of PeerDid")
}
pub fn hash(&self) -> Result<String, DidPeerError> {
let short_form_did = self.short_form();
let hash = short_form_did.id()[1..].to_string(); // the first character of id did:peer:4 ID is always "4", followed by hash
Ok(hash)
}
fn encoded_did_peer_4_document(&self) -> Option<&str> {
let did = self.did();
did.id().split(':').collect::<Vec<_>>().get(1).copied()
}
fn to_did_peer_4_encoded_diddoc(
&self,
) -> Result<DidPeer4ConstructionDidDocument, DidPeerError> {
let encoded_did_doc =
self.encoded_did_peer_4_document()
.ok_or(DidPeerError::GeneralError(format!(
"to_did_peer_4_encoded_diddoc >> Long form is not available for peer did: {}",
self.did
)))?;
let (_base, diddoc_with_multibase_prefix) =
multibase::decode(encoded_did_doc).map_err(|e| {
DidPeerError::GeneralError(format!(
"Failed to decode multibase prefix from encoded did doc: {e}"
))
})?;
// without first 2 bytes
let peer4_did_doc: &[u8] = &diddoc_with_multibase_prefix[2..];
let encoded_document: DidPeer4ConstructionDidDocument =
serde_json::from_slice(peer4_did_doc).map_err(|e| {
DidPeerError::GeneralError(format!("Failed to decode the encoded did doc: {e}"))
})?;
Ok(encoded_document)
}
pub fn resolve_did_doc(&self) -> Result<DidDocument, DidPeerError> {
let did_doc_peer4_encoded = self.to_did_peer_4_encoded_diddoc()?;
Ok(did_doc_peer4_encoded.contextualize_to_did_doc(self))
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use did_doc::schema::{
service::{service_key_kind::ServiceKeyKind, typed::ServiceType, Service},
types::uri::Uri,
utils::OneOrList,
verification_method::{PublicKeyField, VerificationMethodType},
};
use did_parser_nom::DidUrl;
use public_key::KeyType;
use crate::peer_did::{
numalgos::numalgo4::{
construction_did_doc::{DidPeer4ConstructionDidDocument, DidPeer4VerificationMethod},
Numalgo4,
},
PeerDid,
};
fn prepare_verification_method(key_id: &str) -> DidPeer4VerificationMethod {
DidPeer4VerificationMethod::builder()
.id(DidUrl::parse(key_id.to_string()).unwrap())
.verification_method_type(VerificationMethodType::Ed25519VerificationKey2020)
.public_key(PublicKeyField::Base58 {
public_key_base58: "z27uFkiq".to_string(),
})
.build()
}
#[test]
fn test_create_did_peer_4() {
let service = Service::new(
Uri::new("#service-0").unwrap(),
"https://example.com/endpoint".parse().unwrap(),
OneOrList::One(ServiceType::DIDCommV2),
HashMap::default(),
);
let vm = prepare_verification_method("#shared-key-1");
let vm_ka = prepare_verification_method("#key_agreement-1");
let vm_auth = prepare_verification_method("#key-authentication-1");
let vm_deleg = prepare_verification_method("#key-delegation-1");
let vm_invoc = prepare_verification_method("#key-invocation-1");
let mut construction_did_doc = DidPeer4ConstructionDidDocument::new();
construction_did_doc.add_service(service);
construction_did_doc.add_verification_method(vm);
construction_did_doc.add_key_agreement(vm_ka);
construction_did_doc.add_authentication(vm_auth);
construction_did_doc.add_capability_delegation(vm_deleg);
construction_did_doc.add_capability_invocation(vm_invoc);
let did = PeerDid::<Numalgo4>::new(construction_did_doc).unwrap();
let did_expected = "did:peer:4zQmcaWgiE7Q6ERzDovHKrQXEPC1bd7X4YAv9Hb9Pw1Qhjtm:zMeTVLzkiLyX6Wj4CLuZ7WoX3ZSxFQVFBYQy5vfZmgZUCuFcsVeuWMrvhznUxei6NqGDqoE4rYF88ptgdQxFmrCj7fcqxdvzBjncMDsyYXYLzucXydU2N1cXSZH8rN5srWEftBUg4SsVrF8upEMJ81Yts9fBTitgrCzQGdpPGnBtWKh6C21uVBM1wShxrG5FGcisduzRnGDKLCEGxKDZkBrSaTsWk7a2kTMi45nouL8VnXY9DkfcyJTYwvdNC67BXpdp44ksvvtveYH6WqmvCNhPi7RSEdYoD7ZZYDBboRvbuAQANQSMPqpmj9L8Zz62oDxYJffFqK8yjdhBfanyqtQMCnxm7w1rDhExZdUK6BSQL3utQ1LeeZmHLZmXdsQp3nkTLrW4AwWnoTVEGSgnSDsgRiZkma9YaZgnZVhnQeNj4fjes6aZKwEjqLChabXfrXU6d6EJ9v4tRrHxatxdEdM5wmgCMxEVFhpSjcLQu7bpULkj63GUQMVWyWcXyd8UsP56rMWgyutCRtfA4Mm7sVKgcp7324fzAB6VLXLoHy6dPdhrZ2eYcB4Qgke12PpF37xFViScqEdQovUDPWiH41Kz898T3chUvDyFCP6ugXmwJTXGgSTxLT5gpBEjvbshbrV6jAFy4wWnBeaQVvDAG7DgDa7jhGqj3Grg4NHzPLFne37GKrWW1dxtfL2D8XKyLb6tMsny6bAqdrtt5LhRazuaXgGmWCtksLZeaPrjdFKa4Gevj6BiJ67RC15HoecGsZYUtQdXzBPkVvyvWbzbh3UaEYppCP6yq8ZGYc7AeGX8YnatwmhoECdoV1GdZAdRAoqj4pQmn4mTjHUfZ3ZmPQxYqhiAxrdzG51MDVc182YLWhMBbShxxUXs11b1UT4JVXizwzoArZNzg7PQekbRcauHHaRLRcQ";
assert_eq!(did.to_string(), did_expected);
let resolved_did_doc = did.resolve_did_doc().unwrap();
println!(
"resolved document: {}",
serde_json::to_string_pretty(&resolved_did_doc).unwrap()
);
assert_eq!(resolved_did_doc.id().to_string(), did.did().to_string());
assert!(resolved_did_doc
.verification_method_by_id("shared-key-1")
.is_some());
assert!(resolved_did_doc
.key_agreement_by_id("key_agreement-1")
.is_some());
assert!(resolved_did_doc
.authentication_by_id("key-authentication-1")
.is_some());
assert!(resolved_did_doc
.capability_delegation_by_id("key-delegation-1")
.is_some());
assert!(resolved_did_doc
.capability_invocation_by_id("key-invocation-1")
.is_some());
log::info!(
"resolved document: {}",
serde_json::to_string_pretty(&resolved_did_doc).unwrap()
);
}
#[test]
fn long_form_to_short_form() {
let peer_did = "did:peer:4z84UjLJ6ugExV8TJ5gJUtZap5q67uD34LU26m1Ljo2u9PZ4xHa9XnknHLc3YMST5orPXh3LKi6qEYSHdNSgRMvassKP:z27uFkiqJVwvvn2ke5M19UCvByS79r5NppqwjiGAJzkj1EM4sf2JmiUySkANKy4YNu8M7yKjSmvPJTqbcyhPrJs9TASzDs2fWE1vFegmaRJxHRF5M9wGTPwGR1NbPkLGsvcnXum7aN2f8kX3BnhWWWp";
let peer_did = PeerDid::<Numalgo4>::parse(peer_did).unwrap();
assert_eq!(peer_did.short_form().to_string(), "did:peer:4z84UjLJ6ugExV8TJ5gJUtZap5q67uD34LU26m1Ljo2u9PZ4xHa9XnknHLc3YMST5orPXh3LKi6qEYSHdNSgRMvassKP".to_string());
}
#[test]
fn short_form_to_short_form() {
let peer_did = "did:peer:4z84UjLJ6ugExV8TJ5gJUtZap5q67uD34LU26m1Ljo2u9PZ4xHa9XnknHLc3YMST5orPXh3LKi6qEYSHdNSgRMvassKP";
let peer_did = PeerDid::<Numalgo4>::parse(peer_did).unwrap();
assert_eq!(peer_did.short_form().to_string(), "did:peer:4z84UjLJ6ugExV8TJ5gJUtZap5q67uD34LU26m1Ljo2u9PZ4xHa9XnknHLc3YMST5orPXh3LKi6qEYSHdNSgRMvassKP".to_string());
}
#[test]
fn long_form_to_long_form() {
let peer_did = "did:peer:4z84UjLJ6ugExV8TJ5gJUtZap5q67uD34LU26m1Ljo2u9PZ4xHa9XnknHLc3YMST5orPXh3LKi6qEYSHdNSgRMvassKP:z27uFkiqJVwvvn2ke5M19UCvByS79r5NppqwjiGAJzkj1EM4sf2JmiUySkANKy4YNu8M7yKjSmvPJTqbcyhPrJs9TASzDs2fWE1vFegmaRJxHRF5M9wGTPwGR1NbPkLGsvcnXum7aN2f8kX3BnhWWWp";
let peer_did = PeerDid::<Numalgo4>::parse(peer_did).unwrap();
assert_eq!(peer_did.long_form().unwrap().to_string(), "did:peer:4z84UjLJ6ugExV8TJ5gJUtZap5q67uD34LU26m1Ljo2u9PZ4xHa9XnknHLc3YMST5orPXh3LKi6qEYSHdNSgRMvassKP:z27uFkiqJVwvvn2ke5M19UCvByS79r5NppqwjiGAJzkj1EM4sf2JmiUySkANKy4YNu8M7yKjSmvPJTqbcyhPrJs9TASzDs2fWE1vFegmaRJxHRF5M9wGTPwGR1NbPkLGsvcnXum7aN2f8kX3BnhWWWp".to_string());
}
#[test]
fn short_form_to_long_form_fails() {
let peer_did = "did:peer:4z84UjLJ6ugExV8TJ5gJUtZap5q67uD34LU26m1Ljo2u9PZ4xHa9XnknHLc3YMST5orPXh3LKi6qEYSHdNSgRMvassKP";
let peer_did = PeerDid::<Numalgo4>::parse(peer_did).unwrap();
peer_did.long_form().unwrap_err();
}
#[test]
fn test_resolve_acapy_test_vector1() {
let peer_did: &str = "did:peer:4zQmcQCH8nWEBBA6BpSEDxHyhPwHdi5CVGcvsZcjhb618zbA:z5CTtVoAxKjH1V1sKizLy5kLvV6AbmACYfcGmfVUDGn4A7BpnVQEESXEYYUG7W479kDHaqLnk7NJuu4w7ftTd9REipB2CQgW9fjzPvmsXyyHzot9o1tgYHNnqFDXgCXwFYJfjkzz3m6mex1WMN4XHWWNM4NB7exDA2maVGis7gJnVAiNrBExaihyeKJ4nBXrB3ArQ1TyuZ39F9qTeCSrBntTTa85wtUtHz5M1oE7Sj1CZeAEQzDnAMToP9idSrSXUo5z8q9Un325d8MtQgxyKGW2a9VYyW189C722GKQbGQSU3dRSwCanVHJwCh9q2G2eNVPeuydAHXmouCUCq3cVHeUkatv73DSoBV17LEJgq8dAYfvSAutG7LFyvrRW5wNjcQMT7WdFHRCqhtzz18zu6fSTQWM4PQPLMVEaKbs51EeYGiGurhu1ChQMjXqnpcRcpCP7RAEgyWSjMER6e3gdCVsBhQSoqGk1UN8NfVah8pxGg2i5Gd1754Ys6aBEhTashFa47Ke7oPoZ6LZiRMETYhUr1cQY65TQhMzyrR6RzLudeRVgcRdKiTTmP2fFi5H8nCHPSGb4wncUxgn3N5CbFaUC";
let peer_did = PeerDid::<Numalgo4>::parse(peer_did).unwrap();
let resolved_did_doc = peer_did.resolve_did_doc().unwrap();
assert_eq!(resolved_did_doc.id().to_string(), "did:peer:4zQmcQCH8nWEBBA6BpSEDxHyhPwHdi5CVGcvsZcjhb618zbA:z5CTtVoAxKjH1V1sKizLy5kLvV6AbmACYfcGmfVUDGn4A7BpnVQEESXEYYUG7W479kDHaqLnk7NJuu4w7ftTd9REipB2CQgW9fjzPvmsXyyHzot9o1tgYHNnqFDXgCXwFYJfjkzz3m6mex1WMN4XHWWNM4NB7exDA2maVGis7gJnVAiNrBExaihyeKJ4nBXrB3ArQ1TyuZ39F9qTeCSrBntTTa85wtUtHz5M1oE7Sj1CZeAEQzDnAMToP9idSrSXUo5z8q9Un325d8MtQgxyKGW2a9VYyW189C722GKQbGQSU3dRSwCanVHJwCh9q2G2eNVPeuydAHXmouCUCq3cVHeUkatv73DSoBV17LEJgq8dAYfvSAutG7LFyvrRW5wNjcQMT7WdFHRCqhtzz18zu6fSTQWM4PQPLMVEaKbs51EeYGiGurhu1ChQMjXqnpcRcpCP7RAEgyWSjMER6e3gdCVsBhQSoqGk1UN8NfVah8pxGg2i5Gd1754Ys6aBEhTashFa47Ke7oPoZ6LZiRMETYhUr1cQY65TQhMzyrR6RzLudeRVgcRdKiTTmP2fFi5H8nCHPSGb4wncUxgn3N5CbFaUC");
assert_eq!(
resolved_did_doc.also_known_as()[0].to_string(),
"did:peer:4zQmcQCH8nWEBBA6BpSEDxHyhPwHdi5CVGcvsZcjhb618zbA"
);
// vm/key
assert_eq!(resolved_did_doc.verification_method().len(), 1);
let vm = resolved_did_doc.verification_method_by_id("key-0").unwrap();
assert_eq!(
vm.verification_method_type(),
&VerificationMethodType::Multikey
);
assert_eq!(
vm.public_key_field(),
&PublicKeyField::Multibase {
public_key_multibase: String::from(
"z6MkuNenWjqDeZ4DjkHoqX6WdDYTfUUqcR7ASezo846GHe74"
)
}
);
let key = vm.public_key().unwrap();
assert_eq!(
key.fingerprint(),
"z6MkuNenWjqDeZ4DjkHoqX6WdDYTfUUqcR7ASezo846GHe74"
);
assert_eq!(key.key_type(), &KeyType::Ed25519);
// servie
assert_eq!(resolved_did_doc.service().len(), 1);
let service = resolved_did_doc
.get_service_by_id(&"#didcomm-0".parse().unwrap())
.unwrap();
assert_eq!(
service.service_type(),
&OneOrList::One(ServiceType::DIDCommV1)
);
assert_eq!(
service.service_endpoint().to_string(),
"http://host.docker.internal:9031/"
);
let service_recip = service.extra_field_recipient_keys().unwrap();
assert_eq!(
service_recip,
vec![ServiceKeyKind::Reference("#key-0".parse().unwrap())]
);
log::info!(
"resolved document: {}",
serde_json::to_string_pretty(&resolved_did_doc).unwrap()
);
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo4/construction_did_doc.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo4/construction_did_doc.rs | use std::collections::HashMap;
use did_doc::schema::{
did_doc::DidDocument,
service::Service,
types::uri::Uri,
verification_method::{
PublicKeyField, VerificationMethod, VerificationMethodKind, VerificationMethodType,
},
};
use did_parser_nom::DidUrl;
use display_as_json::Display;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use typed_builder::TypedBuilder;
use crate::peer_did::{numalgos::numalgo4::Numalgo4, PeerDid};
/// The following structs DidPeer4ConstructionDidDoc, DidPeer4VerificationMethodKind are similar to
/// those defined in did_doc crate, however with minor differences defined
/// in https://identity.foundation/peer-did-method-spec/#creating-a-did
/// In nutshell:
/// - The document MUST NOT include an id at the root.
/// - All identifiers within this document MUST be relative
/// - All references pointing to resources within this document MUST be relative
/// - For verification methods, the controller MUST be omitted if the controller is the document
/// owner.
///
/// These structures are **only** used for construction of did:peer:4 DIDs
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default, Display)]
#[serde(default)]
#[serde(rename_all = "camelCase")]
pub struct DidPeer4ConstructionDidDocument {
#[serde(skip_serializing_if = "Vec::is_empty")]
also_known_as: Vec<Uri>,
#[serde(skip_serializing_if = "Vec::is_empty")]
verification_method: Vec<DidPeer4VerificationMethod>,
#[serde(skip_serializing_if = "Vec::is_empty")]
authentication: Vec<DidPeer4VerificationMethodKind>,
#[serde(skip_serializing_if = "Vec::is_empty")]
assertion_method: Vec<DidPeer4VerificationMethodKind>,
#[serde(skip_serializing_if = "Vec::is_empty")]
key_agreement: Vec<DidPeer4VerificationMethodKind>,
#[serde(skip_serializing_if = "Vec::is_empty")]
capability_invocation: Vec<DidPeer4VerificationMethodKind>,
#[serde(skip_serializing_if = "Vec::is_empty")]
capability_delegation: Vec<DidPeer4VerificationMethodKind>,
#[serde(skip_serializing_if = "Vec::is_empty")]
service: Vec<Service>,
#[serde(skip_serializing_if = "HashMap::is_empty")]
#[serde(flatten)]
extra: HashMap<String, Value>,
}
impl DidPeer4ConstructionDidDocument {
pub fn new() -> DidPeer4ConstructionDidDocument {
DidPeer4ConstructionDidDocument {
also_known_as: vec![],
verification_method: vec![],
authentication: vec![],
assertion_method: vec![],
key_agreement: vec![],
capability_invocation: vec![],
capability_delegation: vec![],
service: vec![],
extra: Default::default(),
}
}
// - Performs DidDocument "contextualization" as described here: https://identity.foundation/peer-did-method-spec/#resolving-a-did
pub(crate) fn contextualize_to_did_doc(&self, did_peer_4: &PeerDid<Numalgo4>) -> DidDocument {
let did_doc_id = did_peer_4.did().clone();
let mut did_doc = DidDocument::new(did_doc_id);
did_doc.set_service(self.service.clone());
for vm in &self.verification_method {
did_doc.add_verification_method(vm.contextualize(did_peer_4));
}
for vm in &self.key_agreement {
did_doc.add_key_agreement(vm.contextualize(did_peer_4))
}
for vm in &self.authentication {
did_doc.add_authentication(vm.contextualize(did_peer_4))
}
for vm in &self.assertion_method {
did_doc.add_assertion_method(vm.contextualize(did_peer_4))
}
for vm in &self.capability_delegation {
did_doc.add_capability_delegation(vm.contextualize(did_peer_4))
}
for vm in &self.capability_invocation {
did_doc.add_capability_invocation(vm.contextualize(did_peer_4))
}
// ** safety note (panic) **
// Formally every DID is URI. Assuming the parsers for both DID and URI correctly
// implement respective specs, this will never panic.
let did_short_form = did_peer_4.short_form().to_string();
let did_as_uri = Uri::new(&did_short_form).unwrap_or_else(|_| {
panic!(
"DID or URI implementation is buggy, because DID {did_short_form} failed to be parsed as URI. \
This counters W3C DID-CORE spec which states that \"DIDs are URIs\" [RFC3986]."
)
});
did_doc.add_also_known_as(did_as_uri);
did_doc
}
pub fn set_also_known_as(&mut self, uris: Vec<Uri>) {
self.also_known_as = uris;
}
pub fn add_also_known_as(&mut self, uri: Uri) {
self.also_known_as.push(uri);
}
pub fn add_verification_method(&mut self, method: DidPeer4VerificationMethod) {
self.verification_method.push(method);
}
pub fn add_authentication(&mut self, method: DidPeer4VerificationMethod) {
self.authentication
.push(DidPeer4VerificationMethodKind::Resolved(method));
}
pub fn add_authentication_ref(&mut self, reference: DidUrl) {
self.authentication
.push(DidPeer4VerificationMethodKind::Resolvable(reference));
}
pub fn add_assertion_method(&mut self, method: DidPeer4VerificationMethod) {
self.assertion_method
.push(DidPeer4VerificationMethodKind::Resolved(method));
}
pub fn add_assertion_method_ref(&mut self, reference: DidUrl) {
self.assertion_method
.push(DidPeer4VerificationMethodKind::Resolvable(reference));
}
pub fn add_key_agreement(&mut self, method: DidPeer4VerificationMethod) {
self.key_agreement
.push(DidPeer4VerificationMethodKind::Resolved(method));
}
pub fn add_key_agreement_ref(&mut self, reference: DidUrl) {
self.key_agreement
.push(DidPeer4VerificationMethodKind::Resolvable(reference));
}
pub fn add_capability_invocation(&mut self, method: DidPeer4VerificationMethod) {
self.capability_invocation
.push(DidPeer4VerificationMethodKind::Resolved(method));
}
pub fn add_capability_invocation_ref(&mut self, reference: DidUrl) {
self.capability_invocation
.push(DidPeer4VerificationMethodKind::Resolvable(reference));
}
pub fn add_capability_delegation(&mut self, method: DidPeer4VerificationMethod) {
self.capability_delegation
.push(DidPeer4VerificationMethodKind::Resolved(method));
}
pub fn add_capability_delegation_ref(&mut self, reference: DidUrl) {
self.capability_delegation
.push(DidPeer4VerificationMethodKind::Resolvable(reference));
}
// Setter for `service`
pub fn set_service(&mut self, services: Vec<Service>) {
self.service = services;
}
// Add a service
pub fn add_service(&mut self, service: Service) {
self.service.push(service);
}
// Setter for an extra field
pub fn set_extra_field(&mut self, key: String, value: Value) {
self.extra.insert(key, value);
}
// Remove an extra field
pub fn remove_extra_field(&mut self, key: &str) {
self.extra.remove(key);
}
}
/// Struct `DidPeer4VerificationMethodKind` is quite similar to `VerificationMethodKind` (defined
/// in did_doc crate) utilized by `DidPeer4ConstructionDidDoc` for construction of did:peer:4* DIDs.
/// The spec describes differences: https://identity.foundation/peer-did-method-spec/#creating-a-did
/// The spec is describing did document in general, but the restrictions applies
/// to Verification Methods such that:
/// - Verification Method IDs MUST be relative
/// - Reference to Verification Methods must be relative
/// - Controller MUST be omitted if the controller is the document owner.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(untagged)]
#[allow(clippy::large_enum_variant)] // todo: revisit this
pub enum DidPeer4VerificationMethodKind {
Resolved(DidPeer4VerificationMethod),
Resolvable(DidUrl), /* MUST be relative,
TODO: Should we have subtype such as RelativeDidUrl? */
}
impl DidPeer4VerificationMethodKind {
pub fn contextualize(&self, did_peer_4: &PeerDid<Numalgo4>) -> VerificationMethodKind {
match self {
DidPeer4VerificationMethodKind::Resolved(vm) => {
VerificationMethodKind::Resolved(vm.contextualize(did_peer_4))
}
DidPeer4VerificationMethodKind::Resolvable(did_url) => {
VerificationMethodKind::Resolvable(did_url.clone())
}
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, TypedBuilder)]
#[serde(rename_all = "camelCase")]
pub struct DidPeer4VerificationMethod {
id: DidUrl,
// - Controller MUST be relative, can we break down DidUrl into new type RelativeDidUrl?
// - Controller MUST be omitted, if the controller is the document owner (main reason why this
// is different from did_doc::schema::verification_method::VerificationMethod)
// - TODO: add support for controller different than the document owner (how does that work for
// peer DIDs?)
// pub(crate) controller: Option<Did>,
#[serde(rename = "type")]
verification_method_type: VerificationMethodType,
#[serde(flatten)]
public_key: PublicKeyField,
}
impl DidPeer4VerificationMethod {
pub(crate) fn contextualize(&self, did_peer_4: &PeerDid<Numalgo4>) -> VerificationMethod {
VerificationMethod::builder()
.id(self.id.clone())
.controller(did_peer_4.short_form().clone())
.verification_method_type(self.verification_method_type)
.public_key(self.public_key.clone())
.build()
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use did_doc::schema::{
service::{typed::ServiceType, Service},
types::uri::Uri,
utils::OneOrList,
};
use crate::peer_did::numalgos::numalgo4::construction_did_doc::DidPeer4ConstructionDidDocument;
#[test]
fn test_encoded_document_has_builder_api() {
let service = Service::new(
Uri::new("#service-0").unwrap(),
"https://example.com/endpoint".parse().unwrap(),
OneOrList::One(ServiceType::DIDCommV2),
HashMap::default(),
);
let mut construction_did_doc = DidPeer4ConstructionDidDocument::new();
construction_did_doc.add_service(service);
assert_eq!(construction_did_doc.service.len(), 1);
assert_eq!(construction_did_doc.assertion_method.len(), 0);
assert_eq!(construction_did_doc.authentication.len(), 0);
assert_eq!(construction_did_doc.key_agreement.len(), 0);
assert_eq!(construction_did_doc.capability_invocation.len(), 0);
assert_eq!(construction_did_doc.capability_delegation.len(), 0);
assert_eq!(construction_did_doc.verification_method.len(), 0);
assert_eq!(construction_did_doc.also_known_as.len(), 0);
assert_eq!(construction_did_doc.extra.len(), 0);
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo3/mod.rs | did_core/did_methods/did_peer/src/peer_did/numalgos/numalgo3/mod.rs | use did_doc::schema::did_doc::DidDocument;
use crate::{
error::DidPeerError,
peer_did::{
numalgos::{numalgo2::Numalgo2, Numalgo},
FromDidDoc, PeerDid,
},
};
#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub struct Numalgo3;
impl Numalgo for Numalgo3 {
const NUMALGO_CHAR: char = '3';
}
impl FromDidDoc for Numalgo3 {
fn from_did_doc(did_document: DidDocument) -> Result<PeerDid<Numalgo3>, DidPeerError> {
PeerDid::<Numalgo2>::from_did_doc(did_document)?.to_numalgo3()
}
}
#[cfg(test)]
mod tests {
use crate::peer_did::{
numalgos::{numalgo2::Numalgo2, numalgo3::Numalgo3},
PeerDid,
};
#[test]
fn test_generate_numalgo3() {
// from spec: https://identity.foundation/peer-did-method-spec/#method-3-did-shortening-with-sha-256-hash
let full_did2_str = "did:peer:2.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg.SeyJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXSwiYSI6WyJkaWRjb21tL3YyIiwiZGlkY29tbS9haXAyO2Vudj1yZmM1ODciXX0";
let peer_did_2 = PeerDid::<Numalgo2>::parse(full_did2_str).unwrap();
assert_eq!(
PeerDid::<Numalgo3>::parse(
"did:peer:3zQmS19jtYDvGtKVrJhQnRFpBQAx3pJ9omx2HpNrcXFuRCz9".to_string()
)
.unwrap(),
peer_did_2.to_numalgo3().unwrap()
);
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/resolver/options.rs | did_core/did_methods/did_peer/src/resolver/options.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum PublicKeyEncoding {
Multibase,
Base58,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExtraFieldsOptions {
public_key_encoding: PublicKeyEncoding,
}
impl Default for ExtraFieldsOptions {
fn default() -> Self {
Self {
public_key_encoding: PublicKeyEncoding::Base58,
}
}
}
impl ExtraFieldsOptions {
pub fn new() -> Self {
Self {
..Default::default()
}
}
pub fn set_public_key_encoding(mut self, public_key_encoding: PublicKeyEncoding) -> Self {
self.public_key_encoding = public_key_encoding;
self
}
pub fn public_key_encoding(&self) -> PublicKeyEncoding {
self.public_key_encoding
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/src/resolver/mod.rs | did_core/did_methods/did_peer/src/resolver/mod.rs | use async_trait::async_trait;
use did_doc::schema::did_doc::DidDocument;
use did_parser_nom::Did;
use did_resolver::{
error::GenericError,
traits::resolvable::{
resolution_metadata::DidResolutionMetadata, resolution_output::DidResolutionOutput,
DidResolvable,
},
};
use serde::{Deserialize, Serialize};
use crate::{
error::DidPeerError, peer_did::generic::AnyPeerDid, resolver::options::PublicKeyEncoding,
};
pub mod options;
#[derive(Default)]
pub struct PeerDidResolver;
impl PeerDidResolver {
pub fn new() -> Self {
Self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct PeerDidResolutionOptions {
pub encoding: Option<PublicKeyEncoding>,
}
#[async_trait]
impl DidResolvable for PeerDidResolver {
type DidResolutionOptions = PeerDidResolutionOptions;
async fn resolve(
&self,
did: &Did,
options: &Self::DidResolutionOptions,
) -> Result<DidResolutionOutput, GenericError> {
let peer_did = AnyPeerDid::parse(did.to_owned())?;
let did_doc = match peer_did {
AnyPeerDid::Numalgo2(peer_did) => {
let encoding = options.encoding.unwrap_or(PublicKeyEncoding::Multibase);
let mut did_doc: DidDocument = peer_did.to_did_doc_builder(encoding)?;
did_doc.add_also_known_as(peer_did.to_numalgo3()?.to_string().parse()?);
did_doc
}
AnyPeerDid::Numalgo4(peer_did) => peer_did.resolve_did_doc()?,
n => return Err(Box::new(DidPeerError::UnsupportedNumalgo(n.numalgo()))),
};
let resolution_metadata = DidResolutionMetadata::builder()
.content_type("application/did+json".to_string())
.build();
let builder =
DidResolutionOutput::builder(did_doc).did_resolution_metadata(resolution_metadata);
Ok(builder.build())
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/tests/resolve_positive.rs | did_core/did_methods/did_peer/tests/resolve_positive.rs | mod fixtures;
use did_doc::schema::did_doc::DidDocument;
use did_peer::resolver::{options::PublicKeyEncoding, PeerDidResolutionOptions, PeerDidResolver};
use did_resolver::traits::resolvable::DidResolvable;
use pretty_assertions::assert_eq;
use tokio::test;
use crate::fixtures::{
basic::{DID_DOC_BASIC, PEER_DID_NUMALGO_2_BASIC},
no_routing_keys::{DID_DOC_NO_ROUTING_KEYS, PEER_DID_NUMALGO_2_NO_ROUTING_KEYS},
no_services::{DID_DOC_NO_SERVICES, PEER_DID_NUMALGO_2_NO_SERVICES},
};
async fn resolve_positive_test(did_doc: &str, peer_did: &str, options: PeerDidResolutionOptions) {
let did_document_expected = serde_json::from_str::<DidDocument>(did_doc).unwrap();
let resolution = PeerDidResolver
.resolve(&peer_did.parse().unwrap(), &options)
.await
.unwrap();
assert_eq!(resolution.did_document, did_document_expected);
}
#[test]
async fn test_resolve_numalgo2_basic() {
let options = PeerDidResolutionOptions {
encoding: Some(PublicKeyEncoding::Base58),
};
resolve_positive_test(DID_DOC_BASIC, PEER_DID_NUMALGO_2_BASIC, options).await;
}
#[test]
async fn test_resolve_numalgo2_no_routing_keys() {
let options = PeerDidResolutionOptions {
encoding: Some(PublicKeyEncoding::Multibase),
};
resolve_positive_test(
DID_DOC_NO_ROUTING_KEYS,
PEER_DID_NUMALGO_2_NO_ROUTING_KEYS,
options,
)
.await;
}
#[test]
async fn test_resolve_numalgo2_no_services() {
let options = PeerDidResolutionOptions {
encoding: Some(PublicKeyEncoding::Multibase),
};
resolve_positive_test(DID_DOC_NO_SERVICES, PEER_DID_NUMALGO_2_NO_SERVICES, options).await;
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/tests/resolve_negative.rs | did_core/did_methods/did_peer/tests/resolve_negative.rs | mod fixtures;
use did_peer::{
error::DidPeerError,
resolver::{options::PublicKeyEncoding, PeerDidResolutionOptions, PeerDidResolver},
};
use did_resolver::traits::resolvable::DidResolvable;
use tokio::test;
async fn resolve_error(peer_did: &str) -> DidPeerError {
let options = PeerDidResolutionOptions {
encoding: Some(PublicKeyEncoding::Multibase),
};
*PeerDidResolver
.resolve(&peer_did.parse().unwrap(), &options)
.await
.unwrap_err()
.downcast::<DidPeerError>()
.unwrap()
}
#[test]
async fn test_resolve_numalgo_2_invalid_0() {
let peer_did = "did:peer:2\
.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc\
.Vz6666YqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V\
.SeyJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXX0";
assert!(matches!(
resolve_error(peer_did).await,
DidPeerError::PublicKeyError(_)
));
}
#[test]
async fn test_resolve_numalgo_2_invalid_1() {
let peer_did = "did:peer:2\
.Ez7777sY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc\
.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V\
.SeyJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXX0";
assert!(matches!(
resolve_error(peer_did).await,
DidPeerError::PublicKeyError(_)
));
}
#[test]
async fn test_resolve_numalgo_2_invalid_2() {
let peer_did = "did:peer:2.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc.\
Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.\
Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg.Sasdf123";
assert!(matches!(
resolve_error(peer_did).await,
DidPeerError::Base64DecodingError(_)
));
}
#[test]
async fn test_resolve_numalgo_2_invalid_4() {
let peer_did = "did:peer:2\
.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc\
.Vz6MkqRYqQiS\
.SeyJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXX0";
assert!(matches!(
resolve_error(peer_did).await,
DidPeerError::PublicKeyError(_)
));
}
#[test]
async fn test_resolve_numalgo_2_invalid_5() {
let peer_did = "did:peer:2\
.Ez6LSbysY2\
.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V\
.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg\
.SeyJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXX0";
assert!(matches!(
resolve_error(peer_did).await,
DidPeerError::PublicKeyError(_)
));
}
#[test]
async fn test_resolve_numalgo_2_invalid_6() {
let peer_did = "did:peer:2\
.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc\
.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7Vcccccccccc\
.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg\
.SeyJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXX0";
assert!(matches!(
resolve_error(peer_did).await,
DidPeerError::PublicKeyError(_)
));
}
#[test]
async fn test_resolve_numalgo_2_invalid_7() {
let peer_did = "did:peer:2\
.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCcccccccc\
.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V\
.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg\
.SeyJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXX0";
assert!(matches!(
resolve_error(peer_did).await,
DidPeerError::PublicKeyError(_)
));
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/tests/generate.rs | did_core/did_methods/did_peer/tests/generate.rs | mod fixtures;
use did_doc::schema::did_doc::DidDocument;
use did_peer::peer_did::{
numalgos::{numalgo2::Numalgo2, numalgo3::Numalgo3},
PeerDid,
};
use pretty_assertions::assert_eq;
use crate::fixtures::{
basic::{DID_DOC_BASIC, PEER_DID_NUMALGO_2_BASIC, PEER_DID_NUMALGO_3_BASIC},
no_routing_keys::{
DID_DOC_NO_ROUTING_KEYS, PEER_DID_NUMALGO_2_NO_ROUTING_KEYS,
PEER_DID_NUMALGO_3_NO_ROUTING_KEYS,
},
no_services::{
DID_DOC_NO_SERVICES, PEER_DID_NUMALGO_2_NO_SERVICES, PEER_DID_NUMALGO_3_NO_SERVICES,
},
};
fn test_numalgo2(did_doc: &str, expected_peer_did: &str) {
let did_document = serde_json::from_str::<DidDocument>(did_doc).unwrap();
assert_eq!(
PeerDid::<Numalgo2>::parse(expected_peer_did.to_string()).unwrap(),
PeerDid::<Numalgo2>::from_did_doc(did_document).unwrap()
);
}
fn test_numalgo3(did_doc: &str, expected_peer_did: &str) {
let did_document = serde_json::from_str::<DidDocument>(did_doc).unwrap();
assert_eq!(
PeerDid::<Numalgo3>::parse(expected_peer_did.to_string()).unwrap(),
PeerDid::<Numalgo3>::from_did_doc(did_document).unwrap()
);
}
#[test]
fn test_generate_numalgo2_basic() {
test_numalgo2(DID_DOC_BASIC, PEER_DID_NUMALGO_2_BASIC);
}
#[test]
fn test_generate_numalgo2_no_services() {
test_numalgo2(DID_DOC_NO_SERVICES, PEER_DID_NUMALGO_2_NO_SERVICES);
}
#[test]
fn test_generate_numalgo2_no_routing_keys() {
test_numalgo2(DID_DOC_NO_ROUTING_KEYS, PEER_DID_NUMALGO_2_NO_ROUTING_KEYS);
}
#[test]
fn test_generate_numalgo3_basic() {
test_numalgo3(DID_DOC_BASIC, PEER_DID_NUMALGO_3_BASIC);
}
#[test]
fn test_generate_numalgo3_no_services() {
test_numalgo3(DID_DOC_NO_SERVICES, PEER_DID_NUMALGO_3_NO_SERVICES);
}
#[test]
fn test_generate_numalgo3_no_routing_keys() {
test_numalgo3(DID_DOC_NO_ROUTING_KEYS, PEER_DID_NUMALGO_3_NO_ROUTING_KEYS);
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/tests/fixtures/no_services.rs | did_core/did_methods/did_peer/tests/fixtures/no_services.rs | pub static PEER_DID_NUMALGO_2_NO_SERVICES: &str =
"did:peer:2.Ez6LSpSrLxbAhg2SHwKk7kwpsH7DM7QjFS5iK6qP87eViohud.\
Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V";
pub static PEER_DID_NUMALGO_3_NO_SERVICES: &str =
"did:peer:3zQmdysQimott3jS93beGPVX8sTRSRFJWt1FsihPcSy9kZfB";
pub static DID_DOC_NO_SERVICES: &str = r##"
{
"id": "did:peer:2.Ez6LSpSrLxbAhg2SHwKk7kwpsH7DM7QjFS5iK6qP87eViohud.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V",
"alsoKnownAs": ["did:peer:3zQmdysQimott3jS93beGPVX8sTRSRFJWt1FsihPcSy9kZfB"],
"verificationMethod": [
{
"id": "#key-1",
"type": "X25519KeyAgreementKey2020",
"controller": "did:peer:2.Ez6LSpSrLxbAhg2SHwKk7kwpsH7DM7QjFS5iK6qP87eViohud.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V",
"publicKeyMultibase": "z6LSpSrLxbAhg2SHwKk7kwpsH7DM7QjFS5iK6qP87eViohud"
},
{
"id": "#key-2",
"type": "Ed25519VerificationKey2020",
"controller": "did:peer:2.Ez6LSpSrLxbAhg2SHwKk7kwpsH7DM7QjFS5iK6qP87eViohud.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V",
"publicKeyMultibase": "z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V"
}
],
"authentication": ["#key-2"],
"assertionMethod": [],
"keyAgreement": ["#key-1"],
"capabilityInvocation": [],
"capabilityDelegation": []
}
"##;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/tests/fixtures/mod.rs | did_core/did_methods/did_peer/tests/fixtures/mod.rs | #![allow(dead_code)]
pub mod basic;
pub mod multiple_services;
pub mod no_routing_keys;
pub mod no_services;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/tests/fixtures/basic.rs | did_core/did_methods/did_peer/tests/fixtures/basic.rs | pub static PEER_DID_NUMALGO_2_BASIC: &str = "did:peer:2\
.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc\
.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V\
.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg\
.SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXSwiYSI6WyJkaWRjb21tL3YyIiwiZGlkY29tbS9haXAyO2Vudj1yZmM1ODciXX0";
pub static PEER_DID_NUMALGO_3_BASIC: &str =
"did:peer:3zQmaTbkb2T8CbKPzXSCgsdWHxgX3qvjmpmTQwfATu3crFCv";
pub static DID_DOC_BASIC: &str = r##"
{
"id": "did:peer:2.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg.SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXSwiYSI6WyJkaWRjb21tL3YyIiwiZGlkY29tbS9haXAyO2Vudj1yZmM1ODciXX0",
"alsoKnownAs": ["did:peer:3zQmaTbkb2T8CbKPzXSCgsdWHxgX3qvjmpmTQwfATu3crFCv"],
"verificationMethod": [
{
"id": "#key-1",
"type": "X25519KeyAgreementKey2020",
"controller": "did:peer:2.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg.SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXSwiYSI6WyJkaWRjb21tL3YyIiwiZGlkY29tbS9haXAyO2Vudj1yZmM1ODciXX0",
"publicKeyBase58": "JhNWeSVLMYccCk7iopQW4guaSJTojqpMEELgSLhKwRr"
},
{
"id": "#key-2",
"type": "Ed25519VerificationKey2020",
"controller": "did:peer:2.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg.SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXSwiYSI6WyJkaWRjb21tL3YyIiwiZGlkY29tbS9haXAyO2Vudj1yZmM1ODciXX0",
"publicKeyBase58": "ByHnpUCFb1vAfh9CFZ8ZkmUZguURW8nSw889hy6rD8L7"
},
{
"id": "#key-3",
"type": "Ed25519VerificationKey2020",
"controller": "did:peer:2.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg.SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCIsInIiOlsiZGlkOmV4YW1wbGU6c29tZW1lZGlhdG9yI3NvbWVrZXkiXSwiYSI6WyJkaWRjb21tL3YyIiwiZGlkY29tbS9haXAyO2Vudj1yZmM1ODciXX0",
"publicKeyBase58": "3M5RCDjPTWPkKSN3sxUmmMqHbmRPegYP1tjcKyrDbt9J"
}
],
"authentication": ["#key-2", "#key-3"],
"assertionMethod": [],
"keyAgreement": ["#key-1"],
"capabilityInvocation": [],
"capabilityDelegation": [],
"service": [
{
"id": "#service-0",
"type": "DIDCommMessaging",
"serviceEndpoint": "https://example.com/endpoint",
"routingKeys": ["did:example:somemediator#somekey"],
"accept": ["didcomm/v2", "didcomm/aip2;env=rfc587"]
}
]
}
"##;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/tests/fixtures/multiple_services.rs | did_core/did_methods/did_peer/tests/fixtures/multiple_services.rs | pub static PEER_DID_NUMALGO_2_MULTIPLE_SERVICES: &str = "did:peer:2\
.Ez6LSpSrLxbAhg2SHwKk7kwpsH7DM7QjFS5iK6qP87eViohud\
.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V\
.SW3sidCI6ImRtIiwicyI6Imh0dHBzOi8vZXhhbXBsZS5jb20vZW5kcG9pbnQiLCJyIjpbImRpZDpleGFtcGxlOnNvbWVtZWRpYXRvciNzb21la2V5Il19LHsidCI6ImV4YW1wbGUiLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludDIiLCJyIjpbImRpZDpleGFtcGxlOnNvbWVtZWRpYXRvciNzb21la2V5MiJdLCJhIjpbImRpZGNvbW0vdjIiLCJkaWRjb21tL2FpcDI7ZW52PXJmYzU4NyJdfV0";
pub static PEER_DID_NUMALGO_3_MULTIPLE_SERVICES: &str =
"did:peer:3.345007dfdd2caa52be111e303342350e07233ee5f255f916f413ddafb098395a";
pub static DID_DOC_MULTIPLE_SERVICES: &str = r##"
{
"id": "did:peer:2.Ez6LSpSrLxbAhg2SHwKk7kwpsH7DM7QjFS5iK6qP87eViohud.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.SW3sidCI6ImRtIiwicyI6Imh0dHBzOi8vZXhhbXBsZS5jb20vZW5kcG9pbnQiLCJyIjpbImRpZDpleGFtcGxlOnNvbWVtZWRpYXRvciNzb21la2V5Il19LHsidCI6ImV4YW1wbGUiLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludDIiLCJyIjpbImRpZDpleGFtcGxlOnNvbWVtZWRpYXRvciNzb21la2V5MiJdLCJhIjpbImRpZGNvbW0vdjIiLCJkaWRjb21tL2FpcDI7ZW52PXJmYzU4NyJdfV0",
"alsoKnownAs": ["did:peer:3.345007dfdd2caa52be111e303342350e07233ee5f255f916f413ddafb098395a"],
"verificationMethod": [
{
"id": "#6MkqRYqQ",
"type": "Ed25519VerificationKey2020",
"controller": "did:peer:2.Ez6LSpSrLxbAhg2SHwKk7kwpsH7DM7QjFS5iK6qP87eViohud.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.SW3sidCI6ImRtIiwicyI6Imh0dHBzOi8vZXhhbXBsZS5jb20vZW5kcG9pbnQiLCJyIjpbImRpZDpleGFtcGxlOnNvbWVtZWRpYXRvciNzb21la2V5Il19LHsidCI6ImV4YW1wbGUiLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludDIiLCJyIjpbImRpZDpleGFtcGxlOnNvbWVtZWRpYXRvciNzb21la2V5MiJdLCJhIjpbImRpZGNvbW0vdjIiLCJkaWRjb21tL2FpcDI7ZW52PXJmYzU4NyJdfV0",
"publicKeyMultibase": "z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V"
}
],
"authentication": [],
"assertionMethod": [],
"keyAgreement": [
{
"id": "#6LSpSrLx",
"type": "X25519KeyAgreementKey2020",
"controller": "did:peer:2.Ez6LSpSrLxbAhg2SHwKk7kwpsH7DM7QjFS5iK6qP87eViohud.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.SW3sidCI6ImRtIiwicyI6Imh0dHBzOi8vZXhhbXBsZS5jb20vZW5kcG9pbnQiLCJyIjpbImRpZDpleGFtcGxlOnNvbWVtZWRpYXRvciNzb21la2V5Il19LHsidCI6ImV4YW1wbGUiLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludDIiLCJyIjpbImRpZDpleGFtcGxlOnNvbWVtZWRpYXRvciNzb21la2V5MiJdLCJhIjpbImRpZGNvbW0vdjIiLCJkaWRjb21tL2FpcDI7ZW52PXJmYzU4NyJdfV0",
"publicKeyMultibase": "z6LSpSrLxbAhg2SHwKk7kwpsH7DM7QjFS5iK6qP87eViohud"
}
],
"capabilityInvocation": [],
"capabilityDelegation": [],
"service": [
{
"id": "#didcommmessaging-0",
"type": "DIDCommMessaging",
"serviceEndpoint": "https://example.com/endpoint",
"routingKeys": ["did:example:somemediator#somekey"]
},
{
"id": "#example-1",
"type": "example",
"serviceEndpoint": "https://example.com/endpoint2",
"accept": ["didcomm/v2", "didcomm/aip2;env=rfc587"],
"routingKeys": ["did:example:somemediator#somekey2"]
}
]
}
"##;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/tests/fixtures/no_routing_keys.rs | did_core/did_methods/did_peer/tests/fixtures/no_routing_keys.rs | pub static PEER_DID_NUMALGO_2_NO_ROUTING_KEYS: &str =
"did:peer:2.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc.\
Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.\
Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg.\
SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCJ9";
pub static PEER_DID_NUMALGO_3_NO_ROUTING_KEYS: &str =
"did:peer:3zQmVKBM36ZvoTCEecoNWAmLvDcePbksQ2Ag2pxyGa24eUp8";
pub static DID_DOC_NO_ROUTING_KEYS: &str = r##"
{
"id": "did:peer:2.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg.SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCJ9",
"alsoKnownAs": ["did:peer:3zQmVKBM36ZvoTCEecoNWAmLvDcePbksQ2Ag2pxyGa24eUp8"],
"verificationMethod": [
{
"id": "#key-1",
"type": "X25519KeyAgreementKey2020",
"controller": "did:peer:2.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg.SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCJ9",
"publicKeyMultibase": "z6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc"
},
{
"id": "#key-2",
"type": "Ed25519VerificationKey2020",
"controller": "did:peer:2.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg.SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCJ9",
"publicKeyMultibase": "z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V"
},
{
"id": "#key-3",
"type": "Ed25519VerificationKey2020",
"controller": "did:peer:2.Ez6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc.Vz6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V.Vz6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg.SeyJpZCI6IiNzZXJ2aWNlLTAiLCJ0IjoiZG0iLCJzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9lbmRwb2ludCJ9",
"publicKeyMultibase": "z6MkgoLTnTypo3tDRwCkZXSccTPHRLhF4ZnjhueYAFpEX6vg"
}
],
"authentication": ["#key-2", "#key-3"],
"assertionMethod": [],
"keyAgreement": ["#key-1"],
"capabilityInvocation": [],
"capabilityDelegation": [],
"service": [
{
"id": "#service-0",
"type": "DIDCommMessaging",
"serviceEndpoint": "https://example.com/endpoint"
}
]
}
"##;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_peer/examples/demo.rs | did_core/did_methods/did_peer/examples/demo.rs | use std::{collections::HashMap, error::Error};
use did_doc::schema::{
did_doc::DidDocument,
service::{typed::ServiceType, Service},
types::uri::Uri,
utils::OneOrList,
verification_method::{PublicKeyField, VerificationMethod, VerificationMethodType},
};
use did_parser_nom::{Did, DidUrl};
use did_peer::{
peer_did::{
numalgos::{
numalgo2::Numalgo2,
numalgo3::Numalgo3,
numalgo4::{construction_did_doc::DidPeer4ConstructionDidDocument, Numalgo4},
},
PeerDid,
},
resolver::{options::PublicKeyEncoding, PeerDidResolutionOptions, PeerDidResolver},
};
use did_resolver::traits::resolvable::{resolution_output::DidResolutionOutput, DidResolvable};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn Error>> {
demo().await
}
async fn demo_did_peer_2_and_3() -> Result<(), Box<dyn Error>> {
let did_url = DidUrl::parse("did:foo:bar#key-1".into())?;
let did = Did::parse("did:foo:bar".into())?;
let verification_method = VerificationMethod::builder()
.id(did_url)
.controller(did.clone())
.verification_method_type(VerificationMethodType::Ed25519VerificationKey2018)
.public_key(PublicKeyField::Base64 {
public_key_base64: "Zm9vYmFyCg".to_string(),
})
.build();
let mut did_doc = DidDocument::new(did);
did_doc.add_verification_method(verification_method);
log::info!(
"Did document: \n{}",
serde_json::to_string_pretty(&did_doc)?
);
let peer_did_2 = PeerDid::<Numalgo2>::from_did_doc(did_doc.clone())?;
log::info!("as did:peer numalgo(2): {peer_did_2}");
let peer_did_3 = PeerDid::<Numalgo3>::from_did_doc(did_doc)?;
log::info!("as did:peer numalgo(3): {peer_did_3}");
let peer_did_3_v2 = peer_did_2.to_numalgo3()?;
log::info!("as did:peer numalgo(2) converted to numalgo(3): {peer_did_3_v2}");
let DidResolutionOutput { did_document, .. } = PeerDidResolver::new()
.resolve(
peer_did_2.did(),
&PeerDidResolutionOptions {
encoding: Some(PublicKeyEncoding::Base58),
},
)
.await
.unwrap();
log::info!(
"Decoded did document: \n{}",
serde_json::to_string_pretty(&did_document)?
);
Ok(())
}
async fn demo_did_peer_4() -> Result<(), Box<dyn Error>> {
let service = Service::new(
Uri::new("#service-0").unwrap(),
"https://example.com/endpoint".parse().unwrap(),
OneOrList::One(ServiceType::DIDCommV2),
HashMap::default(),
);
let mut construction_did_doc = DidPeer4ConstructionDidDocument::new();
construction_did_doc.add_service(service);
log::info!(
"Pseudo did document as input for did:peer:4 construction: {}",
serde_json::to_string_pretty(&construction_did_doc)?
);
let peer_did_4 = PeerDid::<Numalgo4>::new(construction_did_doc)?;
log::info!("Instance of peer did: {peer_did_4}");
let did_document = peer_did_4.resolve_did_doc()?;
log::info!(
"Resolved did document: {}",
serde_json::to_string_pretty(&did_document)?
);
Ok(())
}
async fn demo() -> Result<(), Box<dyn Error>> {
let env = env_logger::Env::default().default_filter_or("info");
env_logger::init_from_env(env);
demo_did_peer_2_and_3().await?;
demo_did_peer_4().await?;
Ok(())
}
#[tokio::test]
async fn demo_test() -> Result<(), Box<dyn Error>> {
demo().await
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/lib.rs | did_core/did_resolver/src/lib.rs | pub extern crate did_doc;
pub extern crate did_parser_nom;
pub mod error;
pub mod shared_types;
pub mod traits;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/error.rs | did_core/did_resolver/src/error.rs | use std::error::Error;
pub type GenericError = Box<dyn Error + Send + Sync + 'static>;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/shared_types/media_type.rs | did_core/did_resolver/src/shared_types/media_type.rs | use std::fmt::{self, Display, Formatter};
use serde::Deserialize;
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub enum MediaType {
DidJson,
DidLdJson,
}
impl Display for MediaType {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
MediaType::DidJson => write!(f, "application/did+json"),
MediaType::DidLdJson => write!(f, "application/did+ld+json"),
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/shared_types/did_document_metadata.rs | did_core/did_resolver/src/shared_types/did_document_metadata.rs | use std::collections::HashSet;
use chrono::{DateTime, Utc};
use did_parser_nom::Did;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
#[serde(default)]
#[serde(rename_all = "camelCase")]
pub struct DidDocumentMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
created: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
updated: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
deactivated: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
next_update: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
version_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
next_version_id: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
equivalent_id: Vec<Did>,
#[serde(skip_serializing_if = "Option::is_none")]
canonical_id: Option<Did>,
}
impl DidDocumentMetadata {
pub fn builder() -> DidDocumentMetadataBuilder {
DidDocumentMetadataBuilder::default()
}
pub fn created(&self) -> Option<DateTime<Utc>> {
self.created
}
pub fn updated(&self) -> Option<DateTime<Utc>> {
self.updated
}
pub fn deactivated(&self) -> Option<bool> {
self.deactivated
}
pub fn next_update(&self) -> Option<DateTime<Utc>> {
self.next_update
}
pub fn version_id(&self) -> Option<&String> {
self.version_id.as_ref()
}
pub fn next_version_id(&self) -> Option<&String> {
self.next_version_id.as_ref()
}
pub fn equivalent_id(&self) -> &[Did] {
self.equivalent_id.as_ref()
}
pub fn canonical_id(&self) -> Option<&Did> {
self.canonical_id.as_ref()
}
}
#[derive(Default)]
pub struct DidDocumentMetadataBuilder {
created: Option<DateTime<Utc>>,
updated: Option<DateTime<Utc>>,
deactivated: Option<bool>,
next_update: Option<DateTime<Utc>>,
version_id: Option<String>,
next_version_id: Option<String>,
equivalent_id: HashSet<Did>,
canonical_id: Option<Did>,
}
impl DidDocumentMetadataBuilder {
pub fn created(mut self, created: DateTime<Utc>) -> Self {
self.created = Some(created);
self
}
pub fn updated(mut self, updated: DateTime<Utc>) -> Self {
self.updated = Some(updated);
self
}
pub fn deactivated(mut self, deactivated: bool) -> Self {
self.deactivated = Some(deactivated);
self
}
pub fn next_update(mut self, next_update: DateTime<Utc>) -> Self {
self.next_update = Some(next_update);
self
}
pub fn version_id(mut self, version_id: String) -> Self {
self.version_id = Some(version_id);
self
}
pub fn next_version_id(mut self, next_version_id: String) -> Self {
self.next_version_id = Some(next_version_id);
self
}
pub fn add_equivalent_id(mut self, equivalent_id: Did) -> Self {
self.equivalent_id.insert(equivalent_id);
self
}
pub fn canonical_id(mut self, canonical_id: Did) -> Self {
self.canonical_id = Some(canonical_id);
self
}
pub fn build(self) -> DidDocumentMetadata {
DidDocumentMetadata {
created: self.created,
updated: self.updated,
deactivated: self.deactivated,
next_update: self.next_update,
version_id: self.version_id,
next_version_id: self.next_version_id,
equivalent_id: self.equivalent_id.into_iter().collect(),
canonical_id: self.canonical_id,
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/shared_types/did_resource.rs | did_core/did_resolver/src/shared_types/did_resource.rs | use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use typed_builder::TypedBuilder;
/// https://w3c-ccg.github.io/DID-Linked-Resources/
#[derive(Clone, Debug, PartialEq, Default)]
pub struct DidResource {
pub content: Vec<u8>,
pub metadata: DidResourceMetadata,
}
/// https://w3c-ccg.github.io/DID-Linked-Resources/
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default, TypedBuilder)]
#[serde(default)]
#[serde(rename_all = "camelCase")]
pub struct DidResourceMetadata {
// FUTURE - could be a map according to spec
/// A string or a map that conforms to the rules of RFC3986 URIs which SHOULD directly lead to
/// a location where the resource can be accessed.
/// For example:
/// did:example:46e2af9a-2ea0-4815-999d-730a6778227c/resources/
/// 0f964a80-5d18-4867-83e3-b47f5a756f02.
pub resource_uri: String,
/// A string that conforms to a method-specific supported unique identifier format.
/// For example, a UUID: 46e2af9a-2ea0-4815-999d-730a6778227c.
pub resource_collection_id: String,
/// A string that uniquely identifies the resource.
/// For example, a UUID: 0f964a80-5d18-4867-83e3-b47f5a756f02.
pub resource_id: String,
/// A string that uniquely names and identifies a resource. This property, along with the
/// resourceType below, can be used to track version changes within a resource.
pub resource_name: String,
/// A string that identifies the type of resource. This property, along with the resourceName
/// above, can be used to track version changes within a resource. Not to be confused with
/// mediaType.
pub resource_type: String,
/// (Optional) A string that identifies the version of the resource.
/// This property is provided by the client and can be any value.
#[serde(skip_serializing_if = "Option::is_none")]
pub resource_version: Option<String>,
/// (Optional) An array that describes alternative URIs for the resource.
#[serde(skip_serializing_if = "Option::is_none")]
pub also_known_as: Option<Vec<Value>>,
/// A string that identifies the IANA-media type of the resource.
pub media_type: String,
/// A string that identifies the time the resource was created, as an XML date-time.
#[serde(with = "xml_datetime")]
pub created: DateTime<Utc>,
/// (Optional) A string that identifies the time the resource was updated, as an XML date-time.
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(with = "xml_datetime::optional")]
pub updated: Option<DateTime<Utc>>,
/// A string that may be used to prove that the resource has not been tampered with.
pub checksum: String,
/// (Optional) A string that identifies the previous version of the resource.
#[serde(skip_serializing_if = "Option::is_none")]
pub previous_version_id: Option<String>,
/// (Optional) A string that identifies the next version of the resource.
#[serde(skip_serializing_if = "Option::is_none")]
pub next_version_id: Option<String>,
}
/// Custom serialization module for XMLDateTime format.
/// Uses Z and removes subsecond precision
mod xml_datetime {
use chrono::{DateTime, SecondsFormat, Utc};
use serde::{self, Deserialize, Deserializer, Serializer};
pub fn serialize<S>(dt: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = dt.to_rfc3339_opts(SecondsFormat::Secs, true);
serializer.serialize_str(&s)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
s.parse::<DateTime<Utc>>().map_err(serde::de::Error::custom)
}
pub mod optional {
use chrono::{DateTime, Utc};
use serde::{self, Deserialize, Deserializer, Serializer};
pub fn serialize<S>(dt: &Option<DateTime<Utc>>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match dt {
Some(dt) => super::serialize(dt, serializer),
None => serializer.serialize_none(),
}
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<DateTime<Utc>>, D::Error>
where
D: Deserializer<'de>,
{
let s = Option::<String>::deserialize(deserializer)?;
match s {
Some(s) => {
let parsed = s
.parse::<DateTime<Utc>>()
.map_err(serde::de::Error::custom)?;
Ok(Some(parsed))
}
None => Ok(None),
}
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/shared_types/mod.rs | did_core/did_resolver/src/shared_types/mod.rs | pub mod did_document_metadata;
pub mod did_resource;
pub mod media_type;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/traits/mod.rs | did_core/did_resolver/src/traits/mod.rs | pub mod dereferenceable;
pub mod resolvable;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/traits/dereferenceable/dereferencing_output.rs | did_core/did_resolver/src/traits/dereferenceable/dereferencing_output.rs | use std::io::Read;
use super::dereferencing_metadata::DidDereferencingMetadata;
use crate::shared_types::did_document_metadata::DidDocumentMetadata;
pub struct DidDereferencingOutput<R: Read + Send + Sync> {
dereferencing_metadata: DidDereferencingMetadata,
content_stream: R,
content_metadata: DidDocumentMetadata,
}
impl<R> DidDereferencingOutput<R>
where
R: Read + Send + Sync,
{
pub fn builder(content_stream: R) -> DidDDereferencingOutputBuilder<R> {
DidDDereferencingOutputBuilder {
dereferencing_metadata: None,
content_stream,
content_metadata: None,
}
}
pub fn dereferencing_metadata(&self) -> &DidDereferencingMetadata {
&self.dereferencing_metadata
}
pub fn content_stream(&self) -> &R {
&self.content_stream
}
pub fn content_metadata(&self) -> &DidDocumentMetadata {
&self.content_metadata
}
}
pub struct DidDDereferencingOutputBuilder<R: Read + Send + Sync> {
dereferencing_metadata: Option<DidDereferencingMetadata>,
content_stream: R,
content_metadata: Option<DidDocumentMetadata>,
}
impl<R> DidDDereferencingOutputBuilder<R>
where
R: Read + Send + Sync,
{
pub fn dereferencing_metadata(
mut self,
dereferencing_metadata: DidDereferencingMetadata,
) -> Self {
self.dereferencing_metadata = Some(dereferencing_metadata);
self
}
pub fn content_metadata(mut self, content_metadata: DidDocumentMetadata) -> Self {
self.content_metadata = Some(content_metadata);
self
}
pub fn build(self) -> DidDereferencingOutput<R> {
DidDereferencingOutput {
dereferencing_metadata: self.dereferencing_metadata.unwrap_or_default(),
content_stream: self.content_stream,
content_metadata: self.content_metadata.unwrap_or_default(),
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/traits/dereferenceable/dereferencing_error.rs | did_core/did_resolver/src/traits/dereferenceable/dereferencing_error.rs | use std::{error::Error, fmt::Display};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum DidDereferencingError {
InvalidDid,
NotFound,
}
impl Display for DidDereferencingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DidDereferencingError::InvalidDid => write!(f, "invalidDid"),
DidDereferencingError::NotFound => write!(f, "notFound"),
}
}
}
impl Error for DidDereferencingError {}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/traits/dereferenceable/dereferencing_options.rs | did_core/did_resolver/src/traits/dereferenceable/dereferencing_options.rs | use crate::shared_types::media_type::MediaType;
#[derive(Debug, Clone, PartialEq, Default)]
pub struct DidDereferencingOptions {
accept: Option<MediaType>,
}
impl DidDereferencingOptions {
pub fn new() -> Self {
Self { accept: None }
}
pub fn set_accept(mut self, accept: MediaType) -> Self {
self.accept = Some(accept);
self
}
pub fn accept(&self) -> Option<&MediaType> {
self.accept.as_ref()
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/traits/dereferenceable/mod.rs | did_core/did_resolver/src/traits/dereferenceable/mod.rs | pub mod dereferencing_error;
pub mod dereferencing_metadata;
pub mod dereferencing_options;
pub mod dereferencing_output;
use std::io::Read;
use async_trait::async_trait;
use did_parser_nom::DidUrl;
use self::{
dereferencing_options::DidDereferencingOptions, dereferencing_output::DidDereferencingOutput,
};
use crate::{error::GenericError, traits::resolvable::DidResolvable};
#[async_trait]
pub trait DidDereferenceable: DidResolvable {
type Output: Read + Send + Sync;
async fn dereference(
&self,
did: &DidUrl,
options: &DidDereferencingOptions,
) -> Result<DidDereferencingOutput<Self::Output>, GenericError>;
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/traits/dereferenceable/dereferencing_metadata.rs | did_core/did_resolver/src/traits/dereferenceable/dereferencing_metadata.rs | use super::dereferencing_error::DidDereferencingError;
#[derive(Debug, Clone, PartialEq, Default)]
pub struct DidDereferencingMetadata {
content_type: Option<String>,
error: Option<DidDereferencingError>,
}
impl DidDereferencingMetadata {
pub fn builder() -> DidDereferencingMetadataBuilder {
DidDereferencingMetadataBuilder::default()
}
pub fn content_type(&self) -> Option<&String> {
self.content_type.as_ref()
}
pub fn error(&self) -> Option<&DidDereferencingError> {
self.error.as_ref()
}
}
#[derive(Default)]
pub struct DidDereferencingMetadataBuilder {
content_type: Option<String>,
error: Option<DidDereferencingError>,
}
impl DidDereferencingMetadataBuilder {
pub fn content_type(mut self, content_type: String) -> Self {
self.content_type = Some(content_type);
self
}
pub fn error(mut self, error: DidDereferencingError) -> Self {
self.error = Some(error);
self
}
pub fn build(self) -> DidDereferencingMetadata {
DidDereferencingMetadata {
content_type: self.content_type,
error: self.error,
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/traits/resolvable/resolution_error.rs | did_core/did_resolver/src/traits/resolvable/resolution_error.rs | use std::{error::Error, fmt::Display};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum DidResolutionError {
InvalidDid,
NotFound,
RepresentationNotSupported,
MethodNotSupported,
InternalError,
InvalidPublicKey,
InvalidPublicKeyLength,
InvalidPublicKeyType,
UnsupportedPublicKeyType,
NotAllowedVerificationMethodType,
NotAllowedKeyType,
NotAllowedMethod,
NotAllowedCertificate,
NotAllowedLocalDuplicateKey,
NotAllowedLocalDerivedKey,
NotAllowedGlobalDuplicateKey,
}
impl Display for DidResolutionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DidResolutionError::InvalidDid => write!(f, "invalidDid"),
DidResolutionError::NotFound => write!(f, "notFound"),
DidResolutionError::RepresentationNotSupported => {
write!(f, "representationNotSupported")
}
DidResolutionError::MethodNotSupported => write!(f, "methodNotSupported"),
DidResolutionError::InternalError => write!(f, "internalError"),
DidResolutionError::InvalidPublicKey => write!(f, "invalidPublicKey"),
DidResolutionError::InvalidPublicKeyLength => write!(f, "invalidPublicKeyLength"),
DidResolutionError::InvalidPublicKeyType => write!(f, "invalidPublicKeyType"),
DidResolutionError::UnsupportedPublicKeyType => {
write!(f, "unsupportedPublicKeyType")
}
DidResolutionError::NotAllowedVerificationMethodType => {
write!(f, "notAllowedVerificationMethodType")
}
DidResolutionError::NotAllowedKeyType => write!(f, "notAllowedKeyType"),
DidResolutionError::NotAllowedMethod => write!(f, "notAllowedMethod"),
DidResolutionError::NotAllowedCertificate => write!(f, "notAllowedCertificate"),
DidResolutionError::NotAllowedLocalDuplicateKey => {
write!(f, "notAllowedLocalDuplicateKey")
}
DidResolutionError::NotAllowedLocalDerivedKey => {
write!(f, "notAllowedLocalDerivedKey")
}
DidResolutionError::NotAllowedGlobalDuplicateKey => {
write!(f, "notAllowedGlobalDuplicateKey")
}
}
}
}
impl Error for DidResolutionError {}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/traits/resolvable/mod.rs | did_core/did_resolver/src/traits/resolvable/mod.rs | pub mod resolution_error;
pub mod resolution_metadata;
pub mod resolution_output;
use async_trait::async_trait;
use did_parser_nom::Did;
use self::resolution_output::DidResolutionOutput;
use crate::error::GenericError;
#[async_trait]
pub trait DidResolvable {
type DidResolutionOptions: Default;
async fn resolve(
&self,
did: &Did,
options: &Self::DidResolutionOptions,
) -> Result<DidResolutionOutput, GenericError>;
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/traits/resolvable/resolution_output.rs | did_core/did_resolver/src/traits/resolvable/resolution_output.rs | use did_doc::schema::did_doc::DidDocument;
use serde::{Deserialize, Serialize};
use super::resolution_metadata::DidResolutionMetadata;
use crate::shared_types::did_document_metadata::DidDocumentMetadata;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DidResolutionOutput {
pub did_document: DidDocument,
pub did_resolution_metadata: DidResolutionMetadata,
pub did_document_metadata: DidDocumentMetadata,
}
impl DidResolutionOutput {
pub fn builder(did_document: DidDocument) -> DidResolutionOutputBuilder {
DidResolutionOutputBuilder {
did_document,
did_resolution_metadata: None,
did_document_metadata: None,
}
}
}
pub struct DidResolutionOutputBuilder {
did_document: DidDocument,
did_resolution_metadata: Option<DidResolutionMetadata>,
did_document_metadata: Option<DidDocumentMetadata>,
}
impl DidResolutionOutputBuilder {
pub fn did_resolution_metadata(
mut self,
did_resolution_metadata: DidResolutionMetadata,
) -> Self {
self.did_resolution_metadata = Some(did_resolution_metadata);
self
}
pub fn did_document_metadata(mut self, did_document_metadata: DidDocumentMetadata) -> Self {
self.did_document_metadata = Some(did_document_metadata);
self
}
pub fn build(self) -> DidResolutionOutput {
DidResolutionOutput {
did_document: self.did_document,
did_resolution_metadata: self.did_resolution_metadata.unwrap_or_default(),
did_document_metadata: self.did_document_metadata.unwrap_or_default(),
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver/src/traits/resolvable/resolution_metadata.rs | did_core/did_resolver/src/traits/resolvable/resolution_metadata.rs | use serde::{Deserialize, Serialize};
use super::resolution_error::DidResolutionError;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
pub struct DidResolutionMetadata {
content_type: Option<String>,
error: Option<DidResolutionError>,
}
impl DidResolutionMetadata {
pub fn builder() -> DidResolutionMetadataBuilder {
DidResolutionMetadataBuilder::default()
}
pub fn content_type(&self) -> Option<&String> {
self.content_type.as_ref()
}
pub fn error(&self) -> Option<&DidResolutionError> {
self.error.as_ref()
}
}
#[derive(Default)]
pub struct DidResolutionMetadataBuilder {
content_type: Option<String>,
error: Option<DidResolutionError>,
}
impl DidResolutionMetadataBuilder {
pub fn content_type(mut self, content_type: String) -> Self {
self.content_type = Some(content_type);
self
}
pub fn error(mut self, error: DidResolutionError) -> Self {
self.error = Some(error);
self
}
pub fn build(self) -> DidResolutionMetadata {
DidResolutionMetadata {
content_type: self.content_type,
error: self.error,
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver_registry/src/lib.rs | did_core/did_resolver_registry/src/lib.rs | pub mod error;
use std::collections::HashMap;
use async_trait::async_trait;
use did_resolver::{
did_doc::schema::did_doc::DidDocument,
did_parser_nom::Did,
error::GenericError,
traits::resolvable::{resolution_output::DidResolutionOutput, DidResolvable},
};
use error::DidResolverRegistryError;
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub type GenericResolver = dyn DidResolvableAdaptorTrait + Send + Sync;
#[derive(Default)]
pub struct ResolverRegistry {
resolvers: HashMap<String, Box<GenericResolver>>,
}
pub struct DidResolvableAdaptor<T: DidResolvable> {
inner: T,
}
#[async_trait]
pub trait DidResolvableAdaptorTrait: Send + Sync {
async fn resolve(
&self,
did: &Did,
options: HashMap<String, Value>,
) -> Result<DidResolutionOutput, GenericError>;
}
#[async_trait]
impl<T: DidResolvable + Send + Sync> DidResolvableAdaptorTrait for DidResolvableAdaptor<T>
where
T::DidResolutionOptions: Send + Sync + Serialize + for<'de> Deserialize<'de>,
{
async fn resolve(
&self,
did: &Did,
options: HashMap<String, Value>,
) -> Result<DidResolutionOutput, GenericError> {
let options: T::DidResolutionOptions = if options.is_empty() {
Default::default()
} else {
let json_map = options.into_iter().collect();
serde_json::from_value(Value::Object(json_map))?
};
let result_inner = self.inner.resolve(did, &options).await?;
let did_document_inner_hashmap = serde_json::to_value(result_inner.did_document)
.unwrap()
.as_object()
.unwrap()
.clone();
let did_document: DidDocument =
serde_json::from_value(Value::Object(did_document_inner_hashmap))?;
Ok(DidResolutionOutput::builder(did_document)
.did_resolution_metadata(result_inner.did_resolution_metadata)
.did_document_metadata(result_inner.did_document_metadata)
.build())
}
}
impl ResolverRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn register_resolver<T>(mut self, method: String, resolver: T) -> Self
where
T: DidResolvable + 'static + Send + Sync,
for<'de> <T as DidResolvable>::DidResolutionOptions:
Send + Sync + Serialize + Deserialize<'de>,
{
let adaptor = DidResolvableAdaptor { inner: resolver };
self.resolvers.insert(method, Box::new(adaptor));
self
}
pub fn unregister_resolver(mut self, method: &str) -> Self {
self.resolvers.remove(method);
self
}
pub async fn resolve(
&self,
did: &Did,
options: &HashMap<String, Value>,
) -> Result<DidResolutionOutput, GenericError> {
let method = did
.method()
.ok_or(DidResolverRegistryError::UnsupportedMethod)?;
match self.resolvers.get(method) {
Some(resolver) => resolver.resolve(did, options.clone()).await,
None => Err(Box::new(DidResolverRegistryError::UnsupportedMethod)),
}
}
}
#[cfg(test)]
mod tests {
use std::{error::Error, pin::Pin};
use async_trait::async_trait;
use did_resolver::did_doc::schema::did_doc::DidDocument;
use mockall::automock;
use super::*;
#[allow(unused)] // false positive. used for automock
struct DummyDidResolver;
#[async_trait]
#[automock]
impl DidResolvable for DummyDidResolver {
type DidResolutionOptions = ();
async fn resolve(
&self,
did: &Did,
_options: &Self::DidResolutionOptions,
) -> Result<DidResolutionOutput, GenericError> {
Ok(DidResolutionOutput::builder(DidDocument::new(did.clone())).build())
}
}
#[derive(Debug)]
struct DummyResolverError;
impl std::fmt::Display for DummyResolverError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Dummy resolver error")
}
}
impl Error for DummyResolverError {}
#[tokio::test]
async fn test_resolve_error() {
let did = Did::parse("did:example:1234".to_string()).unwrap();
let method = did.method().unwrap().to_string();
let mut mock_resolver = MockDummyDidResolver::new();
mock_resolver
.expect_resolve()
// .with(eq(did.clone()), eq(DidResolutionOptions::default()))
.times(1)
.return_once(move |_, _| {
let future = async move {
Err::<DidResolutionOutput, GenericError>(Box::new(DummyResolverError))
};
Pin::from(Box::new(future))
});
let registry = ResolverRegistry::new()
.register_resolver::<MockDummyDidResolver>(method, mock_resolver);
let result = registry.resolve(&did, &HashMap::new()).await;
assert!(result.is_err());
let error = result.unwrap_err();
assert!(
error.downcast_ref::<DummyResolverError>().is_some(),
"Error is not of type DummyResolverError"
)
}
#[tokio::test]
async fn test_resolve_success() {
let did = "did:example:1234";
let parsed_did = Did::parse(did.to_string()).unwrap();
let parsed_did_cp = parsed_did.clone();
let method = parsed_did.method().unwrap().to_string();
let mut mock_resolver = MockDummyDidResolver::new();
mock_resolver
.expect_resolve()
// .with(eq(parsed_did.clone()), eq(DidResolutionOptions::default()))
.times(1)
.return_once(move |_, _| {
let future = async move {
Ok::<DidResolutionOutput, GenericError>(
DidResolutionOutput::builder(DidDocument::new(parsed_did_cp)).build(),
)
};
Pin::from(Box::new(future))
});
let registry = ResolverRegistry::new()
.register_resolver::<MockDummyDidResolver>(method, mock_resolver);
let result = registry.resolve(&parsed_did, &HashMap::new()).await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_register_and_unregister_resolver() {
let method = "example".to_string();
let mock_resolver = MockDummyDidResolver::new();
let mut registry = ResolverRegistry::new();
assert_eq!(registry.resolvers.len(), 0);
registry =
registry.register_resolver::<MockDummyDidResolver>(method.clone(), mock_resolver);
assert_eq!(registry.resolvers.len(), 1);
assert!(registry.resolvers.contains_key(&method));
registry = registry.unregister_resolver(&method);
assert_eq!(registry.resolvers.len(), 0);
assert!(!registry.resolvers.contains_key(&method));
}
#[tokio::test]
async fn test_resolve_unsupported_method() {
let did = Did::parse("did:unknown:1234".to_string()).unwrap();
let registry = ResolverRegistry::new();
let result = registry.resolve(&did, &HashMap::new()).await;
assert!(result.is_err());
let error = result.unwrap_err();
assert!(
matches!(
error.downcast_ref::<DidResolverRegistryError>(),
Some(DidResolverRegistryError::UnsupportedMethod)
),
"Error is not of type DidResolverRegistryError"
);
}
#[tokio::test]
async fn test_resolve_after_registering_resolver() {
let did = "did:example:1234";
let parsed_did = Did::parse(did.to_string()).unwrap();
let parsed_did_cp = parsed_did.clone();
let method = parsed_did.method().unwrap().to_string();
let mut mock_resolver = MockDummyDidResolver::new();
mock_resolver
.expect_resolve()
// .with(eq(parsed_did.clone()), eq(DidResolutionOptions::default()))
.times(1)
.return_once(move |_, _| {
let future = async move {
Ok::<DidResolutionOutput, GenericError>(
DidResolutionOutput::builder(DidDocument::new(parsed_did_cp)).build(),
)
};
Pin::from(Box::new(future))
});
let mut registry = ResolverRegistry::new();
let result_before = registry.resolve(&parsed_did, &HashMap::new()).await;
assert!(result_before.is_err());
let error_before = result_before.unwrap_err();
assert!(
matches!(
error_before.downcast_ref::<DidResolverRegistryError>(),
Some(DidResolverRegistryError::UnsupportedMethod)
),
"Error is not of type DidResolverRegistryError"
);
registry = registry.register_resolver::<MockDummyDidResolver>(method, mock_resolver);
let result_after = registry.resolve(&parsed_did, &HashMap::new()).await;
assert!(result_after.is_ok());
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_resolver_registry/src/error.rs | did_core/did_resolver_registry/src/error.rs | use std::error::Error;
#[derive(Debug)]
pub enum DidResolverRegistryError {
UnsupportedMethod,
UnqualifiedDid,
}
impl std::fmt::Display for DidResolverRegistryError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
DidResolverRegistryError::UnsupportedMethod => write!(f, "Unsupported DID method"),
DidResolverRegistryError::UnqualifiedDid => {
write!(f, "Attempted to resolve unqualified DID")
}
}
}
}
impl Error for DidResolverRegistryError {}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/public_key/src/key.rs | did_core/public_key/src/key.rs | use std::fmt::Display;
use serde::{Deserialize, Serialize};
use super::KeyType;
use crate::error::PublicKeyError;
/// Represents raw public key data along with information about the key type
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Key {
key_type: KeyType,
key: Vec<u8>,
}
impl Key {
pub fn new(key: Vec<u8>, key_type: KeyType) -> Result<Self, PublicKeyError> {
// If the key is a multibase key coming from a verification method, for some reason it is
// also multicodec encoded, so we need to strip that. But should it be?
let key = Self::strip_multicodec_prefix_if_present(key, &key_type);
Ok(Self { key_type, key })
}
pub fn key_type(&self) -> &KeyType {
&self.key_type
}
pub fn validate_key_type(&self, key_type: KeyType) -> Result<&Self, PublicKeyError> {
if self.key_type() != &key_type {
return Err(PublicKeyError::InvalidKeyType(
self.key_type().to_owned(),
key_type,
));
}
Ok(self)
}
pub fn key(&self) -> &[u8] {
self.key.as_ref()
}
pub fn multicodec_prefixed_key(&self) -> Vec<u8> {
let code = self.key_type().into();
let mut buffer = [0u8; 10];
let bytes = unsigned_varint::encode::u64(code, &mut buffer);
let mut prefixed_key = bytes.to_vec();
prefixed_key.extend_from_slice(&self.key);
prefixed_key
}
pub fn fingerprint(&self) -> String {
multibase::encode(multibase::Base::Base58Btc, self.multicodec_prefixed_key())
}
pub fn prefixless_fingerprint(&self) -> String {
self.fingerprint().trim_start_matches('z').to_string()
}
pub fn base58(&self) -> String {
bs58::encode(&self.key).into_string()
}
pub fn multibase58(&self) -> String {
multibase::encode(multibase::Base::Base58Btc, &self.key)
}
pub fn from_fingerprint(fingerprint: &str) -> Result<Self, PublicKeyError> {
let (_base, decoded_bytes) = multibase::decode(fingerprint)?;
let (code, remaining_bytes) = unsigned_varint::decode::u64(&decoded_bytes)?;
Ok(Self {
key_type: code.try_into()?,
key: remaining_bytes.to_vec(),
})
}
pub fn from_base58(base58: &str, key_type: KeyType) -> Result<Self, PublicKeyError> {
let decoded_bytes = bs58::decode(base58).into_vec()?;
Ok(Self {
key_type,
key: decoded_bytes,
})
}
pub fn short_prefixless_fingerprint(&self) -> String {
self.prefixless_fingerprint()
.chars()
.take(8)
.collect::<String>()
}
fn strip_multicodec_prefix_if_present(key: Vec<u8>, key_type: &KeyType) -> Vec<u8> {
if let Ok((value, remaining)) = unsigned_varint::decode::u64(&key) {
if value == Into::<u64>::into(key_type) {
remaining.to_vec()
} else {
key
}
} else {
key
}
}
}
impl Display for Key {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.base58())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn new_key_test(key_bytes: Vec<u8>, key_type: KeyType) {
let key = Key::new(key_bytes.clone(), key_type);
assert!(key.is_ok());
let key = key.unwrap();
assert_eq!(key.key_type(), &key_type);
assert_eq!(key.key(), key_bytes.as_slice());
}
fn prefixed_key_test(
key_bytes: Vec<u8>,
key_type: KeyType,
expected_prefixed_key: String,
encode_fn: fn(Vec<u8>) -> String,
) {
let key = Key::new(key_bytes, key_type).unwrap();
let prefixed_key = key.multicodec_prefixed_key();
assert_eq!(expected_prefixed_key, encode_fn(prefixed_key),);
}
fn fingerprint_test(key_bytes: Vec<u8>, key_type: KeyType, expected_fingerprint: &str) {
let key = Key::new(key_bytes, key_type).unwrap();
let fingerprint = key.fingerprint();
assert_eq!(fingerprint, expected_fingerprint);
}
fn base58_test(key_bytes: Vec<u8>, key_type: KeyType, expected_base58: &str) {
let key = Key::new(key_bytes, key_type).unwrap();
let base58 = key.base58();
assert_eq!(base58, expected_base58);
}
fn from_fingerprint_test(key_bytes: Vec<u8>, key_type: KeyType, fingerprint: &str) {
let key = Key::new(key_bytes, key_type).unwrap();
let key_from_fingerprint = Key::from_fingerprint(fingerprint);
assert!(key_from_fingerprint.is_ok());
let key_from_fingerprint = key_from_fingerprint.unwrap();
assert_eq!(key.key_type(), key_from_fingerprint.key_type());
assert_eq!(key.key(), key_from_fingerprint.key());
assert_eq!(
key.multicodec_prefixed_key(),
key_from_fingerprint.multicodec_prefixed_key()
);
assert_eq!(key.fingerprint(), fingerprint);
assert_eq!(key_from_fingerprint.fingerprint(), fingerprint);
}
fn strip_multicodec_prefix_if_present_test(key_bytes: Vec<u8>, key_type: &KeyType) {
let key_type_u64: u64 = key_type.into();
let mut buffer = [0u8; 10];
let key_type_bytes = unsigned_varint::encode::u64(key_type_u64, &mut buffer);
let mut prefixed_key = key_type_bytes.to_vec();
prefixed_key.extend_from_slice(&key_bytes);
let (_, remaining_bytes) = unsigned_varint::decode::u64(&prefixed_key).unwrap();
let manually_stripped_key = remaining_bytes.to_vec();
let function_stripped_key = Key::strip_multicodec_prefix_if_present(prefixed_key, key_type);
assert_eq!(function_stripped_key, manually_stripped_key);
let no_prefix_stripped_key =
Key::strip_multicodec_prefix_if_present(key_bytes.clone(), key_type);
assert_eq!(no_prefix_stripped_key, key_bytes);
}
#[test]
fn from_fingerprint_error_test() {
let key = Key::from_fingerprint("this is not a valid fingerprint");
assert!(key.is_err());
}
mod ed25519 {
use super::*;
const TEST_KEY_BASE58: &str = "8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K";
const TEST_FINGERPRINT: &str = "z6MkmjY8GnV5i9YTDtPETC2uUAW6ejw3nk5mXF5yci5ab7th";
fn key_bytes() -> Vec<u8> {
bs58::decode(TEST_KEY_BASE58).into_vec().unwrap()
}
fn encode_multibase(key_bytes: Vec<u8>) -> String {
multibase::encode(multibase::Base::Base58Btc, key_bytes)
}
#[test]
fn new_key_test() {
super::new_key_test(key_bytes(), KeyType::Ed25519);
}
#[test]
fn prefixed_key_test() {
super::prefixed_key_test(
key_bytes(),
KeyType::Ed25519,
TEST_FINGERPRINT.to_string(),
encode_multibase,
);
}
#[test]
fn fingerprint_test() {
super::fingerprint_test(key_bytes(), KeyType::Ed25519, TEST_FINGERPRINT);
}
#[test]
fn base58_test() {
super::base58_test(key_bytes(), KeyType::Ed25519, TEST_KEY_BASE58);
}
#[test]
fn from_fingerprint_test() {
super::from_fingerprint_test(key_bytes(), KeyType::Ed25519, TEST_FINGERPRINT);
}
#[test]
fn strip_multicodec_prefix_if_present_test() {
super::strip_multicodec_prefix_if_present_test(key_bytes(), &KeyType::Ed25519);
}
}
mod x25519 {
use super::*;
const TEST_KEY_BASE58: &str = "6fUMuABnqSDsaGKojbUF3P7ZkEL3wi2njsDdUWZGNgCU";
const TEST_FINGERPRINT: &str = "z6LShLeXRTzevtwcfehaGEzCMyL3bNsAeKCwcqwJxyCo63yE";
fn key_bytes() -> Vec<u8> {
bs58::decode(TEST_KEY_BASE58).into_vec().unwrap()
}
fn encode_multibase(key_bytes: Vec<u8>) -> String {
multibase::encode(multibase::Base::Base58Btc, key_bytes)
}
#[test]
fn new_key_test() {
super::new_key_test(key_bytes(), KeyType::X25519);
}
#[test]
fn prefixed_key_test() {
super::prefixed_key_test(
key_bytes(),
KeyType::X25519,
TEST_FINGERPRINT.to_string(),
encode_multibase,
);
}
#[test]
fn fingerprint_test() {
super::fingerprint_test(key_bytes(), KeyType::X25519, TEST_FINGERPRINT);
}
#[test]
fn base58_test() {
super::base58_test(key_bytes(), KeyType::X25519, TEST_KEY_BASE58);
}
#[test]
fn from_fingerprint_test() {
super::from_fingerprint_test(key_bytes(), KeyType::X25519, TEST_FINGERPRINT);
}
#[test]
fn strip_multicodec_prefix_if_present_test() {
super::strip_multicodec_prefix_if_present_test(key_bytes(), &KeyType::X25519);
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/public_key/src/lib.rs | did_core/public_key/src/lib.rs | mod error;
#[cfg(feature = "jwk")]
mod jwk;
mod key;
mod key_type;
pub use error::PublicKeyError;
pub use key::Key;
pub use key_type::KeyType;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/public_key/src/jwk.rs | did_core/public_key/src/jwk.rs | use askar_crypto::{
alg::{AnyKey, AnyKeyCreate, BlsCurves, EcCurves, KeyAlg},
jwk::{FromJwk, ToJwk},
repr::ToPublicBytes,
};
use crate::{Key, KeyType, PublicKeyError};
impl Key {
pub fn from_jwk(jwk: &str) -> Result<Key, PublicKeyError> {
let askar_key: Box<AnyKey> =
FromJwk::from_jwk(jwk).map_err(|e| PublicKeyError::JwkDecodingError(Box::new(e)))?;
let askar_alg = askar_key.algorithm();
let pub_key_bytes = askar_key
.to_public_bytes()
.map_err(|e| PublicKeyError::JwkDecodingError(Box::new(e)))?
.to_vec();
let key_type = match askar_alg {
askar_crypto::alg::KeyAlg::Ed25519 => KeyType::Ed25519,
askar_crypto::alg::KeyAlg::Bls12_381(BlsCurves::G1) => KeyType::Bls12381g1,
askar_crypto::alg::KeyAlg::Bls12_381(BlsCurves::G2) => KeyType::Bls12381g2,
askar_crypto::alg::KeyAlg::X25519 => KeyType::X25519,
askar_crypto::alg::KeyAlg::EcCurve(EcCurves::Secp256r1) => KeyType::P256,
askar_crypto::alg::KeyAlg::EcCurve(EcCurves::Secp384r1) => KeyType::P384,
_ => return Err(PublicKeyError::UnsupportedKeyType(askar_alg.to_string())),
};
Key::new(pub_key_bytes, key_type)
}
pub fn to_jwk(&self) -> Result<String, PublicKeyError> {
let askar_key = self.to_askar_local_key()?;
askar_key.to_jwk_public(None).map_err(|e| {
PublicKeyError::UnsupportedKeyType(format!("Could not process this key as JWK {e:?}"))
})
}
fn to_askar_local_key(&self) -> Result<Box<AnyKey>, PublicKeyError> {
let alg = public_key_type_to_askar_key_alg(self.key_type())?;
AnyKeyCreate::from_public_bytes(alg, self.key()).map_err(|e| {
PublicKeyError::UnsupportedKeyType(format!("Could not process key type {alg:?}: {e:?}"))
})
}
}
pub fn public_key_type_to_askar_key_alg(value: &KeyType) -> Result<KeyAlg, PublicKeyError> {
let alg = match value {
KeyType::Ed25519 => KeyAlg::Ed25519,
KeyType::X25519 => KeyAlg::X25519,
KeyType::Bls12381g1 => KeyAlg::Bls12_381(BlsCurves::G1),
KeyType::Bls12381g2 => KeyAlg::Bls12_381(BlsCurves::G2),
KeyType::P256 => KeyAlg::EcCurve(EcCurves::Secp256r1),
KeyType::P384 => KeyAlg::EcCurve(EcCurves::Secp384r1),
other => {
return Err(PublicKeyError::UnsupportedKeyType(format!(
"Unsupported key type: {other:?}"
)));
}
};
Ok(alg)
}
#[cfg(test)]
mod tests {
use serde_json::Value;
use super::*;
// vector from https://w3c-ccg.github.io/did-method-key/#ed25519-x25519
const ED25519_JWK: &str = r#"{
"kty": "OKP",
"crv": "Ed25519",
"x": "O2onvM62pC1io6jQKm8Nc2UyFXcd4kOmOsBIoYtZ2ik"
}"#;
const ED25519_FINGERPRINT: &str = "z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp";
// vector from https://w3c-ccg.github.io/did-method-key/#ed25519-x25519
const X25519_JWK: &str = r#"{
"kty": "OKP",
"crv": "X25519",
"x": "W_Vcc7guviK-gPNDBmevVw-uJVamQV5rMNQGUwCqlH0"
}"#;
const X25519_FINGERPRINT: &str = "z6LShs9GGnqk85isEBzzshkuVWrVKsRp24GnDuHk8QWkARMW";
// vector from https://dev.uniresolver.io/
const P256_JWK: &str = r#"{
"kty": "EC",
"crv": "P-256",
"x": "fyNYMN0976ci7xqiSdag3buk-ZCwgXU4kz9XNkBlNUI",
"y": "hW2ojTNfH7Jbi8--CJUo3OCbH3y5n91g-IMA9MLMbTU"
}"#;
const P256_FINGERPRINT: &str = "zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169";
// vector from https://dev.uniresolver.io/
const P384_JWK: &str = r#"{
"kty": "EC",
"crv": "P-384",
"x": "bKq-gg3sJmfkJGrLl93bsumOTX1NubBySttAV19y5ClWK3DxEmqPy0at5lLqBiiv",
"y": "PJQtdHnInU9SY3e8Nn9aOPoP51OFbs-FWJUsU0TGjRtZ4bnhoZXtS92wdzuAotL9"
}"#;
const P384_FINGERPRINT: &str =
"z82Lkytz3HqpWiBmt2853ZgNgNG8qVoUJnyoMvGw6ZEBktGcwUVdKpUNJHct1wvp9pXjr7Y";
#[test]
fn test_from_ed25519_jwk() {
let key = Key::from_jwk(ED25519_JWK).unwrap();
assert_eq!(key.fingerprint(), ED25519_FINGERPRINT);
}
#[test]
fn test_from_x25519_jwk() {
let key = Key::from_jwk(X25519_JWK).unwrap();
assert_eq!(key.fingerprint(), X25519_FINGERPRINT);
}
#[test]
fn test_from_p256_jwk() {
let key = Key::from_jwk(P256_JWK).unwrap();
assert_eq!(key.fingerprint(), P256_FINGERPRINT);
}
#[test]
fn test_from_p384_jwk() {
let key = Key::from_jwk(P384_JWK).unwrap();
assert_eq!(key.fingerprint(), P384_FINGERPRINT);
}
#[test]
fn test_ed25519_to_jwk() {
let key = Key::from_fingerprint(ED25519_FINGERPRINT).unwrap();
let jwk: Value = serde_json::from_str(&key.to_jwk().unwrap()).unwrap();
assert_eq!(jwk, serde_json::from_str::<Value>(ED25519_JWK).unwrap());
}
#[test]
fn test_x25519_to_jwk() {
let key = Key::from_fingerprint(X25519_FINGERPRINT).unwrap();
let jwk: Value = serde_json::from_str(&key.to_jwk().unwrap()).unwrap();
assert_eq!(jwk, serde_json::from_str::<Value>(X25519_JWK).unwrap());
}
#[test]
fn test_p256_to_jwk() {
let key = Key::from_fingerprint(P256_FINGERPRINT).unwrap();
let jwk: Value = serde_json::from_str(&key.to_jwk().unwrap()).unwrap();
assert_eq!(jwk, serde_json::from_str::<Value>(P256_JWK).unwrap());
}
#[test]
fn test_p384_to_jwk() {
let key = Key::from_fingerprint(P384_FINGERPRINT).unwrap();
let jwk: Value = serde_json::from_str(&key.to_jwk().unwrap()).unwrap();
assert_eq!(jwk, serde_json::from_str::<Value>(P384_JWK).unwrap());
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/public_key/src/error.rs | did_core/public_key/src/error.rs | use std::error::Error;
use thiserror::Error;
use crate::KeyType;
#[derive(Debug, Error)]
pub enum PublicKeyError {
#[error("Base 64 decoding error")]
Base64DecodingError(#[from] base64::DecodeError),
#[error("Base 58 decoding error")]
Base58DecodingError(#[from] bs58::decode::Error),
#[error("Multibase decoding error")]
MultibaseDecodingError(#[from] multibase::Error),
#[error("Varint decoding error")]
VarintDecodingError(#[from] VarintDecodingError),
#[error("JWK decoding error")]
JwkDecodingError(#[from] Box<dyn Error + Send + Sync>),
#[error("Unsupported multicodec descriptor: {0}")]
UnsupportedMulticodecDescriptor(u64),
#[error("Unsupported multicodec descriptor: {0}")]
UnsupportedKeyType(String),
#[error("Invalid KeyType {0}, expected KeyType: {1}")]
InvalidKeyType(KeyType, KeyType),
}
#[derive(Debug, Error)]
pub struct VarintDecodingError(unsigned_varint::decode::Error);
impl std::fmt::Display for VarintDecodingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Varint decoding error: {}", self.0)
}
}
impl From<unsigned_varint::decode::Error> for VarintDecodingError {
fn from(error: unsigned_varint::decode::Error) -> Self {
Self(error)
}
}
impl From<unsigned_varint::decode::Error> for PublicKeyError {
fn from(error: unsigned_varint::decode::Error) -> Self {
Self::VarintDecodingError(error.into())
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/public_key/src/key_type.rs | did_core/public_key/src/key_type.rs | use std::fmt::Display;
use serde::{Deserialize, Serialize};
use crate::error::PublicKeyError;
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum KeyType {
Ed25519,
Bls12381g1g2,
Bls12381g1,
Bls12381g2,
X25519,
P256,
P384,
P521,
}
impl KeyType {
const C_BLS12381G1: u64 = 234;
const C_BLS12381G2: u64 = 235;
const C_X25519: u64 = 236;
const C_ED25519: u64 = 237;
const C_BLS12381G1G2: u64 = 238;
const C_P256: u64 = 4608;
const C_P384: u64 = 4609;
const C_P521: u64 = 4610;
}
// https://github.com/multiformats/multicodec/blob/master/table.csv
impl From<&KeyType> for u64 {
fn from(key_type: &KeyType) -> Self {
match key_type {
KeyType::Bls12381g1 => KeyType::C_BLS12381G1,
KeyType::Bls12381g2 => KeyType::C_BLS12381G2,
KeyType::X25519 => KeyType::C_X25519,
KeyType::Ed25519 => KeyType::C_ED25519,
KeyType::Bls12381g1g2 => KeyType::C_BLS12381G1G2,
KeyType::P256 => KeyType::C_P256,
KeyType::P384 => KeyType::C_P384,
KeyType::P521 => KeyType::C_P521,
}
}
}
impl TryFrom<u64> for KeyType {
type Error = PublicKeyError;
fn try_from(value: u64) -> Result<Self, Self::Error> {
match value {
KeyType::C_BLS12381G1 => Ok(KeyType::Bls12381g1),
KeyType::C_BLS12381G2 => Ok(KeyType::Bls12381g2),
KeyType::C_X25519 => Ok(KeyType::X25519),
KeyType::C_ED25519 => Ok(KeyType::Ed25519),
KeyType::C_BLS12381G1G2 => Ok(KeyType::Bls12381g1g2),
KeyType::C_P256 => Ok(KeyType::P256),
KeyType::C_P384 => Ok(KeyType::P384),
KeyType::C_P521 => Ok(KeyType::P521),
p => Err(PublicKeyError::UnsupportedMulticodecDescriptor(p)),
}
}
}
impl Display for KeyType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
KeyType::Bls12381g1 => write!(f, "Bls12381g1"),
KeyType::Bls12381g2 => write!(f, "Bls12381g2"),
KeyType::X25519 => write!(f, "X25519"),
KeyType::Ed25519 => write!(f, "Ed25519"),
KeyType::Bls12381g1g2 => write!(f, "Bls12381g1g2"),
KeyType::P256 => write!(f, "P256"),
KeyType::P384 => write!(f, "P384"),
KeyType::P521 => write!(f, "P521"),
}
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/src/lib.rs | did_core/did_parser_nom/src/lib.rs | mod did;
mod did_url;
mod error;
use std::ops::Range;
type DidRange = Range<usize>;
pub use did::Did;
pub use did_url::DidUrl;
pub use error::ParseError;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/src/error.rs | did_core/did_parser_nom/src/error.rs | use std::fmt;
#[derive(Debug)]
pub enum ParseError {
InvalidInput(&'static str),
ParserError(Box<dyn std::error::Error + 'static + Send + Sync>),
}
impl std::error::Error for ParseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ParseError::InvalidInput(_) => None,
ParseError::ParserError(err) => Some(err.as_ref()),
}
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ParseError::InvalidInput(input) => write!(f, "Invalid input: {input}"),
ParseError::ParserError(error) => write!(f, "Parsing library error: {error}"),
}
}
}
impl From<nom::Err<nom::error::Error<&str>>> for ParseError {
fn from(err: nom::Err<nom::error::Error<&str>>) -> Self {
ParseError::ParserError(err.to_owned().into())
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/src/did_url/mod.rs | did_core/did_parser_nom/src/did_url/mod.rs | mod parsing;
use std::{collections::HashMap, fmt::Display, str::FromStr};
use nom::combinator::all_consuming;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use self::parsing::{fragment_parser, parse_did_url};
use crate::{error::ParseError, Did, DidRange};
#[derive(Default, Debug, Clone, PartialEq)]
pub struct DidUrl {
did_url: String,
did: Option<DidRange>,
method: Option<DidRange>,
namespace: Option<DidRange>,
id: Option<DidRange>,
path: Option<DidRange>,
fragment: Option<DidRange>,
queries: HashMap<DidRange, DidRange>,
}
impl DidUrl {
// todo: can be &str
pub fn parse(did_url: String) -> Result<Self, ParseError> {
parse_did_url(did_url)
}
pub fn did_url(&self) -> &str {
self.did_url.as_ref()
}
pub fn did(&self) -> Option<&str> {
self.did.clone().map(|range| self.did_url[range].as_ref())
}
pub fn method(&self) -> Option<&str> {
self.method
.clone()
.map(|range| self.did_url[range].as_ref())
}
pub fn namespace(&self) -> Option<&str> {
self.namespace
.clone()
.map(|range| self.did_url[range].as_ref())
}
pub fn id(&self) -> Option<&str> {
self.id.clone().map(|range| self.did_url[range].as_ref())
}
pub fn path(&self) -> Option<&str> {
self.path.as_ref().map(|path| &self.did_url[path.clone()])
}
pub fn queries(&self) -> HashMap<String, String> {
self.queries
.iter()
.map(|(k, v)| {
(
query_percent_decode(&self.did_url[k.clone()]),
query_percent_decode(&self.did_url[v.clone()]),
)
})
.collect()
}
pub fn fragment(&self) -> Option<&str> {
self.fragment
.as_ref()
.map(|fragment| &self.did_url[fragment.clone()])
}
// TODO: Ideally we would have a builder instead of purpose-specific constructors
pub fn from_fragment(fragment: String) -> Result<Self, ParseError> {
if all_consuming(fragment_parser)(&fragment).is_err() {
return Err(ParseError::InvalidInput("Invalid fragment"));
}
let len = fragment.len();
Ok(Self {
did_url: format!("#{fragment}"),
did: None,
method: None,
namespace: None,
id: None,
path: None,
fragment: Some(1..len + 1),
queries: HashMap::new(),
})
}
pub(crate) fn from_did_parts(
did_url: String,
did: DidRange,
method: Option<DidRange>,
id: DidRange,
) -> Self {
Self {
did_url,
did: Some(did),
method,
namespace: None,
id: Some(id),
path: None,
fragment: None,
queries: HashMap::new(),
}
}
}
/// Decode percent-encoded URL query item (application/x-www-form-urlencoded encoded).
/// Primary difference from general percent encoding is encoding of ' ' as '+'
fn query_percent_decode(input: &str) -> String {
percent_encoding::percent_decode_str(&input.replace('+', " "))
.decode_utf8_lossy()
.into_owned()
}
impl TryFrom<String> for DidUrl {
type Error = ParseError;
fn try_from(did_url: String) -> Result<Self, Self::Error> {
Self::parse(did_url)
}
}
impl FromStr for DidUrl {
type Err = ParseError;
fn from_str(did: &str) -> Result<Self, Self::Err> {
Self::parse(did.to_string())
}
}
impl Display for DidUrl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.did_url)
}
}
impl Serialize for DidUrl {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.did_url)
}
}
impl<'de> Deserialize<'de> for DidUrl {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let did_url = String::deserialize(deserializer)?;
DidUrl::parse(did_url).map_err(serde::de::Error::custom)
}
}
impl TryFrom<&DidUrl> for Did {
type Error = ParseError;
fn try_from(did_url: &DidUrl) -> Result<Self, Self::Error> {
let err = || ParseError::InvalidInput("Unable to construct a DID from relative DID URL");
Ok(Did::from_parts(
did_url.did().ok_or_else(err)?.to_owned(),
did_url.method.to_owned(),
did_url.namespace.to_owned(),
did_url.id.to_owned().ok_or_else(err)?,
))
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/src/did_url/parsing.rs | did_core/did_parser_nom/src/did_url/parsing.rs | use std::collections::HashMap;
use nom::{
branch::alt,
bytes::complete::{tag, take_while1},
character::complete::{char, one_of, satisfy},
combinator::{all_consuming, cut, opt, recognize, success},
multi::{many0, many1, separated_list0},
sequence::{preceded, separated_pair, tuple},
AsChar, IResult,
};
type UrlPart<'a> = (&'a str, Option<Vec<(&'a str, &'a str)>>, Option<&'a str>);
use crate::{
did::parsing::{parse_did_ranges, DidRanges},
DidRange, DidUrl, ParseError,
};
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
fn is_unreserved(c: char) -> bool {
c.is_ascii_alphabetic() || c.is_ascii_digit() || "-._~".contains(c)
}
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
fn is_sub_delims(c: char) -> bool {
"!$&'()*+,;=".contains(c)
}
// pct-encoded = "%" HEXDIG HEXDIG
fn pct_encoded(input: &str) -> IResult<&str, &str> {
recognize(tuple((
tag("%"),
satisfy(|c| c.is_hex_digit()),
satisfy(|c| c.is_hex_digit()),
)))(input)
}
// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
fn pchar(input: &str) -> IResult<&str, &str> {
alt((
recognize(satisfy(is_unreserved)),
pct_encoded,
recognize(satisfy(is_sub_delims)),
tag(":"),
tag("@"),
))(input)
}
// segment = *pchar
fn segment(input: &str) -> IResult<&str, &str> {
recognize(many1(pchar))(input)
}
// path-abempty = *( "/" segment )
fn path_abempty(input: &str) -> IResult<&str, &str> {
recognize(many0(preceded(tag("/"), segment)))(input)
}
// fragment = *( pchar / "/" / "?" )
pub(super) fn fragment_parser(input: &str) -> IResult<&str, &str> {
fn fragment_element(input: &str) -> IResult<&str, &str> {
alt(((pchar), tag("/"), tag("?")))(input)
}
recognize(many1(fragment_element))(input)
}
// query = *( pchar / "/" / "?" )
fn query_key_value_pair(input: &str) -> IResult<&str, (&str, &str)> {
fn query_element(input: &str) -> IResult<&str, &str> {
alt(((pchar), tag("/"), tag("?")))(input)
}
let (remaining, (key, value)) = cut(separated_pair(
take_while1(|c| !"=&#".contains(c)),
char('='),
alt((take_while1(|c| !"&#?".contains(c)), success(""))),
))(input)?;
cut(all_consuming(many1(query_element)))(key)?;
if !value.is_empty() {
cut(all_consuming(many1(query_element)))(value)?;
}
Ok((remaining, (key, value)))
}
fn query_parser(input: &str) -> IResult<&str, Vec<(&str, &str)>> {
separated_list0(one_of("&?"), query_key_value_pair)(input)
}
fn parse_did_ranges_with_empty_allowed(input: &str) -> IResult<&str, DidRanges> {
alt((
parse_did_ranges,
success(Default::default()), // Relative DID URL
))(input)
}
// did-url-remaining = path-abempty [ "?" query ] [ "#" fragment ]
fn parse_url_part(input: &str) -> IResult<&str, UrlPart> {
let (remaining, path) = path_abempty(input)?;
let (remaining, queries) = opt(preceded(tag("?"), cut(query_parser)))(remaining)?;
let (remaining, fragment) =
opt(preceded(tag("#"), cut(all_consuming(fragment_parser))))(remaining)?;
Ok((remaining, (path, queries, fragment)))
}
fn to_did_url_ranges(
id_range: Option<DidRange>,
(path, queries, fragment): UrlPart,
) -> (
Option<DidRange>,
HashMap<DidRange, DidRange>,
Option<DidRange>,
) {
let id_end = id_range.unwrap_or_default().end;
let path_range = if path.is_empty() {
None
} else {
let path_start = id_end;
let path_end = path_start + path.len();
Some(path_start..path_end)
};
let mut current_last_position = path_range
.clone()
.map(|range| range.end + 1)
.unwrap_or(id_end + 1);
let mut query_map = HashMap::<DidRange, DidRange>::new();
for (key, value) in queries.unwrap_or_default() {
let key_start = current_last_position;
let key_end = key_start + key.len();
let value_start = key_end + 1;
let value_end = value_start + value.len();
current_last_position = value_end + 1;
query_map.insert(key_start..key_end, value_start..value_end);
}
let fragment_range = fragment.map(|fragment| {
let fragment_end = fragment.len() + current_last_position;
current_last_position..fragment_end
});
(path_range, query_map, fragment_range)
}
fn validate_result_not_empty(url_part: &UrlPart, did_ranges: &DidRanges) -> Result<(), ParseError> {
if (url_part, did_ranges) == (&Default::default(), &Default::default()) {
Err(ParseError::InvalidInput("Invalid input"))
} else {
Ok(())
}
}
// did-url = did path-abempty [ "?" query ] [ "#" fragment ]
pub fn parse_did_url(did_url: String) -> Result<DidUrl, ParseError> {
if did_url.is_empty() {
return Err(ParseError::InvalidInput("Empty input"));
}
let (remaining, did_ranges) = parse_did_ranges_with_empty_allowed(&did_url)?;
let (_, url_part) = all_consuming(parse_url_part)(remaining)?;
validate_result_not_empty(&url_part, &did_ranges)?;
let (method, namespace, id) = did_ranges;
let (path, queries, fragment) = to_did_url_ranges(id.clone(), url_part);
Ok(DidUrl {
did_url,
did: id.clone().map(|range| 0..range.end),
method,
namespace,
id,
path,
fragment,
queries,
})
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/src/did/mod.rs | did_core/did_parser_nom/src/did/mod.rs | pub(crate) mod parsing;
use std::{
convert::TryFrom,
fmt::{Display, Formatter},
str::FromStr,
};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use self::parsing::parse_did;
use crate::{error::ParseError, DidRange, DidUrl};
#[derive(Clone, PartialEq, Eq, Hash, Default)]
pub struct Did {
did: String,
method: Option<DidRange>,
namespace: Option<DidRange>,
id: DidRange,
}
// TODO: Add a builder / constructor so that we don't have to create strings and parse them?
impl Did {
pub fn parse(did: String) -> Result<Self, ParseError> {
parse_did(did)
}
pub fn did(&self) -> &str {
self.did.as_ref()
}
pub fn method(&self) -> Option<&str> {
self.method.as_ref().map(|range| &self.did[range.clone()])
}
pub fn namespace(&self) -> Option<&str> {
self.namespace
.as_ref()
.map(|range| &self.did[range.clone()])
}
pub fn id(&self) -> &str {
self.did[self.id.start..self.id.end].as_ref()
}
pub(crate) fn from_parts(
did: String,
method: Option<DidRange>,
namespace: Option<DidRange>,
id: DidRange,
) -> Self {
Self {
did,
method,
namespace,
id,
}
}
}
impl TryFrom<String> for Did {
type Error = ParseError;
fn try_from(did: String) -> Result<Self, Self::Error> {
Self::parse(did)
}
}
impl TryFrom<&str> for Did {
type Error = ParseError;
fn try_from(did: &str) -> Result<Self, Self::Error> {
Did::from_str(did)
}
}
impl FromStr for Did {
type Err = ParseError;
fn from_str(did: &str) -> Result<Self, Self::Err> {
Self::parse(did.to_string())
}
}
impl Display for Did {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.did)
}
}
impl std::fmt::Debug for Did {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Did")
.field("did", &self.did)
.field("method", &self.method())
.field("id", &self.id())
.field("namespace", &self.namespace())
.finish()
}
}
impl Serialize for Did {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.did())
}
}
impl<'de> Deserialize<'de> for Did {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let did = String::deserialize(deserializer)?;
Self::parse(did).map_err(serde::de::Error::custom)
}
}
impl From<Did> for DidUrl {
fn from(did: Did) -> Self {
Self::from_did_parts(did.did().to_string(), 0..did.did.len(), did.method, did.id)
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/src/did/parsing/did_key.rs | did_core/did_parser_nom/src/did/parsing/did_key.rs | use nom::{
bytes::complete::{tag, take_while1},
character::complete::char,
combinator::{cut, fail, opt, recognize},
sequence::{delimited, tuple},
IResult,
};
use super::{DidPart, BASE58CHARS};
fn is_base58char(c: char) -> bool {
BASE58CHARS.contains(c)
}
// mb-value := z[a-km-zA-HJ-NP-Z1-9]+
fn parse_mb_value(input: &str) -> IResult<&str, &str> {
recognize(tuple((char('z'), take_while1(is_base58char))))(input)
}
// did-key-format := did:key:<mb-value>
pub(super) fn parse_did_key(input: &str) -> IResult<&str, DidPart> {
fn did_key_method(input: &str) -> IResult<&str, &str> {
delimited(char(':'), tag("key"), char(':'))(input)
}
let (input_left, (prefix, method, namespace, id)) = tuple((
tag("did"),
did_key_method,
opt(fail::<_, &str, _>),
cut(parse_mb_value),
))(input)?;
Ok((input_left, (prefix, method, namespace, id)))
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/src/did/parsing/did_sov.rs | did_core/did_parser_nom/src/did/parsing/did_sov.rs | use nom::{
branch::alt,
bytes::complete::tag,
character::complete::{char, one_of},
combinator::{all_consuming, cut, opt, recognize},
multi::{many1, many_m_n},
sequence::{delimited, tuple},
IResult,
};
use super::{DidPart, BASE58CHARS};
use crate::did::parsing::did_core::idchar;
fn base58char(input: &str) -> IResult<&str, &str> {
recognize(one_of(BASE58CHARS))(input)
}
// namespace = *idchar ":"
fn did_sov_namespace(input: &str) -> IResult<&str, &str> {
if let Some((before_last_colon, after_last_colon)) = input.rsplit_once(':') {
match cut(all_consuming(many1(alt((idchar, tag(":"))))))(before_last_colon) {
Ok(_) => Ok((after_last_colon, before_last_colon)),
Err(err) => Err(err),
}
} else {
Err(nom::Err::Error(nom::error::Error::new(
input,
nom::error::ErrorKind::Tag,
)))
}
}
// idstring = 21*22(base58char)
pub(super) fn parse_unqualified_sovrin_did(input: &str) -> IResult<&str, &str> {
recognize(many_m_n(21, 22, base58char))(input)
}
// The specification seems to contradict practice?
// sovrin-did = "did:sov:" idstring *(":" subnamespace)
// subnamespace = ALPHA *(ALPHA / DIGIT / "_" / "-")
pub(super) fn parse_qualified_sovrin_did(input: &str) -> IResult<&str, DidPart> {
fn did_sov_method(input: &str) -> IResult<&str, &str> {
delimited(char(':'), tag("sov"), char(':'))(input)
}
let (input_left, (prefix, method, namespace, id)) = tuple((
tag("did"),
did_sov_method,
opt(did_sov_namespace),
cut(parse_unqualified_sovrin_did),
))(input)?;
Ok((input_left, (prefix, method, namespace, id)))
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/src/did/parsing/did_peer_4.rs | did_core/did_parser_nom/src/did/parsing/did_peer_4.rs | use nom::{
bytes::complete::tag,
character::complete::char,
combinator::{cut, peek},
sequence::{delimited, tuple},
IResult,
};
use super::DidPart;
use crate::did::parsing::did_core::general_did_id;
fn did_peer_method(input: &str) -> IResult<&str, &str> {
delimited(char(':'), tag("peer"), char(':'))(input)
}
fn check_4(input: &str) -> IResult<&str, &str> {
peek(tag("4"))(input)
}
pub(super) fn parse_did_peer_4(input: &str) -> IResult<&str, DidPart> {
let ret = tuple((tag("did"), did_peer_method, check_4, cut(general_did_id)))(input);
let (input_left, (prefix, method, _peek, id)) = ret?;
Ok((input_left, (prefix, method, None, id)))
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/src/did/parsing/mod.rs | did_core/did_parser_nom/src/did/parsing/mod.rs | mod did_cheqd;
mod did_core;
mod did_key;
mod did_peer_4;
mod did_sov;
mod did_web;
use did_cheqd::parse_did_cheqd;
use nom::{
branch::alt,
combinator::{all_consuming, map},
IResult,
};
use self::{
did_core::parse_qualified_did,
did_key::parse_did_key,
did_sov::{parse_qualified_sovrin_did, parse_unqualified_sovrin_did},
did_web::parse_did_web,
};
use crate::{did::parsing::did_peer_4::parse_did_peer_4, Did, DidRange, ParseError};
type DidPart<'a> = (&'a str, &'a str, Option<&'a str>, &'a str);
pub type DidRanges = (Option<DidRange>, Option<DidRange>, Option<DidRange>);
static BASE58CHARS: &str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static HEX_DIGIT_CHARS: &str = "0123456789abcdefABCDEF";
fn to_id_range(id: &str) -> DidRanges {
(None, None, Some(0..id.len()))
}
fn to_did_ranges((did_prefix, method, namespace, id): DidPart) -> DidRanges {
let mut next_start = if !did_prefix.is_empty() {
did_prefix.len() + 1
} else {
0
};
let method_range = if !method.is_empty() {
let method_start = next_start;
let method_end = method_start + method.len();
next_start = method_end + 1;
Some(method_start..method_end)
} else {
next_start = 0;
None
};
let namespace_range = namespace.map(|ns| {
let namespace_start = next_start;
let namespace_end = namespace_start + ns.len();
next_start = namespace_end + 1;
namespace_start..namespace_end
});
let id_start = next_start;
let id_end = id_start + id.len();
let id_range = match id_start..id_end {
range if range.is_empty() => None,
range => Some(range),
};
(method_range, namespace_range, id_range)
}
pub fn parse_did_ranges(input: &str) -> IResult<&str, DidRanges> {
alt((
map(parse_did_peer_4, to_did_ranges),
map(parse_did_web, to_did_ranges),
map(parse_did_key, to_did_ranges),
map(parse_did_cheqd, to_did_ranges),
map(parse_qualified_sovrin_did, to_did_ranges),
map(parse_qualified_did, to_did_ranges),
map(parse_unqualified_sovrin_did, to_id_range),
))(input)
}
pub fn parse_did(did: String) -> Result<Did, ParseError> {
if did.is_empty() {
return Err(ParseError::InvalidInput("Empty input"));
}
let (_, (method, namespace, id)) = all_consuming(parse_did_ranges)(&did)?;
let id = id.ok_or_else(|| ParseError::InvalidInput("Invalid DID"))?;
if id.end > did.len() {
return Err(ParseError::InvalidInput("Invalid DID"));
}
Ok(Did {
did,
method,
namespace,
id,
})
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/src/did/parsing/did_web.rs | did_core/did_parser_nom/src/did/parsing/did_web.rs | use nom::{
bytes::complete::{tag, take_till},
character::complete::char,
combinator::{fail, opt},
sequence::{delimited, tuple},
IResult,
};
use super::DidPart;
pub(super) fn parse_did_web(input: &str) -> IResult<&str, DidPart> {
fn did_web_method(input: &str) -> IResult<&str, &str> {
delimited(char(':'), tag("web"), char(':'))(input)
}
let (input_left, (prefix, method, namespace, id)) = tuple((
tag("did"),
did_web_method,
opt(fail::<_, &str, _>),
take_till(|c| "?/#".contains(c)),
))(input)?;
Ok((input_left, (prefix, method, namespace, id)))
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/src/did/parsing/did_core.rs | did_core/did_parser_nom/src/did/parsing/did_core.rs | // https://www.w3.org/TR/did-core/#did-syntax
use nom::{
branch::alt,
bytes::complete::{tag, take_while1},
character::complete::{alphanumeric1, char, satisfy},
combinator::recognize,
multi::{many0, many1},
sequence::{delimited, terminated, tuple},
AsChar, IResult,
};
use super::DidPart;
fn hexadecimal_digit(input: &str) -> IResult<&str, &str> {
fn is_hexadecimal_digit(c: char) -> bool {
c.is_ascii_hexdigit()
}
recognize(satisfy(is_hexadecimal_digit))(input)
}
// todo: is this better?
// fn hexadecimal_digit(input: &str) -> IResult<&str, &str> {
// recognize(alt((nom::character::is_hex_digit, nom::character::is_hex_digit)))(input)
// }
fn is_lowercase_alphanumeric(c: char) -> bool {
c.is_ascii_lowercase() || c.is_dec_digit()
}
// pct-encoded = "%" HEXDIG HEXDIG
fn pct_encoded(input: &str) -> IResult<&str, &str> {
recognize(tuple((tag("%"), hexadecimal_digit, hexadecimal_digit)))(input)
}
// idchar = ALPHA / DIGIT / "." / "-" / "_" / pct-encoded
pub(super) fn idchar(input: &str) -> IResult<&str, &str> {
alt((alphanumeric1, tag("."), tag("-"), tag("_"), pct_encoded))(input)
}
// method-name = 1*method-char
// method-char = %x61-7A / DIGIT
fn method_name(input: &str) -> IResult<&str, &str> {
delimited(char(':'), take_while1(is_lowercase_alphanumeric), char(':'))(input)
}
fn method_specific_id_optional_repeat(input: &str) -> IResult<&str, &str> {
log::trace!("did_core::method_specific_id_optional_repeat >> input: {input:?}");
let ret = recognize(many0(terminated(many0(idchar), char(':'))))(input); // First half of DID Syntax ABNF rule method-specific-id: *( *idchar ":"
// )recognize(many1(idchar))(input)
log::trace!("did_core::method_specific_id_optional_repeat >> ret: {ret:?}");
ret
}
fn method_specific_id_required_characters(input: &str) -> IResult<&str, &str> {
log::trace!("did_core::method_specific_id_required_characters >> input: {input:?}");
let ret = recognize(many1(idchar))(input); // Second half of DID Syntax ABNF rule method-specific-id: 1*idchar
log::trace!("did_core::method_specific_id_required_characters >> ret: {ret:?}");
ret
}
pub(super) fn general_did_id(input: &str) -> IResult<&str, &str> {
log::trace!("did_core::general_did_id >> input: {input:?}");
let (input, did_id) = recognize(tuple((
method_specific_id_optional_repeat,
method_specific_id_required_characters,
)))(input)?;
log::trace!("did_core::general_did_id >> did_id: {did_id:?}");
Ok((input, did_id))
}
// did = "did:" method-name ":" method-specific-id
pub(super) fn parse_qualified_did(input: &str) -> IResult<&str, DidPart> {
let (input_left, (prefix, method, id)) =
tuple((tag("did"), method_name, general_did_id))(input)?;
Ok((input_left, (prefix, method, None, id)))
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/src/did/parsing/did_cheqd.rs | did_core/did_parser_nom/src/did/parsing/did_cheqd.rs | //! https://docs.cheqd.io/product/architecture/adr-list/adr-001-cheqd-did-method#syntax-for-did-cheqd-method
use nom::{
branch::alt,
bytes::complete::tag,
character::complete::{alphanumeric1, char, one_of},
combinator::{cut, recognize},
multi::count,
sequence::{delimited, terminated, tuple},
IResult,
};
use super::{did_sov::parse_unqualified_sovrin_did, DidPart, HEX_DIGIT_CHARS};
// namespace = 1*namespace-char ":" ...
fn did_cheqd_namespace(input: &str) -> IResult<&str, &str> {
terminated(alphanumeric1, tag(":"))(input)
}
// Parser for a single hexDigit
fn hex_digit_char(input: &str) -> IResult<&str, char> {
one_of(HEX_DIGIT_CHARS)(input)
}
// Parser for hexOctet (2 hex digits)
fn parse_hex_octet(input: &str) -> IResult<&str, &str> {
recognize(count(hex_digit_char, 2))(input)
}
// https://datatracker.ietf.org/doc/html/rfc4122#section-3
fn parse_uuid(input: &str) -> IResult<&str, &str> {
recognize(tuple((
count(parse_hex_octet, 4), // time-low
tag("-"),
count(parse_hex_octet, 2), // time mid
tag("-"),
count(parse_hex_octet, 2), // time high & version
tag("-"),
count(parse_hex_octet, 1), // clock sequence and reserved
count(parse_hex_octet, 1), // clock sequence low
tag("-"),
count(parse_hex_octet, 6), // node
)))(input)
}
// unique-id = *id-char / UUID
// id-char = ALPHA / DIGIT
// > Note: The *id-char unique-id must be 16 bytes of Indy-style base58 encoded identifier.
fn parse_did_cheqd_unique_id(input: &str) -> IResult<&str, &str> {
alt((
recognize(parse_unqualified_sovrin_did), // indy-style DID ID
recognize(parse_uuid), // UUID-style DID ID
))(input)
}
pub(super) fn parse_did_cheqd(input: &str) -> IResult<&str, DidPart> {
fn did_cheqd_method(input: &str) -> IResult<&str, &str> {
delimited(char(':'), tag("cheqd"), char(':'))(input)
}
let (input_left, (prefix, method, namespace, id)) = tuple((
tag("did"),
did_cheqd_method,
cut(did_cheqd_namespace),
cut(parse_did_cheqd_unique_id),
))(input)?;
Ok((input_left, (prefix, method, Some(namespace), id)))
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/tests/lib.rs | did_core/did_parser_nom/tests/lib.rs | mod did;
mod did_url;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/tests/did_url/serde.rs | did_core/did_parser_nom/tests/did_url/serde.rs | use did_parser_nom::DidUrl;
use serde_test::{assert_tokens, Token};
const DID_URL: &str = "did:example:namespace:123456789abcdefghi/path?query=value#fragment";
#[test]
fn test_did_url_serde() {
assert_tokens(
&DidUrl::parse(DID_URL.to_string()).unwrap(),
&[Token::Str(DID_URL)],
);
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/tests/did_url/positive.rs | did_core/did_parser_nom/tests/did_url/positive.rs | use std::collections::HashMap;
use did_parser_nom::DidUrl;
macro_rules! test_cases_positive {
($($name:ident: $input:expr, $expected_did:expr, $expected_method:expr, $expected_namespace:expr, $expected_id:expr, $expected_path:expr, $expected_fragment:expr, $expected_queries:expr)*) => {
$(
#[test]
fn $name() {
let parsed_did = DidUrl::parse($input.to_string()).unwrap();
assert_eq!(parsed_did.did(), $expected_did, "DID");
assert_eq!(parsed_did.method(), $expected_method, "Method");
assert_eq!(parsed_did.namespace(), $expected_namespace, "Namespace");
assert_eq!(parsed_did.id(), $expected_id, "ID");
assert_eq!(parsed_did.path(), $expected_path, "Path");
assert_eq!(parsed_did.fragment(), $expected_fragment, "Fragment");
assert_eq!(parsed_did.queries(), $expected_queries, "Queries");
}
)*
};
}
test_cases_positive! {
test_case1:
"did:example:namespace:123456789abcdefghi",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
None,
HashMap::new()
test_case2:
"did:example:namespace:123456789abcdefghi/path",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
Some("/path"),
None,
HashMap::new()
test_case3:
"did:example:namespace:123456789abcdefghi/path?query1=value1&query2=value2",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
Some("/path"),
None,
{
vec![
("query1".to_string(), "value1".to_string()),
("query2".to_string(), "value2".to_string()),
].into_iter().collect()
}
test_case4:
"did:example:namespace:123456789abcdefghi/path?query=value#fragment",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
Some("/path"),
Some("fragment"),
{
vec![
("query".to_string(), "value".to_string()),
].into_iter().collect()
}
test_case5:
"did:example:namespace:123456789abcdefghi?query1=value1&query2=value2#fragment",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
Some("fragment"),
{
vec![
("query1".to_string(), "value1".to_string()),
("query2".to_string(), "value2".to_string()),
].into_iter().collect()
}
test_case6:
"did:example:namespace:123456789abcdefghi#fragment",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
Some("fragment"),
HashMap::new()
test_case7:
"did:example:namespace:123456789abcdefghi?query=value",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
None,
{
vec![
("query".to_string(), "value".to_string()),
].into_iter().collect()
}
test_case8:
"did:example:namespace:123456789abcdefghi/path#fragment",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
Some("/path"),
Some("fragment"),
HashMap::new()
test_case9:
"did:example:namespace:123456789abcdefghi#fragment",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
Some("fragment"),
HashMap::new()
test_case10:
"did:example:namespace:123456789abcdefghi?query=value",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
None,
{
let mut queries = HashMap::new();
queries.extend(vec![("query".to_string(), "value".to_string())]);
queries
}
test_case11:
"did:example:namespace:123456789abcdefghi/path?query=value",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
Some("/path"),
None,
{
vec![
("query".to_string(), "value".to_string()),
].into_iter().collect()
}
test_case12:
"did:example:namespace:123456789abcdefghi/path?query1=value1&query2=value2#fragment",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
Some("/path"),
Some("fragment"),
{
vec![
("query1".to_string(), "value1".to_string()),
("query2".to_string(), "value2".to_string()),
].into_iter().collect()
}
test_case13:
"did:example:namespace:123456789abcdefghi?query1=value1?query2=value2",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
None,
{
vec![
("query1".to_string(), "value1".to_string()),
("query2".to_string(), "value2".to_string()),
].into_iter().collect()
}
test_case14:
"did:example:namespace:123456789abcdefghi?query=",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
None,
{
vec![
("query".to_string(), "".to_string()),
].into_iter().collect()
}
test_case15:
"did:example:namespace:123456789abcdefghi?query1=value1&query2=#fragment",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
Some("fragment"),
{
vec![
("query1".to_string(), "value1".to_string()),
("query2".to_string(), "".to_string()),
].into_iter().collect()
}
test_case16:
"did:example:namespace:123456789abcdefghi?query1=value1&query2=value2#fragment",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
Some("fragment"),
{
vec![
("query1".to_string(), "value1".to_string()),
("query2".to_string(), "value2".to_string()),
].into_iter().collect()
}
test_case17:
"/path",
None,
None,
None,
None,
Some("/path"),
None,
HashMap::new()
test_case18:
"?query=value",
None,
None,
None,
None,
None,
None,
{
vec![
("query".to_string(), "value".to_string()),
].into_iter().collect()
}
test_case19:
"#fragment",
None,
None,
None,
None,
None,
Some("fragment"),
HashMap::new()
test_case20:
"/path?query=value",
None,
None,
None,
None,
Some("/path"),
None,
{
vec![
("query".to_string(), "value".to_string()),
].into_iter().collect()
}
test_case21:
"/path#fragment",
None,
None,
None,
None,
Some("/path"),
Some("fragment"),
HashMap::new()
test_case22:
"did:web:w3c-ccg.github.io:user:alice",
Some("did:web:w3c-ccg.github.io:user:alice"),
Some("web"),
None,
Some("w3c-ccg.github.io:user:alice"),
None,
None,
HashMap::new()
test_case23:
"2ZHFFhzA2XtTD6hJqzL7ux#1",
Some("2ZHFFhzA2XtTD6hJqzL7ux"),
None,
None,
Some("2ZHFFhzA2XtTD6hJqzL7ux"),
None,
Some("1"),
HashMap::new()
test_case24:
"did:example:namespace:123456789abcdefghi?query1=val;ue1",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
None,
{
vec![
("query1".to_string(), "val;ue1".to_string()),
].into_iter().collect()
}
test_case25:
"did:example:namespace:123456789abcdefghi?quer;y1=value1",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
None,
{
vec![
("quer;y1".to_string(), "value1".to_string()),
].into_iter().collect()
}
test_case26:
"did:example:namespace:123456789abcdefghi?query1=val=ue1",
Some("did:example:namespace:123456789abcdefghi"),
Some("example"),
None,
Some("namespace:123456789abcdefghi"),
None,
None,
{
vec![
("query1".to_string(), "val=ue1".to_string()),
].into_iter().collect()
}
test_case27:
"did:sov:5nDyJVP1NrcPAttP3xwMB9/anoncreds/v0/REV_REG_DEF/56495/npdb/TAG1",
Some("did:sov:5nDyJVP1NrcPAttP3xwMB9"),
Some("sov"),
None,
Some("5nDyJVP1NrcPAttP3xwMB9"),
Some("/anoncreds/v0/REV_REG_DEF/56495/npdb/TAG1"),
None,
HashMap::new()
test_case28:
"did:cheqd:testnet:d8ac0372-0d4b-413e-8ef5-8e8f07822b2c/resources/40829caf-b415-4b1d-91a3-b56dfb6374f4",
Some("did:cheqd:testnet:d8ac0372-0d4b-413e-8ef5-8e8f07822b2c"),
Some("cheqd"),
Some("testnet"),
Some("d8ac0372-0d4b-413e-8ef5-8e8f07822b2c"),
Some("/resources/40829caf-b415-4b1d-91a3-b56dfb6374f4"),
None,
HashMap::new()
test_case29:
"did:cheqd:mainnet:zF7rhDBfUt9d1gJPjx7s1J?resourceName=universityDegree&resourceType=anonCredsCredDef",
Some("did:cheqd:mainnet:zF7rhDBfUt9d1gJPjx7s1J"),
Some("cheqd"),
Some("mainnet"),
Some("zF7rhDBfUt9d1gJPjx7s1J"),
None,
None,
{
vec![
("resourceName".to_string(), "universityDegree".to_string()),
("resourceType".to_string(), "anonCredsCredDef".to_string()),
].into_iter().collect()
}
test_case30:
"did:cheqd:testnet:36e695a3-f133-46ec-ac1e-79900a927f67?resourceType=anonCredsStatusList&resourceName=Example+schema-default-0&resourceVersionTime=2024-12-10T04%3A13%3A50.000Z",
Some("did:cheqd:testnet:36e695a3-f133-46ec-ac1e-79900a927f67"),
Some("cheqd"),
Some("testnet"),
Some("36e695a3-f133-46ec-ac1e-79900a927f67"),
None,
None,
{
vec![
("resourceName".to_string(), "Example schema-default-0".to_string()),
("resourceType".to_string(), "anonCredsStatusList".to_string()),
("resourceVersionTime".to_string(), "2024-12-10T04:13:50.000Z".to_string()),
].into_iter().collect()
}
test_case31:
"did:example:123?foo+bar=123&bar%20foo=123%20123&h3%21%210%20=w%40rld%3D%3D",
Some("did:example:123"),
Some("example"),
None,
Some("123"),
None,
None,
{
vec![
("foo bar".to_string(), "123".to_string()),
("bar foo".to_string(), "123 123".to_string()),
("h3!!0 ".to_string(), "w@rld==".to_string())
].into_iter().collect()
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/tests/did_url/mod.rs | did_core/did_parser_nom/tests/did_url/mod.rs | mod negative;
mod positive;
mod serde;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/tests/did_url/negative.rs | did_core/did_parser_nom/tests/did_url/negative.rs | use did_parser_nom::DidUrl;
macro_rules! test_cases_negative {
($($name:ident: $input:expr)*) => {
$(
#[test]
fn $name() {
assert!(DidUrl::parse($input.to_string()).is_err());
}
)*
};
}
test_cases_negative! {
empty:
""
random_string:
"not-a-did"
no_method_specific_id:
"did:example"
no_equal_sign_after_last_query:
"did:example:123456789abcdefghi/path?query1=value1&query2"
no_equal_sign_after_query:
"did:example:123456789abcdefghi/path?query1"
fragment_doubled:
"did:example:123456789abcdefghi#fragment1#fragment2"
fragment_invalid_char:
"did:example:123456789abcdefghi#fr^gment"
query_doubled:
"did:example:123456789abcdefghi/path??"
query_not_delimited:
"did:example:123456789abcdefghi&query1=value1"
query_invalid_char:
"did:example:123456789abcdefghi?query1=v^lue1"
query_unfinished_pct_encoding:
"did:example:123456789?query=a%3&query2=b"
query_invalid_space_char:
"did:example:123456789?query=a b"
relative_empty_path: "/"
relative_empty_path_and_query: "/?"
relative_empty_path_and_fragment: "/#"
relative_semicolon: ";"
relative_semicolon_query: ";?"
relative_semicolon_fragment: ";#"
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/tests/did/serde.rs | did_core/did_parser_nom/tests/did/serde.rs | use did_parser_nom::Did;
use serde_test::{assert_tokens, Token};
const DID: &str = "did:example:123456789abcdefghi";
#[test]
fn test_did_serde() {
assert_tokens(&Did::parse(DID.to_string()).unwrap(), &[Token::Str(DID)]);
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/tests/did/positive.rs | did_core/did_parser_nom/tests/did/positive.rs | use std::sync::Once;
use did_parser_nom::Did;
static TEST_LOGGING_INIT: Once = Once::new();
pub fn init_logger() {
TEST_LOGGING_INIT.call_once(|| {
let env = env_logger::Env::default().default_filter_or("info");
env_logger::init_from_env(env);
})
}
macro_rules! test_cases_positive {
($($name:ident: $input_did:expr, $expected_method:expr, $expected_namespace:expr, $expected_id:expr)*) => {
$(
#[test]
fn $name() {
init_logger();
log::debug!("Testing parsing of {}", $input_did);
let parsed_did = Did::parse($input_did.to_string()).unwrap();
assert_eq!(parsed_did.did(), $input_did, "DID");
assert_eq!(parsed_did.method(), $expected_method, "Method");
assert_eq!(parsed_did.namespace(), $expected_namespace, "Namespace");
assert_eq!(parsed_did.id(), $expected_id, "ID");
}
)*
};
}
test_cases_positive! {
test_did_unknown_method:
"did:example:123456789abcdefghi",
Some("example"),
None,
"123456789abcdefghi"
test_did_web:
"did:web:w3c-ccg.github.io",
Some("web"),
None,
"w3c-ccg.github.io"
test_did_sov_unqualified:
"2ZHFFhzA2XtTD6hJqzL7ux",
None,
None,
"2ZHFFhzA2XtTD6hJqzL7ux"
test_did_sov:
"did:sov:2wJPyULfLLnYTEFYzByfUR",
Some("sov"),
None,
"2wJPyULfLLnYTEFYzByfUR"
test_did_key:
"did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK",
Some("key"),
None,
"z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK"
test_did_indy:
"did:indy:sovrin:7Tqg6BwSSWapxgUDm9KKgg",
Some("indy"),
None,
"sovrin:7Tqg6BwSSWapxgUDm9KKgg"
test_did_sov_namespaced:
"did:sov:builder:VbPQNHsvoLZdaNU7fTBeFx",
Some("sov"),
Some("builder"),
"VbPQNHsvoLZdaNU7fTBeFx"
test_did_peer_2:
"did:peer:2.Vz6Mkj3PUd1WjvaDhNZhhhXQdz5UnZXmS7ehtx8bsPpD47kKc.Ez6LSg8zQom395jKLrGiBNruB9MM6V8PWuf2FpEy4uRFiqQBR.SeyJ0IjoiZG0iLCJzIjp7InVyaSI6Imh0dHA6Ly9leGFtcGxlLmNvbS9kaWRjb21tIiwiYSI6WyJkaWRjb21tL3YyIl0sInIiOlsiZGlkOmV4YW1wbGU6MTIzNDU2Nzg5YWJjZGVmZ2hpI2tleS0xIl19fQ.SeyJ0IjoiZG0iLCJzIjp7InVyaSI6Imh0dHA6Ly9leGFtcGxlLmNvbS9hbm90aGVyIiwiYSI6WyJkaWRjb21tL3YyIl0sInIiOlsiZGlkOmV4YW1wbGU6MTIzNDU2Nzg5YWJjZGVmZ2hpI2tleS0yIl19fQ",
Some("peer"),
None,
"2.Vz6Mkj3PUd1WjvaDhNZhhhXQdz5UnZXmS7ehtx8bsPpD47kKc.Ez6LSg8zQom395jKLrGiBNruB9MM6V8PWuf2FpEy4uRFiqQBR.SeyJ0IjoiZG0iLCJzIjp7InVyaSI6Imh0dHA6Ly9leGFtcGxlLmNvbS9kaWRjb21tIiwiYSI6WyJkaWRjb21tL3YyIl0sInIiOlsiZGlkOmV4YW1wbGU6MTIzNDU2Nzg5YWJjZGVmZ2hpI2tleS0xIl19fQ.SeyJ0IjoiZG0iLCJzIjp7InVyaSI6Imh0dHA6Ly9leGFtcGxlLmNvbS9hbm90aGVyIiwiYSI6WyJkaWRjb21tL3YyIl0sInIiOlsiZGlkOmV4YW1wbGU6MTIzNDU2Nzg5YWJjZGVmZ2hpI2tleS0yIl19fQ"
test_did_peer_3:
"did:peer:3zQmS19jtYDvGtKVrJhQnRFpBQAx3pJ9omx2HpNrcXFuRCz9",
Some("peer"),
None,
"3zQmS19jtYDvGtKVrJhQnRFpBQAx3pJ9omx2HpNrcXFuRCz9"
test_did_peer_4:
"did:peer:4z84UjLJ6ugExV8TJ5gJUtZap5q67uD34LU26m1Ljo2u9PZ4xHa9XnknHLc3YMST5orPXh3LKi6qEYSHdNSgRMvassKP:z27uFkiqJVwvvn2ke5M19UCvByS79r5NppqwjiGAJzkj1EM4sf2JmiUySkANKy4YNu8M7yKjSmvPJTqbcyhPrJs9TASzDs2fWE1vFegmaRJxHRF5M9wGTPwGR1NbPkLGsvcnXum7aN2f8kX3BnhWWWp",
Some("peer"),
None,
"4z84UjLJ6ugExV8TJ5gJUtZap5q67uD34LU26m1Ljo2u9PZ4xHa9XnknHLc3YMST5orPXh3LKi6qEYSHdNSgRMvassKP:z27uFkiqJVwvvn2ke5M19UCvByS79r5NppqwjiGAJzkj1EM4sf2JmiUySkANKy4YNu8M7yKjSmvPJTqbcyhPrJs9TASzDs2fWE1vFegmaRJxHRF5M9wGTPwGR1NbPkLGsvcnXum7aN2f8kX3BnhWWWp"
test_did_cheqd:
"did:cheqd:mainnet:de9786cd-ec53-458c-857c-9342cf264f80",
Some("cheqd"),
Some("mainnet"),
"de9786cd-ec53-458c-857c-9342cf264f80"
test_did_cheqd_indy_style:
"did:cheqd:testnet:TAwT8WVt3dz2DBAifwuSkn",
Some("cheqd"),
Some("testnet"),
"TAwT8WVt3dz2DBAifwuSkn"
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/tests/did/mod.rs | did_core/did_parser_nom/tests/did/mod.rs | mod negative;
mod positive;
mod serde;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_parser_nom/tests/did/negative.rs | did_core/did_parser_nom/tests/did/negative.rs | use did_parser_nom::Did;
macro_rules! test_cases_negative {
($($name:ident: $input:expr)*) => {
$(
#[test]
fn $name() {
assert!(Did::parse($input.to_string()).is_err());
}
)*
};
}
test_cases_negative! {
empty:
""
random_string:
"not-a-did"
no_method_specific_id:
"did:example"
unqualified_invalid_len:
"2ZHFFhtTD6hJqzux"
indy_non_method_specific_id_char_in_namespace:
"did:indy:s@vrin:7Tqg6BwSSWapxgUDm9KKgg"
indy_multiple_namespaces_invalid_char_in_method_specific_id:
"did:indy:sovrin:alpha:%0zqg6BwS.Wapxg-Dm9K_gg"
sov_invalid_len:
"did:sov:2wJPyULfLLnYTEFYzByf"
sov_invalid_char:
"did:sov:2wJPyULfOLnYTEFYzByfUR"
sov_unqualified_invalid_len:
"2wJPyULfLLnYTEFYzByf"
sov_unqualified_invalid_char:
"2wJPyULfOLnYTEFYzByfUR"
key_non_mb_value_char:
"did:key:zWA8Ta6fesJIxeYku6cbA"
key_non_base58_btc_encoded:
"did:key:6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK"
cheqd_no_namespace_did:
"did:cheqd:de9786cd-ec53-458c-857c-9342cf264f80"
cheqd_empty_namespace_did:
"did:cheqd::de9786cd-ec53-458c-857c-9342cf264f80"
cheqd_sub_namespace_did:
"did:cheqd:mainnet:foo:de9786cd-ec53-458c-857c-9342cf264f80"
cheqd_invalid_namespace_character:
"did:cheqd:m@innet:de9786cd-ec53-458c-857c-9342cf264f80"
cheqd_short_indy_style_id:
"did:cheqd:mainnet:TAwT8WVt3dz2DBAifwuS"
cheqd_long_indy_style_id:
"did:cheqd:mainnet:TAwT8WVt3dz2DBAifwuSknT"
cheqd_non_base58_indy_style_char:
"did:cheqd:mainnet:TAwT8WVt0dz2DBAifwuSkn"
cheqd_invalid_uuid_style_id_1:
"did:cheqd:mainnet:de9786cd-ec53-458c-857c-9342cf264f8"
cheqd_invalid_uuid_style_id_2:
"did:cheqd:mainnet:de9786cd-ec53-458c-857c9342cf264f80"
cheqd_invalid_uuid_style_id_3:
"did:cheqd:mainnet:de9786cd-ec53-458c-857c9342cf2-64f80"
cheqd_non_alpha_uuid_style_char:
"did:cheqd:mainnet:qe9786cd-ec53-458c-857c-9342cf264f80"
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/misc/anoncreds_types/src/lib.rs | aries/misc/anoncreds_types/src/lib.rs | extern crate log;
#[macro_use]
extern crate serde;
#[cfg(test)]
#[macro_use]
extern crate serde_json;
#[doc(hidden)]
pub use anoncreds_clsignatures as cl;
#[macro_use]
mod error;
#[doc(hidden)]
pub use self::error::Result;
pub use self::error::{Error, ErrorKind};
pub mod utils;
pub mod data_types;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/misc/anoncreds_types/src/error.rs | aries/misc/anoncreds_types/src/error.rs | use std::{
error::Error as StdError,
fmt::{self, Display, Formatter},
};
use crate::cl::{Error as CryptoError, ErrorKind as CryptoErrorKind};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorKind {
Input,
InvalidState,
Unexpected,
ProofRejected,
ConversionError,
ValidationError,
}
impl ErrorKind {
#[must_use]
pub const fn as_str(&self) -> &'static str {
match self {
Self::Input => "Input error",
Self::InvalidState => "Invalid state",
Self::Unexpected => "Unexpected error",
Self::ProofRejected => "Proof rejected",
Self::ConversionError => "Conversion error",
Self::ValidationError => "Validation error",
}
}
}
impl Display for ErrorKind {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// The standard crate error type
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
pub cause: Option<Box<dyn StdError + Send + Sync + 'static>>,
pub message: Option<String>,
// backtrace (when supported)
}
impl Error {
pub fn from_msg<T: Into<String>>(kind: ErrorKind, msg: T) -> Self {
Self {
kind,
cause: None,
message: Some(msg.into()),
}
}
#[must_use]
#[inline]
pub const fn kind(&self) -> ErrorKind {
self.kind
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match (self.kind, &self.message) {
(ErrorKind::Input, None) => write!(f, "{}", self.kind),
(ErrorKind::Input, Some(msg)) => f.write_str(msg),
(kind, None) => write!(f, "{kind}"),
(kind, Some(msg)) => write!(f, "{kind}: {msg}"),
}?;
if let Some(ref source) = self.cause {
write!(f, " [{source}]")?;
}
Ok(())
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
self.cause
.as_ref()
.map(|err| unsafe { std::mem::transmute(&**err) })
}
}
impl PartialEq for Error {
fn eq(&self, other: &Self) -> bool {
self.kind == other.kind && self.message == other.message
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Self {
Self {
kind,
cause: None,
message: None,
}
}
}
impl From<CryptoError> for Error {
fn from(err: CryptoError) -> Self {
let message = err.to_string();
let kind = match err.kind() {
CryptoErrorKind::InvalidState => ErrorKind::InvalidState,
CryptoErrorKind::ProofRejected => ErrorKind::ProofRejected,
};
Self::from_msg(kind, message)
}
}
impl<M> From<(ErrorKind, M)> for Error
where
M: fmt::Display + Send + Sync + 'static,
{
fn from((kind, msg): (ErrorKind, M)) -> Self {
Self::from_msg(kind, msg.to_string())
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/misc/anoncreds_types/src/utils/validation.rs | aries/misc/anoncreds_types/src/utils/validation.rs | use once_cell::sync::Lazy;
use regex::Regex;
// TODO: stricten the URI regex.
// Right now everything after the first colon is allowed,
// we might want to restrict this
pub static URI_IDENTIFIER: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^[a-zA-Z0-9\+\-\.]+:.+$").unwrap());
/// base58 alpahet as defined in the [base58
/// specification](https://datatracker.ietf.org/doc/html/draft-msporny-base58#section-2) This is
/// used for legacy indy identifiers that we will keep supporting for backwards compatibility. This
/// might validate invalid identifiers if they happen to fall within the base58 alphabet, but there
/// is not much we can do about that.
pub static LEGACY_DID_IDENTIFIER: Lazy<Regex> =
Lazy::new(|| Regex::new("^[1-9A-HJ-NP-Za-km-z]{21,22}$").unwrap());
pub static LEGACY_SCHEMA_IDENTIFIER: Lazy<Regex> =
Lazy::new(|| Regex::new("^[1-9A-HJ-NP-Za-km-z]{21,22}:2:.+:[0-9.]+$").unwrap());
pub static LEGACY_CRED_DEF_IDENTIFIER: Lazy<Regex> = Lazy::new(|| {
Regex::new(
"^[1-9A-HJ-NP-Za-km-z]{21,22}:3:CL:(([1-9][0-9]*)|([a-zA-Z0-9]{21,22}:2:.+:[0-9.]+)):(.+)?\
$",
)
.unwrap()
});
pub fn is_uri_identifier(id: &str) -> bool {
URI_IDENTIFIER.captures(id).is_some()
}
#[macro_export]
macro_rules! invalid {
($($arg:tt)+) => {
$crate::error::Error::from_msg($crate::ErrorKind::ConversionError, format!($($arg)+))
};
}
/// Trait for data types which need validation after being loaded from external sources
/// TODO: this should not default to Ok(())
pub trait Validatable {
fn validate(&self) -> Result<(), crate::error::Error> {
Ok(())
}
}
#[cfg(test)]
mod test_identifiers {
use super::*;
#[test]
fn should_validate_valid_identifiers() {
let valid_uri_identifier = "mock:uri";
let valid_legacy_schema_identifier = "DXoTtQJNtXtiwWaZAK3rB1:2:example:1.0";
let valid_legacy_cred_def_identifier = "DXoTtQJNtXtiwWaZAK3rB1:3:CL:98153:default";
let valid_legacy_did_identifier = "DXoTtQJNtXtiwWaZAK3rB1";
assert!(URI_IDENTIFIER.captures(valid_uri_identifier).is_some());
assert!(LEGACY_SCHEMA_IDENTIFIER
.captures(valid_legacy_schema_identifier)
.is_some());
assert!(LEGACY_CRED_DEF_IDENTIFIER
.captures(valid_legacy_cred_def_identifier)
.is_some());
assert!(LEGACY_DID_IDENTIFIER
.captures(valid_legacy_did_identifier)
.is_some());
}
#[test]
fn should_not_validate_invalid_identifiers() {
let invalid_uri_identifier = "DXoTtQJNtXtiwWaZAK3rB1";
let invalid_legacy_schema_identifier = "invalid:id";
let invalid_legacy_cred_def_identifier = "invalid:id";
let invalid_legacy_did_identifier = "invalid:id";
assert!(URI_IDENTIFIER.captures(invalid_uri_identifier).is_none());
assert!(LEGACY_DID_IDENTIFIER
.captures(invalid_legacy_schema_identifier)
.is_none());
assert!(LEGACY_CRED_DEF_IDENTIFIER
.captures(invalid_legacy_cred_def_identifier)
.is_none());
assert!(LEGACY_DID_IDENTIFIER
.captures(invalid_legacy_did_identifier)
.is_none());
assert!(LEGACY_SCHEMA_IDENTIFIER
.captures("DXoTtQJNtXtiwWaZAK3rB1:3:example:1.0")
.is_none());
assert!(LEGACY_CRED_DEF_IDENTIFIER
.captures("DXoTtQJNtXtiwWaZAK3rB1:4:CL:98153:default")
.is_none());
}
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/misc/anoncreds_types/src/utils/mod.rs | aries/misc/anoncreds_types/src/utils/mod.rs | /// VCX utility additon
pub mod conversions;
pub mod query;
pub mod validation;
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/misc/anoncreds_types/src/utils/query.rs | aries/misc/anoncreds_types/src/utils/query.rs | use std::string;
use serde::{
de,
ser::{Serialize, Serializer},
Deserialize, Deserializer,
};
use serde_json::{self, json, Value as JsonValue};
/// An abstract query representation over a key and value type
#[derive(Debug, Hash, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum AbstractQuery<K, V> {
/// Logical AND of multiple clauses
And(Vec<Self>),
/// Logical OR of multiple clauses
Or(Vec<Self>),
/// Negation of a clause
Not(Box<Self>),
/// Equality comparison for a field value
Eq(K, V),
/// Inequality comparison for a field value
Neq(K, V),
/// Greater-than comparison for a field value
Gt(K, V),
/// Greater-than-or-equal comparison for a field value
Gte(K, V),
/// Less-than comparison for a field value
Lt(K, V),
/// Less-than-or-equal comparison for a field value
Lte(K, V),
/// SQL 'LIKE'-compatible string comparison for a field value
Like(K, V),
/// Match one of multiple field values in a set
In(K, Vec<V>),
/// Match any non-null field value of the given field names
Exist(Vec<K>),
}
impl<K, V> Default for AbstractQuery<K, V> {
fn default() -> Self {
Self::And(Vec::new())
}
}
/// A concrete query implementation with String keys and values
pub type Query = AbstractQuery<String, String>;
impl<K, V> AbstractQuery<K, V> {
/// Perform basic query clause optimization
pub fn optimise(self) -> Option<Self> {
match self {
Self::Not(boxed_query) => match boxed_query.optimise() {
None => None,
Some(Self::Not(nested_query)) => Some(*nested_query),
Some(other) => Some(Self::Not(Box::new(other))),
},
Self::And(subqueries) => {
let mut subqueries: Vec<Self> =
subqueries.into_iter().filter_map(Self::optimise).collect();
match subqueries.len() {
0 => None,
1 => Some(subqueries.remove(0)),
_ => Some(Self::And(subqueries)),
}
}
Self::Or(subqueries) => {
let mut subqueries: Vec<Self> =
subqueries.into_iter().filter_map(Self::optimise).collect();
match subqueries.len() {
0 => None,
1 => Some(subqueries.remove(0)),
_ => Some(Self::Or(subqueries)),
}
}
Self::In(key, mut targets) if targets.len() == 1 => {
Some(Self::Eq(key, targets.remove(0)))
}
other => Some(other),
}
}
pub fn get_name(&self) -> Vec<&K> {
match self {
Self::And(subqueries) | Self::Or(subqueries) => {
subqueries.iter().flat_map(Self::get_name).collect()
}
Self::Exist(subquery_names) => subquery_names
.to_owned()
.iter()
.map(|s| s.to_owned())
.collect(),
Self::Not(boxed_query) => boxed_query.get_name(),
Self::Eq(tag_name, _)
| Self::Neq(tag_name, _)
| Self::Gt(tag_name, _)
| Self::Gte(tag_name, _)
| Self::Lt(tag_name, _)
| Self::Lte(tag_name, _)
| Self::Like(tag_name, _)
| Self::In(tag_name, _) => vec![tag_name],
}
}
/// Perform a transformation on all field names in query clauses
pub fn map_names<RK, E>(
self,
mut f: impl FnMut(K) -> Result<RK, E>,
) -> Result<AbstractQuery<RK, V>, E> {
self.map(&mut f, &mut |_k, v| Ok(v))
}
/// Perform a transformation on all field values in query clauses
pub fn map_values<RV, E>(
self,
mut f: impl FnMut(&K, V) -> Result<RV, E>,
) -> Result<AbstractQuery<K, RV>, E> {
self.map(&mut |k| Ok(k), &mut f)
}
/// Transform all query clauses using field name and value conversions
pub fn map<RK, RV, KF, VF, E>(
self,
kf: &mut KF,
vf: &mut VF,
) -> Result<AbstractQuery<RK, RV>, E>
where
KF: FnMut(K) -> Result<RK, E>,
VF: FnMut(&K, V) -> Result<RV, E>,
{
match self {
Self::Eq(tag_name, tag_value) => {
let tag_value = vf(&tag_name, tag_value)?;
Ok(AbstractQuery::<RK, RV>::Eq(kf(tag_name)?, tag_value))
}
Self::Neq(tag_name, tag_value) => {
let tag_value = vf(&tag_name, tag_value)?;
Ok(AbstractQuery::<RK, RV>::Neq(kf(tag_name)?, tag_value))
}
Self::Gt(tag_name, tag_value) => {
let tag_value = vf(&tag_name, tag_value)?;
Ok(AbstractQuery::<RK, RV>::Gt(kf(tag_name)?, tag_value))
}
Self::Gte(tag_name, tag_value) => {
let tag_value = vf(&tag_name, tag_value)?;
Ok(AbstractQuery::<RK, RV>::Gte(kf(tag_name)?, tag_value))
}
Self::Lt(tag_name, tag_value) => {
let tag_value = vf(&tag_name, tag_value)?;
Ok(AbstractQuery::<RK, RV>::Lt(kf(tag_name)?, tag_value))
}
Self::Lte(tag_name, tag_value) => {
let tag_value = vf(&tag_name, tag_value)?;
Ok(AbstractQuery::<RK, RV>::Lte(kf(tag_name)?, tag_value))
}
Self::Like(tag_name, tag_value) => {
let tag_value = vf(&tag_name, tag_value)?;
Ok(AbstractQuery::<RK, RV>::Like(kf(tag_name)?, tag_value))
}
Self::In(tag_name, tag_values) => {
let tag_values = tag_values
.into_iter()
.map(|value| vf(&tag_name, value))
.collect::<Result<Vec<_>, E>>()?;
Ok(AbstractQuery::<RK, RV>::In(kf(tag_name)?, tag_values))
}
Self::Exist(tag_names) => Ok(AbstractQuery::<RK, RV>::Exist(
tag_names.into_iter().try_fold(vec![], |mut v, tag_name| {
v.push(kf(tag_name)?);
Result::<_, E>::Ok(v)
})?,
)),
Self::And(subqueries) => {
let subqueries = subqueries
.into_iter()
.map(|query| query.map(kf, vf))
.collect::<Result<Vec<_>, E>>()?;
Ok(AbstractQuery::<RK, RV>::And(subqueries))
}
Self::Or(subqueries) => {
let subqueries = subqueries
.into_iter()
.map(|query| query.map(kf, vf))
.collect::<Result<Vec<_>, E>>()?;
Ok(AbstractQuery::<RK, RV>::Or(subqueries))
}
Self::Not(boxed_query) => Ok(AbstractQuery::<RK, RV>::Not(Box::new(
boxed_query.map(kf, vf)?,
))),
}
}
}
impl<K, V> Serialize for AbstractQuery<K, V>
where
for<'a> &'a K: Into<String>,
V: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.to_value().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Query {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let v = JsonValue::deserialize(deserializer)?;
match v {
JsonValue::Object(map) => parse_query(map).map_err(de::Error::missing_field),
JsonValue::Array(array) => {
// cast old restrictions format to wql
let mut res: Vec<JsonValue> = Vec::new();
for sub_query in array {
let sub_query: serde_json::Map<String, JsonValue> = sub_query
.as_object()
.ok_or_else(|| de::Error::custom("Restriction is invalid"))?
.clone()
.into_iter()
.filter(|(_, v)| !v.is_null())
.collect();
if !sub_query.is_empty() {
res.push(JsonValue::Object(sub_query));
}
}
let mut map = serde_json::Map::new();
map.insert("$or".to_string(), JsonValue::Array(res));
parse_query(map).map_err(de::Error::custom)
}
_ => Err(de::Error::missing_field(
"Restriction must be either object or array",
)),
}
}
}
impl<K, V> AbstractQuery<K, V>
where
for<'a> &'a K: Into<String>,
V: Serialize,
{
fn to_value(&self) -> JsonValue {
match self {
Self::Eq(ref tag_name, ref tag_value) => json!({ tag_name: tag_value }),
Self::Neq(ref tag_name, ref tag_value) => json!({tag_name: {"$neq": tag_value}}),
Self::Gt(ref tag_name, ref tag_value) => json!({tag_name: {"$gt": tag_value}}),
Self::Gte(ref tag_name, ref tag_value) => json!({tag_name: {"$gte": tag_value}}),
Self::Lt(ref tag_name, ref tag_value) => json!({tag_name: {"$lt": tag_value}}),
Self::Lte(ref tag_name, ref tag_value) => json!({tag_name: {"$lte": tag_value}}),
Self::Like(ref tag_name, ref tag_value) => json!({tag_name: {"$like": tag_value}}),
Self::In(ref tag_name, ref tag_values) => json!({tag_name: {"$in":tag_values}}),
Self::Exist(ref tag_names) => {
json!({ "$exist": tag_names.iter().map(Into::into).collect::<Vec<String>>() })
}
Self::And(ref queries) => {
if queries.is_empty() {
json!({})
} else {
json!({
"$and": queries.iter().map(Self::to_value).collect::<Vec<JsonValue>>()
})
}
}
Self::Or(ref queries) => {
if queries.is_empty() {
json!({})
} else {
json!({
"$or": queries.iter().map(Self::to_value).collect::<Vec<JsonValue>>()
})
}
}
Self::Not(ref query) => json!({"$not": query.to_value()}),
}
}
}
#[allow(clippy::to_string_trait_impl)] // mimicks upstream anoncreds-rs, allow this to avoid divergence
impl string::ToString for Query {
fn to_string(&self) -> String {
self.to_value().to_string()
}
}
fn parse_query(map: serde_json::Map<String, JsonValue>) -> Result<Query, &'static str> {
let mut operators: Vec<Query> = Vec::new();
for (key, value) in map {
if let Some(operator_) = parse_operator(key, value)? {
operators.push(operator_);
}
}
let query = if operators.len() == 1 {
operators.remove(0)
} else {
Query::And(operators)
};
Ok(query)
}
fn parse_operator(key: String, value: JsonValue) -> Result<Option<Query>, &'static str> {
match (key.as_str(), value) {
("$and", JsonValue::Array(values)) => {
if values.is_empty() {
Ok(None)
} else {
let operators: Vec<Query> = parse_list_operators(values)?;
Ok(Some(Query::And(operators)))
}
}
("$and", _) => Err("$and must be array of JSON objects"),
("$or", JsonValue::Array(values)) => {
if values.is_empty() {
Ok(None)
} else {
let operators: Vec<Query> = parse_list_operators(values)?;
Ok(Some(Query::Or(operators)))
}
}
("$or", _) => Err("$or must be array of JSON objects"),
("$not", JsonValue::Object(map)) => {
let operator = parse_query(map)?;
Ok(Some(Query::Not(Box::new(operator))))
}
("$not", _) => Err("$not must be JSON object"),
("$exist", JsonValue::String(key)) => Ok(Some(Query::Exist(vec![key]))),
("$exist", JsonValue::Array(keys)) => {
if keys.is_empty() {
Ok(None)
} else {
let mut ks = vec![];
for key in keys {
if let JsonValue::String(key) = key {
ks.push(key);
} else {
return Err("$exist must be used with a string or array of strings");
}
}
Ok(Some(Query::Exist(ks)))
}
}
("$exist", _) => Err("$exist must be used with a string or array of strings"),
(_, JsonValue::String(value)) => Ok(Some(Query::Eq(key, value))),
(_, JsonValue::Object(map)) => {
if map.len() == 1 {
let (operator_name, value) = map.into_iter().next().unwrap();
parse_single_operator(operator_name.as_str(), key, value).map(Some)
} else {
Err("value must be JSON object of length 1")
}
}
(_, _) => Err("Unsupported value"),
}
}
fn parse_list_operators(operators: Vec<JsonValue>) -> Result<Vec<Query>, &'static str> {
let mut out_operators: Vec<Query> = Vec::with_capacity(operators.len());
for value in operators {
if let JsonValue::Object(map) = value {
let subquery = parse_query(map)?;
out_operators.push(subquery);
} else {
return Err("operator must be array of JSON objects");
}
}
Ok(out_operators)
}
fn parse_single_operator(
operator_name: &str,
key: String,
value: JsonValue,
) -> Result<Query, &'static str> {
match (operator_name, value) {
("$neq", JsonValue::String(value_)) => Ok(Query::Neq(key, value_)),
("$neq", _) => Err("$neq must be used with string"),
("$gt", JsonValue::String(value_)) => Ok(Query::Gt(key, value_)),
("$gt", _) => Err("$gt must be used with string"),
("$gte", JsonValue::String(value_)) => Ok(Query::Gte(key, value_)),
("$gte", _) => Err("$gte must be used with string"),
("$lt", JsonValue::String(value_)) => Ok(Query::Lt(key, value_)),
("$lt", _) => Err("$lt must be used with string"),
("$lte", JsonValue::String(value_)) => Ok(Query::Lte(key, value_)),
("$lte", _) => Err("$lte must be used with string"),
("$like", JsonValue::String(value_)) => Ok(Query::Like(key, value_)),
("$like", _) => Err("$like must be used with string"),
("$in", JsonValue::Array(values)) => {
let mut target_values: Vec<String> = Vec::with_capacity(values.len());
for v in values {
if let JsonValue::String(s) = v {
target_values.push(s);
} else {
return Err("$in must be used with array of strings");
}
}
Ok(Query::In(key, target_values))
}
("$in", _) => Err("$in must be used with array of strings"),
(_, _) => Err("Unknown operator"),
}
}
#[cfg(test)]
mod tests {
use rand::{distr::Alphanumeric, rng, Rng};
use serde_json::json;
use super::*;
fn _random_string(len: usize) -> String {
String::from_utf8(rng().sample_iter(&Alphanumeric).take(len).collect()).unwrap()
}
/// parse
#[test]
fn test_simple_operator_empty_json_parse() {
let json = "{}";
let query: Query = ::serde_json::from_str(json).unwrap();
let expected = Query::And(vec![]);
assert_eq!(query, expected);
}
#[test]
fn test_simple_operator_explicit_empty_and_parse() {
let json = r#"{"$and":[]}"#;
let query: Query = ::serde_json::from_str(json).unwrap();
let expected = Query::And(vec![]);
assert_eq!(query, expected);
}
#[test]
fn test_simple_operator_empty_or_parse() {
let json = r#"{"$or":[]}"#;
let query: Query = ::serde_json::from_str(json).unwrap();
let expected = Query::And(vec![]);
assert_eq!(query, expected);
}
#[test]
fn test_simple_operator_empty_not_parse() {
let json = r#"{"$not":{}}"#;
let query: Query = ::serde_json::from_str(json).unwrap();
let expected = Query::Not(Box::new(Query::And(vec![])));
assert_eq!(query, expected);
}
#[test]
fn test_simple_operator_eq_plaintext_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"{name1}":"{value1}"}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::Eq(name1, value1);
assert_eq!(query, expected);
}
#[test]
fn test_simple_operator_neq_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"{name1}":{{"$neq":"{value1}"}}}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::Neq(name1, value1);
assert_eq!(query, expected);
}
#[test]
fn test_simple_operator_gt_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"{name1}":{{"$gt":"{value1}"}}}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::Gt(name1, value1);
assert_eq!(query, expected);
}
#[test]
fn test_simple_operator_gte_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"{name1}":{{"$gte":"{value1}"}}}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::Gte(name1, value1);
assert_eq!(query, expected);
}
#[test]
fn test_simple_operator_lt_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"{name1}":{{"$lt":"{value1}"}}}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::Lt(name1, value1);
assert_eq!(query, expected);
}
#[test]
fn test_simple_operator_lte_plaintext_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"{name1}":{{"$lte":"{value1}"}}}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::Lte(name1, value1);
assert_eq!(query, expected);
}
#[test]
fn test_simple_operator_like_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"{name1}":{{"$like":"{value1}"}}}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::Like(name1, value1);
assert_eq!(query, expected);
}
#[test]
fn test_simple_operator_in_plaintext_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"{name1}":{{"$in":["{value1}"]}}}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::In(name1, vec![value1]);
assert_eq!(query, expected);
}
#[test]
fn test_simple_operator_in_plaintexts_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let value2 = _random_string(10);
let value3 = _random_string(10);
let json = format!(r#"{{"{name1}":{{"$in":["{value1}","{value2}","{value3}"]}}}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::In(name1, vec![value1, value2, value3]);
assert_eq!(query, expected);
}
#[test]
fn test_exist_parse_string() {
let name1 = _random_string(10);
let json = format!(r#"{{"$exist":"{name1}"}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::Exist(vec![name1]);
assert_eq!(query, expected);
}
#[test]
fn test_exist_parse_array() {
let name1 = _random_string(10);
let name2 = _random_string(10);
let json = format!(r#"{{"$exist":["{name1}","{name2}"]}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::Exist(vec![name1, name2]);
assert_eq!(query, expected);
}
#[test]
fn test_and_exist() {
let name1 = _random_string(10);
let name2 = _random_string(10);
let json = format!(r#"{{"$and":[{{"$exist":"{name1}"}},{{"$exist":"{name2}"}}]}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![Query::Exist(vec![name1]), Query::Exist(vec![name2])]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_one_eq_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"$and":[{{"{name1}":"{value1}"}}]}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![Query::Eq(name1, value1)]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_one_neq_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"$and":[{{"{name1}":{{"$neq":"{value1}"}}}}]}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![Query::Neq(name1, value1)]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_one_gt_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"$and":[{{"{name1}":{{"$gt":"{value1}"}}}}]}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![Query::Gt(name1, value1)]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_one_gte_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"$and":[{{"{name1}":{{"$gte":"{value1}"}}}}]}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![Query::Gte(name1, value1)]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_one_lt_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"$and":[{{"{name1}":{{"$lt":"{value1}"}}}}]}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![Query::Lt(name1, value1)]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_one_lte_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"$and":[{{"{name1}":{{"$lte":"{value1}"}}}}]}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![Query::Lte(name1, value1)]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_one_like_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"$and":[{{"{name1}":{{"$like":"{value1}"}}}}]}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![Query::Like(name1, value1)]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_one_in_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"$and":[{{"{name1}":{{"$in":["{value1}"]}}}}]}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![Query::In(name1, vec![value1])]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_one_not_eq_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let json = format!(r#"{{"$and":[{{"$not":{{"{name1}":"{value1}"}}}}]}}"#);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![Query::Not(Box::new(Query::Eq(name1, value1)))]);
assert_eq!(query, expected);
}
#[test]
fn test_short_and_with_multiple_eq_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let name2 = _random_string(10);
let value2 = _random_string(10);
let name3 = _random_string(10);
let value3 = _random_string(10);
let json =
format!(r#"{{"{name1}":"{value1}","{name2}":"{value2}","{name3}":"{value3}"}}"#,);
let query: Query = ::serde_json::from_str(&json).unwrap();
let mut clauses = vec![
Query::Eq(name1, value1),
Query::Eq(name2, value2),
Query::Eq(name3, value3),
];
clauses.sort();
let expected = Query::And(clauses);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_multiple_eq_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let name2 = _random_string(10);
let value2 = _random_string(10);
let name3 = _random_string(10);
let value3 = _random_string(10);
let json = format!(
r#"{{"$and":[{{"{name1}":"{value1}"}},{{"{name2}":"{value2}"}},{{"{name3}":"{value3}"}}]}}"#,
);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![
Query::Eq(name1, value1),
Query::Eq(name2, value2),
Query::Eq(name3, value3),
]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_multiple_neq_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let name2 = _random_string(10);
let value2 = _random_string(10);
let name3 = _random_string(10);
let value3 = _random_string(10);
let json = format!(
r#"{{"$and":[{{"{name1}":{{"$neq":"{value1}"}}}},{{"{name2}":{{"$neq":"{value2}"}}}},{{"{name3}":{{"$neq":"{value3}"}}}}]}}"#,
);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![
Query::Neq(name1, value1),
Query::Neq(name2, value2),
Query::Neq(name3, value3),
]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_multiple_gt_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let name2 = _random_string(10);
let value2 = _random_string(10);
let name3 = _random_string(10);
let value3 = _random_string(10);
let json = format!(
r#"{{"$and":[{{"{name1}":{{"$gt":"{value1}"}}}},{{"{name2}":{{"$gt":"{value2}"}}}},{{"{name3}":{{"$gt":"{value3}"}}}}]}}"#,
);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![
Query::Gt(name1, value1),
Query::Gt(name2, value2),
Query::Gt(name3, value3),
]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_multiple_gte_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let name2 = _random_string(10);
let value2 = _random_string(10);
let name3 = _random_string(10);
let value3 = _random_string(10);
let json = format!(
r#"{{"$and":[{{"{name1}":{{"$gte":"{value1}"}}}},{{"{name2}":{{"$gte":"{value2}"}}}},{{"{name3}":{{"$gte":"{value3}"}}}}]}}"#,
);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![
Query::Gte(name1, value1),
Query::Gte(name2, value2),
Query::Gte(name3, value3),
]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_multiple_lt_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let name2 = _random_string(10);
let value2 = _random_string(10);
let name3 = _random_string(10);
let value3 = _random_string(10);
let json = format!(
r#"{{"$and":[{{"{name1}":{{"$lt":"{value1}"}}}},{{"{name2}":{{"$lt":"{value2}"}}}},{{"{name3}":{{"$lt":"{value3}"}}}}]}}"#,
);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![
Query::Lt(name1, value1),
Query::Lt(name2, value2),
Query::Lt(name3, value3),
]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_multiple_lte_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let name2 = _random_string(10);
let value2 = _random_string(10);
let name3 = _random_string(10);
let value3 = _random_string(10);
let json = format!(
r#"{{"$and":[{{"{name1}":{{"$lte":"{value1}"}}}},{{"{name2}":{{"$lte":"{value2}"}}}},{{"{name3}":{{"$lte":"{value3}"}}}}]}}"#,
);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![
Query::Lte(name1, value1),
Query::Lte(name2, value2),
Query::Lte(name3, value3),
]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_multiple_like_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let name2 = _random_string(10);
let value2 = _random_string(10);
let name3 = _random_string(10);
let value3 = _random_string(10);
let json = format!(
r#"{{"$and":[{{"{name1}":{{"$like":"{value1}"}}}},{{"{name2}":{{"$like":"{value2}"}}}},{{"{name3}":{{"$like":"{value3}"}}}}]}}"#,
);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![
Query::Like(name1, value1),
Query::Like(name2, value2),
Query::Like(name3, value3),
]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_multiple_in_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let name2 = _random_string(10);
let value2 = _random_string(10);
let name3 = _random_string(10);
let value3 = _random_string(10);
let json = format!(
r#"{{"$and":[{{"{name1}":{{"$in":["{value1}"]}}}},{{"{name2}":{{"$in":["{value2}"]}}}},{{"{name3}":{{"$in":["{value3}"]}}}}]}}"#,
);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![
Query::In(name1, vec![value1]),
Query::In(name2, vec![value2]),
Query::In(name3, vec![value3]),
]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_multiple_not_eq_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let name2 = _random_string(10);
let value2 = _random_string(10);
let name3 = _random_string(10);
let value3 = _random_string(10);
let json = format!(
r#"{{"$and":[{{"$not":{{"{name1}":"{value1}"}}}},{{"$not":{{"{name2}":"{value2}"}}}},{{"$not":{{"{name3}":"{value3}"}}}}]}}"#,
);
let query: Query = ::serde_json::from_str(&json).unwrap();
let expected = Query::And(vec![
Query::Not(Box::new(Query::Eq(name1, value1))),
Query::Not(Box::new(Query::Eq(name2, value2))),
Query::Not(Box::new(Query::Eq(name3, value3))),
]);
assert_eq!(query, expected);
}
#[test]
fn test_and_with_multiple_mixed_parse() {
let name1 = _random_string(10);
let value1 = _random_string(10);
let name2 = _random_string(10);
let value2 = _random_string(10);
let name3 = _random_string(10);
let value3 = _random_string(10);
let name4 = _random_string(10);
let value4 = _random_string(10);
let name5 = _random_string(10);
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | true |
openwallet-foundation/vcx | https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/aries/misc/anoncreds_types/src/utils/conversions.rs | aries/misc/anoncreds_types/src/utils/conversions.rs | use bitvec::bitvec;
use crate::data_types::{
identifiers::{issuer_id::IssuerId, rev_reg_def_id::RevocationRegistryDefinitionId},
ledger::{rev_reg_delta::RevocationRegistryDeltaValue, rev_status_list::RevocationStatusList},
};
/// Converts from a [RevocationRegistryDeltaValue] into a completed [RevocationStatusList]
/// (newer format).
///
/// NOTE: this conversion only works if the delta was calculated from START (timestamp 0/None)
/// to `timestamp`.
pub fn from_revocation_registry_delta_to_revocation_status_list(
delta: &RevocationRegistryDeltaValue,
timestamp: u64,
rev_reg_id: &RevocationRegistryDefinitionId,
max_cred_num: usize,
issuer_id: IssuerId,
) -> Result<RevocationStatusList, crate::Error> {
// no way to derive this value here. So we assume true, as false (ISSAUNCE_ON_DEAMAND) is not
// recomended by anoncreds: https://hyperledger.github.io/anoncreds-spec/#anoncreds-issuer-setup-with-revocation
let issuance_by_default = true;
let default_state = if issuance_by_default { 0 } else { 1 };
let mut revocation_list = bitvec![default_state; max_cred_num];
let revocation_len = revocation_list.len();
for issued in &delta.issued {
if revocation_len <= *issued as usize {
return Err(crate::Error::from_msg(
crate::ErrorKind::ConversionError,
format!(
"Error whilst constructing a revocation status list from the ledger's delta. \
Ledger delta reported an issuance for cred_rev_id '{issued}', but the \
revocation_list max size is {revocation_len}"
),
));
}
revocation_list.insert(*issued as usize, false);
}
for revoked in &delta.revoked {
if revocation_len <= *revoked as usize {
return Err(crate::Error::from_msg(
crate::ErrorKind::ConversionError,
format!(
"Error whilst constructing a revocation status list from the ledger's delta. \
Ledger delta reported an revocation for cred_rev_id '{revoked}', but the \
revocation_list max size is {revocation_len}"
),
));
}
revocation_list.insert(*revoked as usize, true);
}
let accum = delta.accum.into();
RevocationStatusList::new(
Some(&rev_reg_id.to_string()),
issuer_id,
revocation_list,
Some(accum),
Some(timestamp),
)
}
| rust | Apache-2.0 | 2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7 | 2026-01-04T20:24:59.602734Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.