Compare commits

...
Author SHA1 Message Date
apk-dev
b91101d17a
feat(android): surface outbox delivery state in chat
Renders the core's own Queued/Sending/Sent/Failed per outgoing row instead of
implying a message either sent or did not: a clock for queued, a progress
spinner for sending, a double-check for delivered and an error marker with the
short reason for a terminal failure, plus a chat-level `N queued` footer that
keeps a fail-closed `send failed: <reason>` statement on screen.

States are read verbatim from ChatMessage.delivery (Node::outbox_status_of_message
over UniFFI) — no parallel enum, nothing guessed from a timeout. A missing or
unrecognised status renders as queued, never delivered.

WireViewModel.send() now returns the SDK SendState instead of dropping it, so the
composer can say a send is queued rather than pretend it landed, and the empty-chat
copy no longer claims 'there is no outbox in v1'.

Accessibility: every marker carries an explicit contentDescription sentence and a
test tag; the glyph is never what a screen reader announces.
2026-09-12 17:17:32 -04:00
Hermes rust-dev
168727ac39
fix(sdk): surface Sent/Queued on send(), and build the SDK in CI
All checks were successful
ci / test (pull_request) Successful in 4m5s
ci / sdk (pull_request) Successful in 6m47s
`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
2026-09-12 17:17:19 -04:00
24 changed files with 788 additions and 124 deletions

View file

@ -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

View file

@ -289,7 +289,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, 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`. - [`.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:

View file

@ -20,6 +20,7 @@ import uniffi.onionwire_sdk.ChatMessage
import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.FriendInfo
import uniffi.onionwire_sdk.InviteInfo import uniffi.onionwire_sdk.InviteInfo
import uniffi.onionwire_sdk.RotateOutcome import uniffi.onionwire_sdk.RotateOutcome
import uniffi.onionwire_sdk.SendState
import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.Wire
import uniffi.onionwire_sdk.decodeInvite import uniffi.onionwire_sdk.decodeInvite
import uniffi.onionwire_sdk.openWire import uniffi.onionwire_sdk.openWire
@ -303,7 +304,16 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
suspend fun messages(pubkeyHex: String): List<ChatMessage> = suspend fun messages(pubkeyHex: String): List<ChatMessage> =
requireWire().messages(pubkeyHex) requireWire().messages(pubkeyHex)
suspend fun send(pubkeyHex: String, body: String) = /**
* Sends one chat message and reports what the core did with it.
*
* `SENT` — the peer's onion took the frame during this call. `QUEUED` — it
* was unreachable, so the message is in the local outbox and the retry
* worker will dial again with backoff until it lands or fails terminally.
* The state is returned rather than swallowed so the UI never shows a
* queued message as delivered.
*/
suspend fun send(pubkeyHex: String, body: String): SendState =
requireWire().send(pubkeyHex, body) requireWire().send(pubkeyHex, body)
suspend fun wipeMessages() { suspend fun wipeMessages() {

View file

@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
@ -33,10 +34,14 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import uniffi.onionwire_sdk.ChatMessage import uniffi.onionwire_sdk.ChatMessage
import uniffi.onionwire_sdk.SendState
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@ -45,17 +50,19 @@ fun ChatScreen(
fingerprint: String, fingerprint: String,
onion: String, onion: String,
loadMessages: suspend () -> List<ChatMessage>, loadMessages: suspend () -> List<ChatMessage>,
onSend: suspend (String) -> Unit, onSend: suspend (String) -> SendState,
onBack: () -> Unit, onBack: () -> Unit,
) { ) {
var messages by remember { mutableStateOf<List<ChatMessage>?>(null) } var messages by remember { mutableStateOf<List<ChatMessage>?>(null) }
var draft by remember { mutableStateOf("") } var draft by remember { mutableStateOf("") }
var pending by remember { mutableStateOf<String?>(null) } var pending by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf<String?>(null) } var error by remember { mutableStateOf<String?>(null) }
var notice by remember { mutableStateOf<String?>(null) }
val listState = rememberLazyListState() val listState = rememberLazyListState()
// Poll: the node appends inbound messages in the background; there is no // Poll: the node appends inbound messages in the background and the retry
// push channel into the UI in v1. // worker moves queued rows along; there is no push channel into the UI in
// v1, so the delivery markers refresh on the same cadence as the bodies.
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
while (true) { while (true) {
runCatching { loadMessages() } runCatching { loadMessages() }
@ -65,12 +72,22 @@ fun ChatScreen(
} }
} }
// Fail-closed send. `send` retries the peer's onion for up to 3 minutes and // Send. An unreachable peer's onion is not an error any more: the core
// then errors — nothing is spooled, so a failure is a real failure. // stores the message in its local outbox and the retry worker dials again
// with backoff (30s doubling, capped at 30 min, 8 attempts, then terminal
// `failed`). A protocol error is still a real failure here — nothing is
// queued for those.
LaunchedEffect(pending) { LaunchedEffect(pending) {
val body = pending ?: return@LaunchedEffect val body = pending ?: return@LaunchedEffect
error = null error = null
notice = null
runCatching { onSend(body) } runCatching { onSend(body) }
.onSuccess {
if (it == SendState.QUEUED) {
notice = "Queued: their onion is unreachable. The message stays on " +
"this device and is retried until it lands."
}
}
.onFailure { error = it.message ?: it.toString() } .onFailure { error = it.message ?: it.toString() }
pending = null pending = null
} }
@ -127,8 +144,11 @@ fun ChatScreen(
Text("No messages", style = MaterialTheme.typography.titleSmall) Text("No messages", style = MaterialTheme.typography.titleSmall)
Spacer(Modifier.height(6.dp)) Spacer(Modifier.height(6.dp))
Text( Text(
"Sends fail closed: if their onion is down the message is " + "If their onion is unreachable the message is queued in a " +
"not spooled anywhere. There is no outbox in v1.", "local outbox on this device and retried with backoff " +
"(30s doubling, up to 30 min, 8 attempts) — never handed " +
"to a third party. A queued message is local-only until " +
"their onion takes it.",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
@ -148,6 +168,10 @@ fun ChatScreen(
Modifier.fillMaxWidth(), Modifier.fillMaxWidth(),
horizontalArrangement = horizontalArrangement =
if (mine) Arrangement.End else Arrangement.Start, if (mine) Arrangement.End else Arrangement.Start,
) {
Column(
horizontalAlignment = if (mine) Alignment.End
else Alignment.Start,
) { ) {
Text( Text(
m.body, m.body,
@ -162,11 +186,41 @@ fun ChatScreen(
) )
.padding(horizontal = 10.dp, vertical = 8.dp), .padding(horizontal = 10.dp, vertical = 8.dp),
) )
parseDelivery(m.direction, m.delivery)?.let { d ->
DeliveryMarker(d)
} }
} }
} }
} }
} }
}
}
// Chat-level outbox state: what is still coming, and whether
// anything has terminated as failed.
val summary = outboxSummary(
messages.orEmpty().map { parseDelivery(it.direction, it.delivery) },
)
summary.note?.let { note ->
Text(
note,
style = MaterialTheme.typography.labelSmall,
color = if (summary.hasFailures) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
.padding(horizontal = 12.dp, vertical = 2.dp)
.testTag("outbox-summary"),
)
}
notice?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
)
}
error?.let { error?.let {
Text( Text(
@ -204,3 +258,44 @@ fun ChatScreen(
} }
} }
} }
/**
* One message's delivery marker, straight from the core's outbox state.
*
* The row carries an explicit [Delivery.contentDescription] so a screen reader
* announces "Queued, not delivered yet" instead of reading a clock glyph, and a
* [Delivery.testTag] so a UI test can find the state without depending on the
* glyph. `send` shows a small indeterminate spinner while the worker has an
* attempt in flight.
*/
@Composable
private fun DeliveryMarker(d: Delivery) {
val tint = when (d) {
is Delivery.Failed -> MaterialTheme.colorScheme.error
Delivery.Sent -> MaterialTheme.colorScheme.onSurfaceVariant
else -> MaterialTheme.colorScheme.primary
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.padding(horizontal = 4.dp, vertical = 1.dp)
.testTag(d.testTag)
.semantics(mergeDescendants = true) {
contentDescription = d.contentDescription
},
) {
if (d is Delivery.Sending) {
CircularProgressIndicator(
modifier = Modifier.size(10.dp),
strokeWidth = 1.5.dp,
color = tint,
)
Spacer(Modifier.width(4.dp))
}
Text(
d.marker,
style = MaterialTheme.typography.labelSmall,
color = tint,
)
}
}

View file

@ -0,0 +1,176 @@
package com.siriusdevops.onionwire.ui
/**
* Delivery state of one outgoing chat row.
*
* The states are the core's own — `Queued` / `Sending` / `Sent` / `Failed`
* (`src/store.rs::OutboxStatus`), surfaced verbatim over UniFFI as
* `ChatMessage.delivery` (`crates/onionwire-sdk/src/lib.rs::delivery_of`, fed by
* `Node::outbox_status_of_message`). There is no parallel model here and nothing
* is inferred from a timeout: if the state is not in that string it is not
* rendered.
*
* [testTag] and [contentDescription] are the assertable handles: the Composable
* applies exactly these values, and `MessageDeliveryTest` asserts on them, so a
* change to the marker without a change to the announcement fails a test.
* A screen reader must never be left hearing a bare glyph like "clock" — that is
* why every state carries a sentence.
*/
sealed interface Delivery {
/** Stable handle for Compose semantics and tests. */
val testTag: String
/** What a screen reader announces. Always a sentence, never a glyph. */
val contentDescription: String
/** Marker drawn next to the message body. */
val glyph: String
/** Short text drawn after the glyph. Empty for a wordless state. */
val label: String
/** The frame reached the peer's onion during the send call. */
data object Sent : Delivery {
override val testTag: String = "delivery-sent"
override val contentDescription: String = "Delivered"
override val glyph: String = "✓✓"
override val label: String = ""
}
/**
* The peer's onion was unreachable: the message is in the local outbox and
* the retry worker will dial again with backoff. Local-only — not delivered.
*/
data object Queued : Delivery {
override val testTag: String = "delivery-queued"
override val contentDescription: String =
"Queued, not delivered yet: retrying their onion"
override val glyph: String = "◷"
override val label: String = "queued"
}
/** The worker has a delivery attempt in flight right now. */
data object Sending : Delivery {
override val testTag: String = "delivery-sending"
override val contentDescription: String = "Sending"
override val glyph: String = "»"
override val label: String = "sending"
}
/** Terminal: retries are exhausted or the failure cannot be retried. */
data class Failed(val reason: String) : Delivery {
override val testTag: String = "delivery-failed"
override val contentDescription: String = "Failed: $reason"
override val glyph: String = "✗"
override val label: String = "failed: $reason"
}
/** `"◷ queued"`, `"✓✓"`, `"✗ failed: no route"` — the row's marker text. */
val marker: String
get() = if (label.isEmpty()) glyph else "$glyph $label"
}
/** Longest short-form failure reason rendered in a chat row. Mirrors
* `src/tui.rs::FAIL_REASON_BUDGET` so both clients cut the same way. */
const val FAIL_REASON_BUDGET: Int = 24
private val STRIPPED: CharRange = '\u0000'..'\u001f'
private val STRIPPED_C1: CharRange = '\u007f'..'\u009f'
/** C0/C1 controls and bidi/format marks — mirrors `src/sanitize.rs`. */
internal fun isControlOrBidi(c: Char): Boolean =
c in STRIPPED || c in STRIPPED_C1 ||
c in '\u202a'..'\u202e' || c in '\u2066'..'\u2069' ||
c == '\u200e' || c == '\u200f' || c == '\u200b' || c == '\u200c'
/**
* Transport failure text, short form: sanitized, tail of the `a: b: c` chain,
* capped at [budget] cells so one peer's error cannot blow out the row.
* Mirrors `src/tui.rs::short_send_reason`.
*/
fun shortSendReason(why: String, budget: Int = FAIL_REASON_BUDGET): String {
val clean = why.filterNot(::isControlOrBidi)
val tail = clean.split(": ").lastOrNull().orEmpty().trim()
val text = tail.ifEmpty { clean.trim() }
if (text.length <= budget) return text
if (budget <= 1) return "…".take(budget)
return text.take(budget - 1) + "…"
}
/**
* Maps one history row onto a [Delivery], or `null` for anything that is not an
* outgoing message.
*
* [delivery] is `ChatMessage.delivery`: `"sent"`, `"queued"`, `"sending"`,
* `"failed: <reason>"`, or `null` for inbound rows. The SDK already resolves an
* outgoing row with no outbox row to `"sent"` (it was accepted on the first
* attempt), so a *missing* value on an outgoing row means the core did not
* confirm anything — and that is reported as [Delivery.Queued], never as
* delivered. Same rule for a status this build does not recognise: the only
* direction that cannot lie is "not confirmed delivered yet".
*/
fun parseDelivery(direction: String, delivery: String?): Delivery? {
if (direction != "out") return null
return when (val raw = delivery?.trim().orEmpty()) {
"" -> Delivery.Queued
"sent" -> Delivery.Sent
"sending" -> Delivery.Sending
"queued" -> Delivery.Queued
else ->
if (raw.startsWith("failed")) {
val why = raw.substringAfter(':', "").trim().ifEmpty { "unknown" }
Delivery.Failed(shortSendReason(why))
} else {
Delivery.Queued
}
}
}
/**
* Chat-level delivery summary derived from the rendered rows.
*
* Mirrors `src/tui.rs::OutboxSummary`: `Queued` + `Sending` are "still coming",
* `Failed` is terminal and keeps a fail-closed statement on screen.
*/
data class OutboxSummary(
val queued: Int = 0,
val failed: Int = 0,
val firstError: String? = null,
) {
/** Footer note, or `null` when nothing is outstanding. */
val note: String?
get() {
val reason = shortSendReason(firstError ?: "unknown")
return when {
queued == 0 && failed == 0 -> null
failed == 0 -> "$queued queued"
queued == 0 && failed == 1 -> "send failed: $reason"
queued == 0 -> "send failed: $reason ($failed failed)"
else -> "$queued queued, send failed: $reason"
}
}
/** `true` when at least one send has terminated as failed. */
val hasFailures: Boolean get() = failed > 0
}
/** Summarizes the rows currently on screen. */
fun outboxSummary(deliveries: Iterable<Delivery?>): OutboxSummary {
var queued = 0
var failed = 0
var firstError: String? = null
for (d in deliveries) {
when (d) {
null, Delivery.Sent -> Unit
is Delivery.Failed -> {
failed++
if (firstError == null) firstError = d.reason
}
Delivery.Queued, Delivery.Sending -> queued++
}
}
return OutboxSummary(queued = queued, failed = failed, firstError = firstError)
}

View file

@ -0,0 +1,180 @@
package com.siriusdevops.onionwire.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Renders each of the four core outbox states and asserts the semantic the
* Composable applies for it — the same `testTag` / `contentDescription` values
* `ChatScreen`'s delivery row uses, so a marker change without an announcement
* change fails here.
*
* `compose.ui.test` is not on the JVM unit-test classpath (and adding it is
* outside this card's scope), so the assertion target is the state model that
* the Composable renders from, not a laid-out node. Same shape as
* `InviteAddFlowTest`.
*/
class MessageDeliveryTest {
private val glyphs = listOf("✓", "◷", "»", "✗")
private fun out(delivery: String?) = parseDelivery("out", delivery)
@Test
fun every_core_state_is_rendered_with_its_own_handle_and_sentence() {
val sent = requireNotNull(out("sent"))
val queued = requireNotNull(out("queued"))
val sending = requireNotNull(out("sending"))
val failed = requireNotNull(out("failed: connection timed out"))
assertEquals(Delivery.Sent, sent)
assertEquals(Delivery.Queued, queued)
assertEquals(Delivery.Sending, sending)
assertEquals(Delivery.Failed("connection timed out"), failed)
assertEquals("delivery-sent", sent.testTag)
assertEquals("delivery-queued", queued.testTag)
assertEquals("delivery-sending", sending.testTag)
assertEquals("delivery-failed", failed.testTag)
assertEquals("Delivered", sent.contentDescription)
assertEquals("Queued, not delivered yet: retrying their onion", queued.contentDescription)
assertEquals("Sending", sending.contentDescription)
assertEquals("Failed: connection timed out", failed.contentDescription)
// Four states, four distinct handles and four distinct sentences.
val all = listOf(sent, queued, sending, failed)
assertEquals(4, all.map { it.testTag }.toSet().size)
assertEquals(4, all.map { it.contentDescription }.toSet().size)
}
@Test
fun markers_are_visually_distinct_per_state() {
assertEquals("✓✓", Delivery.Sent.marker)
assertEquals("◷ queued", Delivery.Queued.marker)
assertEquals("» sending", Delivery.Sending.marker)
assertEquals("✗ failed: no route", Delivery.Failed("no route").marker)
val all = listOf(
Delivery.Sent.marker,
Delivery.Queued.marker,
Delivery.Sending.marker,
Delivery.Failed("no route").marker,
)
assertEquals(4, all.toSet().size)
}
@Test
fun every_state_announces_words_not_a_bare_glyph() {
val all = listOf(
Delivery.Sent,
Delivery.Queued,
Delivery.Sending,
Delivery.Failed("no route"),
)
for (d in all) {
for (glyph in glyphs) {
assertFalse(
"${d.testTag} announces a glyph: ${d.contentDescription}",
d.contentDescription.contains(glyph),
)
}
assertTrue(
"${d.testTag} must announce words, not an icon name: ${d.contentDescription}",
d.contentDescription.length >= 7 && d.contentDescription.any { it.isLetter() },
)
}
}
@Test
fun failed_reason_is_sanitized_tailed_and_capped_like_the_tui() {
// C0 controls and bidi marks are stripped.
assertEquals("badsignature", shortSendReason("bad\u0007\u202esignature"))
// Tail of the `a: b: c` chain.
assertEquals(
"connection timed out",
shortSendReason("dial 7f4k.onion: onion: connection timed out"),
)
// Capped at the row budget, with the ellipsis inside it.
val long = "x".repeat(80)
val cut = shortSendReason(long)
assertEquals(FAIL_REASON_BUDGET, cut.length)
assertTrue(cut.endsWith("…"))
assertEquals(long, shortSendReason(long, budget = 80))
}
@Test
fun an_unrecognised_status_is_queued_never_delivered() {
// A status this build does not know must not read as delivered.
assertEquals(Delivery.Queued, out("spooling"))
assertEquals(Delivery.Queued, out("SENDING"))
}
@Test
fun a_missing_delivery_on_an_outgoing_row_is_not_called_delivered() {
// The SDK reports "sent" explicitly for an outgoing row with no outbox
// row, so a missing value means nothing was confirmed.
assertEquals(Delivery.Queued, out(null))
assertEquals(Delivery.Queued, out(" "))
}
@Test
fun the_core_reporting_sent_is_the_only_way_to_render_delivered() {
assertEquals(Delivery.Sent, out("sent"))
assertEquals(Delivery.Sent, out(" sent "))
}
@Test
fun inbound_rows_carry_no_delivery_state() {
assertNull(parseDelivery("in", null))
assertNull(parseDelivery("in", "sent"))
}
@Test
fun blank_failure_reason_still_says_failed() {
val d = out("failed:") as Delivery.Failed
assertEquals("unknown", d.reason)
assertEquals("Failed: unknown", d.contentDescription)
}
@Test
fun footer_reports_pending_sends_and_keeps_a_failure_statement() {
// Nothing outstanding: no note at all.
assertNull(outboxSummary(listOf(Delivery.Sent, null)).note)
// Anything still coming is counted, queued and sending alike.
assertEquals(
"2 queued",
outboxSummary(listOf(Delivery.Queued, Delivery.Sending, Delivery.Sent)).note,
)
// A terminal failure is stated, not hidden behind the queue count.
val withFailure = outboxSummary(listOf(Delivery.Queued, Delivery.Failed("no route")))
assertEquals(1, withFailure.queued)
assertEquals(1, withFailure.failed)
assertTrue(withFailure.hasFailures)
assertEquals("1 queued, send failed: no route", withFailure.note)
// No queue, one failure.
assertEquals(
"send failed: no route",
outboxSummary(listOf(Delivery.Failed("no route"))).note,
)
// No queue, several failures: first reason plus how many.
assertEquals(
"send failed: no route (3 failed)",
outboxSummary(
listOf(
Delivery.Failed("no route"),
Delivery.Failed("timeout"),
Delivery.Failed("bad identity"),
),
).note,
)
// Nothing pending and nothing failed: silent.
assertFalse(outboxSummary(listOf(Delivery.Sent)).hasFailures)
}
}

View file

@ -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"

View file

@ -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.

View file

@ -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
@ -27,7 +30,7 @@ use std::sync::{Arc, Mutex, OnceLock};
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::qr; use onionwire::outbox::OutboxStatus;use onionwire::qr;
uniffi::setup_scaffolding!(); uniffi::setup_scaffolding!();
@ -98,11 +101,34 @@ 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 {
/// "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>,
} }
#[derive(Debug, Clone, uniffi::Record)] #[derive(Debug, Clone, uniffi::Record)]
@ -332,34 +358,44 @@ 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(ChatMessage { body: String::from_utf8_lossy(&m.plaintext).into_owned(),
.into_iter() delivery: delivery_of(&m.dir, status),
.map(|m| ChatMessage {
direction: m.dir, direction: m.dir,
body: String::from_utf8_lossy(&m.plaintext).into_owned(), });
}) }
.collect()) Ok(out)
} }
/// Delete every message body. Identity and friends survive. /// Delete every message body. Identity and friends survive.
@ -415,6 +451,30 @@ 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,
}
}
/// 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)] #[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
@ -422,6 +482,7 @@ mod tests {
//! node is exactly the state `shutdown()` leaves behind. //! node is exactly the state `shutdown()` leaves behind.
use super::*; use super::*;
use onionwire::outbox::OutboxStatus;
fn stopped_wire() -> Wire { fn stopped_wire() -> Wire {
Wire { Wire {
@ -482,4 +543,42 @@ 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")
);
}
} }

View file

@ -251,7 +251,8 @@ impl Node {
/// `sending`; `Outbox::reset_stale` requeues those on the next unlock, the /// `sending`; `Outbox::reset_stale` requeues those on the next unlock, the
/// same recovery the parent uses for a process that died mid-attempt. /// same recovery the parent uses for a process that died mid-attempt.
async fn drain(&self, budget: Duration) -> Result<FlushOutcome, String> { 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(Ok(rows)) => Some(rows),
Ok(Err(e)) => return Err(e), Ok(Err(e)) => return Err(e),
Err(_) => { Err(_) => {
@ -733,7 +734,10 @@ impl Node {
/// Pending and failed outbox rows for a friend, for UI surfacing. /// Pending and failed outbox rows for a friend, for UI surfacing.
/// Delivered rows are dropped, so a message absent here was sent. /// 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) self.outbox.pending(friend_pk)
} }
@ -1055,7 +1059,8 @@ fn checkpoint_wal(home: &Path) -> Result<(), String> {
if !db.exists() { if !db.exists() {
return Ok(()); 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 let (busy, log, checkpointed): (i64, i64, i64) = conn
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| { .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
Ok((row.get(0)?, row.get(1)?, row.get(2)?)) Ok((row.get(0)?, row.get(1)?, row.get(2)?))
@ -1145,7 +1150,10 @@ mod lifecycle_tests {
conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);") conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);")
.expect("create table"); .expect("create table");
for _ in 0..64 { for _ in 0..64 {
conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params![vec![7u8; 512]]) conn.execute(
"INSERT INTO t (v) VALUES (?1)",
rusqlite::params![vec![7u8; 512]],
)
.expect("insert"); .expect("insert");
} }

View file

@ -99,8 +99,7 @@ impl Deliverer for ArtiDeliverer {
.connect((onion, HS_PORT)) .connect((onion, HS_PORT))
.await .await
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?; .map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
let mut sess = let mut sess = session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey)
session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey)
.await .await
.map_err(|e| e.into_message())?; .map_err(|e| e.into_message())?;
let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?; let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?;
@ -145,7 +144,11 @@ impl Outbox {
/// protocol error or a bad local state, never retried. /// protocol error or a bad local state, never retried.
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> { pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
let (onion, prekey) = self.target(friend_pk)?; 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(()) => { Ok(()) => {
self.store()?.append_message(friend_pk, "out", plaintext)?; self.store()?.append_message(friend_pk, "out", plaintext)?;
Ok(OutboxStatus::Sent) Ok(OutboxStatus::Sent)
@ -155,14 +158,7 @@ impl Outbox {
let now = unix_now(); let now = unix_now();
let store = self.store()?; let store = self.store()?;
let message_id = store.append_message_id(friend_pk, "out", plaintext)?; let message_id = store.append_message_id(friend_pk, "out", plaintext)?;
store.enqueue_outbox( store.enqueue_outbox(friend_pk, message_id, 1, now + backoff_secs(0), &e, now)?;
friend_pk,
message_id,
1,
now + backoff_secs(0),
&e,
now,
)?;
Ok(OutboxStatus::Queued) Ok(OutboxStatus::Queued)
} }
} }

View file

@ -802,17 +802,13 @@ impl Store {
} }
pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> { 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 /// Same as `append_message`, returning the row id so an outbox row can
/// point at the body instead of storing a second copy. /// point at the body instead of storing a second copy.
pub fn append_message_id( pub fn append_message_id(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<i64> {
&self,
friend_pk: &[u8],
dir: &str,
plaintext: &[u8],
) -> Result<i64> {
if dir != "in" && dir != "out" { if dir != "in" && dir != "out" {
return Err(Error("dir must be in or out".into())); 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 aad = message_aad(friend_id, &dir, id);
let plaintext = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad) let plaintext = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
.map_err(|_| Error("message decrypt failed".into()))?; .map_err(|_| Error("message decrypt failed".into()))?;
out.push(Message { out.push(Message { id, dir, plaintext });
id,
dir,
plaintext,
});
} }
Ok(out) Ok(out)
} }
@ -1115,7 +1107,10 @@ fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Friend> {
fn gen_prekey() -> (Zeroizing<Vec<u8>>, Vec<u8>) { fn gen_prekey() -> (Zeroizing<Vec<u8>>, Vec<u8>) {
let sk = StaticSecret::random_from_rng(OsRng); let sk = StaticSecret::random_from_rng(OsRng);
let pk = X25519Public::from(&sk); 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 /// Per-install KDF salt for the whole-database key. Not secret (a salt never
@ -1638,21 +1633,15 @@ mod at_rest {
params![salt.as_slice(), wrapped], params![salt.as_slice(), wrapped],
) )
.unwrap(); .unwrap();
for (dir, body) in [ for (dir, body) in [("in", "legacy-body-xyz"), ("out", "legacy-reply-xyz")] {
("in", "legacy-body-xyz"),
("out", "legacy-reply-xyz"),
] {
conn.execute( conn.execute(
"INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (1, ?1, x'', 7)", "INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (1, ?1, x'', 7)",
params![dir], params![dir],
) )
.unwrap(); .unwrap();
let id = conn.last_insert_rowid(); let id = conn.last_insert_rowid();
let blob = crate::backup::aead_encrypt( let blob =
&data_key, crate::backup::aead_encrypt(&data_key, body.as_bytes(), &message_aad(1, dir, id))
body.as_bytes(),
&message_aad(1, dir, id),
)
.unwrap(); .unwrap();
conn.execute( conn.execute(
"UPDATE messages SET plaintext = ?1 WHERE id = ?2", "UPDATE messages SET plaintext = ?1 WHERE id = ?2",
@ -1681,7 +1670,8 @@ mod at_rest {
"fixture must be a plaintext sqlite file" "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!( assert_eq!(
store.self_identity().unwrap().identity_sk[..], store.self_identity().unwrap().identity_sk[..],
LEGACY_IDENTITY_SK[..] LEGACY_IDENTITY_SK[..]
@ -1703,7 +1693,10 @@ mod at_rest {
); );
for (needle, what) in [ for (needle, what) in [
(b"legacy-body-xyz".to_vec(), "message body"), (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"), (LEGACY_IDENTITY_SK.to_vec(), "identity secret"),
(b"legacy-friend.onion".to_vec(), "locator"), (b"legacy-friend.onion".to_vec(), "locator"),
] { ] {

View file

@ -276,8 +276,10 @@ pub fn chat_with_delivery(
// second), and `pending` is ordered by row id, so a hypothetical duplicate // second), and `pending` is ordered by row id, so a hypothetical duplicate
// resolves to the newest — the same rule the store's own // resolves to the newest — the same rule the store's own
// `outbox_status_of_message` uses. // `outbox_status_of_message` uses.
let by_id: HashMap<i64, &OutboxEntry> = let by_id: HashMap<i64, &OutboxEntry> = pending
pending.iter().map(|entry| (entry.message_id, entry)).collect(); .iter()
.map(|entry| (entry.message_id, entry))
.collect();
let mut tags: Vec<Option<String>> = vec![None; msgs.len()]; let mut tags: Vec<Option<String>> = vec![None; msgs.len()];
for (i, msg) in msgs.iter().enumerate() { for (i, msg) in msgs.iter().enumerate() {
if msg.dir != "out" { if msg.dir != "out" {

View file

@ -1,6 +1,6 @@
//! M6: typed-frame dispatcher — classify before append_message. //! M6: typed-frame dispatcher — classify before append_message.
use onionwire::dispatch::{classify, Kind}; use onionwire::dispatch::{Kind, classify};
#[test] #[test]
fn chat_is_chat() { fn chat_is_chat() {

View file

@ -5,11 +5,11 @@
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use onionwire::Store;
use onionwire::outbox::{ use onionwire::outbox::{
BACKOFF_CAP_SECS, BACKOFF_START_SECS, BoxFut, Deliverer, Outbox, OutboxStatus, backoff_secs, BACKOFF_CAP_SECS, BACKOFF_START_SECS, BoxFut, Deliverer, Outbox, OutboxStatus, backoff_secs,
is_permanent_send_error, is_permanent_send_error,
}; };
use onionwire::Store;
const PASS: &str = "outbox-pass"; const PASS: &str = "outbox-pass";
@ -96,9 +96,7 @@ fn backoff_schedule_doubles_from_30s_and_caps_at_30m() {
#[test] #[test]
fn transport_errors_are_retryable_protocol_errors_are_not() { fn transport_errors_are_retryable_protocol_errors_are_not() {
assert!(!is_permanent_send_error( assert!(!is_permanent_send_error("connect abc.onion:80: timed out"));
"connect abc.onion:80: timed out"
));
assert!(!is_permanent_send_error("connect abc.onion:80: refused")); assert!(!is_permanent_send_error("connect abc.onion:80: refused"));
assert!(is_permanent_send_error("fingerprint mismatch")); assert!(is_permanent_send_error("fingerprint mismatch"));
assert!(is_permanent_send_error("frame too large")); 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 ob = outbox(Arc::clone(&store), dead, 8);
let status = ob.send(&pk(1), b"hello dead peer").await.unwrap(); 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()); assert!(!status.is_terminal());
let pending = ob.pending(&pk(1)).unwrap(); 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].status, OutboxStatus::Queued);
assert_eq!(pending[0].attempts, 1, "the immediate attempt counted"); assert_eq!(pending[0].attempts, 1, "the immediate attempt counted");
assert!( 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" "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" "protocol errors are never queued"
); );
assert!( 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" "a failed protocol send is not written to history"
); );
} }

View file

@ -2,8 +2,8 @@
use std::sync::{Mutex, MutexGuard}; use std::sync::{Mutex, MutexGuard};
use onionwire::qr;
use onionwire::Store; use onionwire::Store;
use onionwire::qr;
static ENV_LOCK: Mutex<()> = Mutex::new(()); static ENV_LOCK: Mutex<()> = Mutex::new(());

View file

@ -1,7 +1,7 @@
//! Composer Enter must send chat to the selected friend, not only slash commands. //! Composer Enter must send chat to the selected friend, not only slash commands.
use onionwire::tui::{ 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::sync::mpsc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};

View file

@ -46,7 +46,11 @@ fn spawn_echo(
async fn launch_echo( async fn launch_echo(
client: &Client, client: &Client,
nickname: &str, nickname: &str,
) -> (Arc<RunningOnionService>, tokio::task::JoinHandle<()>, String) { ) -> (
Arc<RunningOnionService>,
tokio::task::JoinHandle<()>,
String,
) {
let launched = client let launched = client
.launch_onion_service(hs::hs_config(nickname).expect("hs_config")) .launch_onion_service(hs::hs_config(nickname).expect("hs_config"))
.expect("launch_onion_service") .expect("launch_onion_service")
@ -66,7 +70,10 @@ async fn echo_ping(client: &Client, onion: &str) -> Result<(), String> {
.write_all(PING) .write_all(PING)
.await .await
.map_err(|e| format!("write ping: {e}"))?; .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()]; let mut buf = vec![0u8; PING.len()];
stream stream
.read_exact(&mut buf) .read_exact(&mut buf)

View file

@ -12,8 +12,8 @@
//! checkpoint, and the SDK's typed error after shutdown — runs in the normal //! 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`). //! suite (`tests/hs.rs`, `src/node.rs`, `crates/onionwire-sdk/src/lib.rs`).
use onionwire::node::{FlushOutcome, Node};
use onionwire::hs::TorState; use onionwire::hs::TorState;
use onionwire::node::{FlushOutcome, Node};
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[ignore = "needs live Tor network"] #[ignore = "needs live Tor network"]

