Bu eğitimde, Alice ve Bob adlı iki kişinin hesap oluşturduğu, aynı şifreli grupta bir mesaj alışverişi yaptığı küçük bir Rust programı geliştirirsiniz. Her şey bilgisayarınızda geçici bir röle üzerinden çalışır, bu yüzden hiçbir hesap veya mesaj herkese açık bir röleye ulaşmaz.
Ön koşullar
- git ve Rust 1.97.1, MDK’nın araç zinciri dosyasında belirlediği sürüm
- Bir C derleyicisi, make ve Perl. Derleme, SQLCipher ve OpenSSL’i kaynaktan derler.
- Hata ayıklama derlemesi için yaklaşık 10 GB boş disk alanı
Program ne yapar
- Programın içinde, rastgele bir yerel bağlantı noktasında bir Nostr rölesi başlatır.
- Alice ve Bob’a, iki ayrı cihazdaymış gibi, kendi veri dizinlerini verir.
- Her kişi için bir hesap oluşturur ve başkalarının onları davet edebilmesi için gereken anahtar verilerini yayımlar.
- Alice bir grup oluşturur ve Bob’u davet eder. Bob daveti alır ve kabul eder.
- Alice "Hello, Bob!" mesajını gönderir; Bob mesajı alır ve şifresini çözer.
- İkisi de uygulamalarını kapatır. Grubun ve mesajın depolandığını göstermek için Bob’un veri dizini yeniden açılır.
Adımlar
- Bir proje oluşturun:
cargo new two-party-example
cd two-party-example
- Bunu
rust-toolchain.tomlolarak kaydederek Rust sürümünü sabitleyin:
[toolchain]
channel = "1.97.1"
Cargo.tomldosyasını aşağıdakiyle değiştirin. Her MDK crate’ini tek bir commit’e sabitler.[patch]bölümü, MDK’nın kendiCargo.tomldosyasından o commit’te kopyalanmıştır; Cargo yamaları yalnızca en üst düzey projeden uyguladığı için sizin projenizin de bunu tekrarlaması gerekir.
[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.rsdosyasını şununla değiştirin:
//! 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(())
}
- Çalıştırın:
cargo run
İlk derleme MDK’yı ve bağımlılıklarını derler ve birkaç dakika sürebilir. Sonraki çalıştırmalar bu derlemeyi yeniden kullanır; bizim makinemizde program o zaman yaklaşık 25 saniyede bitti.
Beklenen sonuç
Çıktı şuna benzer. Bağlantı noktası ve iki hesap kimliği her çalıştırmada farklıdır.
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!
Bu programı MDK’nın 4d525102389ea8fc053b4be1e3904fe23eb9b931 commit’inde, Linux üzerinde Rust 1.97.1 ile çalıştırdık ve art arda üç çalıştırmada bu çıktıyı aldık. macOS veya Windows’ta denenmemiştir.
Bunun göstermedikleri
- Anahtar depolama.
AccountHome::open, her özel anahtarı veri dizininin altındaki bir dosyada tutar; bu bir deneme için uygundur.chat-dataaltındaki hersecret.jsonbir özel anahtarı düz metin olarak barındırır, bu yüzdenchat-data/dizinini.gitignoredosyasına ekleyin ve o dizini asla paylaşmayın. Bir uygulamaAccountHome::open_with_keychainveya kendi gizli bilgi deposunu kullanmalıdır. - Herkese açık röleler. Röle programın içinde çalışır ve durduğunda her şeyi unutur. Gerçek bir uygulama, iki kişinin de ulaşabildiği röleleri seçer. Program
127.0.0.1rölesine yalnızcawith_allow_loopback_relay_endpoints(true)ayarladığı için izin verir; bir uygulamada bunu kapalı bırakın. - Yeniden bağlanma. Yeniden başlatmadan sonra Bob, bir çalışma ortamı başlatmadan depolanmış verileri okur. Mesaj almayı sürdürmek için bir uygulama
start()işlevini yeniden çağırır. - Diğer özellikler. Üye ekleme veya çıkarma, medya gönderme ve mesaj gönderildiğinde çevrimdışı olan bir cihaza teslimat kapsanmaz.
Başarısız olursa
- Bir hata ayıklama derlemesi yığın taşmasıyla duruyorsa,
mainişlevinin çalışma ortamını hâlâ 8 MiB’lık iş parçacığı yığınlarıyla oluşturduğunu denetleyin. - Tekrarlanan
WARN MEMORY sqlcipher_mlocksatırları,libsqlite3-sysyamasınınCargo.tomldosyasında eksik olduğu anlamına gelir. - Bir olay beklerken oluşan zaman aşımı, Bob’un daveti veya mesajı 30 saniye içinde almadığı anlamına gelir. Hiçbir şeyin 127.0.0.1 adresine bağlantıları engellemediğini denetleyin.
- MDK kodunda bir derleme hatası, Cargo’nun denediğimizden daha yeni bir bağımlılık sürümü seçtiği anlamına gelebilir. Yeni bir proje MDK’nın
Cargo.lockdosyasını yeniden kullanmaz, bu yüzden Cargo sürümleri ilk derlemede seçer.revdeğerlerinin hâlâ yukarıdaki commit’le eşleştiğini denetleyin ve hatayı bildirirsenizCargo.lockdosyanızı da ekleyin.
Hâlâ başarısız oluyorsa, commit’i, Rust sürümünüzü, işletim sisteminizi ve eksiksiz çıktıyı içeren bir sorunu MDK deposunda açın. Göndermeden önce nelerin çıkarılacağı Katkıda bulunun sayfasında listelenir.
Sonraki adımlar
- Çalışma ortamı API’sinin geri kalanı için aynı commit’teki
marmot-appREADME dosyasını okuyun. - Gerçek sohbetleri depolamadan önce Durum ve hatalar bölümünü okuyun.
- Arayüzünüz Rust ile yazılmadıysa MarmotKit’i (Swift ve Kotlin) veya C arayüzünü kullanın.