Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c969e60185 |
||
|
|
cce0721ba9 |
||
|
|
381f424733 |
5 changed files with 429 additions and 28 deletions
|
|
@ -39,6 +39,11 @@ env:
|
||||||
CARGO_REGISTRY_VOLUME: onionwire-cargo-registry
|
CARGO_REGISTRY_VOLUME: onionwire-cargo-registry
|
||||||
CARGO_TARGET_VOLUME: onionwire-target-ci
|
CARGO_TARGET_VOLUME: onionwire-target-ci
|
||||||
BUILD_CONTAINER: onionwire-ci-${{ github.run_id }}
|
BUILD_CONTAINER: onionwire-ci-${{ github.run_id }}
|
||||||
|
# The SDK job gets its own target volume: it resolves the root crate with
|
||||||
|
# `rustls` instead of `native-tls`, so sharing a target dir would thrash both
|
||||||
|
# jobs' feature-unified artifacts.
|
||||||
|
SDK_CARGO_TARGET_VOLUME: onionwire-target-ci-sdk
|
||||||
|
SDK_BUILD_CONTAINER: onionwire-ci-sdk-${{ github.run_id }}
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
|
|
@ -73,3 +78,44 @@ jobs:
|
||||||
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \
|
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \
|
||||||
| docker start -a -i "$BUILD_CONTAINER"
|
| docker start -a -i "$BUILD_CONTAINER"
|
||||||
docker rm -f "$BUILD_CONTAINER" > /dev/null
|
docker rm -f "$BUILD_CONTAINER" > /dev/null
|
||||||
|
|
||||||
|
# `crates/onionwire-sdk` is a SEPARATE cargo workspace: its own Cargo.lock and
|
||||||
|
# a path dependency on the root crate, resolved with `rustls` instead of
|
||||||
|
# `native-tls`. The `test` job above therefore never compiles it, so a
|
||||||
|
# root-crate signature change (`Node::send` gaining the outbox result, the
|
||||||
|
# SQLCipher passphrase entry points) breaks the Android SDK — and the tagged
|
||||||
|
# release AAR, since android-release.yml only builds on `v*.*.*` — while both
|
||||||
|
# the root suites and local `cargo test` stay green. Build it here.
|
||||||
|
sdk:
|
||||||
|
runs-on: docker
|
||||||
|
timeout-minutes: 120
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: https://code.forgejo.org/actions/checkout@v4
|
||||||
|
|
||||||
|
- name: cargo test + clippy for crates/onionwire-sdk on aarch64
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
cd "${GITHUB_WORKSPACE}"
|
||||||
|
echo "workspace: $GITHUB_WORKSPACE"
|
||||||
|
docker volume create "$CARGO_REGISTRY_VOLUME" > /dev/null
|
||||||
|
docker volume create "$SDK_CARGO_TARGET_VOLUME" > /dev/null
|
||||||
|
docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null 2>&1 || true
|
||||||
|
docker create --name "$SDK_BUILD_CONTAINER" -i \
|
||||||
|
-e CARGO_TARGET_DIR=/target \
|
||||||
|
-e CARGO_BUILD_JOBS=2 \
|
||||||
|
-e CARGO_TERM_COLOR=never \
|
||||||
|
-v "$CARGO_REGISTRY_VOLUME":/usr/local/cargo/registry \
|
||||||
|
-v "$SDK_CARGO_TARGET_VOLUME":/target \
|
||||||
|
-w /src \
|
||||||
|
"$RUST_IMAGE" \
|
||||||
|
sh -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src/crates/onionwire-sdk \
|
||||||
|
&& apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends pkg-config libssl-dev \
|
||||||
|
&& rustup component add clippy \
|
||||||
|
&& cargo test --locked \
|
||||||
|
&& cargo clippy --locked --all-targets -- -D warnings'
|
||||||
|
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees \
|
||||||
|
--exclude=./crates/onionwire-sdk/target . \
|
||||||
|
| docker start -a -i "$SDK_BUILD_CONTAINER"
|
||||||
|
docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null
|
||||||
|
|
|
||||||
|
|
@ -286,7 +286,7 @@ FORGEJO_TOKEN=<pat> scripts/build-release-local.sh vX.Y.Z
|
||||||
|
|
||||||
Workflows (Forgejo Actions, `.forgejo/workflows/`):
|
Workflows (Forgejo Actions, `.forgejo/workflows/`):
|
||||||
|
|
||||||
- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. Pi runner, `docker` label.
|
- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — two jobs on the Pi runner (`docker` label), serialized by `onionwire-ci-pi`. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk` (separate cargo workspace — own `Cargo.lock`, root crate by path, `rustls` instead of `native-tls` — so a root signature change cannot silently break the Android SDK). Both run on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite.
|
||||||
- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — on core paths to `main` (`src/`, `crates/`, `Cargo.toml`, `Cargo.lock`, `scripts/release-body.md`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release. `workflow_dispatch` rebuilds a tag or `dry_run`s. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`.
|
- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — on core paths to `main` (`src/`, `crates/`, `Cargo.toml`, `Cargo.lock`, `scripts/release-body.md`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release. `workflow_dispatch` rebuilds a tag or `dry_run`s. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`.
|
||||||
|
|
||||||
Scripts:
|
Scripts:
|
||||||
|
|
|
||||||
25
crates/onionwire-sdk/Cargo.lock
generated
25
crates/onionwire-sdk/Cargo.lock
generated
|
|
@ -2443,6 +2443,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15"
|
checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cc",
|
"cc",
|
||||||
|
"openssl-sys",
|
||||||
"pkg-config",
|
"pkg-config",
|
||||||
"vcpkg",
|
"vcpkg",
|
||||||
]
|
]
|
||||||
|
|
@ -2774,6 +2775,7 @@ dependencies = [
|
||||||
"rusqlite",
|
"rusqlite",
|
||||||
"safelog",
|
"safelog",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
"sha3 0.10.9",
|
"sha3 0.10.9",
|
||||||
"snow",
|
"snow",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
|
@ -2781,6 +2783,7 @@ dependencies = [
|
||||||
"tor-hsservice",
|
"tor-hsservice",
|
||||||
"tor-rtcompat",
|
"tor-rtcompat",
|
||||||
"x25519-dalek",
|
"x25519-dalek",
|
||||||
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2801,6 +2804,28 @@ version = "0.3.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
|
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "openssl-src"
|
||||||
|
version = "300.6.1+3.6.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "openssl-sys"
|
||||||
|
version = "0.9.117"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"libc",
|
||||||
|
"openssl-src",
|
||||||
|
"pkg-config",
|
||||||
|
"vcpkg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "option-ext"
|
name = "option-ext"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
|
|
|
||||||
|
|
@ -18,8 +18,8 @@ onions directly. There is no `tor` binary, no torrc, no Orbot as the pipe.
|
||||||
| Onion | A **locator**, not an identity. It rotates. |
|
| Onion | A **locator**, not an identity. It rotates. |
|
||||||
| Invite | `onionwire:v1:k=…:o=…:spk=…:sig=…` |
|
| Invite | `onionwire:v1:k=…:o=…:spk=…:sig=…` |
|
||||||
| Crypto | Noise IK (`Noise_IK_25519_ChaChaPoly_BLAKE2s`). `spk` is x25519. |
|
| Crypto | Noise IK (`Noise_IK_25519_ChaChaPoly_BLAKE2s`). `spk` is x25519. |
|
||||||
| Fail closed | Peer onion down → the send fails. No outbox, no spool in v1. |
|
| Chat send | Unreachable peer onion → the message goes to the **local outbox** and is retried with backoff. `send()` returns `SendState.Sent` or `SendState.Queued`. File transfer and payments stay fail-closed. |
|
||||||
| At rest | Chat bodies encrypted (Argon2id wrap + ChaCha20-Poly1305). Identity keys in sqlite are plaintext — that is honest, not an oversight. |
|
| At rest | The whole sqlite file is SQLCipher (key = Argon2id of the store passphrase), and chat bodies carry a second per-row ChaCha20-Poly1305 layer with row-bound AAD. Identity keys live in that same encrypted file. |
|
||||||
|
|
||||||
### Invite string
|
### Invite string
|
||||||
|
|
||||||
|
|
@ -66,8 +66,10 @@ Requirements:
|
||||||
|
|
||||||
## Kotlin surface
|
## Kotlin surface
|
||||||
|
|
||||||
Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes,
|
Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes.
|
||||||
and a send retries the peer for up to 3 minutes before failing.
|
A send that cannot reach the peer comes back immediately as `QUEUED` (it is not
|
||||||
|
a long retry inside the call): the message is stored locally and a background
|
||||||
|
worker in the core keeps retrying it.
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
import uniffi.onionwire_sdk.*
|
import uniffi.onionwire_sdk.*
|
||||||
|
|
@ -88,8 +90,16 @@ val friend: FriendInfo = wire.addFriend(pasted)
|
||||||
// 4. Roster and chat.
|
// 4. Roster and chat.
|
||||||
val roster: List<FriendInfo> = wire.friends()
|
val roster: List<FriendInfo> = wire.friends()
|
||||||
wire.setPetname(friend.pubkeyHex, "ada")
|
wire.setPetname(friend.pubkeyHex, "ada")
|
||||||
wire.send(friend.pubkeyHex, "hello wire")
|
when (wire.send(friend.pubkeyHex, "hello wire")) {
|
||||||
|
SendState.SENT -> { /* the peer's onion took the frame */ }
|
||||||
|
SendState.QUEUED -> { /* unreachable: stored in the local outbox and
|
||||||
|
retried in the background. Show it as pending —
|
||||||
|
it is local-only until a circuit takes it. */ }
|
||||||
|
}
|
||||||
val msgs: List<ChatMessage> = wire.messages(friend.pubkeyHex)
|
val msgs: List<ChatMessage> = wire.messages(friend.pubkeyHex)
|
||||||
|
// msgs[i].direction == "out" -> msgs[i].delivery is "sent" | "queued" |
|
||||||
|
// "sending" | "failed: <reason>"; null for incoming messages. Render the
|
||||||
|
// queued and failed states distinctly from sent.
|
||||||
|
|
||||||
// 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds
|
// 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds
|
||||||
// the SDK owns the typed confirmation.
|
// the SDK owns the typed confirmation.
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,10 @@
|
||||||
//! the friend.
|
//! the friend.
|
||||||
//! * Transport is in-process Arti. There is no `tor` binary, no torrc, no
|
//! * Transport is in-process Arti. There is no `tor` binary, no torrc, no
|
||||||
//! Orbot pipe. If the onion service cannot publish, this fails closed.
|
//! Orbot pipe. If the onion service cannot publish, this fails closed.
|
||||||
//! * Chat bodies are encrypted at rest. Identity keys in sqlite are not.
|
//! * Chat bodies are encrypted at rest, and the whole sqlite file is
|
||||||
|
//! SQLCipher on top of that (see the root crate).
|
||||||
|
//! * A chat send that cannot reach the peer's onion is queued in a local
|
||||||
|
//! outbox and retried — see [`SendState`]. Nothing leaves the device.
|
||||||
//!
|
//!
|
||||||
//! Lifecycle: a node is started by [`open_wire`] and stopped by
|
//! Lifecycle: a node is started by [`open_wire`] and stopped by
|
||||||
//! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable
|
//! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable
|
||||||
|
|
@ -25,8 +28,10 @@
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::{Arc, Mutex, OnceLock};
|
use std::sync::{Arc, Mutex, OnceLock};
|
||||||
|
|
||||||
|
use onionwire::Message;
|
||||||
use onionwire::hs::TorState as CoreTorState;
|
use onionwire::hs::TorState as CoreTorState;
|
||||||
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
|
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
|
||||||
|
use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus};
|
||||||
use onionwire::qr;
|
use onionwire::qr;
|
||||||
|
|
||||||
uniffi::setup_scaffolding!();
|
uniffi::setup_scaffolding!();
|
||||||
|
|
@ -98,11 +103,79 @@ pub struct FriendInfo {
|
||||||
pub last_connect_ok: bool,
|
pub last_connect_ok: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What `send()` did with the message.
|
||||||
|
///
|
||||||
|
/// The core has a local outbox: when a friend's onion is unreachable the
|
||||||
|
/// message is written to the local sqlite store and a background worker
|
||||||
|
/// retries it with backoff. Nothing is handed to a third party — every attempt
|
||||||
|
/// is a fresh handshake straight to that friend's onion — but until a circuit
|
||||||
|
/// takes it the message exists only on this device. A consumer must not render
|
||||||
|
/// `Queued` as delivered.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
|
||||||
|
pub enum SendState {
|
||||||
|
/// The frame reached the peer's onion service during this call.
|
||||||
|
Sent,
|
||||||
|
/// The peer's onion was unreachable: the message is in the local outbox,
|
||||||
|
/// local-only until the retry worker delivers it (or it ends `Failed`).
|
||||||
|
Queued,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, uniffi::Record)]
|
#[derive(Debug, Clone, uniffi::Record)]
|
||||||
pub struct ChatMessage {
|
pub struct ChatMessage {
|
||||||
|
/// `messages.id` of the stored row. This is the join key an
|
||||||
|
/// [`OutboxRow::message_id`] refers to, so a client matches an outbox row to
|
||||||
|
/// this message by id instead of matching bodies or counting rows. Stable
|
||||||
|
/// for the life of the row; never `0`.
|
||||||
|
pub id: i64,
|
||||||
/// "in" or "out".
|
/// "in" or "out".
|
||||||
pub direction: String,
|
pub direction: String,
|
||||||
pub body: String,
|
pub body: String,
|
||||||
|
/// Outgoing messages only: `"sent"`, `"queued"`, `"sending"` or
|
||||||
|
/// `"failed: <reason>"`. `None` for incoming messages. An outgoing row with
|
||||||
|
/// no outbox row is one the peer accepted on the first attempt, so it reads
|
||||||
|
/// `"sent"` — never treat a missing value as "delivered" on the app side,
|
||||||
|
/// read this field.
|
||||||
|
pub delivery: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One row of the local outbox for a friend: a chat send the core has not
|
||||||
|
/// finished delivering.
|
||||||
|
///
|
||||||
|
/// The join key is `message_id` — the `messages.id` a [`ChatMessage`] belongs
|
||||||
|
/// to — so a client matches these against its own list instead of matching
|
||||||
|
/// bodies. Delivered rows are deleted, which is why a message with no row here
|
||||||
|
/// was accepted by the peer and never needed a retry.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
|
||||||
|
pub struct OutboxRow {
|
||||||
|
/// `messages.id` of the chat row this outbox row belongs to.
|
||||||
|
pub message_id: i64,
|
||||||
|
/// `"queued"`, `"sending"` or `"failed"` — the store's own encoding of
|
||||||
|
/// `OutboxStatus`, the same string [`ChatMessage::delivery`] uses.
|
||||||
|
/// `"sent"` does not occur: a delivered row is deleted before this is read.
|
||||||
|
pub status: String,
|
||||||
|
/// Attempts already spent on this row. Compare against
|
||||||
|
/// [`outbox_max_attempts`] to render `try n/8`.
|
||||||
|
pub attempts: u32,
|
||||||
|
/// Absolute unix seconds of the next attempt, so the client renders its own
|
||||||
|
/// countdown from `now` instead of a stale number baked into a record.
|
||||||
|
/// Only meaningful while `status == "queued"`: a `"failed"` row is terminal
|
||||||
|
/// and keeps the last time it was scheduled for, which must not be shown as
|
||||||
|
/// a countdown.
|
||||||
|
pub next_attempt_at: i64,
|
||||||
|
/// Why the last attempt failed, as the core reported it. `None` until the
|
||||||
|
/// row has been attempted once.
|
||||||
|
pub last_error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retry budget after which a queued message turns terminally `"failed"` — the
|
||||||
|
/// denominator in `try n/8`.
|
||||||
|
///
|
||||||
|
/// A constant of the core's outbox, not per-node state, so it is a free
|
||||||
|
/// function: fetch it once and render `attempts` against it. It is exposed at
|
||||||
|
/// all because the client cannot read the Rust constant.
|
||||||
|
#[uniffi::export]
|
||||||
|
pub fn outbox_max_attempts() -> u32 {
|
||||||
|
DEFAULT_MAX_ATTEMPTS
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, uniffi::Record)]
|
#[derive(Debug, Clone, uniffi::Record)]
|
||||||
|
|
@ -179,7 +252,10 @@ impl Wire {
|
||||||
let guard = self.node.lock().map_err(|_| WireError::Stopped {
|
let guard = self.node.lock().map_err(|_| WireError::Stopped {
|
||||||
message: "node handle lock poisoned by a panic; reopen the identity".to_string(),
|
message: "node handle lock poisoned by a panic; reopen the identity".to_string(),
|
||||||
})?;
|
})?;
|
||||||
guard.as_ref().cloned().ok_or_else(|| WireError::stopped("this call"))
|
guard
|
||||||
|
.as_ref()
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| WireError::stopped("this call"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -332,34 +408,57 @@ impl Wire {
|
||||||
.map_err(WireError::new)
|
.map_err(WireError::new)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send one message. Returns once the outcome is known: delivered now, or
|
/// Send one chat message.
|
||||||
/// queued for retry because the peer's onion is unreachable. A protocol
|
///
|
||||||
/// error (bad signature, bad frame) still fails immediately and is never
|
/// Returns [`SendState::Sent`] when the frame reached the peer's onion
|
||||||
/// queued. Use [`flush`](Self::flush) to retry the queue on demand.
|
/// service during this call, and [`SendState::Queued`] when it did not: the
|
||||||
pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> {
|
/// message is then in the local outbox and a background worker retries it
|
||||||
|
/// with exponential backoff (30s doubling, capped at 30 min, 8 attempts)
|
||||||
|
/// until it lands or ends terminally failed. A queued send is local-only —
|
||||||
|
/// show it as pending, not delivered.
|
||||||
|
///
|
||||||
|
/// A protocol error (signature mismatch, malformed or oversize frame) is
|
||||||
|
/// not retryable and still fails here; nothing is queued in that case.
|
||||||
|
pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<SendState> {
|
||||||
let pk = unhex(&pubkey_hex)?;
|
let pk = unhex(&pubkey_hex)?;
|
||||||
self.node()?
|
let status = self
|
||||||
|
.node()?
|
||||||
.send(&pk, body.as_bytes())
|
.send(&pk, body.as_bytes())
|
||||||
.await
|
.await
|
||||||
.map_err(WireError::new)?;
|
.map_err(WireError::new)?;
|
||||||
Ok(())
|
Ok(send_state(status))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Chat history for a friend, oldest first. Bodies are decrypted here;
|
/// Chat history for a friend, oldest first. Bodies are decrypted here;
|
||||||
/// they are stored encrypted at rest.
|
/// they are stored encrypted at rest. Outgoing rows carry their delivery
|
||||||
|
/// state in [`ChatMessage::delivery`].
|
||||||
pub async fn messages(&self, pubkey_hex: String) -> WResult<Vec<ChatMessage>> {
|
pub async fn messages(&self, pubkey_hex: String) -> WResult<Vec<ChatMessage>> {
|
||||||
let pk = unhex(&pubkey_hex)?;
|
let pk = unhex(&pubkey_hex)?;
|
||||||
let rows = self
|
let rows = self.node()?.list_messages(&pk).map_err(WireError::new)?;
|
||||||
|
let mut out = Vec::with_capacity(rows.len());
|
||||||
|
for m in rows {
|
||||||
|
let status = self
|
||||||
.node()?
|
.node()?
|
||||||
.list_messages(&pk)
|
.outbox_status_of_message(m.id)
|
||||||
.map_err(WireError::new)?;
|
.map_err(WireError::new)?;
|
||||||
Ok(rows
|
out.push(chat_message(m, status));
|
||||||
.into_iter()
|
}
|
||||||
.map(|m| ChatMessage {
|
Ok(out)
|
||||||
direction: m.dir,
|
}
|
||||||
body: String::from_utf8_lossy(&m.plaintext).into_owned(),
|
|
||||||
})
|
/// Outbox rows for one friend that the core has not delivered yet: the
|
||||||
.collect())
|
/// `"queued"` / `"sending"` / `"failed"` rows behind
|
||||||
|
/// [`ChatMessage::delivery`], with the core's own attempt counter and next
|
||||||
|
/// attempt time attached.
|
||||||
|
///
|
||||||
|
/// This is what lets a chat row say *why* it is still queued — `try 3/8,
|
||||||
|
/// retry 45s` — instead of a flat `"queued"`: [`OutboxRow::attempts`] and
|
||||||
|
/// [`OutboxRow::next_attempt_at`] are read from the store, never guessed by
|
||||||
|
/// the client. An empty result means nothing is outstanding for that friend.
|
||||||
|
pub async fn outbox(&self, pubkey_hex: String) -> WResult<Vec<OutboxRow>> {
|
||||||
|
let pk = unhex(&pubkey_hex)?;
|
||||||
|
let rows = self.node()?.outbox_pending(&pk).map_err(WireError::new)?;
|
||||||
|
Ok(rows.iter().map(outbox_row).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Delete every message body. Identity and friends survive.
|
/// Delete every message body. Identity and friends survive.
|
||||||
|
|
@ -415,13 +514,67 @@ fn unhex(s: &str) -> WResult<Vec<u8>> {
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `Node::send` only ever yields `Sent` or `Queued`; `Sending`/`Failed` exist
|
||||||
|
/// only on stored outbox rows. Everything that is not a completed send maps to
|
||||||
|
/// `Queued`, so a status this build does not know about is never reported as
|
||||||
|
/// delivered — the fail-safe direction for a caller that hides its retry UI.
|
||||||
|
fn send_state(status: OutboxStatus) -> SendState {
|
||||||
|
match status {
|
||||||
|
OutboxStatus::Sent => SendState::Sent,
|
||||||
|
_ => SendState::Queued,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One stored chat row as the record a client renders. `id` is copied through
|
||||||
|
/// untouched: it is the `messages.id` an [`OutboxRow::message_id`] joins to.
|
||||||
|
fn chat_message(m: Message, status: Option<OutboxStatus>) -> ChatMessage {
|
||||||
|
ChatMessage {
|
||||||
|
id: m.id,
|
||||||
|
direction: m.dir.clone(),
|
||||||
|
body: String::from_utf8_lossy(&m.plaintext).into_owned(),
|
||||||
|
delivery: delivery_of(&m.dir, status),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delivery string for one stored chat row. `None` for incoming rows. An
|
||||||
|
/// outgoing row with no outbox row was accepted on the first attempt, so it is
|
||||||
|
/// reported as `"sent"` rather than left blank.
|
||||||
|
fn delivery_of(dir: &str, status: Option<OutboxStatus>) -> Option<String> {
|
||||||
|
if dir != "out" {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(match status {
|
||||||
|
None | Some(OutboxStatus::Sent) => "sent".to_string(),
|
||||||
|
Some(other) => other.to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One core outbox row as the record a client renders.
|
||||||
|
///
|
||||||
|
/// Field-for-field, so the client shows the store's numbers instead of a
|
||||||
|
/// timeout it invented: the row is keyed by `message_id` (the chat row to
|
||||||
|
/// patch), carries the store's own status string, and next-attempt as an
|
||||||
|
/// absolute unix second for the client to count down from.
|
||||||
|
fn outbox_row(entry: &OutboxEntry) -> OutboxRow {
|
||||||
|
OutboxRow {
|
||||||
|
message_id: entry.message_id,
|
||||||
|
status: entry.status.as_db_str().to_string(),
|
||||||
|
attempts: entry.attempts,
|
||||||
|
next_attempt_at: entry.next_attempt_at,
|
||||||
|
last_error: entry.last_error.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
//! No Tor here on purpose: these exercise the *lifecycle* contract of the
|
//! No Tor here on purpose: these exercise the *lifecycle* contract of the
|
||||||
//! handle, which is what a shut-down node must guarantee. A `Wire` with no
|
//! handle, which is what a shut-down node must guarantee. A `Wire` with no
|
||||||
//! node is exactly the state `shutdown()` leaves behind.
|
//! node is exactly the state `shutdown()` leaves behind.
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use onionwire::Store;
|
||||||
|
use onionwire::outbox::OutboxStatus;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
fn stopped_wire() -> Wire {
|
fn stopped_wire() -> Wire {
|
||||||
Wire {
|
Wire {
|
||||||
|
|
@ -482,4 +635,171 @@ mod tests {
|
||||||
);
|
);
|
||||||
assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped);
|
assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sent_is_sent_everything_else_is_queued() {
|
||||||
|
assert_eq!(send_state(OutboxStatus::Sent), SendState::Sent);
|
||||||
|
assert_eq!(send_state(OutboxStatus::Queued), SendState::Queued);
|
||||||
|
// `Node::send` never returns these today, but they exist on stored
|
||||||
|
// rows. Unknown states map to `Queued` — the safe direction: never
|
||||||
|
// report a send as delivered unless the core says `Sent`.
|
||||||
|
assert_eq!(send_state(OutboxStatus::Sending), SendState::Queued);
|
||||||
|
assert_eq!(
|
||||||
|
send_state(OutboxStatus::Failed("no route".into())),
|
||||||
|
SendState::Queued
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn delivery_is_reported_for_outgoing_rows_only() {
|
||||||
|
assert_eq!(delivery_of("in", Some(OutboxStatus::Queued)), None);
|
||||||
|
// Outgoing row with no outbox row: delivered on the first attempt.
|
||||||
|
assert_eq!(delivery_of("out", None).as_deref(), Some("sent"));
|
||||||
|
assert_eq!(
|
||||||
|
delivery_of("out", Some(OutboxStatus::Sent)).as_deref(),
|
||||||
|
Some("sent")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
delivery_of("out", Some(OutboxStatus::Queued)).as_deref(),
|
||||||
|
Some("queued")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
delivery_of("out", Some(OutboxStatus::Sending)).as_deref(),
|
||||||
|
Some("sending")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
delivery_of("out", Some(OutboxStatus::Failed("no route".into()))).as_deref(),
|
||||||
|
Some("failed: no route")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One core outbox row with only the fields a record carries filled in
|
||||||
|
/// interestingly. `id`, `friend_pk`, `body` and `created_at` do not cross
|
||||||
|
/// UniFFI, so their values are irrelevant.
|
||||||
|
fn entry(status: OutboxStatus, attempts: u32, last_error: Option<&str>) -> OutboxEntry {
|
||||||
|
OutboxEntry {
|
||||||
|
id: 3,
|
||||||
|
friend_pk: vec![0xaa; 32],
|
||||||
|
message_id: 42,
|
||||||
|
body: b"hello".to_vec(),
|
||||||
|
attempts,
|
||||||
|
next_attempt_at: 1_700_000_045,
|
||||||
|
created_at: 1_700_000_000,
|
||||||
|
status,
|
||||||
|
last_error: last_error.map(str::to_string),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outbox_row_carries_the_join_key_the_attempt_count_and_the_next_attempt_time() {
|
||||||
|
let row = outbox_row(&entry(
|
||||||
|
OutboxStatus::Queued,
|
||||||
|
3,
|
||||||
|
Some("peer onion unreachable"),
|
||||||
|
));
|
||||||
|
assert_eq!(row.message_id, 42);
|
||||||
|
assert_eq!(row.status, "queued");
|
||||||
|
assert_eq!(row.attempts, 3);
|
||||||
|
assert_eq!(row.next_attempt_at, 1_700_000_045);
|
||||||
|
assert_eq!(row.last_error.as_deref(), Some("peer onion unreachable"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outbox_row_keeps_the_stores_own_status_encoding() {
|
||||||
|
// These four strings are the `outbox.status` CHECK constraint in
|
||||||
|
// `src/store.rs`; a client switches on them verbatim.
|
||||||
|
for (status, want) in [
|
||||||
|
(OutboxStatus::Queued, "queued"),
|
||||||
|
(OutboxStatus::Sending, "sending"),
|
||||||
|
(OutboxStatus::Sent, "sent"),
|
||||||
|
(
|
||||||
|
OutboxStatus::Failed("peer onion unreachable".into()),
|
||||||
|
"failed",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
assert_eq!(outbox_row(&entry(status, 0, None)).status, want);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_failed_outbox_row_carries_the_cores_reason_verbatim() {
|
||||||
|
let row = outbox_row(&entry(
|
||||||
|
OutboxStatus::Failed("peer onion unreachable".into()),
|
||||||
|
8,
|
||||||
|
Some("peer onion unreachable"),
|
||||||
|
));
|
||||||
|
assert_eq!(row.status, "failed");
|
||||||
|
assert_eq!(row.attempts, 8);
|
||||||
|
assert_eq!(row.last_error.as_deref(), Some("peer onion unreachable"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outbox_max_attempts_is_the_denominator_a_client_renders_against() {
|
||||||
|
// The Android chat row renders `try n/8`. Pin the number so the SDK and
|
||||||
|
// the core's retry budget cannot drift apart silently.
|
||||||
|
assert_eq!(outbox_max_attempts(), 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An empty dir for a store-backed test. `tempfile` is not a dependency of
|
||||||
|
/// this crate and a store only needs somewhere private to live.
|
||||||
|
fn temp_home() -> PathBuf {
|
||||||
|
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
let dir = std::env::temp_dir().join(format!(
|
||||||
|
"onionwire-sdk-join-{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||||
|
));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
dir
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The property the Android client joins on: a chat row and the outbox row
|
||||||
|
/// behind it report the same `messages.id`. Reads both sides out of a real
|
||||||
|
/// store through the same helpers `Wire::messages` / `Wire::outbox` use, so
|
||||||
|
/// a client can match on the id instead of counting rows.
|
||||||
|
#[test]
|
||||||
|
fn a_chat_row_joins_to_its_outbox_row_by_message_id() {
|
||||||
|
let home = temp_home();
|
||||||
|
let store = Store::open_at_with_passphrase(&home, "join-key-pass").unwrap();
|
||||||
|
let friend = [0x11u8; 32];
|
||||||
|
store.upsert_friend(&friend, "peer.onion", None).unwrap();
|
||||||
|
let row_id = store
|
||||||
|
.append_message_id(&friend, "out", b"still queued")
|
||||||
|
.unwrap();
|
||||||
|
store
|
||||||
|
.enqueue_outbox(
|
||||||
|
&friend,
|
||||||
|
row_id,
|
||||||
|
3,
|
||||||
|
1_700_000_045,
|
||||||
|
"peer onion unreachable",
|
||||||
|
1_700_000_000,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Same two reads `Wire::messages` / `Wire::outbox` do.
|
||||||
|
let mut messages = Vec::new();
|
||||||
|
for m in store.list_messages(&friend).unwrap() {
|
||||||
|
let status = store.outbox_status_of_message(m.id).unwrap();
|
||||||
|
messages.push(chat_message(m, status));
|
||||||
|
}
|
||||||
|
let rows: Vec<OutboxRow> = store
|
||||||
|
.pending_outbox(&friend)
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(outbox_row)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
assert_eq!(messages.len(), 1);
|
||||||
|
assert_eq!(rows.len(), 1);
|
||||||
|
// The outbox side really is the stored row (not a defaulted id) …
|
||||||
|
assert_eq!(rows[0].message_id, row_id);
|
||||||
|
// … and the id the client gets on the message is that same row id.
|
||||||
|
assert_eq!(messages[0].id, rows[0].message_id);
|
||||||
|
// Both sides describe the same row, queued with its attempt count.
|
||||||
|
assert_eq!(messages[0].delivery.as_deref(), Some("queued"));
|
||||||
|
assert_eq!(rows[0].attempts, 3);
|
||||||
|
|
||||||
|
std::fs::remove_dir_all(&home).ok();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue