open-standards/smart-byte/smart-byte-rs/crates/smart-byte-didcomm/src/state.rs
Transaction Science 6575ff1eb7 Ingest batch 3: 9 more crates across openpay / smart-byte / eoc
openpay/ (+3 crates)
  op-bnpl/        Affirm + Klarna + Afterpay/Clearpay rails. Full lifecycle
                  typestate (Initiated→Approved→Captured→Settled→Refunded).
                  Per-provider sandbox+production base URLs, regions (NA/EU/OC
                  for Klarna; US/AuNz/Gb/Ca/Eu for Afterpay). HMAC-SHA256
                  webhook verification with constant-time compare. 61 tests.
  op-batch/       NACHA ACH (94-char records, PPD/CCD/WEB/TEL/CTX, R01-R99
                  return codes, Same-Day ACH cutoffs); SEPA pain.001.001.09
                  (CT) + pain.008.001.08 (DD) with SCT-Inst flagging; Fedwire
                  MT103/MT202/CHIPS + pacs.008.001.12 / pacs.009.001.10 +
                  UETR; Bacs Standard 18. Per-rail cutoff scheduler. Exception
                  taxonomy unified across rails. 51 tests.
  op-screening/   OFAC SDN + EU consolidated + UN consolidated + HMT UK
                  consolidated + Australia DFAT + Canada SEMA + Japan MOF.
                  Levenshtein + Jaro-Winkler + Soundex + Metaphone + token
                  Jaccard scoring. Unicode NFKD normalisation + Cyrillic /
                  Arabic transliteration. Ed25519-signed BLAKE3-chained
                  audit log. BSA helpers: CTR + SAR pattern detection
                  (structuring, round-dollar, rapid-in-out). 43 tests.

smart-byte/smart-byte-rs/ (+3 crates)
  smart-byte-bbs/      BBS+ signatures (IETF draft-irtf-cfrg-bbs-signatures-08).
                       BLS12-381 keys, signatures, disclosure proofs with
                       cryptographic unlinkability. bbs-2023 Data Integrity
                       cryptosuite. AnonCreds-shaped link secrets +
                       predicate proofs. SecretKey zeroize-on-drop. 49 tests.
  smart-byte-didcomm/  DIDComm v2 messaging per DIF spec. Pack-encrypted
                       (ECDH-1PU + ECDH-ES via X25519), pack-signed (JWS),
                       pack-plaintext. Aries protocols: issue-credential v3,
                       present-proof v3, basic-message, trust-ping, discover-
                       features, out-of-band, coordinate-mediation, message-
                       pickup. Mediator role with pluggable storage. 23 tests.
  smart-byte-mdl/      ISO/IEC 18013-5 mobile driver's licence + 18013-7
                       online presentment. mDoc + MSO with salted-hash
                       selective disclosure (per item; SHA-256 digest tree).
                       org.iso.18013.5.1 namespace + AAMVA add-on. ES256
                       device-auth + issuer-auth. QR-code device-engagement
                       scaffolding. 28 tests.

eoc/eoc-rs/ (+3 crates)
  eoc-local/      Local-inference backends behind one NeuralBackend:
                  llama.cpp (GGUF, Q4/Q5/Q6/Q8/F16/F32 quantisation),
                  MLX (Apple Silicon, feature-gated), MLC-LLM (TVM, feature-
                  gated marker), ONNX Runtime. GGUF file-format reader.
                  HuggingFace tokenizers. Greedy / top-k / top-p / temperature /
                  Mirostat samplers. Model registry scanning ~/.eoc/models/.
                  Joule attribution via eoc-meter. 39 tests.
  eoc-rerank/     BM25 sparse + HNSW dense + RRF + min-max hybrid fusion.
                  Cohere v3.5 + Voyage v2 + bge-reranker v2-m3 + ms-marco
                  MiniLM + ColBERT v2 rerankers. Two-stage pipeline:
                  retrieve top-K hybrid → cross-encoder rerank → top-N.
                  KV-stage recovery shim into the cascade. 31 tests.
  eoc-eval/       15 canonical eval harnesses: MMLU, MMLU-Pro, GPQA,
                  HumanEval (pass@1 with python3 sandbox), BBH, IFEval (25
                  verifiable constraints), AlpacaEval, AGIEval, HellaSwag,
                  ARC (Easy + Challenge), TruthfulQA (MC1+MC2), BoolQ,
                  GSM8K, MATH (boxed-answer equivalence), Winogrande. Real
                  questions in BuiltinSamples. EvalRunner emits joules-per-
                  correct alongside accuracy. 49 tests.

Quality:
- cargo check across all three workspaces: clean
- cargo clippy --all-targets -- -D warnings on every new crate: clean
- 374 new tests, 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-24 01:09:35 -04:00

153 lines
4.8 KiB
Rust

