1827 lines
66 KiB
Rust
1827 lines
66 KiB
Rust
|
|
//! Two-node onion session: host HS, Noise IK, persist plaintext locally.
|
||
|
|
|
||
|
|
use std::path::{Path, PathBuf};
|
||
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||
|
|
use std::sync::{Arc, Mutex};
|
||
|
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||
|
|
|
||
|
|
use futures::StreamExt;
|
||
|
|
use futures::io::{AsyncRead, AsyncWrite};
|
||
|
|
use hkdf::Hkdf;
|
||
|
|
use sha2::Sha256;
|
||
|
|
use tor_cell::relaycell::msg::Connected;
|
||
|
|
use tor_hsservice::{RunningOnionService, handle_rend_requests};
|
||
|
|
use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
|
||
|
|
use zeroize::Zeroizing;
|
||
|
|
|
||
|
|
use crate::dispatch::{self, Kind};
|
||
|
|
use crate::file;
|
||
|
|
use crate::frame;
|
||
|
|
use crate::hs::{self, Client, HS_PORT, TorState};
|
||
|
|
use crate::loc;
|
||
|
|
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
|
||
|
|
use crate::pay;
|
||
|
|
use crate::profile;
|
||
|
|
use crate::qr;
|
||
|
|
use crate::ratchet::{RatchetKeyPair, RatchetState};
|
||
|
|
use crate::ratelimit::TokenBucket;
|
||
|
|
use crate::sanitize;
|
||
|
|
use crate::session::{self, Keys};
|
||
|
|
use crate::store::{Friend, FriendProfile, Message, PaymentWrite, Store};
|
||
|
|
use crate::wallet::{self, Wallet};
|
||
|
|
|
||
|
|
pub struct RotateResult {
|
||
|
|
pub notified: usize,
|
||
|
|
pub friends: usize,
|
||
|
|
}
|
||
|
|
|
||
|
|
/// What a `flush` actually managed to do, for UI surfacing.
|
||
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
|
|
pub struct FlushOutcome {
|
||
|
|
/// Outbox rows we tried to deliver in this pass.
|
||
|
|
pub attempted: usize,
|
||
|
|
/// Rows delivered now — their outbox rows are gone.
|
||
|
|
pub delivered: usize,
|
||
|
|
/// Rows still queued or terminally failed after the pass.
|
||
|
|
pub remaining: usize,
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A foreground/unlock flush is bounded: the caller is a UI thread and a dead
|
||
|
|
/// peer's onion can hold a dial open for 20s. Whatever is left stays queued and
|
||
|
|
/// the retry worker picks it up on its normal schedule.
|
||
|
|
pub const FLUSH_TIMEOUT: Duration = Duration::from_secs(30);
|
||
|
|
/// The drain inside `shutdown` gets a shorter budget: teardown must not hang
|
||
|
|
/// the caller behind a Tor dial. Undelivered rows survive in sqlite.
|
||
|
|
pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10);
|
||
|
|
|
||
|
|
struct HsHandle {
|
||
|
|
svc: Arc<RunningOnionService>,
|
||
|
|
rend: tokio::task::JoinHandle<()>,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl Drop for HsHandle {
|
||
|
|
fn drop(&mut self) {
|
||
|
|
self.rend.abort();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Abort the outbox worker when the node goes away.
|
||
|
|
struct WorkerHandle(tokio::task::JoinHandle<()>);
|
||
|
|
|
||
|
|
impl Drop for WorkerHandle {
|
||
|
|
fn drop(&mut self) {
|
||
|
|
self.0.abort();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
pub struct Node {
|
||
|
|
home: PathBuf,
|
||
|
|
store: Arc<Mutex<Store>>,
|
||
|
|
client: Client,
|
||
|
|
hs: Mutex<Option<HsHandle>>,
|
||
|
|
onion: Mutex<String>,
|
||
|
|
keys: Mutex<Keys>,
|
||
|
|
wallet: Wallet,
|
||
|
|
incoming_limit: Mutex<TokenBucket>,
|
||
|
|
inbox: Mutex<file::Inbox>,
|
||
|
|
outbox: Arc<Outbox>,
|
||
|
|
worker: Mutex<Option<WorkerHandle>>,
|
||
|
|
/// Set by `shutdown`. Checked before any operation that would touch Tor or
|
||
|
|
/// the store, so a stopped node fails cleanly instead of dialing.
|
||
|
|
stopped: AtomicBool,
|
||
|
|
/// Has this node's onion service ever crossed the reachability bar (status
|
||
|
|
/// `Running`/`DegradedReachable`, or a successful probe of our own onion)?
|
||
|
|
/// Arti's combined status can stay `Bootstrapping` for minutes *after* the
|
||
|
|
/// descriptor is downloadable, so without this the UI would keep saying
|
||
|
|
/// "starting" long past the point where friends can reach us. Cleared when
|
||
|
|
/// `rotate` hard-cuts the service.
|
||
|
|
onion_reachable: AtomicBool,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl Node {
|
||
|
|
pub async fn start(home: PathBuf) -> Result<Arc<Self>, String> {
|
||
|
|
let pass = Zeroizing::new(
|
||
|
|
std::env::var("ONIONWIRE_STORE_PASSPHRASE")
|
||
|
|
.map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?,
|
||
|
|
);
|
||
|
|
if pass.is_empty() {
|
||
|
|
return Err("empty passphrase".into());
|
||
|
|
}
|
||
|
|
Self::start_with_passphrase(home, pass.as_str()).await
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn start_with_passphrase(
|
||
|
|
home: PathBuf,
|
||
|
|
passphrase: &str,
|
||
|
|
) -> Result<Arc<Self>, String> {
|
||
|
|
let store = Store::open_at_with_passphrase(&home, passphrase).map_err(|e| e.to_string())?;
|
||
|
|
let me = store.self_identity().map_err(|e| e.to_string())?;
|
||
|
|
let keys = Keys::from_self(&me).map_err(|e| e.to_string())?;
|
||
|
|
let nickname = store.hs_nickname().map_err(|e| e.to_string())?;
|
||
|
|
let state = home.join("arti");
|
||
|
|
let cache = home.join("cache");
|
||
|
|
let client = hs::bootstrapped(&state, &cache).await?;
|
||
|
|
let launched = client
|
||
|
|
.launch_onion_service(hs::hs_config(&nickname)?)
|
||
|
|
.map_err(|e| format!("launch_onion_service: {e}"))?
|
||
|
|
.ok_or_else(|| "onion service disabled in config — fail closed".to_string())?;
|
||
|
|
let (svc, rend) = launched;
|
||
|
|
let onion = hs::onion_string(&svc)?;
|
||
|
|
let inbox = file::Inbox::new(home.join("inbox"));
|
||
|
|
let store = Arc::new(Mutex::new(store));
|
||
|
|
let outbox = Arc::new(Outbox::new(
|
||
|
|
Arc::clone(&store),
|
||
|
|
Arc::new(ArtiDeliverer::new(client.clone(), keys.clone())),
|
||
|
|
));
|
||
|
|
if let Err(e) = outbox.reset_stale() {
|
||
|
|
eprintln!("outbox: {e}");
|
||
|
|
}
|
||
|
|
let node = Arc::new(Self {
|
||
|
|
home,
|
||
|
|
store,
|
||
|
|
client,
|
||
|
|
hs: Mutex::new(None),
|
||
|
|
onion: Mutex::new(onion.clone()),
|
||
|
|
keys: Mutex::new(keys),
|
||
|
|
wallet: Wallet::from_env(),
|
||
|
|
incoming_limit: Mutex::new(TokenBucket::default()),
|
||
|
|
inbox: Mutex::new(inbox),
|
||
|
|
outbox: Arc::clone(&outbox),
|
||
|
|
worker: Mutex::new(Some(WorkerHandle(outbox.spawn_worker()))),
|
||
|
|
stopped: AtomicBool::new(false),
|
||
|
|
onion_reachable: AtomicBool::new(false),
|
||
|
|
});
|
||
|
|
// Unlock trigger: flush anything queued by a previous run now, in the
|
||
|
|
// background, rather than waiting out its backoff.
|
||
|
|
spawn_flush_all(Arc::clone(&node.outbox));
|
||
|
|
// Accept rens before waiting so a reachability probe can succeed
|
||
|
|
// while combined status is still Bootstrapping.
|
||
|
|
let rend = spawn_rend(Arc::clone(&node), rend);
|
||
|
|
*node.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
|
||
|
|
svc: Arc::clone(&svc),
|
||
|
|
rend,
|
||
|
|
});
|
||
|
|
hs::wait_until_published(&node.client, &svc, &onion).await?;
|
||
|
|
// Published by the same bar `wait_until_published` uses — a probe
|
||
|
|
// success counts, which is the whole reason `tor_state` tracks it
|
||
|
|
// separately from Arti's (slower, flappier) combined status.
|
||
|
|
node.onion_reachable.store(true, Ordering::SeqCst);
|
||
|
|
node.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.set_onion(&onion)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(node)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Observable onion/Tor lifecycle state: `Bootstrapping` / `Published` /
|
||
|
|
/// `DegradedReachable` / `Stopped`.
|
||
|
|
///
|
||
|
|
/// Read-only and cheap (one mutex + one status read, no I/O), so a UI or a
|
||
|
|
/// foreground-service notification can poll it instead of guessing from a
|
||
|
|
/// timer. A poisoned handle is reported as `Stopped` rather than panicking:
|
||
|
|
/// the node is unusable either way, and the caller is often a UI thread.
|
||
|
|
pub fn tor_state(&self) -> TorState {
|
||
|
|
let stopped = self.stopped.load(Ordering::SeqCst);
|
||
|
|
let reachable = self.onion_reachable.load(Ordering::SeqCst);
|
||
|
|
match self.hs.lock() {
|
||
|
|
Ok(guard) => match guard.as_ref() {
|
||
|
|
Some(h) => hs::tor_state_of(h.svc.status().state(), stopped, reachable),
|
||
|
|
// Between `rotate`'s hard cut and the new service being
|
||
|
|
// installed there is no handle; before the first publish there
|
||
|
|
// is none either. Both are "not serving *yet*" unless we stopped.
|
||
|
|
None if stopped => TorState::Stopped,
|
||
|
|
None => TorState::Bootstrapping,
|
||
|
|
},
|
||
|
|
Err(_) => TorState::Stopped,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Drain the outbox: one delivery attempt for every outstanding row, now,
|
||
|
|
/// ignoring its retry schedule. Then checkpoint the WAL.
|
||
|
|
///
|
||
|
|
/// This is the "deliver what is deliverable before we lose the process"
|
||
|
|
/// call. Bounded by [`FLUSH_TIMEOUT`] because a dead peer's onion holds a
|
||
|
|
/// dial for ~20s and the caller is usually a UI thread. Rows that could not
|
||
|
|
/// be delivered stay queued and are picked up by the retry worker on its
|
||
|
|
/// normal backoff.
|
||
|
|
pub async fn flush(&self) -> Result<FlushOutcome, String> {
|
||
|
|
self.ensure_running()?;
|
||
|
|
let outcome = self.drain(FLUSH_TIMEOUT).await?;
|
||
|
|
self.checkpoint();
|
||
|
|
Ok(outcome)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Stop the node.
|
||
|
|
///
|
||
|
|
/// Order matters: drain the outbox while the Tor client is still alive,
|
||
|
|
/// then drop the onion service (its rendezvous task is aborted and the v3
|
||
|
|
/// service goes down), then abort the retry worker so nothing dials after
|
||
|
|
/// this, then checkpoint the WAL.
|
||
|
|
///
|
||
|
|
/// Idempotent: the flag is swapped first, so a second call — or a call
|
||
|
|
/// racing another teardown — returns `Ok(())` without touching anything
|
||
|
|
/// twice. Every other method on a stopped node returns a clean `Err`, never
|
||
|
|
/// a panic. A process killed outright never gets here at all, which is why
|
||
|
|
/// [`flush`](Self::flush) exists.
|
||
|
|
pub async fn shutdown(&self) -> Result<(), String> {
|
||
|
|
if self.stopped.swap(true, Ordering::SeqCst) {
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
// Bounded: teardown must not hang behind a Tor dial. Undelivered rows
|
||
|
|
// survive in sqlite and are retried on the next unlock.
|
||
|
|
match self.drain(SHUTDOWN_FLUSH_TIMEOUT).await {
|
||
|
|
Ok(o) if o.remaining > 0 => {
|
||
|
|
eprintln!("shutdown: {} outbox row(s) still pending", o.remaining)
|
||
|
|
}
|
||
|
|
Ok(_) => {}
|
||
|
|
Err(e) => eprintln!("shutdown: drain failed: {e}"),
|
||
|
|
}
|
||
|
|
match self.hs.lock() {
|
||
|
|
Ok(mut g) => *g = None,
|
||
|
|
Err(_) => eprintln!("shutdown: onion-service lock poisoned"),
|
||
|
|
}
|
||
|
|
match self.worker.lock() {
|
||
|
|
Ok(mut g) => drop(g.take()),
|
||
|
|
Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"),
|
||
|
|
}
|
||
|
|
self.checkpoint();
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One bounded pass over every outstanding outbox row.
|
||
|
|
///
|
||
|
|
/// A timeout cancels the pass mid-flight, which can leave a row in
|
||
|
|
/// `sending`; `Outbox::reset_stale` requeues those on the next unlock, the
|
||
|
|
/// same recovery the parent uses for a process that died mid-attempt.
|
||
|
|
async fn drain(&self, budget: Duration) -> Result<FlushOutcome, String> {
|
||
|
|
let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await {
|
||
|
|
Ok(Ok(rows)) => Some(rows),
|
||
|
|
Ok(Err(e)) => return Err(e),
|
||
|
|
Err(_) => {
|
||
|
|
eprintln!("outbox: drain hit its {budget:?} budget, undelivered rows stay queued");
|
||
|
|
None
|
||
|
|
}
|
||
|
|
};
|
||
|
|
let delivered = attempted
|
||
|
|
.as_ref()
|
||
|
|
.map(|rows| {
|
||
|
|
rows.iter()
|
||
|
|
.filter(|(_, s)| matches!(s, OutboxStatus::Sent))
|
||
|
|
.count()
|
||
|
|
})
|
||
|
|
.unwrap_or(0);
|
||
|
|
Ok(FlushOutcome {
|
||
|
|
// `None` means the pass was cancelled: we know how many rows are
|
||
|
|
// still queued, not how many were started.
|
||
|
|
attempted: attempted.as_ref().map(Vec::len).unwrap_or(0),
|
||
|
|
delivered,
|
||
|
|
remaining: self.pending_rows()?,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Rows the outbox still holds for every friend, queued or terminally
|
||
|
|
/// failed. A message absent here was delivered.
|
||
|
|
fn pending_rows(&self) -> Result<usize, String> {
|
||
|
|
let friends = self.list_friends()?;
|
||
|
|
let mut n = 0usize;
|
||
|
|
for f in &friends {
|
||
|
|
n += self.outbox.pending(&f.pubkey)?.len();
|
||
|
|
}
|
||
|
|
Ok(n)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Checkpoint the sqlite WAL into the main db file and truncate it.
|
||
|
|
///
|
||
|
|
/// Best effort on purpose: WAL replay on open recovers everything committed,
|
||
|
|
/// so this is about leaving less to replay (and less on disk) if the
|
||
|
|
/// process is killed right after teardown — not about correctness.
|
||
|
|
fn checkpoint(&self) {
|
||
|
|
let store = match self.store.lock() {
|
||
|
|
Ok(s) => s,
|
||
|
|
Err(e) => {
|
||
|
|
eprintln!("wal checkpoint: store lock poisoned: {e}");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
};
|
||
|
|
if let Err(e) = store.checkpoint_wal() {
|
||
|
|
eprintln!("wal checkpoint: {e}");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fn ensure_running(&self) -> Result<(), String> {
|
||
|
|
if self.stopped.load(Ordering::SeqCst) {
|
||
|
|
return Err("node is stopped — open the identity again".to_string());
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn onion(&self) -> String {
|
||
|
|
self.onion.lock().map(|g| g.clone()).unwrap_or_default()
|
||
|
|
}
|
||
|
|
|
||
|
|
fn keys(&self) -> Result<Keys, String> {
|
||
|
|
self.keys
|
||
|
|
.lock()
|
||
|
|
.map(|g| g.clone())
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn identity_pk(&self) -> [u8; 32] {
|
||
|
|
self.keys().map(|k| k.identity_pk).unwrap_or([0; 32])
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn arti_dir(&self) -> PathBuf {
|
||
|
|
self.home.join("arti")
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn cache_dir(&self) -> PathBuf {
|
||
|
|
self.home.join("cache")
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn qr_payload(&self) -> Result<String, String> {
|
||
|
|
let k = self.keys()?;
|
||
|
|
qr::encode(&k.identity_sk, &self.onion(), &k.prekey_pk).map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn write_backup(&self, path: &str, passphrase: &str) -> Result<(), String> {
|
||
|
|
use std::io::Write;
|
||
|
|
use std::os::unix::fs::OpenOptionsExt;
|
||
|
|
let k = self.keys()?;
|
||
|
|
let blob = crate::backup::seal(
|
||
|
|
passphrase,
|
||
|
|
&crate::backup::BackupKeys {
|
||
|
|
identity_sk: k.identity_sk,
|
||
|
|
identity_pk: k.identity_pk,
|
||
|
|
prekey_sk: k.prekey_sk,
|
||
|
|
prekey_pk: k.prekey_pk,
|
||
|
|
},
|
||
|
|
)?;
|
||
|
|
let mut f = std::fs::OpenOptions::new()
|
||
|
|
.write(true)
|
||
|
|
.create(true)
|
||
|
|
.truncate(true)
|
||
|
|
.mode(0o600)
|
||
|
|
.open(path)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
f.write_all(&blob).map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn restore_backup(&self, path: &str, passphrase: &str) -> Result<(), String> {
|
||
|
|
let blob = std::fs::read(path).map_err(|e| e.to_string())?;
|
||
|
|
let k = crate::backup::open(passphrase, &blob)?;
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.replace_identity_keys(&k.identity_sk, &k.identity_pk, &k.prekey_sk, &k.prekey_pk)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
*self.keys.lock().map_err(|e| e.to_string())? = Keys {
|
||
|
|
identity_sk: k.identity_sk,
|
||
|
|
identity_pk: k.identity_pk,
|
||
|
|
prekey_sk: k.prekey_sk,
|
||
|
|
prekey_pk: k.prekey_pk,
|
||
|
|
};
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn add_friend_from_qr(&self, raw: &str) -> Result<(), String> {
|
||
|
|
let p = qr::decode(raw).map_err(|e| e.to_string())?;
|
||
|
|
self.add_friend_payload(&p)
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn add_friend_payload(&self, p: &qr::QrPayload) -> Result<(), String> {
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
let prekey_changed = store
|
||
|
|
.get_friend(&p.pubkey)
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.map(|f| f.prekey != p.signed_prekey)
|
||
|
|
.unwrap_or(false);
|
||
|
|
store
|
||
|
|
.upsert_friend(&p.pubkey, &p.onion, None)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.set_friend_prekey(&p.pubkey, &p.signed_prekey)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
if prekey_changed {
|
||
|
|
// The bootstrap epoch is derived from the peers' static prekey DH,
|
||
|
|
// so a refreshed invite makes the stored ratchet state unusable on
|
||
|
|
// both sides. Drop it: the next frame rebuilds a fresh state.
|
||
|
|
store.clear_ratchet(&p.pubkey).map_err(|e| e.to_string())?;
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn get_friend(&self, pubkey: &[u8]) -> Result<Option<Friend>, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.get_friend(pubkey)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn list_friends(&self) -> Result<Vec<Friend>, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.list_friends()
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Fingerprint of our own identity key (identity = pubkey).
|
||
|
|
pub fn fingerprint(&self) -> Result<String, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.self_fingerprint()
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Local-only label. Does not go on the wire.
|
||
|
|
pub fn set_petname(&self, pubkey: &[u8], petname: Option<&str>) -> Result<(), String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.set_petname(pubkey, petname)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn friend(&self, pubkey: &[u8]) -> Result<Friend, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.get_friend(pubkey)
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.ok_or_else(|| "friend not found".into())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn list_messages(&self, friend_pk: &[u8]) -> Result<Vec<Message>, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.list_messages(friend_pk)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Current wallet balance as a human-readable XMR string, or `off` when the
|
||
|
|
/// wallet is not configured.
|
||
|
|
pub async fn wallet_balance(&self) -> String {
|
||
|
|
if !self.wallet.configured() {
|
||
|
|
return "off".into();
|
||
|
|
}
|
||
|
|
match self.wallet.get_balance().await {
|
||
|
|
Ok(b) => crate::pay::atomic_to_xmr_str(&b),
|
||
|
|
Err(_) => "err".into(),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
pub fn wipe_messages(&self) -> Result<(), String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.wipe_messages()
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn self_profile(&self) -> Result<FriendProfile, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.self_profile()
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn friend_profile(&self, pubkey: &[u8]) -> Result<Option<FriendProfile>, String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.friend_profile(pubkey)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn set_self_profile(
|
||
|
|
&self,
|
||
|
|
display_name: &str,
|
||
|
|
bio: &str,
|
||
|
|
xmr_addr: &str,
|
||
|
|
) -> Result<(), String> {
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.set_self_profile(display_name, bio, xmr_addr)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One-shot signed `prf` to a friend. Fail closed; no retry, no outbox.
|
||
|
|
pub async fn push_self_profile(&self, friend_pk: &[u8]) -> Result<(), String> {
|
||
|
|
let me = self.self_profile()?;
|
||
|
|
let k = self.keys()?;
|
||
|
|
let prf = profile::sign(
|
||
|
|
&k.identity_sk,
|
||
|
|
&me.display_name,
|
||
|
|
&me.bio,
|
||
|
|
&me.xmr_addr,
|
||
|
|
me.updated_at,
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let pt = profile::encode(&prf);
|
||
|
|
let (onion, prekey) = {
|
||
|
|
let f = self.friend(friend_pk)?;
|
||
|
|
if f.prekey.len() != 32 {
|
||
|
|
return Err("friend missing prekey".into());
|
||
|
|
}
|
||
|
|
(f.onion, f.prekey)
|
||
|
|
};
|
||
|
|
self.try_send(&onion, friend_pk, &prekey, &pt).await
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Sign an invoice with this node's identity key.
|
||
|
|
///
|
||
|
|
/// The signing half of [`Self::pay_invoice`], for callers that build the
|
||
|
|
/// frame themselves (the Android SDK). The ed25519 secret never leaves the
|
||
|
|
/// node: it is signed with here and not handed out. `amount_atomic` is
|
||
|
|
/// piconero; `address` must be a valid Monero address; `memo` may be empty.
|
||
|
|
pub fn sign_invoice(
|
||
|
|
&self,
|
||
|
|
amount_atomic: &str,
|
||
|
|
address: &str,
|
||
|
|
memo: &str,
|
||
|
|
) -> Result<pay::Invoice, String> {
|
||
|
|
let k = self.keys()?;
|
||
|
|
pay::sign_invoice(&k.identity_sk, amount_atomic, address, memo, unix_now())
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Sign a receipt for a transfer that already happened: the signing half of
|
||
|
|
/// [`Self::tip`]. Same key discipline as [`Self::sign_invoice`].
|
||
|
|
pub fn sign_receipt(
|
||
|
|
&self,
|
||
|
|
txid: &str,
|
||
|
|
amount_atomic: &str,
|
||
|
|
address: &str,
|
||
|
|
) -> Result<pay::Receipt, String> {
|
||
|
|
let k = self.keys()?;
|
||
|
|
pay::sign_receipt(&k.identity_sk, txid, amount_atomic, address, unix_now())
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Sign a tip frame (receipt + memo) for a transfer that already happened.
|
||
|
|
/// This signs only — it does not move funds; that is [`Self::tip`].
|
||
|
|
pub fn sign_tip(
|
||
|
|
&self,
|
||
|
|
txid: &str,
|
||
|
|
amount_atomic: &str,
|
||
|
|
address: &str,
|
||
|
|
memo: &str,
|
||
|
|
) -> Result<pay::Tip, String> {
|
||
|
|
let k = self.keys()?;
|
||
|
|
pay::sign_tip(
|
||
|
|
&k.identity_sk,
|
||
|
|
txid,
|
||
|
|
amount_atomic,
|
||
|
|
address,
|
||
|
|
memo,
|
||
|
|
unix_now(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Invoice to receive. Wallet subaddress if up, else self_profile.xmr_addr.
|
||
|
|
pub async fn pay_invoice(
|
||
|
|
&self,
|
||
|
|
friend_pk: &[u8],
|
||
|
|
atomic: &str,
|
||
|
|
memo: &str,
|
||
|
|
) -> Result<(), String> {
|
||
|
|
let address = self.invoice_address().await?;
|
||
|
|
let inv = self.sign_invoice(atomic, &address, memo)?;
|
||
|
|
let pt = pay::encode_invoice(&inv);
|
||
|
|
self.send_once(friend_pk, &pt).await?;
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.insert_payment(
|
||
|
|
friend_pk,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "out",
|
||
|
|
kind: "invoice",
|
||
|
|
amount_atomic: atomic,
|
||
|
|
address: &address,
|
||
|
|
memo,
|
||
|
|
txid: None,
|
||
|
|
verified: false,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.append_message(
|
||
|
|
friend_pk,
|
||
|
|
"out",
|
||
|
|
pay::invoice_chat_line(atomic, memo).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Pay selected friend via wallet RPC, then signed receipt.
|
||
|
|
pub async fn tip(&self, friend_pk: &[u8], atomic: &str, _memo: &str) -> Result<(), String> {
|
||
|
|
if !self.wallet.configured() {
|
||
|
|
return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into());
|
||
|
|
}
|
||
|
|
let address = self
|
||
|
|
.friend_profile(friend_pk)?
|
||
|
|
.map(|p| p.xmr_addr)
|
||
|
|
.unwrap_or_default();
|
||
|
|
if address.is_empty() {
|
||
|
|
return Err("friend has no Monero address — they must /profile".into());
|
||
|
|
}
|
||
|
|
pay::check_address(&address).map_err(|e| e.to_string())?;
|
||
|
|
let amount: u64 = atomic
|
||
|
|
.parse()
|
||
|
|
.map_err(|_| "amount too large for wallet RPC".to_string())?;
|
||
|
|
let txid = self
|
||
|
|
.wallet
|
||
|
|
.transfer(&address, amount)
|
||
|
|
.await
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let rcp = self.sign_receipt(&txid, atomic, &address)?;
|
||
|
|
let rcp_pt = pay::encode_receipt(&rcp);
|
||
|
|
let tip = self.sign_tip(&txid, atomic, &address, _memo)?;
|
||
|
|
let tip_pt = pay::encode_tip(&tip);
|
||
|
|
self.send_once(friend_pk, &rcp_pt).await?;
|
||
|
|
self.send_once(friend_pk, &tip_pt).await?;
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.insert_payment(
|
||
|
|
friend_pk,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "out",
|
||
|
|
kind: "receipt",
|
||
|
|
amount_atomic: atomic,
|
||
|
|
address: &address,
|
||
|
|
memo: "",
|
||
|
|
txid: Some(&txid),
|
||
|
|
verified: true,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.append_message(
|
||
|
|
friend_pk,
|
||
|
|
"out",
|
||
|
|
pay::receipt_chat_line(atomic, true).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
// The receipt line is the recipient's view of the frame that arrived;
|
||
|
|
// the payer's own chat shows the tip they just spent (unverified: the
|
||
|
|
// recipient has not confirmed it).
|
||
|
|
store
|
||
|
|
.append_message(
|
||
|
|
friend_pk,
|
||
|
|
"out",
|
||
|
|
pay::tip_chat_line(atomic, _memo, false).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn invoice_address(&self) -> Result<String, String> {
|
||
|
|
if self.wallet.configured()
|
||
|
|
&& let Ok(addr) = self.wallet.create_address().await
|
||
|
|
&& pay::check_address(&addr).is_ok()
|
||
|
|
{
|
||
|
|
return Ok(addr);
|
||
|
|
}
|
||
|
|
let profile_addr = self.self_profile()?.xmr_addr;
|
||
|
|
if profile_addr.is_empty() {
|
||
|
|
return Err("no receive address — set profile xmr or ONIONWIRE_WALLET_RPC".into());
|
||
|
|
}
|
||
|
|
pay::check_address(&profile_addr).map_err(|e| e.to_string())?;
|
||
|
|
Ok(profile_addr)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Receive address for the wallet screen: a freshly created subaddress when
|
||
|
|
/// the wallet is configured, else the profile `xmr_addr` fallback. Returns
|
||
|
|
/// the raw address (not a `monero:` URI) so the QR render path can decide
|
||
|
|
/// how to wrap it.
|
||
|
|
pub async fn wallet_receive_address(&self) -> Result<String, String> {
|
||
|
|
let profile_addr = self.self_profile()?.xmr_addr;
|
||
|
|
if self
|
||
|
|
.wallet
|
||
|
|
.configured()
|
||
|
|
&& let Ok(addr) = self.wallet.get_address().await
|
||
|
|
&& pay::check_address(&addr).is_ok()
|
||
|
|
{
|
||
|
|
return Ok(addr);
|
||
|
|
}
|
||
|
|
if !profile_addr.is_empty() {
|
||
|
|
pay::check_address(&profile_addr).map_err(|e| e.to_string())?;
|
||
|
|
return Ok(profile_addr);
|
||
|
|
}
|
||
|
|
Err("no receive address — set profile xmr or ONIONWIRE_WALLET_RPC".into())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Formatted balance for the wallet screen, or "off" when the wallet is not
|
||
|
|
/// configured. Calls `pay::atomic_to_xmr_str` so the UI never parses
|
||
|
|
/// piconero itself.
|
||
|
|
pub async fn wallet_balance_line(&self) -> String {
|
||
|
|
if self.wallet.configured() {
|
||
|
|
match self.wallet.get_balance().await {
|
||
|
|
Ok(b) if !b.is_empty() => {
|
||
|
|
let xmr = pay::atomic_to_xmr_str(&b);
|
||
|
|
if xmr == "0" {
|
||
|
|
"balance 0 XMR".to_string()
|
||
|
|
} else {
|
||
|
|
format!("balance {xmr} XMR")
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Ok(_) => "balance —".to_string(),
|
||
|
|
Err(_) => "balance —".to_string(),
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
"wallet off".to_string()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Recent in/out transfers for the wallet screen, newest first, capped to a
|
||
|
|
/// small window. Returns the same `TransferRow` shape the existing tests
|
||
|
|
/// already cover.
|
||
|
|
pub async fn wallet_recent_transfers(&self, cap: usize) -> Result<Vec<wallet::TransferRow>, String> {
|
||
|
|
if !self.wallet.configured() {
|
||
|
|
return Ok(Vec::new());
|
||
|
|
}
|
||
|
|
let rows = self.wallet.get_transfers().await.map_err(|e| e.to_string())?;
|
||
|
|
let mut rows = rows;
|
||
|
|
rows.sort_by(|a, b| b.txid.cmp(&a.txid));
|
||
|
|
Ok(rows.into_iter().take(cap).collect())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Create a new spend-capable wallet. Returns the seed once for backup.
|
||
|
|
/// The user never pastes a key on this path.
|
||
|
|
pub async fn wallet_create(&self, password: &str) -> Result<String, String> {
|
||
|
|
if !self.wallet.configured() {
|
||
|
|
return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into());
|
||
|
|
}
|
||
|
|
self.wallet
|
||
|
|
.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password)
|
||
|
|
.await
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Import a wallet from an existing 25-word seed. This is the only path
|
||
|
|
/// that takes a user-supplied secret.
|
||
|
|
pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> {
|
||
|
|
if !self.wallet.configured() {
|
||
|
|
return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into());
|
||
|
|
}
|
||
|
|
self.wallet
|
||
|
|
.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed)
|
||
|
|
.await
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
|
||
|
|
self.ensure_running()?;
|
||
|
|
let (onion, prekey) = {
|
||
|
|
let f = self.friend(friend_pk)?;
|
||
|
|
if f.prekey.len() != 32 {
|
||
|
|
return Err("friend missing prekey".into());
|
||
|
|
}
|
||
|
|
(f.onion, f.prekey)
|
||
|
|
};
|
||
|
|
self.try_send(&onion, friend_pk, &prekey, plaintext).await
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Dial a peer's onion. Success is evidence the peer is up, which is one of
|
||
|
|
/// the outbox retry triggers.
|
||
|
|
pub async fn connect_onion(&self, onion: &str) -> Result<(), String> {
|
||
|
|
self.ensure_running()?;
|
||
|
|
tokio::time::timeout(
|
||
|
|
Duration::from_secs(20),
|
||
|
|
self.client.connect((onion, HS_PORT)),
|
||
|
|
)
|
||
|
|
.await
|
||
|
|
.map_err(|_| format!("connect {onion}:{HS_PORT} timed out"))?
|
||
|
|
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
|
||
|
|
if let Ok(Some(friend)) = self
|
||
|
|
.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
.and_then(|s| s.friend_by_onion(onion).map_err(|e| e.to_string()))
|
||
|
|
{
|
||
|
|
spawn_flush_friend(Arc::clone(&self.outbox), friend.pubkey);
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn rotate(self: &Arc<Self>) -> Result<RotateResult, String> {
|
||
|
|
self.ensure_running()?;
|
||
|
|
let old_nick = self
|
||
|
|
.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.hs_nickname()
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let new_nick = next_hs_nickname(&old_nick);
|
||
|
|
let launched = self
|
||
|
|
.client
|
||
|
|
.launch_onion_service(hs::hs_config(&new_nick)?)
|
||
|
|
.map_err(|e| format!("launch_onion_service: {e}"))?
|
||
|
|
.ok_or_else(|| "onion service disabled in config — fail closed".to_string())?;
|
||
|
|
let (svc, rend) = launched;
|
||
|
|
let onion = hs::onion_string(&svc)?;
|
||
|
|
// ponytail: hard-cut old HS before waiting; keeping both stalled ow1 at Bootstrapping.
|
||
|
|
*self.hs.lock().map_err(|e| e.to_string())? = None;
|
||
|
|
// The new service is not reachable until it publishes: the locator in
|
||
|
|
// flight is dead until then, so do not carry the old verdict over.
|
||
|
|
self.onion_reachable.store(false, Ordering::SeqCst);
|
||
|
|
let rend = spawn_rend(Arc::clone(self), rend);
|
||
|
|
*self.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
|
||
|
|
svc: Arc::clone(&svc),
|
||
|
|
rend,
|
||
|
|
});
|
||
|
|
hs::wait_until_published(&self.client, &svc, &onion).await?;
|
||
|
|
self.onion_reachable.store(true, Ordering::SeqCst);
|
||
|
|
{
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
store.set_onion(&onion).map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.set_hs_nickname(&new_nick)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
}
|
||
|
|
*self.onion.lock().map_err(|e| e.to_string())? = onion.clone();
|
||
|
|
|
||
|
|
let ts = unix_now();
|
||
|
|
let k = self.keys()?;
|
||
|
|
let loc = loc::sign(&k.identity_sk, &onion, ts).map_err(|e| e.to_string())?;
|
||
|
|
let loc_pt = loc::encode(&loc);
|
||
|
|
let friends = self
|
||
|
|
.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.list_friends()
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let mut notified = 0;
|
||
|
|
for f in &friends {
|
||
|
|
if self
|
||
|
|
.push_loc(&f.pubkey, &f.onion, &f.prekey, &loc_pt)
|
||
|
|
.await
|
||
|
|
.is_ok()
|
||
|
|
{
|
||
|
|
notified += 1;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
Ok(RotateResult {
|
||
|
|
notified,
|
||
|
|
friends: friends.len(),
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One-shot file to a friend. Fail closed; no outbox, no resume.
|
||
|
|
/// Chunks are paced (`file::CHUNK_PACE`) with bounded per-chunk retry so
|
||
|
|
/// a 1 MiB transfer fits the receiver's rendezvous token bucket.
|
||
|
|
pub async fn send_file(&self, friend_pk: &[u8], path: &Path) -> Result<String, String> {
|
||
|
|
let (name, bytes) = file::read_limited(path).map_err(|e| e.to_string())?;
|
||
|
|
let chunks = file::chunks(&name, &bytes).map_err(|e| e.to_string())?;
|
||
|
|
let frames: Vec<Vec<u8>> = chunks.iter().map(file::encode).collect();
|
||
|
|
file::send_chunks(frames.len(), |i| self.send_once(friend_pk, &frames[i])).await?;
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.append_message(
|
||
|
|
friend_pk,
|
||
|
|
"out",
|
||
|
|
file::chat_line(&name, bytes.len()).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(name)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Send one chat message. Returns `Sent` when it went out now and `Queued`
|
||
|
|
/// when the peer's onion is unreachable — the outbox worker then retries with
|
||
|
|
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
|
||
|
|
/// frame) still fails immediately and is never retried.
|
||
|
|
///
|
||
|
|
/// Chat travels as a `rat ` frame: the plaintext is ratchet-encrypted once,
|
||
|
|
/// here, before the first attempt, and the frame is what the outbox retries.
|
||
|
|
/// Local history keeps the plaintext (the store is encrypted at rest).
|
||
|
|
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
|
||
|
|
self.ensure_running()?;
|
||
|
|
let keys = self.keys()?;
|
||
|
|
let frame = {
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
encode_chat_frame(&store, &keys, friend_pk, plaintext)?
|
||
|
|
};
|
||
|
|
self.outbox.send_payload(friend_pk, plaintext, &frame).await
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Pending and failed outbox rows for a friend, for UI surfacing.
|
||
|
|
/// Delivered rows are dropped, so a message absent here was sent.
|
||
|
|
pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result<Vec<crate::store::OutboxEntry>, String> {
|
||
|
|
self.outbox.pending(friend_pk)
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn outbox_status_of_message(
|
||
|
|
&self,
|
||
|
|
message_id: i64,
|
||
|
|
) -> Result<Option<OutboxStatus>, String> {
|
||
|
|
self.outbox.status_of_message(message_id)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Foreground/unlock trigger: try every outstanding queued send now.
|
||
|
|
pub fn flush_outbox(&self) {
|
||
|
|
spawn_flush_all(Arc::clone(&self.outbox));
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn push_loc(
|
||
|
|
&self,
|
||
|
|
friend_pk: &[u8],
|
||
|
|
onion: &str,
|
||
|
|
prekey: &[u8],
|
||
|
|
loc_pt: &[u8],
|
||
|
|
) -> Result<(), String> {
|
||
|
|
if prekey.len() != 32 {
|
||
|
|
return Err("friend missing prekey".into());
|
||
|
|
}
|
||
|
|
let deadline = Instant::now() + Duration::from_secs(180);
|
||
|
|
let mut last = None::<String>;
|
||
|
|
while Instant::now() < deadline {
|
||
|
|
match self.try_send(onion, friend_pk, prekey, loc_pt).await {
|
||
|
|
Ok(()) => return Ok(()),
|
||
|
|
Err(e) if e.contains("fingerprint mismatch") => return Err(e),
|
||
|
|
Err(e) => last = Some(e),
|
||
|
|
}
|
||
|
|
tokio::time::sleep(Duration::from_secs(3)).await;
|
||
|
|
}
|
||
|
|
Err(last.unwrap_or_else(|| "loc push timed out".into()))
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn try_send(
|
||
|
|
&self,
|
||
|
|
onion: &str,
|
||
|
|
pinned_id: &[u8],
|
||
|
|
remote_prekey: &[u8],
|
||
|
|
plaintext: &[u8],
|
||
|
|
) -> Result<(), String> {
|
||
|
|
self.outbox
|
||
|
|
.deliverer()
|
||
|
|
.deliver(onion, pinned_id, remote_prekey, plaintext)
|
||
|
|
.await
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn handle_incoming<S>(&self, stream: &mut S) -> Result<(), String>
|
||
|
|
where
|
||
|
|
S: AsyncRead + AsyncWrite + Unpin,
|
||
|
|
{
|
||
|
|
let store = &self.store;
|
||
|
|
let keys = self.keys()?;
|
||
|
|
let mut sess = session::handshake_responder(stream, &keys, |spk| {
|
||
|
|
let Ok(g) = store.lock() else {
|
||
|
|
return None;
|
||
|
|
};
|
||
|
|
g.get_friend_by_prekey(spk).ok().flatten().map(|f| f.pubkey)
|
||
|
|
})
|
||
|
|
.await
|
||
|
|
.map_err(session_err)?;
|
||
|
|
// Trigger (c): the peer just proved they are online. Try their queued
|
||
|
|
// sends now instead of waiting out the backoff, off this stream's path.
|
||
|
|
spawn_flush_friend(Arc::clone(&self.outbox), sess.peer_identity.clone());
|
||
|
|
let ct = frame::read_frame(stream).await.map_err(|e| e.to_string())?;
|
||
|
|
let pt = sess.decrypt(&ct).map_err(session_err)?;
|
||
|
|
match dispatch::classify(&pt) {
|
||
|
|
Kind::Loc => {
|
||
|
|
if let Some(loc) = loc::decode(&pt) {
|
||
|
|
let applied = store.lock().map_err(|e| e.to_string())?.apply_loc(
|
||
|
|
&sess.peer_identity,
|
||
|
|
&loc.onion,
|
||
|
|
loc.ts,
|
||
|
|
&loc.sig,
|
||
|
|
);
|
||
|
|
match applied {
|
||
|
|
Ok(true) => {}
|
||
|
|
Ok(false) => {
|
||
|
|
eprintln!("loc dropped (bad sig, stale ts, or unknown friend)")
|
||
|
|
}
|
||
|
|
Err(e) => return Err(e.to_string()),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
Kind::Profile => {
|
||
|
|
if let Some(prf) = profile::decode(&pt) {
|
||
|
|
let applied = store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.apply_profile(&sess.peer_identity, &prf);
|
||
|
|
match applied {
|
||
|
|
Ok(true) => {}
|
||
|
|
Ok(false) => {
|
||
|
|
eprintln!("prf dropped (bad sig, stale ts, or unknown friend)")
|
||
|
|
}
|
||
|
|
Err(e) => return Err(e.to_string()),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
Kind::Chat => {
|
||
|
|
store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.append_message(
|
||
|
|
&sess.peer_identity,
|
||
|
|
"in",
|
||
|
|
sanitize::display_text(&pt).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
Kind::Ratchet => {
|
||
|
|
// Chat arrives as a ratchet frame: decrypt, log the plaintext,
|
||
|
|
// drop the frame. A bad frame is logged and dropped — the
|
||
|
|
// ciphertext is never stored and there is no plaintext fallback.
|
||
|
|
let keys = self.keys()?;
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
if let Err(e) = ingest_chat_frame(&store, &keys, &sess.peer_identity, &pt) {
|
||
|
|
eprintln!("rat dropped ({e})");
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
Kind::Invoice => self.ingest_invoice(&sess.peer_identity, &pt).await,
|
||
|
|
Kind::Receipt => self.ingest_receipt(&sess.peer_identity, &pt).await,
|
||
|
|
Kind::Tip => self.ingest_tip(&sess.peer_identity, &pt).await,
|
||
|
|
Kind::File => self.ingest_file(&sess.peer_identity, &pt),
|
||
|
|
Kind::Ping | Kind::Drop => Ok(()),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fn ingest_file(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
||
|
|
let Some(chunk) = file::decode(pt) else {
|
||
|
|
return Ok(());
|
||
|
|
};
|
||
|
|
let fp: String = peer.iter().map(|b| format!("{b:02x}")).collect();
|
||
|
|
let done = {
|
||
|
|
let mut inbox = self.inbox.lock().map_err(|e| e.to_string())?;
|
||
|
|
match inbox.ingest(&fp, &chunk) {
|
||
|
|
Ok(p) => p,
|
||
|
|
Err(e) => {
|
||
|
|
eprintln!("fil dropped ({e})");
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
};
|
||
|
|
if let Some(path) = done {
|
||
|
|
let nbytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0) as usize;
|
||
|
|
let name = path
|
||
|
|
.file_name()
|
||
|
|
.and_then(|s| s.to_str())
|
||
|
|
.unwrap_or(&chunk.filename);
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.append_message(
|
||
|
|
peer,
|
||
|
|
"in",
|
||
|
|
sanitize::display_text(file::chat_line(name, nbytes).as_bytes()).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn ingest_invoice(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
||
|
|
let Some(inv) = pay::decode_invoice(pt) else {
|
||
|
|
return Ok(());
|
||
|
|
};
|
||
|
|
if !pay::verify_invoice(peer, &inv) {
|
||
|
|
eprintln!("inv dropped (bad sig)");
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.insert_payment(
|
||
|
|
peer,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "in",
|
||
|
|
kind: "invoice",
|
||
|
|
amount_atomic: &inv.amount_atomic,
|
||
|
|
address: &inv.address,
|
||
|
|
memo: &inv.memo,
|
||
|
|
txid: None,
|
||
|
|
verified: false,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.append_message(
|
||
|
|
peer,
|
||
|
|
"in",
|
||
|
|
pay::invoice_chat_line(&inv.amount_atomic, &inv.memo).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn ingest_receipt(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
||
|
|
let Some(rcp) = pay::decode_receipt(pt) else {
|
||
|
|
return Ok(());
|
||
|
|
};
|
||
|
|
if !pay::verify_receipt(peer, &rcp) {
|
||
|
|
eprintln!("rcp dropped (bad sig)");
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
let id = {
|
||
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||
|
|
store
|
||
|
|
.insert_payment(
|
||
|
|
peer,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "in",
|
||
|
|
kind: "receipt",
|
||
|
|
amount_atomic: &rcp.amount_atomic,
|
||
|
|
address: &rcp.address,
|
||
|
|
memo: "",
|
||
|
|
txid: Some(&rcp.txid),
|
||
|
|
verified: false,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
};
|
||
|
|
let mut verified = false;
|
||
|
|
if self.wallet.configured() {
|
||
|
|
match self.wallet.get_transfers().await {
|
||
|
|
Ok(rows)
|
||
|
|
if wallet::transfers_match(
|
||
|
|
&rows,
|
||
|
|
&rcp.txid,
|
||
|
|
&rcp.amount_atomic,
|
||
|
|
&rcp.address,
|
||
|
|
) =>
|
||
|
|
{
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.mark_verified(id)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
verified = true;
|
||
|
|
}
|
||
|
|
Ok(_) => {}
|
||
|
|
Err(e) => eprintln!("receipt unverified: {e}"),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if !verified {
|
||
|
|
eprintln!("receipt unverified");
|
||
|
|
}
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.append_message(
|
||
|
|
peer,
|
||
|
|
"in",
|
||
|
|
pay::receipt_chat_line(&rcp.amount_atomic, verified).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn ingest_tip(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
||
|
|
let Some(tip) = pay::decode_tip(pt) else {
|
||
|
|
return Ok(());
|
||
|
|
};
|
||
|
|
if !pay::verify_tip(peer, &tip) {
|
||
|
|
eprintln!("tip dropped (bad sig)");
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.insert_payment(
|
||
|
|
peer,
|
||
|
|
PaymentWrite {
|
||
|
|
dir: "in",
|
||
|
|
kind: "tip",
|
||
|
|
amount_atomic: &tip.amount_atomic,
|
||
|
|
address: &tip.address,
|
||
|
|
memo: &tip.memo,
|
||
|
|
txid: Some(&tip.txid),
|
||
|
|
verified: false,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
self.store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.append_message(
|
||
|
|
peer,
|
||
|
|
"in",
|
||
|
|
pay::tip_chat_line(&tip.amount_atomic, &tip.memo, false).as_bytes(),
|
||
|
|
)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// HKDF info strings for the bootstrap derivation (see [`bootstrap_ratchet`]).
|
||
|
|
const RATCHET_BOOTSTRAP_SALT: &[u8] = b"onionwire-ratchet-v1-bootstrap";
|
||
|
|
const RATCHET_BOOTSTRAP_ROOT_INFO: &[u8] = b"root";
|
||
|
|
const RATCHET_BOOTSTRAP_KEY_INFO: &[u8] = b"ratchet-key";
|
||
|
|
|
||
|
|
/// Bootstrap a peer's ratchet state from key material both sides already have.
|
||
|
|
///
|
||
|
|
/// The Noise handshake is frozen and carries no payload, so no wire field can
|
||
|
|
/// hand over an initial ratchet public key. Both peers instead derive the
|
||
|
|
/// bootstrap epoch from the X25519 DH of the two signed prekeys — each side
|
||
|
|
/// computes the same secret — and seed each side's initial ratchet keypair with
|
||
|
|
/// that DH plus *its own* identity pubkey. Each peer therefore derives its own
|
||
|
|
/// keypair and the peer's, and the two agree on the epoch without a new wire
|
||
|
|
/// field; fresh entropy enters at the first DH ratchet step. Because the
|
||
|
|
/// derivation is prekey-bound, a peer whose prekey changed gets its stored state
|
||
|
|
/// dropped (`Node::add_friend_payload`).
|
||
|
|
fn bootstrap_ratchet(
|
||
|
|
keys: &Keys,
|
||
|
|
peer_pk: &[u8],
|
||
|
|
peer_prekey: &[u8],
|
||
|
|
) -> Result<RatchetState, String> {
|
||
|
|
let peer_pk: [u8; 32] = peer_pk
|
||
|
|
.try_into()
|
||
|
|
.map_err(|_| "peer pubkey is not 32 bytes".to_string())?;
|
||
|
|
let peer_prekey: [u8; 32] = peer_prekey
|
||
|
|
.try_into()
|
||
|
|
.map_err(|_| "peer prekey is not 32 bytes".to_string())?;
|
||
|
|
let shared =
|
||
|
|
StaticSecret::from(keys.prekey_sk).diffie_hellman(&X25519Public::from(peer_prekey));
|
||
|
|
let hk = Hkdf::<Sha256>::new(Some(RATCHET_BOOTSTRAP_SALT), shared.as_bytes());
|
||
|
|
|
||
|
|
let mut root_key = [0u8; 32];
|
||
|
|
hk.expand(RATCHET_BOOTSTRAP_ROOT_INFO, &mut root_key)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let local = RatchetKeyPair::from_secret(ratchet_seed(&hk, &keys.identity_pk)?);
|
||
|
|
let remote = ratchet_seed(&hk, &peer_pk)?;
|
||
|
|
let remote_pub = X25519Public::from(&StaticSecret::from(remote)).to_bytes();
|
||
|
|
Ok(RatchetState::bootstrap(root_key, local, remote_pub))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `HKDF(info = "ratchet-key" || pubkey)` — the initial ratchet secret both
|
||
|
|
/// peers compute for the peer with that identity pubkey.
|
||
|
|
fn ratchet_seed(hk: &Hkdf<Sha256>, pubkey: &[u8; 32]) -> Result<[u8; 32], String> {
|
||
|
|
let mut info = Vec::with_capacity(RATCHET_BOOTSTRAP_KEY_INFO.len() + 32);
|
||
|
|
info.extend_from_slice(RATCHET_BOOTSTRAP_KEY_INFO);
|
||
|
|
info.extend_from_slice(pubkey);
|
||
|
|
let mut seed = Zeroizing::new([0u8; 32]);
|
||
|
|
hk.expand(&info, &mut seed[..]).map_err(|e| e.to_string())?;
|
||
|
|
Ok(*seed)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The peer's ratchet state: the persisted blob when there is one, a freshly
|
||
|
|
/// bootstrapped state otherwise.
|
||
|
|
///
|
||
|
|
/// The blob is opaque to the store; `RatchetState::to_bytes`/`from_bytes` own
|
||
|
|
/// the format. Nothing is written here — the caller persists once, after a
|
||
|
|
/// successful encrypt/decrypt, so a rejected frame cannot leave a half-created
|
||
|
|
/// session behind.
|
||
|
|
fn ratchet_for(store: &Store, keys: &Keys, friend_pk: &[u8]) -> Result<RatchetState, String> {
|
||
|
|
if let Some(blob) = store.load_ratchet(friend_pk).map_err(|e| e.to_string())? {
|
||
|
|
return RatchetState::from_bytes(&blob).map_err(|e| format!("ratchet state: {e}"));
|
||
|
|
}
|
||
|
|
let f = store
|
||
|
|
.get_friend(friend_pk)
|
||
|
|
.map_err(|e| e.to_string())?
|
||
|
|
.ok_or_else(|| "unknown friend".to_string())?;
|
||
|
|
if f.prekey.len() != 32 {
|
||
|
|
return Err("friend missing prekey".into());
|
||
|
|
}
|
||
|
|
bootstrap_ratchet(keys, friend_pk, &f.prekey)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Encode one chat send as a `rat ` frame, then persist the advanced state.
|
||
|
|
///
|
||
|
|
/// Exactly one frame per call, and the caller passes those bytes to
|
||
|
|
/// `Outbox::send_payload`, so a retry re-sends them verbatim instead of
|
||
|
|
/// advancing the sending chain a second time.
|
||
|
|
///
|
||
|
|
/// Public because it is the wire half of `Node::send`: `tests/ratchet_wire.rs`
|
||
|
|
/// drives the real path without Tor. Callers hold the store lock across
|
||
|
|
/// load → encrypt → save.
|
||
|
|
pub fn encode_chat_frame(
|
||
|
|
store: &Store,
|
||
|
|
keys: &Keys,
|
||
|
|
friend_pk: &[u8],
|
||
|
|
plaintext: &[u8],
|
||
|
|
) -> Result<Vec<u8>, String> {
|
||
|
|
let mut state = ratchet_for(store, keys, friend_pk)?;
|
||
|
|
let frame = state.encrypt(plaintext).map_err(|e| e.to_string())?;
|
||
|
|
let blob = Zeroizing::new(state.to_bytes());
|
||
|
|
store
|
||
|
|
.save_ratchet(friend_pk, &blob)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(frame)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Decrypt one inbound `rat ` frame and append it to the chat log as an
|
||
|
|
/// incoming line, then persist the advanced state.
|
||
|
|
///
|
||
|
|
/// Returns the logged plaintext, or `Err` for anything that did not
|
||
|
|
/// authenticate — a bad frame writes no chat row and leaves the stored state
|
||
|
|
/// untouched, because `RatchetState` validates fully before it mutates. The
|
||
|
|
/// ciphertext is never stored and there is no plaintext fallback.
|
||
|
|
///
|
||
|
|
/// Public for the same reason as [`encode_chat_frame`]. Callers hold the store
|
||
|
|
/// lock across load → decrypt → append → save, which is what makes the
|
||
|
|
/// read-modify-write atomic against a second inbound session on the same peer.
|
||
|
|
pub fn ingest_chat_frame(
|
||
|
|
store: &Store,
|
||
|
|
keys: &Keys,
|
||
|
|
peer_pk: &[u8],
|
||
|
|
frame: &[u8],
|
||
|
|
) -> Result<Vec<u8>, String> {
|
||
|
|
let mut state = ratchet_for(store, keys, peer_pk)?;
|
||
|
|
let plaintext = state.decrypt(frame).map_err(|e| e.to_string())?;
|
||
|
|
let line = Zeroizing::new(sanitize::display_text(&plaintext).as_bytes().to_vec());
|
||
|
|
store
|
||
|
|
.append_message(peer_pk, "in", &line[..])
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
let blob = Zeroizing::new(state.to_bytes());
|
||
|
|
store
|
||
|
|
.save_ratchet(peer_pk, &blob)
|
||
|
|
.map_err(|e| e.to_string())?;
|
||
|
|
Ok(line.to_vec())
|
||
|
|
}
|
||
|
|
|
||
|
|
fn spawn_rend(
|
||
|
|
node: Arc<Node>,
|
||
|
|
rend: impl futures::Stream<Item = tor_hsservice::RendRequest> + Send + 'static,
|
||
|
|
) -> tokio::task::JoinHandle<()> {
|
||
|
|
tokio::spawn(async move {
|
||
|
|
let mut requests = std::pin::pin!(handle_rend_requests(rend));
|
||
|
|
while let Some(req) = requests.next().await {
|
||
|
|
let allow = node
|
||
|
|
.incoming_limit
|
||
|
|
.lock()
|
||
|
|
.map(|mut b| b.try_acquire())
|
||
|
|
.unwrap_or(false);
|
||
|
|
if !allow {
|
||
|
|
eprintln!("rate-limit drop");
|
||
|
|
drop(req);
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
let serve = Arc::clone(&node);
|
||
|
|
tokio::spawn(async move {
|
||
|
|
let Ok(mut stream) = req.accept(Connected::new_empty()).await else {
|
||
|
|
return;
|
||
|
|
};
|
||
|
|
if let Err(e) = serve.handle_incoming(&mut stream).await {
|
||
|
|
eprintln!("incoming: {e}");
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Foreground/unlock flush: every outstanding queued send gets one attempt now.
|
||
|
|
fn spawn_flush_all(outbox: Arc<Outbox>) {
|
||
|
|
tokio::spawn(async move {
|
||
|
|
if let Err(e) = outbox.flush_all(unix_now()).await {
|
||
|
|
eprintln!("outbox: {e}");
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
/// We just saw this peer (handshake or successful dial): try their queue now.
|
||
|
|
fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
|
||
|
|
tokio::spawn(async move {
|
||
|
|
if let Err(e) = outbox.flush_friend(&friend_pk, unix_now()).await {
|
||
|
|
eprintln!("outbox: {e}");
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
fn next_hs_nickname(cur: &str) -> String {
|
||
|
|
let n = cur
|
||
|
|
.strip_prefix("ow")
|
||
|
|
.and_then(|s| s.parse::<u32>().ok())
|
||
|
|
.unwrap_or(0);
|
||
|
|
format!("ow{}", n.saturating_add(1))
|
||
|
|
}
|
||
|
|
|
||
|
|
fn unix_now() -> i64 {
|
||
|
|
SystemTime::now()
|
||
|
|
.duration_since(UNIX_EPOCH)
|
||
|
|
.map(|d| d.as_secs() as i64)
|
||
|
|
.unwrap_or(0)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn session_err(e: session::Error) -> String {
|
||
|
|
if e.is_fingerprint_mismatch() {
|
||
|
|
crate::tui::fingerprint_mismatch_banner().to_string()
|
||
|
|
} else {
|
||
|
|
e.to_string()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
|
||
|
|
let mut stack = vec![dir.to_path_buf()];
|
||
|
|
while let Some(p) = stack.pop() {
|
||
|
|
let Ok(rd) = std::fs::read_dir(&p) else {
|
||
|
|
continue;
|
||
|
|
};
|
||
|
|
for ent in rd.flatten() {
|
||
|
|
let path = ent.path();
|
||
|
|
if path.is_dir() {
|
||
|
|
stack.push(path);
|
||
|
|
} else if let Ok(bytes) = std::fs::read(&path)
|
||
|
|
&& bytes.windows(needle.len()).any(|w| w == needle)
|
||
|
|
{
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
false
|
||
|
|
}
|
||
|
|
|
||
|
|
#[cfg(test)]
|
||
|
|
mod tests {
|
||
|
|
use super::*;
|
||
|
|
use std::pin::Pin;
|
||
|
|
use std::task::{Context, Poll};
|
||
|
|
|
||
|
|
use futures::io::{AsyncRead, AsyncWrite};
|
||
|
|
use tokio::io::AsyncRead as TokioRead;
|
||
|
|
use tokio::io::AsyncWrite as TokioWrite;
|
||
|
|
|
||
|
|
const PASS: &str = "node-ratchet-test-pass";
|
||
|
|
|
||
|
|
/// Never dials: every send queues, which is what leaves the encoded frame
|
||
|
|
/// visible on the outbox row.
|
||
|
|
struct NoDial;
|
||
|
|
|
||
|
|
impl crate::outbox::Deliverer for NoDial {
|
||
|
|
fn deliver<'a>(
|
||
|
|
&'a self,
|
||
|
|
_onion: &'a str,
|
||
|
|
_pinned_id: &'a [u8],
|
||
|
|
_prekey: &'a [u8],
|
||
|
|
_payload: &'a [u8],
|
||
|
|
) -> crate::outbox::BoxFut<'a, Result<(), String>> {
|
||
|
|
Box::pin(async { Err("connect peer.onion:80: timed out".to_string()) })
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `handle_incoming` is generic over `futures::io` streams while
|
||
|
|
/// `tokio::io::duplex` hands out `tokio::io` ones; one line per method
|
||
|
|
/// beats a new dev-dependency.
|
||
|
|
struct Duplex(tokio::io::DuplexStream);
|
||
|
|
|
||
|
|
impl AsyncRead for Duplex {
|
||
|
|
fn poll_read(
|
||
|
|
self: Pin<&mut Self>,
|
||
|
|
cx: &mut Context<'_>,
|
||
|
|
buf: &mut [u8],
|
||
|
|
) -> Poll<std::io::Result<usize>> {
|
||
|
|
let mut read_buf = tokio::io::ReadBuf::new(buf);
|
||
|
|
match Pin::new(&mut self.get_mut().0).poll_read(cx, &mut read_buf) {
|
||
|
|
Poll::Ready(Ok(())) => Poll::Ready(Ok(read_buf.filled().len())),
|
||
|
|
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
|
||
|
|
Poll::Pending => Poll::Pending,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
impl AsyncWrite for Duplex {
|
||
|
|
fn poll_write(
|
||
|
|
self: Pin<&mut Self>,
|
||
|
|
cx: &mut Context<'_>,
|
||
|
|
buf: &[u8],
|
||
|
|
) -> Poll<std::io::Result<usize>> {
|
||
|
|
Pin::new(&mut self.get_mut().0).poll_write(cx, buf)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||
|
|
Pin::new(&mut self.get_mut().0).poll_flush(cx)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||
|
|
Pin::new(&mut self.get_mut().0).poll_shutdown(cx)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A real `Node` with no Tor: an unbootstrapped client, no onion service,
|
||
|
|
/// and a deliverer that never dials. `Node::start` / `start_with_passphrase`
|
||
|
|
/// are the only public constructors and both bootstrap Tor and publish an
|
||
|
|
/// onion service, so this is the only way to drive the shipped send and
|
||
|
|
/// receive path offline.
|
||
|
|
fn offline_node(home: &Path, deliverer: Arc<dyn crate::outbox::Deliverer>) -> Node {
|
||
|
|
offline_node_with_wallet(home, deliverer, Wallet::disabled())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// [`offline_node`] with a wallet child attached: the outbound tip path
|
||
|
|
/// cannot get past `Wallet::configured()` without one.
|
||
|
|
fn offline_node_with_wallet(
|
||
|
|
home: &Path,
|
||
|
|
deliverer: Arc<dyn crate::outbox::Deliverer>,
|
||
|
|
wallet: Wallet,
|
||
|
|
) -> Node {
|
||
|
|
std::fs::create_dir_all(home).expect("create home");
|
||
|
|
let store = Store::open_at_with_passphrase(home, PASS).expect("open store");
|
||
|
|
let keys = Keys::from_self(&store.self_identity().expect("self identity")).expect("keys");
|
||
|
|
let client = arti_client::TorClient::builder()
|
||
|
|
.config(hs::client_config(&home.join("arti"), &home.join("cache")))
|
||
|
|
.create_unbootstrapped()
|
||
|
|
.expect("unbootstrapped Tor client");
|
||
|
|
let store = Arc::new(Mutex::new(store));
|
||
|
|
let outbox = Arc::new(Outbox::new(Arc::clone(&store), deliverer));
|
||
|
|
Node {
|
||
|
|
home: home.to_path_buf(),
|
||
|
|
store,
|
||
|
|
client,
|
||
|
|
hs: Mutex::new(None),
|
||
|
|
onion: Mutex::new("test.onion".to_string()),
|
||
|
|
keys: Mutex::new(keys),
|
||
|
|
wallet,
|
||
|
|
incoming_limit: Mutex::new(TokenBucket::default()),
|
||
|
|
inbox: Mutex::new(file::Inbox::new(home.join("inbox"))),
|
||
|
|
outbox,
|
||
|
|
worker: Mutex::new(None),
|
||
|
|
stopped: AtomicBool::new(false),
|
||
|
|
onion_reachable: AtomicBool::new(false),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The friend row a scanned invite leaves behind.
|
||
|
|
fn befriend(store: &Store, other_pk: &[u8], other_prekey: &[u8], onion: &str) {
|
||
|
|
store
|
||
|
|
.upsert_friend(other_pk, onion, None)
|
||
|
|
.expect("upsert friend");
|
||
|
|
store
|
||
|
|
.set_friend_prekey(other_pk, other_prekey)
|
||
|
|
.expect("set friend prekey");
|
||
|
|
}
|
||
|
|
|
||
|
|
fn node_prekey(node: &Node) -> [u8; 32] {
|
||
|
|
node.keys.lock().unwrap().prekey_pk
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One peer→node dial, end to end: a real Noise IK handshake and one
|
||
|
|
/// already-encoded frame over an in-memory stream, into `handle_incoming`.
|
||
|
|
async fn deliver_frame(node: &Node, peer: &Keys, frame: &[u8]) -> Result<(), String> {
|
||
|
|
let node_pk = node.identity_pk();
|
||
|
|
let node_prekey = node_prekey(node);
|
||
|
|
let (client_side, server_side) = tokio::io::duplex(64 * 1024);
|
||
|
|
|
||
|
|
let send = async {
|
||
|
|
let mut stream = Duplex(client_side);
|
||
|
|
let mut sess = session::handshake_initiator(&mut stream, peer, &node_pk, &node_prekey)
|
||
|
|
.await
|
||
|
|
.map_err(|e| e.into_message())?;
|
||
|
|
let ct = sess.encrypt(frame).map_err(|e| e.into_message())?;
|
||
|
|
frame::write_frame(&mut stream, &ct)
|
||
|
|
.await
|
||
|
|
.map_err(|e| e.to_string())
|
||
|
|
};
|
||
|
|
let receive = async {
|
||
|
|
let mut stream = Duplex(server_side);
|
||
|
|
node.handle_incoming(&mut stream).await
|
||
|
|
};
|
||
|
|
let (sent, received) = futures::join!(send, receive);
|
||
|
|
sent?;
|
||
|
|
received
|
||
|
|
}
|
||
|
|
|
||
|
|
fn chat_lines(node: &Node, peer: &Keys) -> Vec<(String, String)> {
|
||
|
|
node.list_messages(&peer.identity_pk)
|
||
|
|
.expect("list messages")
|
||
|
|
.into_iter()
|
||
|
|
.map(|m| {
|
||
|
|
(
|
||
|
|
m.dir,
|
||
|
|
String::from_utf8(m.plaintext).expect("utf8 chat line"),
|
||
|
|
)
|
||
|
|
})
|
||
|
|
.collect()
|
||
|
|
}
|
||
|
|
|
||
|
|
#[tokio::test]
|
||
|
|
async fn send_queues_one_ratchet_frame_and_keeps_the_plaintext_local() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
let peer = Keys::generate();
|
||
|
|
befriend(
|
||
|
|
&node.store.lock().unwrap(),
|
||
|
|
&peer.identity_pk,
|
||
|
|
&peer.prekey_pk,
|
||
|
|
"peer.onion",
|
||
|
|
);
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
node.send(&peer.identity_pk, b"hello bob").await.unwrap(),
|
||
|
|
OutboxStatus::Queued,
|
||
|
|
"with nothing to dial, the send queues for the retry worker"
|
||
|
|
);
|
||
|
|
|
||
|
|
let rows = node.outbox_pending(&peer.identity_pk).unwrap();
|
||
|
|
assert_eq!(rows.len(), 1);
|
||
|
|
let payload = rows[0]
|
||
|
|
.payload
|
||
|
|
.clone()
|
||
|
|
.expect("the encoded frame rides on the outbox row");
|
||
|
|
assert!(
|
||
|
|
payload.starts_with(b"rat "),
|
||
|
|
"chat goes out as a ratchet frame"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!payload.windows(9).any(|w| w == b"hello bob"),
|
||
|
|
"the plaintext is not on the wire"
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
rows[0].body, b"hello bob",
|
||
|
|
"local history keeps the plaintext"
|
||
|
|
);
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
chat_lines(&node, &peer),
|
||
|
|
vec![("out".to_string(), "hello bob".to_string())]
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[tokio::test]
|
||
|
|
async fn an_inbound_frame_is_dispatched_to_the_ratchet_and_logged() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
let peer = Keys::generate();
|
||
|
|
befriend(
|
||
|
|
&node.store.lock().unwrap(),
|
||
|
|
&peer.identity_pk,
|
||
|
|
&peer.prekey_pk,
|
||
|
|
"peer.onion",
|
||
|
|
);
|
||
|
|
// The peer's own store holds its ratchet state, as a second Node does.
|
||
|
|
let peer_store =
|
||
|
|
Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store");
|
||
|
|
befriend(
|
||
|
|
&peer_store,
|
||
|
|
&node.identity_pk(),
|
||
|
|
&node_prekey(&node),
|
||
|
|
"node.onion",
|
||
|
|
);
|
||
|
|
|
||
|
|
let frame =
|
||
|
|
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"hi bob").expect("encode");
|
||
|
|
deliver_frame(&node, &peer, &frame).await.expect("receive");
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
chat_lines(&node, &peer),
|
||
|
|
vec![("in".to_string(), "hi bob".to_string())],
|
||
|
|
"`rat ` is dispatched to the ratchet, not logged as ciphertext chat"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[tokio::test]
|
||
|
|
async fn the_receive_path_keeps_arrival_order_and_drops_replays_and_garbage() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||
|
|
let peer = Keys::generate();
|
||
|
|
befriend(
|
||
|
|
&node.store.lock().unwrap(),
|
||
|
|
&peer.identity_pk,
|
||
|
|
&peer.prekey_pk,
|
||
|
|
"peer.onion",
|
||
|
|
);
|
||
|
|
let peer_store =
|
||
|
|
Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store");
|
||
|
|
befriend(
|
||
|
|
&peer_store,
|
||
|
|
&node.identity_pk(),
|
||
|
|
&node_prekey(&node),
|
||
|
|
"node.onion",
|
||
|
|
);
|
||
|
|
|
||
|
|
let frames: Vec<Vec<u8>> = ["m0", "m1", "m2"]
|
||
|
|
.iter()
|
||
|
|
.map(|t| {
|
||
|
|
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), t.as_bytes())
|
||
|
|
.expect("encode")
|
||
|
|
})
|
||
|
|
.collect();
|
||
|
|
|
||
|
|
// Arrival order 2, 0, 1 — the ratchet holds the two it has not seen.
|
||
|
|
deliver_frame(&node, &peer, &frames[2]).await.unwrap();
|
||
|
|
deliver_frame(&node, &peer, &frames[0]).await.unwrap();
|
||
|
|
deliver_frame(&node, &peer, &frames[1]).await.unwrap();
|
||
|
|
// A replay of an already-consumed frame, and a corrupted one: both are
|
||
|
|
// dropped inside `handle_incoming` without a chat row and without
|
||
|
|
// wedging the session.
|
||
|
|
deliver_frame(&node, &peer, &frames[0]).await.unwrap();
|
||
|
|
let mut corrupt = frames[1].clone();
|
||
|
|
let last = corrupt.len() - 1;
|
||
|
|
corrupt[last] ^= 0x01;
|
||
|
|
deliver_frame(&node, &peer, &corrupt).await.unwrap();
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
chat_lines(&node, &peer),
|
||
|
|
vec![
|
||
|
|
("in".to_string(), "m2".to_string()),
|
||
|
|
("in".to_string(), "m0".to_string()),
|
||
|
|
("in".to_string(), "m1".to_string())
|
||
|
|
],
|
||
|
|
"three lines, arrival order, no duplicates"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The peer takes the frame: one-shot payment sends are fail-closed, so the
|
||
|
|
/// tip path only reaches its chat rows when the deliverer answers `Ok`.
|
||
|
|
struct DialOk;
|
||
|
|
|
||
|
|
impl crate::outbox::Deliverer for DialOk {
|
||
|
|
fn deliver<'a>(
|
||
|
|
&'a self,
|
||
|
|
_onion: &'a str,
|
||
|
|
_pinned_id: &'a [u8],
|
||
|
|
_prekey: &'a [u8],
|
||
|
|
_payload: &'a [u8],
|
||
|
|
) -> crate::outbox::BoxFut<'a, Result<(), String>> {
|
||
|
|
Box::pin(async { Ok(()) })
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Same documented mainnet standard as `tests/wallet.rs`.
|
||
|
|
fn xmr_addr() -> String {
|
||
|
|
"4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge"
|
||
|
|
.to_string()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A wallet child that clears the Digest challenge and answers one
|
||
|
|
/// `transfer` — the two-connection dance `tests/wallet.rs` mocks.
|
||
|
|
async fn mock_wallet() -> Wallet {
|
||
|
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||
|
|
|
||
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||
|
|
.await
|
||
|
|
.expect("bind mock wallet");
|
||
|
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||
|
|
tokio::spawn(async move {
|
||
|
|
for attempt in 0..2 {
|
||
|
|
let Ok((mut sock, _)) = listener.accept().await else {
|
||
|
|
return;
|
||
|
|
};
|
||
|
|
let mut buf = vec![0u8; 8192];
|
||
|
|
let _ = sock.read(&mut buf).await;
|
||
|
|
if attempt == 0 {
|
||
|
|
let _ = sock
|
||
|
|
.write_all(
|
||
|
|
b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
|
||
|
|
)
|
||
|
|
.await;
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
let body = r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#;
|
||
|
|
let _ = sock
|
||
|
|
.write_all(
|
||
|
|
format!(
|
||
|
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||
|
|
body.len()
|
||
|
|
)
|
||
|
|
.as_bytes(),
|
||
|
|
)
|
||
|
|
.await;
|
||
|
|
}
|
||
|
|
});
|
||
|
|
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The payer of a tip must see it in their own chat: `receipt_chat_line` is
|
||
|
|
/// the recipient's view of the frame that arrived, `tip_chat_line` is what
|
||
|
|
/// the sender just spent.
|
||
|
|
#[tokio::test]
|
||
|
|
async fn outbound_tip_appends_the_senders_own_tip_chat_line() {
|
||
|
|
let dir = tempfile::tempdir().unwrap();
|
||
|
|
let node = offline_node_with_wallet(
|
||
|
|
&dir.path().join("bob"),
|
||
|
|
Arc::new(DialOk),
|
||
|
|
mock_wallet().await,
|
||
|
|
);
|
||
|
|
let peer = Keys::generate();
|
||
|
|
let addr = xmr_addr();
|
||
|
|
{
|
||
|
|
let store = node.store.lock().unwrap();
|
||
|
|
befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion");
|
||
|
|
let prf = crate::profile::sign(&peer.identity_sk, "peer", "", &addr, 1)
|
||
|
|
.expect("sign peer profile");
|
||
|
|
assert!(store.apply_profile(&peer.identity_pk, &prf).unwrap());
|
||
|
|
}
|
||
|
|
|
||
|
|
node.tip(&peer.identity_pk, "500000000000", "lunch")
|
||
|
|
.await
|
||
|
|
.expect("tip");
|
||
|
|
|
||
|
|
assert_eq!(
|
||
|
|
chat_lines(&node, &peer),
|
||
|
|
vec![
|
||
|
|
("out".to_string(), "[receipt] 0.5 XMR".to_string()),
|
||
|
|
(
|
||
|
|
"out".to_string(),
|
||
|
|
"[tip] 0.5 XMR — lunch (pending)".to_string()
|
||
|
|
),
|
||
|
|
],
|
||
|
|
"the sender's chat must show the tip they just paid"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|