fix(sdk): surface Sent/Queued on send(), and build the SDK in CI
`Node::send()` became `Result<OutboxStatus, String>` in the local-outbox work,
which broke `crates/onionwire-sdk` (E0308 at src/lib.rs:195) — and nothing
noticed, because the SDK is a separate cargo workspace that root CI never
compiles and android-release.yml only builds on a v*.*.* tag.
- `Wire::send()` now returns `WResult<SendState>` (`Sent` | `Queued`) instead
of swallowing the outcome as `()`. A queued send is local-only until the
retry worker gets a circuit through, so the Kotlin boundary must be able to
tell it apart from a delivered one.
- `ChatMessage` gains `delivery: Option<String>` ("sent" | "queued" |
"sending" | "failed: <reason>"), populated from the message's outbox row;
`None` for incoming messages. An outgoing row with no outbox row was accepted
on the first attempt, so it reads "sent".
- New `sdk` job in `.forgejo/workflows/ci.yml`: `cargo test --locked` +
`cargo clippy --locked --all-targets -- -D warnings` in `crates/onionwire-sdk`
in the same rust:1.91-bookworm container, with its own target volume (the SDK
resolves the root crate with rustls, so sharing the root job's target dir
would thrash feature-unified artifacts).
- Drift found while un-rotting it: the SDK `Cargo.lock` was stale (missing
`sha2`, added to the root crate by the zeroize work), so `--locked` failed;
and the SDK README still said "no outbox, no spool in v1" and "identity keys
in sqlite are plaintext", both untrue since the outbox and SQLCipher landed.
Tests: crates/onionwire-sdk 4 passed (2 new unit tests over the status
mapping), clippy clean; root `cargo test --locked` clean. The CI job body was
smoke-run locally in the same container image before being committed.
# Conflicts:
# crates/onionwire-sdk/src/lib.rs
This commit is contained in:
parent
2cbe7d41e5
commit
168727ac39
20 changed files with 306 additions and 103 deletions
|
|
@ -39,6 +39,11 @@ env:
|
|||
CARGO_REGISTRY_VOLUME: onionwire-cargo-registry
|
||||
CARGO_TARGET_VOLUME: onionwire-target-ci
|
||||
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:
|
||||
test:
|
||||
|
|
@ -73,3 +78,44 @@ jobs:
|
|||
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \
|
||||
| docker start -a -i "$BUILD_CONTAINER"
|
||||
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
|
||||
|
|
|
|||
|
|
@ -289,7 +289,7 @@ FORGEJO_TOKEN=<pat> scripts/build-release-local.sh vX.Y.Z
|
|||
|
||||
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, both on the Pi runner (`docker` label), serialized by the `onionwire-ci-pi` concurrency group. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk`, which is a separate cargo workspace (own `Cargo.lock`, root crate by path, `rustls` instead of `native-tls`) and therefore never gets compiled by the root job — without it a root-crate signature change would silently break the Android SDK and the tagged release AAR. 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`.
|
||||
|
||||
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"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"openssl-sys",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
|
@ -2774,6 +2775,7 @@ dependencies = [
|
|||
"rusqlite",
|
||||
"safelog",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha3 0.10.9",
|
||||
"snow",
|
||||
"tokio",
|
||||
|
|
@ -2781,6 +2783,7 @@ dependencies = [
|
|||
"tor-hsservice",
|
||||
"tor-rtcompat",
|
||||
"x25519-dalek",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -2801,6 +2804,28 @@ version = "0.3.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
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]]
|
||||
name = "option-ext"
|
||||
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. |
|
||||
| Invite | `onionwire:v1:k=…:o=…:spk=…:sig=…` |
|
||||
| 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. |
|
||||
| At rest | Chat bodies encrypted (Argon2id wrap + ChaCha20-Poly1305). Identity keys in sqlite are plaintext — that is honest, not an oversight. |
|
||||
| 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 | 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
|
||||
|
||||
|
|
@ -66,8 +66,10 @@ Requirements:
|
|||
|
||||
## Kotlin surface
|
||||
|
||||
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.
|
||||
Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes.
|
||||
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
|
||||
import uniffi.onionwire_sdk.*
|
||||
|
|
@ -88,8 +90,16 @@ val friend: FriendInfo = wire.addFriend(pasted)
|
|||
// 4. Roster and chat.
|
||||
val roster: List<FriendInfo> = wire.friends()
|
||||
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)
|
||||
// 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
|
||||
// the SDK owns the typed confirmation.
|
||||
|
|
|
|||
|
|
@ -11,7 +11,10 @@
|
|||
//! the friend.
|
||||
//! * Transport is in-process Arti. There is no `tor` binary, no torrc, no
|
||||
//! 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
|
||||
//! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable
|
||||
|
|
@ -27,7 +30,7 @@ use std::sync::{Arc, Mutex, OnceLock};
|
|||
|
||||
use onionwire::hs::TorState as CoreTorState;
|
||||
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
|
||||
use onionwire::qr;
|
||||
use onionwire::outbox::OutboxStatus;use onionwire::qr;
|
||||
|
||||
uniffi::setup_scaffolding!();
|
||||
|
||||
|
|
@ -98,11 +101,34 @@ pub struct FriendInfo {
|
|||
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)]
|
||||
pub struct ChatMessage {
|
||||
/// "in" or "out".
|
||||
pub direction: 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>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, uniffi::Record)]
|
||||
|
|
@ -332,34 +358,44 @@ impl Wire {
|
|||
.map_err(WireError::new)
|
||||
}
|
||||
|
||||
/// Send one message. Returns once the outcome is known: delivered now, or
|
||||
/// queued for retry because the peer's onion is unreachable. A protocol
|
||||
/// error (bad signature, bad frame) still fails immediately and is never
|
||||
/// queued. Use [`flush`](Self::flush) to retry the queue on demand.
|
||||
pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> {
|
||||
/// Send one chat message.
|
||||
///
|
||||
/// Returns [`SendState::Sent`] when the frame reached the peer's onion
|
||||
/// service during this call, and [`SendState::Queued`] when it did not: the
|
||||
/// 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)?;
|
||||
self.node()?
|
||||
let status = self
|
||||
.node()?
|
||||
.send(&pk, body.as_bytes())
|
||||
.await
|
||||
.map_err(WireError::new)?;
|
||||
Ok(())
|
||||
}
|
||||
Ok(send_state(status)) }
|
||||
|
||||
/// 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>> {
|
||||
let pk = unhex(&pubkey_hex)?;
|
||||
let rows = self
|
||||
.node()?
|
||||
.list_messages(&pk)
|
||||
.map_err(WireError::new)?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|m| ChatMessage {
|
||||
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()?
|
||||
.outbox_status_of_message(m.id)
|
||||
.map_err(WireError::new)?;
|
||||
out.push(ChatMessage { body: String::from_utf8_lossy(&m.plaintext).into_owned(),
|
||||
delivery: delivery_of(&m.dir, status),
|
||||
direction: m.dir,
|
||||
body: String::from_utf8_lossy(&m.plaintext).into_owned(),
|
||||
})
|
||||
.collect())
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Delete every message body. Identity and friends survive.
|
||||
|
|
@ -415,6 +451,30 @@ fn unhex(s: &str) -> WResult<Vec<u8>> {
|
|||
.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,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
//! No Tor here on purpose: these exercise the *lifecycle* contract of the
|
||||
|
|
@ -422,6 +482,7 @@ mod tests {
|
|||
//! node is exactly the state `shutdown()` leaves behind.
|
||||
|
||||
use super::*;
|
||||
use onionwire::outbox::OutboxStatus;
|
||||
|
||||
fn stopped_wire() -> Wire {
|
||||
Wire {
|
||||
|
|
@ -482,4 +543,42 @@ mod tests {
|
|||
);
|
||||
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")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
18
src/node.rs
18
src/node.rs
|
|
@ -251,7 +251,8 @@ impl Node {
|
|||
/// `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 {
|
||||
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(_) => {
|
||||
|
|
@ -733,7 +734,10 @@ impl Node {
|
|||
|
||||
/// 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> {
|
||||
pub fn outbox_pending(
|
||||
&self,
|
||||
friend_pk: &[u8],
|
||||
) -> Result<Vec<crate::store::OutboxEntry>, String> {
|
||||
self.outbox.pending(friend_pk)
|
||||
}
|
||||
|
||||
|
|
@ -1055,7 +1059,8 @@ fn checkpoint_wal(home: &Path) -> Result<(), String> {
|
|||
if !db.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
let conn = rusqlite::Connection::open(&db).map_err(|e| format!("open {}: {e}", db.display()))?;
|
||||
let conn =
|
||||
rusqlite::Connection::open(&db).map_err(|e| format!("open {}: {e}", db.display()))?;
|
||||
let (busy, log, checkpointed): (i64, i64, i64) = conn
|
||||
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
|
||||
|
|
@ -1145,8 +1150,11 @@ mod lifecycle_tests {
|
|||
conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);")
|
||||
.expect("create table");
|
||||
for _ in 0..64 {
|
||||
conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params![vec![7u8; 512]])
|
||||
.expect("insert");
|
||||
conn.execute(
|
||||
"INSERT INTO t (v) VALUES (?1)",
|
||||
rusqlite::params![vec![7u8; 512]],
|
||||
)
|
||||
.expect("insert");
|
||||
}
|
||||
|
||||
let wal = home.join("onionwire.db-wal");
|
||||
|
|
|
|||
|
|
@ -99,10 +99,9 @@ impl Deliverer for ArtiDeliverer {
|
|||
.connect((onion, HS_PORT))
|
||||
.await
|
||||
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
|
||||
let mut sess =
|
||||
session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey)
|
||||
.await
|
||||
.map_err(|e| e.into_message())?;
|
||||
let mut sess = session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey)
|
||||
.await
|
||||
.map_err(|e| e.into_message())?;
|
||||
let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?;
|
||||
frame::write_frame(&mut stream, &ct)
|
||||
.await
|
||||
|
|
@ -145,7 +144,11 @@ impl Outbox {
|
|||
/// protocol error or a bad local state, never retried.
|
||||
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
|
||||
let (onion, prekey) = self.target(friend_pk)?;
|
||||
match self.deliverer.deliver(&onion, friend_pk, &prekey, plaintext).await {
|
||||
match self
|
||||
.deliverer
|
||||
.deliver(&onion, friend_pk, &prekey, plaintext)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
self.store()?.append_message(friend_pk, "out", plaintext)?;
|
||||
Ok(OutboxStatus::Sent)
|
||||
|
|
@ -155,14 +158,7 @@ impl Outbox {
|
|||
let now = unix_now();
|
||||
let store = self.store()?;
|
||||
let message_id = store.append_message_id(friend_pk, "out", plaintext)?;
|
||||
store.enqueue_outbox(
|
||||
friend_pk,
|
||||
message_id,
|
||||
1,
|
||||
now + backoff_secs(0),
|
||||
&e,
|
||||
now,
|
||||
)?;
|
||||
store.enqueue_outbox(friend_pk, message_id, 1, now + backoff_secs(0), &e, now)?;
|
||||
Ok(OutboxStatus::Queued)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
43
src/store.rs
43
src/store.rs
|
|
@ -802,17 +802,13 @@ impl Store {
|
|||
}
|
||||
|
||||
pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> {
|
||||
self.append_message_id(friend_pk, dir, plaintext).map(|_| ())
|
||||
self.append_message_id(friend_pk, dir, plaintext)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Same as `append_message`, returning the row id so an outbox row can
|
||||
/// point at the body instead of storing a second copy.
|
||||
pub fn append_message_id(
|
||||
&self,
|
||||
friend_pk: &[u8],
|
||||
dir: &str,
|
||||
plaintext: &[u8],
|
||||
) -> Result<i64> {
|
||||
pub fn append_message_id(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<i64> {
|
||||
if dir != "in" && dir != "out" {
|
||||
return Err(Error("dir must be in or out".into()));
|
||||
}
|
||||
|
|
@ -861,11 +857,7 @@ impl Store {
|
|||
let aad = message_aad(friend_id, &dir, id);
|
||||
let plaintext = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
|
||||
.map_err(|_| Error("message decrypt failed".into()))?;
|
||||
out.push(Message {
|
||||
id,
|
||||
dir,
|
||||
plaintext,
|
||||
});
|
||||
out.push(Message { id, dir, plaintext });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
|
@ -1115,7 +1107,10 @@ fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Friend> {
|
|||
fn gen_prekey() -> (Zeroizing<Vec<u8>>, Vec<u8>) {
|
||||
let sk = StaticSecret::random_from_rng(OsRng);
|
||||
let pk = X25519Public::from(&sk);
|
||||
(Zeroizing::new(sk.to_bytes().to_vec()), pk.to_bytes().to_vec())
|
||||
(
|
||||
Zeroizing::new(sk.to_bytes().to_vec()),
|
||||
pk.to_bytes().to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Per-install KDF salt for the whole-database key. Not secret (a salt never
|
||||
|
|
@ -1638,22 +1633,16 @@ mod at_rest {
|
|||
params![salt.as_slice(), wrapped],
|
||||
)
|
||||
.unwrap();
|
||||
for (dir, body) in [
|
||||
("in", "legacy-body-xyz"),
|
||||
("out", "legacy-reply-xyz"),
|
||||
] {
|
||||
for (dir, body) in [("in", "legacy-body-xyz"), ("out", "legacy-reply-xyz")] {
|
||||
conn.execute(
|
||||
"INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (1, ?1, x'', 7)",
|
||||
params![dir],
|
||||
)
|
||||
.unwrap();
|
||||
let id = conn.last_insert_rowid();
|
||||
let blob = crate::backup::aead_encrypt(
|
||||
&data_key,
|
||||
body.as_bytes(),
|
||||
&message_aad(1, dir, id),
|
||||
)
|
||||
.unwrap();
|
||||
let blob =
|
||||
crate::backup::aead_encrypt(&data_key, body.as_bytes(), &message_aad(1, dir, id))
|
||||
.unwrap();
|
||||
conn.execute(
|
||||
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
|
||||
params![blob, id],
|
||||
|
|
@ -1681,7 +1670,8 @@ mod at_rest {
|
|||
"fixture must be a plaintext sqlite file"
|
||||
);
|
||||
|
||||
let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade");
|
||||
let store =
|
||||
Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade");
|
||||
assert_eq!(
|
||||
store.self_identity().unwrap().identity_sk[..],
|
||||
LEGACY_IDENTITY_SK[..]
|
||||
|
|
@ -1703,7 +1693,10 @@ mod at_rest {
|
|||
);
|
||||
for (needle, what) in [
|
||||
(b"legacy-body-xyz".to_vec(), "message body"),
|
||||
(fingerprint(&LEGACY_FRIEND_PK).into_bytes(), "friend pubkey hex"),
|
||||
(
|
||||
fingerprint(&LEGACY_FRIEND_PK).into_bytes(),
|
||||
"friend pubkey hex",
|
||||
),
|
||||
(LEGACY_IDENTITY_SK.to_vec(), "identity secret"),
|
||||
(b"legacy-friend.onion".to_vec(), "locator"),
|
||||
] {
|
||||
|
|
|
|||
|
|
@ -276,8 +276,10 @@ pub fn chat_with_delivery(
|
|||
// second), and `pending` is ordered by row id, so a hypothetical duplicate
|
||||
// resolves to the newest — the same rule the store's own
|
||||
// `outbox_status_of_message` uses.
|
||||
let by_id: HashMap<i64, &OutboxEntry> =
|
||||
pending.iter().map(|entry| (entry.message_id, entry)).collect();
|
||||
let by_id: HashMap<i64, &OutboxEntry> = pending
|
||||
.iter()
|
||||
.map(|entry| (entry.message_id, entry))
|
||||
.collect();
|
||||
let mut tags: Vec<Option<String>> = vec![None; msgs.len()];
|
||||
for (i, msg) in msgs.iter().enumerate() {
|
||||
if msg.dir != "out" {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
//! M6: typed-frame dispatcher — classify before append_message.
|
||||
|
||||
use onionwire::dispatch::{classify, Kind};
|
||||
use onionwire::dispatch::{Kind, classify};
|
||||
|
||||
#[test]
|
||||
fn chat_is_chat() {
|
||||
|
|
|
|||
|
|
@ -5,11 +5,11 @@
|
|||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use onionwire::Store;
|
||||
use onionwire::outbox::{
|
||||
BACKOFF_CAP_SECS, BACKOFF_START_SECS, BoxFut, Deliverer, Outbox, OutboxStatus, backoff_secs,
|
||||
is_permanent_send_error,
|
||||
};
|
||||
use onionwire::Store;
|
||||
|
||||
const PASS: &str = "outbox-pass";
|
||||
|
||||
|
|
@ -96,9 +96,7 @@ fn backoff_schedule_doubles_from_30s_and_caps_at_30m() {
|
|||
|
||||
#[test]
|
||||
fn transport_errors_are_retryable_protocol_errors_are_not() {
|
||||
assert!(!is_permanent_send_error(
|
||||
"connect abc.onion:80: timed out"
|
||||
));
|
||||
assert!(!is_permanent_send_error("connect abc.onion:80: timed out"));
|
||||
assert!(!is_permanent_send_error("connect abc.onion:80: refused"));
|
||||
assert!(is_permanent_send_error("fingerprint mismatch"));
|
||||
assert!(is_permanent_send_error("frame too large"));
|
||||
|
|
@ -114,7 +112,11 @@ async fn send_to_dead_onion_is_queued_and_row_persists() {
|
|||
let ob = outbox(Arc::clone(&store), dead, 8);
|
||||
|
||||
let status = ob.send(&pk(1), b"hello dead peer").await.unwrap();
|
||||
assert_eq!(status, OutboxStatus::Queued, "dead onion must queue, not Err");
|
||||
assert_eq!(
|
||||
status,
|
||||
OutboxStatus::Queued,
|
||||
"dead onion must queue, not Err"
|
||||
);
|
||||
assert!(!status.is_terminal());
|
||||
|
||||
let pending = ob.pending(&pk(1)).unwrap();
|
||||
|
|
@ -122,7 +124,9 @@ async fn send_to_dead_onion_is_queued_and_row_persists() {
|
|||
assert_eq!(pending[0].status, OutboxStatus::Queued);
|
||||
assert_eq!(pending[0].attempts, 1, "the immediate attempt counted");
|
||||
assert!(
|
||||
ob.status_of_message(pending[0].message_id).unwrap().is_some(),
|
||||
ob.status_of_message(pending[0].message_id)
|
||||
.unwrap()
|
||||
.is_some(),
|
||||
"status is addressable by chat row id"
|
||||
);
|
||||
|
||||
|
|
@ -253,7 +257,12 @@ async fn protocol_error_fails_immediately_and_is_not_queued() {
|
|||
"protocol errors are never queued"
|
||||
);
|
||||
assert!(
|
||||
store.lock().unwrap().list_messages(&pk(1)).unwrap().is_empty(),
|
||||
store
|
||||
.lock()
|
||||
.unwrap()
|
||||
.list_messages(&pk(1))
|
||||
.unwrap()
|
||||
.is_empty(),
|
||||
"a failed protocol send is not written to history"
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@
|
|||
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
|
||||
use onionwire::qr;
|
||||
use onionwire::Store;
|
||||
use onionwire::qr;
|
||||
|
||||
static ENV_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
//! Composer Enter must send chat to the selected friend, not only slash commands.
|
||||
|
||||
use onionwire::tui::{
|
||||
composer_enter, take_job_result, ComposerAction, SlashCmd, WipeKind, TUI_POLL,
|
||||
ComposerAction, SlashCmd, TUI_POLL, WipeKind, composer_enter, take_job_result,
|
||||
};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
|
|
|||
|
|
@ -46,7 +46,11 @@ fn spawn_echo(
|
|||
async fn launch_echo(
|
||||
client: &Client,
|
||||
nickname: &str,
|
||||
) -> (Arc<RunningOnionService>, tokio::task::JoinHandle<()>, String) {
|
||||
) -> (
|
||||
Arc<RunningOnionService>,
|
||||
tokio::task::JoinHandle<()>,
|
||||
String,
|
||||
) {
|
||||
let launched = client
|
||||
.launch_onion_service(hs::hs_config(nickname).expect("hs_config"))
|
||||
.expect("launch_onion_service")
|
||||
|
|
@ -66,7 +70,10 @@ async fn echo_ping(client: &Client, onion: &str) -> Result<(), String> {
|
|||
.write_all(PING)
|
||||
.await
|
||||
.map_err(|e| format!("write ping: {e}"))?;
|
||||
stream.flush().await.map_err(|e| format!("flush ping: {e}"))?;
|
||||
stream
|
||||
.flush()
|
||||
.await
|
||||
.map_err(|e| format!("flush ping: {e}"))?;
|
||||
let mut buf = vec![0u8; PING.len()];
|
||||
stream
|
||||
.read_exact(&mut buf)
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@
|
|||
//! checkpoint, and the SDK's typed error after shutdown — runs in the normal
|
||||
//! suite (`tests/hs.rs`, `src/node.rs`, `crates/onionwire-sdk/src/lib.rs`).
|
||||
|
||||
use onionwire::node::{FlushOutcome, Node};
|
||||
use onionwire::hs::TorState;
|
||||
use onionwire::node::{FlushOutcome, Node};
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "needs live Tor network"]
|
||||
|
|
@ -93,4 +93,4 @@ async fn shutdown_stops_the_node_and_later_calls_are_typed_errors() {
|
|||
home.join("onionwire.db").exists(),
|
||||
"shutdown must not delete the store"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,19 +11,19 @@
|
|||
//! `chars().count()` width checks here match `tests/tui_chrome.rs` on purpose.
|
||||
//! They are the known-wrong metric (see `chars_count_is_not_terminal_cells`).
|
||||
|
||||
use onionwire::FriendProfile;
|
||||
use onionwire::qr;
|
||||
use onionwire::tui::{
|
||||
backup_screen_text, banner_for_width, compact_banner, draw_share, fingerprint_mismatch_banner,
|
||||
help_overlay_text, main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text,
|
||||
rotate_screen_text, status_footer, who_overlay_text, wipe_screen_text, wordmark_banner,
|
||||
ProfileEditor, WipeKind,
|
||||
ProfileEditor, WipeKind, backup_screen_text, banner_for_width, compact_banner, draw_share,
|
||||
fingerprint_mismatch_banner, help_overlay_text, main_footer_hints, onion_glyph,
|
||||
quit_screen_text, restore_screen_text, rotate_screen_text, status_footer, who_overlay_text,
|
||||
wipe_screen_text, wordmark_banner,
|
||||
};
|
||||
use onionwire::FriendProfile;
|
||||
use ratatui::Frame;
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
|
||||
use ratatui::Frame;
|
||||
use ratatui::Terminal;
|
||||
|
||||
const SIZES: [(u16, u16); 3] = [(80, 24), (120, 40), (200, 60)];
|
||||
const FP: &str = "abcdef0123456789deadbeefcafebabe";
|
||||
|
|
|
|||
|
|
@ -426,7 +426,14 @@ fn pending_row(
|
|||
}
|
||||
|
||||
fn queued_row(message_id: i64, body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry {
|
||||
pending_row(message_id, body, OutboxStatus::Queued, attempts, next_in, now)
|
||||
pending_row(
|
||||
message_id,
|
||||
body,
|
||||
OutboxStatus::Queued,
|
||||
attempts,
|
||||
next_in,
|
||||
now,
|
||||
)
|
||||
}
|
||||
|
||||
fn sending_row(message_id: i64, body: &str, now: i64) -> OutboxEntry {
|
||||
|
|
@ -549,7 +556,12 @@ fn delivery_markers_have_exercised_ascii_fallbacks() {
|
|||
in_msg(5, "epsilon"),
|
||||
];
|
||||
let pending = vec![
|
||||
failed_row(1, "alpha", "connect peer.onion:80: connection timed out", now),
|
||||
failed_row(
|
||||
1,
|
||||
"alpha",
|
||||
"connect peer.onion:80: connection timed out",
|
||||
now,
|
||||
),
|
||||
queued_row(2, "beta", 1, 30, now),
|
||||
sending_row(3, "gamma", now),
|
||||
];
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ use tokio::net::TcpListener;
|
|||
/// `ONIONWIRE_WALLET_NO_SPEND` is process-wide; tests that touch env serialize.
|
||||
static ENV_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
|
||||
fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
|
||||
TransferRow {
|
||||
txid: txid.into(),
|
||||
|
|
@ -321,10 +320,7 @@ async fn no_spend_mode_refuses_transfer_with_no_rpc_request() {
|
|||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(
|
||||
err.to_ascii_lowercase().contains("view-only"),
|
||||
"got {err}"
|
||||
);
|
||||
assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
let seen = log.lock().expect("log").clone();
|
||||
assert!(seen.is_empty(), "no RPC request may be made: {seen:?}");
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
//! M5: wipe messages (keep identity + friends); wipe-all is a new person.
|
||||
|
||||
use onionwire::tui::{
|
||||
parse_slash, quit_screen_text, wipe_screen_text, QuitDecision, QuitPrompt, WipeDecision,
|
||||
WipeKind, WipePrompt,
|
||||
QuitDecision, QuitPrompt, WipeDecision, WipeKind, WipePrompt, parse_slash, quit_screen_text,
|
||||
wipe_screen_text,
|
||||
};
|
||||
use onionwire::{PaymentWrite, Store};
|
||||
|
||||
|
|
|
|||
|
|
@ -4,11 +4,11 @@
|
|||
//! core dumps, OS `String` interning, `src/file.rs` + TUI buffers, and the
|
||||
//! Noise handshake/transport state that lives inside `snow`.
|
||||
|
||||
use onionwire::Store;
|
||||
use onionwire::backup::BackupKeys;
|
||||
use onionwire::profile;
|
||||
use onionwire::session::Keys;
|
||||
use onionwire::wallet::Wallet;
|
||||
use onionwire::Store;
|
||||
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
|
||||
|
||||
/// Type-level: the wrapper is applied to the type, not just mentioned in a
|
||||
|
|
|
|||
Loading…
Reference in a new issue