# Send and receive messages through your mediator

> Add DIDComm messaging to a Rust or Dart application: give each party a DID that uses your mediator, let the sender message the recipient, and exchange end-to-end encrypted messages.

Send an end-to-end encrypted message from one DID to another through a DIDComm Mediator, and receive it, from a Rust or Dart application.

This guide adds DIDComm v2.1 messaging to your application. Each party gets a decentralised identifier (DID) that uses your mediator, authenticates to the mediator, and exchanges encrypted messages through it. For how DIDComm messages, envelopes and mediators work, see [How DIDComm works](/products/affinidi-elements/affinidi-messaging/how-didcomm-works.md).

A recipient that receives messages directly needs a public address and has to be online when each message arrives. A mediator holds each message, still encrypted for its recipient, until the recipient collects it, so a mobile app or an agent behind a firewall can receive messages whenever it connects.

Use this guide when:

- Your application or agent needs to send messages to other DIDs, or receive messages from them.

- You have a mediator, Affinidi-hosted or self-hosted, and want your application to use it.

- You want each message encrypted so that only its recipient can read it, and the recipient can confirm who sent it.

The steps build one program that plays both parties, Alice the sender and Bob the recipient, so that you can run the whole exchange at once. In your application, each party usually runs in its own process. To check that a mediator works without writing an application, see [Test mediator connection](/products/affinidi-elements/affinidi-messaging/didcomm-mediator/test-mediator-connection.md).

## Prerequisites

- Your mediator’s DID: the Mediator DID on your mediator’s page in Affinidi Portal, or the DID you configured for a self-hosted mediator. See [Mediator deployment options](/products/affinidi-elements/affinidi-messaging/didcomm-mediator/deployment-options.md).