View file

@ -11,19 +11,19 @@
//! `chars().count()` width checks here match `tests/tui_chrome.rs` on purpose. //! `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`). //! They are the known-wrong metric (see `chars_count_is_not_terminal_cells`).
use onionwire::FriendProfile;
use onionwire::qr; use onionwire::qr;
use onionwire::tui::{ use onionwire::tui::{
backup_screen_text, banner_for_width, compact_banner, draw_share, fingerprint_mismatch_banner, ProfileEditor, WipeKind, backup_screen_text, banner_for_width, compact_banner, draw_share,
help_overlay_text, main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text, fingerprint_mismatch_banner, help_overlay_text, main_footer_hints, onion_glyph,
rotate_screen_text, status_footer, who_overlay_text, wipe_screen_text, wordmark_banner, quit_screen_text, restore_screen_text, rotate_screen_text, status_footer, who_overlay_text,
ProfileEditor, WipeKind, wipe_screen_text, wordmark_banner,
}; };
use onionwire::FriendProfile; use ratatui::Frame;
use ratatui::Terminal;
use ratatui::backend::TestBackend; use ratatui::backend::TestBackend;
use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}; 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 SIZES: [(u16, u16); 3] = [(80, 24), (120, 40), (200, 60)];
const FP: &str = "abcdef0123456789deadbeefcafebabe"; const FP: &str = "abcdef0123456789deadbeefcafebabe";

