open-standards/smart-byte/smart-byte-rs/crates/smart-byte-did/src/resolver.rs
Transaction Science 01d4ad9c7b Ingest batch 2: 9 new crates across openpay / smart-byte / eoc
openpay/ (+3 crates, ~8400 LOC, 162 tests)
  op-iso8583/         ISO 8583 messages for direct acquirer / card-network
                      connectivity. MTIs, primary+secondary bitmaps, full
                      DE catalogue, BCD/ASCII/EBCDIC/LLVAR/LLLVAR codecs,
                      five dialects (Visa Base I, Mastercard MDS, Amex GNS,
                      Discover, JCB), network-management messages
                      (sign-on/echo/cutover), DE 55 EMV TLV.
  op-mobile-wallets/  Apple Pay (ECDH-P256 + AES-256-GCM), Google Pay ECv2
                      (ECDH + HKDF + AES-256-CTR + HMAC), Samsung Pay. PAN
                      never leaves the decryption boundary as a String;
                      lands in VaultRef. No-PAN-leakage assertions per
                      wallet.
  op-routing/         Least-cost routing + MCC-aware routing + intelligent
                      retry / soft-decline recovery. 231-MCC catalogue.
                      Real ISO 8583 DE-39 soft/hard decline taxonomies.

smart-byte/smart-byte-rs/ (+3 crates, ~7100 LOC, 96 tests)
  smart-byte-vc/      W3C Verifiable Credentials 2.0: VCDM, presentations,
                      Data Integrity proofs (eddsa-jcs-2022), VC-JWT,
                      SD-JWT (selective disclosure), Bitstring Status
                      List 2021. Cargo-bridge maps VCs to Smart Byte
                      envelopes with SAID stability.
  smart-byte-did/     W3C DID resolution: did:key (Ed25519/P-256/secp256k1),
                      did:web (HTTPS), did:peer (numalgo 2+4), did:jwk,
                      did:ion (feature-gated stub). DID URL dereferencer.
  smart-byte-pq/      Post-quantum signatures: ML-DSA-44/65/87 (FIPS 204),
                      SLH-DSA across 12 parameter sets (FIPS 205), FN-DSA
                      (draft FIPS 206, feature-gated). Hybrid Ed25519 +
                      ML-DSA pattern for the transition. Secret-key
                      zeroize-on-drop.

eoc/eoc-rs/ (+3 crates, ~6450 LOC, 76 tests)
  eoc-vendor-api/     NeuralBackend implementations: Anthropic, OpenAI,
                      Google, Mistral, Cohere, Groq, Together, Fireworks.
                      SSE streaming. Prompt-caching where supported.
                      Joule estimates per published energy coefficient
                      (12-model curated table).
  eoc-embeddings/     21 embedding models behind one Embedder trait:
                      OpenAI v3 (3), Cohere v3 (3), Voyage (5), Mistral,
                      Jina, plus local ONNX (BGE x3, nomic, mxbai, GTE,
                      E5) behind 'local' feature. Matryoshka-style
                      dimension projection. Per-content-hash cache.
  eoc-route-learned/  RouteLLM-style matrix-factorisation router +
                      multinomial-logreg classifier + LinUCB / Thompson
                      bandits for online learning. LearnedCascade wraps
                      the rule-based cascade with a confidence-threshold
                      skip policy. Synthetic-eval accuracy: MF 0.935,
                      LogReg 0.980.

Quality:
- cargo check across all three workspaces: clean
- cargo clippy --all-targets -- -D warnings on every new crate: clean
- 334 new tests total; all passing
- #![forbid(unsafe_code)] across every new crate
- No unwrap/expect outside #[cfg(test)]

Rust 1.95.0 edition 2024 (inherited via root rust-toolchain.toml).
2026-05-23 18:12:24 -04:00

128 lines
4.7 KiB
Rust

