Skip to main content

Build a Reticulum app in Rust

Start every Rust Reticulum application with rns_runtime::prelude. It re-exports the runtime handle alongside core identity, destination, packet, Link, Request/Response, Channel, Buffer, Resource, interface, and shutdown types without hiding them behind an opaque wrapper.

1. Add rns-runtime to Cargo.toml​

Pin a tagged release of rsReticulum (MSRV Rust 1.89+, C compiler required for the default bundled SQLite storage):

[dependencies]
rns-runtime = { git = "https://github.com/ratspeak/rsReticulum.git", tag = "v1.5.1" }
tokio = { version = "1", features = ["full"] }
hex = "0.4"

2. Start the runtime, register a destination & announce​

This complete starter follows rsReticulum/api/README.md and crates/rns-runtime/examples/announce.rs:

use std::sync::Arc;
use std::sync::atomic::AtomicBool;

use rns_runtime::prelude::*;

const ASPECT: &str = "myapp.demo.service";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let shutdown = ShutdownSignal::new();
let runtime = init(
None, // default config dir (~/.rsReticulum)
None, // default log level
shutdown.clone(),
Arc::new(AtomicBool::new(true)), // enable normal startup
)
.await?;

// Subscribe to announces matching our aspect before announcing
let mut announces = runtime
.subscribe_announces(Some(ASPECT.to_string()), false)
.await?;

// Register a Single destination bound to a fresh identity
let identity = Identity::new();
let destination = runtime
.register_destination(
identity,
ASPECT.to_string(),
DestinationRuntimeOptions::default(),
)
.await?;

println!(
"Listening on destination: {}",
hex::encode(destination.handle.destination_hash())
);

destination
.handle
.announce(DestinationAnnounceOptions {
app_data: Some(b"hello-mesh".to_vec()),
..DestinationAnnounceOptions::default()
})
.await?;

// Receive one peer announce (or exit on shutdown)
tokio::select! {
_ = shutdown.wait() => {}
Some(ann) = announces.recv() => {
println!(
"Observed {} app_data={}",
hex::encode(ann.destination_hash),
ann.app_data.as_deref().map(String::from_utf8_lossy).unwrap_or_default(),
);
}
}

announces.close().await?;
destination.close().await?;
runtime.shutdown_and_wait().await;
Ok(())
}

AnnounceSubscription owns exactly one announce handler registration and cleans up cleanly on .close() or drop.

Once a peer destination hash is known, connect an ephemeral X25519 Link with ReticulumHandle::connect_link (from examples/link.rs and examples/request.rs):

use std::time::Duration;
use rns_runtime::prelude::*;

// Client side: connect to a peer destination and send an RPC request
async fn send_echo_request(
runtime: &ReticulumHandle,
destination_hash: [u8; 16],
) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
let options = LinkConnectOptions {
identify: false, // set true to disclose your client identity over the encrypted Link
client_label: "echo-client".to_string(),
..LinkConnectOptions::default()
};

let session = runtime
.connect_link(destination_hash, Identity::new(), options)
.await?;

let response = session
.handle
.request("/echo", b"ping", Some(Duration::from_secs(30)))
.await?;

session.handle.close().await;
Ok(response.data)
}

On the server side, attach a handler to your registered DestinationHandle before announcing:

destination
.handle
.register_request_handler(
"/echo",
AllowPolicy::AllowAll,
Vec::new(),
true,
|request| RequestOutcome::ReplyBytes(request.data),
)
.await?;

For streaming byte I/O over an established Link, open a bidirectional Buffer (session.handle.channel().create_bidirectional_buffer(stream_id, stream_id).await?), which implements tokio::io::AsyncRead and AsyncWrite (examples/buffer.rs). For large files of arbitrary size, stream straight to disk with DestinationHandle::receive_resource_files or LinkSessionResourceOffer::accept_to_file (examples/filetransfer.rs).

4. Production runtime patterns​

Explicit shared-instance ownership (InstancePolicy)​

By default, init() uses config-driven automatic owner/client detection. Services that must never silently fall back between owning local radios and attaching to a daemon should use reticulum::init_with_policy with shared_instance::InstancePolicy:

PolicyBehavior
ConfiguredStandard config-file automatic owner/client selection.
StandaloneOwns local interfaces directly without exposing shared IPC sockets.
SharedOwner / SharedOwnerAt(endpoint)Binds the shared data & control endpoints or fails startup — never joins another owner.
SharedClient(credentials)Attaches to an existing owner, authenticates control RPC via HMAC key (redacted in Debug), reauthenticates on reconnect, and never starts local interfaces.

Check availability before starting a runtime with credentials.test().await, monitor reconnect state via shared_instance_state(), and inspect non-fatal interface startup issues with startup_interface_failures(). (If an interface fails during startup, rsReticulum 1.5+ fails startup by default to match Python Reticulum; pass InitOptions::keep_starting_after_interface_failure when an embedder wants to continue with remaining interfaces.)

Finite discovery vs. long-lived observation​

  • One-shot lookup: Call resolve_destination_on_transport with a single deadline and validated identity recall. It does not install or mutate announce handler tables.
  • Long-lived stream: Call ReticulumHandle::subscribe_announces and drain the returned AnnounceSubscription.

Atomic route recovery & delivery clocks​

  • Route invalidation: Obtain ReticulumHandle::path_recovery_handle(). try_recover(dest, Some(failed_link_id)) and try_recover_packet(dest, packet_hash) atomically compare against the exact route used by that failed local attempt so fresh routes on the same interface are never wiped by a stale failure.
  • Local admission vs. proof timing: ReticulumHandle::link_endpoint_dispatch_handle() provides exact local-admission receipts (try_send, try_send_cancellable) separate from Link::packet_proof_timeout() (measured-RTT proof budget) and OutboundTransfer::timeout_window() (Resource phase budget).

5. Explore the 13 CI-compiled examples​

Every example in crates/rns-runtime/examples/ is compiled in CI:

ExampleWhat it demonstrates
minimal / announce / broadcastRuntime startup, Single/Plain Destinations, signed announces, plain broadcast
echo / link / identifyPacket proofs, ephemeral X25519 Link handshake, optional initiator identification
requestRequest / Response RPC over an established Link (AllowPolicy, RequestOutcome)
channel / bufferOrdered reliable Channels and AsyncRead/AsyncWrite streaming Buffers
resource / filetransfer / speedtestChunked Resource transfers, direct-to-file receives, and throughput benchmarking
ratchetsForward-secret destination ratchets

Run any example from a local rsReticulum checkout:

cargo run -p rns-runtime --example minimal
cargo run -p rns-runtime --example link -- server
cargo run -p rns-runtime --example link -- client <32_hex_dest_hash> "Hello Link"
cargo doc --workspace --no-deps --open

Next steps​