View file

@ -426,7 +426,14 @@ fn pending_row(
} }
fn queued_row(message_id: i64, body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry { 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 { 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"), in_msg(5, "epsilon"),
]; ];
let pending = vec![ 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), queued_row(2, "beta", 1, 30, now),
sending_row(3, "gamma", now), sending_row(3, "gamma", now),
]; ];

View file

@ -13,7 +13,6 @@ use tokio::net::TcpListener;
/// `ONIONWIRE_WALLET_NO_SPEND` is process-wide; tests that touch env serialize. /// `ONIONWIRE_WALLET_NO_SPEND` is process-wide; tests that touch env serialize.
static ENV_LOCK: Mutex<()> = Mutex::new(()); static ENV_LOCK: Mutex<()> = Mutex::new(());
fn row(txid: &str, amount: &str, address: &str) -> TransferRow { fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
TransferRow { TransferRow {
txid: txid.into(), txid: txid.into(),
@ -321,10 +320,7 @@ async fn no_spend_mode_refuses_transfer_with_no_rpc_request() {
.await .await
.unwrap_err() .unwrap_err()
.to_string(); .to_string();
assert!( assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
err.to_ascii_lowercase().contains("view-only"),
"got {err}"
);
tokio::time::sleep(std::time::Duration::from_millis(200)).await; tokio::time::sleep(std::time::Duration::from_millis(200)).await;
let seen = log.lock().expect("log").clone(); let seen = log.lock().expect("log").clone();
assert!(seen.is_empty(), "no RPC request may be made: {seen:?}"); assert!(seen.is_empty(), "no RPC request may be made: {seen:?}");

View file

@ -1,8 +1,8 @@
//! M5: wipe messages (keep identity + friends); wipe-all is a new person. //! M5: wipe messages (keep identity + friends); wipe-all is a new person.
use onionwire::tui::{ use onionwire::tui::{
parse_slash, quit_screen_text, wipe_screen_text, QuitDecision, QuitPrompt, WipeDecision, QuitDecision, QuitPrompt, WipeDecision, WipeKind, WipePrompt, parse_slash, quit_screen_text,
WipeKind, WipePrompt, wipe_screen_text,
}; };
use onionwire::{PaymentWrite, Store}; use onionwire::{PaymentWrite, Store};

View file

@ -4,11 +4,11 @@
//! core dumps, OS `String` interning, `src/file.rs` + TUI buffers, and the //! core dumps, OS `String` interning, `src/file.rs` + TUI buffers, and the
//! Noise handshake/transport state that lives inside `snow`. //! Noise handshake/transport state that lives inside `snow`.
use onionwire::Store;
use onionwire::backup::BackupKeys; use onionwire::backup::BackupKeys;
use onionwire::profile; use onionwire::profile;
use onionwire::session::Keys; use onionwire::session::Keys;
use onionwire::wallet::Wallet; use onionwire::wallet::Wallet;
use onionwire::Store;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
/// Type-level: the wrapper is applied to the type, not just mentioned in a /// Type-level: the wrapper is applied to the type, not just mentioned in a