- A mediator that lets new DIDs connect, because the program creates new DIDs on each run. For an Affinidi-hosted mediator, its Mediator ACL mode is Explicit Deny. For a self-hosted mediator, see the ACL settings in the [Test mediator connection prerequisites](/products/affinidi-elements/affinidi-messaging/didcomm-mediator/test-mediator-connection.md#prerequisites).

- For Rust: [Rust](https://www.rust-lang.org/tools/install) 1.95.0 or later.

- For Dart: the [Dart SDK](https://dart.dev/get-dart) 3.6.0 or later, and a mediator served over HTTPS, because the DIDComm library for Dart connects only to https:// endpoints.

The Rust program on this page was run against mediator release 0.55.0, the release that new Affinidi-hosted mediators run. The Dart program was run against a 0.55.0 mediator with trust_task_verification set to warn.

- RustAffinidi TDK for Rust

- DartDIDComm library for Dart

## Send and receive with Rust

The program uses the [Affinidi Trust Development Kit (TDK) for Rust](https://crates.io/crates/affinidi-tdk), which includes the Affinidi Messaging SDK.

Create the project

```bash
cargo new didcomm-messaging
cd didcomm-messaging
```

Replace the contents of Cargo.toml with the following. The affinidi-tdk requirement keeps the program on the 0.49 release line it was run with.

```toml
[package]
name = "didcomm-messaging"
version = "0.1.0"
edition = "2024"

[dependencies]
affinidi-tdk = "0.49"
serde_json = "1"
tokio = { version = "1", features = ["full"] }
uuid = { version = "1", features = ["v4"] }
```

Start the TDK

Start the TDK with its messaging client, which manages each party’s connection to the mediator.

```rust
let tdk = TDK::new(
    TDKConfig::builder()
        .with_load_environment(false)
        .with_use_atm(true)
        .build()?,
    None,
)
.await?;
let atm = tdk.atm.clone().expect("messaging client is enabled");
```

Create a DID for each party and connect it

Create a did:peer DID whose service points at your mediator, so that other parties know where to send its messages. Adding the profile authenticates the DID to the mediator and opens a WebSocket connection for live delivery.

```rust
async fn connect_party(
    tdk: &TDK,
    atm: &ATM,
    name: &str,
    mediator_did: &str,
) -> Result, ATMError> {
    let (did, secrets) = DID::generate_did_peer(
        vec![
            (PeerKeyRole::Verification, KeyType::Ed25519),
            (PeerKeyRole::Encryption, KeyType::X25519),
        ],
        Some(mediator_did.to_string()),
    )?;
    println!("{name} DID: {did}");

    let profile = TDKProfile::new(name, &did, Some(mediator_did), secrets);
    tdk.add_profile(&profile).await;
    atm.profile_add(&ATMProfile::from_tdk_profile(atm, &profile).await?, true)
        .await
}
```

In your application, create each DID once and keep its secrets in your secret store. Each time the application starts, create the profile from the stored DID and secrets instead of generating new ones.

Let the sender message the recipient

Each DID has an access list on the mediator, which decides who may message it. Depending on the mediator’s configuration, a new DID’s list is an allow list or a deny list, so the recipient adds the sender to an allow list or removes it from a deny list. The SDK sends the change to the mediator as a Trust Task, a management message. Access lists hold the SHA-256 hash of each DID, which account_get returns.

```rust
async fn allow_sender(
    atm: &ATM,
    owner: &Arc,
    sender: &Arc,
) -> Result {
    let account = atm.trust_tasks().account_get(owner, None).await?;
    let sender_hash = atm
        .trust_tasks()
        .account_get(sender, None)
        .await?
        .did
        .as_str()
        .to_string();
    let (add, remove) = match account.acl.access_list_mode {
        Some(MediatorAclAccessListMode::ExplicitAllow) => (vec![sender_hash], vec![]),
        _ => (vec![], vec![sender_hash]),
    };
    atm.trust_tasks()
        .access_list_update(owner, None, false, add, remove)
        .await?;
    Ok(())
}
```

Send a message

Build the message, encrypt it for the recipient with authenticated encryption (authcrypt), and wrap it in a forward message for the recipient’s mediator, the mediator named in the recipient’s DID. In this program both parties use your mediator.

```rust
async fn send_message(
    atm: &ATM,
    sender: &Arc,
    recipient: &Arc,
    recipient_mediator_did: &str,
    content: &str,
) -> Result {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let message = Message::build(
        Uuid::new_v4().to_string(),
        "https://didcomm.org/basicmessage/2.0/message".to_string(),
        json!({ "content": content }),
    )
    .from(sender.inner.did.to_string())
    .to(recipient.inner.did.to_string())
    .created_time(now)
    .expires_time(now + 60)
    .finalize();
    let message_id = message.id.clone();

    let (packed, _) = atm
        .pack_encrypted(&message, &recipient.inner.did, Some(&sender.inner.did), None)
        .await?;
    let (_, forward) = atm
        .routing()
        .forward_message(
            sender,
            false,
            &packed,
            recipient_mediator_did,
            &recipient.inner.did,
            None,
            None,
        )
        .await?;
    atm.send_message(sender, &forward, &message_id, false, false)
        .await?;
    Ok(message_id)
}
```

Receive the message

The recipient waits for the message over its WebSocket connection. Passing true as the last argument deletes the message at the mediator once it is received.

```rust
let received = atm
    .message_pickup()
    .live_stream_get(&bob, &message_id, Some(Duration::from_secs(10)), true)
    .await?;
```

This program knows the message’s ID because it sent the message itself. In your application, the recipient calls live_stream_next to wait for the next message, whatever its ID.

Run the program

Replace the contents of src/main.rs with the [full Rust program](#full-rust-program), then run it with your mediator’s DID in place of <REPLACE_MEDIATOR_DID>:

```bash
cargo run -- ""
```

The first run downloads and compiles the dependencies, which takes a few minutes.

### Full Rust program

```rust
use affinidi_tdk::{
    TDK,
    common::{config::TDKConfig, profiles::TDKProfile},
    didcomm::message::Message,
    dids::{DID, KeyType, PeerKeyRole},
    messaging::{
        ATM, errors::ATMError, profiles::ATMProfile,
        tasks::messaging::account::get::v0_2::MediatorAclAccessListMode,
    },
};
use serde_json::json;
use std::{
    env,
    sync::Arc,
    time::{Duration, SystemTime, UNIX_EPOCH},
};
use uuid::Uuid;

#[tokio::main]
async fn main() -> Result {
    let mediator_did = env::args()
        .nth(1)
        .expect("Usage: cargo run -- ");

    // Step 2: start the TDK with its messaging client.
    let tdk = TDK::new(
        TDKConfig::builder()
            .with_load_environment(false)
            .with_use_atm(true)
            .build()?,
        None,
    )
    .await?;
    let atm = tdk.atm.clone().expect("messaging client is enabled");

    // Step 3: create a DID for each party and connect it to the mediator.
    let alice = connect_party(&tdk, &atm, "Alice", &mediator_did).await?;
    let bob = connect_party(&tdk, &atm, "Bob", &mediator_did).await?;

    // Step 4: Bob lets Alice message him.
    allow_sender(&atm, &bob, &alice).await?;

    // Step 5: Alice sends Bob an encrypted message through the mediator.
    let message_id = send_message(&atm, &alice, &bob, &mediator_did, "Hello, Bob!").await?;

    // Step 6: Bob receives and decrypts Alice's message.
    let received = atm
        .message_pickup()
        .live_stream_get(&bob, &message_id, Some(Duration::from_secs(10)), true)
        .await?;
    atm.graceful_shutdown().await;
    match received {
        Some((message, _)) => {
            println!("Bob received from Alice: {}", message.body);
            Ok(())
        }
        None => {
            println!("Bob received nothing within 10 seconds");
            std::process::exit(1);
        }
    }
}

/// Creates a DID that uses the mediator, then authenticates it and opens a
/// WebSocket connection for live delivery.
async fn connect_party(
    tdk: &TDK,
    atm: &ATM,
    name: &str,
    mediator_did: &str,
) -> Result, ATMError> {
    let (did, secrets) = DID::generate_did_peer(
        vec![
            (PeerKeyRole::Verification, KeyType::Ed25519),
            (PeerKeyRole::Encryption, KeyType::X25519),
        ],
        Some(mediator_did.to_string()),
    )?;
    println!("{name} DID: {did}");

    let profile = TDKProfile::new(name, &did, Some(mediator_did), secrets);
    tdk.add_profile(&profile).await;
    atm.profile_add(&ATMProfile::from_tdk_profile(atm, &profile).await?, true)
        .await
}

/// Lets `sender` message `owner`. A new account's access list is either an
/// allow list or a deny list, depending on the mediator's configuration, so
/// add the sender to an allow list or remove it from a deny list.
async fn allow_sender(
    atm: &ATM,
    owner: &Arc,
    sender: &Arc,
) -> Result {
    let account = atm.trust_tasks().account_get(owner, None).await?;
    // Access lists hold DID hashes: get the sender's from its own account.
    let sender_hash = atm
        .trust_tasks()
        .account_get(sender, None)
        .await?
        .did
        .as_str()
        .to_string();
    let (add, remove) = match account.acl.access_list_mode {
        Some(MediatorAclAccessListMode::ExplicitAllow) => (vec![sender_hash], vec![]),
        _ => (vec![], vec![sender_hash]),
    };
    atm.trust_tasks()
        .access_list_update(owner, None, false, add, remove)
        .await?;
    Ok(())
}

/// Encrypts a message from `sender` to `recipient`, wraps it in a forward for
/// the recipient's mediator, and sends it. Returns the message ID.
async fn send_message(
    atm: &ATM,
    sender: &Arc,
    recipient: &Arc,
    recipient_mediator_did: &str,
    content: &str,
) -> Result {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let message = Message::build(
        Uuid::new_v4().to_string(),
        "https://didcomm.org/basicmessage/2.0/message".to_string(),
        json!({ "content": content }),
    )
    .from(sender.inner.did.to_string())
    .to(recipient.inner.did.to_string())
    .created_time(now)
    .expires_time(now + 60)
    .finalize();
    let message_id = message.id.clone();

    // Authenticated encryption: only the recipient can read the message, and
    // the recipient can confirm who sent it.
    let (packed, _) = atm
        .pack_encrypted(&message, &recipient.inner.did, Some(&sender.inner.did), None)
        .await?;
    let (_, forward) = atm
        .routing()
        .forward_message(
            sender,
            false,
            &packed,
            recipient_mediator_did,
            &recipient.inner.did,
            None,
            None,
        )
        .await?;
    atm.send_message(sender, &forward, &message_id, false, false)
        .await?;
    Ok(message_id)
}
```

## Send and receive with Dart

The program uses the [DIDComm library for Dart](https://pub.dev/packages/didcomm) and [Affinidi Dart SSI](https://pub.dev/packages/ssi), which manages keys and DIDs.

Create the project

Create a folder for the program and go to it:

```bash
mkdir didcomm_messaging
cd didcomm_messaging
```

Create a pubspec.yaml file with the following content. The constraints keep each library on the major version the program was run with. didcomm 2.4.0 needs ssi 3.x.

```yaml
name: didcomm_messaging
description: Send and receive messages through a mediator
version: 1.0.0

environment:
  sdk: ^3.6.0

dependencies:
  didcomm: ^2.4.0
  ssi: ^3.9.4
  uuid: ^4.5.1
```

Install the dependencies:

```bash
dart pub get
```

Create a DID for each party

Create a did:key DID from a new Ed25519 key. Its key agreement key is X25519, which Affinidi mediators support.

```dart
Future createDidManager(String keyId) async {
  final wallet = PersistentWallet(InMemoryKeyStore());
  final didManager = DidKeyManager(wallet: wallet, store: InMemoryDidStore());
  await wallet.generateKey(keyId: keyId, keyType: KeyType.ed25519);
  await didManager.addVerificationMethod(keyId);
  return didManager;
}
```

InMemoryKeyStore loses its keys when the program stops. In your application, implement the KeyStore interface over your secure storage, so that each party keeps its DID.

Connect each party to the mediator

Resolve the mediator’s DID, then create a client that authenticates to the mediator. Set shouldSign: true, because by default the mediator rejects anonymous messages.

```dart
final mediatorDidDocument =
    await UniversalDIDResolver.defaultResolver.resolveDid(mediatorDid);
```

```dart
Future connectToMediator(
  DidManager didManager,
  DidDocument mediatorDidDocument,
) async {
  return MediatorClient.init(
    mediatorDidDocument: mediatorDidDocument,
    didManager: didManager,
    authorizationProvider: await AffinidiAuthorizationProvider.init(
      mediatorDidDocument: mediatorDidDocument,
      didManager: didManager,
    ),
    forwardMessageOptions: const ForwardMessageOptions(
      shouldSign: true,
      keyWrappingAlgorithm: KeyWrappingAlgorithm.ecdhEs,
      encryptionAlgorithm: EncryptionAlgorithm.a256cbc,
    ),
  );
}
```

Let the sender message the recipient

Each DID has an access list on the mediator, which decides who may message it. The recipient sends the mediator two Trust Tasks, management messages: one puts its access list in allow-list mode, and the other adds the sender. Mediators differ in the mode they give a new DID, so the recipient sets the mode itself rather than relying on the default. A self-hosted mediator that doesn’t let a DID change its own mode refuses this step, as [Troubleshooting](#troubleshooting) describes.

```dart
Future allowSender(
  MediatorClient ownerClient, {
  required String owner,
  required String sender,
  required String mediatorDid,
}) async {
  final expiresTime = DateTime.now().toUtc().add(const Duration(seconds: 60));
  await ownerClient.sendTrustTask(
    TrustTaskMessage(
      id: const Uuid().v4(),
      document: AccountUpdateTask(
        issuer: owner,
        mediatorDid: mediatorDid,
        acl: const MediatorAcl(accessListMode: AccessListMode.explicitAllow),
      ),
      expiresTime: expiresTime,
    ),
  );
  await ownerClient.sendTrustTask(
    TrustTaskMessage(
      id: const Uuid().v4(),
      document: AccessListUpdateTask(
        issuer: owner,
        mediatorDid: mediatorDid,
        add: [sender],
      ),
      expiresTime: expiresTime,
    ),
  );
}
```

Send a message

Sign the message, encrypt it for the recipient with authenticated encryption (authcrypt), and wrap it in a forward message for the recipient’s mediator, the mediator named in the recipient’s DID. In this program both parties use your mediator.

```dart
Future sendMessage(
  MediatorClient senderClient, {
  required DidManager sender,
  required PlainTextMessage message,
  required DidDocument recipientDidDocument,
  required String recipientMediatorDid,
}) async {
  final senderDidDocument = await sender.getDidDocument();
  final keyAgreementId = senderDidDocument.keyAgreement.first.id;
  final encrypted = await DidcommMessage.packIntoSignedAndEncryptedMessages(
    message,
    keyPair: await sender.getKeyPairByDidKeyId(keyAgreementId),
    didKeyId: keyAgreementId,
    recipientDidDocuments: [recipientDidDocument],
    keyWrappingAlgorithm: KeyWrappingAlgorithm.ecdh1Pu,
    encryptionAlgorithm: EncryptionAlgorithm.a256cbc,
    signer: await sender.getSigner(
      senderDidDocument.assertionMethod.first.id,
    ),
  );

  final forward = ForwardMessage(
    id: const Uuid().v4(),
    to: [recipientMediatorDid],
    from: senderDidDocument.id,
    next: recipientDidDocument.id,
    expiresTime: DateTime.now().toUtc().add(const Duration(seconds: 60)),
    attachments: [
      Attachment(
        mediaType: 'application/json',
        data: AttachmentData(
          base64: base64UrlEncodeNoPadding(encrypted.toJsonBytes()),
        ),
      ),
    ],
  );
  await senderClient.sendMessage(forward);
}
```

Receive the message

The recipient fetches the messages waiting in its inbox and decrypts them. fetchMessages returns up to 25 messages per call and deletes them at the mediator. The inbox also holds the mediator’s responses to the recipient’s Trust Tasks, which use a different message wrapping, so list both wrapping types.

```dart
Future
- > receiveMessages(
  MediatorClient client,
  DidManager recipient,
) async {
  final received = 

[];
  for (final message in await client.fetchMessages()) {
    received.add(
      await DidcommMessage.unpackToPlainTextMessage(
        message: message,
        recipientDidManager: recipient,
        expectedMessageWrappingTypes: [
          MessageWrappingType.authcryptSignPlaintext,
          MessageWrappingType.authcryptPlaintext,
        ],
      ),
    );
  }
  return received;
}
```

To receive messages as they arrive instead of fetching them, call listenForIncomingMessages on the client, which opens a WebSocket connection to the mediator.

Run the program

Create a messaging.dart file with the [full Dart program](#full-dart-program), replace <REPLACE_MEDIATOR_DID> with your mediator’s DID, and run it:

```bash
dart run messaging.dart
```

### Full Dart program

```dart
import 'dart:io';

import 'package:didcomm/didcomm.dart';
import 'package:ssi/ssi.dart';
import 'package:uuid/uuid.dart';

void main() async {
  const mediatorDid = '';

  // Step 2: create a DID for each party.
  final alice = await createDidManager('alice-key-1');
  final bob = await createDidManager('bob-key-1');
  final aliceDidDocument = await alice.getDidDocument();
  final bobDidDocument = await bob.getDidDocument();
  print('Alice DID: ${aliceDidDocument.id}');
  print('Bob DID: ${bobDidDocument.id}');

  // Step 3: connect each party to the mediator.
  final mediatorDidDocument =
      await UniversalDIDResolver.defaultResolver.resolveDid(mediatorDid);
  final aliceClient = await connectToMediator(alice, mediatorDidDocument);
  final bobClient = await connectToMediator(bob, mediatorDidDocument);

  // Step 4: Bob lets Alice message him.
  await allowSender(
    bobClient,
    owner: bobDidDocument.id,
    sender: aliceDidDocument.id,
    mediatorDid: mediatorDidDocument.id,
  );

  // Step 5: Alice sends Bob a signed and encrypted message.
  final message = PlainTextMessage(
    id: const Uuid().v4(),
    from: aliceDidDocument.id,
    to: [bobDidDocument.id],
    type: Uri.parse('https://didcomm.org/basicmessage/2.0/message'),
    body: {'content': 'Hello, Bob!'},
  );
  await sendMessage(
    aliceClient,
    sender: alice,
    message: message,
    recipientDidDocument: bobDidDocument,
    recipientMediatorDid: mediatorDidDocument.id,
  );

  // Step 6: Bob fetches and decrypts his messages.
  for (var attempt = 0; attempt  0) await Future.delayed(const Duration(seconds: 1));
    for (final received in await receiveMessages(bobClient, bob)) {
      if (received.type == message.type) {
        print('Bob received from Alice: ${received.body}');
        exit(0);
      }
    }
  }
  print('Bob received nothing within 10 seconds');
  exit(1);
}

/// Creates a did:key identity from a new Ed25519 key. Its key agreement key
/// is X25519, which Affinidi mediators support.
Future createDidManager(String keyId) async {
  final wallet = PersistentWallet(InMemoryKeyStore());
  final didManager = DidKeyManager(wallet: wallet, store: InMemoryDidStore());
  await wallet.generateKey(keyId: keyId, keyType: KeyType.ed25519);
  await didManager.addVerificationMethod(keyId);
  return didManager;
}

/// Authenticates to the mediator. Signing what the client sends is required,
/// because by default the mediator rejects anonymous messages.
Future connectToMediator(
  DidManager didManager,
  DidDocument mediatorDidDocument,
) async {
  return MediatorClient.init(
    mediatorDidDocument: mediatorDidDocument,
    didManager: didManager,
    authorizationProvider: await AffinidiAuthorizationProvider.init(
      mediatorDidDocument: mediatorDidDocument,
      didManager: didManager,
    ),
    forwardMessageOptions: const ForwardMessageOptions(
      shouldSign: true,
      keyWrappingAlgorithm: KeyWrappingAlgorithm.ecdhEs,
      encryptionAlgorithm: EncryptionAlgorithm.a256cbc,
    ),
  );
}

/// Puts the owner's access list in allow-list mode, then adds the sender.
/// Mediators differ in the mode they give a new DID, so set it explicitly
/// before adding the sender.
Future allowSender(
  MediatorClient ownerClient, {
  required String owner,
  required String sender,
  required String mediatorDid,
}) async {
  final expiresTime = DateTime.now().toUtc().add(const Duration(seconds: 60));
  await ownerClient.sendTrustTask(
    TrustTaskMessage(
      id: const Uuid().v4(),
      document: AccountUpdateTask(
        issuer: owner,
        mediatorDid: mediatorDid,
        acl: const MediatorAcl(accessListMode: AccessListMode.explicitAllow),
      ),
      expiresTime: expiresTime,
    ),
  );
  await ownerClient.sendTrustTask(
    TrustTaskMessage(
      id: const Uuid().v4(),
      document: AccessListUpdateTask(
        issuer: owner,
        mediatorDid: mediatorDid,
        add: [sender],
      ),
      expiresTime: expiresTime,
    ),
  );
}

/// Signs the message, encrypts it for the recipient with authenticated
/// encryption, wraps it in a forward for the recipient's mediator, and sends it.
Future sendMessage(
  MediatorClient senderClient, {
  required DidManager sender,
  required PlainTextMessage message,
  required DidDocument recipientDidDocument,
  required String recipientMediatorDid,
}) async {
  final senderDidDocument = await sender.getDidDocument();
  final keyAgreementId = senderDidDocument.keyAgreement.first.id;
  final encrypted = await DidcommMessage.packIntoSignedAndEncryptedMessages(
    message,
    keyPair: await sender.getKeyPairByDidKeyId(keyAgreementId),
    didKeyId: keyAgreementId,
    recipientDidDocuments: [recipientDidDocument],
    keyWrappingAlgorithm: KeyWrappingAlgorithm.ecdh1Pu,
    encryptionAlgorithm: EncryptionAlgorithm.a256cbc,
    signer: await sender.getSigner(
      senderDidDocument.assertionMethod.first.id,
    ),
  );

  final forward = ForwardMessage(
    id: const Uuid().v4(),
    to: [recipientMediatorDid],
    from: senderDidDocument.id,
    next: recipientDidDocument.id,
    expiresTime: DateTime.now().toUtc().add(const Duration(seconds: 60)),
    attachments: [
      Attachment(
        mediaType: 'application/json',
        data: AttachmentData(
          base64: base64UrlEncodeNoPadding(encrypted.toJsonBytes()),
        ),
      ),
    ],
  );
  await senderClient.sendMessage(forward);
}

/// Fetches the messages waiting in the inbox and decrypts them. Each fetch
/// deletes the messages it returns from the mediator.
Future
- > receiveMessages(
  MediatorClient client,
  DidManager recipient,
) async {
  final received = 

[];
  for (final message in await client.fetchMessages()) {
    received.add(
      await DidcommMessage.unpackToPlainTextMessage(
        message: message,
        recipientDidManager: recipient,
        expectedMessageWrappingTypes: [
          // A message from another DID: signed, then encrypted.
          MessageWrappingType.authcryptSignPlaintext,
          // The mediator's responses to Trust Tasks.
          MessageWrappingType.authcryptPlaintext,
        ],
      ),
    );
  }
  return received;
}
```

## Confirm

### Test 1: a message from Alice reaches Bob

Run the program as its last step describes. It prints the DIDs it created, then the message Bob received.

Rust:

```text
Alice DID: did:peer:2.Vz6Mk...
Bob DID: did:peer:2.Vz6Mk...
Bob received from Alice: {"content":"Hello, Bob!"}
```

Dart:

```text
Alice DID: did:key:z6Mk...
Bob DID: did:key:z6Mk...
Bob received from Alice: {content: Hello, Bob!}
```

Seeing Hello, Bob! confirms that both DIDs authenticated to the mediator, that Bob’s access list admitted Alice, and that the mediator delivered Alice’s message to Bob. If the message has not arrived after 10 seconds, the program prints Bob received nothing within 10 seconds and exits with status 1.

## Troubleshooting

| Symptom | Likely cause | Fix |
| e.p.authentication.blocked with “DID is blocked”. | The mediator is in Explicit Allow mode, so it accepts only DIDs on its allow list, and the program’s DIDs are new. | For this program, use a mediator in Explicit Deny mode. In your application, add each party’s DID to the mediator’s allow list, under Access Controls for an Affinidi-hosted mediator. |
| messaging/access-list/update:selfChangeDenied with “this account may not self-manage its access list”. | The mediator’s default ACL for new DIDs leaves out SELF_MANAGE_LIST, so Bob can’t update his access list. | On a self-hosted mediator, add SELF_MANAGE_LIST to global_acl_default, then restart it. See [Supported ACLs](/products/affinidi-elements/affinidi-messaging/didcomm-mediator/supported-acls.md). |
| Dart: messaging/account/update:selfChangeDenied with “this account may not change accessListMode”. | The mediator’s default ACL for new DIDs leaves out MODE_SELF_CHANGE, so Bob can’t put his access list in allow-list mode. | On a self-hosted mediator, add MODE_SELF_CHANGE to global_acl_default, then restart it. See [Supported ACLs](/products/affinidi-elements/affinidi-messaging/didcomm-mediator/supported-acls.md). |
| Bob received nothing within 10 seconds, or in Dart Status code: 403 with e.p.delivery.refused or e.p.authorization.send_forwarded. | The mediator refused the message, or accepted it but didn’t deliver it in time. | Check that the access list step ran. For a self-hosted mediator, check its log, and see the matching rows in [Test mediator connection](/products/affinidi-elements/affinidi-messaging/didcomm-mediator/test-mediator-connection.md#troubleshooting). |
| Dart: Status code: 403 with e.p.proofRequired and “this Trust Task type requires a proof”. Bob’s access list update is refused. | The mediator’s trust_task_verification setting is enforce, for example on a self-hosted mediator set up with mediator-setup, and the DIDComm library for Dart sends Trust Tasks without a proof. | Use the Rust program, which signs its Trust Tasks, or set trust_task_verification to warn and restart the mediator. |
| Dart: Status code: 400 with w.m.message.anonymous. | A MediatorClient created without shouldSign: true sends unsigned messages. | Pass shouldSign: true in forwardMessageOptions, as Step 3 shows. |
| Dart: MessageWrappingType.authcryptPlaintext in not in expected list. | The inbox holds the mediator’s responses to Bob’s Trust Tasks. | List both authcryptSignPlaintext and authcryptPlaintext, as Step 6 shows. |
| Dart: Can not find https endpoint in DIDCommMessaging service. | The mediator’s DID lists only an http:// endpoint. | Serve the mediator over HTTPS, and list the https:// URL in its DID. |
| HTTP 429, or a WebSocket closed with code 1013, or with code 1008 and “message rate limit exceeded”. | The client is over one of the mediator’s limits. | Wait for the Retry-After time after a 429, and reconnect after a random delay, sending more slowly. See [Mediator sizes and limits](/products/affinidi-elements/affinidi-messaging/didcomm-mediator/deployment-options/mediator-affinidi-portal/sizes-and-limits.md#limits-that-apply-to-clients). |
| A WebSocket closed with code 1008 and “authentication token expired”. | The DID’s session with the mediator has expired. | Authenticate again, then reconnect. |

## What’s next

  [Connect two users and chat with Meeting Place](/products/affinidi-elements/affinidi-messaging/integration-guides/meeting-place.md)

  [Deploy an Affinidi-hosted mediator](/products/affinidi-elements/affinidi-messaging/didcomm-mediator/deployment-options/mediator-affinidi-portal.md)

## Related

  [How DIDComm works](/products/affinidi-elements/affinidi-messaging/how-didcomm-works.md)

  [Mediator sizes and limits](/products/affinidi-elements/affinidi-messaging/didcomm-mediator/deployment-options/mediator-affinidi-portal/sizes-and-limits.md)

  [Supported ACLs](/products/affinidi-elements/affinidi-messaging/didcomm-mediator/supported-acls.md)

  [Test mediator connection](/products/affinidi-elements/affinidi-messaging/didcomm-mediator/test-mediator-connection.md)