//! Connection abstractions and replay-protection helpers.
//!
//! A [`Connection`] is an asynchronous bidirectional channel between two
//! DIDs. The trait is intentionally minimal — concrete transports
//! (HTTPS, websocket, message-pickup-via-mediator) implement it. For
//! tests and in-process flows the [`InMemoryConnection`] uses an
//! `mpsc` pair.
use std::collections::HashSet;
use std::sync::Arc;
use async_trait::async_trait;
use smart_byte_did::Did;
use tokio::sync::Mutex;
use tokio::sync::mpsc;
use crate::error::DidcommError;
use crate::message::DidcommMessage;
/// An asynchronous DIDComm connection between two DIDs.
#[async_trait]
pub trait Connection: Send + Sync {
/// Connection id (locally unique).
fn id(&self) -> &str;
/// Their DID.
fn theirs(&self) -> &Did;
/// Our DID.
fn ours(&self) -> &Did;
/// Send a message to the other party.
async fn send(&self, msg: DidcommMessage) -> Result<(), DidcommError>;
/// Receive the next message from the other party. Blocks until one
/// is available or the connection is closed.
async fn receive(&self) -> Result<DidcommMessage, DidcommError>;
}
/// In-memory connection backed by a pair of `mpsc` channels. Useful for
/// tests and for in-process agent-to-agent flows.
pub struct InMemoryConnection {
/// Locally unique id.
pub id: String,
/// Our DID.
pub ours: Did,
/// Their DID.
pub theirs: Did,
outbox: mpsc::UnboundedSender<DidcommMessage>,
inbox: Arc<Mutex<mpsc::UnboundedReceiver<DidcommMessage>>>,
seen_ids: Arc<Mutex<HashSet<String>>>,
}
impl InMemoryConnection {
/// Construct a connected pair `(alice_side, bob_side)`.
pub fn pair(alice: Did, bob: Did) -> (Self, Self) {
let (atx, brx) = mpsc::unbounded_channel();
let (btx, arx) = mpsc::unbounded_channel();
let a = InMemoryConnection {
id: uuid::Uuid::new_v4().to_string(),
ours: alice.clone(),
theirs: bob.clone(),
outbox: atx,
inbox: Arc::new(Mutex::new(arx)),
seen_ids: Arc::new(Mutex::new(HashSet::new())),
};
let b = InMemoryConnection {
id: uuid::Uuid::new_v4().to_string(),
ours: bob,
theirs: alice,
outbox: btx,
inbox: Arc::new(Mutex::new(brx)),
seen_ids: Arc::new(Mutex::new(HashSet::new())),
};
(a, b)
}
}
#[async_trait]
impl Connection for InMemoryConnection {
fn id(&self) -> &str {
&self.id
}
fn theirs(&self) -> &Did {
&self.theirs
}
fn ours(&self) -> &Did {
&self.ours
}
async fn send(&self, msg: DidcommMessage) -> Result<(), DidcommError> {
self.outbox
.send(msg)
.map_err(|e| DidcommError::Internal(format!("send failed: {e}")))
}
async fn receive(&self) -> Result<DidcommMessage, DidcommError> {
let mut rx = self.inbox.lock().await;
let m = rx
.recv()
.await
.ok_or_else(|| DidcommError::Internal("connection closed".into()))?;
let mut seen = self.seen_ids.lock().await;
if !seen.insert(m.id.clone()) {
return Err(DidcommError::Replay(m.id));
}
Ok(m)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::protocols::trust_ping::{
PingBody, TrustPingKind, respond_to,
};
use crate::protocol::ProtocolMessage;
#[tokio::test]
async fn trust_ping_round_trip() {
let alice: Did = "did:example:alice".parse().unwrap();
let bob: Did = "did:example:bob".parse().unwrap();
let (a, b) = InMemoryConnection::pair(alice.clone(), bob.clone());
let ping = TrustPingKind::Ping(PingBody {
response_requested: true,
comment: None,
})
.to_message()
.from_did(alice)
.to_dids(vec![bob.clone()]);
a.send(ping.clone()).await.unwrap();
let recvd = b.receive().await.unwrap();
let resp = respond_to(&recvd);
b.send(resp).await.unwrap();
let pong = a.receive().await.unwrap();
match TrustPingKind::from_message(&pong).unwrap() {
TrustPingKind::PingResponse(_) => {}
_ => panic!("expected ping-response"),
}
}
#[tokio::test]
async fn replay_detected() {
let alice: Did = "did:example:alice".parse().unwrap();
let bob: Did = "did:example:bob".parse().unwrap();
let (a, b) = InMemoryConnection::pair(alice, bob);
let m = TrustPingKind::Ping(PingBody::default()).to_message();
a.send(m.clone()).await.unwrap();
b.receive().await.unwrap();
// Push the same id back into b's inbox.
a.send(m).await.unwrap();
let res = b.receive().await;
assert!(matches!(res, Err(DidcommError::Replay(_))));
}
}