在這份教學中,你會建置一個小型 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 儲存庫中提出議題,附上提交、你的 Rust 版本、作業系統和完整輸出。「貢獻」頁面列出了發文前要移除的內容。
後續步驟
- 閱讀同一個提交上的
marmot-appREADME,了解執行環境 API 的其餘部分。 - 在儲存真實對話之前,請先閱讀「狀態與錯誤」。
- 如果你的介面不是用 Rust 撰寫,請使用 MarmotKit(Swift 和 Kotlin)或 C 介面。