在本教程中,你将构建一个小型 Rust 程序:Alice 和 Bob 两个人创建账号,共享一个加密群组并交换一条消息。程序在你的电脑上运行,通过本地临时网络中继器通信,因此不会有任何账号或消息到达公共网络中继器。
前提条件
- git 和 Rust 1.97.1,即 MDK 在其工具链文件中设定的版本
- C 编译器、make 和 Perl。构建时会从源代码编译 SQLCipher 和 OpenSSL。
- 调试构建大约需要 10 GB 的可用磁盘空间
程序做了什么
- 在程序内部的一个随机本地端口上启动一个 Nostr 中继器。
- 给 Alice 和 Bob 各自分配独立的数据目录,就像他们分别在两台设备上一样。
- 为每个人创建账号,并发布他人邀请他们所需的密钥材料。
- Alice 创建一个包含 Bob 的群组。Bob 收到邀请并接受。
- Alice 发送 "Hello, Bob!",Bob 收到并解密这条消息。
- 两人都关闭各自的应用。重新打开 Bob 的数据目录,以显示群组和消息已被存储。
步骤
- 创建项目:
cargo new two-party-example
cd two-party-example
- 将下面的内容保存为
rust-toolchain.toml,以固定 Rust 版本:
[toolchain]
channel = "1.97.1"
- 用下面的内容替换
Cargo.toml。它把每个 MDK crate 都固定到同一个提交。[patch]部分复制自该提交处 MDK 自己的Cargo.toml;Cargo 只应用顶层项目中的补丁,所以你的项目必须重复这一部分。
[package]
name = "two-party-example"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
marmot-app = { git = "https://github.com/marmot-protocol/mdk", rev = "4d525102389ea8fc053b4be1e3904fe23eb9b931" }
marmot-account = { git = "https://github.com/marmot-protocol/mdk", rev = "4d525102389ea8fc053b4be1e3904fe23eb9b931" }
cgka-traits = { git = "https://github.com/marmot-protocol/mdk", rev = "4d525102389ea8fc053b4be1e3904fe23eb9b931" }
nostr-relay-builder = "0.44"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] }
# Copied from MDK's own Cargo.toml at the same commit. Cargo only applies
# [patch] from the top-level project, so a project that depends on MDK has
# to repeat it. Without the libsqlite3-sys patch, SQLCipher prints a
# "WARN MEMORY sqlcipher_mlock" line for every failed mlock() call.
[patch.crates-io]
hax-lib-macros = { git = "https://github.com/cryspen/hax.git", rev = "8f9cb576e58f6cc7e9ed249a7d4439b0f7ed0da7" }
libsqlite3-sys = { git = "https://github.com/rusqlite/rusqlite.git", rev = "5ae7fdf83085c595fd54f977b3a56ccacabaf16b" }
- 用下面的内容替换
src/main.rs:
//! Two people, one encrypted group, one message, using MDK's app-level API.
//!
//! Alice and Bob each get their own data directory (as if they were on two
//! different phones). Both talk to one Nostr relay that runs inside this
//! process, so nothing touches the public network.
use std::error::Error;
use std::path::Path;
use std::time::Duration;
use cgka_traits::TransportEndpoint;
use marmot_account::AccountHome;
use marmot_app::{
AccountSetupRequest, MarmotApp, MarmotAppConfig, MarmotAppEvent, MarmotAppRuntime,
};
use nostr_relay_builder::MockRelay;
use tokio::sync::broadcast;
use tokio::time::timeout;
type Result<T> = std::result::Result<T, Box<dyn Error>>;
/// Open (or create) one person's local Marmot installation in `root`.
fn open_app(root: &Path, relay_url: &str) -> Result<MarmotApp> {
let config = MarmotAppConfig::default()
// Our relay is on 127.0.0.1. Real apps leave loopback refused.
.with_allow_loopback_relay_endpoints(true);
let app = MarmotApp::try_with_relays_and_account_home_and_config(
root,
vec![relay_url.to_owned()],
// Development key store: the secret key is a file under `root`.
AccountHome::open(root),
config,
)?;
Ok(app)
}
/// Create a new Nostr identity, publish its relay lists, profile and
/// KeyPackage to our relay, and return its account id (hex public key).
async fn create_account(runtime: &MarmotAppRuntime, relay_url: &str) -> Result<String> {
let relay = TransportEndpoint(relay_url.to_owned());
let setup = runtime
.create_identity(AccountSetupRequest {
default_relays: vec![relay.clone()],
bootstrap_relays: vec![relay],
publish_initial_key_package: true,
..AccountSetupRequest::default()
})
.await?;
Ok(setup.account.account_id_hex)
}
/// Wait up to 30 seconds for the first event that `pick` accepts.
async fn wait_for<T>(
events: &mut broadcast::Receiver<MarmotAppEvent>,
mut pick: impl FnMut(MarmotAppEvent) -> Option<T>,
) -> Result<T> {
let found = timeout(Duration::from_secs(30), async {
loop {
match events.recv().await {
Ok(event) => {
if let Some(found) = pick(event) {
return Ok(found);
}
}
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(err) => return Err(err),
}
}
})
.await??;
Ok(found)
}
fn main() -> Result<()> {
// MDK's async call chains are deep; unoptimized (debug) builds overflow
// Tokio's default 2 MiB worker stacks. Give every thread 8 MiB.
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.thread_stack_size(8 * 1024 * 1024)
.enable_all()
.build()?
.block_on(run())
}
async fn run() -> Result<()> {
// Start a throwaway relay on a random local port.
let relay = MockRelay::run().await?;
let relay_url = relay.url().await.to_string();
println!("relay running at {relay_url}");
// Fresh data directories for every run.
let data = Path::new("chat-data");
if data.exists() {
std::fs::remove_dir_all(data)?;
}
let (alice_dir, bob_dir) = (data.join("alice"), data.join("bob"));
std::fs::create_dir_all(&alice_dir)?;
std::fs::create_dir_all(&bob_dir)?;
// 1. Each person opens their own app and creates an account.
let alice = open_app(&alice_dir, &relay_url)?.runtime();
let bob = open_app(&bob_dir, &relay_url)?.runtime();
let alice_id = create_account(&alice, &relay_url).await?;
let bob_id = create_account(&bob, &relay_url).await?;
println!("alice = {alice_id}");
println!("bob = {bob_id}");
// 2. Both start their runtimes, which connect to the relay and listen.
let mut bob_events = bob.subscribe();
alice.start().await?;
bob.start().await?;
// 3. Alice creates a group with Bob in it. MDK fetches Bob's KeyPackage
// from the relay and sends him an encrypted Welcome.
let group_id = alice
.create_group(&alice_id, "Tutorial chat", &[bob_id.clone()], None)
.await?;
println!("alice created group, inviting bob");
// 4. Bob's runtime receives the Welcome and shows a pending invite.
wait_for(&mut bob_events, |event| match event {
MarmotAppEvent::GroupJoined { group_id: id, .. } if id == group_id => Some(()),
_ => None,
})
.await?;
let group = bob.accept_group_invite(&bob_id, &group_id).await?;
println!("bob accepted invite to \"{}\"", group.profile.name);
// 5. Alice sends a message; Bob receives and decrypts it.
alice
.send_message(&alice_id, &group_id, b"Hello, Bob!".to_vec())
.await?;
let received = wait_for(&mut bob_events, |event| match event {
MarmotAppEvent::MessageReceived(m) if m.message.group_id == group_id => Some(m.message),
_ => None,
})
.await?;
let from = if received.sender == alice_id { "alice" } else { "?" };
println!("bob received from {from}: {}", received.plaintext);
// 6. Shut down cleanly: this closes every database and releases locks.
alice.shutdown_and_close().await?;
bob.shutdown_and_close().await?;
drop((alice, bob));
// 7. "Restart" Bob: open his data directory again and read what was
// stored, without starting a runtime or touching the network.
let bob_again = open_app(&bob_dir, &relay_url)?;
for group in bob_again.groups(&bob_id)? {
println!("after restart, bob is in group \"{}\"", group.profile.name);
}
for message in bob_again.messages(&bob_id)? {
if message.kind == 9 {
println!("after restart, bob has message: {}", message.plaintext);
}
}
Ok(())
}
- 运行它:
cargo run
第一次构建会编译 MDK 及其依赖,可能需要几分钟。之后的运行会复用这次构建;在我们的机器上,程序随后大约 25 秒就能跑完。
预期结果
输出类似下面这样。端口和两个账号 id 每次运行都不同。
relay running at ws://127.0.0.1:34067
alice = bf95e7c8a9f099ef9f7314f8b27acac9c00cfbcdc77b65b27d308115854c04e5
bob = a33c25186f7cc88921fd032be5ec92e7cad231594fd3fab80cf5f42833e84f4b
alice created group, inviting bob
bob accepted invite to "Tutorial chat"
bob received from alice: Hello, Bob!
after restart, bob is in group "Tutorial chat"
after restart, bob has message: Hello, Bob!
我们在 MDK 提交 4d525102389ea8fc053b4be1e3904fe23eb9b931、Rust 1.97.1、Linux 环境下运行了这个程序,连续三次运行都得到了这样的输出。它尚未在 macOS 或 Windows 上测试过。
它没有展示什么
- 密钥存储。
AccountHome::open把每个私钥保存在数据目录下的一个文件中,这对测试来说没问题。chat-data下的每个secret.json都以明文保存一个私钥,所以请把chat-data/加入.gitignore,并且绝不要分享这个目录。应用应使用AccountHome::open_with_keychain或它自己的密钥存储。 - 公共网络中继器。 这个网络中继器运行在程序内部,停止后不会保留任何数据。真实的应用会选择两个人都能连上的网络中继器。程序之所以允许
127.0.0.1的网络中继器,只是因为它设置了with_allow_loopback_relay_endpoints(true);在应用中请不要开启它。 - 重新连接。 重启之后,Bob 读取的是已存储的数据,并没有启动运行时。要继续接收消息,应用需要再次调用
start()。 - 其他功能。 添加或移除成员、发送媒体,以及向消息发送时处于离线的设备传递消息,都没有涉及。
如果失败
- 如果调试构建因栈溢出而停止,请检查
main是否仍以 8 MiB 的线程栈来构建运行时。 - 反复出现
WARN MEMORY sqlcipher_mlock行,说明Cargo.toml中缺少libsqlite3-sys补丁。 - 等待事件时超时,表示 Bob 在 30 秒内没有收到邀请或消息。请检查是否有东西阻止了到 127.0.0.1 的连接。
- MDK 代码中的编译错误,可能意味着 Cargo 选择了比我们测试时更新的依赖版本。新项目不会复用 MDK 的
Cargo.lock,所以 Cargo 在第一次构建时自行选择版本。请检查rev的值是否仍与上面的提交一致,并且在报告错误时附上你的Cargo.lock。
如果仍然失败,请在 MDK 代码仓库中提交议题(issue),附上提交、你的 Rust 版本、你的操作系统和完整输出。“参与贡献”页面列出了发布前应删去的内容。
后续步骤
- 阅读同一提交处的
marmot-appREADME,了解运行时 API 的其余部分。 - 在存储真实会话之前,请先阅读“状态与错误”。
- 如果你的界面不是用 Rust 编写的,请使用 MarmotKit(Swift 和 Kotlin)或 C 接口。