Integrate DIDComm for Rust

Integrate DIDComm v2.1 messaging into your Rust application using the Affinidi Messaging SDK.

This guide covers how to send and receive DIDComm messages in a Rust application using the Affinidi Messaging SDK. The SDK enables privacy-preserving, verifiable messaging between decentralised identifiers (DIDs) without relying on centralised intermediaries.

Key features

  • Implements the DIDComm v2.1 protocol.

  • Support for DIDComm Messaging Envelope types.

  • Connect and authenticate with different mediator services that follow the DIDComm v2.1 protocol.

Requirements

Required packages

PackageDescription
Affinidi Messaging - DIDComm for RustThe package for sending and receiving messages using the DIDComm protocol. It is designed to be used with the Affinidi Messaging SDK.
Affinidi Messaging SDKA Software Development Kit (SDK) to simplify the implementation of Affinidi Messaging into your application.
Affinidi Trust Development KitSimplifies development of privacy preserving solutions using decentralised identity and data sharing technologies.

Add them to your Cargo.toml, with the crates the examples use:

[dependencies]
affinidi-tdk = "0.36"
affinidi-messaging-sdk = "0.44"
affinidi-messaging-didcomm = "0.15"
serde_json = "1"
tokio = { version = "1", features = ["full"] }
uuid = { version = "1", features = ["v4"] }

Sample usage

The examples demonstrate how to construct, encrypt, and send messages according to the DIDComm Messaging spec. They follow the alice_bob example, where you can see the complete program.

Instantiate the TDK

Initialise the Trust Development Kit. It loads the mediator and the DIDs it uses, called profiles, from an environments.json file. For the file’s shape, see Hand-write environments.json.

let tdk = TDK::new(
    TDKConfig::builder()
        .with_environment_name(environment_name.clone())
        .build()?,
    None,
)
.await?;

let shared = tdk.get_shared_state();
let environment = shared.environment();
let atm = tdk.atm.clone().unwrap();

Activate profiles

Enable profiles needed for communication.

// Activate Alice profile
let tdk_alice = if let Some(alice) = environment.profiles().get("Alice") {
    tdk.add_profile(alice).await;
    alice
} else {
    return Err(ATMError::ConfigError(
        format!("Alice not found in Environment: {environment_name}").to_string(),
    ));
};

let atm_alice = atm
    .profile_add(&ATMProfile::from_tdk_profile(&atm, tdk_alice).await?, true)
    .await?;

let Ok(alice_info) = atm.trust_tasks().account_get(&atm_alice, None).await else {
    panic!("Alice account not found on mediator");
};
let alice_acl_mode = alice_info.acl.access_list_mode;

// Activate Bob profile
let tdk_bob = if let Some(bob) = environment.profiles().get("Bob") {
    tdk.add_profile(bob).await;
    bob
} else {
    return Err(ATMError::ConfigError(
        format!("Bob not found in Environment: {environment_name}").to_string(),
    ));
};

let atm_bob = atm
    .profile_add(&ATMProfile::from_tdk_profile(&atm, tdk_bob).await?, true)
    .await?;

let Ok(bob_info) = atm.trust_tasks().account_get(&atm_bob, None).await else {
    panic!("Bob account not found on mediator");
};
let bob_acl_mode = bob_info.acl.access_list_mode;

Add Sender DID to ACL (Access Control List)

When the recipient’s access list allows only listed senders (explicit allow), the recipient adds the sender’s DID before the sender’s messages can be delivered. The SDK sends this to the mediator as a messaging/access-list/update Trust Task. Its last two arguments are the DIDs to add and the DIDs to remove.

// Bob adds Alice to his allow list
if let Some(MediatorAclAccessListMode::ExplicitAllow) = bob_acl_mode {
    atm.trust_tasks()
        .access_list_update(
            &atm_bob,
            None,
            false,
            vec![alice_info.did.as_str().to_string()],
            vec![],
        )
        .await?;
}

Compose plaintext message

A plain text message is a simple JSON message with headers and a body.

let now = SystemTime::now()
    .duration_since(SystemTime::UNIX_EPOCH)
    .unwrap()
    .as_secs();

let msg = Message::build(
    Uuid::new_v4().to_string(),
    "Chatty Alice".to_string(),
    json!("Hello Bob!"),
)
.to(atm_bob.inner.did.clone())
.from(atm_alice.inner.did.clone())
.created_time(now)
.expires_time(now + 10)
.finalize();

let msg_id = msg.id.clone();

Pack DIDComm message

Encrypt the plaintext message to Bob, authenticated as Alice (authcrypt), so only Bob can read it and Bob can tell it came from Alice. The fourth argument, sign_by, isn’t used in this SDK version, so the message isn’t signed.

// Pack an authenticated, encrypted message from Alice to Bob
let packed_msg = atm
    .pack_encrypted(
        &msg,
        &atm_bob.inner.did,
        Some(&atm_alice.inner.did),
        Some(&atm_alice.inner.did),
    )
    .await?;

Send message

Wrap the packed message in a forward for Bob’s mediator, and send it.

// Wrap the message in a forward for Bob's mediator
let bobs_mediator_did = tdk_bob.mediator.to_owned().unwrap();

let (_forward_id, forward_msg) = atm
    .routing()
    .forward_message(
        &atm_alice,
        false,
        &packed_msg.0,
        &bobs_mediator_did,
        &atm_bob.inner.did,
        None,
        None,
    )
    .await?;

// Alice sends the message to the mediator
atm.send_message(&atm_alice, &forward_msg, &msg_id, false, false)
    .await?;

Receive message

Bob picks up the message from his mediator.

// Bob waits up to 5 seconds for the message
let received = atm
    .message_pickup()
    .live_stream_get(&atm_bob, &msg_id, Duration::from_secs(5), true)
    .await?;

What’s next

  Explore Meeting Place, an implementation of Affinidi Messaging

  Integrate Affinidi Messaging into your applications