//! Resolver trait and the [`UniversalResolver`] that dispatches by method.
use std::collections::HashMap;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use crate::did::{Did, DidMethod};
use crate::document::DidDocument;
use crate::error::DidError;
use crate::methods::{jwk::JwkResolver, key::KeyResolver, peer::PeerResolver, web::WebResolver};
#[cfg(feature = "ion")]
use crate::methods::ion::IonResolver;
/// W3C DID Resolution v1 result (DID Resolution § 7).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResolutionResult {
/// The resolved DID document, or `None` if the document was
/// deactivated or not found.
#[serde(rename = "didDocument", default)]
pub did_document: Option<DidDocument>,
/// Metadata about the resolution process itself.
#[serde(rename = "didResolutionMetadata", default)]
pub did_resolution_metadata: ResolutionMetadata,
/// Metadata about the document (created, updated, deactivated, etc.).
#[serde(rename = "didDocumentMetadata", default)]
pub did_document_metadata: DocumentMetadata,
}
/// Resolution metadata (DID Resolution § 7.1).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResolutionMetadata {
/// MIME content type of the document representation.
#[serde(rename = "contentType", skip_serializing_if = "Option::is_none", default)]
pub content_type: Option<String>,
/// Resolver-supplied error code (DID Resolution § 7.1.2).
#[serde(skip_serializing_if = "Option::is_none", default)]
pub error: Option<String>,
}
/// Document metadata (DID Resolution § 7.2).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DocumentMetadata {
/// ISO-8601 creation timestamp.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub created: Option<String>,
/// ISO-8601 last-update timestamp.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub updated: Option<String>,
/// `true` if the DID has been deactivated.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub deactivated: Option<bool>,
/// Version id, if the method versions documents.
#[serde(rename = "versionId", skip_serializing_if = "Option::is_none", default)]
pub version_id: Option<String>,
}
/// A method-specific resolver. Resolution is async because some methods
/// (notably `did:web`) involve network I/O.
#[async_trait]
pub trait Resolver: Send + Sync {
/// Resolve `did` to a [`ResolutionResult`].
async fn resolve(&self, did: &Did) -> Result<ResolutionResult, DidError>;
}
/// Universal resolver that dispatches to method-specific resolvers based
/// on `did.method`.
///
/// By default it knows about [`DidMethod::Key`], [`DidMethod::Web`],
/// [`DidMethod::Peer`] and [`DidMethod::Jwk`] (and [`DidMethod::Ion`]
/// when the `ion` feature is enabled). Custom resolvers can be
/// registered via [`UniversalResolver::register`].
pub struct UniversalResolver {
resolvers: HashMap<String, Box<dyn Resolver>>,
}
impl Default for UniversalResolver {
fn default() -> Self {
Self::new()
}
}
impl UniversalResolver {
/// Build a resolver with the built-in method resolvers wired up.
pub fn new() -> Self {
let mut resolvers: HashMap<String, Box<dyn Resolver>> = HashMap::new();
resolvers.insert("key".into(), Box::new(KeyResolver::new()));
resolvers.insert("web".into(), Box::new(WebResolver::new()));
resolvers.insert("peer".into(), Box::new(PeerResolver::new()));
resolvers.insert("jwk".into(), Box::new(JwkResolver::new()));
#[cfg(feature = "ion")]
resolvers.insert("ion".into(), Box::new(IonResolver::new()));
UniversalResolver { resolvers }
}
/// Build a resolver with no built-in methods registered.
pub fn empty() -> Self {
UniversalResolver {
resolvers: HashMap::new(),
}
}
/// Register (or replace) a resolver for a specific DID method name.
pub fn register(
&mut self,
method: impl Into<String>,
resolver: Box<dyn Resolver>,
) {
self.resolvers.insert(method.into(), resolver);
}
/// Look up the resolver for a method, if any.
pub fn resolver_for(&self, method: &DidMethod) -> Option<&dyn Resolver> {
self.resolvers.get(method.as_str()).map(|r| r.as_ref())
}
}
#[async_trait]
impl Resolver for UniversalResolver {
async fn resolve(&self, did: &Did) -> Result<ResolutionResult, DidError> {
let method_name = did.method.as_str();
let r = self.resolvers.get(method_name).ok_or_else(|| {
DidError::MethodNotSupported(method_name.to_string())
})?;
r.resolve(did).await
}
}