Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
7665da997e Merge pull request 'deps: Arti set tor-* 0.46 -> 0.49 (Arti 2.9.0)' (#216) from onionwire/t_30d0f0c6-onionwire-212-arti-upstream-tor-rtcompat into main
All checks were successful
android-ci / android (push) Successful in 19m44s
ci / test (push) Successful in 29m45s
ci / sdk (push) Successful in 2m2s
Reviewed-on: #216
2026-12-03 05:33:01 +00:00
agent
90d982b369
deps: bump the Arti set tor-* 0.46 -> 0.49 (Arti 2.9.0)
All checks were successful
ci / test (pull_request) Successful in 31m8s
ci / sdk (pull_request) Successful in 1m34s
android-ci / android (pull_request) Successful in 18m10s
Arti publishes these in lockstep. Bumped together:
- arti-client 0.46 -> 0.49 (root + crates/onionwire-sdk, both lockfiles)
- tor-cell, tor-hsservice, tor-rtcompat 0.46 -> 0.49
- safelog 0.9 -> 0.10 (same repo; 0.49's HsId implements safelog 0.10's
  DisplayRedacted, so the old direct pin broke display_redacted)

Arti 0.49 (Arti 2.9.0, 2026-12-01) carries a medium-severity security fix
(TROVE-2026-078, custom build flags) and two low-severity fixes.

MSRV unchanged: Arti 0.49 needs rustc 1.92, the repo floor stays 1.98
(cuprate-daemon / tapes). Only docs/comments moved; src/hs.rs workarounds
rechecked against 0.49: tor-hsservice OVERALL_UPLOAD_TIMEOUT is still 5 min
(PUBLISH_WAIT 360s stands) and tor-config's Listen is still IP-only.

Verified: cargo test --locked (173 lib + all integration suites), clippy
--locked --all-targets -D warnings, SDK cargo test/clippy, live ignored
tor_hs + two_node tests, and scripts/build-android-local.sh (APK + AAR).
2026-12-02 02:37:17 -05:00
488eb94e28 Merge pull request 'wallet: derive readiness from the wallet's get_height, not a nonexistent get_info' (#204) from wt/t_e4e55a04 into main
All checks were successful
android-ci / android (push) Successful in 11m31s
ci / test (push) Successful in 29m44s
ci / sdk (push) Successful in 2m6s
Reviewed-on: #204
2026-10-31 05:49:06 +00:00
717a33b4c2 Merge branch 'main' into wt/t_e4e55a04
Some checks failed
ci / test (pull_request) Has been cancelled
ci / sdk (pull_request) Has been cancelled
2026-10-31 05:48:56 +00:00
83e9527a5f Merge pull request 'wallet_child: spawn errors must name argv[0] and refuse a bin that is not an executable file' (#203) from wt/t_af5bbc1a into main
All checks were successful
ci / test (push) Successful in 7s
ci / sdk (push) Successful in 7s
android-ci / android (push) Successful in 11m37s
Reviewed-on: #203
2026-10-31 05:47:27 +00:00
3092b9d63e Merge branch 'main' into wt/t_af5bbc1a
Some checks failed
ci / test (pull_request) Has been cancelled
ci / sdk (pull_request) Has been cancelled
android-ci / android (pull_request) Has been cancelled
2026-10-31 05:47:21 +00:00
rust-dev
3aafaefae8
wallet: derive readiness from the wallet's get_height, not a nonexistent get_info
Some checks failed
ci / test (pull_request) Has been cancelled
ci / sdk (pull_request) Has been cancelled
monero-wallet-rpc does not implement get_info (-32601 Method not found); it
exists on the daemon only. Every wallet therefore sat in syncing forever:
no balance, spends refused, receipts never verified.

Readiness is now the pair:
- the wallet RPC's own get_height (its scanned height), and
- the chain tip from the existing daemon client (GET /get_height).

ready = height > 0 && (tip == 0 || height + 2 >= tip). The 2-block slack is
deliberate: the tip moves every ~2 min and the two reads are not a snapshot.
A daemon that does not answer, a missing height and -13 No wallet file are
all not-ready, never an error banner.

ChildConfig::daemon_probe_addr resolves a tip source for clearnet remotes
(the wallet child already dials them); a .onion daemon is not dialled without
the SOCKS child and stays fail-closed. docs/WALLET.md now documents the real
rule. Tests cover -32601 get_info, equal tip, slack boundary, dead daemon and
the no-wallet-file answer.
2026-10-31 01:35:15 -04:00
dddf74f274 Merge pull request 'android wallet: self-heal the stored wallet_rpc_bin, gate Start/Create, one info banner' (#202) from wt/t_d63f9279 into main
All checks were successful
android-ci / android (push) Successful in 11m30s
Reviewed-on: #202
2026-10-31 05:33:17 +00:00
a0b704cd09 Merge branch 'main' into wt/t_d63f9279
Some checks failed
android-ci / android (pull_request) Has been cancelled
2026-10-31 05:33:07 +00:00
agent
a375ef9d1e
wallet_child: name argv[0] in spawn errors and pre-flight the RPC bin
All checks were successful
ci / test (pull_request) Successful in 29m37s
ci / sdk (pull_request) Successful in 10s
The Android report was `spawn monero-wallet-rpc: No such file or directory
(os error 2)` — the label, not the argv[0] that failed, so a bare name and
an absolute jniLibs path read identically.

- spawn() now prints the label and argv[0]: `spawn monero-wallet-rpc
  (/data/app/.../libmonerowalletrpc.so): ...`, errno verbatim.
- check_wallet_rpc_bin() pre-flights the resolved bin before anything is
  spawned: not found / not a file / not executable, with the configured
  path in the message. No PATH search, no fallback.
- A bare wallet_rpc_bin is refused where a child has no PATH to resolve it
  (cfg(target_os = "android")), in ChildConfig::validate() and in the
  start-path pre-flight. Desktop keeps the bare-name default.
- Tests for each refusal and for the argv[0] error; the node test that
  asserted the old `spawn` copy now asserts the path.
2026-10-31 01:23:18 -04:00
agent
3cd70ca9b5
android wallet: self-heal the stored wallet_rpc_bin, gate Start/Create, one info banner
All checks were successful
android-ci / android (pull_request) Successful in 11m51s
Device report (v0.7.0): Start died with `spawn monero-wallet-rpc: No such
file or directory`, and Create answered with the desktop TUI's `wallet not
configured — open F7 …`. Both were reachable states on the phone, so the
screen offered two dead ends.

- WireViewModel: `healStoredWalletBin()` re-points a stored wallet_rpc_bin
  that this device cannot execute at the resolved nativeLibraryDir path,
  preserving kind/mode/host/port/datadir/filename, skipping receive-only,
  and never overwriting a stored path that is a real executable file. It
  runs on wallet-screen open and again at the top of `startWalletChild()`,
  which then re-reads the stored record and refuses to spawn when the path
  still cannot run — writing the named path instead of ENOENT.
- Gate: `startGateReason()` = existing `startBlockedReason()` plus
  `storedWalletBinBlockedReason()`, which names the stored path, the
  resolved path, or the absent-binary message (unchanged strings).
  `shouldStartAfterSelectingChain()` now takes that reason, so a mode tap
  stores the source but cannot launch what Start would refuse.
- Create/Import: `walletSetupBlockedReason()` disables both controls with a
  sentence until the child answers; the TUI's unconfigured copy is mapped by
  `walletFailureText` to a phone sentence, so `open F7` and
  ONIONWIRE_WALLET_RPC never render.
- Banner: `walletFailureBanner()` paints `WALLET_NOT_OPEN_TEXT` as one info
  banner (or nothing when the No-wallet-open hint is already up), never as
  the red `Wallet error`; the sticky error is cleared when a wallet opens.
  Real failures (connect refusals, exited) still paint red.

Tests: 241/241 `:app:testDebugUnitTest`, including the four required cases.
Not verified on a device — no adb/device on this host.
2026-10-31 01:10:34 -04:00
b5f3829c23 Merge pull request 'fuzz: pass the 4th bootstrap arg (hybrid ML-KEM peer key)' (#201) from wt/t_a866e490 into main
Reviewed-on: #201
2026-10-31 03:29:04 +00:00
7c1da42e7b Merge branch 'main' into wt/t_a866e490 2026-10-31 03:28:55 +00:00
agent
9d93fb5cfa
fuzz: pass the 4th bootstrap arg (hybrid ML-KEM peer key)
RatchetState::bootstrap gained remote_kem_pub in b22abd7 (PR #185), so the
fuzz target has not compiled since 2026-10-20 and the nightly fuzz job has
been red for ten days.

Pass None for the classical shape and a real ML-KEM-768 encapsulation key
(crate::kem::PK_LEN bytes, built once from a fixed 64-byte seed) for the
hybrid shape, so both bootstrap paths are fuzzed. The invariants are
unchanged: arbitrary bytes never panic, a parsed state re-serializes, and a
rejected frame rolls back to the exact pre-decrypt state.
2026-10-30 23:24:58 -04:00
fb45143695 Merge pull request 'docs: point the docs at v0.7.0, and name the Android UI overhaul' (#200) from docs/release-v0.7.0 into main 2026-10-31 03:03:02 +00:00
sirius
6216475b13
docs: point the docs at v0.7.0, and name the Android UI overhaul
The README and VERIFY.md pinned downloads to v0.5.0 while v0.6.0 had already
shipped, so every documented asset URL was two versions stale. A release tags
the default-branch tip, so the fix has to land before the cut, not after.

Also one sentence on the Android section: the APK's UI is now a design-token
system with a three-tab shell, which android/README.md documents in detail.
2026-10-30 23:04:43 -04:00
20d2d00e4d Merge pull request 'ui: wallet hero card, node card and the P4/P5 verification sweep' (#199) from ui/refactor-wallet-node into main
Some checks failed
android-ci / android (push) Has been cancelled
Reviewed-on: #199
2026-10-29 06:19:57 +00:00
76f6661171 Merge branch 'main' into ui/refactor-wallet-node
All checks were successful
android-ci / android (pull_request) Successful in 11m4s
2026-10-29 06:19:45 +00:00
890620763f Merge pull request 'ui: design system, app shell and messenger refactor (plan P1-P3)' (#198) from ui/refactor-shell-messenger into main
All checks were successful
android-ci / android (push) Successful in 11m19s
Reviewed-on: #198
2026-10-29 05:13:59 +00:00
agent
9b3a0ad177
ui: drop two imports the wallet screen no longer uses
All checks were successful
android-ci / android (pull_request) Successful in 11m57s
2026-10-29 01:03:51 -04:00
agent
ef149ac496
ui: one door to the saved-wallet catalogue
All checks were successful
android-ci / android (pull_request) Successful in 15s
The wallet tab was carrying "Saved wallets" twice: once as a top-bar action
(the alpha screen's "Wallets" text link, which I kept when I moved the screen
onto OwTopBar) and once in the hero card's header, where the plan puts it. Two
controls that do the same thing on one page is how a screen starts to look
unfinished.

The hero header keeps it; the top bar is a title and nothing else.
2026-10-29 01:02:59 -04:00
agent
0d0b0b975d
ui: saved-wallets screen and profile copy on the shared components (plan P4.1)
All checks were successful
android-ci / android (pull_request) Successful in 14m2s
The catalogue screen was still the alpha build: a TopAppBar with a text "Back"
and a text "Refresh", eight hand-rolled Cards on Material's surfaceVariant,
outlined twins for the two secret actions, and every failure — including "no
wallet is open", which is a state the app is in, not a failure — printed as a
raw red Text. It now uses the shared components: a chevron top bar, OwCard rows
with an "In use" pill, and OwButton tiers.

Copy, verbatim from the plan:

  "No wallet is open in the wallet child yet. Open a saved wallet on the Saved
   wallets screen, or create or import one here."
      -> "Select a saved wallet or create a new one to view your balance and
         transact."

  "No wallet is open in the wallet child yet. Open one from the list below — a
   wallet that needs a passphrase asks for it here — and the balance, address
   and backups work again."
      -> "Open or create a wallet to enable balance, address, and backup
         controls."

WALLET_NOT_OPEN_TEXT is now rendered as an info banner with its own title, not
as an error; ErrorText picks the variant from the text, so the same string
cannot read as a crash on one screen and a state on the other. The "no wallet
open" hint, the passphrase prompt's blocked reasons and its "wallet is not
running" line, and the catalogue/keys failures are banners too.

The two remaining user-facing mentions of the daemon process are gone: the
passphrase card says "the wallet is pointed at <file>" and the secrets block
reason says "the wallet is not running". ProfileScreen's empty-address notice
loses its copy of the same phrase ("then comes from the running wallet"), and
its test now asserts the consequence instead of the internal name.

No behaviour change: every predicate (walletSecretsEnabled,
walletPassphraseSubmitEnabled, walletChildReadable, walletFailureText,
displayLastError) is the same function with the same branches; only strings and
layout moved. The four WalletManagerTest assertions that pinned the old strings
are updated here, in the same commit, as the card requires.
2026-10-29 01:01:50 -04:00
agent
1d7cbd8503
ui: hero wallet card and node card, and the status copy behind them (plan P4)
The wallet tab was nine equal boxes: a balance card, a daemon card, and then
four outlined twins (Invoice/Tip, Create/Import) pushed below the fold under a
wall of grey helper text. This rebuilds it as two cards.

Hero card. While no wallet file is open the card says "No Wallet Active" with
the plan's subtitle and puts Create Wallet (primary) / Import Wallet
(secondary) first, with Saved wallets in the card header. Once a wallet is
open the balance is the headline at 28sp bold with a sync-state pill, then the
gated receive address and its QR, then Receive / Invoice and Send / Tip, and a
destructive Lock Wallet. Creating and importing a further wallet stay reachable
in both states, and so does invoicing in the no-wallet state: the core resolves
a payee address from the profile, so hiding the action there would drop a path
that works ("no receive address - set profile xmr or ONIONWIRE_WALLET_RPC" is
the both-missing case). A tip really does need the wallet, so it appears only
when one is open.

Node card. The raw "connecting . in-process mainnet pruned . node starting .
sync 485253/3794383" line is replaced by a status sentence, a percentage, a 6dp
progress track and "Block 485,253 of 3,794,383" with the free disk on the
right; the full line is still the header's contentDescription, so a screen
reader loses nothing. The three stacked mode buttons become one segmented
control, Remote vs On-Device is a second one, and the lifecycle is a single
context-aware control (Start Node and Wallet, or Stop Node while it runs)
instead of a permanently disabled twin. Every raw paragraph (no binary, no
wallet open, start blocked, core error) is now an AlertBanner.

Fail-closed rules are unchanged and now tested: target_height == 0 prints no
percentage (it is "no target reported", never "caught up", which is what
Cuprate reports at the tip), a height past the target clamps at 100.0%, and an
unrecognised state is never green. The wallet off / err sentinels still come
back from the core untouched; only their display changed, to "No Wallet Loaded"
and "Balance unavailable".

Deliberate, and named in the handoff: WalletScreen drops its onBack parameter
because Wallet is a top-level tab now (MainActivity updated; Chats and Settings
already have no back affordance), and OwSegmentedControl gains an optional
testTags list - additive, defaulting to empty, so no existing call site
changes.
2026-10-29 01:01:39 -04:00
apk-dev
dc45d9cb81
ui: route the last raw buttons through OwButton, with a content slot
All checks were successful
android-ci / android (pull_request) Successful in 14m48s
Chat's send, Profile's save, and both Rotate actions were still material
Buttons — the 50%-rounded pill the design pass exists to remove. They now
take the design-system shape and height.

OwButton gains an optional RowScope content slot so a caller that needs a
spinner beside its label (chat send while a message is pending) keeps that
behaviour without dropping back to a raw Button. The slot is additive: the
existing text/leading-icon path is unchanged for every other caller.

Rotate's confirm is the Destructive tier — it destroys the current onion —
and the post-rotation action is labelled "Share the new invite" instead of
"Back — share the new invite": the top bar already owns the chevron back.
2026-10-29 00:44:22 -04:00
apk-dev
5a4701992e
ui: mute the empty-state shield and set its heading to the plan's 18sp
All checks were successful
android-ci / android (pull_request) Successful in 14m56s
The plan asks for a *muted* mint/grey icon inside the subtle surface circle and
an 18px/600 heading. The first pass drew the shield in full accent at 16sp
SemiBold, which made the empty state read as a warning and competed with the
primary CTA under it. The accent now stays on the button only.
2026-10-29 00:22:16 -04:00
apk-dev
7d86fd6a03
ui: drop the stale key-type phrase and pin the DrawableRes param target
All checks were successful
android-ci / android (pull_request) Successful in 14m54s
Two nits the plan's own greps would have flagged:

- `ChatScreen`'s `peer` KDoc still spelled out the key type. It is an
  internal comment, but the acceptance grep for the removed identity copy
  (`ed25519 pubkey`) should come back empty across `ui/`, not empty-except-
  a-comment.
- `OwTab`'s `@DrawableRes` is now `@param:`-targeted, which silences Kotlin's
  KT-73255 warning about the annotation moving to the backing field.
2026-10-29 00:15:47 -04:00
agent
a7b7792b3f
ui: About rows, and drop the removed copy from the roster's own KDoc
The SDK/key-type footnote moved to Node and Settings, so it should not survive
as a quoted string in ui/ either — the About card now shows IDENTITY ed25519 and
SDK <version> as label plus mono value, which is the design system's idiom for a
machine fact. Same reasoning for the KDoc: it describes the change instead of
pasting the strings that were removed.
2026-10-29 00:06:07 -04:00
agent
b65c990014
ui: cap the invite payload card and shorten the settings tab label
Two things the emulator run surfaced:

- The invite payload is about a kilobyte, so the plain Text card grew past the
  screen and pushed Copy invite / Done below the fold on a phone. Four lines
  with an ellipsis: the copy button carries the whole string, and the QR is the
  primary path anyway.
- "Node & Settings" as a 10sp label in a third of the bottom bar is one OEM font
  scale away from wrapping. The tab says "Settings"; the destination screen keeps
  its "Node & Settings" title.
2026-10-29 00:05:17 -04:00
agent
0283e6bf48
ui: app shell, messenger and invite refresh (plan P2 and P3)
Plans P2 and P3 are one change: the shell decides who calls the roster, so the
roster cannot land before it. The tree is green at this commit, which is why
they are not split.

Shell (P2)
- The horizontal text-link bar is gone. Three top-level destinations hang off a
  persistent 64dp bottom bar — Chats (default), Wallet, Node and Settings — and
  everything else is a sub-screen behind a chevron.
- MainActivity owns the shell: a Scaffold with the tab bar around a NavHost of
  chats / wallet / settings plus share, paste, chat, profile, wallets and
  rotate. Tab selection pops back to the start destination and restores saved
  state, so a chat left open behind the Wallet tab survives a trip to Settings.
- The node keeps living on the wallet screen, where its card already is, so the
  third tab is the security surface: profile, saved wallets, rotate identity,
  delete message history, the keep-alive status row, and — disclosed here
  instead of under the roster — the identity/SDK lines that made the home screen
  read as a test build.
- OwTopBar: 20sp bold title, optional "Tor active" pill beneath it, a 36dp
  padlock surface for Lock, and the overflow. Rotate identity, saved wallets and
  delete history live in the overflow; the destructive two go through a typed
  confirmation dialog or the typed ROTATE screen, never a single tap.
- Insets: the tab bar consumes the navigation-bar inset and
  LocalBottomBarPresent tells screens inside the shell not to pad for it again,
  so there is no double gap above the tabs and the IME still wins when the
  keyboard is up.
- window.isNavigationBarContrastEnforced = false on Q+, so the system's
  translucent scrim does not draw a second band over the canvas.

Messenger (P3)
- The identity block is one bar: identicon, "Your identity", the truncated
  fingerprint in mono, a copy-invite icon and a QR icon. Gone from here: the
  YOU (stable forever) card, the "sdk … · identity = ed25519 pubkey" line and
  the keep-alive paragraph. The full fingerprint and locator stay on the profile
  and invite screens.
- The empty state says what to do and offers both ways out ("Add contact",
  "Share my invite"), and keeps the honest sentence: invites are not
  discoverable.
- Friend rows: petname, short mono fingerprint, and a locator shortened as
  head…tail.onion — the suffix is never the part that is cut, and a v3 onion is
  never soft-wrapped.
- Invite sharing shows a QR of the payload beside the copyable text; the clip is
  marked sensitive on API 33+.

No ViewModel, SDK, Tor or wallet call changed. Every callback is the call the
old screens made; the wallet screens are untouched for the next card.
2026-10-28 23:51:51 -04:00
agent
5f2a6a184f
ui: design tokens and the shared component set (plan P1)
One palette, one geometry, one button. The alpha build had a four-colour
darkColorScheme and every screen inventing its own pill, which is why the app
read as a debug harness; `ui/Theme.kt` now carries the tokens and new UI takes
them from `OwColors` / `OwRadius` / `OwSize` instead of Material defaults.

Tokens (§1.1, §1.2): canvas #0A0C0E, surface #12161A, interactive #1C2228,
border #262E36, mint accent #2EE59D, text #F3F5F7 / #9BA3AE / #5E6773, and the
amber/crimson status triples. Cards are 16dp; buttons and inputs are 12dp
squircles; 999dp survives only for status pills. Typography is system sans for
chrome, and `MonoStyle` is the single mono style, reserved for pubkeys,
truncated locators, seeds, host:port and block heights.

Primitives (§1.3), in `ui/components/`:
- OwButton — primary / secondary / outline / destructive, exact heights and
  radii, no elevation;
- OwSegmentedControl — one track, accent selected segment, animated;
- OwAlertBanner — warning / error / info with a status icon and a tinted
  surface;
- OwCard, OwDivider, OwPill, OwStatusDot, TorStatusPill, OwSectionTitle,
  OwIconButton (36dp), Identicon, OwConfirmDialog (typed confirmation),
  OwQrCode (zxing, light plate for scanning).

Fourteen single-colour vector icons, so no `material-icons-extended` (a
multi-MB dependency) and no icon font. `Label`/`Mono` moved here from the
roster so the design system is not owned by one screen.

Behaviour: none. These are pure view helpers.
2026-10-28 23:51:29 -04:00
4e8342b2d8 Merge pull request 'kdf: version Argon2id profiles (legacy stores still open) and raise the default to 64 MiB / t=3' (#194) from onionwire/t_fb6ffa87-strengthen-and-version-the-store-backup into main
All checks were successful
android-ci / android (push) Successful in 13m0s
ci / test (push) Successful in 45m56s
ci / sdk (push) Successful in 2m16s
Reviewed-on: #194
2026-10-26 16:13:08 +00:00
4cf0a09ceb Merge branch 'main' into onionwire/t_fb6ffa87-strengthen-and-version-the-store-backup
Some checks failed
ci / sdk (pull_request) Has been cancelled
ci / test (pull_request) Has been cancelled
2026-10-26 16:13:01 +00:00
713dbd9006 Merge pull request 'pay: domain-separate tip and make legacy signature acceptance one switch' (#193) from onionwire/t_438331aa-close-the-legacy-signature-surface-and-d into main
Some checks failed
android-ci / android (push) Has been cancelled
ci / test (push) Successful in 36m49s
ci / sdk (push) Successful in 2m8s
Reviewed-on: #193
2026-10-24 22:11:53 +00:00
d3f1a44ef6 Merge branch 'main' into onionwire/t_438331aa-close-the-legacy-signature-surface-and-d
Some checks failed
ci / sdk (pull_request) Has been cancelled
ci / test (pull_request) Has been cancelled
android-ci / android (pull_request) Has been cancelled
2026-10-24 22:11:41 +00:00
56c0b67cdf Merge pull request 'docs: ADR for a post-quantum bootstrap epoch (epoch 0)' (#190) from onionwire/t_8fb1a517-decision-doc-post-quantum-bootstrap-epoc into main
Reviewed-on: #190
2026-10-24 22:10:48 +00:00
d1a8aeccd0 Merge branch 'main' into onionwire/t_8fb1a517-decision-doc-post-quantum-bootstrap-epoc
Some checks failed
android-ci / android (pull_request) Has been cancelled
ci / sdk (pull_request) Has been cancelled
ci / test (pull_request) Has been cancelled
2026-10-24 22:10:35 +00:00
d3a28a5c1c Merge pull request 'wallet: keep RPC spend credentials out of env, argv and error strings' (#192) from onionwire/t_79e98511-wallet-rpc-keep-spend-credentials-out-of into main
All checks were successful
android-ci / android (push) Successful in 12m16s
ci / test (push) Successful in 23m25s
ci / sdk (push) Successful in 4m7s
Reviewed-on: #192
2026-10-23 02:46:27 +00:00
af9077046b Merge branch 'main' into onionwire/t_79e98511-wallet-rpc-keep-spend-credentials-out-of
Some checks failed
android-ci / android (pull_request) Successful in 11m10s
ci / test (pull_request) Has been cancelled
ci / sdk (pull_request) Has been cancelled
2026-10-23 02:46:18 +00:00
rust-dev
8f959e937f
kdf: version Argon2id profiles and raise the default to 64 MiB / t=3
All checks were successful
ci / test (pull_request) Successful in 29m38s
ci / sdk (pull_request) Successful in 2m7s
The store and identity backup shared one hard-coded Argon2id profile
(m=19456 KiB, t=2, p=1) with nothing recorded on disk, so changing it
would have bricked every existing store and backup.

Record the profile with the data and raise the default:
- KdfProfile { Legacy = 0, Current = 1 }; Current is m=65536 KiB,
  t=3, p=1, out=32.
- Backups: seal() writes a profile byte after owbak1. Legacy blobs
  (exactly SEALED_BODY_LEN after MAGIC) still open; an unknown id is
  an error, never a fallback.
- Stores: store_meta gains kdf_profile (additive, default 0). The
  SQLCipher file key has no place to record a profile before the db
  opens, so a legacy file is detected by trial-opening with the
  legacy profile, then rekeyed to Current in one SQLCipher
  transaction; store_meta is re-wrapped (salt + ciphertext + profile)
  in a single transaction on the first successful unlock. Both are
  one-shot: the next start takes the current path.
- docs/THREAT_MODEL.md states the new params and the versioning.

Measured in release on this host: kdf legacy 0.018s / current 0.095s;
Store reopen current 0.354s, legacy upgrade path 0.528s.
2026-10-22 22:29:28 -04:00
rust-dev
b8c52ca97d
pay: domain-separate tip and gate legacy signature acceptance
All checks were successful
ci / test (pull_request) Successful in 19m52s
ci / sdk (pull_request) Successful in 2m16s
`tip` was the one payment frame with no domain tag: sign_tip signed the
LF-joined fields, so its signature could be confused with any other
newline-joined preimage. Mirror inv/rcp: sign_tip now emits
"onionwire-tip-v1" || 0x00-separated txid/amount/address/memo/ts, and
verify_tip tries that form then the historical layout.

Legacy acceptance is now one switch instead of nine call sites:
`pay::LEGACY_SIGS` (default true) plus `pay::legacy_sigs()`. Every v1 /
concat fallback reads it — the `onionwire:v1` invite string and its two
historical signature forms, `loc`, `inv`, `rcp`, and `tip`. `prf` is not
gated here because src/profile.rs is outside this card's file scope; the
spec says so.

Tests: legacy-on keeps every untagged form verifying (incl. a new tip
case); legacy-off rejects each untagged form while the tagged form still
verifies (loc, inv, rcp, tip, invite); sign_tip is pinned to the tagged
layout.

docs/PROTOCOL.md gains the emitted/accepted table per signed frame and
the mixed-fleet consequence.
2026-10-22 22:23:44 -04:00
1b562ca149 Merge pull request 'android: gate the Keystore passphrase key on device unlock, and migrate old installs' (#191) from onionwire/t_a84365da-android-gate-the-keystore-passphrase-key into main
All checks were successful
android-ci / android (push) Successful in 12m53s
Reviewed-on: #191
2026-10-23 02:20:40 +00:00
agent
625879e000
wallet: redact RPC creds everywhere and warn once on a login from env
All checks were successful
ci / test (pull_request) Successful in 19m31s
ci / sdk (pull_request) Successful in 2m3s
The app-spawned child already takes its login from the sealed store record
and only falls back to ONIONWIRE_WALLET_RPC_LOGIN; make that order explicit
in the code and name the exposure once per process when the fallback is used.

The dial URL still carries user:pass (Wallet::from_url needs it), but no
rendering path repeats it: Endpoint::redacted and WalletClient::redacted_url
print http://<redacted>:<redacted>@host:port/json_rpc, WalletClient has a
hand-written Debug, and error/status copy redacts the whole login, not just
the password half.

Residual, documented at the top of wallet_child.rs: --rpc-login is visible in
/proc/<pid>/cmdline to same-uid processes because monero-wallet-rpc has no
other credential channel.
2026-10-22 22:20:12 -04:00
apk-dev
d64114ca1c
android: gate the Keystore passphrase key on device unlock, and migrate old installs
All checks were successful
android-ci / android (pull_request) Successful in 11m41s
`setUnlockedDeviceRequired(true)` is now set on the key that wraps the store
passphrase (API 28+; below that the pre-gate path is unchanged and logs which
branch ran). `setUserAuthenticationRequired(false)` is untouched: the gate only
refuses while the lock screen is up, it is not a biometric prompt, so an
unattended unlock on an unlocked device still works.

A Keystore key cannot be retrofitted, so the gate needs a second alias:
`onionwire.store.unlock-gated` is generated with the flag and is the only key a
fresh install creates; `onionwire.store` is the pre-gate key and exists only on
installs that stored a passphrase earlier. Migration runs the next time the
passphrase is in hand (save(), or a successful load() — never inside open(),
which must not generate keys):

  1. seal under the unlock-gated key (created here if needed)
  2. write the blob to `…bin.tmp`
  3. read those bytes back, open them with the gated key alone, compare to the
     passphrase in hand — failure drops the temp file, throws SecretUnavailable
     with the reason, and leaves the previous blob and key untouched
  4. rename the temp file over the blob
  5. only now delete the pre-gate alias

A crash before 4 leaves the old blob and key intact; a crash between 4 and 5
leaves a working gated blob plus a stale alias the next save/unlock retires.
`open()` tries the gated key first and falls back to the pre-gate key, so that
window is harmless. `forget()` deletes both aliases.

Reporting is honest about a platform limit: `KeyInfo` exposes
`isUserAuthenticationRequired` but has no getter for the unlock requirement, so
nothing can ask the Keystore whether the flag stuck.
`KeystorePassphraseCipher.unlockGateReport()` reports our own bookkeeping (which
alias the live key was generated under) plus `platformReportsGate = false`, and
a device whose Keystore refuses the flag falls back to the ungated alias and
says so instead of claiming the gate. A locked device that makes the gated key
unusable is reported as "the device is locked", not as a GCM tag failure.

Instrumentation: migration happy path (gated key appears, pre-gate alias gone
only after the on-disk blob opens under the new key), a failed re-wrap (old key
and blob byte-identical, no temp file), the gated proof refusing a pre-gate
blob, and the crash window still unlocking. Logcat lines print
MANUFACTURER/MODEL/SDK_INT and the branch taken. Not run here: no device or
emulator on this host. JVM suite still 213 tests / 0 failures; androidTest
sources compile.
2026-10-22 22:08:06 -04:00
rust-dev
53d7f47b89
docs: ADR for a post-quantum bootstrap epoch (options A/B/C, decision C)
Records why epoch 0 is prekey-derived: one-shot Noise sessions plus
both-send-first convergence forbid a per-session secret with no wire field.
Evaluates a one-time prekey batch in the invite, a per-session epoch field in
the hybrid header, and accepting the window; picks accept with named revisit
triggers. No code or protocol change.

Measured facts used: v2 invite is 1930 chars; each ML-KEM-768 OPK adds 1584
base64url chars; MAX_INVITE is 4096; the TUI QR path (qrcode 0.14.1,
EcLevel::M) caps at 2331 bytes.
2026-10-22 22:01:34 -04:00
36969a7e95 Merge pull request 'ci: give android-release publish job the always() prefix' (#189) from fix/android-release-publish-if into main 2026-10-21 03:40:35 +00:00
sirius
99ea4e17ac
ci: give android-release's publish job the always() prefix it needs
Run 770 built the APK and AAR and uploaded them as an artifact, then the release
never received them: /actions/runs/770/jobs lists only `android`, because a
job-level `if` that reads `needs.android.result` on this runner is evaluated as
unset and the job is dropped before it is created. A dropped job is invisible -
it is not a red job and not a skipped job in the job list - so the run reads
green while the release is missing two assets.

release.yml's publish job already carries `always() &&` for exactly this reason
(its comment cites run 135). Mirror it. Nothing else changes: the job is still
gated on android succeeding and on dry_run being false.
2026-10-20 23:42:21 -04:00
08bf6649df Merge pull request 'release: stage dist before signing, and sign via a named volume' (#188) 2026-10-21 02:59:22 +00:00
Hermes DevOps
46baf67a14
release: stage dist before signing, and sign via a named volume
The publish job has never completed. Two plumbing bugs, no crypto involved:

1. The sign step ran `docker run -v "${GITHUB_WORKSPACE}:/work"`.
   GITHUB_WORKSPACE is a path INSIDE the job container, but docker resolves a
   bind mount's source on the HOST, where that path does not exist — so /work
   arrived empty and the script was absent. Run 768 failed with
   "bash: .ci-tools/scripts/sign-release.sh: No such file or directory" (127).
   Rehearsed locally against the pinned image: the bind mount yields an empty
   /work, the same command with a named volume + docker cp signs and
   self-verifies all four assets. Use the build jobs' pattern.

2. Signing ran before the files it signs existed. The find+cp loop that fills
   dist/ lived in the publish step, after the signature step. Move it into its
   own "Stage both arch artifacts into dist" step before signing, and let
   publish only validate dist/.

Fail-closed design unchanged: no MINISIGN_SECRET_KEY stops before any upload,
signing still precedes publishing, and the tag cleanup step is untouched.
docs/RELEASING.md described the old publish job; it now matches the workflow.
2026-10-20 23:01:09 -04:00
5d10cb3d00 Merge pull request 'release: commit the minisign public key' (#187) from release/signing-pubkey into main 2026-10-21 02:34:18 +00:00
sirius
37b08595a4
release: commit the minisign public key
The signing step has never run: there was no keypair, so no .pub in the tree and
no MINISIGN_SECRET_KEY secret. scripts/sign-release.sh resolves its public key at
.ci-tools/scripts/onionwire-signing.pub, which is this path in the CI checkout,
so it exited on "no public key" before minisign was ever invoked. Release run 767
died here and its fail-closed cleanup deleted the tag it had created; nothing was
published.

Generated with `minisign -G -W` (no passphrase: CI cannot answer a prompt, and a
passphrase stored beside the key in the same secret store protects nothing). The
secret half lives only in the Forgejo Actions secret MINISIGN_SECRET_KEY; it is
not in this repository and never has been. Procedure: docs/VERIFY.md,
"Maintainer: the signing key".

Public key: RWRWHhuty5VhgHpdAsbzMVNLmu1mztJblfxv06HjtVcrKHKS75792Jb+
2026-10-20 22:36:10 -04:00
bd806a1f50 Merge pull request 'docs: point the docs at v0.5.0, and say why a download 404s or 403s' (#186) from docs/release-version into main
All checks were successful
android-ci / android (push) Successful in 13m23s
2026-10-21 00:02:51 +00:00
sirius
57d1bb0bd2
docs: point the docs at v0.5.0 and explain why a download 404s or 403s
All checks were successful
android-ci / android (pull_request) Successful in 12m20s
README, android/README, VERIFY and the two release scripts all named v0.14.0,
a version that was never tagged or released - the newest tag is v0.4.0, so the
documented download URLs were dead. Align them with the version this release
cuts (minor bump off v0.4.0 -> v0.5.0).

VERIFY.md gains a Check 0: /releases/latest/download/... is not served by this
Forgejo (404, pin the tag), and Cloudflare answers a non-browser User-Agent with
403 error code 1010 even on a correct URL (measured: browser 206, curl 206,
Python-urllib 403).
2026-10-20 19:51:50 -04:00
4216a6731f Merge pull request 'ratchet: hybrid ML-KEM ratchet steps (KDF_RK v2, 2312-byte header, state v2)' (#185) from wt/t_fdce78d2 into main
All checks were successful
android-ci / android (push) Successful in 13m4s
ci / test (push) Successful in 17m41s
ci / sdk (push) Successful in 1m33s
2026-10-20 18:03:24 +00:00
agent
7a3c0055b3
chat: pin the classical and hybrid frame floors under padding
All checks were successful
ci / test (pull_request) Successful in 19m7s
ci / sdk (pull_request) Successful in 2m13s
Padding and the hybrid header are independent layers: the bucket is inside
the ratchet AEAD, the 2312-byte header is outside it. tests/padding.rs now
drives the ladder through a real hybrid step and asserts 2601 bytes in the
Noise body (2622 on the wire) against the classical 329/350, plus the
35113-byte largest-bucket frame under the 65535 cap. The node-level PQ
round-trip is corrected to say what it actually proves: epoch 0 stays
classical, so its frame does not widen.
2026-10-20 13:12:06 -04:00
rust-dev
b22abd7b2b
ratchet: hybrid ML-KEM steps (KDF_RK v2, 2312-byte header, state v2)
Every ratchet keypair is {x25519, ml-kem-768}. On a rotation the stepper
encapsulates to the receiver's current ratchet KEM key; both the X25519 DH
and the ML-KEM secret feed KDF_RK under the new onionwire-ratchet-v2-kdfrk
domain, so a later X25519 break does not open a chain established by a
hybrid step.

Epoch 0 stays classical by construction: the bootstrap root must be a pure
function of the two long-lived prekeys for both-send-first convergence, and
a per-session ss_kem differs for every one-shot Noise dial. The first
rotation (including the bootstrap tie-break rotation) is hybrid, so the
residual HNDL window is exactly the epoch-0 chain. docs/THREAT_MODEL.md
states that window; no full PQ forward secrecy is claimed.

Header 0x02 adds kem_pub[1184] || kem_ct[1088] to the 40-byte classical
header and is used on every frame of a hybrid chain, so a lost first frame
is harmless. A step with no KEM section is rejected (hybrid step required)
and a hybrid step at a classical friend is rejected (unexpected hybrid
step): no classical fallback.

State moves to blob v0.2: fixed 211-byte prefix plus flagged KEM fields.
A v1 blob is dropped and re-bootstrapped (hard cut, like F8); a corrupt v2
or a newer version is an error, not a silent reset.

Tests: hybrid root agreement on both sides, both-send-first convergence
with hybrid keys, no-downgrade, tampered kem_pub/kem_ct fail closed,
MAX_SKIP on a hybrid chain, classical friends still step classically,
state freeze at v0.2 and the node-level hard cut.
2026-10-20 13:02:48 -04:00
fec68e31ff Merge pull request 'chat: length buckets and plaintext padding' (#184) from wt/t_3c0798f2 into main
All checks were successful
android-ci / android (push) Successful in 13m13s
ci / test (push) Successful in 18m41s
ci / sdk (push) Successful in 1m34s
2026-10-20 16:58:41 +00:00
agent
7fa3edcdb4
chat: pad plaintext to a normative length ladder
All checks were successful
ci / test (pull_request) Successful in 15m47s
ci / sdk (pull_request) Successful in 1m31s
Chat plaintext is padded inside the ratchet AEAD to one of
256/512/1024/2048/4096/8192/16384/32768 bytes, with an explicit big-endian
uint16 pad_len followed by the body and random fill. An observer sees only
the bucket; the padding is authenticated by ChaCha20-Poly1305 and by the
Noise session. The receiver trusts pad_len only, rejects an overrun before
appending or persisting anything, and never infers a boundary from trailing
bytes. fil chunks are unchanged.

docs/PROTOCOL.md gains a normative Length buckets section, THREAT_MODEL
replaces the no-padding limit, README notes the bucketed chat length.
2026-10-20 12:38:04 -04:00
e26813809a Merge pull request 'transport: ML-KEM-768 hybrid prelude and onionwire:v2 invites' (#183) from wt/t_8bb448b5 into main
All checks were successful
android-ci / android (push) Successful in 12m44s
ci / test (push) Successful in 14m23s
ci / sdk (push) Successful in 1m24s
2026-10-20 16:25:13 +00:00
agent
c741b660e4
transport: ML-KEM-768 hybrid prelude and onionwire:v2 invites
All checks were successful
ci / test (pull_request) Successful in 18m32s
android-ci / android (pull_request) Successful in 20m14s
ci / sdk (pull_request) Successful in 3m11s
Adds an ML-KEM-768 install key beside the ed25519 identity and x25519
prekey. A friend added from a v2 invite always gets a version-2 PQ
prelude before Noise msg 1, and both sides bind (ct, ss_kem) into the
Noise prologue (onionwire-v2 \0 ct \0 ss_kem). The row decides: a
kem_pk friend without a prelude is rejected with 'prelude required',
a prelude for a classical row with 'unexpected prelude'.

Invites are now onionwire:v2 with kem=<base64url pk>; decode still
accepts v1 (no kem) and yields a classical friend. F8 rotates the
KEM key with the prekey and hard-cuts stored ratchet state. The TUI
labels a legacy friend 'classical'.

Docs: PROTOCOL (keys, framing, prologues, no-downgrade, invite v2),
THREAT_MODEL (what PQ transport does and does not buy; epoch 0 stays
classical), README (invite size, F8, legacy caveat). SDK exposes pq on
InviteInfo/FriendInfo and gains a v2 decode round-trip test.
2026-10-20 11:15:55 -04:00
00bb95675f Merge pull request 'tui: spawn the bundled monero-wallet-rpc next to the app' (#182) from wt/tui-bundled-wallet-rpc into main
All checks were successful
android-ci / android (push) Successful in 13m28s
ci / test (push) Successful in 13m49s
ci / sdk (push) Successful in 1m21s
Reviewed-on: #182
2026-10-12 02:42:19 +00:00
agent
37690e3d48
tui: spawn the wallet-rpc binary that sits next to the app
All checks were successful
ci / test (pull_request) Successful in 14m27s
ci / sdk (pull_request) Successful in 1m26s
A bare monero-wallet-rpc name is the executable beside this binary
when that file is executable, then PATH. An absolute path is left
alone, so Android and operator overrides keep working. Remote daemon
and remote wallet RPC are unchanged.
2026-10-11 19:41:11 -04:00
9b827fc001 Merge pull request 'tui: re-probe chain height while the node screen is up' (#181) from wt/tui-sync-status into main
All checks were successful
android-ci / android (push) Successful in 12m44s
ci / test (push) Successful in 13m24s
ci / sdk (push) Successful in 1m29s
Reviewed-on: #181
2026-10-11 20:28:28 +00:00
agent
99581bec5e
tui: re-probe chain height while the node screen is up
All checks were successful
ci / test (pull_request) Successful in 14m16s
ci / sdk (pull_request) Successful in 1m28s
The F7 NODE row kept the height from child start. Ctrl-R only
re-read that cache, so a syncing daemon looked frozen. Poll
wallet_child_refresh off the UI thread and copy the answer back.
2026-10-11 16:12:38 -04:00
a0b79d457d Merge pull request 'release: reproducible builds and signed assets' (#180) from repro-builds-and-signing into main
All checks were successful
android-ci / android (push) Successful in 12m39s
ci / test (push) Successful in 13m29s
ci / sdk (push) Successful in 1m21s
Reviewed-on: #180
2026-10-11 17:21:13 +00:00
agent
601f640f78
release: reproducible builds, and sign every asset
All checks were successful
android-ci / android (pull_request) Successful in 12m34s
ci / test (pull_request) Successful in 13m28s
ci / sdk (pull_request) Successful in 1m13s
"The source is public" is not a check anyone can run, and against a Tor +
Monero tool the surviving objection is that the released binary might not be
that source. This makes the build checkable instead of trusted.

- scripts/reproducible-build.sh is the single definition of a release build:
  digest-pinned builder image, fixed in-container paths, SOURCE_DATE_EPOCH
  from the released commit, --locked, its own apt build deps, and RUSTFLAGS
  replaced rather than extended. The fixed paths are load-bearing: rustc's
  --remap-path-prefix cannot reach absolute paths compiled in by a C
  toolchain, and this graph always has one (rusqlite compiles OpenSSL from
  vendored sources; the default cuprate-daemon adds RandomX and cmake). It
  also records toolchain versions in build-info, because the apt build deps
  are not digest-pinned the way the image is.
- release.yml pins the image by digest, resolves SOURCE_DATE_EPOCH from the
  tag's commit, runs that recipe, and uploads build-info-<target>.txt beside
  the binary. The cargo target volume is created per run and removed, so the
  published artifact cannot come out of a cache that a verifier does not have.
- scripts/verify-reproducible.sh rebuilds a tag in the same pinned image and
  compares bytes against the release asset. Two fresh builds of the same tree
  in that image produce identical sha256.
- scripts/sign-release.sh signs with minisign and verifies its own signature
  against the committed public key. The publish job signs BEFORE publishing
  and fails closed without MINISIGN_SECRET_KEY, so nothing unsigned reaches
  the release page: an unsigned release is indistinguishable from a signed
  one to anyone who is not checking. Checked: signature accepted by an
  independent minisign -V, a tampered file rejected, a missing key refused,
  a missing public key refused.
- build-release-local.sh runs the same container and the same recipe. A host
  cargo build would publish a hash nobody could reproduce, which is worse
  than having no fallback at all.
- docs/VERIFY.md is the verifier-facing walkthrough: the dependency graph and
  where its HTTP actually comes from, the wallet's real seed-read exposure,
  the rebuild check, the signature check, and an explicit list of what none
  of it proves.
- Cargo.toml repository: point at the Forgejo instance that hosts this and
  builds its releases.

Needs a MINISIGN_SECRET_KEY secret before the next release; without it the
publish job stops by design. docs/RELEASING.md has the keygen procedure.
2026-10-11 12:57:40 -04:00
1031092192 Merge pull request 'ci: build the default graph on Rust 1.98, not 1.91' (#179) from onionwire/ci-rust-198 into main
All checks were successful
android-ci / android (push) Successful in 12m45s
ci / test (push) Successful in 13m49s
ci / sdk (push) Successful in 1m22s
Reviewed-on: #179
2026-10-09 00:45:26 +00:00
agent
7391c5b7a4
ci: build the default graph on Rust 1.98, not 1.91
All checks were successful
android-ci / android (pull_request) Successful in 12m6s
ci / test (pull_request) Successful in 30m41s
ci / sdk (pull_request) Successful in 14m52s
`cuprate-daemon` is a default feature, so `cargo test --locked` in the Pi CI
job compiles `tapes`. That crate calls `VecDeque::pop_front_if`, stable only
since 1.93. `rust:1.91-bookworm` dies with `error[E0658]: use of unstable
library feature 'vec_deque_pop_if'` after the rest of the graph has already
built. The Android workflows were already on 1.98 for this; ci.yml and
release.yml were left on 1.91 when the feature was off, and that is no longer
true.

`rust-version` moves with the image. cargo checks it before features, so a
1.91 compiler must be refused up front instead of fifteen minutes into
`tapes`. `--no-default-features` would still compile on 1.91; the declared
floor is the default build's floor, which is what CI and `cargo build` run.
2026-10-08 17:41:22 -04:00
d89539e8b0 Merge pull request 'tui: drop the F9 menu that restates F6 and F7' (#178) from onionwire/t_7121b6ba-onionwire-tui-drop-the-menu-that-restate into main
Some checks failed
ci / test (push) Failing after 20s
ci / sdk (push) Successful in 1m31s
android-ci / android (push) Successful in 12m45s
Reviewed-on: #178
2026-10-08 21:24:42 +00:00
174923f80f Merge pull request 'tui: the Cuprate start path answers get_info, and the Linux TUI includes it' (#177) from onionwire/t_6f94e378-onionwire-tui-cuprate-start-path-must-la into main
Some checks failed
ci / test (push) Failing after 25s
ci / sdk (push) Successful in 7s
android-ci / android (push) Successful in 12m16s
Reviewed-on: #177
2026-10-08 21:24:23 +00:00
agent
14a0d22b20
ci: install cmake for the default Cuprate build
Some checks failed
ci / test (pull_request) Failing after 52s
ci / sdk (pull_request) Successful in 1m34s
android-ci / android (pull_request) Successful in 11m50s
RandomX's cmake-rs build script panics with "is cmake not installed?"
in the rust:bookworm job container once cuprate-daemon is a default
feature. Install cmake and build-essential in the root test, release,
and fuzz containers. Android jobs already did this.
2026-10-08 11:34:44 -04:00
agent
4e13242a44
tui: drop the F9 menu that restates F6 and F7
All checks were successful
ci / test (pull_request) Successful in 7m40s
ci / sdk (pull_request) Successful in 1m42s
The Wallets & Settings screen only named keys that already work. F6 is the
wallet, F7 is the node, and p on the roster or chat opens peer payments.
Profile, backup and wipe stay composer commands, named in help.
2026-10-08 11:03:28 -04:00
agent
a466c43764
tui: the Cuprate start path answers get_info, and the Linux TUI includes it
Some checks failed
ci / test (pull_request) Failing after 2m50s
ci / sdk (pull_request) Successful in 1m23s
android-ci / android (pull_request) Successful in 12m40s
Node::start_wallet_child is the call the TUI makes. The test stores an
in-process testnet source, starts the child, and checks the typed daemon
client's get_info. It does not bootstrap Tor.

cuprate-daemon is now in the Linux TUI default, so a release build of the
onionwire bin links the daemon with no extra feature flag. A build with
--no-default-features still refuses with NO_FEATURE_MSG. cuprated keeps
default-features = false so Cuprate's arti feature cannot pull arti-client
0.44 next to OnionWire's 0.46.

Cargo.lock is unchanged: cuprated was already an optional dependency.
2026-10-08 10:59:45 -04:00
c550a197ac Merge pull request 'tui: F7 can save and start an app-owned chain source' (#170) from onionwire/t_fcd38efc-onionwire-tui-f7-can-save-and-start-an-a into main
All checks were successful
ci / test (push) Successful in 6m45s
ci / sdk (push) Successful in 1m25s
android-ci / android (push) Successful in 12m6s
Reviewed-on: #170
2026-09-28 05:09:45 +00:00
agent
1e3eceabcb
docs: the F7 save gate and the app-owned chain source
All checks were successful
ci / test (pull_request) Successful in 6m49s
ci / sdk (pull_request) Successful in 1m25s
TUI.md: the `last` line's shape when one half of a save is refused, why an
app-owned source saves with an empty `url` while a typed endpoint with no login
is still refused, and the wording the `chain` row carries in a build without
`cuprate-daemon`.

WALLET.md: the same gate from the node's side, and the start contract — a start
that fails part way stops what it spawned and leaves the chain datadir as the
thing a retry reuses.
2026-09-27 23:16:35 -04:00
agent
6c1fc5008a
wallet_child: one contract for a start that fails part way
Settle the contract the red feature-gated test was fighting, and make the code
and both tests express it: a start that fails after the chain daemon came up is
all or nothing, the same contract
node::tests::a_missing_binary_fails_the_start_and_leaves_no_child asserts one
level up. A daemon left running behind an error has no owner (the caller gets
the error back, not the client), no handle to stop it, and holds 18081 against
the next start; what a retry reuses is the chain datadir on disk, never a
process that outlived its owner. start_with_creds already behaved that way, so
this states the contract where the stop happens rather than changing it.

in_process_source_launches_a_daemon_and_stop_shuts_it_down was red because its
fake monero-wallet-rpc never binds the port its own readiness gate probes:
start() returns that error, the test discarded it with `let _ =`, and it then
asserted the daemon had survived a failed start. It now holds the published
port the way the module's other start tests do
(test_support::PublishedPortHold) and expects the start to succeed, with every
assertion it had kept. The failure path gets its own test instead, which pins
the tear-down: neither child running, the daemon's port closed, the chain
datadir kept.
2026-09-27 23:16:30 -04:00
agent
c776ea3e0c
tui: the chain row says when this build has no in-process daemon
cuprate::available() was never consulted in the TUI, so the 'chain' row
offered 'in-process node · cuprate in this app' in a build whose only possible
answer is cuprate::NO_FEATURE_MSG. The row now carries that wording where the
choice is made, the same way prune_display()/network_display() carry theirs.
The choice stays in the picker: builds with the feature exist, and a stored
in-process source must still be readable.
2026-09-27 23:16:10 -04:00
agent
c877375ea5
tui: an app-owned chain source saves without an external wallet RPC
A save on F7 ran the wallet-config write first and returned early on its
error, so an empty 'url' row failed the whole save: 'wallet RPC endpoint
required'. That refusal belongs to Wallet::from_config and it is about an
externally run monero-wallet-rpc; an app-owned chain source (local monerod,
in-process Cuprate) spawns its own child with generated creds and a port it
picked, and Node::start_wallet_child_with replaces the stored client after
the spawn, so the url/login rows describe no endpoint the app dials.

- an empty endpoint on an app-owned source no longer vetoes the chain-source
  write; the validator itself is untouched, and a *typed* endpoint with no
  login is still refused
- both halves of a save are attempted and reported on one line shape, so a
  wallet-config refusal cannot silently drop a chain source the user picked
2026-09-27 23:15:53 -04:00
02f8e4d914 Merge pull request 'tui: F7 becomes the node-setup screen, and F6 goes back to being the wallet' (#169) from onionwire/f7-node-setup into main
All checks were successful
ci / test (push) Successful in 7m8s
ci / sdk (push) Successful in 1m19s
android-ci / android (push) Successful in 13m45s
Reviewed-on: #169
2026-09-28 00:43:14 +00:00
06367b2949 Merge pull request 'ci: skip superseded runs, move fuzz to nightly, trim the android PR trigger' (#168) from ci/trim-redundant-runs into main
Some checks failed
ci / test (push) Failing after 47s
ci / sdk (push) Successful in 10s
android-ci / android (push) Successful in 13m36s
Reviewed-on: #168
2026-09-28 00:42:46 +00:00
agent
5cdfbacf10
tui: F7 becomes the node-setup screen, and F6 goes back to being the wallet
All checks were successful
ci / test (pull_request) Successful in 7m20s
ci / sdk (pull_request) Successful in 1m45s
android-ci / android (pull_request) Successful in 13m36s
ci / fuzz (pull_request) Successful in 5m29s
The chain source was reachable from three places and configured from none of
them properly: `F6`'s inline `1`/`2`/`3` picker wrote only the in-process
choice, the `F9` menu showed the state and named keys that edited it, and
`Node::set_local_monerod` / `set_remote_daemon` / `set_receive_only` — the only
way to point the app at a Monero node — had **no TUI caller at all** (Kotlin
only). `wallet::NOT_CONFIGURED_MSG` told users to "open F7" and there was no F7.

F7 (`WalletSetupConfig`) is now the one screen that sets up the node:

- The `datadir` row is new and editable. `Node::set_local_monerod_at` takes the
  path; `set_local_monerod` delegates with the derived default, so an existing
  install keeps the store it already has. An empty datadir is refused rather
  than silently replaced — a store that moved unasked looks like a vanished
  chain and resyncs somewhere the user did not choose.
- The `network` row is new: it carries the Cuprate mainnet/testnet choice that
  `F6`'s `1`/`2`/`3` used to own, so deleting those keys loses nothing. Mainnet
  reads `unvalidated` before it is picked.
- A `NODE` section shows the live `Node::wallet_child_status` line (state, chain
  source, `sync h/t`, last error) and the last save/test answer. It is the
  node's answer, never the draft above it, and `Ctrl-R` re-reads it.
- `Ctrl-S` saves and starts the child (the daemon, and `monerod` for a local
  source); `Ctrl-X` stops it. Both go through the same `Node::start_wallet_child`
  / `stop_wallet_child` the app's own lifecycle uses, so a start that lands on a
  wallet with no stored passphrase still reaches the unlock prompt.

F6 loses the chain picker and the `s`/`x`/`p` child keys — it is the wallet
again (receive, balance, transfers, create/import) — and its footer points at
`F7 node`. The `F9` menu's `child`/`sync` rows now name `F7 ctrl-s/x` and
`F7 ctrl-r` instead of keys that no longer exist on F6. `set_cuprate_chain` and
the `p` probe handler are deleted rather than left dead.

The node's own keys are named in the body, on the section they act on: at 80
columns the footer has room for one group and the status line already spends
half the width, which is the same reason the login row names `Ctrl-U`.

Tests: six new cases in `src/tui.rs`'s `wallet_setup_config_tests` drive the real
key path and the real node — the typed datadir reaching `ChainSource::Local`, an
empty one being refused with nothing written, the live row on open, `Ctrl-S`
saving then reporting the node's own refusal, the in-process network pick
reaching the store, and F6 no longer owning keys it does not handle.
`tests/tui_spec.rs`'s menu-key check now asserts the F7 keys; the F6 keys it
asserted before no longer work.
2026-09-27 20:06:51 -04:00
agent
a37712f3af
tui: F7 wallet setup — RPC endpoint and chain source on screen
`wallet::NOT_CONFIGURED_MSG` has always said "open F7 to set it up" and there
was no F7. This is that screen.

- `FunctionKey::Setup` on `F7`, live on Main, the settings menu and peer
  payments, same invariant `F9` follows.
- `Screen::WalletSetupConfig` carries `WalletSetupConfigState`: a snapshot of
  plain data taken when the screen opens, never a handle onto `Node`.
- Rows: the wallet RPC endpoint and its login (never rendered back — the row
  says `hidden · set`, `Debug` redacts it), the view-only toggle, and a chain
  picker over all four `ChainSource` cases with their own fields.
- `Node::set_remote_daemon` / `set_local_monerod` / `set_receive_only`, so the
  TUI can reach what only the Android API could, plus `F6`'s in-process source.
- An untouched chain row is not written, so an F7 save cannot silently undo the
  in-process choice; picking a remote daemon says who is trusted in the same
  frame, one line, lowercase.
- `Ctrl-T` tests the endpoint and shows the sanitized `PingResult::line()`.
  Saving never dials. A rejected form writes nothing — the node validates.
- Docs that claimed there is no F7 (`docs/TUI.md`, `docs/WALLET.md`) now
  describe the screen; the settings menu's `endpoint` row names the key.

(cherry picked from commit a48d40bc4e)
2026-09-27 19:23:51 -04:00
agent
404ceea0f8
ci: skip superseded runs, move fuzz to nightly, trim the android PR trigger
All checks were successful
ci / test (pull_request) Successful in 6m33s
ci / sdk (pull_request) Successful in 1m27s
android-ci / android (pull_request) Successful in 12m47s
Three sources of wasted Pi time, measured over a two-week window
(353 workflow runs, 694 job runs): ~78% of CI wall-clock was spent on
work that did not need to happen.

1. Nothing was ever cancelled. Every `concurrency:` block in the repo
   had `cancel-in-progress: false`, and 279 of 353 runs sat in the
   queue behind a newer commit on the same branch. The comment
   justifying it ("shared the container name `onionwire-ci`") was
   stale — the name has been per-run-id for a while — but the real
   constraint is the shared cargo target volume, which two concurrent
   writers corrupt (`Permission denied (os error 13)` on
   /target/debug/deps). So the flag stays false and superseded runs
   instead stand down at a new gate: compare GITHUB_SHA against the
   remote branch tip and skip. Seconds, not minutes, and it cannot
   release the concurrency group into a volume race. Added to
   ci.yml (test, sdk) and android-ci.yml (android).

   Verified against the run history: Forgejo's pull_request GITHUB_SHA
   is the branch head, never a synthetic merge commit (245/245 recorded
   PR runs match a refs/pull/*/head tip), so the gate cannot skip a
   live run. It fails open — an unresolvable ref runs the job. 232 of
   477 historical PR runs would have been skipped.

2. `fuzz` ran on almost every push. A job cannot narrow a
   workflow-level path filter, so `fuzz/**` sat in ci.yml's list
   beside `src/**` and `crates/**`: 80 of 84 recorded runs touched
   nothing in fuzz/, each paying a nightly toolchain install and
   `cargo install cargo-fuzz` for 15 seconds of actual fuzzing. Moved
   to its own workflow, schedule-only (03:30 UTC, off the arti-watch
   slot) plus workflow_dispatch. The build/run single-container fix
   and the PATH export from #106/#107 come along unchanged.

3. android-ci built a full APK for commits that touched no android/
   file — 95 of 143 runs, at ~11 minutes each. The PR trigger now
   covers android/**, crates/onionwire-sdk/**, Cargo.toml, Cargo.lock
   and the build script. The push-to-main trigger keeps src/** and
   crates/**, so every merge still runs the in-APK checks that earn
   their keep (the target_max_memory marker gate, the .so listing, the
   sha256 round-trip) — a Rust-only PR now finds out at merge instead
   of before it, and nothing reaches a release untested.

Also drops `fetch-depth: 0` from android-ci: nothing in the build
reads git history (PUBLISH_TAG comes from the environment).

ci.yml's `push: [main]` trigger is unchanged. It re-tests trees a PR
already tested identically (73 job runs in the window), but branch
protection is empty, so it is not a merge gate — it is the "CI green
on main" signal docs/RELEASING.md's readiness gate reads, and a merge
commit has a different sha so statuses do not carry over. The
staleness gate already removes most of its cost.

docs/RELEASING.md describes all of the above; its android-ci path
list and its fuzz-job account were both wrong after this change.
2026-09-27 15:34:58 -04:00
9f3745cd1d Merge pull request 'tui: the F6 wallet screen draws its body in the slot that has the height' (#167) from onionwire/t_716400d7-onionwire-tui-the-f6-wallet-screen-clips into main
Some checks failed
android-ci / android (push) Has been cancelled
ci / test (push) Failing after 29s
ci / sdk (push) Successful in 1m15s
ci / fuzz (push) Successful in 5m15s
Reviewed-on: #167
2026-09-27 18:45:13 +00:00
d93e9c3276 Merge branch 'main' into onionwire/t_716400d7-onionwire-tui-the-f6-wallet-screen-clips
Some checks failed
android-ci / android (pull_request) Has been cancelled
ci / test (pull_request) Failing after 42s
ci / sdk (pull_request) Successful in 1m45s
ci / fuzz (pull_request) Successful in 5m10s
2026-09-27 18:45:04 +00:00
dca69bad6f Merge pull request 'tests/tui_spec: remove the NO_COLOR env race behind the flaky suite' (#164) from onionwire/t_75caf868-onionwire-tui-tests-no_color-env-race-ma into main
Some checks failed
ci / test (push) Failing after 26s
ci / sdk (push) Successful in 1m16s
ci / fuzz (push) Successful in 4m54s
android-ci / android (push) Successful in 10m25s
Reviewed-on: #164
2026-09-27 18:08:48 +00:00
0149e105b0 Merge branch 'main' into onionwire/t_75caf868-onionwire-tui-tests-no_color-env-race-ma
Some checks failed
ci / test (pull_request) Failing after 29s
ci / sdk (pull_request) Successful in 1m11s
ci / fuzz (pull_request) Successful in 5m10s
android-ci / android (pull_request) Successful in 12m5s
2026-09-27 18:08:39 +00:00
agent
3bec3bffbf
tui: the F6 wallet screen draws its body in the slot that has the height
All checks were successful
android-ci / android (pull_request) Successful in 10m37s
ci / test (pull_request) Successful in 6m46s
ci / sdk (pull_request) Successful in 1m17s
ci / fuzz (pull_request) Successful in 5m1s
2026-09-26 23:35:31 -04:00
b78e0fcb55 Merge pull request 'tui: a fresh install must not open on the Monero spend-authority warning' (#162) from onionwire/t_6aa61cf8-onionwire-tui-a-fresh-install-must-not-o into main
Some checks failed
android-ci / android (push) Successful in 10m51s
ci / test (push) Failing after 36s
ci / sdk (push) Successful in 1m9s
ci / fuzz (push) Successful in 4m49s
Reviewed-on: #162
2026-09-27 03:34:52 +00:00
fa58930678 Merge branch 'main' into onionwire/t_6aa61cf8-onionwire-tui-a-fresh-install-must-not-o
Some checks failed
android-ci / android (pull_request) Successful in 11m8s
ci / test (pull_request) Failing after 39s
ci / sdk (pull_request) Successful in 1m34s
ci / fuzz (pull_request) Successful in 5m0s
2026-09-27 03:34:38 +00:00
73130b443f Merge pull request 'tui: F6 opens the wallet screen instead of exiting when no wallet is configured' (#161) from onionwire/t_da08817e-onionwire-tui-f6-exits-the-app-when-no-w into main
All checks were successful
android-ci / android (push) Successful in 10m31s
ci / test (push) Successful in 6m17s
ci / sdk (push) Successful in 1m9s
ci / fuzz (push) Successful in 4m54s
Reviewed-on: #161
2026-09-27 02:58:22 +00:00
4ff5af3fab Merge branch 'main' into onionwire/t_da08817e-onionwire-tui-f6-exits-the-app-when-no-w
Some checks failed
android-ci / android (pull_request) Has been cancelled
ci / test (pull_request) Successful in 6m6s
ci / sdk (pull_request) Successful in 1m21s
ci / fuzz (pull_request) Successful in 5m3s
2026-09-27 02:58:10 +00:00
863adc22dd Merge pull request 'docs: TUI wallet surfaces — presentation and flow review (report only)' (#160) from onionwire/t_e4eb38a8-onionwire-tui-presentation-flow-review-o into main
Reviewed-on: #160
2026-09-27 02:51:19 +00:00
agent
a9cb0d5758 tests/tui_spec: remove the NO_COLOR env race behind the flaky suite
Some checks failed
android-ci / android (pull_request) Has been cancelled
ci / test (pull_request) Successful in 6m23s
ci / sdk (pull_request) Successful in 1m17s
ci / fuzz (pull_request) Successful in 5m6s
`alert_line_prefixes_when_no_color` flipped the process-global `NO_COLOR`
without the `ASCII_ENV` mutex the other env-touching tests in this binary
hold, so a concurrent `remove_var("NO_COLOR")` could win and make
`alert_line()` resolve to Rgb/Ansi16 — the `! ` assertion then failed on an
otherwise green run (measured 1/12 runs at cc1201d).

Inject the colour mode instead of reading the environment in the test:

* `tui::alert_line_for_mode(mode, msg, width)` — `alert_line()` is now a
  one-line delegate passing `color_mode()`, so production behaviour is
  unchanged and the no-colour path is asserted without touching the env.
* The test now pins all three shapes of that path: `None` prefixes `! `,
  Rgb leaves the message verbatim, and an already-prefixed alert is not
  double-prefixed.

Also fix the second, same-class race the 20x repeat surfaced:
`wallets_settings_menu_frame_shows_the_shipped_footer` compares a rendered
frame against `status_footer_phased` computed moments earlier, and both read
`ascii_chrome()`/`color_mode()` live — a concurrent `ONIONWIRE_ASCII=1` made
the two sides disagree (✓/… vs ok/...). It now takes the same `ASCII_ENV`
lock and forces the unicode mode.

Evidence (TMPDIR=/home/lancelot/.hermes/tmp/onionwire-tui):
* cargo test --locked -> exit 0, 35 suites, 472 passed, 0 failed, 4 ignored
* cargo clippy --locked --all-targets -- -D warnings -> exit 0
* cargo test --locked --test tui_spec x60 -> 60 ok, 0 failures
* teeth: with the `! ` prefix removed from the None path, the test fails
  ("expected '! ' prefix in None mode: \"peer down\"") — reverted.
* ONIONWIRE_ASCII=1 cargo test --locked --test tui_spec -> 37 passed (no
  unlocked test's outcome depends on the ambient value)
* rustfmt --edition 2024 --check on both files: only the inherited hunks
  (src/tui.rs 16 == HEAD 16; tests/tui_spec.rs 3 vs HEAD 4, one inherited
  hunk reformatted away by this edit)
2026-09-26 22:46:43 -04:00
agent
cc1201d876
tui: a fresh install opens on the main view, not the spend-authority warning
All checks were successful
android-ci / android (pull_request) Successful in 10m37s
ci / test (pull_request) Successful in 6m20s
ci / sdk (pull_request) Successful in 1m20s
ci / fuzz (pull_request) Successful in 5m13s
2026-09-26 22:29:59 -04:00
rust-dev
5fcd4ed643
tui: F6 opens the wallet screen instead of exiting when no wallet is configured
All checks were successful
ci / test (pull_request) Successful in 6m44s
ci / sdk (pull_request) Successful in 1m33s
android-ci / android (pull_request) Successful in 12m2s
ci / fuzz (pull_request) Successful in 18m34s
App::open_wallet propagated the node's "no receive address" error with `?`,
so on an install with no wallet RPC configured and no profile xmr the Err
travelled out of App::run and out of boot(), and the process exited 1. The
same call already degrades to an empty address on F9.

Degrade it here too, and leave a status note that names the way forward:
this screen's own `c`/`i` create/import keys plus ONIONWIRE_WALLET_RPC.
A configured-but-failing endpoint gets the existing NOT_CONNECTED_MSG
instead of the unconfigured copy. balance and transfers are unchanged.

Tests: F6 on a bare install opens Screen::Wallet with an empty receive_addr,
a status note, and no error text in the frame drawn through App::draw; the
frame after Esc back to Main really renders the note. The control case (a
profile xmr address) still fills receive_addr and sets no note. The existing
offset-notice test asserted the propagation itself and now asserts the screen
it reaches instead.
2026-09-26 22:15:51 -04:00
tui-design
041179eb89
docs: presentation and flow review of the TUI wallet surfaces
Report-only audit of the wallet screens at a1f5c878: rendered frames at
80x24/120x40/200x60 for the first-run frame, the F6 wallet screen, the
F6 -> w wallet list, the create-spend-wallet gate and the F9 menu, plus a
findings table located by function and line.

No source file changed.
2026-09-26 22:07:15 -04:00
a1f5c878d3 Merge pull request 'wallet: optional seed-offset passphrase on import' (#156) from onionwire/t_dc9b74a6-onionwire-wallet-optional-seed-offset-pa into main
All checks were successful
ci / test (push) Successful in 6m21s
ci / sdk (push) Successful in 1m29s
android-ci / android (push) Successful in 12m27s
ci / fuzz (push) Successful in 5m6s
Reviewed-on: #156
2026-09-25 22:22:57 +00:00
agent
f6a7daf892
wallet: optional seed-offset passphrase on import
All checks were successful
ci / test (pull_request) Successful in 6m21s
ci / sdk (pull_request) Successful in 1m28s
android-ci / android (pull_request) Successful in 12m54s
ci / fuzz (pull_request) Successful in 18m31s
Monero's `restore_deterministic_wallet` takes a `seed_offset`: a second
spend secret mixed into the 25 words at restore time, so the same words
with a different offset open a different wallet. It is not the wallet-file
passphrase and must never be sealed, stored, logged or put on an argv.

- `Wallet::restore_wallet` gains `seed_offset: Option<&str>`: None, empty
  or whitespace-only leaves the field out of the JSON entirely; otherwise
  the ends are trimmed and it is sent beside the seed.
- `Node::wallet_restore` passes it through and still seals only the file
  passphrase.
- SDK: `import_wallet` keeps its signature (None) and
  `import_wallet_with_offset` is added (Kotlin `importWalletWithOffset`).
- TUI: a new `ImportOffset` step between the seed and the file passphrase
  (blank Enter skips, a real one is confirmed, a mismatch never dials), and
  `ImportOffsetSeen` after a successful import that used one -- Esc cannot
  leave it, only SEEN, and the offset is not drawn anywhere.
- Docs: WALLET.md, THREAT_MODEL.md, TUI.md, one README sentence.
2026-09-25 00:42:44 -04:00
6d815b0fe8 Merge pull request 'wallet: wait for listeners before treating connect refusal as an error' (#155) from onionwire/t_c8fe0549-onionwire-wallet-start-waits-for-the-dae into main
All checks were successful
android-ci / android (push) Successful in 11m35s
ci / test (push) Successful in 5m48s
ci / sdk (push) Successful in 1m14s
ci / fuzz (push) Successful in 5m1s
Reviewed-on: #155
2026-09-24 00:44:44 +00:00
agent
2f3d5d69c3
docs: start waits for the daemon and wallet RPC listeners
Some checks failed
android-ci / android (pull_request) Has been cancelled
ci / test (pull_request) Successful in 8m43s
ci / sdk (pull_request) Successful in 1m16s
ci / fuzz (pull_request) Successful in 5m21s
2026-09-23 20:37:13 -04:00
agent
4136f36dd4
wallet: a connect refusal while coming up is not a status error 2026-09-23 20:37:13 -04:00
agent
081bdfac3e
wallet: wait for monero-wallet-rpc to accept before publishing the child 2026-09-23 20:37:13 -04:00
agent
f5e310fdf4
wallet: wait for the daemon RPC before spawning monero-wallet-rpc 2026-09-23 20:37:13 -04:00
rust-dev
052879fa39
wallet: share the loopback accept wait the SOCKS path already uses 2026-09-23 20:37:13 -04:00
9322d885f8 Merge pull request 'android: do not paint a connect refusal while the wallet is connecting' (#154) from onionwire/t_1b021834-onionwire-android-do-not-paint-a-wallet into main
All checks were successful
android-ci / android (push) Successful in 11m26s
Reviewed-on: #154
2026-09-24 00:08:52 +00:00
agent
971d8b3894
android: reload wallet reads when the child starts answering
All checks were successful
android-ci / android (pull_request) Successful in 12m46s
2026-09-23 19:50:18 -04:00
agent
9eb054b10f
android: do not paint a connect refusal while the wallet is connecting 2026-09-23 19:48:52 -04:00
25e4c67181 Merge pull request 'wallet: land the file-name picker fix and the wallet manager on main (from t_67879b98)' (#153) from onionwire/t_67879b98-wallet-actually-open-the-wallet-file-and into main
Some checks failed
android-ci / android (push) Has been cancelled
ci / test (push) Successful in 6m38s
ci / sdk (push) Successful in 1m18s
ci / fuzz (push) Has been cancelled
Reviewed-on: #153
2026-09-23 02:33:38 +00:00
685ce89b29 Merge pull request 'wallet: the file-name picker must consult the disk, not only the catalogue' (#151) from onionwire/t_81deabb5-wallet-the-file-name-picker-must-consult into onionwire/t_67879b98-wallet-actually-open-the-wallet-file-and
Some checks failed
android-ci / android (pull_request) Has been cancelled
ci / sdk (pull_request) Has been cancelled
ci / fuzz (pull_request) Has been cancelled
ci / test (pull_request) Has been cancelled
Reviewed-on: #151
2026-09-23 00:46:47 +00:00
c1fda00080 Merge branch 'onionwire/t_67879b98-wallet-actually-open-the-wallet-file-and' into onionwire/t_81deabb5-wallet-the-file-name-picker-must-consult
All checks were successful
ci / test (pull_request) Successful in 6m39s
ci / sdk (pull_request) Successful in 1m49s
ci / fuzz (pull_request) Successful in 7m1s
android-ci / android (pull_request) Successful in 19m1s
2026-09-23 00:46:34 +00:00
3ddd370b3d Merge pull request 'android: ask for the wallet passphrase, and stop printing RPC errors' (#150) from onionwire/t_9ef8561c-wallet-manager-ask-for-the-passphrase-an into onionwire/t_67879b98-wallet-actually-open-the-wallet-file-and
Reviewed-on: #150
2026-09-23 00:41:47 +00:00
01d3294282 Merge pull request 'wallet: actually open the wallet file, and remember its passphrase' (#149) from onionwire/t_67879b98-wallet-actually-open-the-wallet-file-and into main
All checks were successful
ci / test (push) Successful in 6m2s
ci / sdk (push) Successful in 1m33s
android-ci / android (push) Successful in 13m13s
ci / fuzz (push) Successful in 4m57s
Reviewed-on: #149
2026-09-23 00:26:38 +00:00
agent
6edcd65e96
tests: take the restart's port from the child that dials it
All checks were successful
ci / test (pull_request) Successful in 6m3s
ci / sdk (pull_request) Successful in 1m14s
ci / fuzz (pull_request) Successful in 4m53s
android-ci / android (pull_request) Successful in 12m15s
`a_restart_opens_the_stored_wallet_file` failed on the Pi runner twice in a
row — CI run 905 job 1373 and run 901 job 1365 — and passed 3/3 on a 16-core
host:

  open the wallet with a passphrase: "wallet file onionwire-1 is not open —
  the wallet RPC never answered (wallet connect: Connection refused (os error
  111))"

The whole `WALLET_OPEN_WAIT` was burned on refusals, so the mock was bound on
a port the restarted child never dialled. Production is not the suspect:
`WalletChild::start_children` builds the child's argv and the `WalletClient`
URL from the same `pick_port` value, and `start_wallet_child_with` installs
that client in `self.wallet` before `open_child_wallet` dials it, so the client
can never carry the previous child's port.

The harness is the suspect. It learned the restarted child's port from the
*shared* argv log — a file every child writes — and cleared that file first.
A clear is not a synchronisation: on a loaded runner the killed child's write
lands after it, so the poller read the port of a child that was already dead
and bound the mock there. Reproduced deterministically with a stand-in whose
exec is late; with the old read the new test fails with the CI message, byte
for byte.

Each fake child now writes `<log>.<pid>` as well, and the shared copy lands
first, so a pid-named file implies the shared one is complete. A test that
spans two children reads the pid-named file: only that child can write it, so
the port belongs to the child that dials it. `WalletChild::wallet_rpc_pid`
(test-only) supplies the pid.

`open_wallet_blocking` already retries while the RPC is unreachable and gives
up after a bounded wait with a typed `OpenFailure::NotAnswering`, so it cannot
refuse forever against a merely slow child: no production change.

new test: node::tests::a_restart_is_not_given_the_stopped_childs_port
2026-09-22 15:37:55 -04:00
agent
8d80a4fd55
tests: write the fake child's argv log with one mv, not append-per-line
Some checks failed
android-ci / android (pull_request) Successful in 12m25s
ci / test (pull_request) Failing after 4m11s
ci / sdk (pull_request) Successful in 1m20s
ci / fuzz (pull_request) Successful in 5m28s
The wallet-child tests learn a spawned stand-in's port by polling its argv
log, and `fake_bin`/`fake_child_bin` truncated the log and then appended
one line per argument -- so a poller could read a prefix. A truncated port
is a *valid* u16 ("427" out of "42765"), so `wait_for_child_rpc_port`
happily returned a port nothing was listening on and the restart's
`open_wallet` died with `Connection refused` after its 10s budget; the
same prefix read is what `loopback_and_clearnet_remotes_carry_no_proxy...`
printed with its `--daemon-address` value missing.

Both tests failed on the first CI run of this branch (ci / test) and are
green in isolation, which is the signature of this race rather than of a
code defect. The argv now lands in the log with a single `mv`, so a reader
sees either no log or the complete one.

Measured with a tight read loop (argv-race-probe.sh): the append version
was caught mid-write 1/300 reads, the mv version 0/300.
2026-09-22 14:33:32 -04:00
agent
b4f8bb809c
android: filter the wallet child's last_error where the SDK record becomes the model
All checks were successful
android-ci / android (pull_request) Successful in 12m53s
The status line renders WalletChildInput.lastError through walletChildLine,
and the same field feeds walletChildStatusDescription for the screen reader.
The filter added in 3f84021 sat on the sticky error card only, so in exactly
the state this card targets — a live child with no wallet file open answering
-13 No wallet file — the raw daemon sentence still reached the line and the
screen-reader sentence.

Move it to the producer: WalletChildStatus.toInput() now runs lastError
through walletFailureText, the one seam where the SDK record becomes the
Kotlin model. Idempotent on its own replacement texts, so the error card's
second pass is stable.

New JVM tests build the SDK record and assert on the rendered line (and its
description), not on walletFailureText in isolation: with the filter removed
they fail on the raw 'No wallet file'.
2026-09-22 14:11:34 -04:00
rust-dev
59175f6931
wallet: the file-name picker consults the disk, not only the catalogue
Some checks failed
ci / test (pull_request) Failing after 4m25s
ci / sdk (pull_request) Successful in 1m29s
ci / fuzz (pull_request) Successful in 4m57s
android-ci / android (pull_request) Successful in 12m6s
next_wallet_filename returned <default>-<n> for the first n the SQLCipher
catalogue did not hold, and never looked at the wallet directory. monero
writes two files per wallet (<name> and <name>.keys) and refuses a create
that would collide with either, so a file whose catalogue row is gone -
Store::delete_wallet keeps the file, and a create whose record_wallet
failed leaves one - meant every attempt proposed the same taken name and
the daemon answered -21 Cannot create wallet. Already exists. for ever.

Add wallet_name_taken (src/wallet_child.rs): it lists the wallet dir and
answers whether <name> or <name>.keys is already there. next_wallet_filename
now needs the candidate free in both places, and Node::wallet_dir() is the
single source of $ONIONWIRE_HOME/wallet, used by the child spawn too.

Fail closed: an unreadable (or missing) wallet dir is an error, not a
guess. Reads only - nothing here deletes a file the catalogue does not
hold, which may be the only copy of a funded wallet.
2026-09-22 13:41:35 -04:00
apk-dev
3f84021abb
android: ask for the wallet passphrase, and stop printing RPC errors
All checks were successful
android-ci / android (pull_request) Successful in 12m38s
The wallet manager could not open a wallet it holds no passphrase for: the
child came up pointed at the file with no wallet open, `needs_passphrase`
was true, and every read answered the daemon's `-13 No wallet file`. The
screen rendered that string.

Phone side of t_67879b98:

* WalletManagerScreen asks for the passphrase when the child reports
  `needs_passphrase` and no wallet is open, and submits it through the
  parent's `Wire::open_wallet_with_passphrase` on the file the child is
  already pointed at. Masked field, no copy action (same rule as the seed
  card), wiped on success and on dispose, FLAG_SECURE while the screen is
  up.
* `walletFailureText` filters every user-visible wallet failure: the
  daemon's `No wallet file`, a bare `-13`, and any JSON envelope become a
  plain sentence that says whether a wallet is open and what to do next.
  Applied at every site that renders a wallet error, in both wallet
  screens and the wallet-child error flow in the ViewModel.
* The wallet screen says "no wallet is open in the child" and where to fix
  it, instead of leaving it to surface later as the daemon's own words.

Tests: WalletManagerTest covers the new decisions (prompt shown / not
shown, submit gate and its reasons, the failure-text filter, the open
hint) on the JVM. 203 unit tests green.
2026-09-22 13:30:08 -04:00
agent
ed29131a67
wallet: actually open the wallet file, and remember its passphrase
All checks were successful
ci / test (pull_request) Successful in 6m14s
ci / sdk (pull_request) Successful in 1m44s
android-ci / android (pull_request) Successful in 12m56s
ci / fuzz (pull_request) Successful in 5m1s
`monero-wallet-rpc` starts with no wallet open and keeps one only for the
life of its process, so a restart, a Lock/unlock or a wallet re-point left
a live child answering `-13 No wallet file` to every read while the file
sat on disk. The app now opens the configured catalogue file itself
(`Wallet::open_wallet`, over RPC — never `--wallet-file`/`--password` on
argv, which `ps` exposes) after the child is up, and keeps the passphrase
that does it, sealed with the store data key beside the RPC creds under
its own AAD.

- core: `Wallet::open_wallet`, `WalletConfig::wallet_passphrase`
  (+ `with_wallet_passphrase`, redacted Debug, kept out of the endpoint
  config), `Error::is_unreachable` for the one retryable class (the port
  binds a moment after spawn; a timeout is not a start in progress).
- store: `wallet_config.sealed_passphrase` column (additive, AAD
  `onionwire-store-v1:wallet-passphrase`), read-modify-written so the
  endpoint/login survive; `wallet_save_config` keeps the stored one.
- node: `start_wallet_child` opens the file, `open_wallet_with_passphrase`
  opens a file with a passphrase the user just typed and seals it only
  once a live daemon accepted it, `wallet_status` grows `wallet_open` and
  `needs_passphrase`. A child the RPC refuses is stopped rather than left
  inert; an install with no stored passphrase still starts, and says so.
- tui: one-shot prompt (`WalletSetup::UnlockPass`) on a wallet that needs
  it, reachable from the saved-wallet picker and from `s`.
- sdk: `openWalletWithPassphrase`, the two status fields, README flow.
- docs: WALLET/THREAT_MODEL/README — the passphrase is kept, and the
  consequence (the store passphrase is sufficient to spend) is stated
  rather than implied.

Tests: 4 new node tests drive a real child lifecycle against a loopback
wallet RPC (open on restart, no open without a passphrase, refused
passphrase, sealed-on-success), a `tests/wallet.rs` test asserts the bytes
sent (`open_wallet` + filename + password), and `tests/store.rs` covers
the sealed column and the plaintext->encrypted upgrade with it set.
Mutation-checked: stubbing the two open paths fails all four.
2026-09-22 12:52:08 -04:00
c5725856ad Merge pull request 'android: profile screen — nickname + Monero receiving address' (#148) from onionwire/t_54329f2b-android-profile-screen-nickname-monero-r into main
All checks were successful
android-ci / android (push) Successful in 11m34s
Reviewed-on: #148
2026-09-22 12:28:49 +00:00
dc8c3933cd Merge branch 'main' into onionwire/t_54329f2b-android-profile-screen-nickname-monero-r
All checks were successful
android-ci / android (pull_request) Successful in 12m30s
2026-09-22 12:09:33 +00:00
460a5afb12 Merge pull request 'android: saved-wallets screen (list, select, back up the open wallet)' (#147) from onionwire/t_cf7e07f9-android-saved-wallets-screen-list-select into main
All checks were successful
android-ci / android (push) Successful in 11m55s
Reviewed-on: #147
2026-09-22 12:09:18 +00:00
agent
775f2e88be
android: profile screen — nickname + Monero receiving address
All checks were successful
android-ci / android (pull_request) Successful in 12m27s
The phone's half of the TUI's `/profile`. A `Profile` action on the roster's
app bar opens `ui/ProfileScreen.kt`: nickname, bio, and the Monero address
friends pay to, all three loaded from the store and written back through the
core's own validation.

- The address is checked with `uniffi.onionwire_sdk.checkAddress` *before* the
  write, so a typo is refused with the typed text still in the field instead of
  surfacing as a store error afterwards. An empty address is allowed and is
  labelled with its consequence: with no profile address and no running wallet
  child the core has nothing to hand a payer.
- The bio is carried, not owned: a save that did not touch the field writes
  back the value read from the store immediately before the write, so a bio set
  in the TUI cannot be blanked from the phone.
- On save the profile is pushed to **every** friend in the roster, one-shot and
  fail-closed per friend like the TUI's `save_profile`. A push failure is not a
  save failure: the status line always starts with `profile saved` and names the
  count, with each failure listed by petname (else shortened fingerprint).

Every decision the screen makes is a pure function in the new file, covered by
`ProfileDraftTest` (21 cases) on the JVM: the save-button rule (dead until the
read lands, dead while the form is unchanged), the address branch, the bio rule,
label selection and the status-line aggregation.

Verified on AVD ow35 (x86_64 slice, emulator-5560): the roster app bar carries
`Profile`; nickname/bio/address survive `am force-stop` + relaunch; an invalid
address is refused before the write; a save with an empty roster reports
`profile saved`; with one (self-)peer in the roster a save reports
`profile saved · sent to 1 friend`, and with the emulator's network cut the same
save reports `profile saved · sent to 0 of 1 friend · failed: <label>: <tor err>`.
2026-09-22 02:12:32 -04:00
apk-dev
812c259f46
android: saved-wallets screen (list, select, back up the open wallet)
All checks were successful
android-ci / android (pull_request) Successful in 10m37s
The app could hold several wallets and show none of them. Add the screen
that lists the store's catalogue, marks the one the wallet child has open,
switches to another on a tap, and — for the open one only — shows its
recovery phrase and private keys.

Everything secret here belongs to the file the child currently has open:
`query_key` is answered by that file and no other, so the seed card and the
keys card hang off `active_wallet_filename()`, not off a row. On a row that
is not the open one both actions are dead and say why ("open this wallet to
view its backup") instead of opening it under the user — switching wallets
is a deliberate tap, because `open_wallet` stops and restarts a running
child.

The phrase keeps the existing treatment: the wallet screen's own
`SeedBackupCard`, widened from `private` to `internal` rather than copied,
so the gate constants are still the one `SeedBackupGate`. The keys card
shows the view key always and the spend key when there is one; a view-only
wallet says "view-only wallet — no spend key" in words, because `null` is
the wallet's own answer and not a failure. Neither value is logged,
persisted, tagged, or held in saved state, and both are dropped on dispose.

The catalogue is re-read on entry and on Refresh, never cached from app
start, so a wallet created on the wallet screen after this one was first
opened shows up without restarting the app. An empty catalogue ("No saved
wallets yet") and a read failure ("could not read the wallet catalogue" +
the core's text) are rendered as the two different states they are.

The gate is pure Kotlin in the new file and `WalletManagerTest` covers it on
the JVM (17 cases): the row label's name/blank/whitespace fallback, which
child states count as readable, and whether the secret actions are offered
for a row.
2026-09-22 01:23:47 -04:00
573bf4bf8d Merge pull request 'android: collapse the roster identity block into a dropdown' (#146) from onionwire/t_d62da406-android-roster-collapse-the-identity-blo into main
All checks were successful
android-ci / android (push) Successful in 10m20s
Reviewed-on: #146
2026-09-22 04:31:22 +00:00
181c13647a Merge branch 'main' into onionwire/t_d62da406-android-roster-collapse-the-identity-blo
All checks were successful
android-ci / android (pull_request) Successful in 12m1s
2026-09-22 04:31:06 +00:00
0e866c096a Merge pull request 'sdk: expose the wallet catalogue, the open wallet's keys, and the self profile over UniFFI' (#145) from onionwire/t_c9e48c46-onionwire-sdk-expose-the-wallet-catalogu into main
Some checks failed
android-ci / android (push) Has been cancelled
ci / test (push) Successful in 8m8s
ci / sdk (push) Successful in 1m7s
ci / fuzz (push) Successful in 4m53s
Reviewed-on: #145
2026-09-22 04:30:20 +00:00
agent
b6447f76d6
android: collapse the roster identity block into a dropdown
All checks were successful
android-ci / android (pull_request) Successful in 12m26s
The identity card's full fingerprint wraps to several lines on a phone and
pushes the friend list off the first screen. Collapse it: one line by
default (label + `shortId(fingerprint)` + chevron), the full fingerprint and
the full onion behind a tap, in the order they already had.

The `sdk …` line and `keepAliveNote` stay outside the disclosure — the
keep-alive denial is the only place that note appears, so hanging it off a
collapsed block would hide it.

`shortId` is a pure top-level function (`head … tail`, unchanged when the
value is no longer than the abbreviation, empty stays empty) so the collapsed
line is a slice of the value shown expanded, not a parallel encoding. The
expand state is `rememberSaveable`: a rotation keeps what the user chose, and
nothing about it belongs in the store.

RosterIdTest covers the abbreviation on the JVM (7 cases: the 64-hex
fingerprint, the head/tail boundary, custom head/tail, shorter-than-input,
empty, single-char ellipsis).
2026-09-22 00:28:39 -04:00
sirius
5f19a56be3
sdk: expose the wallet catalogue, the open wallet's keys, and the self profile
Some checks failed
ci / test (pull_request) Successful in 5m59s
ci / sdk (pull_request) Successful in 1m35s
android-ci / android (pull_request) Successful in 12m42s
ci / fuzz (pull_request) Has been cancelled
The Android wallet/profile screens had nothing to call: the core could list
wallets, switch the child onto one, read its keys and read/write the self
profile, but none of it crossed UniFFI.

Core:
- Wallet::keys() -> WalletKeys { view_key, spend_key: Option<String> }: two
  query_key calls against the file the RPC has open. A view-only wallet's -29
  is spend_key: None, not an error. WalletKeys' Debug redacts both halves.
- Node::wallet_keys() mirrors wallet_create/wallet_seed; refuses locally when
  no wallet is configured.
- Node::active_wallet_filename() -> Option<String>: the file the child is
  pointed at, None until wallet-child settings exist, so a client can mark the
  open row.

SDK (UniFFI):
- records WalletRow / WalletKeys / SelfProfile, and Wire::{wallets,
  open_wallet, active_wallet_filename, wallet_keys, self_profile,
  set_self_profile, push_self_profile}.
- The rule the clients must express is in the docs: the seed and the private
  keys come from the OPEN wallet, so there is deliberately no accessor that
  reads another saved wallet's secrets without opening it.

docs/WALLET.md (catalogue + 'secrets belong to the open wallet'),
docs/THREAT_MODEL.md (the new on-demand-display exposure surface) and the SDK
README are updated in the same commit.
2026-09-22 00:25:33 -04:00
agent
a9117b8991
Merge PR #144: tui -- read the wallet list from the store and load the chosen wallet
All checks were successful
ci / test (push) Successful in 5m47s
ci / sdk (push) Successful in 1m24s
android-ci / android (push) Successful in 10m42s
ci / fuzz (push) Successful in 4m52s
# Conflicts:
#	docs/TUI.md
#	src/tui.rs
2026-09-21 12:12:12 -04:00
agent
511c9e921d
Merge PR #143: node -- remember a created wallet in the store catalogue 2026-09-21 12:11:19 -04:00
agent
8986724848
tui: read the wallet list from the store and load the chosen wallet
All checks were successful
ci / test (pull_request) Successful in 6m14s
android-ci / android (pull_request) Successful in 12m16s
ci / sdk (pull_request) Successful in 1m30s
ci / fuzz (pull_request) Successful in 4m50s
The selection screen shipped as presentation only: `F6 w` opened its
unavailable state, the rows were never read, and Enter on a wallet said
switching was not wired up. The catalogue, the create path and the screen
all existed; nothing joined them.

- `App::open_wallet_select` builds its rows from `Node::list_wallets` at
  the moment the screen opens (never cached from startup), and a failed
  read is the screen's own error state rather than "no saved wallets".
- `App::choose_wallet` resolves `WalletChoice::Open(index)` against the
  catalogue as it is now — the index is a position, and two saved wallets
  may share an identity key — then loads it. `+ create new wallet` still
  starts the existing create flow.
- `Node::open_wallet(filename)` is the load: it refuses a file the
  catalogue does not hold, re-points the sealed wallet-child record with a
  read-modify-write (the generated RPC creds survive), and restarts a
  running child onto the new file. An idle child takes the change on its
  next start.
- `App::new` starts on the selection screen when the catalogue is
  non-empty and on the create flow when it is empty, so a restart lands on
  the wallets it remembers and a first run has no dead empty list.
- The stored identity/locator stay catalogue columns: a locator rotates
  (F4) and identity is the roster key the node already holds, so the live
  header keeps reading them from the node.
- `SELECT_UNAVAILABLE` is gone with the state it described; docs/TUI.md
  now describes the wired behaviour.

Tests (both new): `Node::open_wallet` over an offline node — the chosen
file, the creds kept across the read-modify-write, the choice surviving a
reopen, and a non-catalogue file refused; and the app path in src/tui.rs
over a real store-backed node — start screen both ways, catalogue mapping,
row index over a shared identity, the create row, and a wallet recorded
after startup appearing the next time the list opens.
2026-09-21 11:43:07 -04:00
agent
d96de1d7f0
tui: wallet selection screen (F6 -> w) with create as the last row
Screen::WalletSelect: a table of saved wallets — name, identity prefix,
locator prefix, creation day — the selected row's full identity and locator
under it, and a `+ create new wallet` row as the last item. j/k or arrows
move, Enter takes the choice, Esc back. Empty, failed and in-flight reads
each get their own copy; a wallet with a NULL label, no published locator or
no usable timestamp reads `(unlabelled)` / `-` / `unknown` rather than blank.

Presentation only. Rows are plain display data (WalletRow) built by the
caller; the render path never reads the store, and the selection is by row
index because two records may share an identity key. Loading a chosen record
into the session is the wallet-store integration step, so the F6 `w` entry
opens the screen on its unavailable state until that accessor lands, and the
create row works today either way.

Evidence: tests/tui_select.rs (16 tests) drives the real draw path through
TestBackend at 80x24, 120x40 and 200x60, pins the dumped frame's footer to
status_footer_phased(..., wallet_select_footer_hint()), asserts exactly one
focus marker, a cell-width line budget from 20 to 200 columns, the window
disclosure with the create row always visible, hostile labels (ESC/BEL/C1/
bidi/newline/tab) and the crate-local UTC date formatter.

(cherry picked from commit 99a4ab640e)
2026-09-21 11:15:44 -04:00
dd7c749373 Merge pull request 'node: remember a created wallet in the store catalogue' (#143) from wt/t_511023b6 into wt/t_64c9ba3c
Reviewed-on: #143
2026-09-21 15:10:36 +00:00
5f1500191e Merge pull request 'tui: wallet selection screen (F6 -> w) with create as the last row' (#142) from wt/t_14ac0a3f into main
Some checks failed
android-ci / android (push) Has been cancelled
ci / test (push) Successful in 7m32s
ci / sdk (push) Successful in 1m14s
ci / fuzz (push) Successful in 4m58s
Reviewed-on: #142
2026-09-21 15:10:17 +00:00
49756d2a2d Merge branch 'main' into wt/t_14ac0a3f
Some checks failed
ci / test (pull_request) Successful in 5m56s
android-ci / android (pull_request) Has been cancelled
ci / sdk (pull_request) Successful in 1m30s
ci / fuzz (pull_request) Has been cancelled
2026-09-21 15:10:10 +00:00
948d9b4b0c Merge pull request 'store: a wallet catalogue in the encrypted db (wallets table + CRUD)' (#141) from wt/t_64c9ba3c into main
All checks were successful
ci / test (push) Successful in 6m0s
ci / sdk (push) Successful in 1m35s
android-ci / android (push) Successful in 11m56s
ci / fuzz (push) Successful in 4m51s
Reviewed-on: #141
2026-09-21 15:09:45 +00:00
agent
0043fa0b34
node: remember a created wallet in the store's catalogue
All checks were successful
ci / test (pull_request) Successful in 5m53s
ci / sdk (pull_request) Successful in 1m35s
android-ci / android (pull_request) Successful in 12m30s
ci / fuzz (pull_request) Successful in 4m55s
A wallet created in-app was never remembered: `Node::wallet_create` called
the RPC and returned the seed, and the wallet file name was the one
hardcoded `wallet::DEFAULT_WALLET_FILENAME` ("onionwire"). A second create
reused that name, so the RPC refused it (or opened the first wallet's
file) and no row was ever written — the "cannot create a new wallet, and
nothing survives a restart" report.

Creation and import now go through the catalogue (t_64c9ba3c's
`Store::{create_wallet,list_wallets}`):

- each create/import gets its own file name, `onionwire-<n>` for the first
  `n` the catalogue does not hold, so several wallets coexist;
- the stored row (id, identity, locator, file, created_at) is returned:
  `Node::wallet_create` -> `CreatedWallet` (row + the one-time seed, with a
  redacting `Debug`), `Node::wallet_restore` -> `WalletRecord`;
- `Node::list_wallets` reads the catalogue without dialing;
- the child config is re-pointed at the new file (read-modify-write, so the
  sealed RPC creds survive) — a row the child never opens would still be a
  broken wallet.

The SDK keeps its UniFFI signature (`create_wallet -> String` seed,
`import_wallet -> ()`), so no Kotlin change: it unwraps `.seed`.

TDD: 5 new `src/node.rs` cases (row + list, two wallets + reopen, import,
wallet-off empty list, child re-pointed) over a loopback wallet-RPC mock.
`cargo test --locked` exit 0, `cargo clippy --locked --all-targets -- -D
warnings` clean, and the same two commands are clean in
`crates/onionwire-sdk`.
2026-09-21 10:57:55 -04:00
agent
99a4ab640e
tui: wallet selection screen (F6 -> w) with create as the last row
All checks were successful
ci / test (pull_request) Successful in 5m58s
android-ci / android (pull_request) Successful in 12m2s
ci / sdk (pull_request) Successful in 1m28s
ci / fuzz (pull_request) Successful in 4m46s
Screen::WalletSelect: a table of saved wallets — name, identity prefix,
locator prefix, creation day — the selected row's full identity and locator
under it, and a `+ create new wallet` row as the last item. j/k or arrows
move, Enter takes the choice, Esc back. Empty, failed and in-flight reads
each get their own copy; a wallet with a NULL label, no published locator or
no usable timestamp reads `(unlabelled)` / `-` / `unknown` rather than blank.

Presentation only. Rows are plain display data (WalletRow) built by the
caller; the render path never reads the store, and the selection is by row
index because two records may share an identity key. Loading a chosen record
into the session is the wallet-store integration step, so the F6 `w` entry
opens the screen on its unavailable state until that accessor lands, and the
create row works today either way.

Evidence: tests/tui_select.rs (16 tests) drives the real draw path through
TestBackend at 80x24, 120x40 and 200x60, pins the dumped frame's footer to
status_footer_phased(..., wallet_select_footer_hint()), asserts exactly one
focus marker, a cell-width line budget from 20 to 200 columns, the window
disclosure with the create row always visible, hostile labels (ESC/BEL/C1/
bidi/newline/tab) and the crate-local UTC date formatter.
2026-09-21 10:41:53 -04:00
rust-dev (hermes)
467510f096
store: a wallet catalogue in the encrypted db
All checks were successful
ci / test (pull_request) Successful in 5m48s
ci / sdk (pull_request) Successful in 1m34s
android-ci / android (pull_request) Successful in 12m4s
ci / fuzz (pull_request) Successful in 18m24s
Wallets were only ever a file in $ONIONWIRE_HOME/wallet plus the
single-row wallet_child config for the one the child is currently
pointed at, so a created wallet was not remembered and a second create
had nowhere to go.

Add a 'wallets' table (id, name, identity_pubkey, onion_locator,
wallet_filename, created_at) and CRUD on Store: create_wallet,
get_wallet_by_id, list_wallets, delete_wallet. wallet_filename is
UNIQUE so a second wallet cannot silently reuse the first one's file,
and identity_pubkey is deliberately not unique (identity is the roster
key, a wallet is a file; the locator may rotate or be empty).

No new crate: the store is already rusqlite + SQLCipher with a raw
PRAGMA key, and sqlx has no SQLCipher path, so a second pool would be a
second unencrypted way in.

Tests: 5 store cases in tests/store.rs (round-trip, coexistence across
a reopen, duplicate filename, delete, blank label/filename) plus the
at_rest upgrade case in src/store.rs.
2026-09-21 10:21:48 -04:00
2256d036d5 Merge pull request 'android: block the wallet screen on an unbacked seed, and let it be re-shown' (#139) from onionwire/t_9b2544a7-wallet-screen-block-on-an-unbacked-seed into main
All checks were successful
android-ci / android (push) Successful in 10m15s
Reviewed-on: #139
2026-09-20 16:14:29 +00:00
agent
118191c541
android: block the wallet screen on an unbacked seed, and make it re-showable
All checks were successful
android-ci / android (pull_request) Successful in 10m35s
A created wallet's seed was two lines of small text at the bottom of the
wallet page, dismissed by one tap, gone for good once the screen was left.
A real user created a wallet, never saw the seed, and the app had no way to
show it again.

- `SeedBackupGate` (new, pure Kotlin): the confirm word `SEEN` and its
  case-insensitive match mirror the TUI's own `WalletSetup::CreateSeed`
  gate; create starts unbacked, import is backed up without the gate, and
  only a correct word can confirm.
- The seed card is the whole body until the word is typed and Done is
  tapped: no Cancel, no copy button (the Android clipboard is readable by
  every other app), Done dead until `SEEN`.
- "Back up seed" re-reads the seed through the new `Wire::wallet_seed()`
  (`WireViewModel.walletSeed()`), so a seed missed the first time is not
  lost. Its failure is shown next to the button, not at the bottom of a
  long scroll.
- While unconfirmed: a warning strip stays at the top of the wallet screen
  and the receive address and Show QR are hidden — XMR received into a
  wallet whose 25 words were never written down is unrecoverable.
- The flag lives in app-local prefs (`wallet_seed_backup`), not in the
  Keystore-wrapped store, and is reset by `createWallet` itself so no
  caller can forget it.

The stored flag is nullable, and the null is load-bearing. `false` means
this install created a wallet and nobody has confirmed the seed, so the
strip is up whether or not the balance reads. `null` means nothing is
stored — an install that predates the flag, or one that has never created
a wallet here — and there the strip waits for `wallet_balance` to return a
real amount, the core's own evidence that the child has a wallet open.
Without that distinction a first-run user who had configured a chain
source but not yet created a wallet (`wallet_balance` returns "err") would
be warned about a seed they do not have.

The app-bar Back still leaves the screen, deliberately — it is the TUI's
`Esc`. It costs nothing now, because leaving no longer loses the seed.

Verification: `./gradlew :app:testDebugUnitTest` green, 135 tests
(`SeedBackupGateTest` 18 of them).
2026-09-20 12:15:47 -04:00
94d29b8354 Merge pull request 'wallet: expose an on-demand seed accessor over core + UniFFI' (#138) from onionwire/t_2142490d-wallet-seed-expose-an-on-demand-seed-acc into main
All checks were successful
ci / test (push) Successful in 5m22s
ci / sdk (push) Successful in 1m8s
ci / fuzz (push) Successful in 4m51s
android-ci / android (push) Successful in 10m7s
Reviewed-on: #138
2026-09-20 16:13:28 +00:00
agent
145036fda8
wallet: expose an on-demand seed accessor over core + UniFFI
All checks were successful
ci / test (pull_request) Successful in 5m43s
ci / sdk (pull_request) Successful in 1m21s
android-ci / android (pull_request) Successful in 11m53s
ci / fuzz (pull_request) Successful in 4m53s
Wallet::create_wallet returned the 25-word seed exactly once and nothing
could reach it afterwards, so a seed that was never backed up at creation
was unrecoverable. Add Wallet::mnemonic() (one query_key mnemonic call on
the open wallet file), Node::wallet_seed() mirroring wallet_create, and the
additive UniFFI export Wire::wallet_seed() -> Kotlin Wire.walletSeed().

No existing signature changes. The refusals stay leak-free: an unconfigured
wallet gets NOT_CONFIGURED_MSG without a dial, a watch-only wallet keeps the
RPC's -29 view-only mapping, and no error string carries the RPC login.

Tests (tests/wallet.rs) drive the per-connection Digest mock: the words come
back verbatim, a JSON-RPC error surfaces without the login or endpoint, a
rejected digest refusal does not leak the password, and an unconfigured
wallet is refused without dialing.
2026-09-20 11:53:19 -04:00
3769bd9a42 Merge pull request 'wallet: answer the Digest challenge on the connection that issued it' (#137) from fix/wallet-rpc-digest-same-connection into main
All checks were successful
ci / test (push) Successful in 5m18s
ci / sdk (push) Successful in 1m13s
ci / fuzz (push) Successful in 4m58s
android-ci / android (push) Successful in 11m38s
Reviewed-on: #137
2026-09-20 13:30:21 +00:00
sirius
cb411da813
wallet: answer the Digest challenge on the connection that issued it
All checks were successful
ci / test (pull_request) Successful in 5m37s
ci / sdk (pull_request) Successful in 1m21s
ci / fuzz (pull_request) Successful in 4m52s
android-ci / android (pull_request) Successful in 12m15s
monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the
`http_server_auth` lives inside `http_custom_handler`, which is created per
connection, so its nonce starts empty and any request without a valid
`Authorization` field mints a fresh one. The client opened a *second* connection
for the authenticated retry, presenting a nonce that socket never issued — so a
real wallet RPC answered 401 forever, however correct the login was. That is the
`wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the
canned mocks replayed the challenge on any socket, so they stayed green.

- `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry,
  no `Connection: close` on the challenge (epee closes the socket with the 401
  when the request asks for it), `read_one_response` honouring `Content-Length`
  (a keep-alive response never ends in EOF; with no length the body ends at EOF,
  which is what keeps the 1 MiB cap meaningful for an open RPC).
- A 401 after our *own* challenge now reads: the login does not match the
  child's `--rpc-login`.
- Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce:
  `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one
  connection, and a nonce presented on another connection is refused.
- `docs/WALLET.md`: what a 401 means and why it is not the flow.

Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`,
`--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401
Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
2026-09-20 09:17:05 -04:00
b805bd4ad9 Merge pull request 'docs(android): the APK poller now calls wallet_child_refresh' (#136) from onionwire/t_4afe292a-android-docs-live-poller into main
All checks were successful
android-ci / android (push) Successful in 11m16s
Reviewed-on: #136
2026-09-20 12:47:24 +00:00
agent
0a8105584f
docs(android): the APK poller now calls wallet_child_refresh
All checks were successful
android-ci / android (pull_request) Successful in 10m19s
#135 merged against fa0e4b2-era docs that said the loop was still
wallet_status. #134 already landed: first paint is cached, every later
tick is Wire::wallet_child_refresh.
2026-09-20 00:56:08 -04:00
53b5e6c762 Merge pull request 'docs(android): rewrite the Android docs to match the tree' (#135) from onionwire/t_4afe292a-docs-android-audit-rewrite-the-android-d into main
All checks were successful
android-ci / android (push) Successful in 10m12s
Reviewed-on: #135
2026-09-20 04:53:12 +00:00
agent
c65946bfd5
docs(android): rewrite Android docs to match the tree
All checks were successful
android-ci / android (pull_request) Successful in 10m14s
android/README.md, CUPRATE_DAEMON.md and MONERO_BINARIES.md were the
half PR #133 left out. Releases are two manual dispatches, not a push
to main; the APK version comes from the tag android-release checks out;
the layout now includes wallet/ and keepalive/; the status line's
sync h/t is documented; the APK poller still calls wallet_status, not
wallet_child_refresh.
2026-09-20 00:52:43 -04:00
d2d49d27c5 Merge pull request 'android: poll the live wallet-child probe so the wallet sync line moves' (#134) from wt/t_07542df0 into main
All checks were successful
android-ci / android (push) Successful in 10m26s
Reviewed-on: #134
2026-09-20 04:48:14 +00:00
Lance
4d2528351b
android: poll the live wallet-child probe so the sync line moves
All checks were successful
android-ci / android (pull_request) Successful in 10m51s
The wallet screen's 2s loop read Wire::wallet_status, which only re-reads the
snapshot the last probe left in the store — so the `sync h/t` segment sat frozen
until a chain-mode tap ran start_wallet_child (which probes on its way out).

The loop now paints once from the cached read (non-dialing, so the screen has a
record immediately) and then calls Wire::wallet_child_refresh for every tick:
one live probe of the child's loopback wallet RPC, and of the configured local
daemon's get_info when that RPC does not answer. Same 2s cadence, same
Dispatchers.IO, same sticky walletChildError, same one-poller guarantee.

The loop is a top-level function taking its two reads as parameters, which is
the only seam a JVM test has — requireWire() is NodeHost.requireOpen(), a
process-global only a real Arti bootstrap sets. WalletChildRefreshLoopTest pins
that the cached read paints exactly once and every tick after it is the live
probe, that a probe slower than the tick is never overlapped, and that
cancelling the loop (leaving the screen) stops the dialing.
2026-09-20 00:48:57 -04:00
fa0e4b2f6c Merge pull request 'sdk: expose a live wallet-child probe over UniFFI (wallet_child_refresh)' (#132) from wt/t_0a355a62 into main
All checks were successful
android-ci / android (push) Successful in 12m2s
ci / test (push) Successful in 5m15s
ci / sdk (push) Successful in 1m7s
ci / fuzz (push) Successful in 5m3s
Reviewed-on: #132
2026-09-20 04:32:38 +00:00
803567635f Merge pull request 'docs: rewrite README + docs to match main (audit in PR body)' (#133) from onionwire/t_96d3bd1a-docs-audit-the-onionwire-source-against into wt/t_0a355a62
All checks were successful
android-ci / android (pull_request) Successful in 12m13s
ci / test (pull_request) Successful in 5m16s
ci / sdk (pull_request) Successful in 1m6s
ci / fuzz (pull_request) Successful in 4m54s
Reviewed-on: #133
2026-09-20 04:30:46 +00:00
agent
f95c1e7ca7
docs: rewrite README and living docs to match the tree
Audit the operator docs against the source: pin downloads to v0.14.0,
document the real CLI/flags/env/F-keys (including F9, no F7), keep 18081
as the app-owned daemon port, describe the local chat outbox vs a
server-side one, and stop implying SECURITY_AUDIT.md is a third-party
audit. Spike reports stay; they get a status header only.
2026-09-20 00:31:07 -04:00
rust-dev
db12f4838b
sdk: expose wallet_child_refresh — a live wallet-child probe over UniFFI
All checks were successful
ci / test (pull_request) Successful in 5m16s
ci / sdk (pull_request) Successful in 1m17s
android-ci / android (pull_request) Successful in 13m18s
ci / fuzz (pull_request) Successful in 18m36s
Wire::wallet_status() is the cheap cached read (no dial); only
Node::wallet_child_refresh() writes state/height/target_height, and it was
reachable over UniFFI from exactly one place — start_wallet_child. An Android
refresh loop polling wallet_status() therefore shows a frozen sync line.

Add the additive export, reusing the existing child_status mapper so the record
is the same shape as wallet_status(), and the core probe as the only probe
path. Docs: one sentence in docs/WALLET.md, which enumerates the SDK
wallet-child surface.

Tests: SDK-level (a Wire cannot be built offline in this crate — open_wire
bootstraps Arti): the unprobed child maps to the same 'off' record both reads
report, pinned with an exhaustive record literal; and the probe on a stopped
handle is a typed WireError.Stopped.
2026-09-20 00:20:32 -04:00
69a7b106ee Merge pull request 'android: show chain sync height on the wallet status line (onto main)' (#131) from onionwire/android-sync-height-on-main into main
Some checks failed
android-ci / android (push) Has been cancelled
Reviewed-on: #131
2026-09-20 02:59:26 +00:00
agent
e697045515
android: show the chain daemon's sync height on the wallet status line
All checks were successful
android-ci / android (pull_request) Successful in 12m45s
The SDK surface from the rust-dev parent (#129) carries `WalletChildStatus.height`
and `target_height` (Rust `u64` → generated Kotlin `ULong`), so the wallet status
line can say how far the chain daemon has got instead of only naming it.

* `WalletChildInput` mirrors both fields as `ULong` — checked against the
  generated `uniffi.onionwire_sdk.WalletChildStatus`, not assumed. Defaults stay
  `0uL` so every existing fixture is unchanged.
* `walletChildLine` appends ` · sync h/t` after the source and the `node` segment,
  before the error em-dash, and only when either value is non-zero: `0/0` is
  unknown (probe failed, daemon not up), not `0%`, and a zero target still prints
  as `/0`. No percent, no progress bar, no ETA.
* `WalletScreen.toInput()` copies both fields field-for-field; the status row's
  screen-reader sentence moved into `walletChildStatusDescription`, which carries
  the same `sync h/t` the eye reads. One line, still no second widget.
* Tests cover the three sync cases plus the spoken row; the old exact-line
  assertions (`off · receive-only`, `connecting · local node`,
  `ready · remote onion daemon`) are untouched. `:app:testDebugUnitTest`: 114
  tests, 0 failures.
* `android/CUPRATE_DAEMON.md` no longer claims the record has no height field.
2026-09-19 22:59:09 -04:00
d203594294 Merge pull request 'wallet: show the chain daemon's sync height/target on the child status' (#129) from onionwire/t_bd2e2cd0-onionwire-wallet-show-daemon-sync-height into main
All checks were successful
ci / test (push) Successful in 5m19s
ci / sdk (push) Successful in 1m15s
ci / fuzz (push) Successful in 5m30s
android-ci / android (push) Successful in 12m9s
Reviewed-on: #129
2026-09-20 00:12:16 +00:00
onionwire
0a91744924
wallet: show the chain daemon's sync height and target on the child status
All checks were successful
ci / test (pull_request) Successful in 5m50s
ci / sdk (pull_request) Successful in 1m34s
ci / fuzz (pull_request) Successful in 4m54s
android-ci / android (pull_request) Successful in 12m39s
The user watching an in-process Cuprate node on Android saw only a phase
word (connecting, with 'wallet connect: Connection refused (os error
111)') and asked to see height vs tip.

- WalletChildStatus gains height / target_height, and line() appends
  'sync h/t' when a probe read either number. No percentage is invented
  when the daemon reports no target (h/0 is honest), and an off/exited
  child reports 0/0.
- Node::wallet_child_refresh fills them: one wallet-RPC get_info now
  answers both the readiness gate and the numbers (Wallet::chain_info,
  with chain_ready built on the same parse), and when the wallet RPC is
  down while the chain source is local/in-process, the loopback daemon
  is asked directly (ChildConfig::daemon_probe_addr). A refused daemon
  stays 0/0 — unknown, not caught up. Only refresh dials; the draw path
  reads two atomics.
- UniFFI WalletChildStatus carries the same two u64 fields so Android can
  show them; SDK test covers the round trip.

Tests: cargo test --locked --target x86_64-unknown-linux-gnu (all
green), clippy -D warnings clean; crates/onionwire-sdk cargo test
--locked + clippy clean (separate workspace).
2026-09-19 19:38:52 -04:00
bc74b4f4af Merge pull request 'fix(cuprate): seed XDG so Android parse does not poison LazyLock' (#128) from onionwire/cuprate-android-xdg into main
Some checks failed
ci / test (push) Failing after 3m44s
ci / sdk (push) Successful in 1m9s
ci / fuzz (push) Successful in 4m57s
android-ci / android (push) Successful in 11m32s
Reviewed-on: #128
2026-09-19 21:56:12 +00:00
agent
c00c9d4151
fix(cuprate): seed XDG so Android parse does not poison LazyLock
All checks were successful
ci / sdk (pull_request) Successful in 1m7s
ci / test (pull_request) Successful in 5m20s
ci / fuzz (pull_request) Successful in 5m2s
android-ci / android (pull_request) Successful in 12m23s
Cuprate's serde defaults call ArtiConfig::default, which unwraps
dirs::data_dir(). On Android HOME is unset and dirs-sys has no
getpwuid fallback, so the first Start panics and a retry reports
"LazyLock instance has previously been poisoned". Point XDG at the
chain datadir before parse and set tor.arti.directory_path in TOML.
2026-09-19 17:54:44 -04:00
fb87903137 Merge pull request 'fix(cuprate): catch launch panics and give the thread 8 MiB stack' (#127) from onionwire/cuprate-launch-panic into main
All checks were successful
ci / test (push) Successful in 5m16s
ci / sdk (push) Successful in 1m9s
android-ci / android (push) Successful in 10m46s
ci / fuzz (push) Successful in 5m1s
Reviewed-on: #127
2026-09-19 19:47:40 +00:00
agent
a7daf2c768
fix(cuprate): catch launch panics and give the thread 8 MiB stack
All checks were successful
ci / test (pull_request) Successful in 5m25s
ci / sdk (pull_request) Successful in 1m12s
android-ci / android (pull_request) Successful in 10m50s
ci / fuzz (pull_request) Successful in 4m59s
Android's default pthread stack is ~1 MiB. Cuprate+RandomX overflow it,
the launch thread dies before tx.send, and the UI only says "the launch
thread died before answering". Catch unwind so a Rust panic is the error
string, and size the launch thread plus tokio workers at 8 MiB.
2026-09-19 15:47:51 -04:00
0c21eb7bf0 fix(android): tapping a Cuprate mode starts the node (#126)
All checks were successful
android-ci / android (push) Successful in 11m48s
fix(android): tapping a Cuprate mode starts the node
2026-09-19 18:45:02 +00:00
agent
3868452a4a
fix(android): tapping a Cuprate mode starts the node
All checks were successful
android-ci / android (pull_request) Successful in 12m50s
Selecting mainnet pruned only persisted ChainConfig, so the screen
updated the storage line and nothing else. Store, then Start when the
storage floor allows. Filled button is the stored choice.
2026-09-19 14:33:30 -04:00
82d6dd9082 Merge pull request 'feat(wallet): mainnet pruned and full on-device chain modes' (#125) from onionwire/chain-mainnet-pruned-full into main
All checks were successful
ci / test (push) Successful in 5m8s
ci / sdk (push) Successful in 1m13s
ci / fuzz (push) Successful in 4m54s
android-ci / android (push) Successful in 12m17s
Reviewed-on: #125
2026-09-19 17:34:33 +00:00
95ca45dc17 Merge branch 'main' into onionwire/chain-mainnet-pruned-full
All checks were successful
ci / test (pull_request) Successful in 5m19s
ci / sdk (pull_request) Successful in 1m8s
ci / fuzz (pull_request) Successful in 4m48s
android-ci / android (pull_request) Successful in 12m8s
2026-09-19 17:08:55 +00:00
agent
5080652e3b
feat(wallet): mainnet pruned and full on-device chain modes
All checks were successful
ci / test (pull_request) Successful in 5m45s
ci / sdk (pull_request) Successful in 1m34s
ci / fuzz (pull_request) Successful in 4m51s
android-ci / android (pull_request) Successful in 13m2s
Cuprate in-process and TUI keys 1/2/3 pick mainnet pruned, mainnet
full, or experimental testnet. Datadirs are split so a prune store
cannot mix with a full one. Android storage floors scale with the
choice. Cuprate remains pre-production; mainnet is unvalidated.
2026-09-19 12:54:35 -04:00
cd1acd3c0d Merge pull request 'android: Start wallet no longer looks like a no-op while Cuprate launches' (#124) from onionwire/android-cuprate-start-feedback into main
All checks were successful
ci / test (push) Successful in 5m8s
ci / sdk (push) Successful in 1m7s
ci / fuzz (push) Successful in 4m55s
android-ci / android (push) Successful in 12m14s
Reviewed-on: #124
2026-09-19 16:39:10 +00:00
agent
0acf89a0b4
android: Start wallet no longer looks like a no-op while Cuprate launches
All checks were successful
ci / test (pull_request) Successful in 5m34s
ci / sdk (pull_request) Successful in 1m22s
android-ci / android (pull_request) Successful in 10m48s
ci / fuzz (pull_request) Successful in 4m52s
Tapping Start held the SQLCipher mutex for the whole in-process Node::launch
and blocked the UniFFI tokio worker, so wallet_status stayed off with no
error. Drop the store lock until creds are needed, spawn_blocking the sync
start, and show that Start is in flight.

The APK still runs Cuprate testnet only; this does not add mainnet or prune.
2026-09-19 12:03:01 -04:00
2df10124ef Merge pull request 'fix(tui): invite payload gets a chrome-free region so mouse-copy is exact' (#122) from onionwire/t_af8b509e-onionwire-tui-invite-mouse-copy-must-not into main
Some checks failed
ci / test (push) Successful in 5m17s
android-ci / android (push) Has been cancelled
ci / sdk (push) Successful in 1m5s
ci / fuzz (push) Successful in 4m48s
Reviewed-on: #122
2026-09-19 14:46:42 +00:00
87196e2297 Merge branch 'main' into onionwire/t_af8b509e-onionwire-tui-invite-mouse-copy-must-not
All checks were successful
ci / test (pull_request) Successful in 5m17s
ci / sdk (pull_request) Successful in 1m11s
ci / fuzz (pull_request) Successful in 4m52s
android-ci / android (pull_request) Successful in 12m17s
2026-09-19 14:46:33 +00:00
04fa7ec7f1 Merge pull request 'tui: peer payment history behind the F9 payments row (key p)' (#121) from onionwire/t_ef1d35d2-tui-payments-row-on-f9-render-peer-payme into main
All checks were successful
ci / test (push) Successful in 5m12s
ci / sdk (push) Successful in 1m5s
ci / fuzz (push) Successful in 4m48s
android-ci / android (push) Successful in 11m51s
Reviewed-on: #121
2026-09-19 12:59:59 +00:00
0c00c6f912 Merge branch 'main' into onionwire/t_ef1d35d2-tui-payments-row-on-f9-render-peer-payme
All checks were successful
ci / test (pull_request) Successful in 5m13s
ci / sdk (pull_request) Successful in 1m6s
ci / fuzz (pull_request) Successful in 4m45s
android-ci / android (pull_request) Successful in 11m59s
2026-09-19 12:59:51 +00:00
agent
c1d13178b6
tui: settings-menu frame dumps use the footer the app renders
All checks were successful
ci / test (pull_request) Successful in 5m17s
ci / sdk (pull_request) Successful in 1m8s
ci / fuzz (pull_request) Successful in 4m50s
android-ci / android (pull_request) Successful in 10m19s
The same defect as the peer-payments fixture, one screen over: after the
clean-look chrome redesign (now merged) `App::draw` renders the F9 menu's one
status line with `status_footer_phased` and the hint from `footer_hints`, while
`tests/tui_spec.rs::render_menu` still built a phase-free `status_footer` from a
hand-copied hint string — so every menu frame in the PR body showed a footer the
app does not draw (no Tor phase).

- `wallets_settings_footer_hint()` is now the single source for that hint, the
  way `peer_payments_footer_hint()` is for the history screen.
- `render_menu` makes the app's own two calls, `TorPhase::Ready` for the
  healthy-wallet state the fixture describes.
- `wallets_settings_menu_frame_shows_the_shipped_footer` pins the dumped frame's
  last line to the shipped one (RED first: the fixture's line read
  `TOR  me:… Esc back c copy ? help`, the app's `✓ TOR ready  me:…`).

`cargo test --locked` 384 passed / 0 failed, clippy clean.
2026-09-19 01:18:47 -04:00
agent
e9b4156cf5
ci: re-trigger android-ci for cbe8890 (run 458 was cancelled after 19s)
All checks were successful
ci / test (pull_request) Successful in 5m13s
ci / sdk (pull_request) Successful in 1m5s
ci / fuzz (pull_request) Successful in 4m52s
android-ci / android (pull_request) Successful in 10m38s
The merge commit cbe8890 got a green ci/test and ci/sdk, but its android-ci run
(actions/runs/458) was cancelled by the runner 19 seconds in, which Forgejo
records as a failure on the commit. Nothing in this commit changes the tree;
it exists so the android job runs against the same content.
2026-09-19 01:06:00 -04:00
ca4c2c4562 Merge pull request 'fix(android): the SDK linked static bionic, so openWire segfaults at dlopen and the app dies after the passphrase' (#123) from wt/android-sdk-libc-link into main
All checks were successful
android-ci / android (push) Successful in 10m27s
Reviewed-on: #123
2026-09-19 04:40:48 +00:00
apk-dev
519f0e66c3
fix(android): link the SDK against the dynamic libc, not static bionic
All checks were successful
android-ci / android (pull_request) Successful in 30m59s
`openWire` segfaults at `dlopen` on every ABI, so the app dies the moment the
passphrase is submitted and the onion never publishes. The tombstone:

    signal 11 (SIGSEGV), fault addr 0x0
    #00 libonionwire_sdk.so (getauxval+21)
    #01 libonionwire_sdk.so (__cxa_atexit+604)
    #02 libonionwire_sdk.so (_GLOBAL__sub_I_superscalar.cpp+891)
    #06 libjnidispatch.so (Java_com_sun_jna_Native_open+68)
    #42 uniffi.onionwire_sdk.Onionwire_sdkKt.openWire+0

`_GLOBAL__sub_I_superscalar.cpp` is RandomX's, and RandomX arrived with the
`cuprate-daemon` feature (#113). It calls `getauxval` from a static
initializer — and `libonionwire_sdk.so` had linked bionic **statically**, so
that `getauxval` read an auxv vector only the dynamic linker ever fills in.
The first SDK call is the first `dlopen`, which is the first time anything
touches the library: the crash lands exactly on "user typed the password".

The static libc came in with the same commit that added the C++ link flags.
`linkFlags()` passes `-L<ndk>/sysroot/usr/lib/<triple>` for the libc++
archives; that directory also holds the static `libc.a`, while the dynamic
`libc.so` stub lives in the per-API subdirectory that cargo-ndk's linker
wrapper normally supplies — and that wrapper is bypassed on purpose here, so
the per-API directory was no longer on the search path at all and `-lc`
resolved to `libc.a`. Both directories are now passed, the per-API one first,
and `verifyDynamicLibc` fails the build if `libc.so` ever leaves DT_NEEDED
again.

    before (v0.9.0 arm64): NEEDED liblog.so only, local getauxval/__cxa_atexit
    after:                 NEEDED libstdc++.so, libdl, liblog, libm, libc.so, no local libc

Also: the keep-alive notice is re-announced with the locator once the node
publishes. It is anchored at the Open tap with an empty onion (so the shade
does not claim a reachable node while Tor bootstraps), and only the
POST_NOTIFICATIONS callback ever replaced it — on a device that already
granted notifications there is no callback at all, so the notice claimed
"OnionWire is starting" forever.
2026-09-19 00:40:02 -04:00
agent
cbe889024b
Merge origin/main into the peer-payments branch
Some checks failed
android-ci / android (pull_request) Has been cancelled
ci / test (pull_request) Successful in 5m44s
ci / sdk (pull_request) Successful in 1m26s
ci / fuzz (pull_request) Successful in 4m45s
main moved under this PR when #120 (clean-look chrome redesign) landed, which
touched the same three files (src/tui.rs, tests/tui_spec.rs, docs/TUI.md) and
left PR #121 unmergeable.

- docs/TUI.md: both sections kept — the peer-payment-history section from this
  branch, then #120's chrome-redesign section.
- tests/tui_spec.rs: #120's `fit_cells` flake relaxation kept (it is a superset
  of the one on this branch: same cut point plus the ellipsis assertion).
- src/tui.rs merged cleanly; `cargo test --locked` 383 passed / 0 failed and
  `cargo clippy --locked --all-targets -- -D warnings` clean afterwards.

The peer-payments frames are byte-identical after the merge, so the dumps in
this PR body still hold.
2026-09-19 00:36:38 -04:00
agent
b8fefe9c18
tui: F9 works on the peer-payments screen, and frames dump the real footer
Some checks failed
ci / test (pull_request) Successful in 6m33s
ci / sdk (pull_request) Successful in 1m31s
ci / fuzz (pull_request) Successful in 4m49s
android-ci / android (pull_request) Has been cancelled
Review round 1 on the F9 `payments` row found two false affordances.

1. `footer_hints(Screen::PeerPayments)` prints `F9 menu`, and docs/TUI.md says
   F9 reopens the menu, but the `KeyCode::F(9)` arm opened it only from
   `Screen::Main`, so pressing F9 on the peer history did nothing.

   The function keys are now routed through one table, `function_key_for(screen,
   code)`, and the F9 arm no longer has the Main-only guard: it opens (or
   reopens) the menu from `Main`, `WalletsSettings` and `PeerPayments`. A screen
   that names a key has to answer it while it is open — that is what the table
   encodes, and `mod function_key_tests` locks it, including a test that reads
   the screen's own hint and asserts every `F<n>` it names is answered there.

2. The PR's frame dumps passed `"Esc back  up/down select  ? help"` to
   `status_footer` by hand, so every dumped frame showed a footer the app never
   renders. `peer_payments_footer_hint()` is now the single source both
   `footer_hints` and the fixture read, and
   `peer_payments_frame_shows_the_shipped_footer` pins the dumped frame's last
   line to the shipped one.

Also restores the rustfmt-only reflow of unrelated tests in `tests/tui_spec.rs`
(`queued_row`, a `failed_row` call, `rgb_tokens_…`, `alert_line_…`), keeping this
card's real edits there.

Presentation only: no wire, store, session, send-path or `Node` change.
2026-09-19 00:31:42 -04:00
5ae9a8f7aa Merge pull request 'tui: clean-look chrome redesign (one accent, honest tor phase, real frames)' (#120) from onionwire/t_bcf0ae45-onionwire-tui-clean-look-chrome-redesign into main
Some checks failed
android-ci / android (push) Has been cancelled
ci / test (push) Successful in 5m7s
ci / sdk (push) Successful in 1m6s
ci / fuzz (push) Has been cancelled
Reviewed-on: #120
2026-09-19 04:19:47 +00:00
8cbdcbbd94 Merge branch 'main' into onionwire/t_bcf0ae45-onionwire-tui-clean-look-chrome-redesign
All checks were successful
ci / test (pull_request) Successful in 5m46s
ci / sdk (pull_request) Successful in 1m30s
ci / fuzz (pull_request) Successful in 4m40s
android-ci / android (pull_request) Successful in 10m28s
2026-09-19 04:19:35 +00:00
b46d858a4d Merge pull request 'node: expose peer payment history (Node::list_payments)' (#119) from onionwire/t_21787cec-node-expose-peer-payment-history-node-li into main
Some checks failed
android-ci / android (push) Has been cancelled
ci / test (push) Has been cancelled
ci / sdk (push) Has been cancelled
ci / fuzz (push) Has been cancelled
Reviewed-on: #119
2026-09-19 04:09:05 +00:00
agent
c3116eb19e
fix(tui): invite payload gets a chrome-free region so mouse-copy is exact
Some checks failed
android-ci / android (pull_request) Has been cancelled
ci / test (pull_request) Has been cancelled
ci / sdk (pull_request) Has been cancelled
ci / fuzz (pull_request) Has been cancelled
Mouse-selecting the invite copied the pane border: draw_share rendered the
payload inside themed_block, which is Borders::ALL, so every wrapped row sat
between a leading and a trailing glyph. OnionWire enables no mouse capture,
so the terminal's own drag-select is the copy path and it picks up chrome.

The payload now has its own region — flush at column 0, full frame width,
no block, no title, no gutter on any row it occupies — with the block
(title, fp, onion, copy hint) above it. Measured in cells, not chars.

Also add C: OSC 52 hand the payload to the terminal clipboard (same
sequence the F9 menu uses), with the key named on the screen and the mouse
selection named as the fallback for terminals that block the sequence.

Regression tests reconstruct the payload out of the rendered frame at
80x24, 120x40, 200x60 and 60x20 (they fail on base: the leading border
column) and assert no payload row carries a border glyph.
2026-09-18 23:54:07 -04:00
Lance Walters
2fa3466019
tui: peer payment history behind the F9 payments row (key p)
All checks were successful
ci / test (pull_request) Successful in 5m47s
ci / sdk (pull_request) Successful in 1m28s
ci / fuzz (pull_request) Successful in 4m51s
android-ci / android (pull_request) Successful in 10m36s
The F9 / `/settings` menu's only payment row showed the wallet's own transfer
list (`Node::wallet_recent_transfers`, F6). The signed `/pay` invoices and
`/tip` receipts a peer sent live in the `payments` table and had no path from
the TUI, so they were invisible. `Node::list_payments` (PR #119) closes that
gap; this wires it into a screen.

- `Screen::PeerPayments { state }` + `PeerPaymentsState` /
  `PeerPaymentRow`, built by `PeerPaymentsState::from_payments` from
  `Node::list_payments`' rows (newest first: the store returns `payments.id`
  ascending, the screen windows the vector).
- Key handler: `p` on the F9 screen opens it (`open_peer_payments`); `up`/`down`
  (or `k`/`j`) move the selection, `Esc` goes back, `F9` reopens the menu.
- Rows carry direction, kind, amount (`pay::atomic_to_xmr_str`, the same
  piconero formatter the chat lines use), memo (sanitized at draw time) and the
  receipt's `verified` / `unverified` word; the focused row is marked with `>`
  and bold. The selected row's txid and address sit under the rows — the
  address wrapped over two lines rather than clipped.
- States: populated, `no payments with {peer}`, `could not read payments`, and
  a menu row that refuses when no friend is selected. An empty history is a
  state, never an error.
- Menu: the wallet's own list is retitled `transfers` (F6, unchanged), and the
  new `payments` row (key `p`) names the peer and the count. Two histories, two
  rows, no ambiguity.
- Widths are measured in cells (`Span::width`); trailing columns are dropped
  before they can wrap, so the body fits 80x24 (20 inner rows of 21) as well as
  120x40 and 200x60.

Tests: new `tests/tui_payments.rs` (11 tests) dumps and asserts the screen at
80x24, 120x40 and 200x60 including the empty history, asserts a memo carrying
ESC/BEL/C1/bidi/newline bytes never reaches the frame buffer, and asserts the
window/column invariants for every width from 20 to 200.

Also relaxes one width assertion in `tests/tui_spec.rs`: `fit_cells` was
asserted to start with `"abcdef"`, which only holds when another test's
in-flight `ONIONWIRE_ASCII` mutation is not visible — the suite mutates env vars
without a global lock, so that test flaked (it also fails on an unmodified tree,
1 run in 2). It now accepts either chrome's cut point, which is what the comment
already claimed.

Docs: `docs/TUI.md` gains the screen's section, the retitled/replaced rows and
the updated row count; the "peer payment history" gap entry is closed.
2026-09-18 23:53:10 -04:00
agent
b1a6796742
Merge remote-tracking branch 'origin/onionwire/t_21787cec-node-expose-peer-payment-history-node-li' into onionwire/t_ef1d35d2-tui-payments-row-on-f9-render-peer-payme 2026-09-18 23:19:27 -04:00
agent
eefa7e5cc6
tui: clean-look chrome redesign (one accent, honest tor phase, real frames)
All checks were successful
ci / test (pull_request) Successful in 5m42s
ci / sdk (pull_request) Successful in 1m29s
ci / fuzz (pull_request) Successful in 4m41s
android-ci / android (pull_request) Successful in 10m45s
Applies the bitchat-tui clean-look principles to the OnionWire main screen.

- Hierarchy: header, roster + one primary chat pane, one status line, one
  footer hint line. The header gives up the accent (the accent is reserved
  for focus), so it stops competing with the panes.
- Tor phase is a first-class state: Node::tor_state() -> TorPhase (glyph +
  word, header and footer) so connecting / ready / degraded / off are never
  colour-only and never implied. No new data field.
- Footer changes with the focused pane (pane_footer_hints) and the phase; the
  main footer drops the redundant onion (the header already prints it) and
  uses those cells for hints. status_footer keeps its signature and strings.
- Empty roster / empty chat / connecting / degraded / off are designed states
  with their own copy, not blank panes.
- draw_main_chrome + MainView: the real main render path is public and
  Node-free, so tests/tui_frames.rs dumps the actual chrome at 80x24, 120x40
  and 200x60 (12 tests, 5 states, real Message/OutboxEntry rows) instead of a
  reconstructed stand-in.
- Widths in cells everywhere touched: status_footer*, alert_line,
  main_header_line*, draw_text_overlay, roster_row_text. The roster spends its
  budget name-first, so a 22-cell pane reads `bob-the-sta…  stale` instead of
  `…  bbbbbbbb… stale`.
- draw_text_overlay is centered with a one-cell side margin and clears
  underneath; never full-bleed.

Also fixes a pre-existing race in tests/tui_spec.rs (the ellipsis-form
assertion did not tolerate ONIONWIRE_ASCII being set by a parallel test).

Co-Authored-By: Hermes <[email protected]>
2026-09-18 23:18:24 -04:00
rust-dev
86e20223cf
node: expose peer payment history as Node::list_payments
Some checks failed
ci / test (pull_request) Successful in 8m27s
ci / sdk (pull_request) Successful in 1m29s
ci / fuzz (pull_request) Failing after 16m49s
android-ci / android (pull_request) Successful in 10m52s
Store::list_payments existed but only the node's own tests called it, so the
signed /pay invoices and /tip receipts a peer sent were unreachable from the
app. Add the thinnest read-only accessor next to list_messages/friend_profile:
lock the store, map the error to String, no new state, no new schema, no dial.

Payment rows come back as stored; a renderer sanitizes memo with
sanitize::display_text at draw time, the same way it does for message bodies.
2026-09-18 22:55:23 -04:00
14f9284463 Merge pull request 'tui: analyse the landed wallet + node features and ship a WALLETS & SETTINGS menu (F9)' (#118) from onionwire/t_8bb1bac9-onionwire-tui-analyze-landed-wallet-node into main
Some checks failed
ci / test (push) Has been cancelled
ci / sdk (push) Has been cancelled
ci / fuzz (push) Has been cancelled
android-ci / android (push) Has been cancelled
Reviewed-on: #118
2026-09-19 02:41:39 +00:00
b99d96a145 Merge branch 'main' into onionwire/t_8bb1bac9-onionwire-tui-analyze-landed-wallet-node
Some checks failed
ci / sdk (pull_request) Has been cancelled
ci / fuzz (pull_request) Has been cancelled
ci / test (pull_request) Has been cancelled
android-ci / android (pull_request) Has been cancelled
2026-09-19 02:41:28 +00:00
agent
3b44cb0faf
ci: re-trigger the checks (the first attempt was cancelled by the runner, no code change)
Some checks failed
ci / test (pull_request) Successful in 5m43s
ci / sdk (pull_request) Successful in 1m36s
ci / fuzz (pull_request) Has been cancelled
android-ci / android (pull_request) Has been cancelled
2026-09-18 22:36:08 -04:00
agent
0131803f9c
tui: WALLETS and SETTINGS menu (F9 / /settings) over the landed wallet + node features
Some checks failed
android-ci / android (pull_request) Has been cancelled
ci / sdk (pull_request) Has been cancelled
ci / fuzz (pull_request) Has been cancelled
ci / test (pull_request) Has been cancelled
The Monero wallet and the cuprate node shipped behind function keys only, so a
user who did not already know F6 opened the wallet could not find wallet setup,
the child wallet, the chain source or the settings.

F9 (also /settings) now opens one discoverable screen with the two groups the
card fixes: WALLET (endpoint, child, sync, receive, balance, payments, create,
import) then SETTINGS (nickname, profile, identity, colour, backup, restore,
wipe, wipe-all). Every actionable row prints the key or command that fires it,
including the F6 wallet screen's own keys, and those keys stay live on the
screen so no row can name a dead key.

- Screen, not popup: 19 rows at 80x24 against 21 inner rows; 120x40 and 200x60
  hold. The footer is the shared status_footer, so TOR / identity / ? help stay
  put.
- No credentials: WalletMenuState carries booleans, labels and display-ready
  error strings only. rpc_login, secret(), seeds and passphrases have no field
  to travel in.
- Untrusted values are display data: sanitize + newline/tab strip, then
  truncated in cells.
- Cells, not chars: cell_width() measures through ratatui's own Span::width, so
  no unicode-width dependency was added and chars().count() is never a width.
- Copy without a clipboard crate: c writes the receive address as an OSC 52
  sequence; the terminal owns the clipboard and it survives SSH.
- Colour is never the only signal: every state also spells itself out.
- F7 stays free for the endpoint config screen that names it (db208be,
  docs/WALLET.md).

F2/F3/F4/F5/F6/F8 keep working: the function keys are now handled once, for Main
and this screen, instead of inside the Main arm.
2026-09-18 22:26:57 -04:00
agent
9a1f50eadf
fix(ci): drop stale Gradle journal locks on the shared /gradle volume
All checks were successful
android-ci / android (pull_request) Successful in 11m30s
android-ci failed LockTimeoutException on /gradle/caches/journal-1: two
JVMs (PIDs a few apart) sharing onionwire-android-gradle. A cancelled job
never docker-rms the build container, so the next run mounts the same
volume while the previous Gradle still holds the lock. Also
org.gradle.parallel=true in android/gradle.properties.

Remove leftover onionwire-android-* containers (and trap EXIT), delete
stale *.lock files inside the container, and force parallel=false.
2026-09-18 22:02:22 -04:00
5c43254111 Merge pull request 'fix(ci): drop stale Gradle journal locks on the shared /gradle volume' (#117) from feat/android-ci-gradle-journal-lock into main
All checks were successful
android-ci / android (push) Successful in 11m37s
Reviewed-on: #117
2026-09-19 02:01:25 +00:00
e3fb723a91 Merge pull request 'fix(android): keep Tor bootstrap alive after the unlock activity dies' (#116) from feat/android-bootstrap-survives-ui into main
Some checks failed
android-ci / android (push) Failing after 3m32s
Reviewed-on: #116
2026-09-19 01:51:38 +00:00
agent
396e468f1a
fix(android): keep Tor bootstrap alive after the unlock activity dies
Some checks failed
android-ci / android (pull_request) Has been cancelled
Open set Phase.Opening then ran openWire on viewModelScope, and the
keep-alive refused to start until Wire existed. Closing the activity
cancelled bootstrap, so the spinner vanished and the lock screen came
back idle. Run openWire on NodeHost's process scope, start the FGS on
the Open tap, and treat in-flight bootstrap as keep-alive work. IME Go
also submits unlock the same way as the Open button.
2026-09-18 21:46:34 -04:00
77f577fcf9 Merge pull request 'android-ci: make a :app:packageRelease failure diagnosable (--stacktrace)' (#115) from onionwire/t_d81fb7bf-android-ci-make-a-app-packagerelease-fai into main
All checks were successful
android-ci / android (push) Successful in 11m0s
Reviewed-on: #115
2026-09-19 00:03:08 +00:00
apk-dev
fcdabf8d13
android-ci: pass --stacktrace to the release gradle build
All checks were successful
android-ci / android (pull_request) Successful in 10m27s
Run 414 died in :app:packageRelease with an empty cause chain (no
Caused by: line at all), so a one-off packaging failure leaves nothing
to diagnose. --stacktrace only changes output on failure; it does not
alter the build, the artifact or the timings.

scripts/build-android-local.sh is the single gradle invocation that both
android-ci.yml and android-release.yml build through, so one flag covers
both.
2026-09-18 19:53:41 -04:00
0af97e144a Merge pull request 'android-ci: echo the artifact digests and deflated native-lib sizes (evidence follow-up to #113)' (#114) from onionwire/t_f05be394-evidence-digest into main
All checks were successful
android-ci / android (push) Successful in 11m8s
Reviewed-on: #114
2026-09-18 22:53:43 +00:00
agent
c5e2cae694
android-ci: 2 GB of Gradle heap for the cuprated release packaging
Some checks failed
android-ci / android (pull_request) Failing after 2s
Run 414 (PR #114) died in `:app:packageRelease` after a clean build:

    Execution failed for task ':app:packageRelease'.
    > A failure occurred while executing
      com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable

with no `Caused by` line and nothing else in the log — and it is not
reproducible on the same content: runs 412 and 413 (this tree, 1 GB heap)
packaged fine. The one budget in this build that got tight when cuprate came in
is the single-use Gradle daemon's heap, which now compresses a 55 MB SDK lib
(plus RandomX's 1.1 MB) in-process; the runner has 15 GB and the job's peak RSS
is ~3 GB, so 2 GB of heap costs nothing and removes the most likely mechanism.
android-release.yml gets the same number: it packages the same APK.
2026-09-18 18:15:52 -04:00
agent
294cedfbff
android-ci: echo the artifact digests and the deflated native-lib sizes
Some checks failed
android-ci / android (pull_request) Failing after 9m52s
Run 412 (PR #113) proved the cuprated APK builds and carries the daemon, but
the log only ever printed `sha256sum -c ...: OK` — neither digest — and
`unzip -l`, which shows the uncompressed size of every .so and not the
deflated one the download pays for. Both are what a reader of the run needs to
identify the artifact, and neither can be recovered from the tree afterwards.

Also fills the two remaining cells of CUPRATE_DAEMON.md's CI-cost table from
that run (APK 34,445,514 B / AAR 15,728,039 B, 11m12s job, 5.6 G target
volume), and records that the first feature-on build is the 44-minute one
while later builds settle at +2 minutes over the feature-off baseline.
2026-09-18 17:51:11 -04:00
8626da225b Merge pull request 'android: build the SDK with cuprate-daemon and offer the on-device node' (#113) from onionwire/t_f05be394-android-build-the-sdk-with-cuprate-daemo into main
All checks were successful
android-ci / android (push) Successful in 10m40s
Reviewed-on: #113
2026-09-18 21:42:54 +00:00
agent
3860c3d56d
android: record what the cuprated build costs CI (baseline vs feature on)
All checks were successful
android-ci / android (pull_request) Successful in 11m12s
2026-09-18 17:30:20 -04:00
sirius
9afa22a0bf
android-ci: fix the cuprate marker gate failing its own green build
Some checks failed
android-ci / android (pull_request) Has been cancelled
ci / test (pull_request) Successful in 5m7s
ci / sdk (pull_request) Successful in 1m4s
ci / fuzz (pull_request) Successful in 4m55s
Run 406 built the APK successfully (BUILD SUCCESSFUL in 44m 7s) and the gate then
reported "the cuprate-daemon feature is NOT in this APK" while the line above it
printed `target_max_memory` **5** times. The bug is the classic one:

    strings -a x.so | grep -q pattern     # under `set -o pipefail`

`grep -q` exits at the first match and closes the pipe; `strings` takes SIGPIPE
(141) and pipefail makes the pipeline status non-zero, so `if ! ...` ran. The count
is captured into a variable now (grep -c reads the whole stream, no SIGPIPE) and the
gate fails on `< 1`, which is what it always meant.
2026-09-18 17:16:05 -04:00
sirius
adcf52b8e4
android: pin the Android Rust toolchain to 1.98 (cuprated needs >= 1.93)
The Android jobs pinned `RUST_TOOLCHAIN: "1.91"` — the workspace MSRV — and the
cuprated graph does not build on it. `tapes`, a Cuprate dependency this repo cannot
patch, calls `VecDeque::pop_front_if`, stable only from 1.93:

    error[E0658]: use of unstable library feature `vec_deque_pop_if`
       --> /cargo/git/checkouts/tapes-.../src/tapes/rolling_tape.rs:396:34

1.98 is the stable release the graph is built and tested with on the dev machine
(rustc 1.98.1) and the one the cross-compile spike used. `ci.yml`, `release.yml` and
the `rust-version = "1.91"` MSRV are untouched: the feature-off workspace builds on
1.91, and moving the MSRV is a separate decision, flagged in the PR.

Both workflows, and `android/CUPRATE_DAEMON.md` records it as a pitfall.
2026-09-18 17:16:05 -04:00
sirius
0a2bcf93a2
android: install cmake in the Android build containers
RandomX is the C++ half of the in-process chain daemon and `randomx-rs`'s build
script drives it through `cmake-rs`. Neither `android-ci.yml` nor
`android-release.yml` installed `cmake` in its `debian:bookworm` container, so the
first CI run of this branch compiled 410 crates in 11m37s and then died with

    error: failed to run custom build command for `randomx-rs …`
    failed to execute command: No such file or directory (os error 2)
    is `cmake` not installed?

surfacing as Gradle's "Process 'command 'cargo'' finished with non-zero exit value
101" — which reads like a Rust error and is not one. Both workflows install it now.

`android-ci.yml` also reports the cargo target volume after the build, next to the
wall clock: the disk cost of the feature on the runner is part of the measurement
this change owes.
2026-09-18 17:16:05 -04:00
sirius
e6b6bc8dd6
android: build the SDK with cuprate-daemon and offer the on-device node
Part 3 of "cuprated built in": the chain daemon now ships inside the APK and the
wallet screen can pick it.

Build (android/sdk/build.gradle.kts)
- `cargoBuildAndroid` runs `cargo ndk … build --release --lib --features
  cuprate-daemon`. The Android target only: `cargoHostLib` / `uniffiBindgen` stay
  feature-free, because the host cdylib exists only so `uniffi-bindgen --library`
  can dlopen it and the UniFFI surface does not fork on a cargo feature.
- The link needs the NDK's libc++ and compiler-rt builtins explicitly (RandomX is
  C++ and its aarch64 JIT calls `__clear_cache`; `randomx-rs` links the NDK's stub
  `libstdc++.a`). `cargo ndk --link-builtins` covers the builtins only, so the
  whole set is spelled out as per-ABI `CARGO_TARGET_<TRIPLE>_RUSTFLAGS` — a global
  `RUSTFLAGS` would break the host build scripts. The linker is the NDK clang
  driver at the app's API level, named explicitly, because the dev machines pin
  the API 21 wrapper for `aarch64-linux-android` and API 21 fails this link.
- `ANDROID_NDK` is exported alongside `ANDROID_NDK_HOME`/`NDK_HOME`: without it
  `cmake-rs` aborts and `randomx-rs`'s build script panics.
- The task logs the feature it builds with, so CI carries the request, not just
  the task name.

Wallet screen
- Third chain source, **On-device node (Cuprate)**, beside the daemon field and
  Receive-only. Stored as `ChainChoice.InProcessCuprate` with an empty
  `monerod_datadir`, which the SDK resolves to `$ONIONWIRE_HOME/chain`. Existing
  Save daemon / Receive-only / Start / Stop behaviour is unchanged.
- The status line grows `· node <word>` from `WalletChildStatus.node_state` for
  this source only, fail-closed on an unrecognised word. No sync height: the SDK
  exposes none, so the screen does not show a number it cannot get.
- Storage honesty: free space on the chain store's filesystem, and Start is
  refused below a 3 GiB floor or when that filesystem cannot be read. The floor is
  a floor, not a sync estimate — nothing here exposes one.
- The pre-production warning (quoted user book, testnet only, Cuprate issue #278)
  is a sentence above Start, assertable in a test. Opt-in, never a default.
- The daemon field's hint no longer suggests a loopback daemon on the phone.

CI
- `android-ci.yml` extracts `lib/<abi>/libonionwire_sdk.so` from the built APK and
  fails the job unless it contains `target_max_memory`, a rodata literal compiled
  only under `cuprate-daemon`. v0.7.0's shipped `.so` has zero of them, so this
  separates "in the artifact" from "requested".

Docs
- `android/CUPRATE_DAEMON.md`: the build wiring, the link line, the CI gate, and
  an explicit "not verified on a device" section. `MONERO_BINARIES.md` points at
  it for the chain source that is not a binary.
2026-09-18 17:16:05 -04:00
773dacb062 Merge pull request 'sdk: land the on-device Cuprate chain source on main (replay of #111's SDK commit)' (#112) from onionwire/t_52f8de0f-cuprate-land-the-sdk-surface-on-main-pr into main
All checks were successful
ci / test (push) Successful in 5m9s
ci / sdk (push) Successful in 1m4s
android-ci / android (push) Successful in 8m22s
ci / fuzz (push) Successful in 4m47s
Reviewed-on: #112
2026-09-18 19:44:45 +00:00
agent
e89dd9eaee
sdk: expose the on-device Cuprate chain source (choice, lifecycle, node status)
All checks were successful
ci / test (pull_request) Successful in 5m5s
ci / sdk (pull_request) Successful in 1m4s
android-ci / android (pull_request) Successful in 8m31s
ci / fuzz (pull_request) Successful in 4m47s
ChainChoice gains InProcessCuprate, the SDK passes the core's cuprate-daemon
feature through as its own, and an empty monerod_datadir for that kind resolves
to $ONIONWIRE_HOME/chain so Kotlin never invents a path. wallet_status now
carries chain_in_process / node_available / node_state beside the core's five
state words; no second state machine, no timer, no env var.

start/stop stay the core's pass-through: one call launches the node and the
wallet child, one stops both, both idempotent.

Replayed onto main (25e029e): PR #111 was merged into the core branch
onionwire/t_04975420-cuprate-land-the-in-process-chain-source, not main, so
main had only the core half (from PR #110). This is the same tree change with
no core commits replayed.
2026-09-18 15:29:55 -04:00
25e029ed4e Merge pull request 'wallet: land the in-process Cuprate chain source on main (ChainSource::InProcessCuprate, cuprate-daemon feature)' (#110) from onionwire/t_04975420-cuprate-land-the-in-process-chain-source into main
All checks were successful
ci / test (push) Successful in 5m6s
ci / sdk (push) Successful in 1m3s
android-ci / android (push) Successful in 8m20s
ci / fuzz (push) Successful in 4m43s
Reviewed-on: #110
2026-09-18 18:05:46 +00:00
agent
ffea4bf9df
wallet: land the in-process Cuprate chain source on main
All checks were successful
ci / test (pull_request) Successful in 5m39s
ci / sdk (pull_request) Successful in 1m22s
android-ci / android (pull_request) Successful in 8m58s
ci / fuzz (pull_request) Successful in 4m45s
`ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P,
consensus and RandomX run inside the OnionWire process instead of as a spawned
`monerod`. The wallet layer does not move — the daemon binds the same loopback
unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already
returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment
frames and the receipt-verification path are untouched.

- Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the
  `cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is
  disabled (`default-features = false`): its arti-client 0.44 cannot unify with
  this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in
  the process. `Cargo.lock` gains the graph; a default build's
  `cargo tree --locked -e normal -i cuprated` still says "did not match any
  packages", and only `arti-client v0.46.0` is in the lock.
- src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML
  (testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P
  off), launches it on a runtime it owns, and owns the node. `launch` is
  synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its
  blocking thread, UniFFI calls it from an async context) and a runtime cannot be
  started from inside a runtime, so the launch runs on a thread of its own and
  the node + its runtime come back over a channel. Dropping the value asks the
  node to shut down and `shutdown_background`s the runtime, which is the only
  exit that cannot panic when the value is dropped inside another runtime.
  The type exists in every build (feature off: `launch` fails with the feature
  name), so the chain-source type, its stored record and its copy do not fork on
  a cargo feature.
- src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon
  client the wallet line carried (typed `WalletError`, de-chunked HTTP,
  `get_height` over the URI endpoint, an above-the-tip height as one typed
  error). Cuprate answers those three differently from monerod and the
  in-process source is what makes them the *local* case.
- src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the
  free-space/ownership question, the honest `chain_copy` line, `kind =
  "cuprate"` in the sealed record, and `ChildConfig::validate` for it.
- src/tui.rs: the wallet screen's chain line carries the testnet caveat when the
  configured source is the in-process one. It computes the line at draw time, so
  `Screen::Wallet`'s shape (which tests construct) does not change.
- docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the
  feature flag and how to enable it, where the (fjall) chain store lives, the
  **measured** +11.8 MiB delta, the pre-production/testnet caveat, and the
  in-repo aarch64-linux-android proof with exit codes.

Scope deviations, stated plainly:
- `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's
  allowed list; the card's own deliverable describes the module's behaviour.
- `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a
  `pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the
  root CI `sdk` job runs on every PR. One variant plus two match arms land here
  so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card
  owns the rest — feature passthrough, the config field's semantics, the label
  and its tests, and the Android check.
- `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched:
  main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7
  work, and `docs/WALLET.md` says so rather than describing a picker that does
  not exist).

Proof (all on this tree):
- Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345
  passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked
  --all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0.
- Feature on: `cargo test --locked --features cuprate-daemon --target
  x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with
  `--features cuprate-daemon` exit 0. The two extra tests are the real thing:
  `wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down`
  and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client`
  — the latter launches the node, drives `get_info` / `get_height` / `get_block`
  through the typed client, checks the above-the-tip 500 maps to
  `DaemonHeightOutOfRange`, checks the chain store is under the chain datadir,
  and checks the listener dies with the node.
- aarch64: `cargo check --locked --release --target aarch64-linux-android
  --features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0
  (`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link
  args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26,
  built by NDK r28c`.
- Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and
  37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure
  `docs/WALLET.md` now quotes.
2026-09-18 13:45:59 -04:00
8ba1cf4c6c Merge pull request 'android: start/stop the monero-wallet-rpc child from WalletScreen, bundle the binary (issue #107)' (#109) from onionwire/t_87984328-android-start-stop-the-monero-wallet-rpc into main
All checks were successful
android-ci / android (push) Successful in 8m9s
Reviewed-on: #109
2026-09-18 14:33:54 +00:00
apk-dev
0134396588
android: start/stop the monero-wallet-rpc child from WalletScreen, bundle the binary
All checks were successful
android-ci / android (pull_request) Successful in 8m59s
Implements the Android half of issue #107. Stacked on `wt/t_8a8ff353`
(PR #108) because the UniFFI wallet-child surface is not on `main` yet.

Binary
------

`android/app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so` is a real
`monero-wallet-rpc` cross-compiled for `aarch64-linux-android` from
monero-project/monero v0.18.4.4 (516e5355) via upstream's own
`contrib/depends` + toolchain.cmake path, then stripped with the target's own
strip. 19 954 224 bytes, sha256
d9126788030ecd1ccdb40c7764e66e9a14d158a147ad335b256f0577681b5ad4.

It ships through `jniLibs` and not as an asset on purpose: since API 29 the
kernel refuses `exec()` on a file in the app's data directory, so the only
executable directory an app has is `applicationInfo.nativeLibraryDir`, which
the package manager fills from `lib/<abi>/` at install time. That requires
`android:extractNativeLibs="true"` (`packaging.jniLibs.useLegacyPackaging`),
which `app/build.gradle.kts` now sets, plus `keepDebugSymbols` for this one
entry so AGP's strip pass cannot rewrite the bytes CI verifies.

`scripts/build-monero-wallet-rpc-android.sh` reproduces the build and
`android/MONERO_BINARIES.md` records the four host quirks that cost the most
time (CMake must be 3.x; NDK r17b clang60 needs a libtinfo.so.5 shim; the
generated toolchain.cmake puts the HOST `/usr` in CMAKE_FIND_ROOT_PATH, which
breaks the link with a host libpgm.so and defines HAVE_HIDAPI against host
headers; the CMake target is `wallet_rpc_server`, not `monero-wallet-rpc`).

CI re-verifies the blob rather than taking it on trust:
`scripts/build-android-local.sh` checks `android/monero-binaries.sha256` before
Gradle, and after packaging pulls `lib/<abi>/libmonerowalletrpc.so` back out of
the APK and compares its sha256 with the committed file.

`arti` is NOT bundled, so a `.onion` daemon cannot be started yet. The app says
that instead of pretending: `arti_bin` is set to the path the binary would
occupy, and the screen refuses an `.onion` daemon while it is absent.
Loopback and clearnet daemons work.

UI
--

`WalletScreen` gains a "wallet daemon" card above the existing
Create / Import / Invoice / Tip actions, which are untouched:

* a status line from `Wire::wallet_status()` rendered verbatim —
  `off` / `connecting` / `syncing` / `ready` / `exited` plus the core's
  chain-source label (`receive-only` / `local node` / `remote onion daemon` /
  `remote daemon`). A died child reads `exited`; it is never folded into `off`
  and never into `ready`;
* Start / Stop calling `start_wallet_child` / `stop_wallet_child` through
  `WireViewModel`, on `Dispatchers.IO` (the spawn is synchronous inside the node
  and the status read re-decrypts the sealed record);
* a `host:port` field that saves a remote daemon via `set_chain_source`, plus a
  Receive-only button;
* honest failure states instead of a spinner: no bundled binary, no chain
  source, a `.onion` daemon with no arti, or a start that failed — each gets its
  own sentence, and Start is disabled with the reason on screen.

`WireViewModel` owns the 2s wallet-child poller, the same way it owns the chat
poller, so leaving the wallet screen and coming back cannot stack a second loop.
`ui/WalletChildStatusText.kt` is the pure model (mirrors the
`ChatRowInput`/`OutboxRowInput` convention) and carries the state mapping, the
status line and the Start/Stop gates; `WalletChildStatusTextTest` covers them on
the JVM.

Verified
--------

`./gradlew :app:testDebugUnitTest` passes, `scripts/build-android-local.sh`
produces `dist/onionwire-0.1.0-android-arm64-v8a.apk` (27 884 277 bytes,
versionName 0.1.0 / versionCode 100) with
`lib/arm64-v8a/libmonerowalletrpc.so` inside it at the committed sha256, and
`extractNativeLibs="true"` in the merged release manifest.

NOT verified: the binary was never executed. The build host has no arm64-v8a
AVD (all three existing AVDs are x86_64) and no aarch64 sysroot for qemu-user,
so nothing here proves `monero-wallet-rpc` starts, opens its wallet file and
answers JSON-RPC under Android's runtime. `android/MONERO_BINARIES.md` says so
plainly and lists the emulator steps to close the gap.
2026-09-18 10:20:08 -04:00
143bf6e0d0 Merge pull request 'wallet: land the wallet-child stack on main + expose start/stop/status through UniFFI (issue #107)' (#108) from wt/t_8a8ff353 into main
All checks were successful
ci / test (push) Successful in 4m58s
ci / sdk (push) Successful in 57s
android-ci / android (push) Successful in 8m7s
ci / fuzz (push) Successful in 4m36s
Reviewed-on: #108
2026-09-18 13:45:17 +00:00
agent
c5af978d14
docs(wallet): describe the child lifecycle that ships here
All checks were successful
ci / test (pull_request) Successful in 5m31s
ci / sdk (pull_request) Successful in 1m22s
android-ci / android (pull_request) Successful in 8m52s
ci / fuzz (pull_request) Successful in 4m37s
The inherited section described an F7 config screen with endpoint entry and
test-connection that is not in this stack (it lives on
feat/wallet-create-import), and called local mode 'not wired yet'. Both are
now wrong: the child is wired, and the stored wallet config is a core API
without a screen. Say which is which.
2026-09-18 09:28:11 -04:00
agent
d8a2ee35aa
sdk: expose the wallet-child lifecycle over UniFFI
ChainConfig / ChainChoice / WalletChildStatus records and
set_chain_source(config) / chain_source() / start_wallet_child() /
stop_wallet_child() / wallet_status(). Android passes absolute binary paths
from nativeLibraryDir; the core never resolves a binary the caller named.
2026-09-18 09:28:11 -04:00
agent
440a37caf0
wallet: wire the app-owned child into the node and TUI
The module was dead code: nothing started the child, so the payment spines
could only ever see an env-configured monero-wallet-rpc. Now:

- Node::start_wallet_child / stop_wallet_child / wallet_child_status /
  wallet_child_refresh / wallet_child_config / set_wallet_child_config. The
  start path honours the configured absolute binary path, points the node's
  wallet at the child, and shutdown() stops the child rather than orphaning
  a spend-capable RPC behind a loopback socket.
- The status is derived from the real process (try_wait) and the last probe:
  off / connecting / syncing / ready / exited, plus the chain-source label.
  A dead child is never reported ready.
- ChildConfig (source, wallet_rpc_bin, arti_bin, wallet_filename) persists in
  the sealed wallet_child record next to the generated creds; the record is a
  read-modify-write so first-start creds never clobber a saved config.
- TUI: F6 gains s (start) / x (stop) / p (probe) and a child status row, and
  the /pay and /tip key handlers now call the core readiness guard before
  sending.
2026-09-18 09:28:11 -04:00
agent
11a021acb3
chore: wallet child lifecycle + chain source + SOCKS proxy (t_1bcecf90) 2026-09-18 09:28:11 -04:00
rust-dev
db208be05c
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:

- `wallet_config` table in the encrypted store (one row; the login is sealed
  with the store data key under `onionwire/wallet-config/v1`, on top of
  SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
  `save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
  redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
  prefers stored config, falls back to env, and refuses to dial a bad stored
  endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
  receive_address }`: `connected` only ever comes from a probe
  (`Wallet::status`, get_address + get_balance); config alone leaves it false.
  `Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
  probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
  error }` for the Test-connection button: same loopback/digest rules, errors
  redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
  `Node::wallet_readiness` (async, block_on-friendly): not configured →
  NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
  dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
  live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
  wallet can be re-pointed mid-session.

Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.

Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-18 09:28:11 -04:00
agent
bcf7ec31c1
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.

- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
  port }. No default remote node; Remote is only constructed from explicit
  user input. A .onion Remote is refused without a SOCKS proxy (separate
  card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
  --rpc-bind-ip 127.0.0.1, a random free loopback port, generated
  --rpc-login, and --wallet-dir /wallet; monerod too for a
  local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
  (wallet_child table, AEAD on top of whole-db encryption), never a
  plaintext file. The Wallet client is built from the generated loopback
  URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
  height>=target_height; can_spend() and can_verify_receipts() gate on it.
  Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
  calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
  because a first sync or a remote daemon outlasts 5s and a 5s cap there
  is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
  configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.

Base: feat/wallet-create-import (PR #66). Do not rebase onto main.

Co-Authored-By: Hermes Agent <agent@local>
2026-09-18 09:28:11 -04:00
462b5765bd Merge pull request 'ci: nightly fuzz job for fuzz/ (PR #103 harness) - fix build+run container' (#106) from wt/t_16e835ef into main
Reviewed-on: #106
2026-09-18 11:09:13 +00:00
4623f78a69 Merge branch 'main' into wt/t_16e835ef 2026-09-18 11:08:51 +00:00
agent
518ef30232
Revert "ci: crash-test — inject panic in qr_decode to prove the fuzz job fails on a crash (REVERT BEFORE MERGE)"
All checks were successful
ci / test (pull_request) Successful in 4m51s
ci / sdk (pull_request) Successful in 58s
ci / fuzz (pull_request) Successful in 4m34s
This reverts commit b76bf46100.
2026-09-17 23:28:32 -04:00
agent
99a941b437
fix(ci): merge fuzz build+run into one container so cargo-fuzz persists
All checks were successful
ci / test (push) Successful in 4m46s
ci / sdk (push) Successful in 57s
ci / fuzz (push) Successful in 4m30s
The fuzz job's two CI steps ran in separate Docker containers, so the
cargo-fuzz binary installed in step 1 was gone by step 2: run-fuzz.sh
failed with 'error: no such command: fuzz'. Merge the nightly toolchain
install, cargo-fuzz install, fuzz build, fuzz list, and run-fuzz.sh into
a single container step so the installed binary and built targets survive.

Carry the /target/tmp mkdir from 1b2c63b (rustup self-update needs TMPDIR
to exist before its temp dir creation).
Co-authored-by: agent <agent@local>
2026-09-17 23:13:34 -04:00
agent
8949da1213
fix(ci): merge fuzz build+run into one container so cargo-fuzz persists
Some checks failed
ci / test (pull_request) Successful in 4m54s
ci / sdk (pull_request) Successful in 1m5s
ci / fuzz (pull_request) Failing after 5m56s
The fuzz job's two CI steps ran in separate Docker containers, so the
cargo-fuzz binary installed in step 1 was gone by step 2: `bash
/scripts/run-fuzz.sh` failed with "error: no such command: `fuzz`".

Merge the nightly toolchain + cargo-fuzz install + `cargo fuzz build` +
`cargo fuzz list` + `bash run-fuzz.sh` into a single container step so
the installed binary and the built targets survive across the run.

Also keep the /target/tmp mkdir from 1b2c63b (rustup needs it for its
temp dir when TMPDIR=/target/tmp).

Co-authored-by: agent <agent@local>
2026-09-17 23:10:08 -04:00
agent
1b2c63b9b6
fix(ci): create /target/tmp before rustup/cargo-fuzz in Docker jobs
Some checks failed
ci / test (push) Successful in 4m42s
ci / sdk (push) Successful in 57s
ci / fuzz (push) Failing after 17m18s
All CI Docker jobs set TMPDIR=/target/tmp (via -e), but the directory
was never created inside the container before rustup ran. The /target
volume mount doesn't include a tmp/ subdir, so rustup's temp dir
creation failed with ENOENT.

Fix: add /target/tmp to the mkdir -p in all four Docker shell commands
(test, sdk, fuzz-build, fuzz-run).
2026-09-17 22:16:25 -04:00
2f6f737106 Merge pull request 'fuzz: cargo-fuzz harness for the ratchet/qr/dispatch/file parsers' (#103) from wt/t_1265efb2 into main
Some checks failed
ci / test (push) Successful in 4m49s
ci / sdk (push) Successful in 57s
ci / fuzz (push) Failing after 1m7s
Reviewed-on: #103
2026-09-18 02:00:33 +00:00
2b7a306d43 Merge pull request 'store: widen payments.kind to accept 'tip' (tips were never stored)' (#102) from wt/t_ecf204ad into main
Some checks failed
android-ci / android (push) Successful in 8m57s
ci / test (push) Successful in 4m40s
ci / sdk (push) Successful in 56s
ci / fuzz (push) Failing after 49s
Reviewed-on: #102
2026-09-18 01:53:26 +00:00
agent
186ec7436d
store: widen payments.kind to accept 'tip' so tips are stored
Some checks failed
android-ci / android (pull_request) Successful in 8m6s
ci / test (pull_request) Successful in 4m43s
ci / sdk (pull_request) Successful in 57s
ci / fuzz (pull_request) Failing after 31s
insert_payment has allowed kind = "tip" since the tip path landed, but the
payments table's CHECK only permitted invoice/receipt, so every tip insert
failed ("CHECK constraint failed: kind IN ('invoice','receipt')"). That made
the outbound tip row impossible and silently broke the inbound path too:
ingest_tip returned early and neither the row nor the [tip] chat line was
written.

- recreate the table with the widened CHECK on open, copying rows verbatim
  (new stores get it from the schema directly)
- outbound tip() records kind = "tip" with the tip's memo, matching ingest_tip
- tests: outbound row, inbound round trip, pre-tip store migration

Refs kanban t_ecf204ad
2026-09-17 21:46:57 -04:00
24b5c93c43 Merge pull request 't_2fb507c6: F8 rotate prekey (Node::rotate_prekey + invite re-encode)' (#101) from wt/t_2fb507c6 into main
Some checks failed
android-ci / android (push) Successful in 8m28s
ci / test (push) Has been cancelled
ci / sdk (push) Has been cancelled
ci / fuzz (push) Has been cancelled
Reviewed-on: #101
2026-09-18 01:21:45 +00:00
724e0427b0 Merge pull request 'tls: default to Arti's rustls backend (drop OpenSSL from TLS)' (#100) from wt/t_17e3d3cf-rustls-default into main
Some checks failed
android-ci / android (push) Successful in 9m42s
ci / test (push) Successful in 4m42s
ci / sdk (push) Successful in 1m1s
ci / fuzz (push) Failing after 59s
Reviewed-on: #100
2026-09-18 01:20:35 +00:00
049b612169 Merge branch 'main' into wt/t_17e3d3cf-rustls-default
Some checks failed
android-ci / android (pull_request) Successful in 8m17s
ci / test (pull_request) Successful in 4m50s
ci / sdk (pull_request) Successful in 1m6s
ci / fuzz (pull_request) Failing after 58s
2026-09-18 01:05:55 +00:00
agent
b76bf46100
ci: crash-test — inject panic in qr_decode to prove the fuzz job fails on a crash (REVERT BEFORE MERGE) 2026-09-17 21:04:45 -04:00
rust-dev
2cf9e8c7c6
fuzz: cargo-fuzz harness for the ratchet/qr/dispatch/file parsers
Four pure parsers eat untrusted peer input and had no structured fuzzing:

- ratchet_frame  -> RatchetState::from_bytes + RatchetState::decrypt
                    (the 'rat ' frame parser: prefix, version, length,
                    N/PN bounds, DH step, AEAD open)
- qr_decode      -> qr::decode on pasted/scanned invite strings
- dispatch_classify -> dispatch::classify on raw decrypted plaintext,
                    including the 'rat ' -> Kind::Ratchet routing arm
- file_decode    -> file::decode on 'fil ' chunk frames

No src/ change: every target calls the shipped public API. The fuzz crate is
its own workspace (empty [workspace] table), so no root Cargo.toml dependency
is added and cargo build/test at the root never compiles it.

Seeds in fuzz/seeds/ are committed and copied into the gitignored working
corpus by scripts/run-fuzz.sh; each target asserts properties a panic-free
decode must hold (a rejected ratchet frame leaves the state byte-identical,
a decoded invite is 32/32/onion-shaped, a decoded chunk re-encodes).

Verified: cargo +nightly fuzz list -> 4 targets; scripts/run-fuzz.sh with
FUZZ_SECS=60 FUZZ_JOBS=4 -> exit 0, oom/timeout/crash: 0/0/0 for all four,
fuzz/artifacts/* empty.
2026-09-17 21:04:20 -04:00
407b11f2f8 Merge pull request 'docs+tui: reachability stance (no sealed mailbox) and peer-unreachable queued footer' (#99) from wt/t_d662c8a6 into main
Some checks failed
android-ci / android (push) Successful in 8m31s
ci / test (push) Successful in 4m57s
ci / sdk (push) Successful in 1m5s
ci / fuzz (push) Failing after 36s
Reviewed-on: #99
2026-09-18 01:02:21 +00:00
deaa8a7cfa Merge pull request 'ci: nightly cargo-fuzz job for fuzz/ (PR #103 harness)' (#104) from wt/t_16e835ef into main
Some checks failed
ci / test (push) Successful in 4m41s
ci / sdk (push) Successful in 58s
ci / fuzz (push) Failing after 1m11s
Reviewed-on: #104
2026-09-18 01:00:39 +00:00
agent
bfbbdbf14f
ci: nightly cargo-fuzz job for fuzz/ (PR #103 harness)
Some checks failed
ci / test (pull_request) Successful in 4m47s
ci / sdk (pull_request) Successful in 57s
ci / fuzz (pull_request) Failing after 1m8s
Add a  job to .forgejo/workflows/ci.yml that builds the four
libFuzzer targets on nightly (ratchet_frame, qr_decode,
dispatch_classify, file_decode) and runs each for 15s. Own registry
and target volumes (onionwire-cargo-registry-fuzz /
onionwire-target-ci-fuzz), TMPDIR=/target/tmp, own concurrency group
(onionwire-ci-pi-fuzz) so the ~12min cold build does not serialize the
test/sdk jobs. Path allowlist extended with fuzz/** and
scripts/run-fuzz.sh so fuzz-only PRs actually trigger it.

Job is a no-op until PR #103 lands on main; the fuzz/ crate is a
detached workspace that root cargo test/clippy never sees.
2026-09-17 20:57:50 -04:00
rust-dev
bcee6a72a6
fuzz: cargo-fuzz harness for the ratchet/qr/dispatch/file parsers
Four pure parsers eat untrusted peer input and had no structured fuzzing:

- ratchet_frame  -> RatchetState::from_bytes + RatchetState::decrypt
                    (the 'rat ' frame parser: prefix, version, length,
                    N/PN bounds, DH step, AEAD open)
- qr_decode      -> qr::decode on pasted/scanned invite strings
- dispatch_classify -> dispatch::classify on raw decrypted plaintext,
                    including the 'rat ' -> Kind::Ratchet routing arm
- file_decode    -> file::decode on 'fil ' chunk frames

No src/ change: every target calls the shipped public API. The fuzz crate is
its own workspace (empty [workspace] table), so no root Cargo.toml dependency
is added and cargo build/test at the root never compiles it.

Seeds in fuzz/seeds/ are committed and copied into the gitignored working
corpus by scripts/run-fuzz.sh; each target asserts properties a panic-free
decode must hold (a rejected ratchet frame leaves the state byte-identical,
a decoded invite is 32/32/onion-shaped, a decoded chunk re-encodes).

Verified: cargo +nightly fuzz list -> 4 targets; scripts/run-fuzz.sh with
FUZZ_SECS=60 FUZZ_JOBS=4 -> exit 0, oom/timeout/crash: 0/0/0 for all four,
fuzz/artifacts/* empty.
2026-09-17 20:52:44 -04:00
4a06d794f1 Merge pull request 'ratchet: freeze the v1 state/frame wire format with guard tests' (#98) from wt/t_0ffa68d2 into main
All checks were successful
ci / test (push) Successful in 4m50s
ci / sdk (push) Successful in 55s
Reviewed-on: #98
2026-09-18 00:50:37 +00:00
ba3c39cfe1 Merge branch 'main' into wt/t_0ffa68d2
All checks were successful
ci / test (pull_request) Successful in 4m59s
ci / sdk (pull_request) Successful in 1m7s
2026-09-18 00:50:24 +00:00
fa53237968 Merge pull request 'tests: assert the DH ratchet step in lockstep on a bidirectional burst' (#97) from wt/t_d686a78c into main
Some checks failed
ci / test (push) Has been cancelled
ci / sdk (push) Has been cancelled
Reviewed-on: #97
2026-09-18 00:49:29 +00:00
rust-dev
6827b87a29
tui: F8 rotate prekey + Node::rotate_prekey (hard cut, drops ratchet state)
All checks were successful
ci / test (pull_request) Successful in 5m0s
ci / sdk (pull_request) Successful in 1m11s
android-ci / android (pull_request) Successful in 8m36s
The signed prekey was set at invite creation and never rotated: a long-lived
static is a long-lived forward-secrecy window. F8 now rotates it.

- Node::rotate_prekey(): new X25519 keypair, written through the existing
  replace_identity_keys prekey columns (no store change needed), live Keys
  updated, new pubkey returned for the invite re-encode. Identity untouched.
- It drops every stored ratchet session: the bootstrap epoch is derived from
  the prekey DH, so each friend has to F3-paste the new invite. Nothing is
  pushed to peers \u2014 there is no in-band prekey update.
- TUI: F8 on Main opens the confirm screen (type ROTATE, same prompt as F4),
  then re-opens the F2 share path with the new invite; help overlay + footer
  hint list it.
- Docs: THREAT_MODEL gains a section on the F8 hard cut and the prekey-bound
  epoch bullet; README key table and PROTOCOL 'Roles and keys' follow.

Tests: node-level rotation test (identity/pk/stored row/ratchet drop/invite),
tests/rotate.rs screen text + prompt, tui_chrome help needs F8.
2026-09-17 20:48:10 -04:00
Hermes rust-dev
69672809ab
tls: default to Arti's rustls backend (drop OpenSSL from TLS)
All checks were successful
ci / test (pull_request) Successful in 6m47s
android-ci / android (pull_request) Successful in 8m21s
ci / sdk (pull_request) Successful in 1m25s
Arti's TLS backends are non-additive; the root crate defaulted to
`native-tls` (OpenSSL). Switch `default = ["rustls"]` and pin the `rustls`
crate with its `ring` feature — `tor-rtcompat` pulls rustls in with
`default-features = false`, so without that pin the backend compiles with no
`CryptoProvider` and the first TLS config fails (same reason already recorded
in crates/onionwire-sdk/Cargo.toml).

`native-tls` stays as an opt-in feature. SQLCipher still builds vendored
OpenSSL (`bundled-sqlcipher-vendored-openssl`); that is unrelated to TLS.

- tests/tls_backend.rs: compile-time pin that the default features select
  rustls, plus a runtime check that rustls resolves a provider with no manual
  install.
- ci.yml: the root `test` job no longer installs pkg-config/libssl-dev (the
  SDK job keeps it).
- docs: README build deps, ARTI_UPGRADE backend table, release-body and the
  SDK README now describe the rustls default; the false "binaries link
  libssl.so.3 dynamically" claim is corrected.
- crates/onionwire-sdk/Cargo.lock: regenerated for the root crate's new
  dependency (separate workspace, --locked would otherwise fail).
2026-09-17 20:48:05 -04:00
agent
dff37fe00e
docs+tui: reachability stance (no sealed mailbox) and peer-unreachable queued footer
Some checks failed
ci / test (pull_request) Has been cancelled
ci / sdk (pull_request) Has been cancelled
android-ci / android (pull_request) Has been cancelled
Add a Reachability section to docs/THREAT_MODEL.md: no sealed mailbox or
server-side message store, the chat outbox is local-device retry only, and
there is no mutual-online indicator — a send is a one-shot Noise IK session
and an unanswered dial queues locally with the retry clock shown.

OutboxSummary now carries the outstanding row's attempt count and soonest
retry, so the footer reads 'peer unreachable, queued (n/8, retry 45s)'
instead of a bare 'n queued'. Tests updated to the real outbox wording; the
Android KDoc note stops claiming the footer copy is mirrored (Android shows
per-row 'queued (try n/8, retry …)' via OutboxDetail).
2026-09-17 20:44:28 -04:00
agent
1aec007601
ratchet: freeze the v1 state/frame wire format with guard tests
All checks were successful
ci / test (pull_request) Successful in 4m47s
ci / sdk (pull_request) Successful in 57s
The persisted ratchet state had a version byte and typed errors but no
test that a format change would actually be caught. Add two dedicated
guards to tests/ratchet.rs that assert the frozen shape as literals
(0x01, 210-byte prefix) rather than via STATE_VERSION, so a bump breaks
them visibly, and pin that any foreign version byte is rejected with
Error::UnsupportedStateVersion before any field is read.

Document the frozen v1 state layout, the rat frame layout, and the
migration path a v2 must follow in references/ratchet-wire-frozen.md.

Verified by flipping STATE_VERSION to 2: both guards fail
("the frozen version byte changed"), then revert.
2026-09-17 20:43:31 -04:00
agent
6f267a6aba
tests: assert the DH ratchet step in lockstep on a bidirectional burst
All checks were successful
ci / test (pull_request) Successful in 4m51s
ci / sdk (pull_request) Successful in 58s
`round_trip_across_two_dh_ratchet_steps` only asserts that neither sending
ratchet key stayed put; it would still pass if the two sides stepped onto
unconnected epochs, and it never checks that either peer adopted the key the
other advertised. The new test reads dh_pub out of the wire header and pins the
adoption per step across an A->B / B->A burst:

- round 1 rotates only the lower-key (establishing) peer, so one round cannot
  lockstep both sides -- the intermediate state is asserted, not assumed;
- rounds 2 and 3 step each side in turn, asserting each receiver adopts exactly
  the key the frame advertised;
- the three-frame burst each way asserts chain reads (not extra steps), zero
  skipped keys, and that the peer that received last is keyed to the other's
  current key.

tests/ratchet.rs only; no src change, no new dependency.
2026-09-17 20:41:48 -04:00
ad1b994c08 Merge pull request 'onionwire: outbound tip() appends the sender's own [tip] chat line' (#96) from wt/t_c8441534 into main
All checks were successful
ci / test (push) Successful in 4m45s
ci / sdk (push) Successful in 58s
android-ci / android (push) Successful in 8m30s
Reviewed-on: #96
2026-09-17 21:27:04 +00:00
rust-dev
2ec88b0ce5
onionwire: outbound tip() appends the sender's own [tip] chat line
All checks were successful
ci / test (pull_request) Successful in 5m0s
ci / sdk (pull_request) Successful in 1m9s
android-ci / android (pull_request) Successful in 8m44s
The outbound tip path signed and sent a receipt frame and a tip frame and
logged the receipt line, but never the tip line, so the payer's own chat
showed only `[receipt] 0.5 XMR` — the recipient's view — for what they
had just spent. Append `pay::tip_chat_line(atomic, memo, false)` after the
receipt line so the sender sees `[tip] 0.5 XMR — memo (pending)`.

Test: outbound_tip_appends_the_senders_own_tip_chat_line in src/node.rs's
`#[cfg(test)] mod tests` — the only place a `Node` can be built offline
(Node::start bootstraps Tor). It drives the shipped tip() against a mock
wallet child (Digest challenge + one transfer) and asserts both chat rows.
2026-09-17 17:05:56 -04:00
918fa4d8a8 Merge pull request 'docs: Cuprate cross-compiles for Android aarch64 (NDK r28c, minSdk 26)' (#93) from wt/cuprate-android-crosscompile-spike into main
Reviewed-on: #93
2026-09-17 04:08:28 +00:00
rust-dev
e0bd4e4218
docs: Cuprate cross-compiles for Android aarch64 (NDK r28c, minSdk 26)
Spike evidence for the Phase 1 Android question: cargo check --release --target
aarch64-linux-android exits 0 and the PoC binary links as an Android 26 aarch64 ELF.
Documents the env recipe, the four link args the C++ RandomX build needs, the
cargo-ndk linker-wrapper bug, and the RANDOMX_DIR/DARCH no-op.
2026-09-16 23:58:25 -04:00
564036813a Merge pull request 'docs: Cuprate in-process launch spike A (testnet launch + RPC/sync evidence)' (#92) from wt/cuprate-testnet-spike into main
Reviewed-on: #92
2026-09-17 03:42:42 +00:00
agent
12db06b2ed
docs: Cuprate in-process launch spike A — testnet launch, RPC and sync evidence
Spike A of the Cuprate exploration: Node::launch(config).await runs a real
testnet chain daemon in-process (no monerod, no subprocess). Unrestricted RPC
on 127.0.0.1:18089 answers get_info, /get_height and get_block (heights 0, 1, 2,
1000) with monerod-shaped payloads, and clearnet P2P synced 0 -> 23,758 testnet
blocks in ~120s. Verdict VALIDATED with four parity gaps recorded:
out-of-range get_block returns a bare HTTP 500 with an empty body (monerod
returns a JSON-RPC error object), get_info reports zero peers while syncing,
restricted get_info returns placeholder database_size/version, and the version
label is 0.1.0-preview-release.
2026-09-16 23:39:12 -04:00
agent
c090f16dab
docs: add Cuprate phased integration strategy to payment plan
Adds strategic recommendation: Phase 1 (Cuprate in-process for chain +
monero-wallet-rpc subprocess pointing at it) and Phase 2 (monero-wallet
crate for full in-process wallet). Includes RPC compatibility note,
binary size comparison (+5.6 MB vs ~52 MB monerod), and version
conflict resolution confirmation.

See references/cuprate-integration.md and Obsidian notes for full details.
2026-09-16 23:15:55 -04:00
598270b519 Merge pull request 'ratchet: reject frames under MIN_FRAME_LEN before indexing the version byte (fixes peer-reachable panic)' (#90) from wt/t_c0566260 into main
All checks were successful
ci / test (push) Successful in 4m45s
ci / sdk (push) Successful in 56s
android-ci / android (push) Successful in 7m55s
Reviewed-on: #90
2026-09-17 02:46:17 +00:00
agent
7ba07f84ea
docs: add Cuprate in-process daemon exploration to payment plan
Adds §7a documenting the alternative approach of embedding Cuprate's
crates directly into the OnionWire binary instead of spawning monerod
as a subprocess. Includes PoC results (cargo check passed with both
arti-client 0.44 and 0.46), the wallet-layer gap, dependency bloat
assessment, and exploration card titles.

Does not change any locks — the subprocess wrapper model remains the
default path. See references/cuprate-integration.md for full test log.
2026-09-16 22:47:17 -04:00
8bedf45e53 Merge branch 'main' into wt/t_c0566260
All checks were successful
ci / test (pull_request) Successful in 5m10s
ci / sdk (pull_request) Successful in 1m14s
android-ci / android (pull_request) Successful in 8m5s
2026-09-17 02:46:03 +00:00
agent
3c78cd3e39
ratchet: reject frames under MIN_FRAME_LEN before indexing the version byte
All checks were successful
ci / test (pull_request) Successful in 4m46s
ci / sdk (pull_request) Successful in 56s
android-ci / android (pull_request) Successful in 9m54s
Frame::parse checked the prefix, then indexed frame[4] for the version byte,
then checked the length. A 4-byte `rat ` frame is a prefix hit, so it
panicked with 'index out of bounds: the len is 4 but the index is 4' instead
of being rejected. dispatch::classify routes any `rat `-prefixed message to
Kind::Ratchet, so this is reachable from any authenticated peer.

Move the MIN_FRAME_LEN check ahead of the version match: a frame that cannot
hold a header, nonce and tag is 'truncated' whatever its version byte says,
and nothing past the prefix is indexed until the length is known good. Wire
format unchanged.

Tests: tests/ratchet.rs short_frames_are_rejected_without_panicking (bare
prefix, empty slice, partial prefix, prefix + 5 bytes, MIN_FRAME_LEN - 1) and
a_wrong_frame_version_is_rejected (73-byte frame with version 2 is
BadFrame("version"); a short one is a length error). Both assert the state
stays byte-identical after every rejection.
2026-09-16 19:50:36 -04:00
cf77116143 Merge pull request 'docs: ratchet wire spec + forward-secrecy/PCS threat-model claims' (#89) from wt/t_29a71a55 into main
Reviewed-on: #89
2026-09-16 23:45:59 +00:00
agent
7f3ef8c3fc
docs: ratchet wire spec + forward-secrecy/PCS threat-model claims
PROTOCOL.md gains a 'Ratchet (v1 chat layer)' section written so a second
implementation can interoperate from the text alone: byte-exact frame layout
(rat , 0x01, dh_pub||N||PN as header and AAD, 12-byte nonce,
ChaCha20-Poly1305), the KDF_RK/KDF_CK constructions and the role-separated
epoch rule, the derived bootstrap epoch, the receive and DH-step rules, the
MAX_SKIP/MAX_SKIPPED_KEYS bounds with the replay rule, the SQLCipher
ratchet_sessions row, and what stays unratcheted.

THREAT_MODEL.md gains the corresponding gains (per-chain forward secrecy, PCS
after a DH step, header not on the wire) and honest limits (skipped-key
window, the prekey-bound bootstrap epoch, no deniability, no one-time
prekeys, compromised endpoint out of scope, no metadata gain, the no-server-
outbox lock untouched) plus the amended transport wording.

README.md documents the operator-visible consequence: no reset command yet,
prekey change / invite re-paste is the only recovery, /wipe keeps the state,
and a desync is currently stderr-only.
2026-09-16 19:40:40 -04:00
1c998e9472 Merge pull request 'ratchet verify: end-to-end + adversarial tests on the wired chat path' (#88) from wt/t_95ff7563 into main
All checks were successful
ci / test (push) Successful in 4m41s
ci / sdk (push) Successful in 57s
android-ci / android (push) Successful in 9m32s
Reviewed-on: #88
2026-09-16 23:31:23 +00:00
rust-dev
3620e4f38f
ratchet: end-to-end and adversarial tests on the wired send/receive path
All checks were successful
ci / test (pull_request) Successful in 4m54s
ci / sdk (pull_request) Successful in 1m0s
android-ci / android (pull_request) Successful in 9m26s
Drives the shipped chat ratchet offline against real SQLCipher stores and
the real encode/decode pair Node::send and Node::handle_incoming call, with
a capture-and-release Deliverer so arrival order and drops are controlled.

tests/ratchet_e2e.rs: full exchange, out-of-order arrival, a dropped frame,
a retried frame re-sent byte-identically, and a restart of both peers.

tests/ratchet_adversarial.rs: a frame claiming a jump past MAX_SKIP, a
post-compromise snapshot across a DH step, an unknown friend, a retired
epoch after an invite refresh, and five corruption shapes. Every rejected
frame is asserted to leave the persisted ratchet blob byte-identical.

src/node.rs gains a test-only module that builds a Node with an
unbootstrapped Tor client and drives Node::send plus the real receive path
(Noise IK handshake over an in-memory stream into handle_incoming).
2026-09-16 19:30:39 -04:00
4e8d8c0f25 Merge pull request 'Chat over the Double Ratchet: dispatch Kind::Ratchet + outbox payload' (#87) from wt/t_dcafd1c8 into main
All checks were successful
ci / sdk (push) Successful in 58s
ci / test (push) Successful in 4m18s
android-ci / android (push) Successful in 8m46s
Reviewed-on: #87
2026-09-16 23:08:21 +00:00
agent
69a15fe909
chat: send and receive as ratchet frames through the outbox payload
All checks were successful
ci / test (pull_request) Successful in 4m36s
ci / sdk (pull_request) Successful in 1m15s
android-ci / android (pull_request) Successful in 9m25s
Chat plaintext is ratchet-encrypted once, before the first delivery attempt,
and the frame is what the outbox stores and retries, so a retried message
re-sends identical bytes instead of advancing the sending chain twice.

- dispatch: Kind::Ratchet for the `rat ` prefix, matched before the unknown
  [a-z]{3} prefix rule
- node: encode_chat_frame / ingest_chat_frame (the wire halves of Node::send
  and handle_incoming), bootstrap derived from the peers' static prekey DH
  because the Noise handshake is frozen and carries no ratchet key
- outbox: nullable outbox.payload + Outbox::send_payload; NULL payload keeps
  the previous row-for-row behaviour
- store: additive outbox.payload migration, enqueue_outbox_payload,
  OutboxEntry::payload
- add_friend_payload: a changed prekey clears the (prekey-bound) ratchet state

tests/ratchet_wire.rs (5) covers one frame per send, byte-identical retries,
out-of-order delivery, replay, tampering and fresh-friend both directions.

tests/tui_spec.rs and crates/onionwire-sdk/src/lib.rs only gained a
`payload: None` field in their OutboxEntry test fixtures: the card's required
field on a pub struct cannot be added without it.
2026-09-16 19:02:52 -04:00
14fccd5396 Merge pull request 'store: persist per-peer ratchet session state in the SQLCipher store' (#86) from wt/t_657d57c1 into main
All checks were successful
android-ci / android (push) Successful in 8m3s
ci / test (push) Successful in 4m6s
ci / sdk (push) Successful in 59s
Reviewed-on: #86
2026-09-16 22:35:11 +00:00
agent
34c257dab5
store: persist per-peer ratchet session state in the SQLCipher store
All checks were successful
android-ci / android (pull_request) Successful in 9m3s
ci / test (pull_request) Successful in 4m11s
ci / sdk (pull_request) Successful in 59s
New additive ratchet_sessions table (friend_id PK -> friends(id) ON DELETE
CASCADE, state BLOB, updated_at), plus load/save/clear_ratchet on Store. The
blob is the opaque versioned RatchetState::to_bytes output; the store never
parses or re-serializes it. wipe_messages deliberately keeps sessions: wiping
history is not a session reset.
2026-09-16 18:30:32 -04:00
5a36338178 Merge pull request 'ratchet: Double Ratchet state machine (symmetric + DH ratchet, bounded skipped keys)' (#85) from wt/t_85aaf5a6 into main
All checks were successful
ci / sdk (push) Successful in 55s
android-ci / android (push) Successful in 9m11s
ci / test (push) Successful in 4m2s
Reviewed-on: #85
2026-09-16 22:17:10 +00:00
agent
8b2e834616
ratchet: Double Ratchet state machine for chat frames
All checks were successful
ci / sdk (pull_request) Successful in 1m25s
android-ci / android (pull_request) Successful in 9m12s
ci / test (pull_request) Successful in 4m35s
New wire-independent `src/ratchet.rs` + `tests/ratchet.rs`: KDF_RK/KDF_CK as in
the Signal spec, symmetric ratchet, DH ratchet, skipped-key store with the
MAX_SKIP / MAX_SKIPPED_KEYS bounds, versioned state serialization and zeroize
of every superseded secret.

Initiation gate: per-direction chains seeded by ratchet-key ordering (option
(a)), so both peers can build a sending chain before either has received, and a
single deterministic tie-break (lower ratchet key rotates first) keeps exactly
one rotation in flight. Documented under "Initiation and convergence" and
covered by both_peers_send_first_converges, which fails on a crossing rotation.

Adds hkdf 0.12 + hmac 0.12 (0.13 pulls digest 0.11 and will not build against
sha2 0.10) and regenerates crates/onionwire-sdk/Cargo.lock.
2026-09-16 18:05:39 -04:00
3eee27fd09 Merge pull request 'tui: extract pub ColorMode/TokenStyles/tokens_for for testable colour tokens' (#80) from wt/t_49b7c2b1 into main
All checks were successful
android-ci / android (push) Successful in 8m27s
ci / sdk (push) Successful in 57s
ci / test (push) Successful in 3m55s
Reviewed-on: #80
2026-09-15 21:51:15 +00:00
3a17a564d3 Merge branch 'main' into wt/t_49b7c2b1
Some checks failed
ci / sdk (pull_request) Successful in 1m8s
android-ci / android (pull_request) Has been cancelled
ci / test (pull_request) Successful in 4m3s
2026-09-15 21:50:53 +00:00
agent
d4b0071d1a
tui: fix clippy unnecessary_unwrap in NO_COLOR cleanup
All checks were successful
ci / test (pull_request) Successful in 3m58s
ci / sdk (pull_request) Successful in 56s
android-ci / android (pull_request) Successful in 8m16s
The alert_line_prefixes_when_no_color test stashed the prior NO_COLOR
value and restored it with is_none() + unwrap() — a clippy lint failure
under -D warnings. Replace with a match that takes ownership.

No behavior change; the restored env var is identical.

Co-authored-by: openhands <[email protected]>
2026-09-15 17:34:59 -04:00
agent
6ce97a0e3c
tui: extract pub ColorMode/TokenStyles/tokens_for for testable colour tokens
Some checks failed
ci / test (pull_request) Failing after 4m22s
ci / sdk (pull_request) Successful in 1m16s
android-ci / android (pull_request) Successful in 8m16s
Make ColorMode a pub enum with pub color_mode() fn, add TokenStyles
struct and tokens_for(mode) as the single source of truth for the
style_* helpers. Tests assert RGB/None/Ansi16 fg/bg/modifier resolution
without depending on process environment.
2026-09-15 17:29:26 -04:00
995f46013e Merge pull request 'feat(sdk): sign/encode/decode/verify invoice, receipt and tip frames' (#77) from wt/t_cd793d2c into main
All checks were successful
ci / test (push) Successful in 3m55s
android-ci / android (push) Successful in 8m42s
ci / sdk (push) Successful in 56s
Reviewed-on: #77
2026-09-15 17:38:35 +00:00
b1dd18a4a2 Merge branch 'main' into wt/t_cd793d2c
All checks were successful
ci / test (pull_request) Successful in 3m51s
ci / sdk (pull_request) Successful in 57s
android-ci / android (pull_request) Successful in 8m33s
2026-09-15 17:01:58 +00:00
agent
96d582153a
feat(sdk): sign/encode/decode/verify invoice, receipt and tip frames
All checks were successful
ci / test (pull_request) Successful in 4m24s
android-ci / android (pull_request) Successful in 8m53s
ci / sdk (pull_request) Successful in 1m17s
The SDK could already send an invoice or a tip through Node::pay_invoice /
Node::tip, but it could not touch the payment frames themselves: pay::sign_*
take the ed25519 identity secret and Node exposed only identity_pk(), so the
signing half lived nowhere the SDK could reach.

Add the signing surface to the node instead of exporting the key:

  * Node::sign_invoice / sign_receipt / sign_tip sign with the node's own
    identity key and return the core frame struct. The secret never leaves
    the process and there is no API that hands it out.
  * pay_invoice and tip now call those methods rather than signing inline, so
    there is one signing path, not two.

SDK (crates/onionwire-sdk), all backward compatible:

  * Records Invoice, Receipt, Tip mirroring src/pay.rs, sig as raw bytes so a
    frame re-encodes byte-for-byte.
  * Wire::sign_invoice / sign_receipt / sign_tip (async, over the node).
  * Free functions encode_invoice / encode_receipt / encode_tip,
    decode_invoice / decode_receipt / decode_tip (None on a foreign or
    truncated frame), verify_invoice / verify_receipt / verify_tip against
    the sender's pubkey hex (false on a bad key, never a panic).

Tests: 8 new SDK unit tests (record round-trips through the core encoders,
signer-key-only verification, tamper rejection, foreign/truncated frame,
typed Stopped error after shutdown). SDK 27 passed, 0 failed; SDK clippy
--all-targets -D warnings clean; root clippy --all-targets -D warnings
clean; root lib tests 14 passed; tests/pay.rs 11 passed.
2026-09-15 12:45:49 -04:00
3dc52edc71 Merge pull request 'fix(android): make the new launcher icon actually display (adaptive icon + roundIcon)' (#74) from wt/app-icon-adaptive into main
All checks were successful
android-ci / android (push) Successful in 8m0s
Reviewed-on: #74
2026-09-15 02:31:22 +00:00
6f69d629fb Merge branch 'main' into wt/app-icon-adaptive
All checks were successful
ci / test (pull_request) Successful in 4m19s
ci / sdk (pull_request) Successful in 1m14s
android-ci / android (pull_request) Successful in 8m19s
2026-09-15 02:25:12 +00:00
agent
faf4d1bb15
fix(android): make the new launcher icon actually show up as an adaptive icon
The icon change landed as a bitmap dropped straight into
res/mipmap-anydpi-v26/ and wired to android:icon only, so the installed app
kept showing the old art:

- android:roundIcon still pointed at @mipmap/ic_launcher (the old vector
  adaptive icon). Launchers that prefer roundIcon — Pixel Launcher, Samsung
  One UI — render it in preference to android:icon, so the new bitmap never
  appeared. Verified on the ow35 emulator drawer: old cyan/green line-art
  onion while android:icon was already the new PNG.
- a bitmap under mipmap-anydpi-v26 is a legacy icon, not an adaptive one: the
  launcher pads it into the mask itself and it is not density-aware.

Now:
- drawable-nodpi/onionwire_app_icon.png: the artwork squared to 432x432 with
  the logo at 62% of the canvas (inside the 66dp/108dp safe zone) over a
  seamless blurred backdrop of itself, so no launcher mask clips the logo.
- mipmap-anydpi-v26/ic_launcher.xml and ic_launcher_round.xml: adaptive icons
  with that bitmap as the background layer and a transparent foreground.
- AndroidManifest.xml: icon=@mipmap/ic_launcher, roundIcon=@mipmap/ic_launcher_round.
- Delete the retired vectors (ic_launcher_background/foreground.xml) and the
  misplaced mipmap-anydpi-v26/onionwire_app_icon.png.
2026-09-14 22:16:24 -04:00
33d5d080a4 Merge pull request 'docs(readme): document v0.2.1 wallet create/import, tip frame, F6 screen, SDK payment surface' (#72) from docs/readme-v0.2.1-wallet into main
Reviewed-on: #72
2026-09-14 21:11:15 +00:00
agent
e3a051a980
docs(readme): document v0.2.1 wallet create/import, tip frame, F6 screen, SDK payment surface
All checks were successful
ci / test (pull_request) Successful in 3m54s
ci / sdk (pull_request) Successful in 56s
android-ci / android (pull_request) Successful in 7m37s
2026-09-14 17:00:46 -04:00
agent
2141a6e9a5
fix(ci): resolve conflict markers left in scripts/publish-release.sh
The file reached main with an unresolved stash conflict at the auth_json
helper (line 24) and the asset-upload curl (line 133). Both publish jobs
run it directly, so every release/android-release publish dies with
"line 24: syntax error near unexpected token <<<". Keep the HTTP Basic
auth_json with the CR strip, and the single-line -X POST -u asset upload.
2026-09-14 13:22:53 -04:00
8e97b12f73 Merge pull request 'ci(android): build the APK+AAR on android/, src/ and crates/ changes' (#71) from ci/android-verify into main
All checks were successful
android-ci / android (push) Successful in 7m58s
Reviewed-on: #71
2026-09-14 16:25:55 +00:00
ef1248e730
ci(android): build the APK+AAR on android/, src/ and crates/ changes
All checks were successful
android-ci / android (pull_request) Successful in 9m30s
An android-only PR ran zero jobs: ci.yml's path allowlist never matches
android/**, and android-release.yml is dispatch-driven. #70 merged on an
empty check list.

android-ci.yml runs the release's gradle targets through the release's own
script (scripts/build-android-local.sh) on the amd64 runner, debug-signed,
publishing nothing. Same concurrency group and runner volumes as
android-release.yml so the build is warm and cannot collide with a release.
2026-09-14 12:16:40 -04:00
ce463e8568 Merge pull request 'android: one chat poller owned by the ViewModel, gated auto-scroll, Enter-to-send' (#70) from wt/t_7db68274 into main
Reviewed-on: #70
2026-09-14 16:01:34 +00:00
0150261da2 Merge branch 'main' into wt/t_7db68274 2026-09-14 15:51:43 +00:00
c169e41c33 Merge pull request 'android: wallet + roster bottom actions clipped while the keyboard is up' (#69) from wt/t_3a094045 into main
Reviewed-on: #69
2026-09-14 15:51:31 +00:00
77428789cb Merge branch 'main' into wt/t_3a094045 2026-09-14 15:51:24 +00:00
agent
04c993862c
android: one chat poller owned by the ViewModel, gated auto-scroll, Enter-to-send
The chat screen owned a LaunchedEffect(Unit) that fetched maxAttempts once and
then called loadMessages/loadOutbox every 2s forever, fed by three suspend
lambdas from MainActivity — one SDK poller per composition. The cadence now
lives in WireViewModel: openChat(peer) starts one 2s loop in viewModelScope
(closeChat stops it, re-entering the same peer is a no-op), exposed as
ChatState(messages, outbox, maxAttempts, error) and collected with
collectAsStateWithLifecycle. Same 2s cadence, maxAttempts read once, messages
and outbox refreshed together, load failures sticky on ChatState.error, and
the QUEUED notice unchanged; a send clears the load error.

Auto-scroll no longer steals the reader's place: the tail is followed only when
the last visible index is >= count - 2 (or the list has not filled yet), while
the user's own send still scrolls their message into view. The first fill keeps
its one jump to the bottom. A delivery-only change (same size) still does not
re-run the effect — documented in a comment rather than changed.

The composer keeps ImeAction.Send with maxLines = 4, documented as a deliberate
wrap limit rather than a newline affordance: the action key sends (hardware
Enter still inserts a newline inside the field).

No polling LaunchedEffect remains in ChatScreen.kt.
2026-09-14 02:54:33 -04:00
apk-dev
535a2baff9
android: wallet + roster bottom actions clipped while the keyboard is up
The two screens whose action row lives inside a non-scrollable Column could
not be un-covered by insets alone: the container had no scroll range at all.

- WalletScreen: root Column is now a verticalScroll viewport that consumes
  systemBars ∪ ime itself (screenContentInsets()) before the scroll, paired
  with Scaffold(contentWindowInsets = 0). The nested LazyColumn becomes a
  plain Column (a lazy list cannot be measured inside a scroll container with
  unbounded height) and the weight(1f) bottom spacer goes with it: a weighted
  spacer cannot live in a scrollable Column.
- RosterScreen: same inset treatment; the friends LazyColumn drops
  fillMaxSize() for weight(1f) so the wipe-confirm strip above it keeps its
  height when the IME shrinks the window.
- Insets.kt is PR #67's helper, taken verbatim (this branch does not carry #67).

Stacked on PR #67 (wt/chat-ime-insets, 08381c4) for ui/Insets.kt.
2026-09-14 02:05:03 -04:00
f95e058041 Merge pull request 'android: copy the invite with LocalClipboard, not the deprecated LocalClipboardManager' (#68) from wt/t_f495ce39 into main
Reviewed-on: #68
2026-09-14 05:01:36 +00:00
agent
9c36814eb3
android: copy the invite with LocalClipboard, not the deprecated LocalClipboardManager
LocalClipboardManager is deprecated in compose ui 1.10; the warning was the
only one in :app:compileDebugKotlin. Switch ShareInviteScreen to
LocalClipboard.setClipEntry(ClipEntry(ClipData.newPlainText(...))) on a
rememberCoroutineScope, since the new API is suspend. Same text, same
copied-state flip, same label, no permission change.
2026-09-14 00:49:49 -04:00
ba261a86eb Merge pull request 'android: keep the chat composer above the keyboard (ime insets)' (#67) from wt/chat-ime-insets into main
Reviewed-on: #67
2026-09-14 04:34:11 +00:00
agent
08381c47be
android: keep the chat composer above the keyboard (ime insets)
enableEdgeToEdge() sets decorFitsSystemWindows=false, so on API 30+ the framework
no longer resizes the window for the soft keyboard. The manifest's
android:windowSoftInputMode="adjustResize" therefore has nothing to resize and the
IME arrives as an unconsumed window inset; Scaffold's contentWindowInsets covers
systemBars only. Result: the composer row, its Send button and the typed body were
drawn underneath the keyboard and only reachable by dismissing it.

- ui/Insets.kt (new): screenContentInsets() applies systemBars ∪ ime once, at the
  screen's content root. union is per-side max, so the keyboard and the navigation
  bar are never summed; the Top side is excluded because a Scaffold's pad.top is
  already the app bar's measured height (the app bar carries its own status-bar
  inset). @Composable because WindowInsets.ime is a composable read.
- ChatScreen: Scaffold(contentWindowInsets = 0) plus the root consuming the inset;
  the body region holds weight(1f) in every branch (loading and empty included) so
  the composer can never be squeezed off the bottom; Send is always drawn instead
  of being swapped for a spinner (no layout jump under the thumb); the field sets
  ImeAction.Send so the keyboard's own action key sends; focus returns to the
  field after a send; testTag on the composer/input/send.
- InviteScreens (both screens) and RotateScreen: same inset handoff, so the
  Verify / Approve / confirm buttons under a text field stay reachable by scrolling.
- UnlockScreen: safeDrawingPadding(). It had no system-bar insets at all (title
  drawn under the status bar) and its Open button sat under the keyboard while a
  passphrase was being typed.

Verified on emulator-5554 (ow35, x86_64, API 35) with the debug build whose sources
are byte-identical to this commit:

  element        keyboard closed   keyboard open
  composer       y=2232            y=1380
  Send button    y=2253            y=1433
  keyboard top   -                 y≈1500

mInputShown=true while the draft text was visible; the message sent both via the
Send button and via the keyboard's action key (paper-plane = ImeAction.Send), each
landing with the ✓✓ delivery marker. :app:testDebugUnitTest green.

Note: no CI job covers this — ci.yml's path allowlist is src/**, crates/**,
tests/**, Cargo.*, so an android-only change runs nothing, and android-release.yml
only fires on v*.*.* tags.
2026-09-14 00:26:14 -04:00
87fc3ca1b9 Merge pull request 'wallet: in-app create/import (create takes no key) + opt-in spend policy' (#66) from feat/wallet-create-import into main
All checks were successful
ci / test (push) Successful in 3m54s
ci / sdk (push) Successful in 57s
Reviewed-on: #66
2026-09-14 03:31:19 +00:00
Lance Walters
cf0a517cd2
wallet: create/import in-app (no key paste on create) + opt-in spend
All checks were successful
ci / test (pull_request) Successful in 4m15s
ci / sdk (pull_request) Successful in 1m12s
/ wallet create generates a wallet on the RPC and shows the 25-word seed
once for backup; /wallet import is the only path that takes an existing
seed, and it is collected on a dedicated screen so it never reaches the
composer line or chat history.

Threat model now states the real policy: payments are opt-in, default is
no spend key, spend is a local authority at create/restore, and the chain
source is the user's choice (spawned local monerod or a daemon address
they supply). WALLET.md and README follow.

Tests: canned-RPC create/restore, slash parse, help overlay.
2026-09-13 23:25:25 -04:00
agent
7ad3679b51
change app icon 2026-09-13 21:23:27 -04:00
agent
1aecbbee72
change app icon 2026-09-13 21:15:16 -04:00
11510d3993 Merge pull request 'feat(android): wallet screen + SDK payment surface' (#65) from feat/android-wallet into main
All checks were successful
ci / test (push) Successful in 3m55s
ci / sdk (push) Successful in 57s
Reviewed-on: #65
2026-09-13 19:48:00 +00:00
agent
9c4067d09e
fix(tui): clippy question_mark / unwrap_or_default in open_wallet
All checks were successful
ci / test (pull_request) Successful in 4m8s
ci / sdk (pull_request) Successful in 1m2s
CI clippy -D warnings failed on the match arms in src/tui.rs:1603.
2026-09-13 15:34:39 -04:00
agent
7cf98bb9fe
feat(android): wallet screen and SDK payment surface
Some checks failed
ci / test (pull_request) Failing after 4m1s
ci / sdk (pull_request) Successful in 1m27s
Expose wallet balance/address/transfers plus one-shot invoice and tip on
the UniFFI SDK. Wire a Compose wallet route (QR, composers) without dropping
wipe-chat. Ignore machine-local android/.cargo NDK paths.
2026-09-13 15:27:57 -04:00
agent
dc52df2366
ci(release): authenticate Forgejo API with HTTP Basic
Bearer is rejected on this instance (403/1010). Use sirius + token, matching
the dispatch path that actually works.
2026-09-13 15:27:57 -04:00
agent
10d81964a5
feat: tip frame (sign/verify/encode/decode), wallet balance + receive address, F6 wallet screen with QR, dispatch Kind::Tip
Some checks failed
ci / test (push) Failing after 9m39s
ci / sdk (push) Failing after 20s
2026-09-12 23:13:22 -04:00
7b147d8ebe Merge pull request 'docs(readme): document local outbox, delivery UI, wallet no-spend, Android stack' (#64) from docs/readme-new-features into main
Reviewed-on: #64
2026-09-13 01:06:08 +00:00
agent
e979203c20
docs(readme): document local outbox, delivery UI, wallet no-spend, Android stack
README still claimed "peer down → send fails / no outbox" after the local
chat outbox, TUI/Android delivery markers, SDK SendState/outbox rows,
view-only wallet switch, zeroize, Keystore-wrapped passphrase, and
foreground keep-alive all landed on main. Align the operator-facing
summary with PROTOCOL.md / THREAT_MODEL.md / TUI.md / WALLET.md:

- intro + first-run: local outbox for chat, fail-closed for fil/rcp
- replace Fail closed section with Local outbox (chat) and fail closed
- Monero: prefer view-only + ONIONWIRE_WALLET_NO_SPEND
- seized laptop: zeroize + pending outbox rows in the same store
- Android: SendState/outbox rows, delivery UI, FGS keep-alive, Keystore;
  android-release is dispatch-only
- Not in v1: ban is server-side outbox only
2026-09-12 21:04:50 -04:00
a8aa3098c7 Merge pull request 'fix(sdk): send() returns SendState (Sent|Queued), and build the SDK in CI' (#51) from wt/t_9a29fd3c into main
All checks were successful
ci / test (push) Successful in 3m57s
ci / sdk (push) Successful in 57s
Reviewed-on: #51
2026-09-12 23:58:29 +00:00
448cb73170 Merge pull request 'feat(android): surface outbox delivery state in chat (queued/sending/delivered/failed)' (#56) from feat/android-outbox-state into wt/t_9a29fd3c
All checks were successful
ci / test (pull_request) Successful in 3m52s
ci / sdk (pull_request) Successful in 59s
Reviewed-on: #56
2026-09-12 23:58:15 +00:00
a948627896 Merge pull request 'feat(sdk): expose outbox rows (attempts + next attempt time) behind a queued chat message' (#58) from feat/sdk-outbox-rows into feat/android-outbox-state
All checks were successful
ci / test (pull_request) Successful in 3m55s
ci / sdk (pull_request) Successful in 54s
Reviewed-on: #58
2026-09-12 23:58:01 +00:00
t
fc2b2197c7
feat(android): chat row renders queued (try 3/8, retry 45s) from the SDK's outbox rows
All checks were successful
ci / test (pull_request) Successful in 3m55s
ci / sdk (pull_request) Successful in 1m2s
Consumes the SDK surface from PR #58 (`Wire.outbox(pubkeyHex)` →
`OutboxRow { messageId, status, attempts, nextAttemptAt, lastError }` and
`outboxMaxAttempts()`): a queued chat row now says *why* it is still queued
instead of a flat `queued`.

* `OutboxDetail.kt` — `retryInText` mirrors `src/tui.rs::retry_in_text`
  (`<= 0` → `retry now`; `< 60` → `retry {n}s`; else `retry {ceil-minutes}m`),
  and `outboxDetails` joins the SDK's rows onto the chat rows. The denominator
  is the core's `outboxMaxAttempts()`/`Rust` budget, fetched once — never 8.
* A terminal `"failed"` row keeps the marker's own `failed: <reason>` and gets
  **no** countdown: `nextAttemptAt` on a failed row is the last time it was
  scheduled for, so a countdown there would promise an attempt that never comes.
  `"sending"` stays bare, matching the TUI.
* `ChatScreen` polls the outbox rows on the same 2s cadence as the bodies and
  renders the countdown against an injectable `nowSeconds` (the store holds an
  absolute instant, the app computes the age).
* The join is positional — `ChatMessage` carries no `messages.id` — and
  fail-closed: mismatched row counts, an unknown status, or a status that
  contradicts the one the SDK resolved for that message drops every detail and
  leaves the flat markers. `ChatMessage.id` would remove the positional part;
  filed as follow-up.
* `OutboxDetailTest` (17 tests) asserts the three `retry_in_text` buckets, the
  `queued (try 3/8, retry 45s)` wording, that a failed row shows no countdown,
  that the denominator comes from the caller, and the three fail-closed cases.
  32 unit tests, 0 failures.

Android base: PR #56 (`feat/android-outbox-state`, t_f46a9863) — the Android
half of the #52/#56 duplicate pair, which is not merged here. SDK base: PR #58
on PR #51.
2026-09-12 19:16:45 -04:00
rust-dev
7b68cb4a9f
feat(sdk): ChatMessage.id — join a chat row to its outbox row
`OutboxRow::message_id` documents itself as *the* join key (the
`messages.id` a `ChatMessage` belongs to), but the record carried no id,
so the Android client could only pair the two lists positionally.

Add `ChatMessage.id: i64` as the first field, copied straight from the
`messages.id` the store already selects. Additive over UniFFI: Kotlin
consumers only gain a constructor field and the bindings regenerate.

The id mapping moves into a `chat_message` helper so the join property is
testable without a Node: the new test builds a real store, queues an
outbox row for a message, and asserts the id on the message equals the
`message_id` the outbox row reports for that same row.

# Conflicts:
#	crates/onionwire-sdk/src/lib.rs
2026-09-12 19:16:45 -04:00
rust-dev (hermes)
56bd8845e7
feat(sdk): expose the outbox rows behind a queued chat message
The TUI can say why a queued row is still queued ('queued (try n/8,
retry 45s)') because it reads OutboxEntry::attempts and next_attempt_at
directly. The SDK exposed neither: ChatMessage.delivery is a flat
'queued'/'sending'/'failed: <reason>' string and Wire had no outbox
accessor, so an Android chat row could only invent a countdown.

Adds OutboxRow { message_id, status, attempts, next_attempt_at,
last_error } and Wire::outbox(pubkey_hex) over Node::outbox_pending, plus
outbox_max_attempts() so the client renders 'try n/8' against the core's
own budget instead of a hardcoded 8. Additive: Wire::send() and
ChatMessage.delivery are untouched.

# Conflicts:
#	crates/onionwire-sdk/src/lib.rs
2026-09-12 19:16:45 -04:00
apk-dev
c4b824a83d
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 19:16:44 -04:00
agent
f2dcd79d5c
fix(sdk): surface Sent/Queued on send(), and build the SDK in CI
All checks were successful
ci / test (pull_request) Successful in 3m56s
ci / sdk (pull_request) Successful in 53s
Node::send() became Result<OutboxStatus, String> in the local-outbox work,
which broke crates/onionwire-sdk — and nothing noticed, because the SDK is a
separate cargo workspace that root CI never compiles.

- Wire::send() returns WResult<SendState> (Sent | Queued)
- ChatMessage.delivery for outgoing rows
- New sdk job in ci.yml (own target volume; rustls workspace)
- Refresh SDK Cargo.lock + README (SQLCipher / outbox facts)

Rebased onto main after #50/#54: no src/node.rs changes (WAL checkpoint lives
in Store now). README at-rest claims kept from #55.
2026-09-12 19:16:42 -04:00
997b554bf1 Merge pull request 'ci(release): android-release cannot be woken by a CI-created tag — make it dispatch-only' (#63) from wt/t_95e0d607 into main
Reviewed-on: #63
2026-09-12 23:11:24 +00:00
7f8a1959df Merge branch 'main' into wt/t_95e0d607 2026-09-12 23:10:13 +00:00
2cf055c1e8
ci(release): android-release is dispatch-only; a CI-created tag cannot wake it
Neither decoupled trigger fires on Forgejo 10.0.3: a tag created by the CI
(API or git push) is an Actions-user push and is not dispatched back into
Actions, and reusable workflows need Forgejo >= 12. The release procedure is
therefore two dispatches: release.yml, then android-release with that tag.
2026-09-12 18:55:58 -04:00
7435ce42f5
ci(release): create the release tag with git push so the Android job fires
POST /tags sends no push event on this Forgejo (the v0.2.0 tag it created
produced no android-release run), so the tag is now created locally and
pushed, which does fire android-release.yml's `push: tags` trigger.
2026-09-12 18:49:14 -04:00
0c12abfa32 Merge pull request 'ci(release): manual, batched releases — no release on every merge' (#62) from wt/t_95e0d607 into main
Reviewed-on: #62
2026-09-12 22:29:20 +00:00
70ae597abc Merge branch 'main' into wt/t_95e0d607 2026-09-12 22:29:07 +00:00
46cff770ab Merge pull request 'feat(tui): join outbox rows to chat rows by message id (drop the body match)' (#50) from feat/tui-msgid-join into main
All checks were successful
release / x86_64 (push) Successful in 1m56s
release / aarch64 (push) Successful in 2m26s
release / publish (push) Successful in 12s
ci / test (push) Successful in 3m57s
release / version (push) Successful in 2s
Reviewed-on: #50
2026-09-12 22:11:26 +00:00
18ccab5464 Merge branch 'main' into feat/tui-msgid-join
All checks were successful
ci / test (pull_request) Successful in 4m10s
2026-09-12 22:10:54 +00:00
175cb58aba Merge pull request 'fix(store): checkpoint the WAL on the store's own keyed connection' (#54) from feat/store-checkpoint-wal into main
Some checks are pending
ci / test (push) Waiting to run
release / version (push) Waiting to run
release / aarch64 (push) Blocked by required conditions
release / x86_64 (push) Blocked by required conditions
release / publish (push) Blocked by required conditions
Reviewed-on: #54
2026-09-12 22:10:10 +00:00
111e90ce0a Merge branch 'main' into feat/store-checkpoint-wal
All checks were successful
ci / test (pull_request) Successful in 4m18s
2026-09-12 22:09:58 +00:00
c55dfd2492 Merge pull request 'feat(android): foreground service keeps the onion reachable through Doze' (#60) from feat/android-foreground-keepalive into main
Reviewed-on: #60
2026-09-12 22:08:46 +00:00
5032243934 Merge branch 'main' into feat/android-foreground-keepalive 2026-09-12 22:08:35 +00:00
6c9fd00b8a
ci(release): manual, batched releases — no release on merge
All checks were successful
ci / test (pull_request) Successful in 3m49s
Drop `push: branches: [main]` from both release workflows. release.yml now
runs only via workflow_dispatch, with bump (default minor), version, tag and
dry_run inputs; contradictory input is rejected instead of guessed at.

android-release.yml keeps the Android assets on the same tag by subscribing to
`push: tags: v*.*.*`: creating a tag over the API sends the same push
notification a git push does, so the core's tag wakes it. No workflow_call —
this Forgejo is 10.0.3, where reusable workflows are not supported.

docs/RELEASING.md is the policy and procedure.
2026-09-12 17:57:15 -04:00
dc4ed84a19 Merge pull request 'docs: README at-rest claims match the SQLCipher store (stale since #43)' (#55) from wt/t_f2fc5190 into main
Reviewed-on: #55
2026-09-12 21:21:06 +00:00
t
d256d3bb8e
docs: describe the SQLCipher store, not the pre-#43 design
The v0.2 banner and the "Seized laptop" section still claimed only chat
bodies were encrypted, that `self.identity_sk` and the roster were
plaintext, and that "sqlcipher is out of v1". That has been false since
#43.

- README banner: whole store is encrypted at rest with SQLCipher, with the
  row-bound AEAD layer kept on top.
- "Seized laptop": whole-file SQLCipher (Argon2id key over the 16-byte
  `store_salt`, raw `PRAGMA key`), identity/friends/locators inside the
  encrypted file, fail-closed unlock and `store_salt`-missing refusal, and
  the in-place v0.2.1 upgrade. Kept the honest caveats: no defense against
  a live compromise or a known passphrase, `/wipe` is not a forensic erase
  (SSD wear-levelling), and THREAT_MODEL.md stays the reference.
- "Not in v1": drop `sqlcipher` (shipped in #43).
- docs/SECURITY_AUDIT.md "Still true" bullet repeated the same plaintext
  claim; restated it as the residual risk that actually remains.

No code change. Evidence: cargo test --test store (21 passed, incl.
whole_store_file_is_encrypted_at_rest) and cargo test --lib -- store::
(6 passed, incl. the plaintext->SQLCipher upgrade and the wrong-passphrase
no-op).

Card: t_f2fc5190
2026-09-12 17:20:56 -04:00
rust-dev
2cbe7d41e5
feat(tui): join outbox rows to chat rows by message id
All checks were successful
ci / test (pull_request) Successful in 4m12s
`chat_with_delivery` matched pending outbox rows to chat rows by body
because `store::Message` carried no id, so an older send that was still
queued showed a delivered mark whenever a newer send of the same text had
already crossed the circuit.

`store::Message` now carries its `messages.id`, and the TUI joins
`OutboxEntry::message_id` == `Message::id`. The body match and its
newest-first fallback are gone.

`list_messages()` keeps its signature; callers that do not need the id
are untouched.
2026-09-12 17:12:30 -04:00
02b531625f Merge pull request 'feat(sdk): explicit Tor lifecycle — Wire.shutdown / flush / torState + observable state' (#49) from feat/tor-lifecycle into main
All checks were successful
ci / test (push) Successful in 4m17s
release / version (push) Successful in 2s
release / x86_64 (push) Successful in 1m55s
release / aarch64 (push) Successful in 2m25s
release / publish (push) Successful in 11s
Reviewed-on: #49
2026-09-12 20:58:31 +00:00
apk-dev
e923e06891
feat(android): keep the onion published through Doze with a foreground service
WireViewModel owned the single Wire node and called shutdown() from
onCleared(), so a backgrounded node died with the UI. Node lifetime is now
arbitrated by a pure policy (NodeLifetime) with two anchors — UI and
keep-alive — and one process-wide owner (NodeHost) that is the only caller
of flush()/shutdown() in the app.

KeepAliveService holds the process in the foreground behind an ongoing
notification from the "keep-alive" channel, started on unlock and stopped
by Lock or the notification action, so peers can still reach the device
while the screen is off.

- foregroundServiceType="specialUse": dataSync is documented as a finite
  transfer (upload/download/backup) and this is an always-on node
- POST_NOTIFICATIONS requested when the node becomes reachable; denial
  keeps the service running with no visible notice instead of failing
- re-unlock with a node the service kept alive adopts it rather than
  reopening the store the live node still holds
- 9 device-free unit tests for the start/stop/re-unlock state machine
2026-09-12 16:34:40 -04:00
cecad2b364 Merge pull request 'feat(tui): per-message outbox delivery state (queued/sending/sent/failed) + N queued footer' (#48) from feat/tui-outbox-state into main
All checks were successful
release / x86_64 (push) Successful in 1m52s
release / aarch64 (push) Successful in 2m25s
release / publish (push) Successful in 12s
ci / test (push) Successful in 6m1s
release / version (push) Successful in 2s
Reviewed-on: #48
2026-09-12 20:32:39 +00:00
a50df7ee43 Merge pull request 'feat(core): zeroize the profile/loc signing copy and the TUI passphrase buffer' (#47) from feat/zeroize-tui-profile into main
Some checks failed
release / version (push) Waiting to run
release / aarch64 (push) Blocked by required conditions
release / x86_64 (push) Blocked by required conditions
release / publish (push) Blocked by required conditions
ci / test (push) Has been cancelled
Reviewed-on: #47
2026-09-12 20:31:46 +00:00
beb523bdde Merge pull request 'wallet: no-spend (view-only) mode + RPC view-only detection + docs/WALLET.md' (#41) from feat/wallet-no-spend-view-only into main
All checks were successful
ci / test (push) Successful in 4m2s
release / version (push) Successful in 3s
release / x86_64 (push) Successful in 1m51s
release / aarch64 (push) Successful in 2m28s
release / publish (push) Successful in 10s
Reviewed-on: #41
2026-09-12 20:08:08 +00:00
t
2c3d9fd176
fix(store): checkpoint the WAL on the store's own keyed connection
All checks were successful
ci / test (pull_request) Successful in 4m23s
The WAL checkpoint that `Node::shutdown`/`flush` promise ran through a
short-lived second connection that no longer works: since the SQLCipher
store every db is encrypted and its key lives inside `Store`, so an
unkeyed second connection reads the file as noise and the checkpoint
degenerated to "store is SQLCipher-encrypted — skipped (file is not a
database)".

`Store::checkpoint_wal()` now runs `PRAGMA wal_checkpoint(TRUNCATE)` on
the connection `Store` owns, and `wipe_messages` reuses it instead of its
inline copy. The node-side helper and its doc caveat are gone; the
offline test moves with the code into `store.rs` and runs against a real
encrypted store (it failed on the old implementation with exactly the
SQLITE_NOTADB skip above). The live shutdown test now checks the WAL is
0 bytes after `flush` on a bootstrapped node.

Public signatures of `Node::shutdown`/`flush` are unchanged.
2026-09-12 15:56:33 -04:00
t
e3be8ffdd0
feat(core): zeroize the profile/loc signing copy and the TUI passphrase buffer
All checks were successful
ci / test (pull_request) Successful in 4m14s
The Ed25519 identity secret was still copied into a bare [u8; 32] on the
stack in two signers (profile::sign, loc::sign), and the TUI kept the
typed backup/restore passphrase in a plain String for the life of the
screen. Both now go through Zeroizing:

- profile::signing_key_bytes() builds the 32-byte copy into a
  Zeroizing<[u8; 32]> (same pattern as pay::sign_bytes / qr::encode,
  but with copy_from_slice so no Copy temporary is left behind);
  loc::sign shares the helper instead of making its own copy.
- Screen::Passphrase now owns a PassphraseEntry whose buffers are
  Zeroizing<String>. Every exit path (Enter, mismatch, Esc) calls
  close(), which wipes both buffers eagerly; a drop — including Ctrl-Q
  and a panic — is the backstop.

Evidence: tests/zeroize.rs gains a drop probe (ManuallyDrop +
drop_in_place + read_volatile) on the Zeroizing signing buffer and a
length-rejection test; src/tui.rs gains unit tests asserting the buffer
types and that close() leaves every byte of the passphrase's heap
capacity zeroed.
2026-09-12 15:41:54 -04:00
Sirius DevOps
323100b162
wallet: no-spend mode + view-only detection over RPC
All checks were successful
ci / test (pull_request) Successful in 4m11s
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.

When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.

New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 15:41:33 -04:00
agent
48c06df2cf
docs(sdk): Wire::shutdown doc said the second call returns Ok; it returns Stopped
All checks were successful
ci / test (pull_request) Successful in 4m22s
The handle-level call takes the node out on the first shutdown, so a second
call reports the typed `WireError::Stopped` (covered by
`calls_after_shutdown_are_typed_errors_not_panics`). Only the node-level
`Node::shutdown()` is Ok-idempotent. The rustdoc claimed otherwise.
2026-09-12 15:26:17 -04:00
apk-dev
c068e292a0
feat(android): stop the node when the UI goes away
`WireViewModel.lock()` set `wire = null` and `onCleared()` did not exist at all,
so neither the user pressing Lock nor the Activity finishing stopped anything:
Arti kept its client and the hosted onion service, the outbox worker kept
dialing, and the sqlite connection stayed open behind the JNI handle.

Both paths now go through `stopNode(Wire)`:

1. `flush()` — one last bounded drain, so a queued message gets its chance
   before the process may lose its socket.
2. `shutdown()` — drain again with a shorter budget, stop the onion service,
   abort the retry worker, checkpoint the WAL, and take the node handle out of
   the `Wire` (which is what releases the last Arc to the Tor client and the
   store).

Both run on a process-scoped `TEARDOWN` scope (`SupervisorJob` + `Dispatchers.IO`)
because `onCleared()` runs *after* `viewModelScope` is already cancelled. Errors
are deliberately swallowed there: the UI is gone, and the SDK reports a second
teardown as the typed `WireException.Stopped` rather than a panic.

`unlock()` joins any in-flight teardown before opening again. The old node holds
the sqlite file and Arti's state lock until its teardown returns, and racing it
makes the next `openWire` fail.

A process killed outright (Doze, background-process killer, force-stop) still
never runs any of this — that is what the sqlite outbox and the new `flush()`
are for. The foreground-service card (`t_5bf32cd3`) moves this ownership from
the ViewModel to the service.
2026-09-12 15:10:29 -04:00
apk-dev
38fde75d40
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state
A node had no way to stop. `Wire` was a bare handle over a `Node`: dropping the
Kotlin reference left Arti's client, the hosted v3 onion service, the outbox
retry worker and the sqlite connection alive, and there was no way to ask where
the onion service was. On Android the process is killed without warning by Doze
and the background-process killer, so "drop everything when the process dies" is
not a lifecycle.

Core (`src/node.rs`, `src/hs.rs`):

* `Node::shutdown()` — bounded outbox drain (10s), stop the onion service (the
  rendezvous task is aborted and the RunningOnionService dropped), abort the
  retry worker, checkpoint the sqlite WAL. Idempotent at this level: the flag is
  swapped first, so a racing second call is a no-op.
* `Node::flush() -> FlushOutcome { attempted, delivered, remaining }` — one
  delivery attempt for every queued outbox row, ignoring backoff, then a WAL
  checkpoint. Bounded by 30s because a dead peer's onion holds a dial for ~20s
  and the caller is a UI thread. A timeout leaves rows in `sending`;
  `Outbox::reset_stale` requeues them on the next unlock, same as a process that
  died mid-attempt.
* `Node::tor_state() -> TorState` (`Bootstrapping` / `Published` /
  `DegradedReachable` / `Stopped`) and `hs::tor_state_of(state, stopped,
  reachable)`, which mirrors `hs_is_ready` exactly instead of re-deriving
  readiness.
* Every network entry point (`send`, `send_once`, `connect_onion`, `rotate`,
  `flush`) fails with a typed error after the node stops, rather than dialing a
  dead client.
* `checkpoint_wal` reaches the database through a short-lived second connection:
  `Store` owns the write connection and does not lend it out, and a checkpoint is
  a property of the database, not of one connection. Best effort — WAL replay on
  open recovers anything committed.

The `WorkerHandle` moved into a `Mutex<Option<...>>` so the teardown can *abort*
the retry worker instead of only dropping it when the whole `Node` dies.

SDK (`crates/onionwire-sdk/src/lib.rs`):

* `Wire.shutdown()`, `Wire.flush(): FlushOutcome`, `Wire.torState(): TorState`.
  `Wire` now holds `Mutex<Option<Arc<Node>>>`, so teardown drops the last
  reference to the Tor client and the store instead of keeping them alive behind
  a JNI handle.
* `WireError::Stopped` — a second flat variant, so "you must unlock again" is a
  typed `WireException.Stopped` in Kotlin, not a string match on `Failed`.
* No `unwrap()` on a poisoned mutex anywhere: a poisoned handle reports
  `Stopped`, which is the correct recovery (unlock again).
* Fixes the crate not compiling on this base at all: `Node::send` has returned
  `Result<OutboxStatus, String>` since the outbox landed, and the SDK still
  mapped it to `Result<(), String>` (E0308). CI's path allowlist excludes
  `crates/**` from the Rust job, which is why it stayed green.

The live Tor test found a real bug in the first version of `tor_state`: Arti's
combined status is still `Bootstrapping` after a *successful* probe of our own
onion (that mismatch is what the 360s publish wait exists for), and a freshly
launched service reports `Shutdown` before its publish reactor starts — so a
node that was live and reachable reported `Bootstrapping`, and briefly
`Stopped`, right after unlock. `Node` now tracks an `onion_reachable` flag set
when the publish bar is crossed and cleared when `rotate` hard-cuts the service,
and `Shutdown`/`Broken` on a live node read `Bootstrapping` (transient) rather
than terminal.
2026-09-12 15:10:29 -04:00
c39259b919 Merge pull request 'feat(core): zeroize in-memory secret material (Noise/Ed25519/X25519/store key)' (#46) from feat/zeroize-secrets into main
All checks were successful
ci / test (push) Successful in 3m54s
release / version (push) Successful in 2s
release / x86_64 (push) Successful in 1m53s
release / aarch64 (push) Successful in 2m27s
release / publish (push) Successful in 11s
Reviewed-on: #46
2026-09-12 19:06:58 +00:00
8eb0820df0 Merge branch 'main' into feat/zeroize-secrets
All checks were successful
ci / test (pull_request) Successful in 6m33s
2026-09-12 19:06:50 +00:00
2a53bc2b89 Merge pull request 'feat(outbox): local chat retry queue — queue sends and retry with backoff' (#45) from feat/local-outbox into main
Some checks failed
release / version (push) Waiting to run
release / aarch64 (push) Blocked by required conditions
release / publish (push) Blocked by required conditions
release / x86_64 (push) Blocked by required conditions
ci / test (push) Has been cancelled
Reviewed-on: #45
2026-09-12 19:06:14 +00:00
t
b79f1fd6f3
feat(tui): per-message outbox delivery state + N queued footer
All checks were successful
ci / test (pull_request) Successful in 4m9s
Chat rows now carry the state the local outbox actually holds: `✓` delivered,
`◷ queued (try n/8, retry 45s)` while the retry worker still has it, `» sending`
mid-attempt and `✗ failed: <short reason>` once attempts are exhausted. The
footer replaces the flat `sent` / `send failed` copy with the live count
(`2 queued`), and keeps a fail-closed `send failed: …` statement as long as any
row is terminally failed.

States come from the outbox API (`Node::outbox_pending` → `Queued` / `Sending` /
`Failed`; a delivered row is deleted, so absence is `Sent`). No parallel state
model, no new wire prefix. Every new glyph has an ASCII fallback (`ok` plus the
state word) exercised by a test.

- `chat_with_delivery()` / `delivery_tag()` / `retry_in_text()` /
  `short_send_reason()` / `OutboxSummary::note()` are pure and unit-tested.
- `draw_chat()` is now the real chat-pane renderer (extracted from
  `App::draw_main`) so width/wrap is testable without a `Node`.
- docs/TUI.md: delivery markers, copy, and the 80x24 floor / 120x40 target.

Verified: cargo test 26/26 suites ok (tui_spec 20/20, incl. a real Store +
Outbox::send -> pending() -> render path); clippy --all-targets -D warnings clean.
2026-09-12 14:44:35 -04:00
Sirius DevOps
d6d157765a
feat(outbox): local retry queue for chat sends
All checks were successful
ci / test (pull_request) Successful in 4m8s
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.

- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
  is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
  messages row, under that row's existing AEAD + AAD), append_message_id(),
  queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
  Err on transport failure; protocol errors still fail immediately and are
  never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
  was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
  add the seizure/cadence delta to the threat model.

src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 14:39:14 -04:00
acb6c7dd65 Merge pull request 'feat(android): wrap the store passphrase in the Android Keystore' (#44) from feat/android-keystore-store-passphrase into main
Reviewed-on: #44
2026-09-12 18:29:19 +00:00
bf9900f9dc Merge branch 'main' into feat/android-keystore-store-passphrase 2026-09-12 18:29:10 +00:00
1582f7d450 Merge pull request 'feat(store): encrypt the whole sqlite store with SQLCipher' (#43) from feat/sqlcipher-store into main
All checks were successful
ci / test (push) Successful in 3m28s
release / version (push) Successful in 3s
release / x86_64 (push) Successful in 5m41s
release / aarch64 (push) Successful in 7m34s
release / publish (push) Successful in 12s
Reviewed-on: #43
2026-09-12 18:28:44 +00:00
70e70cfe8d Merge branch 'main' into feat/sqlcipher-store
All checks were successful
ci / test (pull_request) Successful in 3m31s
2026-09-12 18:28:09 +00:00
27e49b4ea6 Merge pull request 'ci: watch upstream Arti/tor-* releases daily and file an upgrade issue' (#42) from wt/t_731235d4 into main
Reviewed-on: #42
2026-09-12 18:27:21 +00:00
4338e8aeb6 Merge pull request 'ci(android): publish APK/AAR from the Pi runner' (#38) from wt/t_0bbaca1b into main
Reviewed-on: #38
2026-09-12 18:06:58 +00:00
Sirius DevOps
fc7378596d
feat(core): zeroize in-memory secret material (Noise/Ed25519/X25519/store key)
All checks were successful
ci / test (pull_request) Successful in 3m50s
Wrap every secret this crate holds in zeroize: the local identity and
prekey secrets (Keys), the backup bundle and its derived Argon2id wrap
key, the store data key and the SQLCipher key material, the identity
secret handed out by Store::self_identity, the raw identity-secret
copies in pay/qr signing, and the wallet RPC password plus the
user:realm:password digest input.
2026-09-12 13:55:07 -04:00
Sirius DevOps
2fd640e230
feat(android): wrap the store passphrase in the Android Keystore
Typing the passphrase on every launch was the v1 posture. It stays the
fallback, but it is no longer required: on first unlock the passphrase can be
remembered (checkbox, on by default) and is stored as an AES-256-GCM blob
wrapped by a key that never leaves the Android Keystore.

- crypto/StoreSecret.kt: the OWSEAL1 envelope (magic + IV + ciphertext + GCM
  tag) and the wipe helpers. No android.* imports, so the code that runs on a
  device is the code the unit tests exercise, with a JVM AES key standing in
  for the Keystore key.
- crypto/KeystorePassphraseCipher.kt: AES-256-GCM key under alias
  `onionwire.store`, StrongBox requested first (API 28+) with a graceful
  fallback on ProviderException (StrongBoxUnavailableException is one), and an
  honest KeyInfo-backed report of where the key actually lives.
  setUserAuthenticationRequired(false) stays the default on purpose.
- crypto/StoredPassphraseStore.kt: ciphertext only, at
  filesDir/secrets/store-passphrase.bin, written tmp+rename. A failed decrypt
  reports Unavailable and does NOT delete the blob.
- WireViewModel: unlock(passphrase, remember), unlockStored(),
  forgetStoredPassphrase(); the secret CharArray is zeroed in `finally`; the
  Keystore probe runs off the main thread at ViewModel construction.
- UnlockScreen: one-tap when a stored blob exists, the typed passphrase is
  dropped from Compose state as soon as it is handed over and is never put in
  saved instance state; "Forget stored passphrase" deletes blob and key.
- androidTest: the device-only half (AndroidKeyStore, StrongBox, KeyInfo),
  which cannot run in the unit-test JVM.

Verified: ./gradlew :app:assembleDebug and :app:testDebugUnitTest green,
25 tests / 0 failures (11 new StoreSecretTest, 9 new StoredPassphraseStoreTest).
2026-09-12 13:55:07 -04:00
Sirius DevOps
e7b37ccb40
feat(store): encrypt the whole sqlite store with SQLCipher
All checks were successful
ci / test (pull_request) Successful in 3m35s
The db held the ed25519 identity secret, friend pubkeys, locators, profiles
and payment rows in the clear; only chat bodies were encrypted. Switch
rusqlite to `bundled-sqlcipher-vendored-openssl` and open every store with
`PRAGMA key = "x'<64 hex>'"` as the first statement after open, using the
existing Argon2id output as a raw key (no second KDF pass).

The per-install KDF salt moves out of the db into `store_salt` (0600) — a key
cannot be derived from a salt that lives inside the file it opens. The
per-message ChaCha20-Poly1305 + row-AAD layer is unchanged: whole-db
encryption does not defend against ciphertext swapped between rows, the AAD
does.

v0.2.1 installs are plaintext. The first open with the right passphrase
upgrades in place (WAL checkpoint, ATTACH ... KEY, sqlcipher_export) and only
swaps the file after the new one opens, passes integrity_check and unwraps
store_meta. A wrong passphrase leaves the plaintext file untouched; a
missing `store_salt` next to an encrypted db refuses to open rather than
guessing.

SQLCipher's internal "hmac check failed" ERROR on a rejected key is
suppressed (cipher_log_level = NONE) so a typo'd passphrase is not an error
dump.

docs/THREAT_MODEL.md: the store is now encrypted at rest; sqlcipher leaves
the "Out of v1" list.
2026-09-12 13:55:07 -04:00
Sirius DevOps
6f96d19901
ci: watch upstream Arti/tor-* releases daily and file an upgrade issue
.forgejo/workflows/arti-watch.yml runs daily (06:17 UTC) and via
workflow_dispatch: scripts/arti-watch.py compares each tor-*/arti-* pin in
Cargo.toml against crates.io and files one Forgejo issue per distinct
major.minor bump, deduped on the title so a repeat run is a no-op. It changes
no dependency.

docs/ARTI_UPGRADE.md records the pinned set (arti-client, tor-cell,
tor-hsservice, tor-rtcompat at 0.46), the lockstep rule, the rustc 1.91
floor, and the tests a bump must pass (tests/tor_hs.rs live publish +
probe-connect + byte pipe, the 360s fail-closed wait and the src/hs.rs
circuit-timeout workarounds in tests/hs.rs, the Android rustls build).

Both artefacts state what this does not cover: Tor Project security
announcements, a yanked crate, and a vulnerability with no version bump.
2026-09-12 13:55:07 -04:00
Sirius DevOps
601eb35c4b
ci(android): publish APK/AAR from the Pi runner
Build stays on docker-amd64. Attach artifacts on the Pi so POST /releases
does not 422 from amd64 dind. Join v0.1.0 when that release is missing
the APK instead of minting patch+1.
2026-09-12 13:55:07 -04:00
e6e2a158a8 Merge pull request 'feat(tui): ASCII chrome, invite wrap, remaining copy' (#27) from wt/t_b02176dc into main
All checks were successful
ci / test (push) Successful in 3m16s
release / version (push) Successful in 3s
release / x86_64 (push) Successful in 1m53s
release / aarch64 (push) Successful in 2m24s
release / publish (push) Successful in 11s
Reviewed-on: #27
2026-09-12 17:47:52 +00:00
2b2ad573c0 Merge pull request 'fix(ci): Android APK build in debian:bookworm sibling container' (#30) from wt/t_87d7245b into main
Reviewed-on: #30
2026-09-12 13:43:38 +00:00
f01cb7b937 Merge branch 'main' into wt/t_87d7245b 2026-09-12 13:43:24 +00:00
81ae8556b9 Merge pull request 'ci(release): publish from the Pi; surface API 422s' (#37) from wt/t_2c84cd13 into main
Reviewed-on: #37
2026-09-12 13:23:16 +00:00
Sirius DevOps
30b0294c2b
ci(release): delete dangling tags from the publish job
The sibling cleanup job ran after a successful v0.1.0 publish (run 135)
because act leaves needs.publish.result unset, so != success is true.
It Early-terminated before deleting, but that is not a guard. Fold
fail-closed delete into publish as if: failure() and drop the extra job.
2026-09-12 03:01:14 -04:00
Sirius DevOps
9b7e72b257
ci(release): publish from the Pi; surface API 422s
Run 116 built both arches then POST /releases returned 422 six times
(--retry-all-errors) with no body, while sitting on docker-amd64 behind
android. Move publish to the Pi runner (same path as tag create) and
print the Forgejo error instead of retrying 4xx. README now matches the
core-only path filter and onionwire-ci-pi concurrency.
2026-09-12 02:51:07 -04:00
Sirius DevOps
63abd8eaf2
fix(ci): do not fail the Android verify pipe on SIGPIPE from head
All checks were successful
ci / test (pull_request) Successful in 2m44s
BUILD SUCCESSFUL produced a 33MB arm64 APK; pipefail + aapt|head then
exited 141 and dropped the artifacts before docker cp.
2026-09-12 02:23:34 -04:00
Sirius DevOps
c90c59146d
fix(ci): new android-release concurrency group so dry_run can queue
All checks were successful
ci / test (pull_request) Successful in 2m46s
2026-09-12 02:06:37 -04:00
Sirius DevOps
53ba1e857f
fix(android): point UniFFI --library at CARGO_TARGET_DIR
All checks were successful
ci / test (pull_request) Successful in 2m51s
CI sets CARGO_TARGET_DIR=/cargo-target. Bindgen still looked at
crates/onionwire-sdk/target/release/libonionwire_sdk.so and died ENOENT
after a green host compile.
2026-09-12 02:05:05 -04:00
fecec6c29a Merge pull request 'ci: skip cargo suite when the change cannot affect Rust' (#32) from wt/t_bc2f5c51 into main
Some checks are pending
ci / test (push) Waiting to run
Reviewed-on: #32
2026-09-12 05:44:13 +00:00
Sirius DevOps
1218869629
ci: skip cargo suite when the change cannot affect Rust
Some checks failed
ci / test (pull_request) Has been cancelled
Path allowlist on push-to-main and pull_request: src/, crates/, tests/,
Cargo.toml, Cargo.lock, and this workflow. workflow_dispatch still always
runs. No branch protections, so a skipped run is not a merge trap.
2026-09-12 01:42:01 -04:00
1e8d4057bb Merge pull request 'ci(release): apt retries, always-run publish, Pi concurrency' (#31) from wt/t_2c84cd13 into main
Some checks failed
ci / test (push) Failing after 2m42s
Reviewed-on: #31
2026-09-12 05:39:08 +00:00
Sirius DevOps
1e6a4c12b2
fix(ci): join latest tag when its release lacks the APK
All checks were successful
ci / test (pull_request) Successful in 2m45s
Core owns tag creation. If vN exists and the release is missing the
Android APK, attach there instead of minting N+1. Never delete tags.
Path filter is sources/Gradle only — README edits do not publish.
2026-09-12 01:37:40 -04:00
Sirius DevOps
ae9cd5728e
ci(release): do not mint a release for workflow-only edits
All checks were successful
ci / test (pull_request) Successful in 4m46s
Drop release.yml and build-release-local.sh from on.push.paths so a CI
tweak cannot cut a user-facing tag. Validate those files with dry_run
dispatch instead. release-body.md stays because it is the published body.
2026-09-12 01:35:13 -04:00
Sirius DevOps
eaea3d49f7
ci(release): apt retries on IPv4; never skip the publish job
All checks were successful
ci / test (pull_request) Successful in 3m39s
Concurrent dind rust containers looped on apt InRelease; abort and retry
with ForceIPv4. Publish always runs after version so cleanup is not
blocked by Forgejo act "'runs-on' key not defined" on a skipped job.
Do not bake a custom rust image on this card.
2026-09-12 01:30:16 -04:00
Sirius DevOps
87ab0d2869
fix(ci): use debian:bookworm for the Android sibling container
All checks were successful
ci / test (pull_request) Successful in 3m0s
eclipse-temurin:17-jdk-bookworm is not a published tag (manifest unknown).
debian:bookworm is current and has openjdk-17.
2026-09-12 01:16:28 -04:00
Sirius DevOps
c087b223e9
fix(ci): build Android APK in a bookworm sibling container
All checks were successful
ci / test (pull_request) Successful in 4m57s
node:20-bullseye (the amd64 job image) is EOL; apt-get there fails on
expired/404 security indexes. Run JDK 17 + SDK/NDK + cargo-ndk inside
eclipse-temurin:17-jdk-bookworm via docker create + stdin tar, matching
the Rust CI pattern. Fetch a static docker CLI if the job image lacks
one. On publish failure after creating a tag, delete that tag so the
next run retries the same version (first release stays v0.1.0).
2026-09-12 01:14:43 -04:00
3e72f40e0e Merge pull request 'fix(ci): Android APK build in bookworm sibling container' (#29) from wt/t_87d7245b into main
All checks were successful
ci / test (push) Successful in 3m40s
Reviewed-on: #29
2026-09-12 05:13:46 +00:00
3e28fa311c Merge pull request 'ci(release): install static docker CLI on amd64 jobs' (#28) from wt/t_2c84cd13 into main
Some checks failed
release / x86_64 (push) Failing after 19m52s
ci / test (push) Waiting to run
release / version (push) Successful in 3s
release / aarch64 (push) Successful in 3m30s
release / publish (push) Has been cancelled
release / cleanup (push) Has been cancelled
Reviewed-on: #28
2026-09-12 05:10:07 +00:00
Sirius DevOps
898b943485
ci(release): share ci.yml concurrency; make cleanup actually delete
Some checks failed
ci / test (pull_request) Failing after 2m51s
Use onionwire-ci-pi so cargo release builds cannot race tests on the
Pi's shared /target volume. Strip PAT newlines in cleanup and treat
publish skipped/failed as the signal to delete the tag this run created,
so the next run retries the same version instead of advancing.
2026-09-12 01:09:46 -04:00
Sirius DevOps
951439d7e2
ci(release): install static docker CLI on amd64 jobs
All checks were successful
ci / test (pull_request) Successful in 3m48s
The docker-amd64 runner's node:20-bullseye job image has no docker
binary (Pi jobs get one via the host socket mount). Fetch the upstream
static CLI so the rust:1.91-bookworm sibling build can run.
2026-09-12 01:03:22 -04:00
4a248f5b73 Merge pull request 'feat(android): auto-publish signed APK and AAR from CI' (#26) from wt/t_87d7245b into main
All checks were successful
ci / test (push) Successful in 3m8s
Reviewed-on: #26
2026-09-12 04:59:41 +00:00
Sirius DevOps
c8693d2006
fix(ci): android-release HTTPS apt mirrors and dry_run input
All checks were successful
ci / test (pull_request) Successful in 7m9s
dind timed out on http://deb.debian.org:80. Flip sources to HTTPS.
Do not let workflow_call's boolean false clobber dispatch dry_run.
2026-09-12 01:00:42 -04:00
Sirius DevOps
1c4aaefb01
feat(android): auto-publish signed APK and AAR from CI
Some checks failed
ci / test (pull_request) Failing after 3m13s
Push to main that touches android/** builds a release APK + SDK AAR on
docker-amd64, verifies size/ABI/signature, and create-or-joins the Forgejo
release. Version is latest v*.*.* patch+1, or v0.1.0 when there are no tags.
Release signing uses repo secrets (ANDROID_KEYSTORE_*), not the debug key.
2026-09-12 00:54:17 -04:00
Sirius DevOps
35b8caa716
feat(tui): ASCII chrome, invite wrap, alert truncate, remaining copy
Some checks failed
ci / test (pull_request) Failing after 4m39s
ONIONWIRE_ASCII (and NO_COLOR) switches truncation to ... and ASCII
borders. Share/paste wrap at : so a mouse-copy cannot lose a mid-hex
line. Alerts truncate to the frame; empty threads and paste errors keep
the next-step hint. Skip the optional 40-row wordmark.
2026-09-12 00:54:16 -04:00
2b704ba464 Merge pull request 'ci(release): auto-tag and publish aarch64+x86_64 on main' (#25) from wt/t_2c84cd13 into main
Some checks failed
ci / test (push) Has been cancelled
release / version (push) Successful in 5s
release / x86_64 (push) Failing after 6s
release / aarch64 (push) Successful in 2m30s
release / publish (push) Failing after 0s
release / cleanup (push) Successful in 15s
Reviewed-on: #25
2026-09-12 04:54:09 +00:00
Sirius DevOps
58e10a0bc0
ci(release): honor dry_run input and send JSON Content-Type
Some checks failed
ci / test (pull_request) Failing after 4m1s
Forgejo dispatch passes string inputs; boolean dry_run stayed false and
tried to mint v0.1.0. Strip PAT newlines so Authorization does not eat
the next header (422 Empty Content-Type).
2026-09-12 00:55:18 -04:00
Sirius DevOps
111b95c3ae
ci(release): auto-tag and publish aarch64+x86_64 on main
Some checks failed
ci / test (pull_request) Failing after 2m16s
Drop the tag-push trigger so API-created tags cannot start a second run.
Core paths on main (or workflow_dispatch) mint the next v*.*.* tag
(v0.1.0 when none exist), build both arches in CI, and publish one
release. dry_run builds without tagging. Fail closed on empty assets.
2026-09-12 00:52:46 -04:00
33beeded92 Merge pull request 'feat(tui): fail-closed footer, 1-line header, help overlay' (#24) from wt/t_0d3b0f80 into main
All checks were successful
ci / test (push) Successful in 2m48s
Reviewed-on: #24
2026-09-12 04:25:07 +00:00
Sirius DevOps
7d3e1bd627
test(tui): keep send-failed visible in crowded status_footer
All checks were successful
ci / test (pull_request) Successful in 3m5s
PR #23 locked the old drop. Flip status_footer_drops_send_failed_when_crowded
to assert the note stays at 80/120/200 with TOR, me:, and ? help.
2026-09-12 00:22:04 -04:00
Sirius DevOps
494a0e4099
Merge remote-tracking branch 'origin/main' into wt/t_0d3b0f80 2026-09-12 00:20:26 -04:00
53f9914be5 Merge pull request 'docs(tui): visual audit, before frames, and design spec' (#23) from wt/t_3c2d56df into main
All checks were successful
ci / test (push) Successful in 3m39s
Reviewed-on: #23
2026-09-12 04:15:38 +00:00
Sirius DevOps
0749d2300a
feat(tui): keep fail-closed footer, flatten main chrome
All checks were successful
ci / test (pull_request) Successful in 4m48s
status_footer never drops send failed / status_note; TOR, me:, and ? help
still fit at 80 and 120. Main at 24 rows uses a one-line header, a 22-cell
roster, chat as the primary pane, and an unboxed composer with a message
placeholder. Help at height < 28 is full-screen so Esc closes this overlay
is visible. Palette maps RGB to 16-color and NO_COLOR (glyphs/weight only).

Do not include docs/TUI.md or tests/tui_frames.rs (PR #23).
2026-09-12 00:15:19 -04:00
175f5dd943 Merge pull request 'fix(file): pace chunks to fit rendezvous rate limit' (#22) from wt/t_fc02d8b6 into main
All checks were successful
ci / test (push) Successful in 2m54s
Reviewed-on: #22
2026-09-12 04:11:10 +00:00
dcb98132e2 Merge branch 'main' into wt/t_fc02d8b6
All checks were successful
ci / test (pull_request) Successful in 3m2s
2026-09-12 04:11:00 +00:00
4457c7330c Merge pull request 'sanitize peer chat/control/bidi before store and TUI render' (#21) from wt/t_6ddd495e into main
All checks were successful
ci / test (push) Successful in 3m42s
Reviewed-on: #21
2026-09-12 03:59:46 +00:00
0a888eced5 Merge branch 'main' into wt/t_6ddd495e
Some checks failed
ci / test (pull_request) Failing after 2m29s
2026-09-12 03:58:53 +00:00
f9395ee070 Merge pull request 'fix(protocol): domain-separate loc/prf/inv/rcp signatures' (#20) from wt/t_ce5649ac into main
All checks were successful
ci / test (push) Successful in 2m27s
Reviewed-on: #20
2026-09-12 03:53:43 +00:00
Sirius DevOps
4205ed149d
docs(tui): visual audit, before frames, and design spec
All checks were successful
ci / test (pull_request) Successful in 2m45s
Dump current chrome through TestBackend at 80x24 / 120x40 / 200x60.
No src changes. Spec in docs/TUI.md for the implementation card.
2026-09-11 23:52:05 -04:00
Sirius DevOps
4bbc2de9ab
[verified] fix(file): pace chunks to fit rendezvous rate limit
All checks were successful
ci / test (pull_request) Successful in 2m42s
Sender-side only. First chunk attempt is immediate; later attempts
(retries and later chunks) wait 3s. Three attempts per chunk, then
fail closed. Token bucket 30/60s burst 10 is unchanged.

A 1 MiB file is 17 one-shot sessions; pacing floor is 16*3s = 48s
plus handshake time. Latency trade, not a security fix.
2026-09-11 23:49:29 -04:00
Sirius DevOps
818cf5922f
ci: retrigger Pi runner after shared target lock
All checks were successful
ci / test (pull_request) Successful in 2m43s
Previous PR run waited on the cargo build-dir lock then compiled
tests against a stale rlib missing sanitize.
2026-09-11 23:46:54 -04:00
Sirius DevOps
e3738c51f7
[verified] sanitize peer chat/control/bidi before store and TUI render
Some checks failed
ci / test (pull_request) Failing after 2m2s
Strip C0 (except tab/newline), DEL, C1, and bidi/format marks at ingest
and render; keep ZWJ; lossy UTF-8 stays U+FFFD. Reject the same set in
fil names. Docs match the policy.
2026-09-11 23:42:48 -04:00
Sirius DevOps
c8e69732c7
fix(protocol): domain-separate loc/prf/inv/rcp signatures
All checks were successful
ci / test (pull_request) Successful in 2m30s
Sign application frames as tag || 0x00 || fields (onionwire-loc-v1,
onionwire-prf-v1, onionwire-inv-v1, onionwire-rcp-v1). Verify accepts
that form first, then the legacy untagged LF-joined layout. Encode still
emits only the tagged signature; wire prefixes and field layout are
unchanged.

Older builds verify untagged bytes only, so they reject new tagged
signatures (fail closed). Mixed-version fleets break outbound app frames
from a new sender to an old receiver until both sides are updated.
2026-09-11 23:42:41 -04:00
cb91ba2b78 Merge pull request 'fix(tui): do not freeze the UI on chat send' (#19) from feat/tui-nonblocking-send into main
All checks were successful
ci / test (push) Successful in 2m36s
Reviewed-on: #19
2026-09-12 03:10:53 +00:00
Sirius DevOps
7d8363a761
fix(tui): do not freeze the UI on chat send
Some checks failed
ci / test (pull_request) Failing after 1s
Enter used block_on(Node::send), which retries for 180s on the TUI
thread so event::read never ran. Spawn send on the runtime, poll keys
at 100ms, show sending/sent/send failed on the footer.
2026-09-11 22:33:55 -04:00
8c79250acf Merge pull request 'fix(android): Approve and add no-op from shared Compose busy flag' (#18) from wt/t_af421dc6 into main
All checks were successful
ci / test (push) Successful in 2m30s
Reviewed-on: #18
2026-09-12 02:05:46 +00:00
d213dd21df Merge pull request 'docs: protocol spec and audit-notes cleanup' (#17) from docs/protocol into main
Some checks are pending
ci / test (push) Waiting to run
Reviewed-on: #17
2026-09-12 02:05:23 +00:00
Sirius DevOps
22b3a0062a
docs: add PROTOCOL.md and retire the stale audit writeup
All checks were successful
ci / test (pull_request) Successful in 3m7s
Wire format lives in docs/PROTOCOL.md so the handshake, invite, and
frames can be read without the Rust. Threat model points at it. The
in-house audit notes are a finding-status table, not a third-party
audit. SDK README no longer claims the legacy concat invite signature
is what we encode.
2026-09-11 13:15:51 -04:00
205 changed files with 66485 additions and 2603 deletions

View file

@ -0,0 +1,339 @@
name: android-ci
# Android changes had no CI at all: ci.yml's path allowlist (src/**, crates/**,
# tests/**, Cargo.toml, Cargo.lock, ci.yml) never matches android/**, and
# android-release.yml is dispatch/tag-driven — so an android-only PR ran zero
# jobs and merged on an empty check list. This is the android side of CI.
#
# It builds the same gradle targets the release builds through the same script
# android-release.yml calls (scripts/build-android-local.sh): `:sdk:assembleRelease`
# + `:app:assembleRelease`, Rust for aarch64-linux-android via cargo-ndk, UniFFI
# bindings, APK packaging with the .so. The only difference from a release is
# signing: ONIONWIRE_REQUIRE_RELEASE_KEY=false and no release keystore, so
# Gradle falls back to the debug key. Nothing here is signed for release,
# nothing is published, no tag is touched.
#
# Why a separate workflow instead of android/** added to ci.yml: the only way
# to keep the Rust jobs from running on android-only diffs is job-level change
# detection, and a gate that mis-detects hands out a green check for a suite
# that never ran. Here the runner's own paths filter decides — same mechanism
# ci.yml already uses.
#
# The two triggers differ on purpose, and the asymmetry is the whole point of
# the `src/**` entry below:
#
# pull_request — the client and the SDK binding surface. NOT `src/**`. A
# Rust-only PR does change the bytes in `libonionwire_sdk.so`, but proving
# that costs a ~11 minute full APK build, and 95 of 143 recorded runs
# touched no `android/` file at all. The in-APK checks that actually earn
# their keep (the `target_max_memory` marker gate, the `.so` listing, the
# sha256 round-trip) still run on every merge via the push trigger, so
# nothing reaches a release untested — a Rust PR just finds out at merge
# instead of before it. If a Rust change ever breaks the Android build
# specifically, add its path here rather than re-adding all of `src/**`.
#
# push: [main] — every Rust or Android change, every merge. This is the
# safety net, and it is why the trigger cannot simply mirror the PR one.
on:
push:
branches: [main]
paths:
- "android/**"
- "crates/**"
- "src/**"
- "Cargo.toml"
- "Cargo.lock"
- "scripts/build-android-local.sh"
- ".forgejo/workflows/android-ci.yml"
pull_request:
paths:
- "android/**"
- "crates/onionwire-sdk/**"
- "Cargo.toml"
- "Cargo.lock"
- "scripts/build-android-local.sh"
- ".forgejo/workflows/android-ci.yml"
workflow_dispatch:
# Deliberately the SAME group and the SAME volumes as android-release.yml: the
# APK build is ~9 min with warm volumes (SDK/NDK, cargo registry, cargo target,
# Gradle cache) and a cold copy of those is over a gigabyte of downloads per
# runner. Serializing the two workflows by group name is what keeps them off
# each other's volumes.
concurrency:
group: onionwire-android-release-v2
cancel-in-progress: false
env:
CARGO_TERM_COLOR: never
CARGO_BUILD_JOBS: "1"
ONIONWIRE_ANDROID_ABI: arm64-v8a
ANDROID_IMAGE: debian:bookworm
ANDROID_CMDLINE_TOOLS_URL: https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
# Same floor as ci.yml and release.yml (`rust:1.98-bookworm`). The cuprated
# graph needs >= 1.93 (`tapes` calls `VecDeque::pop_front_if`); 1.91 dies with
# `error[E0658]: use of unstable library feature 'vec_deque_pop_if'`. 1.98 is
# the stable release this graph is built and tested with.
RUST_TOOLCHAIN: "1.98"
DOCKER_STATIC_URL: https://download.docker.com/linux/static/stable/x86_64/docker-27.5.1.tgz
# Distinct container prefix: run ids are per-workflow, so this workflow and
# android-release.yml can both be holding a container named "<prefix>-<n>".
BUILD_CONTAINER: onionwire-android-ci-${{ github.run_id }}
SDK_VOLUME: onionwire-android-sdk
CARGO_VOLUME: onionwire-android-cargo-registry
TARGET_VOLUME: onionwire-android-target
GRADLE_VOLUME: onionwire-android-gradle
jobs:
android:
runs-on: docker-amd64
timeout-minutes: 120
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
- name: Skip superseded run
id: staleness
run: |
set -uo pipefail
# Same gate as ci.yml: a newer commit on this branch while this run
# sat in the shared android concurrency queue makes the ~11 minute
# APK build a proof of nothing. `origin` is anonymously readable
# here, and a failed lookup runs the job rather than skipping it.
ref="${GITHUB_HEAD_REF:-${GITHUB_REF_NAME:-}}"
remote=""
if [ -n "$ref" ]; then
remote="$(git ls-remote origin "refs/heads/$ref" 2>/dev/null | cut -f1)"
fi
if [ -n "$remote" ] && [ "$remote" != "$GITHUB_SHA" ]; then
echo "::notice::superseded: refs/heads/$ref is at ${remote:0:12}, this run is ${GITHUB_SHA:0:12} — skipping"
echo "skip=true" >> "$GITHUB_OUTPUT"
else
echo "tip=${remote:-unknown} sha=${GITHUB_SHA} ref=${ref:-none} — running"
echo "skip=false" >> "$GITHUB_OUTPUT"
fi
- name: Record runner resources
if: steps.staleness.outputs.skip != 'true'
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
echo "workspace=$GITHUB_WORKSPACE hostname=$(hostname) arch=$(uname -m)"
nproc || true
free -h || true
df -h || true
ls -l /var/run/docker.sock || true
- name: Ensure docker CLI
if: steps.staleness.outputs.skip != 'true'
run: |
set -euo pipefail
if ! command -v docker >/dev/null 2>&1; then
echo "docker CLI missing in job image; fetching static client"
curl -fsSL "$DOCKER_STATIC_URL" -o /tmp/docker.tgz
tar -xzf /tmp/docker.tgz -C /tmp
install -m 755 /tmp/docker/docker /usr/local/bin/docker
fi
export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}"
docker version
docker info >/tmp/docker-info.txt
grep -E 'Server Version|Operating System|Total Memory|Name' /tmp/docker-info.txt || true
- name: Build APK + AAR (debug-signed) in bookworm container
id: build
if: steps.staleness.outputs.skip != 'true'
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}"
start=$(date +%s)
cat > .ci-android-verify.sh <<'INNER'
#!/usr/bin/env bash
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive
apt-get update
# `cmake` is for RandomX, the C++ half of the in-process chain daemon:
# without it `randomx-rs`'s build script panics with "failed to execute
# command: No such file or directory … is `cmake` not installed?" and the
# Gradle task dies on "cargo finished with non-zero exit value 101".
apt-get install -y --no-install-recommends \
openjdk-17-jdk-headless python3 unzip curl ca-certificates file build-essential pkg-config git \
cmake
if [ ! -x /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager ]; then
mkdir -p /opt/android-sdk/cmdline-tools
curl -fsSL "$ANDROID_CMDLINE_TOOLS_URL" -o /tmp/cmdline-tools.zip
rm -rf /tmp/cmdline-tools
unzip -q /tmp/cmdline-tools.zip -d /tmp/cmdline-tools
mkdir -p /opt/android-sdk/cmdline-tools/latest
cp -a /tmp/cmdline-tools/cmdline-tools/. /opt/android-sdk/cmdline-tools/latest/
fi
yes | /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root=/opt/android-sdk --licenses >/tmp/sdk-licenses.log || true
/opt/android-sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root=/opt/android-sdk \
"platform-tools" "platforms;android-36" "build-tools;36.0.0" "ndk;28.2.13676358"
test -d /opt/android-sdk/ndk/28.2.13676358
export ANDROID_HOME=/opt/android-sdk ANDROID_SDK_ROOT=/opt/android-sdk
export ANDROID_NDK_HOME=/opt/android-sdk/ndk/28.2.13676358
export PATH="$ANDROID_HOME/build-tools/36.0.0:$ANDROID_HOME/platform-tools:$PATH"
if [ ! -x /cargo/bin/rustup ]; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain "$RUST_TOOLCHAIN" --no-modify-path --profile minimal
fi
export PATH="/cargo/bin:$PATH"
rustup toolchain install "$RUST_TOOLCHAIN"
rustup default "$RUST_TOOLCHAIN"
rustup target add aarch64-linux-android
command -v cargo-ndk >/dev/null || cargo install cargo-ndk --locked
echo "=== toolchain ==="
java -version
rustc --version
cargo ndk --version
du -sh /opt/android-sdk /cargo /cargo-target /gradle || true
# Shared /gradle volume: a killed container leaves journal-1.lock.
# android/gradle.properties also sets org.gradle.parallel=true, which
# is how two JVMs (PIDs ~5 apart) show up on one lock. Drop the
# stale locks and force one Gradle process for this container.
find /gradle -name '*.lock' -type f -delete 2>/dev/null || true
export GRADLE_OPTS="${GRADLE_OPTS:-} -Dorg.gradle.parallel=false -Dorg.gradle.daemon=false"
# No keystore here on purpose: this is a verification build, not a
# release build. The script warns that Gradle fell back to the debug
# key; that warning is expected in this job.
scripts/build-android-local.sh
version="$(python3 - <<'PY'
import re, pathlib
t = pathlib.Path('android/app/build.gradle.kts').read_text()
m = re.search(r'versionName\s*=.*?:\s*"([^"]+)"', t)
print(m.group(1) if m else '')
PY
)"
abi="${ONIONWIRE_ANDROID_ABI:-arm64-v8a}"
apk="dist/onionwire-$version-android-$abi.apk"
aar="dist/onionwire-sdk-$version.aar"
{
echo "=== file ==="
file "$apk" "$aar"
echo "=== unzip lib ==="
unzip -l "$apk" | grep -E 'lib/.+\.so' || true
unzip -l "$apk" | grep "lib/$abi/libonionwire_sdk.so"
# `unzip -l` shows the uncompressed size only; the *deflated* entry is
# what the download actually costs, and it is not visible anywhere else
# (v0.7.0's SDK lib was 33,481,336 B raw / 12,210,154 B deflated, which
# is the ratio a reader wants when this one grows).
echo "=== native lib entries (length / method / deflated) ==="
unzip -v "$apk" | grep -E 'lib/.+\.so$'
echo "=== in-process chain daemon (cuprate-daemon) is IN this APK ==="
# The build log's "features=cuprate-daemon" line says the feature was
# *requested*; this says it is *in the artifact*. `target_max_memory` is
# a rodata literal from src/cuprate.rs's config TOML, compiled only under
# `#[cfg(feature = "cuprate-daemon")]` — v0.7.0's libonionwire_sdk.so
# contains zero occurrences of it (checked), so its presence is the
# difference between a build that carries the daemon and one that only
# claims to. A missing marker fails the job: an APK whose on-device node
# can only fail is the regression this gate exists to catch.
unzip -p "$apk" "lib/$abi/libonionwire_sdk.so" > /tmp/libonionwire_sdk.so
# `grep -c`, deliberately not `grep -q`: under `set -o pipefail` a `-q`
# match closes the pipe early, `strings` dies on SIGPIPE (141), and the
# pipeline then reports failure even though the marker was there — this
# gate failed its own green build once that way.
marker="$(strings -a /tmp/libonionwire_sdk.so | grep -c 'target_max_memory' || true)"
echo "target_max_memory occurrences: ${marker:-0}"
if [ "${marker:-0}" -lt 1 ]; then
echo "lib/$abi/libonionwire_sdk.so carries no cuprated config string: the cuprate-daemon feature is NOT in this APK" >&2
exit 1
fi
echo "=== classes.dex + Compose entrypoints ==="
unzip -l "$apk" | grep -E 'classes[0-9]*\.dex' | head -n3
echo "=== sha256 ==="
# `sha256sum -c` proves each artifact matches the digest the build
# recorded, but prints neither number. The digest *is* the artifact's
# identity, and an APK is not byte-reproducible across machines, so it
# cannot be derived from the tree afterwards — echo both.
cat "dist/onionwire-$version-android-$abi.apk.sha256" "dist/onionwire-sdk-$version.aar.sha256"
( cd dist && sha256sum -c "onionwire-$version-android-$abi.apk.sha256" "onionwire-sdk-$version.aar.sha256" )
echo "=== apksigner (expect debug cert: this is a verification build) ==="
apksigner verify --print-certs "$apk" | sed -n '1,6p'
echo "=== aapt ==="
aapt dump badging "$apk" | sed -n '1,20p' || true
echo "=== sizes ==="
wc -c "$apk" "$aar"
# The cross-compile volume this build just grew. The cuprated graph is
# ~152 crates plus a C++ RandomX build, so the number is the disk cost
# of the feature on the runner, next to the wall clock above.
echo "=== cargo target volume (after this build) ==="
du -sh /cargo-target 2>/dev/null || true
du -sh /cargo-target/aarch64-linux-android/release 2>/dev/null || true
} | tee dist/android-ci-verify.log
INNER
chmod +x .ci-android-verify.sh
docker volume create "$SDK_VOLUME" >/dev/null
docker volume create "$CARGO_VOLUME" >/dev/null
docker volume create "$TARGET_VOLUME" >/dev/null
docker volume create "$GRADLE_VOLUME" >/dev/null
# Cancelled jobs never reach the trailing `docker rm`, so a previous
# onionwire-android-* container can still hold GRADLE_VOLUME. The next
# Gradle then dies LockTimeoutException on /gradle/caches/journal-1
# (owner PID vs our PID a few numbers apart — two JVMs, one volume).
trap 'docker rm -f "$BUILD_CONTAINER" >/dev/null 2>&1 || true' EXIT
docker ps -aq --filter name=onionwire-android- | xargs -r docker rm -f || true
docker rm -f "$BUILD_CONTAINER" >/dev/null 2>&1 || true
docker pull "$ANDROID_IMAGE"
# 2 GB of Gradle heap, not 1: the only budget in this build that is close
# is the single-use daemon's heap, which now has to package a 55 MB SDK
# lib (plus RandomX's 1.1 MB) through AGP's in-daemon packaging. Run 414
# died in `:app:packageRelease` with the cause hidden inside
# `PackageAndroidArtifact$IncrementalSplitterRunnable` — no "Caused by"
# line, nothing in the log — so give it room instead of guessing again.
# The runner has 15 GB and the job's peak RSS is ~3 GB.
docker create --name "$BUILD_CONTAINER" -i \
-e CARGO_TERM_COLOR=never \
-e CARGO_BUILD_JOBS="$CARGO_BUILD_JOBS" \
-e CARGO_HOME=/cargo \
-e CARGO_TARGET_DIR=/cargo-target \
-e GRADLE_USER_HOME=/gradle \
-e ANDROID_HOME=/opt/android-sdk \
-e ANDROID_SDK_ROOT=/opt/android-sdk \
-e ANDROID_NDK_HOME=/opt/android-sdk/ndk/28.2.13676358 \
-e ONIONWIRE_ANDROID_ABI="$ONIONWIRE_ANDROID_ABI" \
-e ONIONWIRE_REQUIRE_RELEASE_KEY=false \
-e RUST_TOOLCHAIN="$RUST_TOOLCHAIN" \
-e ANDROID_CMDLINE_TOOLS_URL="$ANDROID_CMDLINE_TOOLS_URL" \
-e GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=false -Dorg.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8" \
-v "$SDK_VOLUME":/opt/android-sdk \
-v "$CARGO_VOLUME":/cargo \
-v "$TARGET_VOLUME":/cargo-target \
-v "$GRADLE_VOLUME":/gradle \
-w /src \
"$ANDROID_IMAGE" \
bash -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src && bash /src/.ci-android-verify.sh'
tar czf - \
--exclude=./target --exclude=./.git --exclude=./.worktrees \
--exclude=./android/.gradle --exclude=./android/app/build \
--exclude=./android/sdk/build --exclude=./dist \
--exclude=./crates/onionwire-sdk/target \
. \
| docker start -a -i "$BUILD_CONTAINER"
mkdir -p dist
docker cp "$BUILD_CONTAINER:/src/dist/." dist/
end=$(date +%s)
echo "build_wall_clock_seconds=$((end - start))"
echo "wall_clock_seconds=$((end - start))" >> "$GITHUB_OUTPUT"
docker rm -f "$BUILD_CONTAINER" >/dev/null || true
ls -l dist/
- name: Verify artifacts
if: steps.staleness.outputs.skip != 'true'
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
abi="$ONIONWIRE_ANDROID_ABI"
ls -l dist/
apk="$(ls dist/onionwire-*-android-$abi.apk)"
aar="$(ls dist/onionwire-sdk-*.aar)"
[ -s "$apk" ] || { echo "missing or empty $apk" >&2; exit 1; }
[ -s "$aar" ] || { echo "missing or empty $aar" >&2; exit 1; }
echo "apk=$apk bytes=$(wc -c < "$apk")"
echo "aar=$aar bytes=$(wc -c < "$aar")"
( cd dist && sha256sum -c ./*.sha256 )
echo "=== android-ci-verify.log (from build container) ==="
cat dist/android-ci-verify.log
echo "=== resources after build ==="
free -h || true
df -h || true

View file

@ -0,0 +1,483 @@
name: android-release
# Build the Android APK + SDK AAR on docker-amd64 and attach them to the
# Forgejo release for the computed (or requested) tag.
#
# The runner job image is node:20-bullseye (EOL). Do not apt-get there.
# toolchain runs in a sibling debian:bookworm container,
# the same stdin-tar + docker cp pattern as .forgejo/workflows/ci.yml.
#
# Publish is a separate job on the Pi runner (`docker`). POST /releases from
# the amd64 dind egress returns 422 with an empty body (core run 116);
# core's publish job on the Pi (run 135) is the proven path.
#
# First automated version with zero tags: v0.1.0. Afterwards, patch+1 from the
# latest v*.*.* tag UNLESS that tag's release is missing the Android assets —
# then join it (core owns tag creation). Never move or delete a tag.
#
# No automatic trigger, on purpose. Two candidate decoupled triggers were
# tried and both dead-end on Forgejo 10.0.3 (see docs/RELEASING.md):
# - `push: tags: ['v*.*.*']` — a tag created by release.yml (API or git push)
# does not fire it: pushes made with the CI's token are Actions-user events
# and Forgejo deliberately does not dispatch those back into Actions.
# Verified: the v0.2.0 and v0.2.1 tags produced no run, while hand-pushed
# tags did historically.
# - `workflow_call` from release.yml — reusable workflows only exist from
# Forgejo 12; this instance is 10.0.3.
# So a release is two dispatches: release.yml, then this one with `tag=<the
# tag the core just created>`. The core's run leaves the tag; this attaches
# the APK + AAR to it.
on:
workflow_dispatch:
inputs:
tag:
description: Existing tag to (re)build and attach (empty = next version)
required: false
type: string
dry_run:
description: Build and checksum without creating a tag or publishing (true/false)
required: false
type: string
default: "false"
workflow_call:
inputs:
tag:
required: false
type: string
dry_run:
required: false
type: string
default: "false"
concurrency:
group: onionwire-android-release-v2
cancel-in-progress: false
env:
CARGO_TERM_COLOR: never
CARGO_BUILD_JOBS: "1"
ONIONWIRE_ANDROID_ABI: arm64-v8a
ONIONWIRE_REQUIRE_RELEASE_KEY: "true"
ANDROID_IMAGE: debian:bookworm
ANDROID_CMDLINE_TOOLS_URL: https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
# Same floor as ci.yml (`rust:1.98-bookworm`): the cuprated graph needs >= 1.93
# (`tapes` uses `VecDeque::pop_front_if`), and 1.98 is what this graph is built with.
RUST_TOOLCHAIN: "1.98"
DOCKER_STATIC_URL: https://download.docker.com/linux/static/stable/x86_64/docker-27.5.1.tgz
BUILD_CONTAINER: onionwire-android-${{ github.run_id }}
SDK_VOLUME: onionwire-android-sdk
CARGO_VOLUME: onionwire-android-cargo-registry
TARGET_VOLUME: onionwire-android-target
GRADLE_VOLUME: onionwire-android-gradle
jobs:
android:
runs-on: docker-amd64
timeout-minutes: 90
outputs:
version: ${{ steps.version.outputs.version }}
tag: ${{ steps.version.outputs.tag }}
version_code: ${{ steps.version.outputs.version_code }}
dry_run: ${{ steps.version.outputs.dry_run }}
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ github.event.inputs.tag || inputs.tag || github.sha }}
- name: Record runner resources
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
echo "workspace=$GITHUB_WORKSPACE hostname=$(hostname) arch=$(uname -m)"
nproc || true
free -h || true
df -h || true
ls -l /var/run/docker.sock || true
- name: Compute version
id: version
env:
INPUT_TAG: ${{ github.event.inputs.tag || inputs.tag }}
INPUT_DRY_RUN: ${{ github.event.inputs.dry_run }}
CALL_DRY_RUN: ${{ inputs.dry_run }}
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
echo "INPUT_DRY_RUN='${INPUT_DRY_RUN:-}' CALL_DRY_RUN='${CALL_DRY_RUN:-}' EVENT=${GITHUB_EVENT_NAME:-}"
git fetch --tags --force origin || true
input_tag="${INPUT_TAG:-}"
dry_run=false
case "${INPUT_DRY_RUN:-}" in true|TRUE|True|1|yes|YES) dry_run=true ;; esac
case "${CALL_DRY_RUN:-}" in true|TRUE|True|1|yes|YES) dry_run=true ;; esac
if [ -n "$input_tag" ]; then
ver="${input_tag#v}"
else
latest="$(git tag -l 'v*.*.*' --sort=-v:refname | head -n1 || true)"
if [ -z "$latest" ]; then
ver="0.1.0"
else
# Core owns tag creation. If the latest tag's release is missing
# the Android APK, join that version instead of minting patch+1.
join=0
if [ -n "${FORGEJO_TOKEN:-}" ]; then
http=$(curl -sS --http1.1 -o /tmp/latest-rel.json -w '%{http_code}' \
-u "sirius:${FORGEJO_TOKEN}" \
"$REPO_API/releases/tags/$latest" || true)
if [ "$http" != "200" ]; then
join=1
echo "latest tag $latest has no release (http $http); joining"
elif node -e 'const d=require("/tmp/latest-rel.json"); const n=(d.assets||[]).some(a=>/onionwire-.*-android-.*\\.apk$/.test(a.name)); process.exit(n?0:1)'; then
echo "latest tag $latest already has an Android APK; patch+1"
else
join=1
echo "latest tag $latest release is missing Android APK; joining"
fi
else
echo "FORGEJO_TOKEN unset; cannot inspect release assets, joining $latest"
join=1
fi
if [ "$join" = "1" ]; then
ver="${latest#v}"
else
ver="${latest#v}"
major="${ver%%.*}"
rest="${ver#*.}"
minor="${rest%%.*}"
patch="${rest#*.}"
patch=$((patch + 1))
ver="${major}.${minor}.${patch}"
fi
fi
fi
echo "$ver" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' || {
echo "not a MAJOR.MINOR.PATCH version: $ver" >&2
exit 1
}
major="${ver%%.*}"
rest="${ver#*.}"
minor="${rest%%.*}"
patch="${rest#*.}"
code=$((major * 10000 + minor * 100 + patch))
tag="v$ver"
{
echo "version=$ver"
echo "tag=$tag"
echo "version_code=$code"
echo "dry_run=$dry_run"
} >> "$GITHUB_OUTPUT"
echo "version=$ver tag=$tag versionCode=$code dry_run=$dry_run"
- name: Decode release keystore
env:
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
: "${ANDROID_KEYSTORE_BASE64:?ANDROID_KEYSTORE_BASE64 secret is missing}"
: "${ANDROID_KEYSTORE_PASSWORD:?ANDROID_KEYSTORE_PASSWORD secret is missing}"
: "${ANDROID_KEY_ALIAS:?ANDROID_KEY_ALIAS secret is missing}"
: "${ANDROID_KEY_PASSWORD:?ANDROID_KEY_PASSWORD secret is missing}"
mkdir -p "$HOME/.android"
chmod 700 "$HOME/.android"
ks="$HOME/.android/onionwire-release.jks"
envf="$HOME/.android/onionwire-release.env"
printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 -d > "$ks"
chmod 600 "$ks"
test -s "$ks"
umask 077
printf 'ANDROID_KEYSTORE_FILE=%s\nANDROID_KEYSTORE_PASSWORD=%s\nANDROID_KEY_ALIAS=%s\nANDROID_KEY_PASSWORD=%s\n' \
"/root/.android/onionwire-release.jks" "$ANDROID_KEYSTORE_PASSWORD" "$ANDROID_KEY_ALIAS" "$ANDROID_KEY_PASSWORD" > "$envf"
chmod 600 "$envf"
echo "keystore bytes=$(wc -c < "$ks") staged for the build container"
- name: Ensure docker CLI
run: |
set -euo pipefail
if ! command -v docker >/dev/null 2>&1; then
echo "docker CLI missing in job image; fetching static client"
curl -fsSL "$DOCKER_STATIC_URL" -o /tmp/docker.tgz
tar -xzf /tmp/docker.tgz -C /tmp
install -m 755 /tmp/docker/docker /usr/local/bin/docker
fi
export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}"
docker version
docker info >/tmp/docker-info.txt
grep -E 'Server Version|Operating System|Total Memory|Name' /tmp/docker-info.txt || true
- name: Build APK + AAR in bookworm container
id: build
env:
VERSION: ${{ steps.version.outputs.version }}
VERSION_CODE: ${{ steps.version.outputs.version_code }}
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}"
start=$(date +%s)
cat > .ci-android-build.sh <<'INNER'
#!/usr/bin/env bash
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive
apt-get update
# `cmake` is for RandomX, the C++ half of the in-process chain daemon
# (`cuprate-daemon`, built into the SDK): without it `randomx-rs`'s build
# script panics with "is `cmake` not installed?" and the Gradle task dies
# on "cargo finished with non-zero exit value 101". Same as android-ci.yml.
apt-get install -y --no-install-recommends \
openjdk-17-jdk-headless python3 unzip curl ca-certificates file build-essential pkg-config git \
cmake
mkdir -p /root/.android
cp /src/.ci-android/onionwire-release.jks /root/.android/onionwire-release.jks
cp /src/.ci-android/onionwire-release.env /root/.android/onionwire-release.env
chmod 600 /root/.android/onionwire-release.jks /root/.android/onionwire-release.env
# shellcheck disable=SC1091
set -a
source /root/.android/onionwire-release.env
set +a
if [ ! -x /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager ]; then
mkdir -p /opt/android-sdk/cmdline-tools
curl -fsSL "$ANDROID_CMDLINE_TOOLS_URL" -o /tmp/cmdline-tools.zip
rm -rf /tmp/cmdline-tools
unzip -q /tmp/cmdline-tools.zip -d /tmp/cmdline-tools
mkdir -p /opt/android-sdk/cmdline-tools/latest
cp -a /tmp/cmdline-tools/cmdline-tools/. /opt/android-sdk/cmdline-tools/latest/
fi
yes | /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root=/opt/android-sdk --licenses >/tmp/sdk-licenses.log || true
/opt/android-sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root=/opt/android-sdk \
"platform-tools" "platforms;android-36" "build-tools;36.0.0" "ndk;28.2.13676358"
test -d /opt/android-sdk/ndk/28.2.13676358
export ANDROID_HOME=/opt/android-sdk ANDROID_SDK_ROOT=/opt/android-sdk
export ANDROID_NDK_HOME=/opt/android-sdk/ndk/28.2.13676358
export PATH="$ANDROID_HOME/build-tools/36.0.0:$ANDROID_HOME/platform-tools:$PATH"
if [ ! -x /cargo/bin/rustup ]; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain "$RUST_TOOLCHAIN" --no-modify-path --profile minimal
fi
export PATH="/cargo/bin:$PATH"
rustup toolchain install "$RUST_TOOLCHAIN"
rustup default "$RUST_TOOLCHAIN"
rustup target add aarch64-linux-android
command -v cargo-ndk >/dev/null || cargo install cargo-ndk --locked
echo "=== toolchain ==="
java -version
rustc --version
cargo ndk --version
du -sh /opt/android-sdk /cargo /cargo-target /gradle || true
find /gradle -name '*.lock' -type f -delete 2>/dev/null || true
export GRADLE_OPTS="${GRADLE_OPTS:-} -Dorg.gradle.parallel=false -Dorg.gradle.daemon=false"
scripts/build-android-local.sh "$ONIONWIRE_VERSION"
version="$ONIONWIRE_VERSION"
abi="${ONIONWIRE_ANDROID_ABI:-arm64-v8a}"
apk="dist/onionwire-$version-android-$abi.apk"
aar="dist/onionwire-sdk-$version.aar"
{
echo "=== file ==="
file "$apk" "$aar"
echo "=== unzip lib ==="
unzip -l "$apk" | grep -E 'lib/.+\.so|AndroidManifest.xml' || true
unzip -l "$apk" | grep "lib/$abi/libonionwire_sdk.so"
echo "=== sha256 ==="
( cd dist && sha256sum -c "onionwire-$version-android-$abi.apk.sha256" "onionwire-sdk-$version.aar.sha256" )
echo "=== apksigner ==="
apksigner verify --print-certs "$apk"
echo "=== aapt ==="
aapt dump badging "$apk" | sed -n '1,20p' || true
echo "=== sizes ==="
wc -c "$apk" "$aar"
} | tee dist/ci-verify.log
INNER
chmod +x .ci-android-build.sh
docker volume create "$SDK_VOLUME" >/dev/null
docker volume create "$CARGO_VOLUME" >/dev/null
docker volume create "$TARGET_VOLUME" >/dev/null
docker volume create "$GRADLE_VOLUME" >/dev/null
# Same shared GRADLE_VOLUME as android-ci.yml. A cancelled job leaves
# the build container running and journal-1.lock held.
trap 'docker rm -f "$BUILD_CONTAINER" >/dev/null 2>&1 || true' EXIT
docker ps -aq --filter name=onionwire-android- | xargs -r docker rm -f || true
docker rm -f "$BUILD_CONTAINER" >/dev/null 2>&1 || true
docker pull "$ANDROID_IMAGE"
# 2 GB of Gradle heap, not 1: the only budget in this build that is close
# is the single-use daemon's heap, which now has to package a 55 MB SDK
# lib (plus RandomX's 1.1 MB) through AGP's in-daemon packaging. Run 414
# died in `:app:packageRelease` with the cause hidden inside
# `PackageAndroidArtifact$IncrementalSplitterRunnable` — no "Caused by"
# line, nothing in the log — so give it room instead of guessing again.
# The runner has 15 GB and the job's peak RSS is ~3 GB.
docker create --name "$BUILD_CONTAINER" -i \
-e CARGO_TERM_COLOR=never \
-e CARGO_BUILD_JOBS="$CARGO_BUILD_JOBS" \
-e CARGO_HOME=/cargo \
-e CARGO_TARGET_DIR=/cargo-target \
-e GRADLE_USER_HOME=/gradle \
-e ANDROID_HOME=/opt/android-sdk \
-e ANDROID_SDK_ROOT=/opt/android-sdk \
-e ANDROID_NDK_HOME=/opt/android-sdk/ndk/28.2.13676358 \
-e ONIONWIRE_ANDROID_ABI="$ONIONWIRE_ANDROID_ABI" \
-e ONIONWIRE_REQUIRE_RELEASE_KEY=true \
-e ONIONWIRE_VERSION_CODE="$VERSION_CODE" \
-e ONIONWIRE_VERSION="$VERSION" \
-e RUST_TOOLCHAIN="$RUST_TOOLCHAIN" \
-e ANDROID_CMDLINE_TOOLS_URL="$ANDROID_CMDLINE_TOOLS_URL" \
-e GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=false -Dorg.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8" \
-v "$SDK_VOLUME":/opt/android-sdk \
-v "$CARGO_VOLUME":/cargo \
-v "$TARGET_VOLUME":/cargo-target \
-v "$GRADLE_VOLUME":/gradle \
-w /src \
"$ANDROID_IMAGE" \
bash -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src && bash /src/.ci-android-build.sh'
# Staging dir is included in the tar as .ci-android/ (gitignored paths).
mkdir -p .ci-android
cp "$HOME/.android/onionwire-release.jks" .ci-android/onionwire-release.jks
cp "$HOME/.android/onionwire-release.env" .ci-android/onionwire-release.env
tar czf - \
--exclude=./target --exclude=./.git --exclude=./.worktrees \
--exclude=./android/.gradle --exclude=./android/app/build \
--exclude=./android/sdk/build --exclude=./dist \
--exclude=./crates/onionwire-sdk/target \
. \
| docker start -a -i "$BUILD_CONTAINER"
mkdir -p dist
docker cp "$BUILD_CONTAINER:/src/dist/." dist/
end=$(date +%s)
echo "build_wall_clock_seconds=$((end - start))"
echo "wall_clock_seconds=$((end - start))" >> "$GITHUB_OUTPUT"
docker rm -f "$BUILD_CONTAINER" >/dev/null || true
rm -rf .ci-android
ls -l dist/
- name: Verify artifacts
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
version="${{ steps.version.outputs.version }}"
abi="$ONIONWIRE_ANDROID_ABI"
apk="dist/onionwire-$version-android-$abi.apk"
aar="dist/onionwire-sdk-$version.aar"
[ -s "$apk" ] || { echo "missing or empty $apk" >&2; exit 1; }
[ -s "$aar" ] || { echo "missing or empty $aar" >&2; exit 1; }
apk_bytes=$(wc -c < "$apk")
aar_bytes=$(wc -c < "$aar")
echo "apk_bytes=$apk_bytes aar_bytes=$aar_bytes"
[ "$apk_bytes" -gt 0 ]
[ "$aar_bytes" -gt 0 ]
( cd dist && sha256sum -c "onionwire-$version-android-$abi.apk.sha256" "onionwire-sdk-$version.aar.sha256" )
echo "=== ci-verify.log (from bookworm build container) ==="
cat dist/ci-verify.log
echo "=== resources after build ==="
free -h || true
df -h || true
export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}"
docker images "$ANDROID_IMAGE" --format '{{.Repository}}:{{.Tag}} {{.Size}}' || true
docker system df || true
- name: Upload dist artifact
uses: https://code.forgejo.org/actions/upload-artifact@v3
with:
name: onionwire-android
path: dist/
if-no-files-found: error
retention-days: 1
- name: Scrub keystore
if: always()
run: |
set -euo pipefail
rm -rf "$HOME/.android/onionwire-release.jks" "$HOME/.android/onionwire-release.env" .ci-android
echo "keystore removed from runner"
publish:
needs: android
# Pi runner, not docker-amd64: POST /releases from amd64 dind returns 422
# with an empty body (core run 116). This job only curls the Forgejo API.
# `always()` is load-bearing on this runner, not decoration. Without it the
# job-level `needs.android.result` gate is evaluated as unset, the job is
# dropped before it is ever created (it does not appear in
# /actions/runs/<n>/jobs at all, so it reads as a silent skip), and the APK
# and AAR never reach the release. Run 770 did exactly that: `android`
# green, no `publish` job, eleven assets and no APK. release.yml's publish
# job carries the same prefix for the same reason (run 135).
if: always() && needs.android.result == 'success' && needs.android.outputs.dry_run != 'true'
runs-on: docker
timeout-minutes: 20
steps:
- name: Checkout CI tooling
uses: https://code.forgejo.org/actions/checkout@v4
with:
path: .ci-tools
- name: Download Android dist
uses: https://code.forgejo.org/actions/download-artifact@v3
with:
path: artifacts
- name: Publish (create-or-join)
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
EVENT_SHA: ${{ github.sha }}
TAG: ${{ needs.android.outputs.tag }}
VERSION: ${{ needs.android.outputs.version }}
run: |
set -euo pipefail
: "${FORGEJO_TOKEN:?FORGEJO_TOKEN secret is missing}"
echo "publish host=$(hostname) arch=$(uname -m) tag=$TAG version=$VERSION"
mkdir -p dist
abi="$ONIONWIRE_ANDROID_ABI"
apk="onionwire-$VERSION-android-$abi.apk"
aar="onionwire-sdk-$VERSION.aar"
for f in "$apk" "$apk.sha256" "$aar" "$aar.sha256"; do
src=$(find artifacts -type f -name "$f" -print -quit)
if [ -z "$src" ]; then
echo "missing artifact $f" >&2
find artifacts -type f >&2 || true
exit 1
fi
cp "$src" "dist/$f"
done
for f in dist/"$apk" dist/"$apk".sha256 dist/"$aar" dist/"$aar".sha256; do
bytes=$(wc -c < "$f")
echo "on disk: $f $bytes bytes"
[ "$bytes" -gt 0 ] || { echo "refusing to publish empty $f" >&2; exit 1; }
file "$f" || true
done
tag_exists=0
i=0
while [ "$i" -lt 6 ]; do
code=$(curl -sS --http1.1 -o /tmp/tag.json -w '%{http_code}' \
-u "sirius:${FORGEJO_TOKEN}" \
"$REPO_API/tags/$TAG" || true)
if [ "$code" = "200" ]; then
tag_exists=1
echo "tag $TAG already exists; joining"
break
fi
i=$((i + 1))
echo "tag $TAG not found yet (http $code), wait 10s ($i/6)"
sleep 10
done
if [ "$tag_exists" = "1" ]; then
unset TARGET_COMMITISH || true
else
export TARGET_COMMITISH="$EVENT_SHA"
echo "creating tag $TAG at $TARGET_COMMITISH"
fi
echo "publishing $TAG from $REPO_API"
.ci-tools/scripts/publish-release.sh \
"$TAG" "OnionWire $TAG" \
.ci-tools/scripts/release-body.md \
"dist/$apk" \
"dist/$apk.sha256" \
"dist/$aar" \
"dist/$aar.sha256"

View file

@ -0,0 +1,72 @@
name: arti-watch
# Daily upstream check for the in-process Tor stack. Arti onion services are
# experimental (README) and tor-*/arti-* are the largest attack surface here,
# so when crates.io has a newer major.minor than the pins in Cargo.toml this
# files ONE Forgejo issue (deduped on the title — a second run is a no-op).
#
# Forgejo has no Dependabot: this workflow IS the dependency alert. It
# deliberately bumps nothing. A bump is a reviewed PR; the procedure, toolchain
# floor and the tests it must pass are in docs/ARTI_UPGRADE.md.
#
# NOT covered, by design: Tor Project security announcements (a fix that ships
# with no crates.io version bump is invisible here) and a yanked crate /
# vulnerability in a version that has not changed. Read
# https://blog.torproject.org/ yourself.
on:
schedule:
# 06:17 UTC daily. Forgejo cron is UTC; off the hour on purpose.
- cron: "17 6 * * *"
workflow_dispatch:
inputs:
dry_run:
description: Compare and log only, file no issue (true/false)
required: false
type: string
default: "false"
simulate_pin:
description: 'Test the alert path on real crates.io data, e.g. "arti-client=0.45,tor-hsservice=0.45". Empty = the real Cargo.toml pins.'
required: false
type: string
# Never two watchers at once: two simultaneous runs could both see "no issue
# with this title yet" and file twice.
concurrency:
group: onionwire-arti-watch
cancel-in-progress: false
jobs:
watch:
# Same Pi runner + `docker` job image as ci.yml / release.yml (which run
# python3 and curl there). No cargo, no docker: four crates.io GETs and at
# most one issue POST.
runs-on: docker
timeout-minutes: 10
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
- name: Compare pins against crates.io and file an issue on a bump
shell: bash
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
INPUT_DRY_RUN: ${{ github.event.inputs.dry_run }}
INPUT_SIMULATE_PIN: ${{ github.event.inputs.simulate_pin }}
run: |
set -euo pipefail
args=(--cargo-toml Cargo.toml)
case "${INPUT_DRY_RUN:-false}" in
true|True|TRUE|1|yes|YES) args+=(--dry-run) ;;
esac
if [ -n "${INPUT_SIMULATE_PIN:-}" ]; then
IFS=',' read -ra pairs <<< "$INPUT_SIMULATE_PIN"
for pair in "${pairs[@]}"; do
pair="${pair// /}"
if [ -n "$pair" ]; then
args+=(--simulate-pin "$pair")
fi
done
fi
echo "run: python3 scripts/arti-watch.py ${args[*]}"
python3 scripts/arti-watch.py "${args[@]}"

View file

@ -2,24 +2,72 @@ name: ci
# Tests and clippy run on the Pi runner (aarch64) inside a rust container, so # Tests and clippy run on the Pi runner (aarch64) inside a rust container, so
# this CI proves the aarch64 build too. Jobs use the runner's `docker` label. # this CI proves the aarch64 build too. Jobs use the runner's `docker` label.
#
# Path allowlist: skip the cargo job when the change cannot affect the Rust
# build (docs, android, scripts, sibling workflows, markdown). No required
# status checks on main, so a missing run is not a merge trap.
# workflow_dispatch has no path filter — it always runs the suite.
#
# The nightly cargo-fuzz job used to be a third job here. It had its own
# workflow (`.forgejo/workflows/fuzz.yml`, `schedule` only) because a job
# cannot narrow a workflow-level path filter: `fuzz/**` sat in the list
# alongside `src/**` and `crates/**`, so 80 of 84 recorded fuzz runs touched
# nothing in `fuzz/`.
on: on:
push: push:
branches: [main] branches: [main]
paths:
- "src/**"
- "crates/**"
- "tests/**"
- "Cargo.toml"
- "Cargo.lock"
- ".forgejo/workflows/ci.yml"
pull_request: pull_request:
paths:
- "src/**"
- "crates/**"
- "tests/**"
- "Cargo.toml"
- "Cargo.lock"
- ".forgejo/workflows/ci.yml"
workflow_dispatch: workflow_dispatch:
# One cargo job on the Pi at a time. Overlapping PR+main runs shared the # One cargo job on the Pi at a time. Overlapping runs share the
# container name `onionwire-ci` (docker Conflict) and OOM-killed with 137. # `onionwire-cargo-registry` and `onionwire-target-ci` volumes, and two
# writers to one cargo target dir produce `Permission denied (os error 13)`
# on /target/debug/deps binaries. The per-run container name (below) is no
# longer shared, so the docker Conflict is gone — but the volume race is not,
# and the serialization is what prevents it.
#
# `cancel-in-progress` stays false: cancelling a *queued* run would release
# this group and let the next run start a second cargo job against the same
# volume. Superseded runs are instead skipped by the staleness gate at the
# top of each job, which costs seconds instead of the minutes a full build
# spends proving something nobody will look at.
concurrency: concurrency:
group: onionwire-ci-pi group: onionwire-ci-pi
cancel-in-progress: false cancel-in-progress: false
env: env:
CARGO_TERM_COLOR: never CARGO_TERM_COLOR: never
RUST_IMAGE: rust:1.91-bookworm # Not 1.91. `cuprate-daemon` is a default feature, so `cargo test --locked`
# compiles `tapes`, which calls `VecDeque::pop_front_if` (stable since 1.93).
# On `rust:1.91-bookworm` that is `error[E0658]: use of unstable library
# feature 'vec_deque_pop_if'`, after the job has already built the rest of
# the graph. 1.98 is the release this graph is built with on the dev machine
# and in the Android workflows. `--no-default-features` still builds on 1.91
# (Arti 0.49's floor); the default build does not, so the image follows the
# default build.
RUST_IMAGE: rust:1.98-bookworm
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: `crates/onionwire-sdk` is a
# separate cargo workspace with its own lockfile and its own crate set, so
# sharing a target dir with the root job would thrash both.
SDK_CARGO_TARGET_VOLUME: onionwire-target-ci-sdk
SDK_BUILD_CONTAINER: onionwire-ci-sdk-${{ github.run_id }}
jobs: jobs:
test: test:
@ -29,7 +77,36 @@ jobs:
- name: Checkout - name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4 uses: https://code.forgejo.org/actions/checkout@v4
- name: Skip superseded run
id: staleness
run: |
set -uo pipefail
# A force-push, or a merge of another PR, can put a newer commit on
# this branch while this run sits in the concurrency queue above.
# Testing it then proves nothing about the tree that is actually on
# the branch. 279 of 353 runs in a two-week window were on an
# already-superseded sha — the single largest source of wasted Pi
# time, and `cancel-in-progress: true` cannot fix it without letting
# two cargo jobs share the target volume.
#
# For a pull_request, GITHUB_HEAD_REF is the PR's source branch (the
# ref itself is refs/pull/N/merge); for a push it is empty, so fall
# back to GITHUB_REF_NAME.
ref="${GITHUB_HEAD_REF:-${GITHUB_REF_NAME:-}}"
remote=""
if [ -n "$ref" ]; then
remote="$(git ls-remote origin "refs/heads/$ref" 2>/dev/null | cut -f1)"
fi
if [ -n "$remote" ] && [ "$remote" != "$GITHUB_SHA" ]; then
echo "::notice::superseded: refs/heads/$ref is at ${remote:0:12}, this run is ${GITHUB_SHA:0:12} — skipping"
echo "skip=true" >> "$GITHUB_OUTPUT"
else
echo "tip=${remote:-unknown} sha=${GITHUB_SHA} ref=${ref:-none} — running"
echo "skip=false" >> "$GITHUB_OUTPUT"
fi
- name: cargo test + clippy on aarch64 - name: cargo test + clippy on aarch64
if: steps.staleness.outputs.skip != 'true'
run: | run: |
set -euo pipefail set -euo pipefail
cd "${GITHUB_WORKSPACE}" cd "${GITHUB_WORKSPACE}"
@ -41,16 +118,88 @@ jobs:
-e CARGO_TARGET_DIR=/target \ -e CARGO_TARGET_DIR=/target \
-e CARGO_BUILD_JOBS=2 \ -e CARGO_BUILD_JOBS=2 \
-e CARGO_TERM_COLOR=never \ -e CARGO_TERM_COLOR=never \
-e TMPDIR=/target/tmp \
-v "$CARGO_REGISTRY_VOLUME":/usr/local/cargo/registry \ -v "$CARGO_REGISTRY_VOLUME":/usr/local/cargo/registry \
-v "$CARGO_TARGET_VOLUME":/target \ -v "$CARGO_TARGET_VOLUME":/target \
-w /src \ -w /src \
"$RUST_IMAGE" \ "$RUST_IMAGE" \
sh -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src \ sh -euxc 'mkdir -p /src /target/tmp && tar xzf - -C /src && cd /src \
&& apt-get update \ && apt-get update \
&& apt-get install -y --no-install-recommends pkg-config libssl-dev \ && apt-get install -y --no-install-recommends cmake build-essential \
&& rustup component add clippy \ && rustup component add clippy \
&& cargo test --locked \ && cargo test --locked \
&& cargo clippy --locked --all-targets -- -D warnings' && cargo clippy --locked --all-targets -- -D warnings'
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. 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.
#
# The root `test` job installs `cmake` and `build-essential` (g++, make) because
# the default feature set includes `cuprate-daemon`. RandomX's build script
# calls cmake; without it the job dies with "is cmake not installed?" (os error 2).
# It still does not install `pkg-config`/`libssl-dev` — the root crate defaults
# to Arti's rustls backend, so TLS needs no system OpenSSL.
# The `rusqlite` `bundled-sqlcipher-vendored-openssl` feature that both jobs
# use compiles OpenSSL from source, which needs `perl` and `make` (present in
# the `rust:*-bookworm` image), not the `-dev` headers. This job keeps the
# install: the Android SDK build is unchanged by the root crate's TLS default.
sdk:
runs-on: docker
timeout-minutes: 120
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
- name: Skip superseded run
id: staleness
run: |
set -uo pipefail
# Same gate as the `test` job above — see the comment there.
ref="${GITHUB_HEAD_REF:-${GITHUB_REF_NAME:-}}"
remote=""
if [ -n "$ref" ]; then
remote="$(git ls-remote origin "refs/heads/$ref" 2>/dev/null | cut -f1)"
fi
if [ -n "$remote" ] && [ "$remote" != "$GITHUB_SHA" ]; then
echo "::notice::superseded: refs/heads/$ref is at ${remote:0:12}, this run is ${GITHUB_SHA:0:12} — skipping"
echo "skip=true" >> "$GITHUB_OUTPUT"
else
echo "tip=${remote:-unknown} sha=${GITHUB_SHA} ref=${ref:-none} — running"
echo "skip=false" >> "$GITHUB_OUTPUT"
fi
- name: cargo test + clippy for crates/onionwire-sdk on aarch64
if: steps.staleness.outputs.skip != 'true'
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 \
-e TMPDIR=/target/tmp \
-v "$CARGO_REGISTRY_VOLUME":/usr/local/cargo/registry \
-v "$SDK_CARGO_TARGET_VOLUME":/target \
-w /src \
"$RUST_IMAGE" \
sh -euxc 'mkdir -p /src /target/tmp && 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

@ -0,0 +1,99 @@
name: fuzz
# Nightly cargo-fuzz harness. The `fuzz/` crate (PR #103) is a detached
# workspace with four libFuzzer targets over the untrusted-input parsers —
# RatchetState::from_bytes/decrypt, qr::decode, dispatch::classify, file::decode.
# Nothing else in CI compiles this crate, so the targets bit-rot silently.
#
# This used to be a job in `ci.yml`, which meant it inherited that workflow's
# PR path filter (`src/**`, `crates/**`, `tests/**`, `Cargo.lock`, …) and ran
# on almost every push: 80 of 84 recorded runs touched neither `fuzz/` nor
# `scripts/run-fuzz.sh`. Each one also paid `rustup toolchain install nightly`
# plus `cargo install cargo-fuzz --locked` before it could do 15 seconds of
# fuzzing. Bit-rot is a slow signal; a PR gate is the wrong shape for it.
#
# It is a scheduled job now. `workflow_dispatch` is the manual escape hatch
# (a parser change deserves a longer run than the 15s below — raise FUZZ_SECS
# in the dispatch env for that).
on:
schedule:
# 03:30 UTC nightly. Forgejo cron is UTC; off the hour on purpose so it
# does not pile onto the 06:17 arti-watch slot.
- cron: "30 3 * * *"
workflow_dispatch:
# Never two fuzz runs at once: they hold the shared fuzz registry and target
# volumes, and a second one is a `docker Conflict` plus a cold rebuild.
concurrency:
group: onionwire-ci-pi-fuzz
cancel-in-progress: false
env:
CARGO_TERM_COLOR: never
# Base image only: the job switches to nightly before it compiles. Kept on
# the same tag as ci.yml so a step that forgets `+nightly` does not die in
# `tapes` on 1.91 (`VecDeque::pop_front_if`).
RUST_IMAGE: rust:1.98-bookworm
# The build needs a release profile + debug=line-tables-only, so it must not
# thrash the test/sdk target volumes and needs its own registry cache.
FUZZ_REGISTRY_VOLUME: onionwire-cargo-registry-fuzz
FUZZ_TARGET_VOLUME: onionwire-target-ci-fuzz
FUZZ_BUILD_CONTAINER: onionwire-ci-fuzz-${{ github.run_id }}
# libFuzzer writes its -fork dir into TMPDIR; point it at the target volume so
# a host tmpfs quota can't OOM-kill the builder.
FUZZ_TMP_DIR: /target/tmp
# Per-build CPU budget. The Pi has 4 cores shared with whatever CI run is
# live, so 2 is what leaves headroom.
FUZZ_SECS: "15"
FUZZ_JOBS: "2"
jobs:
build:
runs-on: docker
timeout-minutes: 120
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
- name: build + run fuzz targets
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
echo "workspace: $GITHUB_WORKSPACE"
docker volume create "$FUZZ_REGISTRY_VOLUME" > /dev/null
docker volume create "$FUZZ_TARGET_VOLUME" > /dev/null
docker rm -f "$FUZZ_BUILD_CONTAINER" > /dev/null 2>&1 || true
# Build AND run in ONE container. Splitting them into two
# `docker create` calls gives the second one a fresh image, and the
# cargo-fuzz binary installed in the first is gone with it
# (PR #106 fixed this; PR #106/#107 added the PATH export too).
docker create --name "$FUZZ_BUILD_CONTAINER" -i \
-e CARGO_TARGET_DIR=/target \
-e CARGO_BUILD_JOBS=2 \
-e CARGO_TERM_COLOR=never \
-e TMPDIR=/target/tmp \
-e RUSTUP_HOME=/usr/local/rustup \
-e CARGO_HOME=/usr/local/cargo \
-e FUZZ_SECS="$FUZZ_SECS" \
-e FUZZ_JOBS="$FUZZ_JOBS" \
-v "$FUZZ_REGISTRY_VOLUME":/usr/local/cargo/registry \
-v "$FUZZ_TARGET_VOLUME":/target \
-w /src \
"$RUST_IMAGE" \
sh -euxc 'mkdir -p /src /target/tmp && tar xzf - -C /src && cd /src \
&& apt-get update \
&& apt-get install -y --no-install-recommends pkg-config libssl-dev cmake build-essential \
&& rustup toolchain install nightly --profile minimal \
&& rustup default nightly \
&& cargo install cargo-fuzz --locked \
&& export PATH="/usr/local/cargo/bin:$PATH" \
&& cd /src/fuzz \
&& cargo +nightly fuzz build \
&& cargo +nightly fuzz list \
&& bash /src/scripts/run-fuzz.sh'
# A fresh Docker volume has no tmp/ subdirectory, and rustup fails
# with "error creating temp directory: No such file or directory" if
# TMPDIR points into one that does not exist yet.
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \
| docker start -a -i "$FUZZ_BUILD_CONTAINER"
docker rm -f "$FUZZ_BUILD_CONTAINER" > /dev/null

View file

@ -1,111 +1,620 @@
name: release name: release
# Native aarch64 build on the Pi runner, published to the Forgejo release. # Manual, batched releases. There is deliberately NO push trigger: a merged
# x86_64 is NOT built here: there is no x86_64 runner on this instance — build # PR does not mint a release. A maintainer dispatches this at a stopping point
# it on an x86_64 host with scripts/build-release-local.sh (same release, same # (a batch of work has landed and CI is green on main) — see docs/RELEASING.md.
# asset naming), or the release will carry aarch64 only. # Tag-push is intentionally NOT a trigger here: this workflow creates the tag
# via the API, and a tag-push hook would start a second run of the same release.
# (A tag this workflow creates does not wake android-release.yml either — see
# docs/RELEASING.md: on this Forgejo, pushes made with the CI token are
# Actions-user events and are not dispatched back into Actions.)
# Version: explicit `version`, else `bump` off the newest v*.*.* tag
# (default minor — a batched release is usually a feature set); zero tags → v0.1.0.
on: on:
push:
tags:
- "v*.*.*"
workflow_dispatch: workflow_dispatch:
inputs: inputs:
bump:
description: Bump off the newest v*.*.* tag (ignored when version or tag is set)
required: false
type: choice
options:
- minor
- patch
- major
default: minor
version:
description: Explicit version MAJOR.MINOR.PATCH (or vMAJOR.MINOR.PATCH); overrides bump
required: false
type: string
tag: tag:
description: Existing tag to (re)build and publish description: Existing tag to (re)build and publish (empty = create the next version)
required: true required: false
type: string
dry_run:
description: Build and checksum without creating a tag or publishing (true/false)
required: false
type: string
default: "false"
# Same group as ci.yml: both cargo builds share the Pi's 4 cores and the
# onionwire-cargo-registry volume. A separate group raced tests and produced
# Permission denied (os error 13) on /target/debug/deps/* binaries.
concurrency:
group: onionwire-ci-pi
cancel-in-progress: false
env: env:
CARGO_TERM_COLOR: never CARGO_TERM_COLOR: never
TARGET: aarch64-unknown-linux-gnu # Same floor as ci.yml: the release binary has `cuprate-daemon` on by default,
# Job steps run inside node:20-bullseye (the runner's docker label image) with # and `tapes` does not build on 1.91 (`VecDeque::pop_front_if`, stable in 1.93).
# the host docker socket mounted, so builds happen in a sibling rust container. # Pinned by DIGEST, not by tag. `rust:1.98-bookworm` floats: a rustc patch
RUST_IMAGE: rust:1.91-bookworm # release changes codegen and therefore every published hash — which turns a
# routine toolchain bump into an unexplainable reproducibility mismatch for
# anyone verifying an old release. rustc in this digest is 1.98.1
# (48a229cea), LLVM 21.1.2, host x86_64-unknown-linux-gnu. 1.98 is the floor
# for the default feature set (see Cargo.toml rust-version).
#
# This digest IS the release recipe, and it must match BUILDER_IMAGE in
# scripts/verify-reproducible.sh and scripts/build-release-local.sh. If they
# disagree, a verifier rebuilds with a different toolchain than CI shipped and
# reports a false mismatch. Bump all of them in one commit — docs/VERIFY.md.
RUST_IMAGE: rust@sha256:93ce27a88655056a51dbdd8f5f2d7ddc071c7b0070fb288a37b5a285fc83971e
# Not baking pkg-config/libssl-dev into a custom image on this card —
# dind PVC would make that the durable fix for the apt loop. Filed separately.
CARGO_REGISTRY_VOLUME: onionwire-cargo-registry CARGO_REGISTRY_VOLUME: onionwire-cargo-registry
CARGO_TARGET_VOLUME: onionwire-target-aarch64
BUILD_CONTAINER: onionwire-release-build-${{ github.run_id }}
jobs: jobs:
aarch64: version:
runs-on: docker runs-on: docker
timeout-minutes: 120 timeout-minutes: 10
outputs:
tag: ${{ steps.plan.outputs.tag }}
sha: ${{ steps.plan.outputs.sha }}
dry_run: ${{ steps.plan.outputs.dry_run }}
created_tag: ${{ steps.plan.outputs.created_tag }}
steps: steps:
- name: Checkout the source tag - name: Plan version, create tag unless dry_run
uses: https://code.forgejo.org/actions/checkout@v4 id: plan
with:
# A tag push builds that tag; a manual dispatch builds the tag the
# caller named (otherwise the binary version would not match the
# release it is attached to).
ref: ${{ github.event.inputs.tag || github.ref_name }}
- name: Checkout the CI tooling
uses: https://code.forgejo.org/actions/checkout@v4
with:
# scripts/ and .forgejo/ only exist on the branch (older tags predate
# them), and the workflow itself is read from the dispatched ref — so
# fetch the same ref into .ci-tools and run the scripts from there.
ref: ${{ github.ref_name }}
path: .ci-tools
- name: Build ${{ env.TARGET }} in a rust container
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
echo "workspace: $GITHUB_WORKSPACE"
docker volume create "$CARGO_REGISTRY_VOLUME" > /dev/null
docker volume create "$CARGO_TARGET_VOLUME" > /dev/null
docker rm -f "$BUILD_CONTAINER" > /dev/null 2>&1 || true
# The workspace lives in a per-task volume the host daemon cannot
# resolve, so pipe the source tree in over stdin (tar) and pull the
# binary back out with docker cp.
docker create --name "$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 "$CARGO_TARGET_VOLUME":/target \
-w /src \
"$RUST_IMAGE" \
sh -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src \
&& apt-get update \
&& apt-get install -y --no-install-recommends pkg-config libssl-dev \
&& cargo build --release --locked \
&& strip /target/release/onionwire \
&& ls -l /target/release/onionwire'
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees \
--exclude=./.ci-tools . \
| docker start -a -i "$BUILD_CONTAINER"
mkdir -p dist
docker cp "$BUILD_CONTAINER:/target/release/onionwire" "dist/onionwire-$TARGET"
docker rm -f "$BUILD_CONTAINER" > /dev/null
- name: Pack and checksum
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}/dist"
file "onionwire-$TARGET"
sha256sum "onionwire-$TARGET" > "onionwire-$TARGET.sha256"
sha256sum -c "onionwire-$TARGET.sha256"
ls -l
- name: Publish to the Forgejo release
env: env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }} FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }} REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
EVENT_NAME: ${{ github.event_name }} EVENT_NAME: ${{ github.event_name }}
EVENT_SHA: ${{ github.sha }} EVENT_SHA: ${{ github.sha }}
REF: ${{ github.ref_name }} INPUT_BUMP: ${{ github.event.inputs.bump }}
INPUT_VERSION: ${{ github.event.inputs.version }}
INPUT_TAG: ${{ github.event.inputs.tag }} INPUT_TAG: ${{ github.event.inputs.tag }}
INPUT_DRY_RUN: ${{ github.event.inputs.dry_run }}
run: |
set -euo pipefail
: "${FORGEJO_TOKEN:?FORGEJO_TOKEN secret is not set}"
FORGEJO_TOKEN=$(printf '%s' "$FORGEJO_TOKEN" | tr -d '\r\n')
dry_run=false
if [ "$EVENT_NAME" = "workflow_dispatch" ]; then
case "${INPUT_DRY_RUN:-false}" in
true|True|TRUE|1|yes|YES) dry_run=true ;;
esac
fi
echo "event=$EVENT_NAME sha=$EVENT_SHA input_version=${INPUT_VERSION-} input_tag=${INPUT_TAG-} input_bump=${INPUT_BUMP-} input_dry_run=${INPUT_DRY_RUN-} dry_run=$dry_run"
api_curl() {
curl -sS --http1.1 --retry 5 --retry-all-errors --retry-delay 3 \
--connect-timeout 20 --max-time 60 \
-u "sirius:${FORGEJO_TOKEN}" "$@" | sed 's/\r$//'
}
input_tag="${INPUT_TAG:-}"
version_input="${INPUT_VERSION:-}"
bump="${INPUT_BUMP:-minor}"
# Contradictory input is rejected, never guessed at.
if [ -n "$input_tag" ] && [ -n "$version_input" ]; then
echo "got both tag='$input_tag' and version='$version_input': tag rebuilds an existing tag, version mints a new one — pass one" >&2
exit 1
fi
if [ -n "$input_tag" ]; then
code=$(api_curl -o /tmp/tag.json -w '%{http_code}' \
"$REPO_API/tags/$input_tag")
if [ "$code" != "200" ]; then
echo "dispatch tag $input_tag not found (HTTP $code)" >&2
cat /tmp/tag.json >&2 || true
exit 1
fi
sha=$(python3 -c "import json; print(json.load(open('/tmp/tag.json'))['commit']['sha'])")
tag="$input_tag"
created=false
echo "re-publish existing tag $tag at $sha (dry_run=$dry_run)"
else
if [ -n "$version_input" ]; then
tag=$(python3 -c "import re,sys; m=re.fullmatch(r'v?([0-9]+)\.([0-9]+)\.([0-9]+)', sys.argv[1].strip()); print('v' + '.'.join(m.groups()) if m else '')" "$version_input")
if [ -z "$tag" ]; then
echo "version must be MAJOR.MINOR.PATCH or vMAJOR.MINOR.PATCH, got '$version_input'" >&2
exit 1
fi
else
case "$bump" in
patch|minor|major) ;;
*) echo "bump must be patch|minor|major, got '$bump'" >&2; exit 1 ;;
esac
api_curl "$REPO_API/tags?limit=50" -o /tmp/tags.json
latest=$(python3 -c "import json,re; tags=json.load(open('/tmp/tags.json')); assert isinstance(tags, list), tags; s=[tuple(int(x) for x in m.groups()) for t in tags for m in [re.fullmatch(r'v([0-9]+)\.([0-9]+)\.([0-9]+)', t.get('name') or '')] if m]; print('%d.%d.%d' % max(s) if s else '')")
if [ -z "$latest" ]; then
tag="v0.1.0"
else
major="${latest%%.*}"
rest="${latest#*.}"
minor="${rest%%.*}"
patch="${rest#*.}"
case "$bump" in
major) tag="v$((major + 1)).0.0" ;;
minor) tag="v$major.$((minor + 1)).0" ;;
patch) tag="v$major.$minor.$((patch + 1))" ;;
esac
fi
fi
sha="$EVENT_SHA"
created=false
if [ "$dry_run" = "true" ]; then
echo "dry_run: would use $tag on $sha (no tag created)"
else
code=$(api_curl -o /tmp/tag.json -w '%{http_code}' \
"$REPO_API/tags/$tag")
if [ "$code" = "200" ]; then
existing=$(python3 -c "import json; print(json.load(open('/tmp/tag.json'))['commit']['sha'])")
if [ "$existing" != "$sha" ]; then
echo "tag $tag exists on $existing, not moving from $sha" >&2
exit 1
fi
echo "tag $tag already exists on $sha — joining"
elif [ "$code" = "404" ]; then
python3 -c "import json,sys; json.dump({'tag_name':sys.argv[1],'target':sys.argv[2],'message':'OnionWire '+sys.argv[1]}, sys.stdout)" \
"$tag" "$sha" > /tmp/tag-create.json
echo "tag-create payload $(wc -c < /tmp/tag-create.json) bytes"
create_code=$(api_curl -o /tmp/tag-created.json -w '%{http_code}' \
-X POST -H "Content-Type: application/json" \
--data-binary @/tmp/tag-create.json \
"$REPO_API/tags")
if [ "$create_code" = "201" ]; then
created=true
echo "created tag $tag on $sha"
elif [ "$create_code" = "409" ]; then
echo "tag $tag created concurrently — joining"
else
echo "creating tag $tag failed HTTP $create_code" >&2
cat /tmp/tag-created.json >&2 || true
exit 1
fi
else
echo "GET tags/$tag failed HTTP $code" >&2
cat /tmp/tag.json >&2 || true
exit 1
fi
fi
fi
echo "tag=$tag" >> "$GITHUB_OUTPUT"
echo "sha=$sha" >> "$GITHUB_OUTPUT"
echo "dry_run=$dry_run" >> "$GITHUB_OUTPUT"
echo "created_tag=$created" >> "$GITHUB_OUTPUT"
echo "plan: tag=$tag sha=$sha dry_run=$dry_run created_tag=$created"
aarch64:
needs: version
runs-on: docker
timeout-minutes: 120
env:
TARGET: aarch64-unknown-linux-gnu
# Per-run, and removed at the end of the job: a reused target dir lets the
# published binary come out of cached artifacts, which is precisely what a
# verifier rebuilding from an empty directory cannot reproduce.
CARGO_TARGET_VOLUME: onionwire-target-release-${{ github.run_id }}-aarch64
BUILD_CONTAINER: onionwire-release-${{ github.run_id }}-aarch64
steps:
- name: Checkout source
uses: https://code.forgejo.org/actions/checkout@v4
with:
ref: ${{ needs.version.outputs.sha }}
- name: Show runner arch
run: uname -m && echo "target=$TARGET"
- name: Resolve SOURCE_DATE_EPOCH from the released commit
id: epoch
run: | run: |
set -euo pipefail set -euo pipefail
cd "${GITHUB_WORKSPACE}" cd "${GITHUB_WORKSPACE}"
echo "pwd=$PWD workspace=$GITHUB_WORKSPACE" # The released commit's committer time, not "now". A rebuild of this
ls -l dist/ 2>&1 || true # tag in six months has to hand the compiler the same epoch CI handed
for f in dist/*; do printf 'on disk: %s %s bytes\n' "$f" "$(wc -c < "$f")"; done # it, or the two builds cannot match and every verification is noise.
tag="${INPUT_TAG:-$REF}" epoch=$(git log -1 --format=%ct "${{ needs.version.outputs.sha }}")
# Only a tag push may create the tag; a re-publish must not move it. case "$epoch" in
if [ "$EVENT_NAME" = "push" ]; then export TARGET_COMMITISH="$EVENT_SHA"; fi ''|*[!0-9]*) echo "could not read a commit time for ${{ needs.version.outputs.sha }}" >&2; exit 1 ;;
echo "publishing $tag from $REPO_API (event=$EVENT_NAME)" esac
echo "epoch=$epoch" >> "$GITHUB_OUTPUT"
echo "SOURCE_DATE_EPOCH=$epoch"
- name: Build ${{ env.TARGET }} in the pinned rust container
env:
SOURCE_DATE_EPOCH: ${{ steps.epoch.outputs.epoch }}
RELEASE_SHA: ${{ needs.version.outputs.sha }}
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
echo "workspace: $GITHUB_WORKSPACE"
docker volume create "$CARGO_REGISTRY_VOLUME" > /dev/null
# Fresh per run (see the job env): the published artifact has to be
# reproducible from an empty target dir, so it is not allowed to come
# out of a cache that a verifier does not have.
docker volume create "$CARGO_TARGET_VOLUME" > /dev/null
docker rm -f "$BUILD_CONTAINER" > /dev/null 2>&1 || true
docker create --name "$BUILD_CONTAINER" -i \
-e CARGO_TARGET_DIR=/target \
-e CARGO_BUILD_JOBS=2 \
-e CARGO_TERM_COLOR=never \
-e SOURCE_DATE_EPOCH="$SOURCE_DATE_EPOCH" \
-e BUILDER_IMAGE="$RUST_IMAGE" \
-e TARGET_TRIPLE="$TARGET" \
-e GIT_SHA="$RELEASE_SHA" \
-e OUT=/out \
-v "$CARGO_REGISTRY_VOLUME":/usr/local/cargo/registry \
-v "$CARGO_TARGET_VOLUME":/target \
-w /src \
"$RUST_IMAGE" \
sh -euxc 'mkdir -p /src /out && tar xzf - -C /src && cd /src && bash /src/scripts/reproducible-build.sh'
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees \
--exclude=./.ci-tools . \
| docker start -a -i "$BUILD_CONTAINER"
mkdir -p dist
# The recipe writes the stripped binary, its .sha256 and the build-info
# record into /out, and installs its own apt build deps — the caller
# supplies only the source tree and the pinned epoch.
docker cp "$BUILD_CONTAINER:/out/." dist/
docker rm -f "$BUILD_CONTAINER" > /dev/null
docker volume rm "$CARGO_TARGET_VOLUME" > /dev/null
- name: Verify the recipe's dist output
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}/dist"
ls -l
# scripts/reproducible-build.sh owns the checksum and the build-info
# record. This step only refuses to hand a half-made dist to publish.
for f in "onionwire-$TARGET" "onionwire-$TARGET.sha256" "build-info-$TARGET.txt"; do
if [ ! -s "$f" ]; then
echo "missing or empty dist asset: $f" >&2
exit 1
fi
done
sha256sum -c "onionwire-$TARGET.sha256"
file "onionwire-$TARGET"
cat "build-info-$TARGET.txt"
- name: Upload dist artifact
uses: https://code.forgejo.org/actions/upload-artifact@v3
with:
name: onionwire-aarch64-unknown-linux-gnu
path: dist/
if-no-files-found: error
retention-days: 1
x86_64:
needs: version
runs-on: docker-amd64
timeout-minutes: 120
env:
TARGET: x86_64-unknown-linux-gnu
# Per-run, and removed at the end of the job: a reused target dir lets the
# published binary come out of cached artifacts, which is precisely what a
# verifier rebuilding from an empty directory cannot reproduce.
CARGO_TARGET_VOLUME: onionwire-target-release-${{ github.run_id }}-x86_64
BUILD_CONTAINER: onionwire-release-${{ github.run_id }}-x86_64
steps:
- name: Checkout source
uses: https://code.forgejo.org/actions/checkout@v4
with:
ref: ${{ needs.version.outputs.sha }}
- name: Show runner arch
run: uname -m && echo "target=$TARGET"
- name: Ensure docker CLI (amd64 dind job image has none)
run: |
set -euo pipefail
if ! command -v docker >/dev/null 2>&1; then
curl -fsSL https://download.docker.com/linux/static/stable/x86_64/docker-27.3.1.tgz \
| tar xz -C /tmp
install -m 755 /tmp/docker/docker /usr/local/bin/docker
fi
docker version
if [ ! -S /var/run/docker.sock ]; then
echo "docker.sock is not mounted into the job container" >&2
ls -l /var/run || true
exit 1
fi
- name: Resolve SOURCE_DATE_EPOCH from the released commit
id: epoch
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
# The released commit's committer time, not "now". A rebuild of this
# tag in six months has to hand the compiler the same epoch CI handed
# it, or the two builds cannot match and every verification is noise.
epoch=$(git log -1 --format=%ct "${{ needs.version.outputs.sha }}")
case "$epoch" in
''|*[!0-9]*) echo "could not read a commit time for ${{ needs.version.outputs.sha }}" >&2; exit 1 ;;
esac
echo "epoch=$epoch" >> "$GITHUB_OUTPUT"
echo "SOURCE_DATE_EPOCH=$epoch"
- name: Build ${{ env.TARGET }} in the pinned rust container
env:
SOURCE_DATE_EPOCH: ${{ steps.epoch.outputs.epoch }}
RELEASE_SHA: ${{ needs.version.outputs.sha }}
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
echo "workspace: $GITHUB_WORKSPACE"
docker volume create "$CARGO_REGISTRY_VOLUME" > /dev/null
# Fresh per run (see the job env): the published artifact has to be
# reproducible from an empty target dir, so it is not allowed to come
# out of a cache that a verifier does not have.
docker volume create "$CARGO_TARGET_VOLUME" > /dev/null
docker rm -f "$BUILD_CONTAINER" > /dev/null 2>&1 || true
docker create --name "$BUILD_CONTAINER" -i \
-e CARGO_TARGET_DIR=/target \
-e CARGO_BUILD_JOBS=2 \
-e CARGO_TERM_COLOR=never \
-e SOURCE_DATE_EPOCH="$SOURCE_DATE_EPOCH" \
-e BUILDER_IMAGE="$RUST_IMAGE" \
-e TARGET_TRIPLE="$TARGET" \
-e GIT_SHA="$RELEASE_SHA" \
-e OUT=/out \
-v "$CARGO_REGISTRY_VOLUME":/usr/local/cargo/registry \
-v "$CARGO_TARGET_VOLUME":/target \
-w /src \
"$RUST_IMAGE" \
sh -euxc 'mkdir -p /src /out && tar xzf - -C /src && cd /src && bash /src/scripts/reproducible-build.sh'
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees \
--exclude=./.ci-tools . \
| docker start -a -i "$BUILD_CONTAINER"
mkdir -p dist
# The recipe writes the stripped binary, its .sha256 and the build-info
# record into /out, and installs its own apt build deps — the caller
# supplies only the source tree and the pinned epoch.
docker cp "$BUILD_CONTAINER:/out/." dist/
docker rm -f "$BUILD_CONTAINER" > /dev/null
docker volume rm "$CARGO_TARGET_VOLUME" > /dev/null
- name: Verify the recipe's dist output
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}/dist"
ls -l
# scripts/reproducible-build.sh owns the checksum and the build-info
# record. This step only refuses to hand a half-made dist to publish.
for f in "onionwire-$TARGET" "onionwire-$TARGET.sha256" "build-info-$TARGET.txt"; do
if [ ! -s "$f" ]; then
echo "missing or empty dist asset: $f" >&2
exit 1
fi
done
sha256sum -c "onionwire-$TARGET.sha256"
file "onionwire-$TARGET"
cat "build-info-$TARGET.txt"
- name: Upload dist artifact
uses: https://code.forgejo.org/actions/upload-artifact@v3
with:
name: onionwire-x86_64-unknown-linux-gnu
path: dist/
if-no-files-found: error
retention-days: 1
publish:
needs: [version, aarch64, x86_64]
# Always run after version so a failed build still hits the fail-closed
# delete step (a skipped publish left act without a job result).
# Pi runner, not docker-amd64: the amd64 dind runner is capacity=1 and
# android-release sat in front of run 116's publish for ~1h; the Pi
# already created the tag over the public API (version job), so publish
# uses that same path. This job needs the docker CLI for one thing only —
# running scripts/sign-release.sh in the pinned builder image — and it uses
# a named volume + docker cp, never a bind mount of $GITHUB_WORKSPACE
# (that path exists only inside this container; docker resolves a -v source
# on the host and hands the container an empty /work — run 768).
# Fail-closed tag delete lives as a step here: a sibling cleanup job ran
# after a successful publish (act treats needs.publish.result as unset, so
# != success) and Early-terminated on run 135. Do not restore that job.
if: always() && needs.version.result == 'success'
runs-on: docker
timeout-minutes: 20
steps:
- name: Skip publish on dry_run
if: needs.version.outputs.dry_run == 'true'
run: echo "dry_run not publishing"
- name: Fail closed if a build failed
if: needs.version.outputs.dry_run != 'true' && (needs.aarch64.result != 'success' || needs.x86_64.result != 'success')
run: |
echo "aarch64=${{ needs.aarch64.result }} x86_64=${{ needs.x86_64.result }}" >&2
exit 1
- name: Checkout CI tooling
if: needs.version.outputs.dry_run != 'true' && needs.aarch64.result == 'success' && needs.x86_64.result == 'success'
uses: https://code.forgejo.org/actions/checkout@v4
with:
path: .ci-tools
- name: Download both arch artifacts
if: needs.version.outputs.dry_run != 'true' && needs.aarch64.result == 'success' && needs.x86_64.result == 'success'
uses: https://code.forgejo.org/actions/download-artifact@v3
with:
path: artifacts
- name: Stage both arch artifacts into dist
if: needs.version.outputs.dry_run != 'true' && needs.aarch64.result == 'success' && needs.x86_64.result == 'success'
run: |
set -euo pipefail
# Everything the signer signs must already be in dist/ when the sign
# step runs. This loop used to live inside the publish step, i.e.
# AFTER the signature step, so signing ran against an empty dist/.
mkdir -p dist
find artifacts -type f -print
for target in aarch64-unknown-linux-gnu x86_64-unknown-linux-gnu; do
for name in "onionwire-$target" "onionwire-$target.sha256" "build-info-$target.txt"; do
src=$(find artifacts -type f -name "$name" -print -quit)
if [ -z "$src" ]; then
echo "missing artifact: $name" >&2
find artifacts -type f >&2 || true
exit 1
fi
cp "$src" "dist/$name"
done
done
ls -l dist
- name: Sign the release assets (minisign, fail closed)
if: needs.version.outputs.dry_run != 'true' && needs.aarch64.result == 'success' && needs.x86_64.result == 'success'
env:
MINISIGN_SECRET_KEY: ${{ secrets.MINISIGN_SECRET_KEY }}
RELEASE_TAG: ${{ needs.version.outputs.tag }}
SIGN_VOLUME: onionwire-sign-${{ github.run_id }}
SIGN_CONTAINER: onionwire-sign-${{ github.run_id }}
run: |
set -euo pipefail
# Signing runs BEFORE publish on purpose. A run without the key stops
# here, so nothing unsigned ever reaches the release page: an unsigned
# release is indistinguishable from a signed one to anyone who is not
# checking, which makes it worse than no release at all.
if [ -z "${MINISIGN_SECRET_KEY:-}" ]; then
echo "MINISIGN_SECRET_KEY is not set — add it in Settings -> Actions -> Secrets." >&2
echo "See docs/VERIFY.md, \"Maintainer: the signing key\"." >&2
exit 1
fi
# NO `-v "${GITHUB_WORKSPACE}:/work"`: GITHUB_WORKSPACE is a path
# INSIDE this job container, but docker resolves a bind mount's source
# on the HOST, where it does not exist. Docker then creates an empty
# /work and the sign script is simply absent (run 768: "bash:
# .ci-tools/scripts/sign-release.sh: No such file or directory").
# Same pattern as the build jobs: named volume + docker cp in/out.
# minisign still comes from the same pinned image the builds used, so
# our signature and the verifier's check are the same implementation.
cleanup() {
docker rm -f "$SIGN_CONTAINER" >/dev/null 2>&1 || true
docker volume rm "$SIGN_VOLUME" >/dev/null 2>&1 || true
}
trap cleanup EXIT
docker volume create "$SIGN_VOLUME" >/dev/null
docker rm -f "$SIGN_CONTAINER" >/dev/null 2>&1 || true
docker create --name "$SIGN_CONTAINER" \
-e MINISIGN_SECRET_KEY \
-e RELEASE_TAG \
-v "$SIGN_VOLUME:/work" \
-w /work \
"$RUST_IMAGE" \
bash -c 'apt-get update -qq && apt-get install -y -qq --no-install-recommends minisign >/dev/null \
&& bash /work/scripts/sign-release.sh \
/work/dist/onionwire-aarch64-unknown-linux-gnu \
/work/dist/onionwire-aarch64-unknown-linux-gnu.sha256 \
/work/dist/onionwire-x86_64-unknown-linux-gnu \
/work/dist/onionwire-x86_64-unknown-linux-gnu.sha256'
docker cp .ci-tools/scripts "$SIGN_CONTAINER:/work/scripts"
docker cp dist/. "$SIGN_CONTAINER:/work/dist/"
docker start -a "$SIGN_CONTAINER"
docker cp "$SIGN_CONTAINER:/work/dist/." dist/
# Verify the signatures came back out before anything is published.
for f in \
dist/onionwire-aarch64-unknown-linux-gnu.minisig \
dist/onionwire-aarch64-unknown-linux-gnu.sha256.minisig \
dist/onionwire-x86_64-unknown-linux-gnu.minisig \
dist/onionwire-x86_64-unknown-linux-gnu.sha256.minisig
do
[ -s "$f" ] || { echo "signing produced no $f" >&2; exit 1; }
done
# The public key ships as an asset too, so a verifier can get it from
# the release; getting it from the repo instead is stronger, and
# docs/VERIFY.md says so.
cp .ci-tools/scripts/onionwire-signing.pub dist/onionwire-signing.pub
- name: Publish both binaries to one release
if: needs.version.outputs.dry_run != 'true' && needs.aarch64.result == 'success' && needs.x86_64.result == 'success'
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
TAG: ${{ needs.version.outputs.tag }}
run: |
set -euo pipefail
# dist/ is staged and signed by the two steps above; this step only
# refuses to upload a hole in it.
find dist -type f -print
missing=0
for f in \
dist/onionwire-aarch64-unknown-linux-gnu \
dist/onionwire-aarch64-unknown-linux-gnu.sha256 \
dist/onionwire-aarch64-unknown-linux-gnu.minisig \
dist/onionwire-aarch64-unknown-linux-gnu.sha256.minisig \
dist/build-info-aarch64-unknown-linux-gnu.txt \
dist/onionwire-x86_64-unknown-linux-gnu \
dist/onionwire-x86_64-unknown-linux-gnu.sha256 \
dist/onionwire-x86_64-unknown-linux-gnu.minisig \
dist/onionwire-x86_64-unknown-linux-gnu.sha256.minisig \
dist/build-info-x86_64-unknown-linux-gnu.txt \
dist/onionwire-signing.pub
do
if [ ! -s "$f" ]; then
echo "refusing to publish missing or empty asset $f" >&2
missing=1
continue
fi
bytes=$(wc -c < "$f")
echo "on disk: $f $bytes bytes"
file "$f" || true
done
if [ "$missing" -ne 0 ]; then
exit 1
fi
echo "publishing $TAG from $REPO_API"
.ci-tools/scripts/publish-release.sh \ .ci-tools/scripts/publish-release.sh \
"$tag" "OnionWire $tag" \ "$TAG" "OnionWire $TAG" \
.ci-tools/scripts/release-body.md \ .ci-tools/scripts/release-body.md \
"dist/onionwire-$TARGET" "dist/onionwire-$TARGET.sha256" dist/onionwire-aarch64-unknown-linux-gnu \
dist/onionwire-aarch64-unknown-linux-gnu.sha256 \
dist/onionwire-aarch64-unknown-linux-gnu.minisig \
dist/onionwire-aarch64-unknown-linux-gnu.sha256.minisig \
dist/build-info-aarch64-unknown-linux-gnu.txt \
dist/onionwire-x86_64-unknown-linux-gnu \
dist/onionwire-x86_64-unknown-linux-gnu.sha256 \
dist/onionwire-x86_64-unknown-linux-gnu.minisig \
dist/onionwire-x86_64-unknown-linux-gnu.sha256.minisig \
dist/build-info-x86_64-unknown-linux-gnu.txt \
dist/onionwire-signing.pub
- name: Delete tag we created if this job failed
if: failure() && needs.version.outputs.created_tag == 'true' && needs.version.outputs.dry_run != 'true'
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
TAG: ${{ needs.version.outputs.tag }}
run: |
set -euo pipefail
FORGEJO_TOKEN=$(printf '%s' "$FORGEJO_TOKEN" | tr -d '\r\n')
echo "fail-closed: removing tag $TAG created by this run"
code=$(curl -sS --http1.1 -o /tmp/rel.json -w '%{http_code}' \
-u "sirius:${FORGEJO_TOKEN}" \
"$REPO_API/releases/tags/$TAG")
if [ "$code" = "200" ]; then
rid=$(python3 -c "import json; print(json.load(open('/tmp/rel.json'))['id'])")
echo "deleting incomplete release id $rid"
curl -sS --http1.1 -X DELETE \
-u "sirius:${FORGEJO_TOKEN}" \
"$REPO_API/releases/$rid" -o /dev/null -w "DELETE release HTTP %{http_code}\n"
else
echo "no release for $TAG (HTTP $code)"
fi
del=$(curl -sS --http1.1 -o /tmp/tag-del.json -w '%{http_code}' -X DELETE \
-u "sirius:${FORGEJO_TOKEN}" \
"$REPO_API/tags/$TAG")
echo "DELETE tag HTTP $del"
if [ "$del" != "204" ] && [ "$del" != "404" ]; then
cat /tmp/tag-del.json >&2 || true
exit 1
fi

1
.gitignore vendored
View file

@ -6,6 +6,7 @@
# whatever the developer has installed — never commit them. # whatever the developer has installed — never commit them.
/.android-env.sh /.android-env.sh
android/local.properties android/local.properties
android/.cargo/
# Gradle / Android build output # Gradle / Android build output
android/.gradle/ android/.gradle/

2409
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -2,51 +2,90 @@
name = "onionwire" name = "onionwire"
version = "0.2.1" version = "0.2.1"
edition = "2024" edition = "2024"
rust-version = "1.91" # 1.98, not 1.92. Arti 0.49 builds on 1.92, but the default feature set includes
# `cuprate-daemon`, and `tapes` (a Cuprate dep this repo cannot patch) calls
# `VecDeque::pop_front_if`, stable only from 1.93. 1.98 is the release CI and
# the Android workflows actually build that graph with. `--no-default-features`
# does not need it; `cargo` checks `rust-version` before features, so the
# declared floor is the default build's floor.
rust-version = "1.98"
description = "Lean Tor messenger: Arti in-process, identity=pubkey, onion=locator. No XMPP." description = "Lean Tor messenger: Arti in-process, identity=pubkey, onion=locator. No XMPP."
license = "MIT" license = "MIT"
publish = false publish = false
repository = "https://github.com/sirius0xdev/onionwire" repository = "https://forgejo.siriusdevops.com/sirius/onionwire"
# The Linux TUI build is unchanged: `default` keeps Arti's native-tls # TLS backend: `rustls` by default, `native-tls` (OpenSSL) opt-in.
# (OpenSSL) backend exactly as before, and ratatui remains a normal
# dependency so `src/tui.rs` is untouched.
# #
# Android has no OpenSSL in the NDK, so the SDK crate depends on this crate # Arti marks these two backends non-additive, so exactly one may be selected per
# with `default-features = false, features = ["rustls"]`. Arti marks these two # build graph — hence exposing them as crate features. rustls is the default
# backends non-additive, so exactly one may be selected per build graph — hence # because Android has no OpenSSL in the NDK and the Linux TUI/release build does
# exposing them as crate features. # not need a system OpenSSL for TLS either. (OpenSSL is still *compiled* into
# every build by rusqlite's `bundled-sqlcipher-vendored-openssl`, vendored and
# static: that is the SQLCipher layer, not Arti's TLS.)
[features] [features]
default = ["native-tls"] default = ["rustls", "cuprate-daemon"]
native-tls = ["arti-client/native-tls"] native-tls = ["arti-client/native-tls"]
rustls = ["arti-client/rustls"] rustls = ["arti-client/rustls"]
# In-process Monero chain daemon (Cuprate) as the local chain source, instead of
# spawning `monerod`. ON in the Linux TUI/release binary (this default). A build
# with `--no-default-features` does not include it. `cuprated` is pre-1.0 and is
# not published to crates.io (every Cuprate crate there is a `0.0.0-placeholder`
# name reservation), so this pins a git revision and pulls a large tree (RandomX,
# fjall, axum/hyper, rayon). See `docs/WALLET.md`, "The in-process chain daemon".
#
# Cuprate's own `arti` feature stays OFF (and is off in its default feature set,
# which is why `default-features = false` is load-bearing): it would link a
# second, older Tor stack (arti-client 0.44, which cannot unify with this
# crate's 0.49) next to OnionWire's. The in-process daemon runs clearnet-only;
# OnionWire's Arti is the only Tor in the process.
cuprate-daemon = ["dep:cuprated", "dep:toml"]
[dependencies] [dependencies]
arti-client = { version = "0.46", default-features = false, features = [ arti-client = { version = "0.49", default-features = false, features = [
"tokio", "tokio",
"onion-service-client", "onion-service-client",
"onion-service-service", "onion-service-service",
"compression", "compression",
] } ] }
futures = "0.3" futures = "0.3"
safelog = "0.9" safelog = "0.10"
ed25519-dalek = { version = "2", features = ["rand_core"] } ed25519-dalek = { version = "2", features = ["rand_core"] }
rand = "0.8" rand = "0.8"
rusqlite = { version = "0.36", features = ["bundled"] } rusqlite = { version = "0.36", features = ["bundled-sqlcipher-vendored-openssl"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "time", "net"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "time", "net"] }
tor-cell = "0.46" tor-cell = "0.49"
tor-hsservice = "0.46" tor-hsservice = "0.49"
tor-rtcompat = { version = "0.46", features = ["tokio"] } tor-rtcompat = { version = "0.49", features = ["tokio"] }
# Direct dependency only to select rustls's crypto provider: Arti pulls rustls in
# through `tor-rtcompat` with `default-features = false`, and rustls 0.23
# resolves its provider from its OWN `ring`/`aws-lc-rs` features, so without this
# line the rustls backend compiles with no provider at all and the first TLS
# config fails. Same reasoning (and pin) as `crates/onionwire-sdk/Cargo.toml`.
rustls = { version = "0.23", default-features = false, features = ["ring"] }
ratatui = { version = "0.30.2", default-features = false, features = ["crossterm"] } ratatui = { version = "0.30.2", default-features = false, features = ["crossterm"] }
x25519-dalek = { version = "2", features = ["static_secrets"] } x25519-dalek = { version = "2", features = ["static_secrets"] }
snow = "0.10" snow = "0.10"
serde_json = "1" serde_json = "1"
hkdf = "0.12"
hmac = "0.12"
argon2 = "0.5" argon2 = "0.5"
chacha20poly1305 = "0.10" chacha20poly1305 = "0.10"
sha3 = "0.10" sha3 = "0.10"
sha2 = "0.10" sha2 = "0.10"
md-5 = "0.10" md-5 = "0.10"
rpassword = "7" rpassword = "7"
zeroize = { version = "1", features = ["derive"] }
# ML-KEM-768 (FIPS 203). `zeroize` wipes the decapsulation key; `getrandom`
# is how 0.3's `generate_keypair` / `encapsulate` reach the OS RNG. This
# crate's `rand` 0.8 cannot: ml-kem speaks `rand_core` 0.10.
ml-kem = { version = "0.3", features = ["zeroize", "getrandom"] }
qrcode = { version = "0.14", default-features = false }
cuprated = { git = "https://github.com/Cuprate/cuprate", rev = "4f8fcd1bf468f566fcd89c460d50de4adb6825bf", default-features = false, optional = true }
# `cuprated::config::Config` is deserialized, not built field by field: the
# struct's nested types move with the pinned revision, a TOML document does not.
# Cuprate has `deny_unknown_fields` on every config struct, so a stale key is a
# parse error instead of a silently ignored setting.
toml = { version = "0.8", features = ["parse", "display"], optional = true }
[dev-dependencies] [dev-dependencies]
tempfile = "3" tempfile = "3"

446
README.md
View file

@ -1,72 +1,116 @@
# OnionWire # OnionWire
Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti). Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti).
No hosted server. Identity is a public key; the onion is only a locator. No hosted server. Identity is an ed25519 public key; the onion is only a locator.
**v0.2** — Linux TUI. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion. Optional Monero invoices if you point at a local `monero-wallet-rpc`. Fail closed: peer down → send fails. Arti onion services are still experimental. Chat bodies are encrypted at rest; identity keys in sqlite are still plaintext. Current tagged release: **v0.7.0**. Linux TUI + Android SDK/APK. Two people add
each other with an `onionwire:v2:…` invite string (`F2` share / `F3` paste;
~1.9 KB because it carries an ML-KEM-768 key). There is no invite QR graphic.
Chat is Noise IK over your own v3 onion; when the friend was added from a v2
invite the session is **hybrid** (ML-KEM-768 prelude mixed into the Noise
prologue). A friend from a legacy `onionwire:v1` invite stays classical and the
roster labels them `classical`. Every chat message is ratcheted inside that
session. Unreachable chat peers go to a **local
outbox** (device-only retry queue — no relay). File transfer and payment frames
fail closed. Optional Monero: `/pay` invoices, `/tip` payments, and in-app wallet
create/import (`F6`). Arti onion services are still experimental. The store is
SQLCipher; chat bodies add a row-bound AEAD layer.
You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds Arti and publishes its own v3 onion. You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds
Arti and publishes its own v3 onion. There is no C-tor fallback.
**Docs** (protocol first, then claims): [PROTOCOL.md](docs/PROTOCOL.md) ·
[threat model](docs/THREAT_MODEL.md) · [audit notes](docs/SECURITY_AUDIT.md)
(in-house, **not** a third-party audit). Index: [docs/README.md](docs/README.md).
TUI keys: [docs/TUI.md](docs/TUI.md). Wallet: [docs/WALLET.md](docs/WALLET.md).
Releases: [docs/RELEASING.md](docs/RELEASING.md). Verifying a download:
[docs/VERIFY.md](docs/VERIFY.md).
## Install ## Install
Pick one: a CI-built binary (fastest), or build from source. Pick one: a CI-built binary, or build from source.
### Requirements ### Requirements
| Need | Notes | | Need | Notes |
|---|---| |---|---|
| Linux | x86_64 or aarch64. TUI needs a real terminal (not a pipe). | | Linux | x86_64 or aarch64. TUI needs a real terminal (not a pipe). |
| Network | First run bootstraps Tor via Arti. Offline start will fail closed. | | Network | First run bootstraps Tor via Arti. Offline start fails closed. |
| Not needed | `tor` package, `torrc`, Prosody, an XMPP account, a DHT. | | Not needed | `tor` package, `torrc`, Prosody, an XMPP account, a DHT. |
Arti onion services are still **experimental**. If the hidden service cannot come up, OnionWire exits — it does not fall back to C-tor. Arti onion services are still **experimental**. If the hidden service cannot come
up, OnionWire exits.
### Option A — download a release binary ### Option A — download a release binary
CI (`.forgejo/workflows/release.yml`, Forgejo Actions on the Pi runner) builds the **aarch64** binary on every `v*.*.*` tag and attaches it to the [Forgejo release](https://forgejo.siriusdevops.com/sirius/onionwire/releases). There is no x86_64 runner on this instance, so the **x86_64** asset is built and uploaded by `scripts/build-release-local.sh` on an x86_64 host — both land on the same release page. CI does **not** release on a merge. Releases are manual and batched: a maintainer
dispatches `.forgejo/workflows/release.yml` at a stopping point (`dry_run=true`
first), which tags the next `v*.*.*` version and publishes both Linux binaries to
one [Forgejo release](https://forgejo.siriusdevops.com/sirius/onionwire/releases).
The Android APK + AAR attach to **the same tag** by a second dispatch of
`android-release` with `tag=<that tag>`. Policy: [docs/RELEASING.md](docs/RELEASING.md).
This Forgejo does not serve `/releases/latest/download/…` (404); pin the tag.
**x86_64 (most PCs / VMs):** Every asset is signed with minisign, and every binary is reproducible from its
tag: pin the builder image by digest, fix the build paths and `SOURCE_DATE_EPOCH`,
and the published hash can be rebuilt and compared by anyone. Before running a
download, read [docs/VERIFY.md](docs/VERIFY.md). Each release carries
`build-info-<target>.txt` (commit, epoch, toolchain, builder image digest,
resulting hash) next to its `.sha256`.
**x86_64:**
```bash ```bash
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/latest/download/onionwire-x86_64-unknown-linux-gnu curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.7.0/onionwire-x86_64-unknown-linux-gnu
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/latest/download/onionwire-x86_64-unknown-linux-gnu.sha256 curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.7.0/onionwire-x86_64-unknown-linux-gnu.sha256
sha256sum -c onionwire-x86_64-unknown-linux-gnu.sha256 sha256sum -c onionwire-x86_64-unknown-linux-gnu.sha256
chmod +x onionwire-x86_64-unknown-linux-gnu chmod +x onionwire-x86_64-unknown-linux-gnu
./onionwire-x86_64-unknown-linux-gnu --version ./onionwire-x86_64-unknown-linux-gnu --version
``` ```
**aarch64 (Raspberry Pi, ARM servers):** **aarch64:**
```bash ```bash
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/latest/download/onionwire-aarch64-unknown-linux-gnu curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.7.0/onionwire-aarch64-unknown-linux-gnu
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/latest/download/onionwire-aarch64-unknown-linux-gnu.sha256 curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.7.0/onionwire-aarch64-unknown-linux-gnu.sha256
sha256sum -c onionwire-aarch64-unknown-linux-gnu.sha256 sha256sum -c onionwire-aarch64-unknown-linux-gnu.sha256
chmod +x onionwire-aarch64-unknown-linux-gnu chmod +x onionwire-aarch64-unknown-linux-gnu
./onionwire-aarch64-unknown-linux-gnu --version ./onionwire-aarch64-unknown-linux-gnu --version
``` ```
Install onto `PATH` if you want `onionwire` as a command (keep the asset filename until after `sha256sum -c`): Install onto `PATH` (keep the asset filename until after `sha256sum -c`):
```bash ```bash
mkdir -p ~/.local/bin mkdir -p ~/.local/bin
install -m 755 onionwire-x86_64-unknown-linux-gnu ~/.local/bin/onionwire install -m 755 onionwire-x86_64-unknown-linux-gnu ~/.local/bin/onionwire
# ensure ~/.local/bin is on PATH, then:
onionwire onionwire
``` ```
The binary is dynamically linked against glibc (Ubuntu 24.04 builders). If `./onionwire` dies with `GLIBC_… not found`, use Option B on that machine. The app-owned wallet child looks for an executable named `monero-wallet-rpc` in
the same directory as the OnionWire binary, then on `PATH`. A remote daemon and
a remote wallet RPC stay available on F7. An absolute path configured for the
wallet-rpc binary is used as given. To place the official binary beside
`onionwire`:
Checksum files are `sha256sum` format (`<hash> onionwire-<target>`). Download both files with `curl -O` so the names match, then `sha256sum -c`. ```bash
scripts/fetch-monero-wallet-rpc.sh ~/.local/bin
```
The binary is dynamically linked against glibc (Ubuntu 24.04 builders). If it
dies with `GLIBC_… not found`, use Option B. Checksum files are `sha256sum`
format (`<hash> onionwire-<target>`).
### Option B — build from source ### Option B — build from source
Needs [Rust](https://rustup.rs/) **1.91+** (`edition = "2024"`; the pinned Arti 0.46 crates require rustc 1.91). A distro `rustc` is fine if `rustc --version` reports 1.91 or newer. Do not install `tor` for this app. Needs [Rust](https://rustup.rs/) **1.98+** (`edition = "2024"`; `Cargo.toml`
`rust-version = "1.98"`). Arti 0.49 itself builds on 1.92, but the default
feature set includes the in-process chain daemon, and that graph does not
(`tapes` calls `VecDeque::pop_front_if`, stable since 1.93). Do not install `tor`.
```bash ```bash
# rustup (if you do not already have cargo)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env" source "$HOME/.cargo/env"
rustc --version # must be 1.91 or newer rustc --version # must be 1.98 or newer
``` ```
```bash ```bash
@ -79,140 +123,292 @@ cargo build --release --locked
./target/release/onionwire ./target/release/onionwire
``` ```
Install the binary:
```bash ```bash
cargo install --path . --locked --force cargo install --path . --locked --force
# lands in ~/.cargo/bin/onionwire # lands in ~/.cargo/bin/onionwire
``` ```
Build needs `pkg-config` and OpenSSL 3 headers (`libssl-dev` / `openssl-devel`) — Build needs a C toolchain plus `perl` and `make`: SQLCipher is compiled from
the released binaries link `libssl.so.3` dynamically. vendored OpenSSL (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). No
system OpenSSL headers or `pkg-config` are required — Arti's TLS backend is
`rustls`.
The crate version in `Cargo.toml` is **not** bumped by the release workflow. The
tag (`v0.7.0`) is the version users download; `onionwire --version` prints
`CARGO_PKG_VERSION` from the tree that was built.
### Two instances on one machine ### Two instances on one machine
Each process needs its own data dir (identity + onion + sqlite): Each process needs its own data dir:
```bash ```bash
ONIONWIRE_HOME=/tmp/ow-a ./onionwire ONIONWIRE_HOME=/tmp/ow-a ./onionwire
ONIONWIRE_HOME=/tmp/ow-b ./onionwire ONIONWIRE_HOME=/tmp/ow-b ./onionwire
``` ```
Then `F2` on A (invite string), `F3`-paste on B (and the other way around). No QR. Then `F2` on A, `F3`-paste on B (and the other way). No invite QR.
## First run ## Run
``` There are **no subcommands**. Flags are `--version` / `-V` and `--help` / `-h`
only (`src/main.rs`). Anything else exits 2 with `onionwire: unknown argument`.
```bash
onionwire onionwire
``` ```
or `cargo run --release`. or `cargo run --release`.
On start you are prompted for a store passphrase (echo off, like other CLI passwords) or set `ONIONWIRE_STORE_PASSPHRASE`. Empty passphrase is rejected; a wrong passphrase does not open chat. Then you should see `onionwire: bootstrapping Arti…` on stderr. Directory bootstrap is usually under a minute; the onion is ready once a probe connect works (combined Arti status may still say Bootstrapping). Fail closed at 360s. Data lives in `ONIONWIRE_HOME` if set, otherwise `~/.local/share/onionwire/` (`onionwire.db` + Arti state, mode 0700). First open creates an ed25519 identity key. That key **is** you. On start you are prompted for a store passphrase (echo off) or set
`ONIONWIRE_STORE_PASSPHRASE`. Empty passphrase is rejected; a wrong passphrase
does not open chat. Then `onionwire: bootstrapping Arti…` on stderr. Directory
bootstrap is usually under a minute; the onion is ready once a probe connect
works (combined Arti status may still say Bootstrapping). Fail closed at 360s
(`PUBLISH_WAIT` in `src/hs.rs`). Data lives in `ONIONWIRE_HOME` if set, otherwise
`~/.local/share/onionwire/` (`onionwire.db` + Arti state, mode 0700). First open
creates an ed25519 identity key. That key **is** you.
Then `F2` to share your invite, `F3` to paste a friend’s. Mouse-select the `onionwire:v1:…` line to copy. Highlight them in the roster, type in the composer, Enter to send. Fail closed: if their onion is down, send fails — no outbox. Then `F2` to share your invite, `F3` to paste a friend's. Mouse-select the
`onionwire:v1:…` line to copy. Highlight them in the roster, type in the
composer, Enter to send. Chat rows show delivery state from the local outbox
(`✓` delivered, `◷ queued (try n/8, retry …)`, `» sending`, `✗ failed: …`); the
footer shows `{n} queued` while anything is outstanding. If their onion is down
the message stays on this device and the retry worker re-dials with backoff —
nothing is handed to a third party. File transfer and payments are still one-shot
(both sides online).
## Friends are keys ## Friends are keys
A friend is an ed25519 pubkey (`UNIQUE(pubkey)`). The `.onion` on that row is only where they are reachable right now. Pasting the same `k` updates the locator; it never creates a second person. A friend is an ed25519 pubkey (`UNIQUE(pubkey)`). The `.onion` on that row is
only where they are reachable right now. Pasting the same `k` updates the
locator; it never creates a second person.
## Commands and flags
```
onionwire [--version | -V | --help | -h]
```
Everything else is the TUI (function keys and `/commands` in the composer).
### Environment
| Variable | Read in | Meaning |
|---|---|---|
| `ONIONWIRE_HOME` | `src/store.rs` | Data dir. Unset → `~/.local/share/onionwire`. |
| `ONIONWIRE_STORE_PASSPHRASE` | `src/store.rs` | Non-empty store passphrase; skips the prompt. Empty/missing with no TTY fails closed. |
| `ONIONWIRE_ASCII` | `src/tui.rs` | Present → ASCII chrome (also follows `NO_COLOR`). |
| `ONIONWIRE_WALLET_RPC` | `src/wallet.rs` | External loopback `monero-wallet-rpc` URL. Unused by the app-owned wallet child. |
| `ONIONWIRE_WALLET_RPC_LOGIN` | `src/wallet.rs` | `user:pass` when the URL has no userinfo. |
| `ONIONWIRE_WALLET_NO_SPEND` | `src/wallet.rs` | `1` / `true` / `yes` / `on` → refuse `/tip` locally. |
`NO_COLOR` (any value) also switches ASCII chrome. Android CI uses
`ONIONWIRE_REQUIRE_RELEASE_KEY`; the TUI does not read it.
## Keys (TUI) ## Keys (TUI)
Focus starts on the composer so typing works immediately. `Tab` cycles panes; `j`/`k` and arrows only move the focused pane (roster or chat). `1`/`2`/`3` switch focus when you are not typing in the composer. `?` opens help from every screen except paste (so a payload can contain `?`). Focus starts on the composer. `Tab` cycles panes; `j`/`k` and arrows only move
the focused pane. `1`/`2`/`3` switch focus when you are not typing (on the
**wallet** screen those digits pick an in-process chain source instead — see
[docs/TUI.md](docs/TUI.md)). `?` opens help from every screen except paste (so a
payload can contain `?`).
| Key | Action | | Key | Action |
|---|---| |---|---|
| `Tab` / `Shift-Tab` | Cycle focus: roster → chat → composer | | `Tab` / `Shift-Tab` | Cycle focus: roster → chat → composer |
| `1` / `2` / `3` | Focus roster / chat / composer (when not typing) | | `1` / `2` / `3` | Focus roster / chat / composer (Main, when not typing) |
| `j` `k` / `↑` `↓` | Move or scroll the focused pane | | `j` `k` / `↑` `↓` | Move or scroll the focused pane |
| `g` / `G` | Jump to top / bottom of the focused pane | | `g` / `G` | Jump to top / bottom of the focused pane |
| `?` | Keybinding help (`Esc` closes) | | `?` | Keybinding help (`Esc` closes) |
| `F2` | Share invite (`onionwire:v1:…`) | | `F2` | Share invite (`onionwire:v2:…`, ~1.9 KB) |
| `F3` | Paste a friend’s invite | | `F3` | Paste a friend's invite |
| `F4` | Rotate **onion** (locator only) | | `F4` | Rotate **onion** (locator only) |
| `F5` | Selected friend’s profile (`/who`) | | `F5` | Selected friend's profile (`/who`) |
| `F6` | Wallet (receive QR, balance, transfers, create/import) |
| `F7` | Node & wallet setup (wallet RPC endpoint, chain source, start/stop, live node state) |
| `F8` | Rotate **prekey and ML-KEM key** (hard cut: every friend re-pastes the invite) |
| `F9` | Wallets & settings menu (`/settings`) |
| Enter | Send chat to the selected friend, or run a `/command` | | Enter | Send chat to the selected friend, or run a `/command` |
| `Esc` | Close overlay / back to Main / clear composer | | `Esc` | Close overlay / back to Main / clear composer |
| `Ctrl-Q` | Quit: type `CLEAR`+Enter to wipe history, `QUIT`+Enter to leave it, Esc to stay | | `Ctrl-Q` | Quit: type `CLEAR`+Enter to wipe history, `QUIT`+Enter to leave it, Esc to stay |
`F7` is where the Monero side is set up: the wallet RPC endpoint and login, the
chain source (receive-only, a local `monerod`, a remote daemon, or the in-process
Cuprate node), the chain datadir, and `Ctrl-S`/`Ctrl-X` to start and stop it. It
is also what the “open F7” wallet error points at. Full map:
[docs/TUI.md](docs/TUI.md).
Composer `/commands` (`src/tui.rs` `parse_cmd`): `/wipe`, `/wipe-all`, `/profile`,
`/who`, `/pay <xmr> [memo]`, `/tip <xmr> [memo]`, `/backup /path`, `/restore /path`,
`/file /path`, `/settings`, `/wallet create`, `/wallet import`.
## F2 / F3 invite ## F2 / F3 invite
There is no QR. `F2` opens `(o) invite` with truncated fingerprint, current onion, and the full payload (wrapped, mouse-select to copy): There is no invite QR. `F2` opens the share screen with truncated fingerprint,
current onion, and the full payload (wrapped, mouse-select to copy):
`onionwire:v1:k=…:o=…:spk=…:sig=…` `onionwire:v2:k=…:o=…:spk=…:kem=…:sig=…`
Give that string to a friend. They `F3` paste it (`(o) paste invite`). Unknown `k` asks for approval. Same `k` already in the roster updates `onion` only. The `kem=` field is the 1184-byte ML-KEM-768 public key (base64url), so the
string is about 1.9 KB instead of a few hundred bytes; `C` copies the whole
payload even when the terminal is too short to display all of it. Decode still
accepts a legacy `onionwire:v1:…` invite (no `kem=`): that friend is added as a
**classical** peer and the roster says `classical` next to them. There is no
silent upgrade — only a new signed v2 invite changes that.
Give that string to a friend. They `F3` paste it. Unknown `k` asks for approval.
Same `k` already in the roster updates `onion` (and prekey/KEM key) only.
No PQ for a legacy v1 peer: they have no `kem_pk`, so the session uses the old
`onionwire-v1` prologue with no ML-KEM secret. A v2 friend always sends the
prelude; a peer that omits it is hard-failed with `prelude required`. A v1-only
build cannot talk to a v2 friend, and that break is intentional.
## F4 rotate onion ## F4 rotate onion
`F4` is a locator change, not a new identity. Confirm by typing `ROTATE` (Enter alone does nothing). `F4` is a locator change, not a new identity. Confirm by typing `ROTATE` (Enter
alone does nothing).
- Your identity fingerprint stays the same. - Identity fingerprint stays the same.
- A new onion is published; the old one is hard-cut (no dual-host grace). - A new onion is published; the old one is hard-cut (no dual-host grace).
- Online friends get a signed `loc` frame. - Online friends get a signed `loc` frame.
- Offline friends cannot find you until they F3-paste the new invite. There is no directory. - Offline friends cannot find you until they F3-paste the new invite. There is no directory.
## Fail closed ## Local outbox (chat) and fail closed
If a peer’s onion is down, send fails. v1 has no outbox, no retry queue, no DHT, no name server. There is still no hosted chat server. **Chat** to an unreachable onion is written to a local `outbox` row and retried
in-process while the app runs (exponential backoff from 30s, cap 30 min, stop
after 8 attempts or a terminal failure — `src/outbox.rs`). There is **no**
server-side queue and **no** store-and-forward relay — a queued message never
leaves the device, and it dies with the device.
- **Device seizure.** A pending message sits in the same SQLCipher store as the
rest of the history. Seizure *with* the passphrase reveals messages that were
never sent; seizure without it reveals nothing in this store. `/wipe` clears
outbox rows with chat history; `/wipe-all` removes them with the data dir.
Neither is a forensic erase.
- **Retry cadence is a local traffic-analysis surface.** A queued send re-dials
the peer's onion on a backoff schedule while the app runs.
Still **fail closed** (no queue, no retry):
- file transfer (`/file`) and payment frames (`inv` / `rcp` / `tip`)
- fingerprint mismatch vs the pinned key
- Arti cannot publish the onion (no C-tor fallback)
- no DHT, no name server, no hosted chat server
## Chat ratchet
Chat is ratcheted on top of the Noise session: each chat send is Double-Ratchet
encrypted first, and the resulting `rat ` frame is what the one-shot Noise
session carries. Wire format: [docs/PROTOCOL.md](docs/PROTOCOL.md).
- Per-friend state lives in the encrypted store (`ratchet_sessions`). Nothing
about it is transmitted.
- **Only chat is ratcheted.** `loc`, `prf`, `inv`, `rcp`, `tip`, `png`, and
`fil` keep the one-shot Noise shape.
- **Chat length is bucketed.** The chat line is padded inside the ratchet
ciphertext to one fixed ladder size (256 B to 32 KiB), so the wire shows a
bucket rather than the exact message length. Timing and retry cadence are
still observable; this hides length only.
- Out-of-order delivery works (bounded skipped keys: 2000 per chain jump, 2000
stored). A queued chat message re-sends the *same* `rat ` frame.
- `/wipe` clears chat, payments and outbox but **keeps** ratchet state. `/wipe-all`
removes the data dir.
- There is no `/reset`. State drops when the friend's prekey or ML-KEM key
changes (you `F3`-paste a refreshed invite).
- **Ratchet steps are hybrid; epoch 0 is not.** Every rotation after the
bootstrap mixes an ML-KEM-768 secret into the chain KDF, so a later X25519
break does not open a hybrid chain. The bootstrap epoch is still derived only
from the two X25519 prekeys — a per-session KEM secret cannot be folded in
without breaking both-send-first convergence — so messages sent before the
first rotation stay X25519-only at the ratchet layer, and classical (v1)
friends have no PQ layer at all. No full post-quantum forward secrecy is
claimed; see [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
- An inbound `rat ` frame that does not authenticate is logged as
`rat dropped (<reason>)` on stderr and dropped. There is no in-app desync banner.
## File transfer ## File transfer
`/file /path` sends a local file to the selected friend. Both must be online. `/file /path` sends a local file to the selected friend. Both must be online.
Cap 1 MiB on send and receive. Fail closed: a bad chunk or hash mismatch Cap 1 MiB (`file::MAX_BYTES`). Fail closed: a bad chunk or hash mismatch deletes
deletes the partial (never overwrite). Files land in the partial. Files land in `$ONIONWIRE_HOME/inbox/<fingerprint>/`. Chat shows
`$ONIONWIRE_HOME/inbox/<fingerprint>/`. Chat shows `[file] name (N bytes)`, `[file] name (N bytes)`. Not covered by the chat outbox.
never raw frames. No outbox, no resume, no images in the TUI.
## Profile ## Profile
`/profile` edits your friend-visible display name, bio, and optional Monero address (64 / 512 byte limits, no images). Enter saves and one-shot sends a signed `prf` frame to the selected friend. `F5` or `/who` shows their last signed profile. There is no directory: unknown pubkeys are ignored. `/profile` edits your friend-visible display name, bio, and optional Monero
address (64 / 512 byte limits, no images). Enter saves and one-shot sends a
signed `prf` frame to the selected friend. `F5` or `/who` shows their last signed
profile. Unknown pubkeys are ignored.
## Monero sidecar ## Monero (opt-in)
OnionWire is not a wallet. Optional JSON-RPC to a user-hosted `monero-wallet-rpc`. The wallet **must** use `--rpc-login`; OnionWire refuses an open RPC (HTTP 200 without a Digest challenge) and refuses URLs with no credentials. Chat does not need a wallet. Spend is opt-in at wallet create/restore. Optional
JSON-RPC to `monero-wallet-rpc` on **loopback only** (you run it, or the app
spawns it). Chain source is your choice: spawned local `monerod`, in-process
Cuprate (opt-in feature, **unvalidated on mainnet**), or a daemon address you
type. The wallet **must** use `--rpc-login`; OnionWire refuses an open RPC and
refuses URLs with no credentials. Wallet RPC is never on clearnet and never over
`.onion`. `--trusted-daemon` is never passed.
The app-owned local daemon RPC port is **18081**. **18089** is a daemon's
*restricted*-RPC port and belongs only in examples of a *remote* address you type.
```bash ```bash
# monero-wallet-rpc --rpc-bind-ip 127.0.0.1 --rpc-bind-port 18083 --rpc-login onionwire:secret # externally run wallet RPC (migration path)
export ONIONWIRE_WALLET_RPC=http://onionwire:secret@127.0.0.1:18083 export ONIONWIRE_WALLET_RPC=http://onionwire:secret@127.0.0.1:18083
# or keep the password out of the URL: # or:
export ONIONWIRE_WALLET_RPC=http://127.0.0.1:18083 export ONIONWIRE_WALLET_RPC=http://127.0.0.1:18083
export ONIONWIRE_WALLET_RPC_LOGIN=onionwire:secret export ONIONWIRE_WALLET_RPC_LOGIN=onionwire:secret
``` ```
Loopback only, HTTP Digest (RFC 2617, matching `--rpc-login`), 5s timeout, 1 MiB response cap. `.onion` RPC URLs are rejected (no Arti dial; do not point this at a remote wallet). Unset → chat still works; `/pay` and `/tip` say so. Do not log the RPC password. Prefer `ONIONWIRE_WALLET_NO_SPEND=1` until you actually want `/tip`. Details:
[docs/WALLET.md](docs/WALLET.md).
- `/pay <xmr> [memo]` — invoice (we want to receive). Uses a wallet subaddress if RPC is up, else the profile `xmr_addr`. | Command | Wire frame | What it does |
- `/tip <xmr> [memo]` — pay the selected friend’s profile address, then send a signed `rcp`. Incoming receipts stay unverified until RPC `get_transfers` matches. |---|---|---|
| `/pay <xmr> [memo]` | `inv ` | Invoice to receive. Subaddress if RPC is up, else profile `xmr_addr`. |
| `/tip <xmr> [memo]` | `rcp ` + `tip ` | Chain `transfer`, then signed receipt and tip. One-shot. Disabled under `ONIONWIRE_WALLET_NO_SPEND`. |
Peer onion down → `/pay` and `/tip` fail. A queued invoice does not exist.
`F6` then `c` / `/wallet create` generates a spend-capable wallet and shows the
25-word seed **once**. `F6` then `i` / `/wallet import` restores from a seed, and
takes an optional Monero seed-offset passphrase (a second spend secret, not the
wallet-file passphrase; blank skips it, a wrong one opens a different wallet and
does not fail).
Type `SPEND` then `SEEN` on create. Each wallet gets its own file name
(`onionwire-1`, `onionwire-2`, …); the RPC must be started with `--wallet-dir`.
`monero-wallet-rpc` keeps a wallet open only for the life of one process, so the
app opens the configured file itself after the child is up (`open_wallet`) — and
the passphrase that does it is kept, sealed in the store beside the RPC creds.
That is deliberate and it means the store passphrase is enough to spend; see
[docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) and
[docs/WALLET.md](docs/WALLET.md). A wallet the app holds no passphrase for still
starts — the status reports `needs passphrase` and the app prompts for it once.
## Backup / restore ## Backup / restore
Losing `identity_sk` loses every friend relationship. Losing `identity_sk` loses every friend relationship.
- `/backup /path` — type `BACKUP`, passphrase twice. Writes `owbak1` (Argon2id + ChaCha20-Poly1305). Onion is **not** in the file (locator is disposable; F4 after restore if needed). - `/backup /path` — type `BACKUP`, passphrase twice. Writes `owbak1` (Argon2id +
- `/restore /path` — type `RESTORE`, passphrase. Overwrites self keys. **Does not rewrite the roster** — you may become a different person talking to old friends. ChaCha20-Poly1305). Onion is **not** in the file.
- `/restore /path` — type `RESTORE`, passphrase. Overwrites self keys. **Does not
Treat the backup file like the sqlite db. rewrite the roster.**
## Mixed versions
0.1.2 peers store unknown plaintext as chat. A 0.2 sender of `prf ` / `inv ` / `rcp ` / `fil ` will leave a garbage line on an un-upgraded peer. Upgrade both sides. The Noise handshake is unchanged.
## Wipe ## Wipe
Composer (bottom of the roster screen): - `/wipe` — type `WIPE`. Chat, payments, and outbox gone. Identity and friends stay.
- `/wipe-all` — type `WIPEALL`. Deletes the data dir. Next start is a **new person**.
- `/wipe` — confirm by typing `WIPE`. Chat and payments history gone (overwrite message bodies, drop `payments`, `VACUUM`, WAL checkpoint). Identity key and friends stay. Not a forensic erase (SSD wear-leveling). `/wipe-all` is the identity burn. Not a forensic erase (SSD wear-leveling). Esc cancels.
- `/wipe-all` — confirm by typing `WIPEALL`. Deletes the data dir. Next start is a **new person** (new identity key). Same disk caveat. Esc cancels. Nothing is wiped without confirm.
## Uninstall ## Uninstall
```bash ```bash
# binary (whichever you used)
rm -f ~/.local/bin/onionwire ~/.cargo/bin/onionwire rm -f ~/.local/bin/onionwire ~/.cargo/bin/onionwire
# optional: destroy identity, friends, and message log
# (same as /wipe-all — you become a new person next run)
rm -rf ~/.local/share/onionwire rm -rf ~/.local/share/onionwire
``` ```
@ -220,95 +416,77 @@ If you set `ONIONWIRE_HOME`, delete that directory instead.
## Seized laptop ## Seized laptop
Chat bodies in sqlite are ChaCha20-Poly1305 (`nonce || ciphertext` in `messages.plaintext`) with AAD bound to `friend_id`, `dir`, and row id, wrapped by a passphrase-derived Argon2id key. A disk grep of `onionwire.db` must not yield the message log. Empty-AAD v0.2 blobs are rewrapped once on unlock. The sqlite file is SQLCipher. A 32-byte key is derived from the store passphrase
with Argon2id over a per-install 16-byte salt in `store_salt` (mode 0600) and
handed to SQLCipher as a raw key. Chat bodies carry a second, row-bound
ChaCha20-Poly1305 layer. Unlock is fail-closed. At-rest encryption is not a
defense against a live compromise or an attacker who has your passphrase.
Pending outbox rows live in the same encrypted store as delivered chat.
Still plaintext on disk (unless you add OS/FDE): Threat model: [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
- your identity secret key (`self.identity_sk`)
- friend public keys and current locators
The message key is **not** wrapped with `identity_sk` (that key is in the same file). sqlcipher is out of v1. `/wipe` deletes chat and payments history; it is not a forensic erase. Roster and identity stay. `/wipe-all` deletes the data dir (new identity). Ctrl-Q can clear history on the way out (`CLEAR`) without becoming a new person.
Threat model: [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md).
## Android (SDK + APK) ## Android (SDK + APK)
Same repository, same protocol, separate product from the Linux TUI. An Android Same repository, same protocol. An Android peer and a Linux peer that exchange
peer and a Linux peer that exchange invites interoperate — one protocol, not two. invites interoperate.
- **SDK** — `onionwire-sdk-<version>.aar`. UniFFI Kotlin bindings over the same - **SDK** — `onionwire-sdk-<version>.aar`. UniFFI Kotlin over the same Rust crate
Rust crate the TUI runs on, plus `libonionwire_sdk.so` for `arm64-v8a`. the TUI runs. See [crates/onionwire-sdk/README.md](crates/onionwire-sdk/README.md).
Another Android app depends on it directly. See - **APK** — `onionwire-<version>-android-arm64-v8a.apk`. Kotlin + Jetpack Compose.
[`crates/onionwire-sdk/README.md`](crates/onionwire-sdk/README.md). Build notes: [android/README.md](android/README.md). The UI is a design-token
- **APK** — `onionwire-<version>-android-arm64-v8a.apk`. Kotlin + Jetpack system (one accent, 16px cards, three-tab shell: Chats / Wallet / Node &
Compose + Material 3 messenger that depends on the SDK and nothing else. Settings) rather than per-screen styling; see *App shell* in that README.
It is not a WebView, and `src/tui.rs` is untouched. Both are built on a host with The APK build is amd64-only. After the Linux `release` workflow finishes,
the Android SDK/NDK — the Pi runner is aarch64 Linux and cannot produce an APK: dispatch `android-release` with that tag so the APK/AAR attach to the same
Forgejo release.
```bash ```bash
# one-time: sdkmanager platform 36 / build-tools 36.0.0 / ndk 28.2.13676358, scripts/build-android-local.sh # -> dist/, with .sha256
# rustup target add aarch64-linux-android, cargo install cargo-ndk PUBLISH_TAG=v0.7.0 scripts/build-android-local.sh # + upload to that release
scripts/build-android-local.sh # -> dist/, with .sha256 files
PUBLISH_TAG=v0.3.0 scripts/build-android-local.sh # + upload to that release
``` ```
Every asset has a matching `.sha256` so `sha256sum -c` works. The APK is
**debug-signed** and is for sideloading, not for Play. Full build notes, the
`minSdk 26` rationale, the 16 KB page-size check and the signing story are in
[`android/README.md`](android/README.md).
## Releases (maintainers) ## Releases (maintainers)
Tags trigger Forgejo Actions on the self-hosted Pi runner. The x86_64 asset has Manual and batched: no merge publishes anything, and neither does a tag push.
no runner on this instance, so it is built locally and attached to the same Full procedure: [docs/RELEASING.md](docs/RELEASING.md).
release.
Actions → **release** → Run workflow:
| Input | Meaning |
|---|---|
| `dry_run` | build + checksum both Linux binaries, no tag, no publish. Run this first. |
| `bump` | `patch` / `minor` / `major` off the newest `v*.*.*` tag. Default `minor`. |
| `version` | explicit `X.Y.Z` — overrides `bump`. |
| `tag` | rebuild / re-publish an existing tag. |
Then dispatch **android-release** with `tag=<that tag>` to attach the APK + AAR.
```bash ```bash
# 1. version in Cargo.toml must match the tag without the leading v FORGEJO_TOKEN=<pat> scripts/build-release-local.sh v0.7.0
cargo update --offline -p onionwire # keep Cargo.lock at the new version
git commit -am "chore: release vX.Y.Z" && git push origin main
# 2. tag and push — the release workflow builds + publishes aarch64
git tag -a vX.Y.Z -m "OnionWire vX.Y.Z"
git push origin vX.Y.Z
# 3. attach x86_64 from an x86_64 host (idempotent — safe to re-run)
FORGEJO_TOKEN=<pat> scripts/build-release-local.sh vX.Y.Z
``` ```
Workflows (Forgejo Actions, `.forgejo/workflows/` — jobs run on the `docker` Do not run `cargo publish`; `publish = false`.
label of the Pi runner and do their Rust work in a `rust:1.91-bookworm`
sibling container):
- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` on `main` and PRs (ignored Tor-live tests are not run).
- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — on `v*.*.*` tags: builds `aarch64-unknown-linux-gnu` natively, strips, sha256, publishes to the release. Also runnable via `workflow_dispatch` with a tag input to re-publish.
Scripts:
- [`scripts/publish-release.sh`](scripts/publish-release.sh) — create-or-update a release and (re)upload assets via the Forgejo API. Needs `FORGEJO_TOKEN` (repo secret in CI, env locally).
- [`scripts/build-release-local.sh`](scripts/build-release-local.sh) — x86_64 build + strip + checksum + publish.
- [`scripts/build-android-local.sh`](scripts/build-android-local.sh) — Android AAR + APK build, checksums, optional publish (see the Android section above).
- [`scripts/release-body.md`](scripts/release-body.md) — release notes template (`@TAG@` is substituted).
Do not run `cargo publish`; `publish = false`. CI needs the repo secret
`FORGEJO_TOKEN` (an instance user PAT with repo write) to publish releases.
## Troubleshooting ## Troubleshooting
| Symptom | What to do | | Symptom | What to do |
|---|---| |---|---|
| `GLIBC_… not found` | Binary is newer than your libc. Build from source (Option B). | | `GLIBC_… not found` | Build from source (Option B). |
| `sha256sum: FAILED` | Re-download both the binary and `.sha256`; run the check in the same directory. | | `sha256sum: FAILED` | Re-download binary and `.sha256`; check in the same directory. |
| Hang on `bootstrapping Arti…` / `hs status: Bootstrapping` | Outbound network required. Combined Arti status can stay Bootstrapping through a 5 min HsDir upload round; OnionWire probes the onion and proceeds once a connect works. Still fail closed after 360s if neither a probe nor `DegradedReachable`/`Running` — no C-tor fallback. | | Hang on `bootstrapping Arti…` | Outbound network required. Fail closed after 360s. No C-tor fallback. |
| `onionwire: unknown argument` | No subcommands. Flags are `--version` / `--help` only, then the TUI. | | `onionwire: unknown argument` | No subcommands. `--version` / `--help` only, then the TUI. |
| Blank / broken TUI | Run in a real terminal emulator, not `nohup` / systemd without a TTY. | | Blank / broken TUI | Real terminal emulator, not `nohup` / systemd without a TTY. |
| Two chats, same laptop | Separate `ONIONWIRE_HOME` per process. | | Two chats, same laptop | Separate `ONIONWIRE_HOME` per process. |
| Friend cannot find you after F4 | Expected if they were offline. They must F3-paste the new invite. Same `k` updates the row. | | Friend cannot find you after F4 | Expected if they were offline. They F3-paste the new invite. |
| Wallet error says “open F7” | `F7` is the node & wallet setup screen: set the RPC endpoint there, or set `ONIONWIRE_WALLET_RPC`. |
## Not in v1 ## Not in v1
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, sqlcipher, QR codes. Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward
relay, multi-device, DHT / name server, invite QR codes, A/V. The **local** chat
retry queue is in; it never leaves the device. Protocol lock:
[docs/PROTOCOL.md](docs/PROTOCOL.md).
## License ## License

259
android/CUPRATE_DAEMON.md Normal file
View file

@ -0,0 +1,259 @@
# The in-process chain daemon (`cuprate-daemon`) in the APK
The wallet's third chain source — Cuprate's chain daemon running **inside the
OnionWire process** — is compiled into the Android build. This document is the
provenance record for that: how the feature is enabled, why the link line looks
the way it does, what CI checks, and what has *not* been proven.
Companion reading: [docs/WALLET.md](../docs/WALLET.md) ("The in-process chain
daemon") for what the daemon is, [docs/cuprate-android-spike.md](../docs/cuprate-android-spike.md)
for the cross-compile spike this plumbing comes from,
[MONERO_BINARIES.md](MONERO_BINARIES.md) for the `monero-wallet-rpc` executable
(still a child process — Cuprate has no wallet layer), and
[README.md](README.md#wallet-child-and-chain-sources-as-android-sees-them) for
how the Android wallet screen drives it.
## What changed in the build
`android/sdk/build.gradle.kts`:
| | |
|---|---|
| Feature | `--features cuprate-daemon` on the **Android** build only |
| Where | `cargoBuildAndroid` (the `cargo ndk` cross-compile) |
| Not where | `cargoHostLib` / `uniffiBindgen` stay feature-free |
The host cdylib exists only so `uniffi-bindgen --library` can dlopen it. Building
the Cuprate graph there would add ~152 crates and a C++ RandomX build to every
build for a library that never runs the daemon, and the UniFFI surface does not
fork on a cargo feature (`ChainChoice.InProcessCuprate` is present either way, and
`WalletChildStatus` carries the same fields) — so the generated Kotlin bindings are
the same bytes.
`cargoBuildAndroid` prints the feature it is building with, so the CI log carries
the request rather than only the task name:
```
cargo ndk build for arm64-v8a features=cuprate-daemon api=26 ndk=28.2.13676358
```
There is no `-P` knob that turns the feature off. A build that silently dropped
it would ship an APK whose on-device node can only fail; `android-ci.yml` greps
the artifact (below) so that is not only a log line.
## The link line
RandomX is C++ and its aarch64 JIT calls `__clear_cache`, and `randomx-rs`'s build
script emits `rustc-link-lib=static=stdc++` against the NDK's *stub*
`libstdc++.a`. Without libc++ and the compiler-rt builtins the link fails on
`__cxa_allocate_exception` / `std::runtime_error` / `typeinfo` / `__clear_cache`.
`cargo ndk --link-builtins` covers the builtins but not libc++, and
`-static-libstdc++` is ignored by NDK clang, so the full set is spelled out:
```
-L$NDK/toolchains/llvm/prebuilt/<host>/sysroot/usr/lib/<triple>
-L$NDK/toolchains/llvm/prebuilt/<host>/lib/clang/<ver>/lib/linux
-lclang_rt.builtins-<abi>-android
-lc++_static
-lc++abi
-Wl,--exclude-libs,libc++_static.a
-Wl,--exclude-libs,libc++abi.a
```
Five more things the build has to get right, each of which fails as something
else:
1. **`ANDROID_NDK` must be exported**, not only `ANDROID_NDK_HOME` / `NDK_HOME`.
`cmake-rs` (RandomX's C++ half) aborts with *"Android: Neither the NDK or a
standalone toolchain was found"*, and `randomx-rs`'s build script then panics
inside `cmake`. The task exports all three.
2. **The linker is the NDK clang driver, named explicitly.** The dev machines'
`~/.cargo/config.toml` pins `[target.aarch64-linux-android] linker` to the
**API 21** wrapper, and API 21 fails this link (`pthread_atfork` is API 23+).
`cargo-ndk`'s own linker wrapper is bypassed so the `-Wl,…` args reach clang as
link args.
3. **The flags are `CARGO_TARGET_<TRIPLE>_RUSTFLAGS`, not `RUSTFLAGS`.** A global
rustflags would also apply to build scripts and proc macros, which are
**host**-targeted, where `-lc++_static` breaks the link. Setting the
per-target variable also *replaces* the `target.<triple>.rustflags` in
`~/.cargo/config.toml`, so the sysroot `-L` it carried is repeated in the list.
4. **The build image needs `cmake`.** RandomX is built by `randomx-rs`'s build
script through `cmake-rs`, and both Android workflows' `debian:bookworm`
containers install their own package list. Without `cmake` the build gets
~11 minutes in, compiles 400-odd crates, and then dies with a `randomx-rs`
build-script panic — *failed to execute command: No such file or directory …
is `cmake` not installed?* — surfacing as Gradle's "cargo finished with
non-zero exit value 101", which reads like a Rust error and is not one.
`android-ci.yml` and `android-release.yml` both install it.
5. **The Rust toolchain must be >= 1.93.** `tapes`, a Cuprate dependency this
repo cannot patch, calls `VecDeque::pop_front_if`, which is stable only from
1.93. On 1.91 a job compiles ~400 crates and then dies with
`error[E0658]: use of unstable library feature 'vec_deque_pop_if'`.
`ci.yml`, `release.yml`, `android-ci.yml` and `android-release.yml` all pin
1.98 (the stable release this graph is built and tested with), and
`Cargo.toml` `rust-version` is `"1.98"` for the same reason: `cuprate-daemon`
is a default feature, so the default build is the floor.
`:sdk:preBuild` also runs `verifyDynamicLibc`: `libonionwire_sdk.so` must have
`libc.so` in `DT_NEEDED`. Linking the NDK's static `libc.a` instead null-derefs
inside `dlopen` on the first SDK call.
## What ends up in the APK
```
lib/arm64-v8a/libandroidx.graphics.path.so
lib/arm64-v8a/libjnidispatch.so
lib/arm64-v8a/libmonerowalletrpc.so
lib/arm64-v8a/libonionwire_sdk.so
lib/arm64-v8a/librandomx_rs-<hash>.so <- new, see below
```
`librandomx_rs-<hash>.so` is new and is **not a load-time dependency** of the SDK:
`readelf -d libonionwire_sdk.so` lists `liblog.so` and nothing else, and the
RandomX code is statically inside the SDK's own `.so` (its symbols and strings are
there). `cargo-ndk` copies every cdylib the target directory produced into
`jniLibs`, and `randomx-rs` also builds one. It is left in place rather than
filtered out: it is 1,122,296 bytes uncompressed / 387,996 deflated (sizes from
the feature-on CI run in the table below), and dropping it would be a packaging
rule that silently breaks the day something *does* link it.
## The CI gate
`.forgejo/workflows/android-ci.yml` extracts `lib/<abi>/libonionwire_sdk.so` from
the built APK and greps it for `target_max_memory` — a rodata literal from
`src/cuprate.rs`'s config TOML, compiled only under
`#[cfg(feature = "cuprate-daemon")]`. The job **fails** if it is absent.
The negative control is v0.7.0's shipped APK: its `libonionwire_sdk.so` contains
**zero** occurrences of that string (and of `randomx` / `cuprated`), so a match
means the daemon is in the artifact, not merely requested. The build log line
above is the other half of the proof — request and artifact, separately checkable.
## What the wallet screen does with it
`ui/WalletScreen.kt` grew a third chain source beside the daemon field and
**Receive-only** (`ui/WalletChildStatusText.kt` holds the pure model):
* Selecting **On-device node (Cuprate)** stores `ChainChoice.InProcessCuprate` with
an **empty** `monerod_datadir`, which the SDK resolves to
`$ONIONWIRE_HOME/chain/{testnet,mainnet-pruned,mainnet-full}` from the stored
`mainnet` / `prune` flags — Kotlin never invents an absolute path.
* `monero-wallet-rpc` is still required and still a subprocess: Start is gated on
the bundled binary exactly as before, and an in-process node does not bundle
`arti`, so a `.onion` daemon is still refused. Wallet RPC is loopback only.
Chain traffic stays off until the user opted into a wallet and chose a source.
* The status line renders the core's words verbatim and grows a `node <word>`
segment from `WalletChildStatus.node_state` for this source only. An unrecognised
word is never rendered as ready.
* **The daemon's sync height is on the line.** `WalletChildStatus.height` /
`target_height` (Rust `u64` → UniFFI/Kotlin `ULong`) carry the blocks the chain
daemon had at the last probe — read from the wallet RPC, or, when that RPC is
refused (the 111 case) and the source is local/in-process, from the daemon over
loopback. The status line appends ` · sync h/t` after the source (and after the
`node` segment) whenever either is non-zero: `0/0` means the last probe failed
or the daemon is not up, so it is *unknown*, not `0%` — there is no percent, no
progress bar and no ETA anywhere in the UI, and a zero target still prints as
`/0` when height is non-zero. This is the **daemon's** chain height, not the
wallet's scan height. The same string is what the status row's screen-reader
`contentDescription` carries (`walletChildStatusDescription`), so the spoken row
is never shorter than the visible one. Cross-compiled and unit-tested on the
JVM; still not device-proven.
* **What writes that snapshot on Android.** The wallet screen's loop
(`WireViewModel.openWalletChild` → `walletChildRefreshLoop`) does one cached
`Wire.walletStatus()` paint, then every 2 s a live
`Wire.walletChildRefresh()` (`Wire::wallet_child_refresh`). The live call is
what makes height/target move between ticks; it never spawns. See
[README.md](README.md#what-the-apk-refresh-loop-actually-calls).
* **Storage honesty.** The card shows the free space on the filesystem the fjall
store grows into (`StatFs` on the app's data dir) and refuses Start below a
floor, or when that filesystem cannot be read at all. The floor is a *floor*,
not a sync estimate, and the doc comment says why: nothing in this stack
exposes one — `WalletChildStatus` has no size field, and Cuprate's restricted RPC
reports a hardcoded 5 GiB `database_size` placeholder. Floors in
`ui/WalletChildStatusText.kt`: 3 GiB testnet, 64 GiB mainnet-pruned, 280 GiB
mainnet-full.
* **Pre-production warning**, above the Start button, in a sentence:
`CUPRATE_PREPRODUCTION_WARNING` — quoted user book, testnet-only / mainnet
unvalidated, and Cuprate issue #278, assertable in `WalletChildStatusTextTest`.
Opt-in, never a default.
## What it costs in CI
The Android job runs on the `docker-amd64` runner (it is **not** the Raspberry Pi
runner) with `CARGO_BUILD_JOBS=1` and a warm named volume at `/cargo-target`, so
the numbers below are one runner and one volume: `main` with the feature off, and
the feature on. There are two feature-on regimes, and the second is the one a PR
author feels — the first build after the feature lands compiles the whole cuprated
graph, every later build is incremental against the same volume.
These figures are the **recorded** costs from the runs that landed the feature
(not re-measured on `fa0e4b2`):
| | feature off — `main` 773dacb, run 402 | feature on — PR #113 head 3860c3d (merged as 8626da2), run 412 |
|---|---|---|
| Gradle | `BUILD SUCCESSFUL in 6m 10s` | `BUILD SUCCESSFUL in 7m 14s` |
| job | 8m 21s | 11m 12s |
| build step | 484 s | 653 s |
| `/cargo-target` | 3.1 G before the build | 5.6 G after (2.7 G of it `aarch64-linux-android/release`) |
| `libonionwire_sdk.so` in the APK | 33,533,264 B | 55,438,112 B |
| `librandomx_rs-<hash>.so` | absent | 1,122,296 B |
| APK | 28,038,401 B | 34,445,514 B |
| AAR | 10,377,416 B | 15,728,039 B |
The **first** feature-on build is the expensive one: run 406, against a volume that
did not yet hold the cuprated graph, took `BUILD SUCCESSFUL in 44m 7s` and a
47m 44s job — the ~152-crate graph plus the C++ RandomX cross-build, with a single
cargo job on the runner. After that it settles to roughly **+2 minutes over the
feature-off build** (7m 14s vs 6m 10s), because only this repo's own crates
recompile.
`android-ci.yml`'s job `timeout-minutes` is **120**; `android-release.yml`'s
Android job is **90**. Even the 44-minute first build fits both with room to
spare, and the volume grew to 5.6 G on a runner filesystem with 37 G free (the
`df -h` in the run log). The feature is **not** gated on a build variant, a label
or a manual dispatch — the release path builds exactly what CI verifies.
`android-ci.yml` prints `du -sh /cargo-target`, the length/method/deflated size of
every native lib, and both artifact digests, and the workflow echoes
`build_wall_clock_seconds`: the next person changing this graph reads the cost and
the artifact's identity out of the run log rather than re-deriving either.
## What has not been proven
The daemon was **not executed on a device or an emulator**. There is no
`arm64-v8a` AVD on the build host (the same gap [MONERO_BINARIES.md](MONERO_BINARIES.md)
records), and no aarch64 Android sysroot to run it under `qemu-user`. What is
proven: it cross-compiles and links against the NDK's C++ runtime, the feature is
in the shipped `.so`, the artifact packages, and the Kotlin that drives it
compiles and passes its unit tests. What is not:
* that `cuprated` starts, opens its fjall store and answers on loopback under
Android's runtime;
* **mainnet remains unvalidated.** Cuprate itself is pre-production and its own
user book says not to use `cuprated` for serious purposes. The Android screen
can store a mainnet-pruned or mainnet-full mode; that is not a claim this build
has run either. Core still surfaces `testnet only — mainnet is unvalidated`
(`cuprate::TESTNET_ONLY`);
* **a daemon that dies after the wallet child came up cannot be reported
`exited`.** The in-process node is a value this app owns, not a process with a
pid. The SDK derives `node_state` from the wallet-child state
(`crates/onionwire-sdk/src/lib.rs`, `node_state`). If the daemon dies after its
wallet child is up, the chain probe fails and the state stays `syncing`. It is
never reported `ready` from that failure. `exited` still means what it says:
the `monero-wallet-rpc` child is gone.
To close the device gap, on an arm64 device or a software-emulated arm64 AVD:
```bash
sdkmanager "system-images;android-35;google_apis;arm64-v8a"
avdmanager create avd -n ow-arm64 -k "system-images;android-35;google_apis;arm64-v8a"
emulator -avd ow-arm64 # software-emulated on an x86_64 host: slow
adb install -r dist/onionwire-<version>-android-arm64-v8a.apk
```
then unlock the node, open Wallet, tap **On-device node (Cuprate)**, read the
warning, press **Start wallet**, and watch the status line for
`connecting → syncing · in-process node · node starting → node syncing`. A wallet
balance needs the chain synced, which on a phone is a long wait — the status line
is the thing to watch, not the balance. After the first cached paint, the APK
loop probes live every 2 s, so `sync h/t` should move once the daemon answers.

191
android/MONERO_BINARIES.md Normal file
View file

@ -0,0 +1,191 @@
# Bundled native executables (`jniLibs`)
The wallet screen starts an **app-owned `monero-wallet-rpc` child** (issue #107,
[`src/wallet_child.rs`](../src/wallet_child.rs)). Monero ships no Android
binaries, so this repository carries one, built here.
| | |
|---|---|
| File in the tree | `android/app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so` |
| Bytes | 19 954 224 (stripped) |
| sha256 | `d9126788030ecd1ccdb40c7764e66e9a14d158a147ad335b256f0577681b5ad4` |
| Format | `ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /system/bin/linker64, for Android 21, built by NDK r17b (4828580), stripped` |
| Needed libs | `libc.so`, `libm.so`, `libdl.so` — everything else is static |
| Source | `https://github.com/monero-project/monero` |
| Tag | `v0.18.4.4` |
| Commit | `516e5355a103a2bf0b7e10328ebcaa2945019445` (peeled annotated tag) |
| Reproduce with | `scripts/build-monero-wallet-rpc-android.sh` |
| Verified by | `android/monero-binaries.sha256`, checked by `scripts/build-android-local.sh` on every build (local and CI) |
Re-checked on this tree (`fa0e4b2`): `stat -c %s` is 19954224; `sha256sum` of the
blob equals the hash above and equals the line in `android/monero-binaries.sha256`
(that file's path is relative to `android/`:
`app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so`). `readelf -d` NEEDED is
`libdl.so`, `libm.so`, `libc.so`.
Only `arm64-v8a` is built. `-Ponionwire.abis=x86_64` produces an APK with no
wallet binary in it — the screen says so (`NO_WALLET_RPC_MESSAGE`) instead of
offering a Start that cannot work.
## How it is built
`scripts/build-monero-wallet-rpc-android.sh` runs upstream's own Android
cross-compile path — `contrib/depends` (boost, openssl, libunbound, libzmq,
libsodium, ncurses, readline, libiconv, expat for `aarch64-linux-android`) plus
the `toolchain.cmake` it emits — and then builds the single CMake target
`wallet_rpc_server`. It takes ~40 min on 12 cores and needs ~15 GB of scratch
space. It is **not** part of the CI path: the Android Gradle jobs already run
on `docker-amd64` for ~9 minutes with warm volumes, and rebuilding Monero's C++
tree is a separate 30–45 min host job. CI verifies the committed bytes instead
(`sha256sum -c` plus the APK-entry check in `scripts/build-android-local.sh`).
Four things about the build are worth writing down, because each one is a
failure that looks like something else:
1. **CMake must be 3.x.** `contrib/depends` emits a *standalone-NDK-toolchain*
`toolchain.cmake` (`CMAKE_ANDROID_STANDALONE_TOOLCHAIN`). CMake 4.x no longer
honours that, silently falls back to the host `clang`, and the configure step
dies with `ld.lld: cannot open /usr/lib/clang/.../libclang_rt.builtins.a`.
The script installs 3.22.6 into a venv when the host CMake is 4.x.
2. **The NDK r17b prebuilt `clang60` needs `libtinfo.so.5`.** `android_ndk.mk`
pins NDK r17b and drives the long-removed `make_standalone_toolchain.py`
(r17b still has it). Its `clang60` binary is linked against ncurses 5;
current distros ship ncurses 6 only, so every compile fails with
`error while loading shared libraries: libtinfo.so.5`. A shim directory with
`libtinfo.so.5 -> libtinfo.so.6` on `LD_LIBRARY_PATH` fixes it. The script
creates it.
3. **`/usr` is in `CMAKE_FIND_ROOT_PATH`, and `/usr` is the host.** This is the
one that costs the most time. `CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY` does
not help: `/usr` is listed as a root, so `find_library()` returns host
libraries. Two consequences in this tree:
* `find_package(HIDAPI)` finds the **host** hidapi, defines `HAVE_HIDAPI`,
and `src/device` then fails to compile `hidapi/hidapi.h` — the include dir
it found is `/usr/include/hidapi`, so `<hidapi/hidapi.h>` resolves to
`/usr/include/hidapi/hidapi/hidapi.h`.
* Monero's optional zmq extras (`pgm`, `norm`, `gssapi_krb5`, `protolib`,
`bsd`, `md`, `protokit`) are probed with `find_library` and appended to
`ZMQ_LIB`, so the final link gets `/usr/lib/libpgm.so` — an x86-64 shared
object in an aarch64 link line: `error adding symbols: File in wrong
format`. `libzmq.a` does not actually reference openpgm.
The script rewrites the generated `toolchain.cmake` to
`SET(CMAKE_FIND_ROOT_PATH <depends-prefix>)`. This is also why upstream's
`make depends target=aarch64-linux-android` is not reproducible: it happens
to work only on a build host with none of those libraries installed.
A stale `CMakeCache.txt` keeps the host paths after the toolchain is fixed,
and nothing complains until the link, so the script also passes
`-U PGM_LIBRARY -U GSSAPI_LIBRARY …` and configures in a fresh build dir.
4. **The CMake target is `wallet_rpc_server`, not `monero-wallet-rpc`.** The
latter is the *output* name. `make monero-wallet-rpc` fails with
`No rule to make target`.
### Not bit-reproducible
Build paths and timestamps land in the binary, so a fresh run of the script
will not reproduce the sha256 above. That hash is a **provenance record of the
shipped blob** and the thing CI re-verifies — not a reproducible-build
assertion. If you rebuild, update both `android/monero-binaries.sha256` and this
table in the same commit, and say what changed in the tag or the toolchain.
The reproduce script pins **the tag** (`MONERO_TAG=v0.18.4.4`, shallow clone).
The commit in the table is the peeled object of that annotated tag on GitHub,
recorded here so a rebuild can be compared; it is not a second pin in the
script.
## Why it is a `jniLibs` `.so` and not an asset
Since Android 10 (API 29) an app may not `exec()` a file in its own data
directory: the SELinux policy carries no `execute` on `app_data_file`, so the
familiar "ship it in `assets/`, copy it to `filesDir`, `chmod 700`" recipe is
refused by the kernel regardless of the mode bits. The one directory Android
hands out executable is `ApplicationInfo.nativeLibraryDir`, which the package
manager populates from the APK's `lib/<abi>/` entries at install time.
So the executable is named `libmonerowalletrpc.so` and shipped through
`jniLibs`, and the path the core is handed is
```
<applicationInfo.nativeLibraryDir>/libmonerowalletrpc.so
```
resolved at runtime by `wallet/WalletChildBinaries.kt`. This only works with
`android:extractNativeLibs="true"`; with the AGP 8 default
(`extractNativeLibs="false"`) the file stays inside the APK and there is nothing
on disk to run. `app/build.gradle.kts` sets `packaging.jniLibs.useLegacyPackaging
= true` for exactly that reason, and `keepDebugSymbols` for this one entry so
AGP's strip pass cannot rewrite the bytes that CI verifies.
Cost: the release APK grows from ~9 MB to ~28 MB (the binary is deflate-stored
at 6.9 MB) and installs ~20 MB into the app's native library directory.
(Those packaging sizes are the original measurement when the blob landed; the
committed blob's **uncompressed** size is the 19 954 224 bytes above.)
## `arti` is NOT bundled
`WalletChild` runs `arti proxy -p <port>` as the SOCKS child for a **`.onion`**
daemon, and `ChildConfig::validate` requires a non-empty `arti_bin` for any
chain source that is not receive-only. There is no `arti` executable in this
build, and producing one (a standalone `arti` binary for
`aarch64-linux-android`, from a crate the Rust side does not currently build as
a bin) is a follow-up, not something this document can invent.
What the app does about it, honestly:
* `arti_bin` is set to `<nativeLibraryDir>/libarti.so` — the path the binary
*would* occupy. For a loopback or clearnet daemon the core never spawns it, so
the value is inert. It is deliberately **not** set to a real binary:
`monero-wallet-rpc` named as the SOCKS child would be spawned as the proxy the
moment the user typed an `.onion` host.
* The wallet screen refuses an `.onion` daemon while `libarti.so` is absent, and
says why (`ONION_NEEDS_ARTI_NOTICE`) instead of letting the spawn fail.
So today: **loopback and clearnet daemons work; `.onion` daemons do not.**
## Verification in CI
`.forgejo/workflows/android-ci.yml` (and `android-release.yml`) build the APK on
`docker-amd64` and `scripts/build-android-local.sh` does the checking, so both
CI jobs and local builds get it:
1. before Gradle, `sha256sum -c android/monero-binaries.sha256` against the
committed blob;
2. after packaging, `unzip -p` the `lib/<abi>/libmonerowalletrpc.so` entry out
of the produced APK and compare its sha256 with the committed file. A
mismatch fails the build — the bytes that ship are the bytes that were
verified, not the bytes that were hoped for.
## Not verified
The binary was **not executed on a device or emulator**. There is no
`arm64-v8a` AVD on the build host (all three existing AVDs are `x86_64`), and no
aarch64 sysroot to run it under `qemu-user`. What is proven: it cross-compiles,
it is a valid `aarch64` Android PIE executable, it packages into the APK with
the expected bytes, and the Kotlin that drives it compiles. What is not:
that `monero-wallet-rpc` starts, opens its wallet file and answers JSON-RPC
under Android's runtime.
To close that gap:
```bash
sdkmanager "system-images;android-35;google_apis;arm64-v8a"
avdmanager create avd -n ow-arm64 -k "system-images;android-35;google_apis;arm64-v8a"
emulator -avd ow-arm64 # software-emulated on an x86_64 host: slow
adb install -r dist/onionwire-<version>-android-arm64-v8a.apk
```
then unlock the node, open Wallet, type a daemon as `host:port`, Save, and watch
the status line for `connecting → syncing → ready`. A `.onion` daemon will stop
at the arti notice above.
## The other chain source: an in-process daemon, not a binary
The third chain source — Cuprate's chain daemon running inside the OnionWire
process — is a **linked feature of the SDK's `.so`**, not a `jniLibs` executable,
so it has its own record: [CUPRATE_DAEMON.md](CUPRATE_DAEMON.md) (feature wiring,
the NDK C++ / compiler-rt link line, the CI check that greps the shipped `.so`
for a cuprated-only string, and what has not been verified). `monero-wallet-rpc`
above stays a child process for it — Cuprate has no wallet layer.

View file

@ -9,7 +9,15 @@ Two artifacts out of one Gradle build:
The Linux TUI in the repository root is a **separate product** with a separate The Linux TUI in the repository root is a **separate product** with a separate
Cargo workspace. Nothing here turns it into a WebView, and nothing here imports Cargo workspace. Nothing here turns it into a WebView, and nothing here imports
its TUI code. its TUI code. Same wire protocol: [docs/PROTOCOL.md](../docs/PROTOCOL.md).
Companion records (not duplicated here):
* in-process chain daemon in the APK — [CUPRATE_DAEMON.md](CUPRATE_DAEMON.md)
* bundled `monero-wallet-rpc` blob — [MONERO_BINARIES.md](MONERO_BINARIES.md)
* wallet / chain-source behaviour (core + SDK) — [docs/WALLET.md](../docs/WALLET.md)
* consuming the AAR — [crates/onionwire-sdk/README.md](../crates/onionwire-sdk/README.md)
* how a maintainer actually cuts a release — [docs/RELEASING.md](../docs/RELEASING.md)
## Requirements ## Requirements
@ -36,7 +44,8 @@ cd android
``` ```
The Rust cross-compile and the UniFFI Kotlin bindings are wired into the Gradle The Rust cross-compile and the UniFFI Kotlin bindings are wired into the Gradle
tasks — there is no manual codegen step. `:sdk:preBuild` depends on them. tasks — there is no manual codegen step. `:sdk:preBuild` depends on
`cargoBuildAndroid`, `uniffiBindgen`, and `verifyDynamicLibc`.
Emulator / x86_64 slice: Emulator / x86_64 slice:
@ -44,13 +53,20 @@ Emulator / x86_64 slice:
./gradlew :app:assembleDebug -Ponionwire.abis=arm64-v8a,x86_64 ./gradlew :app:assembleDebug -Ponionwire.abis=arm64-v8a,x86_64
``` ```
That extra ABI does **not** ship `libmonerowalletrpc.so` for x86_64. The wallet
screen says so (`NO_WALLET_RPC_MESSAGE`) instead of offering a Start that cannot
work. See [MONERO_BINARIES.md](MONERO_BINARIES.md).
Or from the repo root, with checksums and an optional publish step: Or from the repo root, with checksums and an optional publish step:
```bash ```bash
scripts/build-android-local.sh # -> dist/onionwire-<v>-android-arm64-v8a.apk scripts/build-android-local.sh # -> dist/onionwire-<v>-android-arm64-v8a.apk
PUBLISH_TAG=v0.3.0 scripts/build-android-local.sh PUBLISH_TAG=v0.5.0 scripts/build-android-local.sh
``` ```
The script re-verifies `android/monero-binaries.sha256` before Gradle, then
again against the bytes inside the APK. It does not create tags.
## Decisions you should know about ## Decisions you should know about
### `minSdk = 26` (Android 8.0) ### `minSdk = 26` (Android 8.0)
@ -79,12 +95,24 @@ readelf -l android/sdk/build/rustJniLibs/arm64-v8a/libonionwire_sdk.so | grep LO
### Permissions ### Permissions
`INTERNET` only, declared at first launch. No camera (invites are pasted, not `INTERNET` is the only permission requested at first launch. No camera (invites
scanned), no contacts, no storage permission — the data directory is are pasted, not scanned), no contacts, no storage permission — the data
`context.filesDir`, which is already app-private. There is **no** directory is `context.filesDir`, which is already app-private.
`FOREGROUND_SERVICE` and no keep-alive notification in v1: the node lives only
while the process does, and the UI says so. Adding one is a product decision The node is **not** process-lifetime-only. After unlock, `KeepAliveService` is
(battery, Play's FGS type declarations), not a silent fix. a foreground service (`specialUse`, not `dataSync`) with an ongoing
notification so the onion stays published across Doze and backgrounding. The
manifest therefore also declares:
* `FOREGROUND_SERVICE`
* `FOREGROUND_SERVICE_SPECIAL_USE`
* `POST_NOTIFICATIONS` (API 33+; denial hides the drawer notification, it does
not stop the service)
`NodeHost` owns the single `Wire` handle. The service never does. Lock, or the
notification's Stop action, drops the keep-alive anchor; the node stays up
only while another owner (the UI) still holds it. `START_NOT_STICKY`: a
restarted empty service would show "reachable" over a dead onion.
### Data at rest ### Data at rest
@ -94,14 +122,67 @@ exclusions, because an auto-backup of `onionwire.db` would hand the wrapped
message key *and* the plaintext identity keys to Google Drive. Chat bodies are message key *and* the plaintext identity keys to Google Drive. Chat bodies are
encrypted at rest; identity keys are not — that is the locked v1 posture. encrypted at rest; identity keys are not — that is the locked v1 posture.
### The store passphrase at rest
Typing the passphrase on every launch is no longer required. On first unlock
the passphrase can be remembered (checkbox, on by default), and it is then
stored as an AES-256-GCM blob:
* the wrapping key is generated inside the **Android Keystore** under alias
`onionwire.store`, AES-256-GCM, `setUserAuthenticationRequired(false)` —
deliberately **not** biometric-gated, because a fingerprint prompt would turn
"the node opens or tells you why it did not" into "the node is unusable";
* **StrongBox is requested first** (`setIsStrongBoxBacked(true)`, guarded by
`FEATURE_STRONGBOX_KEYSTORE` on API 28+) and falls back to an ordinary
TEE-backed or software Keystore key when the chip refuses AES-256
(`StrongBoxUnavailableException is a ProviderException`). The fallback is
reported, not hidden: the lock screen prints what `KeyInfo` actually said,
and a software key is labelled **NOT hardware-backed**;
* only ciphertext + IV reach disk, at
`filesDir/secrets/store-passphrase.bin` — an `OWSEAL1` envelope of
magic + IV + ciphertext + GCM tag. No second copy, no `SharedPreferences`,
no plaintext in logs, and the typed `CharArray` is zeroed as soon as the
unlock call returns. The text field is a plain `remember`, so the typed
passphrase is never written into saved instance state;
* **Keystore invalidation is a supported path, not a crash.** A factory reset,
an app-data wipe, or a key the platform invalidates leaves a blob that cannot
authenticate: `StoredPassphraseStore.load()` returns `Unavailable`, the lock
screen explains it, and the user types the passphrase again. A failed read
does **not** delete the blob — a transient Keystore failure must not destroy
the only copy;
* `forget` deletes the blob **and** the Keystore key.
The one plaintext copy this cannot erase is the immutable `String` the UniFFI
binding takes (`openWire(home, passphrase: String)`). A follow-up SDK change
should accept the key (or a `ByteArray`) so the passphrase never becomes a
`String` at all.
`app/src/test/.../crypto/` covers the envelope and the file handling on the JVM
(the real `StoreSecret` code, with a JVM AES key standing in). The Keystore
provider only exists on a device:
```bash
./gradlew :app:connectedDebugAndroidTest # prints the KeyInfo/hardware report
```
### Signing ### Signing
Both `debug` and `release` are signed with the **standard debug keystore** Release APKs are signed with a **repo-owned keystore**, not the debug key.
(`~/.android/debug.keystore`, auto-created by AGP). This is what makes the
release APK installable for sideloading. It is **not** a Play upload key; * CI reads `ANDROID_KEYSTORE_BASE64`, `ANDROID_KEYSTORE_PASSWORD`,
nothing here should be uploaded to Play. When a real upload key exists, put it `ANDROID_KEY_ALIAS`, and `ANDROID_KEY_PASSWORD` from Forgejo repo secrets
in `~/.gradle/gradle.properties` or CI secrets and reference it from and writes them to `~/.android/onionwire-release.env` for the build.
`signingConfigs` — never in this repository. * Locally, `scripts/build-android-local.sh` sources that same env file if
present (`~/.android/onionwire-release.jks` + `.env`, mode 600). Local and
CI APKs then verify as the same cert and can upgrade in place.
* If the env file is missing, Gradle **warns** and signs with the debug
keystore so a laptop build still installs. CI's `android-release.yml` sets
`ONIONWIRE_REQUIRE_RELEASE_KEY=true` and **fails closed** instead — a
per-machine debug key would make every CI APK uninstallable over the last.
`android-ci.yml` deliberately does **not** set that: it is a verification
build and `apksigner` reporting the debug cert there is expected.
* Never commit a keystore, password, or `android/local.properties`. This is
not a Play upload key; nothing here should be uploaded to Play.
### Release builds are not minified ### Release builds are not minified
@ -111,12 +192,171 @@ path and an on-device test of the JNI surface is how you ship an
`UnsatisfiedLinkError` nobody can read. Turn it on together with crash `UnsatisfiedLinkError` nobody can read. Turn it on together with crash
deobfuscation, not before. deobfuscation, not before.
## CI ## Wallet child and chain sources (as Android sees them)
`.forgejo/workflows/release.yml` runs on an aarch64 Linux container on the Pi. Chain traffic is **off** until the user opens Wallet, picks a source, and
It cannot build an APK. Android artifacts are built on a host with the SDK/NDK presses Start. Receive-only is the default: no `monero-wallet-rpc` child, no
via `scripts/build-android-local.sh`, exactly like the x86_64 Linux binary is daemon, no P2P.
built via `scripts/build-release-local.sh`.
The app owns `monero-wallet-rpc` (issue #107). It is still a **child process**,
exec'd from `applicationInfo.nativeLibraryDir/libmonerowalletrpc.so`. Cuprate
has no wallet layer — an in-process node does not replace that binary.
Sources the screen offers:
1. **Receive-only** — no child, no chain.
2. **A daemon address you type** — loopback or clearnet. Wallet RPC itself is
loopback only. A `.onion` host is refused while `libarti.so` is absent
(`ONION_NEEDS_ARTI_NOTICE`); this APK does not bundle `arti`.
3. **On-device node (Cuprate)** — opt-in. Selecting it stores
`ChainChoice.InProcessCuprate` with an empty `monerod_datadir`, which the
SDK resolves to `$ONIONWIRE_HOME/chain`. Kotlin never invents an absolute
path. The pre-production warning (`CUPRATE_PREPRODUCTION_WARNING`) sits
**above Start**, not after. The screen can store testnet, mainnet-pruned, or
mainnet-full (and applies the matching storage floor); **mainnet remains
unvalidated** and the warning says so. Cross-compiled is not device-proven.
See [CUPRATE_DAEMON.md](CUPRATE_DAEMON.md).
Start is gated on the bundled wallet-rpc binary, on the storage floor for the
chosen Cuprate mode, and on the `.onion`/arti check. The floors are floors, not
sync estimates — nothing in this stack exposes a chain size:
| Mode | Floor |
|---|---|
| testnet | 3 GiB |
| mainnet pruned | 64 GiB |
| mainnet full | 280 GiB |
Unreadable free space (`StatFs` failed) is fail-closed: Start stays blocked.
### Status line
`ui/WalletChildStatusText.kt` is the pure model. The line renders the core's
words verbatim (`off` / `connecting` / `syncing` / `ready` / `exited`), then
the chain-source label, then — for the in-process source only — `node <word>`
from `WalletChildStatus.node_state`. An unrecognised word is never rendered as
ready.
When the last probe reported a non-zero height or target, the line grows
` · sync h/t`. That is the **daemon's** chain height, not the wallet's scan
height. `0/0` is omitted (unknown), not printed as 0%. There is **no
percentage, no progress bar, and no ETA** anywhere in the UI. The same string
is the row's screen-reader `contentDescription`.
Honest limit of the in-process node word: a daemon that dies *after* the wallet
child came up cannot be reported `exited` — there is no separate pid for the
in-process daemon, the chain probe fails, and the state stays `syncing`.
`exited` still means the `monero-wallet-rpc` child is gone. Details:
[CUPRATE_DAEMON.md](CUPRATE_DAEMON.md#what-has-not-been-proven).
### What the APK refresh loop actually calls
`WireViewModel.openWalletChild()` runs `walletChildRefreshLoop` with a 2 s
tick (`WALLET_CHILD_TICK_MS = 2_000`):
1. **First paint** — `paintWalletChildCached()` → `Wire.walletStatus()`
(`Wire::wallet_status`). Cached, no dial, so the screen has a record
while the first probe is still in flight.
2. **Every tick after that** — `refreshWalletChild()` →
`Wire.walletChildRefresh()` (`Wire::wallet_child_refresh`). That dials
the child's loopback wallet RPC, and the configured local daemon's
`get_info` when the wallet RPC does not answer, which is what makes
`sync h/t` move without another Start. It never spawns a child. With no
live child the core short-circuits to the cached `off` / `exited`
snapshot, so this cannot invent `ready`.
The loop suspends on each read before it sleeps: a probe slower than 2 s
delays the next tick instead of overlapping it. Do not run two concurrent
`wallet_child_refresh` calls against one child.
See [docs/WALLET.md](../docs/WALLET.md) (Android / SDK) for the same two
methods as the UniFFI surface.
## CI and releases
A merge to `main` does **not** publish an APK. Neither does a tag push.
Releases are manual and batched: two dispatches. Full procedure:
[docs/RELEASING.md](../docs/RELEASING.md).
### `android-ci.yml` (verification, not a release)
Runs on `docker-amd64` (T480 dind) for every `push`/`pull_request` whose paths
include `android/**`, `src/**`, `crates/**`, `Cargo.toml`, `Cargo.lock`,
`scripts/build-android-local.sh`, or the workflow itself — plus
`workflow_dispatch`. Job image is `node:20-bullseye` (EOL) — **do not apt-get
there**. The toolchain runs in a sibling `debian:bookworm` container
(stdin-tar + `docker cp`). Both Android workflows install `cmake` in that
container (RandomX).
It calls `scripts/build-android-local.sh` with the **debug** key
(`ONIONWIRE_REQUIRE_RELEASE_KEY` unset). Nothing is published. After the APK
is built it greps `lib/arm64-v8a/libonionwire_sdk.so` for `target_max_memory`
and **fails** if that cuprated-only string is missing.
### `android-release.yml` (the APK that lands on a tag)
`on:` is `workflow_dispatch` (and a declared `workflow_call` that this Forgejo
10.0.3 instance cannot invoke). **No `push` trigger.** Inputs:
| Input | Default | Meaning |
|---|---|---|
| `tag` | empty | Existing tag to check out, build, and attach. |
| `dry_run` | `false` | Build and checksum; skip the Pi publish job. |
Operator path, after `release.yml` has minted the tag (`dry_run=true` on that
workflow first):
1. Actions → **android-release** → Run workflow, `tag=vX.Y.Z` (the tag core
just created), `dry_run=false`.
2. The Android job **checks out that tag** (`ref:` is the tag, not `main`) and
stamps `versionName` / `versionCode` from it.
3. `versionCode` is `major*10000 + minor*100 + patch` (so 0.5.0 → 500).
4. Publish is a second job on the Pi runner (`docker`). It attaches
`onionwire-<version>-android-arm64-v8a.apk`, `onionwire-sdk-<version>.aar`,
and both `.sha256` files to **that same tag**.
The APK is built from **the tag's tree**. Building from `main` and stamping a
tag you did not check out is how you ship a binary that does not match the
tag.
**Empty `tag` is the foot-gun.** Checkout then falls back to `github.sha`
(usually `main` HEAD). Version is *not* "latest `v*.*.*` plus patch" as a
rule:
* no tags at all → `0.1.0`;
* latest `v*.*.*` release is **missing** the Android APK (or the job cannot
inspect the release) → **join** that version: same `versionName` restamped
onto whatever tree was checked out. Android will refuse to install that APK
over an already-installed build of the same `versionName`/`versionCode`;
* latest tag already has an Android APK → `patch+1` of that version, still
built from `github.sha`, and this workflow may then **create** that new tag
at publish time if it does not exist.
Do not dispatch `android-release` with an empty `tag` to ship a release. Core
owns minting (`release.yml`, default `bump=minor`). This workflow attaches.
`workflow_dispatch` with `dry_run=true` builds and checksums without
publishing. `scripts/build-android-local.sh` remains the offline fallback; it
does not create tags.
The Android job image / bookworm-container story is the same as `android-ci.yml`.
The cuprated graph is built with Rust 1.98 here, the same floor as `ci.yml`
(`rust-version = "1.98"`). Job timeout is **90** minutes on `android-release.yml` and **120**
on `android-ci.yml`.
## App shell
Three top-level destinations, one persistent bottom tab bar
(`ui/components/BottomTabBar.kt`): **Chats** (default), **Wallet**, and **Node &
Settings**. Sub-screens (chat, invite share, add contact, rotate, profile, saved
wallets) keep a chevron back button and hide the bar. The rare and destructive
actions — rotate identity, delete message history, saved wallets — are behind the
`⋮` overflow and a typed confirmation, not on the home screen.
Colours, radii and type live in `ui/Theme.kt` as `OwColors` / `OwRadius` /
`OwSize`; new UI takes tokens from there instead of `MaterialTheme` defaults.
Monospace is reserved for pubkeys, truncated onion locators, seeds, `host:port`
and block heights — never for a sentence.
## Layout ## Layout
@ -125,14 +365,46 @@ android/
settings.gradle.kts settings.gradle.kts
build.gradle.kts # plugin aliases only build.gradle.kts # plugin aliases only
gradle/libs.versions.toml # version catalog gradle/libs.versions.toml # version catalog
gradle/wrapper/
monero-binaries.sha256 # provenance of the bundled wallet-rpc blob
CUPRATE_DAEMON.md
MONERO_BINARIES.md
sdk/ # -> AAR sdk/ # -> AAR
build.gradle.kts # cargo-ndk + uniffi-bindgen wiring build.gradle.kts # cargo-ndk + uniffi-bindgen wiring
consumer-rules.pro consumer-rules.pro
src/main/AndroidManifest.xml src/main/AndroidManifest.xml
app/ # -> APK app/ # -> APK
build.gradle.kts build.gradle.kts
src/main/AndroidManifest.xml
src/main/java/com/siriusdevops/onionwire/ src/main/java/com/siriusdevops/onionwire/
MainActivity.kt # NavHost MainActivity.kt # app shell: bottom tabs + NavHost
WireViewModel.kt # owns the single Wire node WireViewModel.kt # UI-side Wire handle; wallet-child poller
crypto/ # Keystore-wrapped store passphrase
keepalive/ # NodeHost, KeepAliveService, policy, lifetime
wallet/ # ChainStorage, WalletChildBinaries
ui/ # Compose screens (M3) ui/ # Compose screens (M3)
components/ # design system: OwButton, OwSegmentedControl,
# OwAlertBanner, OwCard, OwTopBar, OwBottomTabBar,
# OwConfirmDialog, OwQrCode, Identicon
WalletScreen.kt
WalletManagerScreen.kt
WalletChildStatusText.kt
ChatScreen.kt
RosterScreen.kt # Chats tab: identity bar + roster
SettingsScreen.kt # Node & Settings tab
ProfileScreen.kt
InviteScreens.kt # share (QR + text) and paste-a-contact
InviteAddFlow.kt
OutboxDetail.kt
MessageDelivery.kt
UnlockScreen.kt
UnlockSubmit.kt
SeedBackupGate.kt
RotateScreen.kt
Insets.kt # systemBars ∪ ime, minus the tab-bar inset
Theme.kt # design tokens: palette, radii, sizes, typography
src/main/res/drawable/ic_ow_*.xml # single-colour design-system icons
src/test/ # JVM: envelope, store, invite, outbox, keepalive, wallet line, refresh loop
src/androidTest/ # device-only: AndroidKeyStore
src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so
``` ```

View file

@ -6,6 +6,9 @@ plugins {
alias(libs.plugins.kotlin.compose) alias(libs.plugins.kotlin.compose)
} }
fun envOrNull(name: String): String? =
System.getenv(name)?.takeIf { it.isNotBlank() }
android { android {
namespace = "com.siriusdevops.onionwire" namespace = "com.siriusdevops.onionwire"
compileSdk = 36 compileSdk = 36
@ -21,13 +24,31 @@ android {
applicationId = "com.siriusdevops.onionwire" applicationId = "com.siriusdevops.onionwire"
minSdk = 26 minSdk = 26
targetSdk = 36 targetSdk = 36
versionCode = 1 // CI/local release scripts override both via -P. Committed values are
versionName = "0.1.0" // the offline default and match the first automated tag (v0.1.0 → 100).
versionCode = (findProperty("onionwire.versionCode") as String?)?.toIntOrNull() ?: 100
versionName = (findProperty("onionwire.versionName") as String?) ?: "0.1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
ndk { ndk {
abiFilters += onionwireAbis abiFilters += onionwireAbis
} }
} }
signingConfigs {
create("release") {
val ksPath = envOrNull("ANDROID_KEYSTORE_FILE")
if (ksPath != null) {
storeFile = file(ksPath)
storePassword = envOrNull("ANDROID_KEYSTORE_PASSWORD")
?: error("ANDROID_KEYSTORE_PASSWORD is required when ANDROID_KEYSTORE_FILE is set")
keyAlias = envOrNull("ANDROID_KEY_ALIAS")
?: error("ANDROID_KEY_ALIAS is required when ANDROID_KEYSTORE_FILE is set")
keyPassword = envOrNull("ANDROID_KEY_PASSWORD")
?: error("ANDROID_KEY_PASSWORD is required when ANDROID_KEYSTORE_FILE is set")
}
}
}
buildTypes { buildTypes {
debug { debug {
// Sideload / device-test builds. Signed with the standard debug key. // Sideload / device-test builds. Signed with the standard debug key.
@ -43,9 +64,28 @@ android {
// :sdk/consumer-rules.pro. // :sdk/consumer-rules.pro.
isMinifyEnabled = false isMinifyEnabled = false
isShrinkResources = false isShrinkResources = false
// Signed with the debug keystore so the release APK installs. // Repo-owned release keystore via ANDROID_KEYSTORE_* env (Forgejo
// This is NOT a Play upload key — see android/README.md. // secrets in CI, ~/.android/onionwire-release.env locally). CI sets
signingConfig = signingConfigs.getByName("debug") // ONIONWIRE_REQUIRE_RELEASE_KEY=true and fails closed if missing —
// the debug keystore is per-machine and would break in-place upgrades.
val requireReleaseKey =
(findProperty("onionwire.requireReleaseKey") as String?) == "true" ||
envOrNull("ONIONWIRE_REQUIRE_RELEASE_KEY") == "true"
val releaseSigning = signingConfigs.getByName("release")
val releaseStore = releaseSigning.storeFile
signingConfig = when {
releaseStore != null && releaseStore.isFile -> releaseSigning
requireReleaseKey -> error(
"Release keystore required but ANDROID_KEYSTORE_FILE is missing or not a file"
)
else -> {
logger.warn(
"No ANDROID_KEYSTORE_FILE; signing the release APK with the debug keystore. " +
"CI must not do this — in-place upgrades will break."
)
signingConfigs.getByName("debug")
}
}
} }
} }
@ -62,6 +102,23 @@ android {
resources { resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}" excludes += "/META-INF/{AL2.0,LGPL2.1}"
} }
jniLibs {
// `android:extractNativeLibs="true"`. This is what puts
// `libmonerowalletrpc.so` on disk in `ApplicationInfo.nativeLibraryDir`
// at install time, which is the ONLY directory Android lets an app
// `exec()` from (since API 29 a file in `filesDir` is not executable
// whatever its mode bits say). With the AGP 8 default
// (`extractNativeLibs="false"`) the wallet binary would stay inside
// the APK and `start_wallet_child` would fail with ENOENT on a path
// that looks correct. See android/MONERO_BINARIES.md.
useLegacyPackaging = true
// The wallet child is an executable, not a linked library, and
// scripts/build-monero-wallet-rpc-android.sh already stripped it with
// the target's own strip. Excluding it from AGP's strip pass keeps the
// bytes in the APK identical to the committed blob, which is what
// scripts/build-android-local.sh verifies in CI.
keepDebugSymbols += "**/libmonerowalletrpc.so"
}
} }
} }
@ -90,4 +147,13 @@ dependencies {
testImplementation(libs.junit) testImplementation(libs.junit)
testImplementation(libs.kotlinx.coroutines.test) testImplementation(libs.kotlinx.coroutines.test)
// Device-only: the AndroidKeyStore provider does not exist in the unit-test
// JVM. These run under `./gradlew :app:connectedDebugAndroidTest`.
androidTestImplementation(libs.junit)
androidTestImplementation(libs.androidx.test.ext.junit)
androidTestImplementation(libs.androidx.test.runner)
// QR code rendering for the wallet receive-address screen.
implementation(libs.zxing)
} }

View file

@ -0,0 +1,450 @@
package com.siriusdevops.onionwire.crypto
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Log
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File
import java.security.KeyStore
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
/**
* The device half of the Keystore story. The unit-test JVM has no
* `AndroidKeyStore` provider, so nothing here can run as a plain JUnit test.
*
* Run on a real device or an emulator:
*
* ./gradlew :app:connectedDebugAndroidTest
*
* and read the `OnionWireKeystore` tag in logcat for the actual
* `KeyInfo`/`isInsideSecureHardware`/`securityLevel` report — the point of
* [key_backing_is_reported_and_logged] is to print the truth, not to assert a
* hardware-backed key on hardware that does not have one.
*
* The migration tests below are the device half of the device-unlock gate:
* a pre-gate key is retired **only** after the replacement blob opens under the
* new key, and an interrupted migration leaves an install that still unlocks.
* They also log `MANUFACTURER`/`MODEL`/`SDK_INT` and the branch taken, because
* `setUnlockedDeviceRequired` is an OEM-sensitive flag and a red test on a
* specific phone is only diagnosable with that line.
*/
@RunWith(AndroidJUnit4::class)
class KeystorePassphraseCipherTest {
private val context: Context =
InstrumentationRegistry.getInstrumentation().targetContext
private val cipher = KeystorePassphraseCipher(context)
private val passphrase = "correct horse battery staple".toCharArray()
@Before
fun cleanSlate() {
// Both aliases: a leftover gated key from an aborted run would hide a
// migration that never happened.
val store = keyStore()
for (alias in listOf(KeystorePassphraseCipher.ALIAS_UNLOCK_GATED, KeystorePassphraseCipher.ALIAS)) {
try {
store.deleteEntry(alias)
} catch (_: Exception) {
// Nothing to delete.
}
}
}
@After
fun tearDown() {
cipher.deleteKey()
}
@Test
fun seal_open_round_trips_through_the_android_keystore() {
val blob = cipher.seal(passphrase)
assertTrue(
"envelope is magic + IV + ciphertext + tag",
blob.size >= passphrase.size + StoreSecret.IV_BYTES + 16 + 9,
)
val out = cipher.open(blob)
try {
assertArrayEquals(passphrase, out)
} finally {
StoreSecret.wipe(out)
}
}
@Test
fun stored_blob_on_a_device_is_not_the_plaintext() {
val dir = File(context.filesDir, "secrets-test")
dir.mkdirs()
val store = StoredPassphraseStore(File(dir, "store-passphrase.bin"), cipher)
try {
store.save(passphrase)
val raw = File(store.path).readBytes()
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
assertFalse(
"the passphrase must not appear in the file",
String(raw, Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)),
)
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
try {
assertArrayEquals(passphrase, loaded.passphrase)
} finally {
StoreSecret.wipe(loaded.passphrase)
}
} finally {
store.forget()
dir.deleteRecursively()
}
}
@Test
fun key_backing_is_reported_and_logged() {
cipher.seal(passphrase) // force key creation
val strongBoxAdvertised = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
val backing = cipher.backing()
val gate = cipher.unlockGateReport()
Log.i(
TAG,
"alias=${KeystorePassphraseCipher.ALIAS} backing=$backing " +
"strongBoxAdvertised=$strongBoxAdvertised " +
"sdk=${Build.VERSION.SDK_INT} device=${Build.MANUFACTURER} ${Build.MODEL} " +
"gate=${gate.describe()}",
)
if (strongBoxAdvertised) {
assertTrue(
"StrongBox is advertised but the key did not land in a secure element: $backing",
backing == KeyBacking.STRONGBOX || backing == KeyBacking.HARDWARE,
)
} else {
assertNotEquals("the API refused to report the backing at all", KeyBacking.UNKNOWN, backing)
}
}
@Test
fun open_does_not_require_user_authentication() {
// The card's contract: unlocking must not need a fingerprint. If the
// key had been created with setUserAuthenticationRequired(true), this
// open() would throw UserNotAuthenticatedException. The device-unlock
// gate is a different flag: it only refuses while the lock screen is up,
// which is not the case while this test runs.
val out = cipher.open(cipher.seal(passphrase))
StoreSecret.wipe(out)
assertTrue(cipher.keyPresent())
}
@Test
fun deleted_key_reports_unavailable_instead_of_crashing() {
val blob = cipher.seal(passphrase)
cipher.deleteKey()
assertFalse(cipher.keyPresent())
try {
cipher.open(blob)
fail("expected SecretUnavailable after the key was deleted")
} catch (e: SecretUnavailable) {
assertTrue(e.message!!.contains("gone"))
}
}
@Test
fun a_regenerated_key_cannot_open_an_old_blob() {
val blob = cipher.seal(passphrase)
cipher.deleteKey() // a reset that leaves the app's data dir intact
cipher.seal(passphrase) // same alias, brand-new key
try {
cipher.open(blob)
fail("expected SecretUnavailable for a blob wrapped by the deleted key")
} catch (_: SecretUnavailable) {
}
}
// ------------------------------------------------------- device-unlock gate
/**
* The upgrade path: an install that stored its passphrase before the gate
* landed has one pre-gate key and a blob wrapped by it. The next successful
* unlock re-wraps that blob under a newly generated unlock-gated key, proves
* it, and only then retires the old alias.
*/
@Test
fun a_pre_flag_key_is_migrated_to_the_unlock_gated_alias_on_unlock() {
val branch = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
"unlock-gated (API >= 28)"
} else {
"ungated (API < 28 — setUnlockedDeviceRequired unavailable)"
}
Log.i(
TAG,
"migration: manufacturer=${Build.MANUFACTURER} model=${Build.MODEL} " +
"sdk=${Build.VERSION.SDK_INT} branch=$branch",
)
val legacy = createPreFlagKey()
val dir = File(context.filesDir, "secrets-migration")
dir.mkdirs()
val store = StoredPassphraseStore(File(dir, "store-passphrase.bin"), cipher)
try {
val blob = StoreSecret.seal(legacy, passphrase)
try {
File(store.path).writeBytes(blob)
} finally {
StoreSecret.wipe(blob)
}
assertTrue("precondition: the pre-gate alias exists", hasAlias(KeystorePassphraseCipher.ALIAS))
assertFalse(
"precondition: no gated key yet",
hasAlias(KeystorePassphraseCipher.ALIAS_UNLOCK_GATED),
)
// The unlock path: load() is where the passphrase is in hand.
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
try {
assertArrayEquals("the unlock must still return the passphrase", passphrase, loaded.passphrase)
} finally {
StoreSecret.wipe(loaded.passphrase)
}
val gate = cipher.unlockGateReport()
Log.i(TAG, "migration: after=${gate.describe()} legacyPending=${gate.legacyKeyPending}")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
assertTrue(
"expected a gated key after the re-wrap: ${gate.describe()}",
hasAlias(KeystorePassphraseCipher.ALIAS_UNLOCK_GATED),
)
assertFalse(
"the pre-gate key must be retired once the new blob verifies: ${gate.describe()}",
hasAlias(KeystorePassphraseCipher.ALIAS),
)
assertTrue("the report must say the live key is gated: ${gate.describe()}", gate.keyIsUnlockGated)
assertFalse("nothing may stay pending: ${gate.describe()}", gate.legacyKeyPending)
// The blob on disk must open under the NEW key alone — this is
// the proof the alias delete was allowed to happen.
val onDisk = File(store.path).readBytes()
val back = try {
StoreSecret.open(requireNotNull(gatedKey()), onDisk)
} finally {
StoreSecret.wipe(onDisk)
}
try {
assertArrayEquals(passphrase, back)
} finally {
StoreSecret.wipe(back)
}
} else {
assertFalse(
"API 26–27 has no flag, so no gated key may be invented",
hasAlias(KeystorePassphraseCipher.ALIAS_UNLOCK_GATED),
)
assertTrue("below API 28 the pre-gate key stays", hasAlias(KeystorePassphraseCipher.ALIAS))
}
} finally {
store.forget()
dir.deleteRecursively()
}
}
/**
* Every failure before "the new blob verified" must leave the previous blob
* and the pre-gate key in place. The simulated failure is the proof step
* itself, which is exactly the step that guards the alias delete.
*/
@Test
fun a_failed_re_wrap_keeps_the_pre_gate_key_and_the_previous_blob() {
val legacy = createPreFlagKey()
val dir = File(context.filesDir, "secrets-failed-migration")
dir.mkdirs()
val file = File(dir, "store-passphrase.bin")
try {
val oldBlob = StoreSecret.seal(legacy, passphrase)
try {
file.writeBytes(oldBlob)
} finally {
StoreSecret.wipe(oldBlob)
}
val before = file.readBytes()
try {
val doomed = StoredPassphraseStore(file, FailingVerifyCipher(cipher))
try {
doomed.save(passphrase)
fail("expected the simulated verification failure")
} catch (e: SecretUnavailable) {
assertTrue(
"the reason must say the old copy was kept: ${e.message}",
e.message!!.contains("previous blob and key were kept"),
)
}
assertTrue(
"the pre-gate key must survive a failed re-wrap",
hasAlias(KeystorePassphraseCipher.ALIAS),
)
assertFalse(
"a failed re-wrap must not leave a temp blob behind",
File(dir, "store-passphrase.bin.tmp").exists(),
)
assertArrayEquals(
"the previous blob must be untouched by a failed re-wrap",
before,
file.readBytes(),
)
} finally {
StoreSecret.wipe(before)
}
// The previous blob is byte-for-byte intact and still opens with the
// pre-gate key: an install that has not migrated is still usable.
val untouched = file.readBytes()
try {
val back = StoreSecret.open(requireNotNull(legacyKey()), untouched)
try {
assertArrayEquals(passphrase, back)
} finally {
StoreSecret.wipe(back)
}
} finally {
StoreSecret.wipe(untouched)
}
// A save that can verify finishes the migration on the spot.
StoredPassphraseStore(file, cipher).save(passphrase)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
assertFalse(
"the pre-gate key is retired as soon as the re-wrap verifies",
hasAlias(KeystorePassphraseCipher.ALIAS),
)
assertTrue(hasAlias(KeystorePassphraseCipher.ALIAS_UNLOCK_GATED))
}
} finally {
cipher.deleteKey()
dir.deleteRecursively()
}
}
/**
* The mirror of [a_pre_flag_key_is_migrated_to_the_unlock_gated_alias_on_unlock]:
* the proof step must use the gated key only. A fallback decrypt succeeding
* must never be mistaken for "the new blob is wrapped by the new key" — that
* is what would allow the alias delete to destroy the only working copy.
*/
@Test
fun the_gated_proof_refuses_a_blob_wrapped_by_the_pre_gate_key() {
val legacy = createPreFlagKey()
val blob = StoreSecret.seal(legacy, passphrase)
try {
cipher.seal(passphrase) // creates the gated key; the legacy key still exists
try {
cipher.openWithUnlockGate(blob)
fail("a pre-gate blob must not verify under the unlock-gated key")
} catch (_: SecretUnavailable) {
// On API 26–27 there is no gated key at all, so this is the
// "no key to prove against" refusal. Both are refusals.
}
} finally {
StoreSecret.wipe(blob)
}
}
/** The crash window: gated key created, blob not yet replaced. Must still open. */
@Test
fun a_blob_wrapped_by_the_pre_gate_key_still_opens_while_both_keys_exist() {
val legacy = createPreFlagKey()
val blob = StoreSecret.seal(legacy, passphrase)
try {
cipher.seal(passphrase) // gated key now exists too
val out = cipher.open(blob)
try {
assertArrayEquals(passphrase, out)
} finally {
StoreSecret.wipe(out)
}
} finally {
StoreSecret.wipe(blob)
}
}
// ------------------------------------------------------------------ helpers
private fun keyStore(): KeyStore =
KeyStore.getInstance(KeystorePassphraseCipher.PROVIDER).apply { load(null) }
private fun hasAlias(alias: String): Boolean = keyStore().containsAlias(alias)
private fun key(alias: String): SecretKey? = keyStore().getKey(alias, null) as? SecretKey
private fun gatedKey(): SecretKey? = key(KeystorePassphraseCipher.ALIAS_UNLOCK_GATED)
private fun legacyKey(): SecretKey? = key(KeystorePassphraseCipher.ALIAS)
/**
* Reproduces the key the app generated before the device-unlock gate
* existed: AES-256-GCM under [KeystorePassphraseCipher.ALIAS], no user-auth
* requirement, no unlock requirement. This is the install state the
* migration test starts from, not a new production path.
*/
private fun createPreFlagKey(): SecretKey {
val spec = KeyGenParameterSpec.Builder(
KeystorePassphraseCipher.ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(StoreSecret.KEY_BITS)
.setRandomizedEncryptionRequired(true)
.setUserAuthenticationRequired(false)
.build()
val generator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES,
KeystorePassphraseCipher.PROVIDER,
)
generator.init(spec)
return generator.generateKey()
}
/**
* Delegates to the real Keystore cipher except for the proof step, so the
* "the old key is deleted only after the new blob verifies" ordering can be
* asserted on a device without a way to corrupt a real Keystore blob.
*/
private class FailingVerifyCipher(
private val real: KeystorePassphraseCipher,
) : PassphraseCipher by real, PassphraseKeyMigration {
override fun unlockGateInEffect(): Boolean = real.unlockGateInEffect()
override fun legacyKeyPending(): Boolean = real.legacyKeyPending()
override fun openWithUnlockGate(blob: ByteArray): CharArray =
throw SecretUnavailable("simulated verify failure")
override fun retireLegacyKey() = real.retireLegacyKey()
override fun noteMigrationFailure(reason: String) = real.noteMigrationFailure(reason)
}
private companion object {
const val TAG = KeystorePassphraseCipher.TAG
}
}

View file

@ -4,10 +4,33 @@
<!-- <!--
INTERNET is the only permission requested at first launch. INTERNET is the only permission requested at first launch.
No camera (invites are typed/pasted, not scanned), no contacts, no No camera (invites are typed/pasted, not scanned), no contacts, no
storage. Tor runs in-process; there is no foreground service and no storage.
keep-alive notification in v1, so the node only lives while the app does.
Tor runs in-process, and the node is kept published across Doze and
backgrounding by KeepAliveService: a foreground service with an ongoing
notification, started on unlock, stopped by Lock or by the notification's
Stop action. Its anchors and the node's lifetime are arbitrated in
NodeHost/NodeLifetime; the service never owns the node itself.
--> -->
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!--
specialUse, not dataSync. dataSync is documented as "data transfer
operations" (upload/download, backup/restore, import/export) and the
official alternatives guide points at WorkManager or a user-initiated
transfer job — all of which assume a transfer with an end. A node holding
an inbound onion service open and draining a retry queue has no end and no
progress to report, so specialUse ("valid foreground service use cases
that aren't covered by the other types") is the honest declaration. It
costs a Play Console justification; dataSync would cost a lie.
-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<!-- API 33+. Without it the keep-alive still runs, but its notification is
hidden from the drawer (the user sees the service in the Task Manager
instead). Denial is handled, not fatal: see WireViewModel.keepAliveNote. -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application <application
android:allowBackup="false" android:allowBackup="false"
@ -15,7 +38,7 @@
android:fullBackupContent="false" android:fullBackupContent="false"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.OnionWire"> android:theme="@style/Theme.OnionWire">
@ -30,6 +53,21 @@
</intent-filter> </intent-filter>
</activity> </activity>
<!--
Not exported: only this app starts it, from a user-visible unlock.
stopWithTask is left at its default (false) on purpose — swiping the
task away must not take the onion offline; the activity is destroyed,
NodeHost flushes the outbox, and the onion stays published.
-->
<service
android:name=".keepalive.KeepAliveService"
android:exported="false"
android:foregroundServiceType="specialUse">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="peer-to-peer messaging node: keeps an inbound onion service published and an outbox retry queue running so peers can deliver messages while the app is backgrounded; there is no user-initiated transfer to bound the work" />
</service>
</application> </application>
</manifest> </manifest>

View file

@ -1,36 +1,68 @@
package com.siriusdevops.onionwire package com.siriusdevops.onionwire
import android.Manifest
import android.os.Build
import android.os.Bundle import android.os.Bundle
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.core.view.WindowCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.NavType import androidx.navigation.NavType
import androidx.navigation.compose.NavHost import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument import androidx.navigation.navArgument
import com.siriusdevops.onionwire.ui.ChatScreen import com.siriusdevops.onionwire.ui.ChatScreen
import com.siriusdevops.onionwire.ui.LocalBottomBarPresent
import com.siriusdevops.onionwire.ui.OnionWireTheme
import com.siriusdevops.onionwire.ui.PasteInviteScreen import com.siriusdevops.onionwire.ui.PasteInviteScreen
import com.siriusdevops.onionwire.ui.ProfileScreen
import com.siriusdevops.onionwire.ui.RosterScreen import com.siriusdevops.onionwire.ui.RosterScreen
import com.siriusdevops.onionwire.ui.RotateScreen import com.siriusdevops.onionwire.ui.RotateScreen
import com.siriusdevops.onionwire.ui.SettingsScreen
import com.siriusdevops.onionwire.ui.ShareInviteScreen import com.siriusdevops.onionwire.ui.ShareInviteScreen
import com.siriusdevops.onionwire.ui.UnlockScreen import com.siriusdevops.onionwire.ui.UnlockScreen
import com.siriusdevops.onionwire.ui.OnionWireTheme import com.siriusdevops.onionwire.ui.WalletManagerScreen
import com.siriusdevops.onionwire.ui.WalletScreen
import com.siriusdevops.onionwire.ui.components.OwBottomTabBar
import com.siriusdevops.onionwire.ui.components.OwTab
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
enableEdgeToEdge() enableEdgeToEdge()
// The shell paints the canvas to the bottom of the screen behind the tab
// bar; the system's translucent three-button scrim would draw a second,
// lighter band over it (edge-to-edge guidance, SDK 29+).
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
window.isNavigationBarContrastEnforced = false
}
// enableEdgeToEdge() from ComponentActivity sets the icon appearance from
// the system theme; the app is dark-only, so the bars are always dark with
// light icons. Re-assert it here in case the theme changes under us.
WindowCompat.getInsetsController(window, window.decorView).apply {
isAppearanceLightStatusBars = false
isAppearanceLightNavigationBars = false
}
setContent { setContent {
OnionWireTheme { OnionWireTheme {
Surface( Surface(
@ -47,40 +79,145 @@ class MainActivity : ComponentActivity() {
@Composable @Composable
private fun AppRoot(vm: WireViewModel = viewModel()) { private fun AppRoot(vm: WireViewModel = viewModel()) {
val phase by vm.phase.collectAsStateWithLifecycle() val phase by vm.phase.collectAsStateWithLifecycle()
val unlock by vm.unlock.collectAsStateWithLifecycle()
val keepAliveNote by vm.keepAliveNote.collectAsStateWithLifecycle()
// Asked in context: the notification is the keep-alive's only visible
// trace, so the prompt lands when the node becomes reachable rather than at
// first launch. Denial is not fatal — the service runs either way and the
// settings screen says the notice is hidden.
val askNotifications = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission(),
) { vm.onNotificationPermissionChanged() }
LaunchedEffect(phase) {
if (phase is Phase.Ready &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
!vm.notificationsAllowed()
) {
askNotifications.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
when (val p = phase) { when (val p = phase) {
is Phase.Ready -> ReadyGraph(vm, p) is Phase.Ready -> ReadyGraph(vm, p, keepAliveNote)
else -> UnlockScreen(phase = p, onUnlock = vm::unlock) else -> UnlockScreen(
phase = p,
unlock = unlock,
onUnlock = vm::unlock,
onUnlockStored = vm::unlockStored,
onForgetStored = vm::forgetStoredPassphrase,
)
} }
} }
/** Top-level destinations. Everything else is a sub-screen with a chevron. */
private object Routes {
const val Chats = "chats"
const val Wallet = "wallet"
const val Settings = "settings"
const val Share = "share"
const val Paste = "paste"
const val Rotate = "rotate"
const val Profile = "profile"
const val Wallets = "wallets"
const val Chat = "chat/{pk}"
fun tabOf(route: String?): OwTab? = when (route) {
Chats -> OwTab.Chats
Wallet -> OwTab.Wallet
Settings -> OwTab.Settings
else -> null
}
fun routeOf(tab: OwTab): String = when (tab) {
OwTab.Chats -> Chats
OwTab.Wallet -> Wallet
OwTab.Settings -> Settings
}
}
/**
* The app shell.
*
* A `Scaffold` whose only job is the persistent bottom tab bar: it owns the
* navigation-bar inset, the screens keep owning their own top bars and system
* insets (see `screenContentInsets`), and `LocalBottomBarPresent` tells those
* screens not to pad for the bar a second time.
*
* Selecting a tab pops back to the start destination and restores that tab's
* saved state, so a chat left open behind the Wallet tab is still there when the
* user comes back — the standard bottom-nav contract.
*/
@Composable @Composable
private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready) { private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: String?) {
val nav = rememberNavController() val nav = rememberNavController()
val friends by vm.friends.collectAsStateWithLifecycle() val friends by vm.friends.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val entry by nav.currentBackStackEntryAsState()
val tab = Routes.tabOf(entry?.destination?.route)
NavHost(navController = nav, startDestination = "roster") { Scaffold(
composable("roster") { // Each screen's Scaffold applies its own bars; zeroing this one keeps the
// status bar from being padded twice and leaves the only inset this
// level owns — the tab bar's height — in `pad`.
contentWindowInsets = WindowInsets(0, 0, 0, 0),
containerColor = MaterialTheme.colorScheme.background,
bottomBar = {
if (tab != null) {
OwBottomTabBar(selected = tab, onSelect = { nav.selectTab(it) })
}
},
) { pad ->
CompositionLocalProvider(LocalBottomBarPresent provides (tab != null)) {
NavHost(
navController = nav,
startDestination = Routes.Chats,
modifier = Modifier.padding(bottom = pad.calculateBottomPadding()),
) {
composable(Routes.Chats) {
RosterScreen( RosterScreen(
fingerprint = ready.fingerprint, fingerprint = ready.fingerprint,
onion = ready.onion,
sdkVersion = ready.sdkVersion,
friends = friends, friends = friends,
invite = vm::invite,
onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") }, onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") },
onShare = { nav.navigate("share") }, onShare = { nav.navigate(Routes.Share) },
onPaste = { nav.navigate("paste") }, onPaste = { nav.navigate(Routes.Paste) },
onRotate = { nav.navigate("rotate") }, onRotate = { nav.navigate(Routes.Rotate) },
onWipe = { scope.launch { vm.wipeMessages() } },
onOpenProfile = { nav.navigate(Routes.Profile) },
onLock = vm::lock,
onOpenWallets = { nav.navigate(Routes.Wallets) },
)
}
composable(Routes.Wallet) {
// A top-level tab, so no back chevron — same shape as the
// Chats and Node & Settings destinations. The catalogue
// sub-screen still gets one from its own top bar.
WalletScreen(
vm = vm,
onOpenWallets = { nav.navigate(Routes.Wallets) },
)
}
composable(Routes.Settings) {
SettingsScreen(
sdkVersion = ready.sdkVersion,
keepAliveNote = keepAliveNote,
onOpenProfile = { nav.navigate(Routes.Profile) },
onOpenWallets = { nav.navigate(Routes.Wallets) },
onRotate = { nav.navigate(Routes.Rotate) },
onWipe = { scope.launch { vm.wipeMessages() } }, onWipe = { scope.launch { vm.wipeMessages() } },
onLock = vm::lock, onLock = vm::lock,
) )
} }
composable("share") { composable(Routes.Share) {
ShareInviteScreen(ownerInvite = vm::invite, onBack = { nav.popBackStack() }) ShareInviteScreen(ownerInvite = vm::invite, onBack = { nav.popBackStack() })
} }
composable("paste") { composable(Routes.Paste) {
PasteInviteScreen( PasteInviteScreen(
onDecode = vm::decode, onDecode = vm::decode,
onAdd = vm::addFriend, onAdd = vm::addFriend,
@ -88,7 +225,7 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready) {
) )
} }
composable("rotate") { composable(Routes.Rotate) {
RotateScreen( RotateScreen(
currentOnion = ready.onion, currentOnion = ready.onion,
onRotate = { onRotate = {
@ -99,22 +236,42 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready) {
) )
} }
composable(Routes.Wallets) {
WalletManagerScreen(vm = vm, onBack = { nav.popBackStack() })
}
composable(Routes.Profile) {
ProfileScreen(vm = vm, onBack = { nav.popBackStack() })
}
composable( composable(
route = "chat/{pk}", route = Routes.Chat,
arguments = listOf(navArgument("pk") { type = NavType.StringType }), arguments = listOf(navArgument("pk") { type = NavType.StringType }),
) { entry -> ) { chatEntry ->
val pk = entry.arguments?.getString("pk").orEmpty() val pk = chatEntry.arguments?.getString("pk").orEmpty()
val friend = friends.firstOrNull { it.pubkeyHex == pk } val friend = friends.firstOrNull { it.pubkeyHex == pk }
ChatScreen( ChatScreen(
vm = vm,
peer = pk,
title = friend?.petname?.takeIf { it.isNotBlank() } title = friend?.petname?.takeIf { it.isNotBlank() }
?: friend?.fingerprint ?: friend?.fingerprint
?: pk.take(16), ?: pk.take(16),
fingerprint = friend?.fingerprint ?: pk.take(16), fingerprint = friend?.fingerprint ?: pk.take(16),
onion = friend?.onion.orEmpty(), onion = friend?.onion.orEmpty(),
loadMessages = { vm.messages(pk) },
onSend = { body -> vm.send(pk, body) },
onBack = { nav.popBackStack() }, onBack = { nav.popBackStack() },
) )
} }
} }
}
}
}
private fun NavHostController.selectTab(target: OwTab) {
val route = Routes.routeOf(target)
if (currentDestination?.route == route) return
navigate(route) {
popUpTo(graph.startDestinationId) { saveState = true }
launchSingleTop = true
restoreState = true
}
} }

View file

@ -0,0 +1,463 @@
package com.siriusdevops.onionwire.crypto
import android.app.KeyguardManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyInfo
import android.security.keystore.KeyProperties
import android.security.keystore.UserNotAuthenticatedException
import android.util.Log
import java.security.GeneralSecurityException
import java.security.KeyStore
import java.security.ProviderException
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
/**
* AES-256-GCM key held by the Android Keystore, wrapping the store passphrase.
*
* The key material is never readable by this process (`SecretKey.encoded` is
* null for AndroidKeyStore keys) — that is the whole point: pulling
* `/data/data/com.siriusdevops.onionwire/` off a rooted device yields the
* ciphertext, not the passphrase.
*
* StrongBox is requested first and falls back to the ordinary TEE-backed (or
* software) Keystore without a crash. The fallback is not silent: call
* [backing] and report what the Keystore actually produced.
*
* `setUserAuthenticationRequired` is deliberately **false**. Requiring a
* fingerprint to unlock the node would turn "fail closed" into "unusable
* unattended", and the SDK's contract is that an unlock either opens the node
* or reports why it did not.
*
* ## Device-unlock gate (what this class adds on top of the flag above)
*
* The key is additionally bound to the device's lock state with
* `setUnlockedDeviceRequired(true)` (API 28+): while the lock screen is up, the
* key refuses to decrypt, so a blob lifted off a powered-on-but-locked device
* is not decryptable by the app's own process either. That is still not a
* fingerprint prompt — an unattended unlock on an unlocked device keeps
* working — it only refuses *while the device is locked*.
*
* Two aliases are in play because a Keystore key cannot be retrofitted and
* cannot be re-aliased:
*
* - [ALIAS] (`onionwire.store`) — the pre-gate key. Never generated by this
* class on API 28+; it exists only on installs that stored a passphrase
* before the gate landed.
* - [ALIAS_UNLOCK_GATED] (`onionwire.store.unlock-gated`) — generated with the
* device-unlock requirement. This is the only key a fresh install ever
* creates.
*
* At most one of the two is live after a migration; both exist only in the
* window between "the re-wrapped blob verified" and "the pre-gate key was
* deleted". [StoredPassphraseStore] drives that window, in that order, and is
* the only thing allowed to delete the pre-gate key.
*
* ## What can be *reported* about the gate, honestly
*
* `KeyInfo` on this API range exposes `isUserAuthenticationRequired` but has
* **no getter for the unlock requirement**, so no code here can ask the
* Keystore whether the flag stuck. [unlockGateReport] therefore reports our own
* bookkeeping — "the live key was generated under the unlock-gated alias" — and
* [UnlockGateReport.platformReportsGate] is a constant `false` saying so. On a
* device whose Keystore refuses the flag, the report shows
* `supported && !keyIsUnlockGated` plus the refusal reason; nothing pretends
* otherwise.
*/
class KeystorePassphraseCipher(private val context: Context) :
PassphraseCipher,
PassphraseKeyMigration {
private var cached: ActiveKey? = null
/** Why this process's attempt at an unlock-gated key failed, if it did. */
private var gateRefusal: String? = null
/** Why the last re-wrap of the stored blob did not finish. Report-only. */
private var migrationFailure: String? = null
override fun seal(plaintext: CharArray): ByteArray {
val key = keyForSeal()
return try {
StoreSecret.seal(key.secret, plaintext)
} catch (e: SecretUnavailable) {
throw gateMessage(e, gatedKeyInPlay = key.gated)
}
}
/**
* Never creates a key. A freshly generated key cannot decrypt an old blob,
* and generating one here would turn "the key is gone" into a confusing
* GCM tag failure. The caller needs the real reason to tell the user.
*
* A blob written before the gate landed is wrapped by [ALIAS], so an
* unlock-gated key is tried first and the pre-gate key is the fallback —
* that ordering is what makes the crash window of the migration harmless.
*/
override fun open(blob: ByteArray): CharArray {
val active = activeKey()
?: throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
try {
return StoreSecret.open(active.secret, blob)
} catch (first: SecretUnavailable) {
if (active.gated) {
val legacy = existingKey(ALIAS)
if (legacy != null) {
try {
return StoreSecret.open(legacy, blob)
} catch (_: SecretUnavailable) {
// Fall through to the honest report below.
}
}
}
throw gateMessage(first, gatedKeyInPlay = active.gated)
}
}
override fun keyPresent(): Boolean = activeKey() != null
override fun backing(): KeyBacking {
val key = activeKey() ?: return KeyBacking.UNKNOWN
val info = try {
SecretKeyFactory.getInstance(key.secret.algorithm, PROVIDER)
.getKeySpec(key.secret, KeyInfo::class.java) as KeyInfo
} catch (_: Exception) {
// Some OEM Keystore implementations refuse getKeySpec. Report
// UNKNOWN rather than guessing hardware backing.
return KeyBacking.UNKNOWN
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
info.securityLevel == KeyProperties.SECURITY_LEVEL_STRONGBOX
) {
return KeyBacking.STRONGBOX
}
// Deprecated in API 31 in favour of securityLevel, but it is the only
// TEE/software answer available on 26–30, and minSdk is 26.
@Suppress("DEPRECATION")
val inSecureHardware = info.isInsideSecureHardware
return if (inSecureHardware) KeyBacking.HARDWARE else KeyBacking.SOFTWARE
}
/** Deletes both aliases: `forget()` must leave nothing that can decrypt. */
override fun deleteKey() {
cached = null
val store = try {
keyStore()
} catch (_: Exception) {
return
}
for (alias in listOf(ALIAS_UNLOCK_GATED, ALIAS)) {
try {
store.deleteEntry(alias)
} catch (_: Exception) {
// Nothing usable to delete under that alias.
}
}
}
// ---------------------------------------------------------------- report
/**
* What can honestly be said about the device-unlock gate on the live key.
* See the class doc: there is no platform getter for the flag itself.
*/
fun unlockGateReport(): UnlockGateReport {
val active = activeKey()
return UnlockGateReport(
supported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P,
sdkInt = Build.VERSION.SDK_INT,
keyIsUnlockGated = active?.gated == true,
legacyKeyPending = existingKey(ALIAS) != null,
backing = if (active == null) KeyBacking.UNKNOWN else backing(),
gateRefusal = gateRefusal,
migrationFailure = migrationFailure,
)
}
private fun logBranch(branch: String) {
Log.i(
TAG,
"wrap key: branch=$branch sdk=${Build.VERSION.SDK_INT} " +
"manufacturer=${Build.MANUFACTURER} model=${Build.MODEL}",
)
}
// --------------------------------------------------- PassphraseKeyMigration
/**
* True when the key [seal] just wrapped with is the unlock-gated one. False
* on API 26–27 and on a device whose Keystore refused the flag — in both
* cases there is nothing to migrate to, and the caller must not delete the
* pre-gate key.
*/
override fun unlockGateInEffect(): Boolean =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && existingKey(ALIAS_UNLOCK_GATED) != null
override fun legacyKeyPending(): Boolean = existingKey(ALIAS) != null
/** Decrypts [blob] with the unlock-gated key alone — never the fallback. */
override fun openWithUnlockGate(blob: ByteArray): CharArray {
val key = existingKey(ALIAS_UNLOCK_GATED)
?: throw SecretUnavailable("no unlock-gated key exists to prove the blob against")
return try {
StoreSecret.open(key, blob)
} catch (e: SecretUnavailable) {
throw gateMessage(e, gatedKeyInPlay = true)
}
}
/**
* Deletes [ALIAS]. [StoredPassphraseStore] calls this only after the
* replacement blob is on disk and has been opened back under the new key;
* a blob wrapped by this alias becomes undecryptable the moment it runs.
*/
override fun retireLegacyKey() {
if (!legacyKeyPending()) return
try {
keyStore().deleteEntry(ALIAS)
} catch (e: Exception) {
noteMigrationFailure("could not delete the pre-gate key under $ALIAS (${e.message})")
return
}
if (cached?.gated == false) cached = null
Log.i(TAG, "retired the pre-gate Keystore key under $ALIAS; only $ALIAS_UNLOCK_GATED remains")
}
override fun noteMigrationFailure(reason: String) {
migrationFailure = reason
Log.w(TAG, "unlock-gated key migration did not complete: $reason (blob and pre-gate key kept)")
}
// ------------------------------------------------------------------ keys
private class ActiveKey(val secret: SecretKey, val gated: Boolean)
/** Existing key we would decrypt with, unlock-gated first. Never creates. */
private fun activeKey(): ActiveKey? {
cached?.let { return it }
existingKey(ALIAS_UNLOCK_GATED)?.let { return ActiveKey(it, gated = true).also { k -> cached = k } }
existingKey(ALIAS)?.let { return ActiveKey(it, gated = false).also { k -> cached = k } }
return null
}
/**
* The key [seal] uses. Prefers the unlock-gated alias (creating it if the
* platform allows), which is what turns a pre-gate install into a gated one
* the next time a passphrase is stored.
*/
private fun keyForSeal(): ActiveKey {
val active = activeKey()
if (active?.gated == true) return active
return gatedKeyOrCreate() ?: active ?: legacyKeyOrCreate()
}
private fun gatedKeyOrCreate(): ActiveKey? {
cached?.let { if (it.gated) return it }
existingKey(ALIAS_UNLOCK_GATED)?.let { return ActiveKey(it, gated = true).also { k -> cached = k } }
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return null
// One attempt per process: a Keystore that refused the flag will refuse
// it again, and unlock must not retry key generation on every call.
if (gateRefusal != null) return null
return try {
val key = generateWithFallback(ALIAS_UNLOCK_GATED, unlockGated = true)
logBranch("unlock-gated alias=$ALIAS_UNLOCK_GATED")
ActiveKey(key, gated = true).also { cached = it }
} catch (e: GeneralSecurityException) {
recordGateRefusal(e)
null
} catch (e: ProviderException) {
recordGateRefusal(e)
null
}
}
private fun legacyKeyOrCreate(): ActiveKey {
cached?.let { if (!it.gated) return it }
existingKey(ALIAS)?.let { return ActiveKey(it, gated = false).also { k -> cached = k } }
val key = generateWithFallback(ALIAS, unlockGated = false)
logBranch(
"ungated alias=$ALIAS" +
(gateRefusal?.let { " (unlock gate refused: $it)" } ?: ""),
)
return ActiveKey(key, gated = false).also { cached = it }
}
private fun recordGateRefusal(e: Exception) {
gateRefusal = "${e.javaClass.simpleName}: ${e.message}"
Log.w(
TAG,
"Keystore refused setUnlockedDeviceRequired(true) under $ALIAS_UNLOCK_GATED; " +
"falling back to the pre-gate alias $ALIAS (=$gateRefusal) " +
"sdk=${Build.VERSION.SDK_INT} manufacturer=${Build.MANUFACTURER} model=${Build.MODEL}",
)
}
private fun existingKey(alias: String): SecretKey? = try {
keyStore().getKey(alias, null) as? SecretKey
} catch (_: Exception) {
null
}
private fun strongBoxAdvertised(): Boolean =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
private fun generateWithFallback(alias: String, unlockGated: Boolean): SecretKey {
if (strongBoxAdvertised()) {
try {
return generate(alias, strongBox = true, unlockGated = unlockGated)
} catch (e: ProviderException) {
// StrongBoxUnavailableException is a ProviderException: the chip
// exists but its slots are full, or it refuses AES-256. Fall
// through to a normal Keystore key instead of failing unlock.
Log.i(TAG, "StrongBox refused a key under $alias (${e.javaClass.simpleName}: ${e.message})")
} catch (e: GeneralSecurityException) {
Log.i(TAG, "StrongBox refused a key under $alias (${e.javaClass.simpleName}: ${e.message})")
}
}
return generate(alias, strongBox = false, unlockGated = unlockGated)
}
private fun generate(alias: String, strongBox: Boolean, unlockGated: Boolean): SecretKey {
val builder = KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(StoreSecret.KEY_BITS)
// Our IV comes from Cipher.init, and the Keystore supplies it.
.setRandomizedEncryptionRequired(true)
// Locked decision: no fingerprint gate on an unattended node.
.setUserAuthenticationRequired(false)
if (unlockGated && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// Refuses while the lock screen is up. No user-auth prompt is
// involved, so this does not turn "fail closed" into "unusable
// unattended" — it narrows *when* the key works, not who is awake.
builder.setUnlockedDeviceRequired(true)
}
if (strongBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
builder.setIsStrongBoxBacked(true)
}
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER)
generator.init(builder.build())
return generator.generateKey()
}
private fun keyStore(): KeyStore = KeyStore.getInstance(PROVIDER).apply { load(null) }
/**
* A gated key refuses to work while the lock screen is up, and the Keystore
* surfaces that as a plain crypto failure. "the stored secret did not
* authenticate" would read as a corrupt blob, so say what happened.
*/
private fun gateMessage(e: SecretUnavailable, gatedKeyInPlay: Boolean): SecretUnavailable {
if (!gatedKeyInPlay) return e
val lockRefusal = e.cause is UserNotAuthenticatedException || deviceLocked()
if (!lockRefusal) return e
return SecretUnavailable(
"the device is locked — the passphrase key is only usable while the device is unlocked",
e,
)
}
private fun deviceLocked(): Boolean =
context.getSystemService(KeyguardManager::class.java)?.isDeviceLocked == true
companion object {
const val PROVIDER = "AndroidKeyStore"
/** Logcat tag; also what `adb logcat -s OnionWireKeystore` filters on. */
const val TAG = "OnionWireKeystore"
/**
* The pre-gate key's alias. Kept as the app's original name: a Keystore
* alias cannot be renamed, so an upgraded install keeps this one until
* [retireLegacyKey] deletes it.
*/
const val ALIAS = "onionwire.store"
/** The key that carries `setUnlockedDeviceRequired(true)`. */
const val ALIAS_UNLOCK_GATED = "onionwire.store.unlock-gated"
}
}
/**
* Re-wrapping a stored blob under a key that carries the device-unlock
* requirement.
*
* Deliberately **not** part of [PassphraseCipher]: an implementation without a
* Keystore (the JVM fakes in `StoredPassphraseStoreTest`) has nothing to
* migrate, and adding methods to the cipher interface would force every fake to
* grow a no-op. [StoredPassphraseStore] asks for this capability with a safe
* cast and skips migration entirely when it is absent.
*/
interface PassphraseKeyMigration {
/**
* True when the key the cipher just sealed with is the unlock-gated one.
* When false — API 26/27, or a Keystore that refused the flag — there is
* nothing to migrate to and the pre-gate key must be left alone.
*/
fun unlockGateInEffect(): Boolean
/** A pre-gate key still exists under [KeystorePassphraseCipher.ALIAS]. */
fun legacyKeyPending(): Boolean
/**
* Decrypts [blob] with the unlock-gated key **only**. Used to prove a
* freshly written blob before the pre-gate key is deleted, so a fallback
* decrypt cannot masquerade as proof.
*
* @throws SecretUnavailable when the blob is not wrapped by that key.
*/
fun openWithUnlockGate(blob: ByteArray): CharArray
/**
* Deletes the pre-gate key. Only valid once the replacement blob is durable
* and [openWithUnlockGate] has proven it.
*/
fun retireLegacyKey()
/** Records why a re-wrap attempt stopped, for logs and [unlockGateReport]. */
fun noteMigrationFailure(reason: String)
}
/**
* What we can honestly say about the device-unlock gate on the live key.
*
* [platformReportsGate] is always `false`: `KeyInfo` has no getter for
* `setUnlockedDeviceRequired`, so the gate state is our own bookkeeping about
* which alias the key was generated under, not a Keystore attestation.
*/
data class UnlockGateReport(
/** API 28+ can carry the flag at all. */
val supported: Boolean,
val sdkInt: Int,
/** The live key was generated under the unlock-gated alias. */
val keyIsUnlockGated: Boolean,
/** The pre-gate key still exists — a migration has not completed yet. */
val legacyKeyPending: Boolean,
val backing: KeyBacking,
/** Set when this process's attempt at a gated key was refused. */
val gateRefusal: String?,
/** Set when a re-wrap of the stored blob did not finish. */
val migrationFailure: String?,
/** No platform getter exists for the unlock requirement. Always false. */
val platformReportsGate: Boolean = false,
) {
/** One honest sentence for logcat / a status line. Never claims hardware proof. */
fun describe(): String = when {
keyIsUnlockGated -> "key: ${backing.name.lowercase()}, unusable while the device is locked"
!supported -> "key: ${backing.name.lowercase()}, unlock gate unsupported on SDK $sdkInt"
gateRefusal != null ->
"key: ${backing.name.lowercase()}, NOT unlock-gated — the Keystore refused the flag"
legacyKeyPending ->
"key: ${backing.name.lowercase()}, NOT unlock-gated — pre-gate key, migrates on the next unlock"
else -> "key: ${backing.name.lowercase()}, NOT unlock-gated"
}
}

View file

@ -0,0 +1,49 @@
package com.siriusdevops.onionwire.crypto
/**
* Wraps the store passphrase with a key that never leaves the Keystore.
*
* Implementations must not persist the plaintext anywhere, and must not log it.
*/
interface PassphraseCipher {
/** Encrypts [plaintext]. The returned blob is the only thing that may hit disk. */
fun seal(plaintext: CharArray): ByteArray
/**
* Decrypts a blob produced by [seal].
*
* @throws SecretUnavailable when the key is gone, invalidated, or the blob
* does not authenticate. Callers fall back to asking the user to type.
*/
fun open(blob: ByteArray): CharArray
/** True when a usable key is already in the Keystore. */
fun keyPresent(): Boolean
/**
* Where the key actually lives, as reported by the Keystore itself.
*
* This is an observation, not a claim: on a device without a StrongBox or
* TEE the honest answer is [KeyBacking.SOFTWARE], and the UI says so.
*/
fun backing(): KeyBacking
/** Removes the key. The ciphertext becomes permanently undecryptable. */
fun deleteKey()
}
/** Result of asking the Keystore where the key lives. */
enum class KeyBacking {
/** Dedicated security chip (API 28+, Pixel 3-class and up). */
STRONGBOX,
/** Key is inside a TEE. Good. */
HARDWARE,
/** Keystore software implementation. Passphrase is still not plaintext on disk. */
SOFTWARE,
/** No key created yet, or the API could not be queried. Never claim hardware here. */
UNKNOWN,
}

View file

@ -0,0 +1,130 @@
package com.siriusdevops.onionwire.crypto
import java.nio.CharBuffer
import java.nio.charset.StandardCharsets
import java.security.GeneralSecurityException
import java.util.Arrays
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/**
* AES-256-GCM envelope for the store passphrase.
*
* This file is deliberately free of `android.*` imports so the exact
* seal/open code that runs on a device can also run in a plain JVM unit test
* with a JVM-generated AES key. The Android Keystore only supplies the key —
* the framing and the AEAD call are these functions.
*
* Wire format (little of it is secret, all of it is authenticated):
*
* magic "OWSEAL1\n" 8 bytes
* iv length 1 byte (always [IV_BYTES])
* iv [IV_BYTES] bytes, from the cipher
* ciphertext n + [TAG_BITS]/8 bytes (GCM tag is appended)
*
* The IV is generated by `Cipher.init` rather than by us: an AndroidKeyStore
* key created with `setRandomizedEncryptionRequired(true)` refuses an
* app-supplied IV, and SunJCE likewise default-generates one. Nothing here
* ever writes the plaintext passphrase to disk.
*/
object StoreSecret {
/** AES-256 per the card. Keystore key size and this constant must agree. */
const val KEY_BITS: Int = 256
/** 96-bit IV is the GCM-recommended size; AndroidKeyStore defaults to it. */
const val IV_BYTES: Int = 12
/** Full-length GCM tag. Truncating it saves 6 bytes and buys nothing. */
private const val TAG_BITS: Int = 128
private val MAGIC = byteArrayOf('O'.code.toByte(), 'W'.code.toByte(), 'S'.code.toByte(), 'E'.code.toByte(), 'A'.code.toByte(), 'L'.code.toByte(), '1'.code.toByte(), '\n'.code.toByte())
private const val TRANSFORMATION = "AES/GCM/NoPadding"
/**
* Encrypts [plaintext] under [key]. The passphrase is never converted to a
* `String` on this path: the UTF-8 encoder reads the `CharArray` directly.
*/
fun seal(key: SecretKey, plaintext: CharArray): ByteArray {
require(plaintext.isNotEmpty()) { "refusing to seal an empty passphrase" }
val bytes = utf8(plaintext)
try {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.ENCRYPT_MODE, key)
val iv = cipher.iv
val ct = cipher.doFinal(bytes)
return ByteArray(MAGIC.size + 1 + iv.size + ct.size).also { out ->
var p = 0
MAGIC.copyInto(out, p); p += MAGIC.size
out[p] = iv.size.toByte(); p += 1
iv.copyInto(out, p); p += iv.size
ct.copyInto(out, p)
}
} catch (e: GeneralSecurityException) {
throw SecretUnavailable("could not encrypt the passphrase", e)
} finally {
wipe(bytes)
}
}
/**
* Reverses [seal]. Throws [SecretUnavailable] on a wrong key, a truncated
* blob, or a failed GCM tag check — never returns partial plaintext.
*/
fun open(key: SecretKey, blob: ByteArray): CharArray {
if (blob.size < MAGIC.size + 1 + IV_BYTES + TAG_BITS / 8) {
throw SecretUnavailable("stored secret is truncated")
}
for (i in MAGIC.indices) {
if (blob[i] != MAGIC[i]) throw SecretUnavailable("stored secret is not an OnionWire envelope")
}
var p = MAGIC.size
val ivLen = blob[p].toInt() and 0xFF
p += 1
if (ivLen != IV_BYTES) throw SecretUnavailable("unexpected IV length $ivLen")
if (blob.size < p + ivLen + TAG_BITS / 8) throw SecretUnavailable("stored secret is truncated")
val iv = blob.copyOfRange(p, p + ivLen)
val ct = blob.copyOfRange(p + ivLen, blob.size)
val plain = try {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, iv))
cipher.doFinal(ct)
} catch (e: GeneralSecurityException) {
throw SecretUnavailable("stored secret did not authenticate", e)
}
return try {
decodeUtf8(plain)
} finally {
wipe(plain)
}
}
/** Zeroes [bytes]. Cheap, and it shortens the window a heap dump can read. */
fun wipe(bytes: ByteArray) {
Arrays.fill(bytes, 0)
}
/** Zeroes [chars]. Kotlin/Java strings are immutable, so this is the best we get. */
fun wipe(chars: CharArray) {
Arrays.fill(chars, '\u0000')
}
private fun utf8(chars: CharArray): ByteArray {
val bb = StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(chars))
return ByteArray(bb.remaining()).also(bb::get)
}
private fun decodeUtf8(bytes: ByteArray): CharArray {
val cb = StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes))
return CharArray(cb.remaining()).also(cb::get)
}
}
/**
* The passphrase could not be recovered. The caller must fall back to typing
* it — a Keystore key does not survive a factory reset, a lock-screen change
* that invalidates keys, or an app-data wipe.
*/
class SecretUnavailable(message: String, cause: Throwable? = null) : RuntimeException(message, cause)

View file

@ -0,0 +1,204 @@
package com.siriusdevops.onionwire.crypto
import java.io.File
import java.io.IOException
/**
* The only on-disk copy of the passphrase: an AES-GCM blob under
* `context.filesDir`, which is app-private and excluded from backup and
* device transfer (`AndroidManifest.xml`, `res/xml/data_extraction_rules.xml`).
*
* The blob is the envelope from [StoreSecret] — magic + IV + ciphertext + tag.
* There is no second copy, no SharedPreferences mirror, and nothing outside the
* app's data dir.
*
* ## Migrating the wrapping key to the device-unlock gate
*
* A Keystore key cannot be retrofitted with `setUnlockedDeviceRequired`, so an
* install that stored a passphrase before the gate landed keeps an ungated key
* until the passphrase is in hand again. The only two places that happens are
* the ones below, and both go through the same crash-safe order:
*
* 1. `cipher.seal()` wraps under the unlock-gated key, creating it if needed.
* 2. The new blob is written to `…bin.tmp`.
* 3. Those exact bytes are read back and opened with the unlock-gated key and
* compared to the passphrase in hand. Failure ⇒ temp file dropped,
* everything else untouched (a [SecretUnavailable] with the reason, not a
* bare "did not authenticate").
* 4. Only then is the temp file renamed over the real blob.
* 5. Only then is the pre-gate Keystore alias deleted.
*
* A crash anywhere before 4 leaves the previous blob and the previous key
* intact; a crash between 4 and 5 leaves a working gated blob plus a stale
* alias that the next save/unlock retires. The pre-gate key is therefore never
* deleted before a blob that supersedes it is proven.
*/
class StoredPassphraseStore(
private val file: File,
private val cipher: PassphraseCipher,
) {
sealed interface Load {
/** Decrypted for this call only. The caller must wipe the array. */
class Loaded(val passphrase: CharArray) : Load
/** Nothing stored yet — first run, or the user forgot it. */
data object Absent : Load
/**
* Something is stored but cannot be read: the Keystore key is gone or
* unusable, the device is locked, or the file is corrupt. Fall back to
* typing.
*/
data class Unavailable(val reason: String) : Load
}
/**
* The optional key-migration capability. Absent for any cipher that is not
* the Keystore one (the JVM fakes in tests), which simply means there is
* nothing to migrate and the pre-gate order above does not apply.
*/
private fun migrator(): PassphraseKeyMigration? = cipher as? PassphraseKeyMigration
fun exists(): Boolean = file.isFile && file.length() > 0L
/** Where the wrapping key actually lives. See [PassphraseCipher.backing]. */
fun backing(): KeyBacking = cipher.backing()
/** True when the stored blob is wrapped by a device-unlock-gated key. */
fun unlockGated(): Boolean = migrator()?.unlockGateInEffect() == true
/** Path for diagnostics in tests. Never logged with its contents. */
val path: String get() = file.absolutePath
/**
* Encrypts and replaces the stored blob, then retires a pre-gate key.
*
* Replaces the blob atomically: written to a sibling temp file, proven to
* open under the key that produced it, and only then renamed, so a crash
* mid-write cannot leave half a blob or a blob nobody can decrypt.
*
* @throws SecretUnavailable when the blob could not be written or could not
* be proven under the unlock-gated key. The previous blob is still in
* place in that case.
*/
fun save(passphrase: CharArray) {
require(passphrase.isNotEmpty()) { "refusing to store an empty passphrase" }
// seal() may create the unlock-gated key, so ask about the gate only
// afterwards — on a fresh install there is no gated key before this.
val blob = cipher.seal(passphrase)
try {
val migration = migrator()
val gated = migration?.unlockGateInEffect() == true
writeVerified(blob, passphrase, if (gated) migration else null)
// The replacement blob is durable and proven. Only now may the
// pre-gate alias go: deleting it earlier would strand a blob.
if (gated) migration?.retireLegacyKey()
} finally {
StoreSecret.wipe(blob)
}
}
/**
* Reads and decrypts the blob. The returned array is the caller's to wipe.
*
* A successful read is also the moment the wrapping key can be upgraded: the
* passphrase is in hand, so a pre-gate key is re-wrapped here rather than
* asking the user to type it again.
*
* A failed decrypt does **not** delete the blob: a transient Keystore
* failure must not silently destroy the user's only copy. Use [forget] to
* drop it deliberately.
*/
fun load(): Load {
if (!exists()) return Load.Absent
val blob = try {
file.readBytes()
} catch (e: IOException) {
return Load.Unavailable("the stored passphrase file could not be read (${e.message})")
}
val passphrase = try {
cipher.open(blob)
} catch (e: SecretUnavailable) {
return Load.Unavailable(e.message ?: "the stored passphrase did not authenticate")
} finally {
StoreSecret.wipe(blob)
}
migrateOnSuccessfulUnlock(passphrase)
return Load.Loaded(passphrase)
}
/** Drops the ciphertext and the Keystore key. Irreversible. */
fun forget() {
file.delete()
File(file.parentFile, file.name + ".tmp").delete()
cipher.deleteKey()
}
/**
* Best effort, after a successful unlock. The unlock itself already
* succeeded, so a failed re-wrap must not fail it — but it must not be
* silent either: the reason goes to logcat and to
* [KeystorePassphraseCipher.unlockGateReport], and the install stays
* honestly "not unlock-gated" until a later save/unlock succeeds.
*/
private fun migrateOnSuccessfulUnlock(passphrase: CharArray) {
val migration = migrator() ?: return
if (!migration.unlockGateInEffect() || !migration.legacyKeyPending()) return
try {
save(passphrase)
} catch (e: Exception) {
migration.noteMigrationFailure(e.message ?: e.toString())
}
}
/**
* Writes [blob] to the temp file, proves the written bytes open under the
* unlock-gated key alone, and renames it into place.
*
* [verifier] is null when no unlock-gated key exists on this device (API
* 26–27, or a Keystore that refused the flag): the blob is then wrapped by
* the pre-gate key, which is the only key there is.
*/
private fun writeVerified(
blob: ByteArray,
passphrase: CharArray,
verifier: PassphraseKeyMigration?,
) {
file.parentFile?.mkdirs()
val tmp = File(file.parentFile, file.name + ".tmp")
tmp.writeBytes(blob)
if (verifier != null) {
val written = tmp.readBytes()
try {
val back = try {
verifier.openWithUnlockGate(written)
} catch (e: SecretUnavailable) {
tmp.delete()
throw SecretUnavailable(
"the new passphrase blob did not open under the unlock-gated key; " +
"the previous blob and key were kept",
e,
)
}
try {
if (!back.contentEquals(passphrase)) {
tmp.delete()
throw SecretUnavailable(
"the new passphrase blob did not read back identically; " +
"the previous blob and key were kept",
)
}
} finally {
StoreSecret.wipe(back)
}
} finally {
StoreSecret.wipe(written)
}
}
if (!tmp.renameTo(file)) {
file.writeBytes(blob)
tmp.delete()
}
}
}

View file

@ -0,0 +1,12 @@
package com.siriusdevops.onionwire.keepalive
/**
* Whether the foreground service has anything to hold.
*
* Bootstrap used to not count: the service bailed when `Wire` was still null,
* and `openWire` ran on the UI ViewModel scope, so closing the activity
* cancelled Tor bring-up. Opening is work; a published node is work; locked
* and idle is not.
*/
fun keepAliveHasWork(nodeOpen: Boolean, bootstrapInFlight: Boolean): Boolean =
nodeOpen || bootstrapInFlight

View file

@ -0,0 +1,189 @@
package com.siriusdevops.onionwire.keepalive
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.siriusdevops.onionwire.MainActivity
import com.siriusdevops.onionwire.R
/**
* Holds the process (and therefore the in-process Arti node) in the foreground
* so the onion stays published after the screen goes off.
*
* The service does *not* own the node — [NodeHost] does. This reports its
* anchor and lets the policy decide: starting the keep-alive keeps the node
* alive, and losing it (user tapped Stop, or the system killed us) shuts the
* node down only if nothing else is holding it.
*
* Returns `START_NOT_STICKY` deliberately. A sticky restart would bring the
* service back with no node behind it — the passphrase is not held in memory
* after unlock — and a notification claiming "OnionWire is reachable" over a
* dead onion is worse than no service at all.
*/
class KeepAliveService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_STOP) {
// The user ended the keep-alive from the notification. `onDestroy()`
// reports the lost anchor: the node stops if nothing else holds it,
// and stays up while the app is still open in front of them (the UI
// anchor). The action is labelled "Stop keep-alive", not "Lock", so
// that is the behaviour it promises.
stopSelf()
return START_NOT_STICKY
}
if (!NodeHost.hasWorkForKeepAlive()) {
// Nothing to keep alive. A notification here would be a lie.
// Bootstrap counts: the node is not `current()` until Tor has
// published, and that is exactly the window Android used to kill.
stopSelf()
return START_NOT_STICKY
}
if (!startInForeground(intent?.getStringExtra(EXTRA_ONION).orEmpty())) {
stopSelf()
return START_NOT_STICKY
}
NodeHost.onKeepAliveStarted()
return START_NOT_STICKY
}
override fun onDestroy() {
NodeHost.onKeepAliveStopped()
super.onDestroy()
}
/**
* @return false when the system refused the foreground start, in which case
* the anchor was never taken and the node stays foreground-only.
*/
private fun startInForeground(onion: String): Boolean {
return try {
createChannel()
val notification = buildNotification(onion)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
startForeground(
NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE,
)
} else {
// API 26-33: the manifest-declared type is what the platform
// records; the three-arg overload only exists from 29.
startForeground(NOTIFICATION_ID, notification)
}
true
} catch (t: Throwable) {
// API 31+: a start from the background throws
// ForegroundServiceStartNotAllowedException. Degrade to "the node
// lives only while the app does" instead of taking the process
// down; the roster says so on screen.
Log.w(TAG, "foreground start refused; node stays foreground-only", t)
NodeHost.onKeepAliveRefused(t.message ?: t.toString())
false
}
}
private fun createChannel() {
val manager = getSystemService(NotificationManager::class.java) ?: return
val channel = NotificationChannel(
CHANNEL_ID,
getString(R.string.keep_alive_channel_name),
// LOW: present in the shade, never a sound or a heads-up. This is a
// status light, not an alert.
NotificationManager.IMPORTANCE_LOW,
).apply {
description = getString(R.string.keep_alive_channel_description)
setShowBadge(false)
}
manager.createNotificationChannel(channel)
}
private fun buildNotification(onion: String): Notification {
val open = PendingIntent.getActivity(
this,
0,
Intent(this, MainActivity::class.java),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
val stop = PendingIntent.getService(
this,
1,
Intent(this, KeepAliveService::class.java).setAction(ACTION_STOP),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
// Never the full v3 locator: a notification body is lock-screen public.
val short = onion.take(ONION_PREFIX)
val opening = short.isEmpty() && NodeHost.isOpening()
val title = if (opening) {
getString(R.string.keep_alive_title_opening)
} else {
getString(R.string.keep_alive_title)
}
val text = when {
opening -> getString(R.string.keep_alive_text_opening)
short.isEmpty() -> getString(R.string.keep_alive_text)
else -> getString(R.string.keep_alive_text_onion, short)
}
return NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_onion)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(open)
.addAction(0, getString(R.string.keep_alive_stop), stop)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setShowWhen(false)
.build()
}
companion object {
private const val TAG = "OnionWireKeepAlive"
const val ACTION_STOP = "com.siriusdevops.onionwire.keepalive.STOP"
const val EXTRA_ONION = "onion"
private const val CHANNEL_ID = "keep-alive"
private const val NOTIFICATION_ID = 1
/** Characters of the onion address shown, prefix only. */
private const val ONION_PREFIX = 10
/**
* Brings up the keep-alive. Must be called while the app is visible —
* an unlock is, and that is the only caller — so the API 31+
* background-start restriction does not apply.
*/
fun start(context: Context, onion: String) {
val intent = Intent(context, KeepAliveService::class.java)
.putExtra(EXTRA_ONION, onion)
try {
context.startForegroundService(intent)
} catch (t: Throwable) {
// Same refusal as in the service, just one call earlier.
Log.w(TAG, "startForegroundService refused", t)
NodeHost.onKeepAliveRefused(t.message ?: t.toString())
}
}
/** Ends the keep-alive; `onDestroy()` reports the lost anchor. */
fun stop(context: Context) {
context.stopService(Intent(context, KeepAliveService::class.java))
}
}
}

View file

@ -0,0 +1,211 @@
package com.siriusdevops.onionwire.keepalive
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import uniffi.onionwire_sdk.Wire
import uniffi.onionwire_sdk.openWire
import java.io.File
/**
* How visible the keep-alive currently is, for the one line of battery honesty
* the roster shows.
*/
sealed interface KeepAliveStatus {
/** No foreground service. The node lives only while the app does. */
data object Off : KeepAliveStatus
/** A foreground service is holding the node, notification and all. */
data object On : KeepAliveStatus
/**
* The system refused the foreground start (API 31+ background-start rules,
* an OEM battery policy). The node is still up, but it dies with the app.
*/
data class Unavailable(val reason: String) : KeepAliveStatus
}
/**
* Process-wide owner of the single `Wire` node.
*
* Ownership rule: whoever opens the node hands the handle here, and **only this
* object ever calls `shutdown()` or `flush()` on it**. The ViewModel and
* [KeepAliveService] report lifecycle transitions; [NodeLifetime] decides
* whether the node survives, and this object executes that decision.
*
* That indirection is the point. `WireViewModel.onCleared()` used to shut the
* node down unconditionally, so a foreground service holding the same node
* would have been torn down by the first configuration change — or worse, the
* service would have kept a notification up for a node the UI had already
* killed. Neither side owns the node now; the policy does.
*
* Threading: [open] runs on [scope] (IO). [wire] is volatile so the main
* thread can read [current] while bootstrap completes off-main.
*/
object NodeHost {
/**
* Teardown must outlive the object graph that asked for it: `onCleared()`
* runs *after* `viewModelScope` is already cancelled, and stopping the node
* means draining the outbox and stopping Arti, not dropping a reference.
* One process-wide scope is enough — there is one node per process.
*/
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val lifetime = NodeLifetime()
@Volatile
private var wire: Wire? = null
/**
* In-flight `openWire`. Lives on [scope], not the UI ViewModel: closing the
* activity must not cancel Tor bootstrap. Null when idle or already open.
*/
@Volatile
private var bootstrap: Deferred<Wire>? = null
/**
* Set before the keep-alive starts, before [bootstrap] exists, so the
* service does not `stopSelf` in the gap between Unlock and `openWire`.
*/
@Volatile
private var claimedOpening: Boolean = false
/**
* The in-flight teardown, if any. Re-opening has to wait for it: the old
* node holds the sqlite file and Arti's state lock until `shutdown()`
* returns, and racing it makes the new node fail to open.
*/
private var stopping: Job? = null
private val _keepAlive = MutableStateFlow<KeepAliveStatus>(KeepAliveStatus.Off)
val keepAlive: StateFlow<KeepAliveStatus> = _keepAlive.asStateFlow()
/** The live node, or null when locked. */
fun current(): Wire? = wire
/** Tor bring-up is running on [scope]. The UI may be gone. */
fun isOpening(): Boolean = claimedOpening || bootstrap?.isActive == true
/** The foreground service holds a published node *or* an in-flight open. */
fun hasWorkForKeepAlive(): Boolean =
keepAliveHasWork(nodeOpen = wire != null, bootstrapInFlight = isOpening())
/**
* Call *before* [KeepAliveService.start] on the unlock path so the service
* sees bootstrap work before `openWire` has a job.
*/
fun noteOpening() {
claimedOpening = true
}
/** The live node, or a hard error. Callers are UI paths that require unlock. */
fun requireOpen(): Wire = wire ?: error("locked")
/**
* Opens the node and anchors it to the UI.
*
* Suspends inside Arti's bootstrap — minutes on a cold start — so this must
* never run on the main thread. The *work* runs on [scope], not the caller's
* job: a `viewModelScope` cancellation (activity gone) must not abort Tor.
* A second call while bootstrap is in flight joins the same job.
*/
suspend fun open(home: File, passphrase: String): Wire {
stopping?.join()
wire?.let { return it }
bootstrap?.let { return it.await() }
val job = scope.async {
val opened = openWire(home.absolutePath, passphrase)
wire = opened
// Keep-alive may already be On: it starts at unlock so Android
// will not kill us mid-bootstrap. Do not stomp that.
if (_keepAlive.value !is KeepAliveStatus.On) {
_keepAlive.value = KeepAliveStatus.Off
}
lifetime.onOpened()
opened
}
bootstrap = job
job.invokeOnCompletion {
if (bootstrap === job) bootstrap = null
claimedOpening = false
}
return job.await()
}
/** Join an in-flight [open] without starting a second `openWire`. */
suspend fun awaitOpen(): Wire {
wire?.let { return it }
return bootstrap?.await() ?: error("locked")
}
/** The UI is going away: finish, task swipe, or process death. */
fun onUiDetached(): NodeAction = apply(lifetime.onUnanchored(NodeAnchor.UI))
/** The keep-alive reached the foreground with its notification. */
fun onKeepAliveStarted(): NodeAction {
_keepAlive.value = KeepAliveStatus.On
return apply(lifetime.onAnchored(NodeAnchor.KEEP_ALIVE))
}
/** The keep-alive stopped, or the system destroyed it. */
fun onKeepAliveStopped(): NodeAction {
if (_keepAlive.value is KeepAliveStatus.On) _keepAlive.value = KeepAliveStatus.Off
return apply(lifetime.onUnanchored(NodeAnchor.KEEP_ALIVE))
}
/**
* `startForeground()` was refused. Nothing is anchoring the node at the OS
* level, so fail over to the honest pre-existing behaviour: the node lives
* as long as the app does, and the roster says why.
*/
fun onKeepAliveRefused(reason: String): NodeAction {
_keepAlive.value = KeepAliveStatus.Unavailable(reason)
return apply(lifetime.onUnanchored(NodeAnchor.KEEP_ALIVE))
}
/**
* Explicit Lock, from the UI or the notification's Stop action. The caller
* stops the keep-alive first — a service that is still running would
* re-anchor a node that no longer exists.
*/
fun lock(): NodeAction {
bootstrap?.cancel()
bootstrap = null
claimedOpening = false
return apply(lifetime.onLocked())
}
private fun apply(action: NodeAction): NodeAction {
when (action) {
NodeAction.Keep -> Unit
NodeAction.Flush -> scope.launch { runCatching { wire?.flush() } }
NodeAction.Stop -> stopNode()
}
return action
}
private fun stopNode() {
val dying = wire ?: return
wire = null
lifetime.onClosed()
// Best effort, both steps: teardown runs on a process-scope job after
// the UI is gone, so there is nobody to show an error to and nothing
// useful to retry. `shutdown()` drains again with a shorter budget, so
// a flush that times out is not fatal.
stopping = scope.launch {
runCatching { dying.flush() }
// A second shutdown — `lock()` and then `onCleared()`, say — lands
// here too: the SDK reports it as a typed WireException.Stopped,
// never a panic, so swallowing it is correct.
runCatching { dying.shutdown() }
}
}
}

View file

@ -0,0 +1,99 @@
package com.siriusdevops.onionwire.keepalive
/**
* Who currently requires the in-process Tor node to stay alive.
*
* [UI] is a live `WireViewModel`; [KEEP_ALIVE] is a running [KeepAliveService].
* Both can be present at the same time — that is the interesting case: the
* screen can go away while the keep-alive stays up, and the node must survive
* it. This enum exists so "who owns the node" is a value, not a convention.
*/
enum class NodeAnchor {
UI,
KEEP_ALIVE,
}
/** What the caller must do to the node after reporting a transition. */
sealed interface NodeAction {
/** Nothing to do; the node's fate is unchanged. */
data object Keep : NodeAction
/** Drain the outbox, leave the node published. */
data object Flush : NodeAction
/** Drain the outbox, then `shutdown()`. The node is gone. */
data object Stop : NodeAction
}
/**
* Pure policy for the single node's lifetime: no Android, no coroutines, no
* SDK. The ViewModel and the foreground service both report transitions here
* and execute the returned [NodeAction].
*
* The rule the whole card turns on: **the UI going away does not stop the node
* while a keep-alive anchor is held.** Before this, `WireViewModel.onCleared()`
* called `shutdown()` unconditionally, which is exactly the bug a foreground
* service would have walked into.
*
* Threading: state is mutated only from the main thread — [NodeHost] is the
* only caller, and it hops back to the main thread after the SDK's blocking
* open. There is no lock here on purpose.
*/
class NodeLifetime {
private var open = false
private val anchors = LinkedHashSet<NodeAnchor>()
/** True between [onOpened] and [onClosed]/[onLocked]. */
val isOpen: Boolean get() = open
fun anchoredBy(anchor: NodeAnchor): Boolean = anchor in anchors
/**
* The unlock path opened a node. The UI is by definition present — the user
* typed the passphrase into it.
*/
fun onOpened(): NodeAction {
open = true
anchors.add(NodeAnchor.UI)
return NodeAction.Keep
}
/** Teardown finished; the node no longer exists. */
fun onClosed(): NodeAction {
open = false
anchors.clear()
return NodeAction.Keep
}
/** A keep-alive reached the foreground. */
fun onAnchored(anchor: NodeAnchor): NodeAction {
anchors.add(anchor)
return NodeAction.Keep
}
/**
* An anchor went away: the UI was destroyed, or the keep-alive stopped or
* was killed. Removing the anchor first means a repeat report (the service
* action and `onDestroy()` both fire) cannot double-count.
*/
fun onUnanchored(anchor: NodeAnchor): NodeAction {
anchors.remove(anchor)
if (!open) return NodeAction.Keep
// Flush rather than Keep when another anchor remains: the process may
// be killed at any moment once the screen is gone, and the outbox is
// the whole point of surviving that.
return if (anchors.isEmpty()) NodeAction.Stop else NodeAction.Flush
}
/**
* The user pressed Lock. Every anchor is dropped: a keep-alive that outlived
* an explicit lock would leave a notification pointing at a dead onion.
*/
fun onLocked(): NodeAction {
val wasOpen = open
open = false
anchors.clear()
return if (wasOpen) NodeAction.Stop else NodeAction.Keep
}
}

View file

@ -2,23 +2,30 @@ package com.siriusdevops.onionwire.ui
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize 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.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
@ -26,6 +33,7 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
@ -33,51 +41,134 @@ 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.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
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.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay import com.siriusdevops.onionwire.R
import uniffi.onionwire_sdk.ChatMessage import com.siriusdevops.onionwire.ui.components.OwButton
import com.siriusdevops.onionwire.ui.components.OwIconButton
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.siriusdevops.onionwire.WireViewModel
import uniffi.onionwire_sdk.SendState
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun ChatScreen( fun ChatScreen(
vm: WireViewModel,
/** The peer's public key, hex — the key the open chat's poller runs for. */
peer: String,
title: String, title: String,
fingerprint: String, fingerprint: String,
onion: String, onion: String,
loadMessages: suspend () -> List<ChatMessage>,
onSend: suspend (String) -> Unit,
onBack: () -> Unit, onBack: () -> Unit,
/**
* Wall clock in unix seconds. `next_attempt_at` is absolute, so the
* countdown is computed here rather than baked into the store — injectable
* so a test can pin "now" instead of racing the clock.
*/
nowSeconds: () -> Long = { System.currentTimeMillis() / 1_000L },
) { ) {
var messages by remember { mutableStateOf<List<ChatMessage>?>(null) } // The refresh cadence lives in the ViewModel: one poller per open chat, not
// one per composition. Collecting here means a re-composition (or a
// configuration change) does not start a second loop against the SDK.
val chat by vm.chat.collectAsStateWithLifecycle()
val messages = chat?.messages
val outbox = chat?.outbox.orEmpty()
// The core's retry budget, fetched once per open chat: `try 3/8` renders
// against this and never against a constant in the app.
val maxAttempts = chat?.maxAttempts
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) } // Send-path failures are the screen's own state; load failures come back on
// [ChatState.error]. Both render in the same place under the list.
var sendError by remember { mutableStateOf<String?>(null) }
var notice by remember { mutableStateOf<String?>(null) }
val error = sendError ?: chat?.error
val listState = rememberLazyListState() val listState = rememberLazyListState()
// Poll: the node appends inbound messages in the background; there is no // Auto-scroll bookkeeping. `firstFillDone` keeps the one-jump-to-the-bottom
// push channel into the UI in v1. // on the first load (and again after leaving and re-entering the chat);
LaunchedEffect(Unit) { // `ownSendPending` is the user's own message asking for the list to follow
while (true) { // even though they may have scrolled up in history.
runCatching { loadMessages() } var firstFillDone by remember { mutableStateOf(false) }
.onSuccess { messages = it } var ownSendPending by remember { mutableStateOf(false) }
.onFailure { error = it.message ?: it.toString() }
delay(2_000) // The composer is the only place a message can be sent from, so after a
// send the keyboard is left up and the caret goes back into the field —
// the next message is one keystroke away instead of a re-tap.
val inputFocus = remember { FocusRequester() }
val send: () -> Unit = {
if (draft.isNotBlank() && pending == null) {
pending = draft
draft = ""
// The user's own message is the one case where the list is allowed
// to move while they are scrolled up in history.
ownSendPending = true
inputFocus.requestFocus()
} }
} }
// Fail-closed send. `send` retries the peer's onion for up to 3 minutes and // The poller's lifetime is the chat screen's: entering starts it, leaving
// then errors — nothing is spooled, so a failure is a real failure. // stops it, and re-entering the same peer is a no-op in the ViewModel, so
// there is exactly one loop no matter how the nav stack is walked.
DisposableEffect(peer) {
vm.openChat(peer)
onDispose { vm.closeChat(peer) }
}
// Send. An unreachable peer's onion is not an error any more: the core
// 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 sendError = null
runCatching { onSend(body) } notice = null
.onFailure { error = it.message ?: it.toString() } // The user has acted on whatever the poller last reported.
vm.clearChatError()
runCatching { vm.send(peer, 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 { sendError = it.message ?: it.toString() }
pending = null pending = null
} }
// Known and accepted: this is keyed on the message count, so a delivery-only
// change (a row flipping `queued` → `sent`, same size, different marker)
// does not re-run it. That has always been the behaviour here and it is the
// safe one — the list never moves for a marker.
LaunchedEffect(messages?.size) { LaunchedEffect(messages?.size) {
val n = messages?.size ?: 0 val n = messages?.size ?: 0
if (n > 0) listState.animateScrollToItem(n - 1) if (n == 0) return@LaunchedEffect
if (!firstFillDone) {
// First load: one jump to the bottom so the newest message is the
// one on screen, without an animation nobody asked for.
listState.scrollToItem(n - 1)
firstFillDone = true
return@LaunchedEffect
}
// Follow the tail only when the reader is already there. `n - 2`
// rather than `!canScrollForward`: the append has already made the list
// scrollable by the time this runs, so "can I scroll further" is true
// even for someone who was glued to the bottom a frame ago — and
// `lastVisible >= n - 2` tolerates the last row being partly on screen.
val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
if (ownSendPending || lastVisible >= n - 2) {
listState.animateScrollToItem(n - 1)
}
ownSendPending = false
} }
Scaffold( Scaffold(
@ -95,15 +186,28 @@ fun ChatScreen(
} }
}, },
navigationIcon = { navigationIcon = {
IconButton(onClick = onBack) { Text("<") } OwIconButton(
iconRes = R.drawable.ic_ow_chevron_left,
contentDescription = "Back",
onClick = onBack,
)
}, },
colors = TopAppBarDefaults.topAppBarColors( colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.background, containerColor = MaterialTheme.colorScheme.background,
), ),
) )
}, },
// The top bar carries its own status-bar inset; the content root applies
// systemBars + IME once (see `screenContentInsets`) so the navigation
// bar is not counted twice while the keyboard is up.
contentWindowInsets = WindowInsets(0, 0, 0, 0),
) { pad -> ) { pad ->
Column(Modifier.padding(pad).fillMaxSize()) { Column(
Modifier
.padding(pad)
.fillMaxSize()
.screenContentInsets(),
) {
Text( Text(
"onion: $onion", "onion: $onion",
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
@ -115,20 +219,30 @@ fun ChatScreen(
val list = messages val list = messages
when { when {
list == null -> { list == null -> {
Spacer(Modifier.height(16.dp)) // The body region always claims the leftover height, so the
// composer below it can never be pushed off the bottom —
// least of all by the keyboard.
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
CircularProgressIndicator(Modifier.padding(16.dp)) CircularProgressIndicator(Modifier.padding(16.dp))
} }
}
list.isEmpty() -> { list.isEmpty() -> {
Column( Column(
Modifier.fillMaxWidth().padding(24.dp), Modifier
verticalArrangement = Arrangement.Center, .weight(1f)
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(24.dp),
) { ) {
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,
) )
@ -136,18 +250,45 @@ fun ChatScreen(
} }
else -> { else -> {
// The outbox rows behind the pending sends: `queued (try
// 3/8, retry 45s)` needs the store's own counters and the
// core's retry budget. With either missing, or with a join
// that cannot prove itself, the rows keep the flat state
// marker — wrong numbers would be worse than none.
val max = maxAttempts
val details = if (max == null) {
List(list.size) { null }
} else {
outboxDetails(
rows = list.map { ChatRowInput(it.direction, it.delivery) },
outbox = outbox.map {
OutboxRowInput(
messageId = it.messageId,
status = it.status,
attempts = it.attempts,
nextAttemptAt = it.nextAttemptAt,
)
},
maxAttempts = max,
now = nowSeconds(),
)
}
LazyColumn( LazyColumn(
state = listState, state = listState,
modifier = Modifier.weight(1f).fillMaxWidth(), modifier = Modifier.weight(1f).fillMaxWidth(),
contentPadding = PaddingValues(12.dp), contentPadding = PaddingValues(12.dp),
verticalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp),
) { ) {
items(list) { m -> itemsIndexed(list) { i, m ->
val mine = m.direction == "out" val mine = m.direction == "out"
Row( Row(
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 +303,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, details.getOrNull(i))
} }
} }
} }
} }
} }
}
}
// 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(
@ -177,30 +348,106 @@ fun ChatScreen(
) )
} }
// The composer sticks to the bottom of the window: `screenContentInsets`
// already lifted it above the keyboard, and its row is never allowed
// to be squeezed out by the messages above it (they hold the weight).
Row( Row(
Modifier.fillMaxWidth().padding(8.dp), Modifier
verticalAlignment = Alignment.CenterVertically, .fillMaxWidth()
.padding(8.dp)
.testTag("chat-composer"),
verticalAlignment = Alignment.Bottom,
) { ) {
OutlinedTextField( OutlinedTextField(
value = draft, value = draft,
onValueChange = { draft = it }, onValueChange = { draft = it },
modifier = Modifier.weight(1f), modifier = Modifier
.weight(1f)
.focusRequester(inputFocus)
.testTag("chat-input"),
maxLines = 4, maxLines = 4,
label = { Text("message") }, label = { Text("message") },
// DECISION (item 3 of the follow-up card): the IME's action
// key sends; the soft keyboard cannot insert a manual
// newline. `ImeAction.Send` and `maxLines = 4` are not in
// conflict — `maxLines` is a wrap limit (a long message
// grows to four lines, then scrolls inside the field), not
// a newline affordance. Chat convention wins: Enter-to-send
// is what a messenger's users reach for, and the Send button
// is on the same row. Nothing is unreachable either — a
// hardware keyboard's Enter never goes through the IME
// action, so Shift+Enter still inserts a real newline in
// the field.
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Sentences,
imeAction = ImeAction.Send,
),
keyboardActions = KeyboardActions(onSend = { send() }),
) )
Spacer(Modifier.width(8.dp)) Spacer(Modifier.width(8.dp))
// Always drawn, never swapped out for a spinner: a button that
// changes size under the thumb — or disappears — is how "I hit
// send and nothing happened" gets reported.
OwButton(
text = "Send",
enabled = draft.isNotBlank() && pending == null,
onClick = send,
modifier = Modifier.testTag("chat-send"),
) {
if (pending != null) { if (pending != null) {
CircularProgressIndicator() CircularProgressIndicator(
} else { modifier = Modifier.size(14.dp),
Button( strokeWidth = 2.dp,
enabled = draft.isNotBlank(), color = LocalContentColor.current,
onClick = { )
pending = draft Spacer(Modifier.width(6.dp))
draft = "" }
}, Text("Send")
) { Text("Send") }
} }
} }
} }
} }
} }
/**
* One message's delivery marker, straight from the core's outbox state.
*
* The row carries an explicit announcement so a screen reader says
* "Queued, not delivered yet: retrying their onion (try 3/8, retry 45s)"
* instead of reading a clock glyph, and a [Delivery.testTag] so a UI test can
* find the state without depending on the glyph. [detail] is the outbox row's
* own counters when the join landed; when it is `null` the row keeps the flat
* marker. `send` shows a small indeterminate spinner while the worker has an
* attempt in flight.
*/
@Composable
private fun DeliveryMarker(d: Delivery, detail: QueuedRowDetail?) {
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 = deliveryAnnouncement(d, detail)
},
) {
if (d is Delivery.Sending) {
CircularProgressIndicator(
modifier = Modifier.size(10.dp),
strokeWidth = 1.5.dp,
color = tint,
)
Spacer(Modifier.width(4.dp))
}
Text(
deliveryMarkerText(d, detail),
style = MaterialTheme.typography.labelSmall,
color = tint,
)
}
}

View file

@ -0,0 +1,64 @@
package com.siriusdevops.onionwire.ui
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
/**
* True while a screen is rendered inside the shell that owns the bottom tab bar.
*
* The tab bar applies the navigation-bar inset itself, so a screen inside the
* shell must not pad for it a second time — that is the difference between the
* list ending just above the tabs and the list floating 48dp above them.
*/
val LocalBottomBarPresent = staticCompositionLocalOf { false }
/**
* The bottom + horizontal window insets one screen's content root must apply
* itself.
*
* `MainActivity` calls `enableEdgeToEdge()`, which means
* `setDecorFitsSystemWindows(window, false)`. On API 30+ that stops the
* framework from resizing the window for the soft keyboard: the manifest's
* `android:windowSoftInputMode="adjustResize"` has nothing left to resize, and
* the IME arrives as a *window inset* instead. `Scaffold`'s
* `contentWindowInsets` only covers `systemBars`, so anything anchored to the
* bottom of the window — the chat composer, a submit button under a text field
* — ends up drawn behind the keyboard, reachable only by dismissing it.
*
* The IME's bottom inset already covers the navigation bar, so the two are
* unioned (per-side `max`), never summed: keyboard height while typing,
* navigation-bar height otherwise, and no double padding in between. Inside the
* tab shell the vertical bar inset is dropped entirely — see
* [LocalBottomBarPresent].
*
* The `Top` side is deliberately excluded — a `Scaffold`'s `pad.top` is the app
* bar's own measured height, and the app bar carries its own status-bar inset
* (`TopAppBarDefaults.windowInsets`).
*
* Pair every use with `Scaffold(contentWindowInsets = WindowInsets(0, 0, 0, 0))`
* so the same inset is not applied twice.
*
* `@Composable` because `WindowInsets.systemBars` / `WindowInsets.ime` are
* composable reads — call it from a composable (every call site is one).
*/
@Composable
fun Modifier.screenContentInsets(): Modifier {
val sides = if (LocalBottomBarPresent.current) {
WindowInsetsSides.Horizontal
} else {
WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom
}
return windowInsetsPadding(
WindowInsets.systemBars.only(sides)
.union(WindowInsets.ime)
.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom),
)
}

View file

@ -1,28 +1,26 @@
package com.siriusdevops.onionwire.ui package com.siriusdevops.onionwire.ui
import android.content.ClipData
import android.content.ClipDescription
import android.os.Build
import android.os.PersistableBundle
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize 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.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@ -30,21 +28,44 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.ClipEntry
import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.platform.LocalClipboard
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.siriusdevops.onionwire.R
import com.siriusdevops.onionwire.ui.components.Label
import com.siriusdevops.onionwire.ui.components.Mono
import com.siriusdevops.onionwire.ui.components.OwAlertBanner
import com.siriusdevops.onionwire.ui.components.OwAlertVariant
import com.siriusdevops.onionwire.ui.components.OwButton
import com.siriusdevops.onionwire.ui.components.OwButtonVariant
import com.siriusdevops.onionwire.ui.components.OwCard
import com.siriusdevops.onionwire.ui.components.OwDivider
import com.siriusdevops.onionwire.ui.components.OwQrCode
import com.siriusdevops.onionwire.ui.components.OwTopBar
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.FriendInfo
import uniffi.onionwire_sdk.InviteInfo import uniffi.onionwire_sdk.InviteInfo
@OptIn(ExperimentalMaterial3Api::class) /**
* Your invite, as a code and as text.
*
* The invite is the one artifact that leaves the device on purpose, so this
* screen is deliberately plain about what it is: one person, one trusted channel,
* nothing published. Both the QR and the text are here because a person pointing
* a camera at a screen and a person pasting into a chat client are different
* people, and neither is wrong.
*/
@Composable @Composable
fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) { fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) {
var invite by remember { mutableStateOf<String?>(null) } var invite by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf<String?>(null) } var error by remember { mutableStateOf<String?>(null) }
var copied by remember { mutableStateOf(false) } var copied by remember { mutableStateOf(false) }
val clip = LocalClipboardManager.current val clipboard = LocalClipboard.current
val scope = rememberCoroutineScope()
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
runCatching { ownerInvite() } runCatching { ownerInvite() }
@ -53,77 +74,135 @@ fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) {
} }
Scaffold( Scaffold(
topBar = { topBar = { OwTopBar(title = "Your invite", onBack = onBack) },
TopAppBar( // The root applies systemBars + IME itself (see `screenContentInsets`),
title = { Text("Your invite") }, // so Scaffold must not also pad for the navigation bar.
navigationIcon = { IconButton(onClick = onBack) { Text("<") } }, contentWindowInsets = WindowInsets(0, 0, 0, 0),
colors = TopAppBarDefaults.topAppBarColors( containerColor = OwColors.Canvas,
containerColor = MaterialTheme.colorScheme.background,
),
)
},
) { pad -> ) { pad ->
Column( Column(
Modifier.padding(pad).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), Modifier
.padding(pad)
.fillMaxSize()
.screenContentInsets()
.verticalScroll(rememberScrollState())
.padding(horizontal = 16.dp),
) { ) {
Text( Spacer(Modifier.height(8.dp))
"Hand this to one person, over a channel you already trust. " + OwAlertBanner(
"It is not published anywhere and cannot be looked up.", variant = OwAlertVariant.Info,
style = MaterialTheme.typography.bodySmall, title = "Not published anywhere",
color = MaterialTheme.colorScheme.onSurfaceVariant, description = "Hand this to one person over a channel you already " +
"trust. There is no directory and no lookup — that is the point.",
) )
Spacer(Modifier.height(12.dp)) Spacer(Modifier.height(16.dp))
when { when {
error != null -> Text( error != null -> OwAlertBanner(
error!!, variant = OwAlertVariant.Error,
style = MaterialTheme.typography.bodySmall, title = "Could not read your invite",
color = MaterialTheme.colorScheme.error, description = error,
) )
invite == null -> CircularProgressIndicator() invite == null -> Row(
Modifier.fillMaxWidth().padding(vertical = 32.dp),
horizontalArrangement = Arrangement.Center,
) { CircularProgressIndicator(color = OwColors.Accent) }
else -> { else -> {
Card( val payload = invite!!
colors = CardDefaults.cardColors( Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) {
containerColor = MaterialTheme.colorScheme.surfaceVariant, OwQrCode(payload = payload, size = 220.dp)
), }
) { Spacer(Modifier.height(16.dp))
// Four lines, ellipsised: the payload is ~1 KB, and a card
// that grows to fill the screen pushes Copy and Done out of
// reach — the copyable text is a fallback for the QR, not
// the main event. `Copy invite` always carries the whole
// string.
OwCard(Modifier.fillMaxWidth(), padding = 12.dp) {
Text( Text(
invite!!, payload,
style = MaterialTheme.typography.bodySmall, style = MonoStyle.copy(color = OwColors.TextSecondary),
modifier = Modifier.padding(12.dp), textAlign = TextAlign.Start,
maxLines = 4,
overflow = TextOverflow.Ellipsis,
) )
} }
Spacer(Modifier.height(12.dp)) Spacer(Modifier.height(12.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Button(onClick = { OwButton(
clip.setText(AnnotatedString(invite!!)) text = if (copied) "Copied" else "Copy invite",
onClick = {
scope.launch {
val clip = ClipData.newPlainText("onionwire invite", payload)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
clip.description.extras = PersistableBundle().apply {
putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true)
}
}
clipboard.setClipEntry(ClipEntry(clip))
copied = true copied = true
}) { Text(if (copied) "Copied" else "Copy") }
} }
Spacer(Modifier.height(20.dp)) },
Text("What is in it", style = MaterialTheme.typography.titleSmall) leadingIconRes = R.drawable.ic_ow_copy,
Spacer(Modifier.height(6.dp))
Mono("k ed25519 identity pubkey — who you are")
Mono("o current onion locator — where you are now")
Mono("spk x25519 signed prekey — session start material")
Mono("sig signature over k‖o‖spk — reject if it fails")
Spacer(Modifier.height(12.dp))
Text(
"The onion in here goes stale when you rotate. The key does not. " +
"If you re-share later, the same k updates their entry — it never " +
"creates a second friend.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
OwButton(
text = "Done",
variant = OwButtonVariant.Outline,
onClick = onBack,
)
}
Spacer(Modifier.height(24.dp))
OwCard(Modifier.fillMaxWidth()) {
Text(
"What is in it",
style = MaterialTheme.typography.titleSmall,
color = OwColors.TextPrimary,
)
Spacer(Modifier.height(8.dp))
InviteField("k", "ed25519 identity pubkey — who you are")
InviteField("o", "current onion locator — where you are now")
InviteField("spk", "x25519 signed prekey — session start material")
InviteField("sig", "signature over k‖o‖spk — reject if it fails")
Spacer(Modifier.height(10.dp))
OwDivider()
Spacer(Modifier.height(10.dp))
Text(
"The onion in here goes stale when you rotate. The key does " +
"not. If you re-share later, the same k updates their entry — " +
"it never creates a second friend.",
style = MaterialTheme.typography.bodySmall,
color = OwColors.TextSecondary,
)
}
Spacer(Modifier.height(24.dp))
} }
} }
} }
} }
} }
@OptIn(ExperimentalMaterial3Api::class) @Composable
private fun InviteField(key: String, meaning: String) {
Row(Modifier.padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {
Text(
key,
style = MonoStyle.copy(color = OwColors.Accent),
modifier = Modifier.padding(end = 10.dp),
)
Label(meaning)
}
}
/**
* Paste someone else's invite.
*
* Verification is a separate, explicit step from adding: the preview shows who
* they are and where they are reachable *before* anything is written to the
* roster, because a mistyped or swapped invite is the one thing a human can
* still catch.
*/
@Composable @Composable
fun PasteInviteScreen( fun PasteInviteScreen(
onDecode: suspend (String) -> InviteInfo, onDecode: suspend (String) -> InviteInfo,
@ -140,101 +219,96 @@ fun PasteInviteScreen(
val adding = flow.adding val adding = flow.adding
Scaffold( Scaffold(
topBar = { topBar = { OwTopBar(title = "Add contact", onBack = onBack) },
TopAppBar( // Same inset handoff as the chat composer: with the keyboard up, the
title = { Text("Add a friend") }, // Verify / Approve buttons under the invite field must still be
navigationIcon = { IconButton(onClick = onBack) { Text("<") } }, // reachable by scrolling, not by dismissing the keyboard.
colors = TopAppBarDefaults.topAppBarColors( contentWindowInsets = WindowInsets(0, 0, 0, 0),
containerColor = MaterialTheme.colorScheme.background, containerColor = OwColors.Canvas,
),
)
},
) { pad -> ) { pad ->
Column( Column(
Modifier.padding(pad).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), Modifier
.padding(pad)
.fillMaxSize()
.screenContentInsets()
.verticalScroll(rememberScrollState())
.padding(horizontal = 16.dp),
) { ) {
Spacer(Modifier.height(8.dp))
OutlinedTextField( OutlinedTextField(
value = raw, value = raw,
onValueChange = { onValueChange = {
raw = it raw = it
flow.clear() flow.clear()
}, },
label = { Text("onionwire:v1:…") }, label = { Text("onionwire:v2:…") },
minLines = 4, minLines = 4,
shape = RoundedCornerShape(OwRadius.Control),
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
) )
Spacer(Modifier.height(12.dp)) Spacer(Modifier.height(12.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Button( OwButton(
text = "Verify",
enabled = raw.isNotBlank() && !verifying && !adding, enabled = raw.isNotBlank() && !verifying && !adding,
onClick = { scope.launch { flow.verify(raw) } }, onClick = { scope.launch { flow.verify(raw) } },
) { Text("Verify") } )
if (added != null) { if (added != null) {
TextButton(onClick = onBack) { Text("Done") } OwButton(text = "Done", variant = OwButtonVariant.Outline, onClick = onBack)
} }
} }
Spacer(Modifier.height(16.dp)) Spacer(Modifier.height(16.dp))
error?.let { error?.let {
Text( OwAlertBanner(
it, variant = OwAlertVariant.Error,
style = MaterialTheme.typography.bodySmall, title = "That invite was not accepted",
color = MaterialTheme.colorScheme.error, description = "$it — unsigned or tampered invites are rejected " +
) "here, before anything is stored.",
Spacer(Modifier.height(8.dp))
Text(
"Unsigned or tampered invites are rejected here, before anything is stored.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
Spacer(Modifier.height(12.dp))
} }
preview?.let { p -> preview?.let { p ->
Card( OwCard(Modifier.fillMaxWidth()) {
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
),
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(12.dp)) {
Label("THEY ARE") Label("THEY ARE")
Mono(p.pubkeyHex) Spacer(Modifier.height(2.dp))
Spacer(Modifier.height(8.dp)) Mono(shortId(p.pubkeyHex, head = 12, tail = 8))
Spacer(Modifier.height(6.dp))
Text( Text(
"fingerprint ${p.pubkeyHex.take(16)}… — compare this with them " + "Compare this fingerprint with them over a second channel " +
"over a second channel before you trust it.", "before you trust it.",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = OwColors.TextSecondary,
) )
Spacer(Modifier.height(8.dp)) Spacer(Modifier.height(10.dp))
OwDivider()
Spacer(Modifier.height(10.dp))
Label("REACHABLE AT") Label("REACHABLE AT")
Mono(p.onion) Spacer(Modifier.height(2.dp))
} Mono(shortOnion(p.onion))
} }
Spacer(Modifier.height(12.dp)) Spacer(Modifier.height(12.dp))
Button( OwButton(
text = "Approve & add",
enabled = !adding && added == null, enabled = !adding && added == null,
onClick = { scope.launch { flow.add(raw) } }, onClick = { scope.launch { flow.add(raw) } },
) { Text("Approve & add") } leadingIconRes = R.drawable.ic_ow_add,
)
} }
added?.let { f -> added?.let { f ->
Spacer(Modifier.height(16.dp)) Spacer(Modifier.height(16.dp))
Text( OwAlertBanner(
"Added ${f.petname ?: f.fingerprint}", variant = OwAlertVariant.Info,
style = MaterialTheme.typography.titleSmall, title = "Added ${f.petname ?: shortId(f.fingerprint)}",
color = MaterialTheme.colorScheme.primary, description = "If that key was already in your roster, only the " +
) "locator was updated. One key is always one friend.",
Spacer(Modifier.height(4.dp))
Text(
"If that key was already in your roster, only the locator was updated. " +
"One key is always one friend.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
} }
Spacer(Modifier.height(24.dp))
} }
} }
} }

View file

@ -0,0 +1,181 @@
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.
*
* The *counting* rule mirrors `src/tui.rs::OutboxSummary`: `Queued` + `Sending`
* are "still coming", `Failed` is terminal and keeps a fail-closed statement on
* screen. The TUI's footer wording for an outstanding row also carries the
* reachability statement and retry clock (`peer unreachable, queued (n/8, retry
* 45s)`); on Android that per-row detail already lives in the row's own
* `queued (try n/8, retry …)` marker (`OutboxDetail.kt`), so the summary stays
* the short count form instead of repeating it.
*/
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,141 @@
package com.siriusdevops.onionwire.ui
/**
* Why a chat row is still queued, read from the SDK's outbox rows
* (`Wire.outbox(pubkeyHex)` → `OutboxRow { messageId, status, attempts,
* nextAttemptAt, lastError }`).
*
* [Delivery] answers *what* state a row is in; this file answers *how far along*
* it is — `queued (try 3/8, retry 45s)` — from the store's own counters, never
* from a time the app invented. Mirrors `src/tui.rs::retry_in_text` /
* `delivery_tag` so both clients word the same state the same way.
*
* Nothing here is Android-specific: the join and the wording are pure functions
* so `OutboxDetailTest` can assert them on the JVM without a device or the
* native binding.
*/
/**
* Next-attempt age for a queued row, from the absolute `next_attempt_at` the
* store holds. Mirrors `src/tui.rs::retry_in_text`:
* `<= 0` → `retry now`; `< 60` → `retry {n}s`; else → `retry {ceil-minutes}m`.
*/
fun retryInText(nextInSecs: Long): String = when {
nextInSecs <= 0L -> "retry now"
nextInSecs < 60L -> "retry ${nextInSecs}s"
else -> "retry ${(nextInSecs + 59L) / 60L}m"
}
/**
* The outbox row's own numbers for one queued chat row.
*
* Only `"queued"` rows produce one: a terminal `"failed"` row keeps the last
* time it was *scheduled* for, so rendering it as a countdown would be a lie —
* a failed row is rendered from [Delivery.Failed] alone. `"sending"` has an
* attempt in flight and no next-attempt time worth showing, matching the TUI's
* bare `sending` tag.
*/
data class QueuedRowDetail(
val attempts: UInt,
val maxAttempts: UInt,
val nextInSecs: Long,
) {
/** `queued (try 3/8, retry 45s)` — the row text, mirroring the TUI. */
val text: String = "queued (try $attempts/$maxAttempts, ${retryInText(nextInSecs)})"
/**
* `try 3/8, retry 45s` — the same numbers without the state word, for a
* screen reader that has already heard "Queued, not delivered yet".
*/
val announcement: String = "try $attempts/$maxAttempts, ${retryInText(nextInSecs)}"
}
/** One SDK `ChatMessage`, narrowed to the fields the join reads. */
data class ChatRowInput(val direction: String, val delivery: String?)
/** One SDK `OutboxRow`, narrowed to the fields the join reads. */
data class OutboxRowInput(
val messageId: Long,
val status: String,
val attempts: UInt,
val nextAttemptAt: Long,
)
/** The store's own three pending encodings, trimmed and lowercased. */
private fun outboxKind(status: String): String? = when (val s = status.trim().lowercase()) {
"queued", "sending", "failed" -> s
else -> null
}
/** The same kind, read off the status the SDK already resolved for the message. */
private fun deliveryKind(d: Delivery?): String? = when (d) {
Delivery.Queued -> "queued"
Delivery.Sending -> "sending"
is Delivery.Failed -> "failed"
Delivery.Sent, null -> null
}
/**
* The SDK's `OutboxRow.message_id` is `messages.id` — the key the chat list is
* ordered by. The SDK's `ChatMessage` does not carry that id yet, so this join
* is positional: `messages()` is `ORDER BY m.id` and the outbox rows are one
* per pending send, so the *n*th pending chat row owns the *n*th outbox row
* (rows are sorted by `messageId` to make that explicit rather than trusting the
* core's row order).
*
* A positional join is only allowed to speak when it can prove itself: if the
* counts disagree, if a row carries a status this build does not know, or if a
* row's status does not match the status the SDK already resolved for the
* message in that slot, *every* detail is dropped and the rows fall back to the
* flat `queued` / `sending` / `failed` markers. Wrong numbers are worse than
* none. (`ChatMessage.id` would remove the positional part entirely; tracked
* as follow-up work.)
*
* Returns one entry per input row, `null` wherever there is nothing to add.
*/
fun outboxDetails(
rows: List<ChatRowInput>,
outbox: List<OutboxRowInput>,
maxAttempts: UInt,
now: Long,
): List<QueuedRowDetail?> {
val none: List<QueuedRowDetail?> = List(rows.size) { null }
val pending = rows.indices.filter {
deliveryKind(parseDelivery(rows[it].direction, rows[it].delivery)) != null
}
val ordered = outbox.sortedBy { it.messageId }
if (pending.size != ordered.size) return none
val details = arrayOfNulls<QueuedRowDetail>(rows.size)
for ((slot, index) in pending.withIndex()) {
val row = ordered[slot]
val kind = outboxKind(row.status) ?: return none
if (kind != deliveryKind(parseDelivery(rows[index].direction, rows[index].delivery))) {
return none
}
if (kind == "queued") {
details[index] = QueuedRowDetail(
attempts = row.attempts,
maxAttempts = maxAttempts,
nextInSecs = row.nextAttemptAt - now,
)
}
}
return details.toList()
}
/**
* Marker text for one row: the outbox row's own numbers when the join landed,
* otherwise the flat state marker `MessageDelivery` already produced.
*/
fun deliveryMarkerText(d: Delivery, detail: QueuedRowDetail?): String =
if (detail == null) d.marker else "${d.glyph} ${detail.text}"
/**
* What a screen reader announces for one row. The detail is appended to the
* sentence [Delivery] carries, never replaces it: a bare `try 3/8` is not a
* sentence.
*/
fun deliveryAnnouncement(d: Delivery, detail: QueuedRowDetail?): String =
if (detail == null) d.contentDescription else "${d.contentDescription} (${detail.announcement})"

View file

@ -0,0 +1,453 @@
package com.siriusdevops.onionwire.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import com.siriusdevops.onionwire.R
import com.siriusdevops.onionwire.ui.components.OwButton
import com.siriusdevops.onionwire.ui.components.OwIconButton
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.siriusdevops.onionwire.WireViewModel
import kotlinx.coroutines.launch
import uniffi.onionwire_sdk.checkAddress
/**
* This identity's own profile — nickname, bio, Monero receiving address — the
* phone's half of the TUI's `/profile`.
*
* The screen is a thin shell over three SDK calls (`self_profile`,
* `set_self_profile`, `push_self_profile`) and every decision it makes is a
* pure function at the bottom of this file, covered by `ProfileDraftTest` on
* the JVM. Nothing here invents policy the core does not have:
*
* - The write goes through the core's own validation (nickname ≤ 64 bytes,
* bio ≤ 512, no newlines, a non-empty address must pass `check_address`).
* The screen pre-checks the address so a typo is refused *before* the write,
* with the typed text still in the field, instead of being reported as a
* store error after it.
* - An **empty** address is a real, allowed value: it clears the profile
* address. It is labelled with its consequence, because with no profile
* address and no running wallet the core has nothing to hand a payer
* (`Node::wallet_receive_address`) and the invoice path fails.
* - The bio is carried, not owned: a save that did not touch the bio field
* writes back the value read from the store immediately before the write, so
* a bio set in the TUI cannot be blanked from the phone.
* - The push is per friend and one-shot, exactly like the TUI's `save_profile`
* (which pushes to the selected friend): a peer whose onion is down fails
* and nothing is queued. A push failure is *not* a save failure — the local
* write already happened — so the two are reported separately.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProfileScreen(
vm: WireViewModel,
onBack: () -> Unit,
) {
val friends by vm.friends.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
// What the store held when this screen opened, and the live edits. Both
// null until the first read lands; the save button is dead until then.
var loaded by remember { mutableStateOf<ProfileDraft?>(null) }
var draft by remember { mutableStateOf<ProfileDraft?>(null) }
var loadError by remember { mutableStateOf<String?>(null) }
var addressError by remember { mutableStateOf<String?>(null) }
var saveError by remember { mutableStateOf<String?>(null) }
var status by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
vm.selfProfile().fold(
onSuccess = { p ->
val d = ProfileDraft(p.displayName, p.bio, p.xmrAddr)
loaded = d
draft = d
},
onFailure = { loadError = it.message ?: it.toString() },
)
}
Scaffold(
contentWindowInsets = WindowInsets(0, 0, 0, 0),
topBar = {
TopAppBar(
title = { Text("Profile") },
navigationIcon = {
OwIconButton(
iconRes = R.drawable.ic_ow_chevron_left,
contentDescription = "Back",
onClick = onBack,
)
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.background,
),
)
},
) { pad ->
Column(
Modifier
.padding(pad)
.fillMaxSize()
.screenContentInsets()
.verticalScroll(rememberScrollState()),
) {
val form = draft
if (form == null) {
Text(
loadError ?: "loading…",
style = MaterialTheme.typography.bodySmall,
color = if (loadError != null) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
modifier = Modifier
.padding(12.dp)
.testTag("profile-load-error"),
)
return@Column
}
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 8.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
),
) {
Column(Modifier.padding(12.dp)) {
Text(
"Friends see this nickname and pay to this address.",
style = MaterialTheme.typography.bodySmall,
)
Spacer(Modifier.height(4.dp))
Text(
"Nothing is published anywhere: each friend gets it only when " +
"this is saved and sent to them.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
OutlinedTextField(
value = form.nickname,
onValueChange = { draft = form.copy(nickname = it) },
singleLine = true,
label = { Text("nickname") },
supportingText = {
Text(
"What friends call you. Empty is allowed — they fall back to " +
"your fingerprint.",
style = MaterialTheme.typography.labelSmall,
)
},
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
.testTag("profile-nickname"),
)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = form.bio,
onValueChange = { draft = form.copy(bio = it) },
singleLine = true,
label = { Text("bio") },
supportingText = {
Text(
"Kept when you save without touching it, including one set in " +
"the TUI.",
style = MaterialTheme.typography.labelSmall,
)
},
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
.testTag("profile-bio"),
)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = form.address,
onValueChange = {
draft = form.copy(address = it)
addressError = null
},
singleLine = true,
isError = addressError != null,
label = { Text("Monero address") },
supportingText = {
Text(
// The consequence, on the screen, before a payment fails:
// `Node::wallet_receive_address` uses the wallet process's
// subaddress while it is up and this address otherwise,
// and with neither there is nothing to be paid to.
profileAddressNotice(form.address),
style = MaterialTheme.typography.labelSmall,
)
},
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
.testTag("profile-address"),
)
addressError?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier
.padding(horizontal = 12.dp, vertical = 4.dp)
.testTag("profile-address-error"),
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
horizontalArrangement = Arrangement.End,
) {
OwButton(
text = if (busy) "Saving…" else "Save",
onClick = {
addressError = null
saveError = null
status = null
val clean = form.normalized()
// The address check first: a typo must be refused before
// the write, and the field keeps exactly what was typed.
val problem = profileAddressProblem(clean.address) { addr ->
runCatching { checkAddress(addr) }
}
if (problem != null) {
addressError = problem
return@OwButton
}
scope.launch {
busy = true
try {
// Read the stored profile again for the bio
// alone: a bio edited elsewhere since this
// screen loaded must not be blanked by a save
// that never touched the field.
val storedBio = vm.selfProfile().getOrNull()?.bio
val bio = bioToWrite(
draftBio = clean.bio,
loadedBio = loaded?.bio.orEmpty(),
storedBio = storedBio ?: clean.bio,
)
vm.setSelfProfile(clean.nickname, bio, clean.address).fold(
onSuccess = {
// Every friend in the roster, like the
// TUI pushes on save. One-shot each: a
// peer that is down is a failure for
// that peer, never a save failure.
val outcomes = friends.map { f ->
ProfilePushOutcome(
label = friendLabel(f.petname, f.fingerprint),
error = vm.pushSelfProfile(f.pubkeyHex)
.exceptionOrNull()
?.let { it.message ?: it.toString() },
)
}
status = profileStatusLine(outcomes)
// Re-read so the form matches the store
// and the save button goes back to dead.
vm.selfProfile().onSuccess { p ->
val d = ProfileDraft(p.displayName, p.bio, p.xmrAddr)
loaded = d
draft = d
}
},
onFailure = { saveError = it.message ?: it.toString() },
)
} finally {
busy = false
}
}
},
enabled = !busy && profileSaveEnabled(loaded, form),
modifier = Modifier.testTag("profile-save"),
)
}
status?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier
.padding(horizontal = 12.dp, vertical = 4.dp)
.testTag("profile-status"),
)
}
saveError?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier
.padding(horizontal = 12.dp, vertical = 4.dp)
.testTag("profile-save-error"),
)
}
Spacer(Modifier.height(12.dp))
}
}
}
// --- the whole decision surface, pure ---------------------------------------
/**
* The three fields this screen edits, as they sit on screen.
*
* A local mirror of the SDK's `SelfProfile`, deliberately: the rules below are
* JVM-testable without UniFFI, and a `data class` gives the dirty check an
* equality that is the fields themselves rather than an identity.
*/
internal data class ProfileDraft(
val nickname: String = "",
val bio: String = "",
val address: String = "",
)
/** One friend's push outcome: the label the roster shows, and the failure if any. */
internal data class ProfilePushOutcome(
val label: String,
val error: String? = null,
)
/**
* Edge whitespace out of every field.
*
* A paste from a clipboard or a soft keyboard's autocorrect habitually carries
* leading/trailing spaces, and none of the three fields can mean anything with
* them: the core refuses a nickname or address carrying a newline, and
* `check_address` is a base58 decode that fails on a stray space. Interior
* whitespace is untouched — the user may well want it in a bio.
*/
internal fun ProfileDraft.normalized(): ProfileDraft = copy(
nickname = nickname.trim(),
bio = bio.trim(),
address = address.trim(),
)
/**
* The save button's rule.
*
* Dead until the first read lands (`loaded == null`), dead while the form is
* byte-identical to what was loaded, live as soon as it differs. Comparison is
* on the normalised forms, so typing a trailing space into a field does not
* offer a save that would write the same value back.
*
* An **empty nickname is allowed**: the core accepts it (it only bounds the
* length and forbids newlines), the TUI's `/profile` accepts it, and the roster
* already renders a friend with no nickname as their fingerprint. Clearing a
* nickname is therefore a real edit that must be saveable.
*/
internal fun profileSaveEnabled(loaded: ProfileDraft?, draft: ProfileDraft): Boolean =
loaded != null && draft.normalized() != loaded.normalized()
/**
* Why the typed address cannot be saved, or `null` when it can.
*
* Empty is *allowed* and returns `null` without calling [check] at all — it
* clears the profile address, which the core permits. A non-empty address is
* handed to [check] (`uniffi.onionwire_sdk.checkAddress` in production) and its
* message is the reason shown, so the words match the core's own.
*/
internal fun profileAddressProblem(address: String, check: (String) -> Result<Unit>): String? {
val trimmed = address.trim()
if (trimmed.isEmpty()) return null
return check(trimmed).exceptionOrNull()?.let { it.message ?: it.toString() }
}
/**
* The bio that actually gets written.
*
* The field wins only when it differs from what was loaded — i.e. the user
* edited it. Otherwise the value read from the store immediately before the
* write is passed through unchanged, which is what keeps a bio set in the TUI
* alive through a phone save that only changed the nickname.
*/
internal fun bioToWrite(draftBio: String, loadedBio: String, storedBio: String): String =
if (draftBio.trim() != loadedBio.trim()) draftBio.trim() else storedBio
/** The label the roster would show for a friend: petname, else the short id. */
internal fun friendLabel(petname: String?, fingerprint: String): String =
petname?.takeIf { it.isNotBlank() } ?: shortId(fingerprint)
/**
* The one line under the Save button, in the TUI's shape.
*
* `src/tui.rs` `save_profile` reports `profile saved · sent` on a clean push
* and `profile saved` with no friends; here the count and the per-friend
* failures are spelled out, because the phone pushes to **every** friend and
* "some of them failed" has to name which.
*/
internal fun profileStatusLine(outcomes: List<ProfilePushOutcome>): String {
if (outcomes.isEmpty()) return PROFILE_SAVED
val failed = outcomes.filter { it.error != null }
if (failed.isEmpty()) {
return "$PROFILE_SAVED · sent to ${friendCount(outcomes.size)}"
}
val sent = outcomes.size - failed.size
val detail = failed.joinToString("; ") { "${it.label}: ${it.error}" }
return "$PROFILE_SAVED · sent to $sent of ${friendCount(outcomes.size)} · failed: $detail"
}
private fun friendCount(n: Int): String = if (n == 1) "1 friend" else "$n friends"
/** The TUI's word for a local write that reached nobody. */
internal const val PROFILE_SAVED: String = "profile saved"
/**
* What an empty address means, stated where the address is typed.
*
* `Node::wallet_receive_address` answers with the wallet process's own subaddress
* while it is up, and this address otherwise; with neither, the invoice path
* fails outright. The user should read that here, not after a friend's payment
* bounces.
*/
internal fun profileAddressNotice(address: String): String =
if (address.trim().isEmpty()) {
"Empty is allowed, and it clears the profile address. Your receive address " +
"then comes from the running wallet — with no address " +
"here and no wallet running, nobody can send you an invoice."
} else {
"What friends pay to. Validated before it is saved; an invalid address is " +
"refused and nothing is written."
}

View file

@ -1,229 +1,379 @@
package com.siriusdevops.onionwire.ui package com.siriusdevops.onionwire.ui
import android.content.ClipData
import android.content.ClipDescription
import android.os.Build
import android.os.PersistableBundle
import android.widget.Toast
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize 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.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
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.text.font.FontFamily import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.ClipEntry
import androidx.compose.ui.platform.Clipboard
import androidx.compose.ui.platform.LocalClipboard
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.siriusdevops.onionwire.R
import com.siriusdevops.onionwire.ui.components.Identicon
import com.siriusdevops.onionwire.ui.components.Label
import com.siriusdevops.onionwire.ui.components.Mono
import com.siriusdevops.onionwire.ui.components.OwButton
import com.siriusdevops.onionwire.ui.components.OwButtonRow
import com.siriusdevops.onionwire.ui.components.OwButtonVariant
import com.siriusdevops.onionwire.ui.components.OwCard
import com.siriusdevops.onionwire.ui.components.OwConfirmDialog
import com.siriusdevops.onionwire.ui.components.OwDivider
import com.siriusdevops.onionwire.ui.components.OwIcon
import com.siriusdevops.onionwire.ui.components.OwIconButton
import com.siriusdevops.onionwire.ui.components.OwOverflowMenu
import com.siriusdevops.onionwire.ui.components.OwStatusDot
import com.siriusdevops.onionwire.ui.components.OwTopBar
import com.siriusdevops.onionwire.ui.components.TorStatusPill
import kotlinx.coroutines.launch
import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.FriendInfo
@OptIn(ExperimentalMaterial3Api::class) /**
* Home: your identity, and the roster.
*
* Three things changed from the alpha build and they are deliberate:
*
* - The identity block is one compact bar. The old expandable card, the version
* and key-type footnote and the keep-alive paragraph are gone from here: the
* technical lines moved to Node & Settings, and reachability is a status row
* there too. A home screen does not explain the transport before it shows the
* people.
* - The five text-link actions are gone. Invite and Add are the two first-class
* actions (in the empty state, and in the bar); the rare and destructive ones
* live behind the overflow menu.
* - The empty state says what to do next, with the two buttons that do it.
*
* Behaviour is unchanged: every callback here is the ViewModel call the old
* screen made — this screen only decides where the entry points sit.
*/
@Composable @Composable
fun RosterScreen( fun RosterScreen(
fingerprint: String, fingerprint: String,
onion: String,
sdkVersion: String,
friends: List<FriendInfo>, friends: List<FriendInfo>,
invite: suspend () -> String,
onOpenChat: (FriendInfo) -> Unit, onOpenChat: (FriendInfo) -> Unit,
onShare: () -> Unit, onShare: () -> Unit,
onPaste: () -> Unit, onPaste: () -> Unit,
onRotate: () -> Unit, onRotate: () -> Unit,
onWipe: () -> Unit, onWipe: () -> Unit,
onOpenProfile: () -> Unit,
onLock: () -> Unit, onLock: () -> Unit,
onOpenWallets: () -> Unit,
) { ) {
var confirmWipe by remember { mutableStateOf(false) } val context = LocalContext.current
val clipboard = LocalClipboard.current
val scope = rememberCoroutineScope()
var confirmDeleteAll by remember { mutableStateOf(false) }
Scaffold( Scaffold(
// The content root below consumes systemBars ∪ ime itself (see
// `screenContentInsets`), and the tab bar above this screen consumes the
// navigation-bar inset; zeroing the Scaffold's own insets is what keeps
// the list from being padded twice.
contentWindowInsets = WindowInsets(0, 0, 0, 0),
containerColor = OwColors.Canvas,
topBar = { topBar = {
TopAppBar( OwTopBar(
title = { Text("OnionWire") }, title = "OnionWire",
status = { TorStatusPill() },
actions = { actions = {
TextButton(onClick = onLock) { Text("Lock") } OwIconButton(
iconRes = R.drawable.ic_ow_lock,
contentDescription = "Lock and stop the node",
onClick = onLock,
)
OwOverflowMenu(
onOpenProfile = onOpenProfile,
onOpenWallets = onOpenWallets,
onRotate = onRotate,
onWipe = { confirmDeleteAll = true },
)
}, },
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.background,
),
) )
}, },
) { pad -> ) { pad ->
Column(Modifier.padding(pad).fillMaxSize()) { Column(Modifier.padding(pad).fillMaxSize().screenContentInsets()) {
IdentityBar(
Card( fingerprint = fingerprint,
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp), onCopyInvite = {
colors = CardDefaults.cardColors( scope.launch {
containerColor = MaterialTheme.colorScheme.surfaceVariant, runCatching { invite() }
), .onSuccess { payload ->
) { copyInvite(clipboard, payload)
Column(Modifier.padding(12.dp)) { Toast.makeText(context, "Invite address copied", Toast.LENGTH_SHORT).show()
Label("YOU (stable forever)") }
Mono(fingerprint) .onFailure {
Spacer(Modifier.height(10.dp)) Toast.makeText(context, "Could not read the invite", Toast.LENGTH_SHORT).show()
Label("ONION (locator — rotates)") }
Mono(onion) }
Spacer(Modifier.height(10.dp)) },
Text( onShare = onShare,
"sdk $sdkVersion · identity = ed25519 pubkey",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
}
}
Spacer(Modifier.height(8.dp)) Spacer(Modifier.height(12.dp))
Row(
Modifier.fillMaxWidth().padding(horizontal = 8.dp),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
TextButton(onClick = onShare) { Text("Invite") }
TextButton(onClick = onPaste) { Text("Add") }
TextButton(onClick = onRotate) { Text("Rotate") }
TextButton(onClick = { confirmWipe = true }) { Text("Wipe chat") }
}
if (confirmWipe) {
ConfirmStrip(
text = "Delete every message body? Identity and friends stay.",
confirm = "WIPE",
onConfirm = { confirmWipe = false; onWipe() },
onCancel = { confirmWipe = false },
)
}
HorizontalDivider(Modifier.padding(vertical = 8.dp))
if (friends.isEmpty()) { if (friends.isEmpty()) {
EmptyRoster(
modifier = Modifier.weight(1f),
onPaste = onPaste,
onShare = onShare,
)
} else {
LazyColumn(Modifier.weight(1f).fillMaxWidth()) {
items(friends, key = { it.pubkeyHex }) { f ->
FriendRow(f) { onOpenChat(f) }
OwDivider(Modifier.padding(horizontal = 16.dp))
}
}
}
}
}
if (confirmDeleteAll) {
OwConfirmDialog(
title = "Delete all message history?",
body = "Every message body on this device is deleted. Your identity, " +
"your friends and the pending queue are untouched.",
confirmationWord = "DELETE",
confirmLabel = "Delete history",
destructive = true,
onConfirm = {
confirmDeleteAll = false
onWipe()
},
onDismiss = { confirmDeleteAll = false },
)
}
}
/**
* Your identity, as one bar: identicon, label, truncated pubkey, then the two
* actions a person actually performs here — copy the invite, show it as a code.
*/
@Composable
private fun IdentityBar(
fingerprint: String,
onCopyInvite: () -> Unit,
onShare: () -> Unit,
) {
OwCard(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
padding = 12.dp,
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Identicon(seed = fingerprint, size = 40.dp)
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) {
Label("Your identity")
Spacer(Modifier.height(2.dp))
Mono(shortId(fingerprint))
}
OwIconButton(
iconRes = R.drawable.ic_ow_copy,
contentDescription = "Copy invite address",
onClick = onCopyInvite,
)
Spacer(Modifier.width(8.dp))
OwIconButton(
iconRes = R.drawable.ic_ow_qr,
contentDescription = "Show your invite",
onClick = onShare,
)
}
}
}
/**
* The empty roster.
*
* The honest sentence stays: invites are not discoverable, nothing is published.
* The two buttons are the two ways out of this state, in the order that helps —
* paste a peer's invite, or hand yours out.
*/
@Composable
private fun EmptyRoster(
modifier: Modifier = Modifier,
onPaste: () -> Unit,
onShare: () -> Unit,
) {
Column( Column(
Modifier.fillMaxSize().padding(24.dp), modifier = modifier.fillMaxWidth().padding(horizontal = 24.dp),
verticalArrangement = Arrangement.Center, verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
) { ) {
Text("No friends yet", style = MaterialTheme.typography.titleMedium) Box(
Spacer(Modifier.height(8.dp)) Modifier
Text( .width(64.dp)
"Share your invite over a channel you already trust, or paste " + .height(64.dp)
"someone else's. Invites are not discoverable — nothing is published.", .clip(CircleShape)
style = MaterialTheme.typography.bodySmall, .background(OwColors.Surface),
color = MaterialTheme.colorScheme.onSurfaceVariant, contentAlignment = Alignment.Center,
) {
// Muted on purpose: the empty state is an invitation, not an alarm.
// The accent stays reserved for the one primary action below it.
OwIcon(
iconRes = R.drawable.ic_ow_shield,
contentDescription = null,
tint = OwColors.TextSecondary,
size = 30.dp,
) )
} }
} else { Spacer(Modifier.height(16.dp))
LazyColumn(Modifier.fillMaxSize()) { Text(
items(friends, key = { it.pubkeyHex }) { f -> "No contacts yet",
FriendRow(f) { onOpenChat(f) } style = MaterialTheme.typography.titleMedium.copy(fontSize = 18.sp, lineHeight = 24.sp),
HorizontalDivider() color = OwColors.TextPrimary,
} )
} Spacer(Modifier.height(8.dp))
} Text(
"Share your invite over a channel you already trust, or paste a peer's " +
"invite to start an end-to-end encrypted chat. Invites are not " +
"discoverable — nothing is published.",
style = MaterialTheme.typography.bodySmall,
color = OwColors.TextSecondary,
textAlign = TextAlign.Center,
modifier = Modifier.widthIn(max = 280.dp),
)
Spacer(Modifier.height(20.dp))
OwButtonRow(Modifier.widthIn(max = 320.dp)) {
OwButton(
text = "Add contact",
onClick = onPaste,
variant = OwButtonVariant.Primary,
modifier = Modifier.weight(1f),
leadingIconRes = R.drawable.ic_ow_add,
)
OwButton(
text = "Share my invite",
onClick = onShare,
variant = OwButtonVariant.Secondary,
modifier = Modifier.weight(1f),
)
} }
} }
} }
@Composable @Composable
private fun FriendRow(f: FriendInfo, onClick: () -> Unit) { private fun FriendRow(f: FriendInfo, onClick: () -> Unit) {
Column( Row(
Modifier Modifier
.fillMaxWidth() .fillMaxWidth()
.clickable(onClick = onClick) .clickable(onClick = onClick)
.background(MaterialTheme.colorScheme.background)
.padding(horizontal = 16.dp, vertical = 12.dp), .padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) { ) {
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
Text( Text(
f.petname?.takeIf { it.isNotBlank() } ?: f.fingerprint, f.petname?.takeIf { it.isNotBlank() } ?: f.fingerprint,
style = MaterialTheme.typography.titleSmall, style = MaterialTheme.typography.titleSmall,
color = OwColors.TextPrimary,
) )
if (!f.lastConnectOk) { if (!f.lastConnectOk) {
Spacer(Modifier.height(0.dp)) Spacer(Modifier.width(8.dp))
OwStatusDot(OwColors.Warning)
Spacer(Modifier.width(6.dp))
Text( Text(
" locator stale", "locator stale",
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.error, color = OwColors.Warning,
) )
} }
} }
Spacer(Modifier.height(2.dp)) Spacer(Modifier.height(3.dp))
Text( Text(
f.fingerprint, shortId(f.fingerprint),
style = MaterialTheme.typography.bodySmall, style = MonoStyle,
fontFamily = FontFamily.Monospace, color = OwColors.TextSecondary,
color = MaterialTheme.colorScheme.primary,
) )
Text( Text(
f.onion, shortOnion(f.onion),
style = MaterialTheme.typography.labelSmall, style = MonoStyle.copy(color = OwColors.TextMuted),
fontFamily = FontFamily.Monospace,
color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
} }
Text("›", style = MaterialTheme.typography.titleMedium, color = OwColors.TextMuted)
}
} }
@Composable /**
fun Label(text: String) { * Clipboard handling for the invite.
Text( *
text, * The invite is a locator plus a prekey: it is a secret-ish string that opens a
style = MaterialTheme.typography.labelSmall, * conversation with you, so the clip is marked sensitive (API 33+) — it will not
color = MaterialTheme.colorScheme.onSurfaceVariant, * be previewed on the lock screen or indexed by the clipboard UI. Nothing here
) * is logged, persisted, or drawn anywhere but the share sheet.
*/
private suspend fun copyInvite(clipboard: Clipboard, text: String) {
val clip = ClipData.newPlainText("onionwire invite", text)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
clip.description.extras = PersistableBundle().apply {
putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true)
}
}
clipboard.setClipEntry(ClipEntry(clip))
} }
@Composable /**
fun Mono(text: String) { * The compact stand-in for a long identity string: `head` characters, an
Text( * ellipsis, then `tail` characters. Pure, so the roster's line and its unit test
text, * agree on what "short" means.
style = MaterialTheme.typography.bodySmall, *
fontFamily = FontFamily.Monospace, * A string no longer than the abbreviation is returned unchanged — the
color = MaterialTheme.colorScheme.onSurface, * abbreviation must never grow a value, and a short value must never come back
) * mangled. Kotlin strings are UTF-16, but these IDs are hex, so `take`/`takeLast`
* cannot split a surrogate pair here.
*/
fun shortId(id: String, head: Int = 6, tail: Int = 4): String {
if (id.length < head + tail + 1) return id
return id.take(head) + "…" + id.takeLast(tail)
} }
@Composable /**
fun ConfirmStrip( * A v3 onion locator shortened for a roster row, with the `.onion` suffix kept
text: String, * visible: `abcdefghij…uvwxyz.onion`.
confirm: String, *
onConfirm: () -> Unit, * The suffix is the part that tells a reader this is an onion address at all, so
onCancel: () -> Unit, * it is never the part that gets truncated. The full value lives on the profile
) { * and invite screens, and a v3 locator is never soft-wrapped — a wrapped address
var typed by remember { mutableStateOf("") } * cannot be copied reliably.
Card( */
modifier = Modifier.fillMaxWidth().padding(12.dp), fun shortOnion(onion: String, head: Int = 10, tail: Int = 6): String {
colors = CardDefaults.cardColors( val suffix = ".onion"
containerColor = MaterialTheme.colorScheme.surfaceVariant, if (onion.isEmpty()) return onion
), if (!onion.endsWith(suffix)) return onion
) { val body = onion.removeSuffix(suffix)
Column(Modifier.padding(12.dp)) { if (body.length <= head + tail + 1) return onion
Text(text, style = MaterialTheme.typography.bodySmall) return body.take(head) + "…" + body.takeLast(tail) + suffix
Spacer(Modifier.height(8.dp))
androidx.compose.material3.OutlinedTextField(
value = typed,
onValueChange = { typed = it },
singleLine = true,
label = { Text("Type $confirm") },
modifier = Modifier.fillMaxWidth(),
)
Spacer(Modifier.height(8.dp))
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
TextButton(onClick = onCancel) { Text("Cancel") }
TextButton(
onClick = onConfirm,
enabled = typed.trim().equals(confirm, ignoreCase = true),
) { Text("Confirm") }
}
}
}
} }

View file

@ -4,13 +4,13 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize 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.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
@ -28,6 +28,12 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.siriusdevops.onionwire.R
import com.siriusdevops.onionwire.ui.components.Label
import com.siriusdevops.onionwire.ui.components.Mono
import com.siriusdevops.onionwire.ui.components.OwButton
import com.siriusdevops.onionwire.ui.components.OwButtonVariant
import com.siriusdevops.onionwire.ui.components.OwIconButton
/** /**
* Rotating publishes a brand new onion service and hard-cuts the old one. * Rotating publishes a brand new onion service and hard-cuts the old one.
@ -53,15 +59,29 @@ fun RotateScreen(
topBar = { topBar = {
TopAppBar( TopAppBar(
title = { Text("Rotate onion") }, title = { Text("Rotate onion") },
navigationIcon = { IconButton(onClick = onBack) { Text("<") } }, navigationIcon = {
OwIconButton(
iconRes = R.drawable.ic_ow_chevron_left,
contentDescription = "Back",
onClick = onBack,
)
},
colors = TopAppBarDefaults.topAppBarColors( colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.background, containerColor = MaterialTheme.colorScheme.background,
), ),
) )
}, },
// Root owns systemBars + IME (see `screenContentInsets`) so the confirm
// button under the passphrase field stays reachable with the keyboard up.
contentWindowInsets = WindowInsets(0, 0, 0, 0),
) { pad -> ) { pad ->
Column( Column(
Modifier.padding(pad).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), Modifier
.padding(pad)
.fillMaxSize()
.screenContentInsets()
.verticalScroll(rememberScrollState())
.padding(16.dp),
) { ) {
Text("Rotate onion address?", style = MaterialTheme.typography.titleLarge) Text("Rotate onion address?", style = MaterialTheme.typography.titleLarge)
Spacer(Modifier.height(12.dp)) Spacer(Modifier.height(12.dp))
@ -90,11 +110,13 @@ fun RotateScreen(
) )
Spacer(Modifier.height(12.dp)) Spacer(Modifier.height(12.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button( OwButton(
text = "Rotate",
variant = OwButtonVariant.Destructive,
enabled = typed.trim().equals("ROTATE", ignoreCase = true) && enabled = typed.trim().equals("ROTATE", ignoreCase = true) &&
!busy, !busy,
onClick = { busy = true; error = null }, onClick = { busy = true; error = null },
) { Text("Rotate") } )
if (busy) CircularProgressIndicator() if (busy) CircularProgressIndicator()
} }
} }
@ -132,7 +154,11 @@ fun RotateScreen(
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
Spacer(Modifier.height(16.dp)) Spacer(Modifier.height(16.dp))
Button(onClick = onBack) { Text("Back — share the new invite") } OwButton(
text = "Share the new invite",
variant = OwButtonVariant.Secondary,
onClick = onBack,
)
} }
} }
} }

View file

@ -0,0 +1,113 @@
package com.siriusdevops.onionwire.ui
/**
* Where the open wallet's key material came from.
*
* The distinction is the whole gate. A seed the user *supplied* (import) is a
* seed the user already has on paper, so that wallet is backed up from the
* start. A seed the app *generated* (create) has been read by nobody until it
* is put on screen, so that wallet starts unbacked and stays unbacked until the
* user proves it is written down.
*/
enum class WalletKeyOrigin {
Created,
Imported,
}
/**
* The seed-backup gate: every decision the wallet screen makes about an
* unconfirmed seed, as pure Kotlin — no Compose, no Android, no prefs — so the
* rules are covered by `SeedBackupGateTest` on the JVM without a device.
*
* The gate exists because a seed shown once and then lost is an unrecoverable
* wallet: XMR received into a wallet whose 25 words were never written down
* cannot be spent or recovered by anyone, including this app. So the answer is
* not advisory — while it says the seed is unbacked, the wallet screen keeps a
* warning up and hides the receive address and its QR.
*
* The confirm word and its case-insensitivity mirror the TUI's own seed screen
* (`src/tui.rs`, `WalletSetup::CreateSeed`, which compares with
* `eq_ignore_ascii_case("SEEN")`) instead of inventing a second convention for
* the same wallet.
*/
object SeedBackupGate {
/** The word that releases the block. The TUI's word, not a new one. */
const val CONFIRM_WORD: String = "SEEN"
/**
* True when [typed] releases the block.
*
* Trimmed and case-insensitive, so a soft keyboard's auto-capitalised `Seen`
* and a trailing space from a paste both count. Everything else — including
* the empty string — stays blocked.
*/
fun accepts(typed: String): Boolean =
typed.trim().equals(CONFIRM_WORD, ignoreCase = true)
/**
* The flag right after a wallet is created or imported.
*
* A create always resets it: the wallet file is new, and the seed it was
* built from has never been read by anyone.
*/
fun afterWallet(origin: WalletKeyOrigin): Boolean = when (origin) {
WalletKeyOrigin.Created -> false
WalletKeyOrigin.Imported -> true
}
/**
* The flag after one confirm step.
*
* Only a correct [typed] can flip it to `true`; a wrong word can never
* un-confirm a wallet that is already backed up.
*/
fun afterConfirm(typed: String, backedUp: Boolean): Boolean =
backedUp || accepts(typed)
/** Done is dead until the word is right. */
fun confirmEnabled(typed: String): Boolean = accepts(typed)
/**
* The persistent strip is up while this install has an unconfirmed seed.
*
* [confirmed] is the stored flag, and it is nullable on purpose:
*
* - `false` — this install created a wallet and nobody has confirmed the
* seed. The wallet exists whether or not its balance reads, so the strip
* is up regardless.
* - `true` — confirmed, or imported. Nothing to say.
* - `null` — nothing stored: an install that predates this flag, or one
* that has never created or imported a wallet here. "We never asked" is
* not "the user wrote it down", but it is also not evidence that a wallet
* exists — so the strip waits for [walletReadable], the core's own proof
* that the child has a wallet open.
*
* Without that last distinction the strip would fire on every install that
* has configured a chain source but not yet created a wallet, which is
* exactly the state a first-run user is in.
*/
fun warningVisible(confirmed: Boolean?, walletReadable: Boolean): Boolean = when (confirmed) {
true -> false
false -> true
null -> walletReadable
}
/**
* The receive address and its QR are shown only while there is no unbacked
* seed to worry about. Receiving into an unbacked wallet is the one mistake
* this gate exists to prevent, so the address is hidden rather than merely
* warned about.
*/
fun receiveAddressVisible(confirmed: Boolean?, walletReadable: Boolean): Boolean =
!warningVisible(confirmed, walletReadable)
/**
* The strip's words. One source: the screen renders this verbatim, so the
* reason the address disappeared travels with the hiding.
*/
const val WARNING: String =
"seed not backed up. write down the 25 words before you receive anything — " +
"a wallet whose seed was never written down cannot be recovered. " +
"the receive address stays hidden until you do."
}

View file

@ -0,0 +1,215 @@
package com.siriusdevops.onionwire.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.siriusdevops.onionwire.R
import com.siriusdevops.onionwire.ui.components.Label
import com.siriusdevops.onionwire.ui.components.Mono
import com.siriusdevops.onionwire.ui.components.OwCard
import com.siriusdevops.onionwire.ui.components.OwConfirmDialog
import com.siriusdevops.onionwire.ui.components.OwDivider
import com.siriusdevops.onionwire.ui.components.OwIconButton
import com.siriusdevops.onionwire.ui.components.OwSectionTitle
import com.siriusdevops.onionwire.ui.components.OwTopBar
import com.siriusdevops.onionwire.ui.components.TorStatusPill
/**
* The third tab: everything that is not a conversation or a balance.
*
* This is where the alpha build's honest-but-noisy bits went — the SDK line, the
* keep-alive paragraph, the identity rotation and the history wipe. They are not
* hidden; they are one tap away instead of on the screen a person opens twenty
* times a day. No behaviour lives here: every callback is a ViewModel call the
* old roster made.
*/
@Composable
fun SettingsScreen(
sdkVersion: String,
keepAliveNote: String?,
onOpenProfile: () -> Unit,
onOpenWallets: () -> Unit,
onRotate: () -> Unit,
onWipe: () -> Unit,
onLock: () -> Unit,
) {
var confirmDeleteAll by remember { mutableStateOf(false) }
Scaffold(
contentWindowInsets = WindowInsets(0, 0, 0, 0),
containerColor = OwColors.Canvas,
topBar = {
OwTopBar(
title = "Node & Settings",
status = { TorStatusPill() },
actions = {
OwIconButton(
iconRes = R.drawable.ic_ow_lock,
contentDescription = "Lock and stop the node",
onClick = onLock,
)
},
)
},
) { pad ->
Column(
Modifier
.padding(pad)
.fillMaxSize()
.screenContentInsets()
.verticalScroll(rememberScrollState())
.padding(horizontal = 16.dp),
) {
Spacer(Modifier.height(8.dp))
OwCard(Modifier.fillMaxWidth()) {
Label("ACCOUNT")
Spacer(Modifier.height(4.dp))
SettingsRow(
title = "Your profile",
subtitle = "Name, bio and Monero address",
onClick = onOpenProfile,
)
OwDivider()
SettingsRow(
title = "Saved wallets",
subtitle = "Open a wallet file, or check its backup",
onClick = onOpenWallets,
)
}
Spacer(Modifier.height(12.dp))
OwCard(Modifier.fillMaxWidth()) {
Label("REACHABILITY")
Spacer(Modifier.height(6.dp))
Text(
keepAliveNote ?: "Checking how this app is kept reachable…",
style = MaterialTheme.typography.bodySmall,
color = OwColors.TextSecondary,
)
}
Spacer(Modifier.height(12.dp))
OwCard(Modifier.fillMaxWidth()) {
Label("SECURITY & DATA")
Spacer(Modifier.height(4.dp))
SettingsRow(
title = "Rotate identity",
subtitle = "New onion address. Offline contacts must re-scan your invite.",
onClick = onRotate,
)
OwDivider()
SettingsRow(
title = "Delete message history",
subtitle = "Removes every message body on this device. Identity and contacts stay.",
danger = true,
onClick = { confirmDeleteAll = true },
)
}
Spacer(Modifier.height(12.dp))
OwCard(Modifier.fillMaxWidth()) {
OwSectionTitle("About")
Spacer(Modifier.height(8.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Label("IDENTITY")
Spacer(Modifier.width(10.dp))
Mono("ed25519")
}
Spacer(Modifier.height(4.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Label("SDK")
Spacer(Modifier.width(10.dp))
Mono(sdkVersion)
}
Spacer(Modifier.height(10.dp))
Text(
"Tor and the chain node run in-process. The wallet is an RPC the app " +
"owns and starts itself.",
style = MaterialTheme.typography.bodySmall,
color = OwColors.TextSecondary,
)
}
Spacer(Modifier.height(24.dp))
}
}
if (confirmDeleteAll) {
OwConfirmDialog(
title = "Delete all message history?",
body = "Every message body on this device is deleted. Your identity, " +
"your friends and the pending queue are untouched.",
confirmationWord = "DELETE",
confirmLabel = "Delete history",
destructive = true,
onConfirm = {
confirmDeleteAll = false
onWipe()
},
onDismiss = { confirmDeleteAll = false },
)
}
}
@Composable
private fun SettingsRow(
title: String,
subtitle: String,
onClick: () -> Unit,
danger: Boolean = false,
) {
Row(
Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.padding(vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Column(Modifier.weight(1f)) {
Text(
title,
style = MaterialTheme.typography.titleSmall,
color = if (danger) OwColors.Danger else OwColors.TextPrimary,
)
Spacer(Modifier.height(2.dp))
Text(
subtitle,
style = MaterialTheme.typography.bodySmall,
color = if (danger) Color(0xCCFF5C5C) else OwColors.TextSecondary,
)
}
Spacer(Modifier.width(12.dp))
Text(
"›",
style = MaterialTheme.typography.titleMedium,
color = if (danger) OwColors.Danger else OwColors.TextMuted,
)
}
}

View file

@ -1,34 +1,149 @@
package com.siriusdevops.onionwire.ui package com.siriusdevops.onionwire.ui
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Typography
import androidx.compose.material3.darkColorScheme import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
private val OnionViolet = Color(0xFF7C4DFF) /**
private val WireCyan = Color(0xFF38F2C7) * OnionWire design tokens.
private val DeepVoid = Color(0xFF0B0B10) *
private val PanelVoid = Color(0xFF15151C) * One canvas, two surfaces, one accent. The palette is deliberately small:
* every screen used to invent its own pill and its own grey, which is what made
* the alpha build read as a debug harness.
*
* Typography rule — the reason this file carries a [MonoStyle]: monospace is
* reserved for cryptographic material and numbers (pubkeys, truncated onion
* locators, seeds, `host:port`, block heights). Chrome is sans. A screen that
* sets `fontFamily = FontFamily.Monospace` on a sentence is a bug.
*/
object OwColors {
/** App canvas. */
val Canvas = Color(0xFF0A0C0E)
/** Cards and elevated surfaces. */
val Surface = Color(0xFF12161A)
/** Inputs, secondary buttons, segmented-control track. */
val SurfaceInteractive = Color(0xFF1C2228)
/** The one border. 1dp, never a gradient. */
val Border = Color(0xFF262E36)
/** Primary brand / accent. Text on top of it is [Canvas], semibold. */
val Accent = Color(0xFF2EE59D)
val TextPrimary = Color(0xFFF3F5F7)
val TextSecondary = Color(0xFF9BA3AE)
val TextMuted = Color(0xFF5E6773)
/** Success / connected is the accent — there is no second green. */
val Success = Accent
/** Warning / syncing. Text, 12% tint, 30% border. */
val Warning = Color(0xFFF5A623)
val WarningTint = Color(0x1FF5A623)
val WarningBorder = Color(0x4DF5A623)
/** Danger / error / destructive. */
val Danger = Color(0xFFFF5C5C)
val DangerTint = Color(0x1FFF5C5C)
val DangerBorder = Color(0x4DFF5C5C)
/** Info banner — the accent at banner tints, no third hue. */
val InfoTint = Color(0x142EE59D)
val InfoBorder = Color(0x3D2EE59D)
}
/** Geometry. Buttons and inputs are 12dp squircles, never 999dp pills. */
object OwRadius {
/** Cards and the identity bar. */
val Card = 16.dp
/** Buttons, inputs, icon surfaces, segmented control. */
val Control = 12.dp
/** Small status badges and address chips only. */
val Pill = 999.dp
}
/** Fixed sizes from the spec. */
object OwSize {
val Button = 48.dp
val ButtonCompact = 44.dp
val IconButton = 36.dp
val TabBar = 64.dp
val TabBarBorder = 1.dp
val ProgressTrack = 6.dp
}
/** The only monospace style in the app. */
val MonoStyle: TextStyle = TextStyle(
fontFamily = FontFamily.Monospace,
fontSize = 13.sp,
lineHeight = 18.sp,
color = OwColors.TextPrimary,
)
private val OnionWireTypography = Typography(
// Chrome: system sans. No display face, no bundled grotesque.
displaySmall = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.Bold, fontSize = 28.sp, lineHeight = 34.sp),
headlineSmall = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.SemiBold, fontSize = 22.sp, lineHeight = 28.sp),
titleLarge = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.SemiBold, fontSize = 20.sp, lineHeight = 26.sp),
titleMedium = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.SemiBold, fontSize = 16.sp, lineHeight = 22.sp),
titleSmall = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.Medium, fontSize = 15.sp, lineHeight = 20.sp),
bodyLarge = TextStyle(fontFamily = FontFamily.SansSerif, fontSize = 16.sp, lineHeight = 24.sp),
bodyMedium = TextStyle(fontFamily = FontFamily.SansSerif, fontSize = 14.sp, lineHeight = 20.sp),
bodySmall = TextStyle(fontFamily = FontFamily.SansSerif, fontSize = 13.sp, lineHeight = 18.sp),
labelLarge = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.SemiBold, fontSize = 14.sp, lineHeight = 18.sp),
labelMedium = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.Medium, fontSize = 12.sp, lineHeight = 16.sp),
labelSmall = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 14.sp, letterSpacing = 0.6.sp),
)
/**
* The scheme Material components (text fields, dialogs, dividers) still read
* from. New UI should take tokens from [OwColors] directly; `surfaceVariant`
* and `onSurfaceVariant` are mapped so untouched Material defaults do not fall
* back to purple.
*/
private val OnionWireColors = darkColorScheme( private val OnionWireColors = darkColorScheme(
primary = WireCyan, primary = OwColors.Accent,
onPrimary = DeepVoid, onPrimary = OwColors.Canvas,
primaryContainer = OnionViolet, primaryContainer = OwColors.SurfaceInteractive,
onPrimaryContainer = Color.White, onPrimaryContainer = OwColors.TextPrimary,
secondary = OnionViolet, secondary = OwColors.SurfaceInteractive,
onSecondary = Color.White, onSecondary = OwColors.TextPrimary,
background = DeepVoid, tertiary = OwColors.TextSecondary,
onBackground = Color(0xFFE6E6F0), onTertiary = OwColors.Canvas,
surface = DeepVoid, background = OwColors.Canvas,
onSurface = Color(0xFFE6E6F0), onBackground = OwColors.TextPrimary,
surfaceVariant = PanelVoid, surface = OwColors.Canvas,
onSurfaceVariant = Color(0xFFB9B9CC), onSurface = OwColors.TextPrimary,
outline = Color(0xFF3A3A4A), surfaceVariant = OwColors.Surface,
error = Color(0xFFFF6B6B), onSurfaceVariant = OwColors.TextSecondary,
onError = DeepVoid, surfaceContainer = OwColors.Surface,
surfaceContainerHigh = OwColors.SurfaceInteractive,
surfaceContainerLow = OwColors.Surface,
outline = OwColors.Border,
outlineVariant = OwColors.Border,
error = OwColors.Danger,
onError = OwColors.Canvas,
errorContainer = OwColors.DangerTint,
onErrorContainer = OwColors.Danger,
scrim = Color(0xCC000000),
) )
@Composable @Composable
fun OnionWireTheme(content: @Composable () -> Unit) { fun OnionWireTheme(content: @Composable () -> Unit) {
MaterialTheme(colorScheme = OnionWireColors, content = content) MaterialTheme(
colorScheme = OnionWireColors,
typography = OnionWireTypography,
content = content,
)
} }

View file

@ -2,19 +2,25 @@ package com.siriusdevops.onionwire.ui
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize 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.safeDrawingPadding
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
@ -22,20 +28,62 @@ 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.LocalSoftwareKeyboardController
import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.siriusdevops.onionwire.Phase import com.siriusdevops.onionwire.Phase
import com.siriusdevops.onionwire.Unlock
import com.siriusdevops.onionwire.crypto.KeyBacking
/**
* Lock screen.
*
* When [Unlock.OneTap] is set, the passphrase is already on disk wrapped by the
* Android Keystore key and the user taps once. Otherwise they type it — and
* they land here, with [Unlock.TypeIt.notice] explaining why, whenever the
* stored blob cannot be read (key invalidated, device reset, corrupt file).
*
* The typed passphrase lives in a plain `remember` (not `rememberSaveable`) and
* is cleared as soon as it is handed to the ViewModel: it never survives a
* config change and never gets written to the saved-instance-state bundle.
*/
@Composable @Composable
fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) { fun UnlockScreen(
phase: Phase,
unlock: Unlock,
onUnlock: (passphrase: String, remember: Boolean) -> Unit,
onUnlockStored: () -> Unit,
onForgetStored: () -> Unit,
) {
var pass by remember { mutableStateOf("") } var pass by remember { mutableStateOf("") }
var storePassphrase by remember { mutableStateOf(true) }
// Only meaningful under OneTap: reveal the form without giving up the
// stored passphrase.
var typeInstead by remember { mutableStateOf(false) }
val keyboard = LocalSoftwareKeyboardController.current
val oneTap = unlock as? Unlock.OneTap
val failed = phase is Phase.Failed
val showForm = oneTap == null || typeInstead || failed
// IME Done and Open share this. Done with no KeyboardActions used to
// dismiss the keyboard and never call unlock, so bootstrap never started.
fun submit() {
val handed = unlockSubmit(pass, storePassphrase) ?: return
pass = ""
keyboard?.hide()
onUnlock(handed.passphrase, handed.remember)
}
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
// This screen has no Scaffold, so its root owns every window inset:
// without this the keyboard covers the passphrase field's Open
// button and the status bar overlaps the title.
.safeDrawingPadding()
.verticalScroll(rememberScrollState()) .verticalScroll(rememberScrollState())
.padding(24.dp), .padding(24.dp),
verticalArrangement = Arrangement.Center, verticalArrangement = Arrangement.Center,
@ -64,11 +112,49 @@ fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
} }
else -> { else -> {
Text( if (oneTap != null && !failed) {
"Passphrase", Text("Passphrase", style = MaterialTheme.typography.titleSmall)
style = MaterialTheme.typography.titleSmall,
)
Spacer(Modifier.height(8.dp)) Spacer(Modifier.height(8.dp))
Text(
"Stored on this device, wrapped by an Android Keystore key " +
"(${backingLabel(oneTap.backing)}).",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(20.dp))
Button(
onClick = onUnlockStored,
modifier = Modifier.fillMaxWidth(),
) { Text("Unlock") }
Spacer(Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
TextButton(onClick = { typeInstead = true }) {
Text("Type it instead")
}
TextButton(onClick = onForgetStored) {
Text("Forget stored passphrase")
}
}
if (showForm) {
Spacer(Modifier.height(16.dp))
HorizontalDivider()
Spacer(Modifier.height(16.dp))
}
}
if (showForm) {
if (unlock is Unlock.TypeIt && unlock.notice != null) {
Text(
unlock.notice,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(16.dp))
}
OutlinedTextField( OutlinedTextField(
value = pass, value = pass,
onValueChange = { pass = it }, onValueChange = { pass = it },
@ -76,7 +162,11 @@ fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
visualTransformation = PasswordVisualTransformation(), visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions( keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password, keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done, imeAction = ImeAction.Go,
),
keyboardActions = KeyboardActions(
onGo = { submit() },
onDone = { submit() },
), ),
label = { Text("wraps the local message key") }, label = { Text("wraps the local message key") },
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@ -88,14 +178,39 @@ fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
Spacer(Modifier.height(4.dp))
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth(),
) {
Checkbox(
checked = storePassphrase,
onCheckedChange = { storePassphrase = it },
)
Text(
"Remember on this device (wrapped by the Android Keystore, " +
"no backup)",
style = MaterialTheme.typography.bodySmall,
)
}
if (oneTap != null) {
Text(
"Typing and remembering replaces the stored passphrase.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Spacer(Modifier.height(20.dp)) Spacer(Modifier.height(20.dp))
Button( Button(
onClick = { onUnlock(pass) }, onClick = { submit() },
enabled = pass.isNotEmpty(), enabled = pass.isNotEmpty(),
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
) { Text("Open") } ) { Text("Open") }
}
if (phase is Phase.Failed) { if (failed) {
Spacer(Modifier.height(20.dp)) Spacer(Modifier.height(20.dp))
Text( Text(
"Failed to start", "Failed to start",
@ -122,9 +237,22 @@ fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
Spacer(Modifier.height(24.dp)) Spacer(Modifier.height(24.dp))
Text( Text(
"INTERNET is the only permission this app requests.", "Permissions: internet, plus a foreground service and its notification so " +
"the onion stays reachable while the screen is off. No camera, contacts " +
"or storage.",
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
} }
} }
/**
* What the Keystore reported, verbatim. Never upgraded into a stronger claim:
* a software key says so.
*/
internal fun backingLabel(backing: KeyBacking): String = when (backing) {
KeyBacking.STRONGBOX -> "StrongBox"
KeyBacking.HARDWARE -> "TEE-backed"
KeyBacking.SOFTWARE -> "software key, NOT hardware-backed"
KeyBacking.UNKNOWN -> "backing not reported by this device"
}

View file

@ -0,0 +1,16 @@
package com.siriusdevops.onionwire.ui
/**
* One submit for IME Done and the Open button.
*
* The IME action used to be `Done` with no [androidx.compose.foundation.text.KeyboardActions]:
* the keyboard closed and [com.siriusdevops.onionwire.WireViewModel.unlock] was never
* called, so bootstrap never started. Empty stays a no-op — the SDK fails closed
* on an empty passphrase, and we do not open the node for it.
*/
internal data class UnlockSubmit(val passphrase: String, val remember: Boolean)
internal fun unlockSubmit(pass: String, remember: Boolean): UnlockSubmit? {
if (pass.isEmpty()) return null
return UnlockSubmit(passphrase = pass, remember = remember)
}

View file

@ -0,0 +1,850 @@
package com.siriusdevops.onionwire.ui
import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE
import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths
import java.io.File
import java.util.Locale
/**
* One snapshot of the app-owned wallet process, as the wallet screen sees it.
*
* A plain mirror of the fields `WalletChildStatus` carries over UniFFI
* (`state`, `running`, `configured`, `chain_source`, `last_error`) — the same
* shape as `ChatRowInput` / `OutboxRowInput`, so this model and its tests stay
* on the JVM and never load the generated UniFFI types or JNA.
*
* `state` is the core's own word (`src/wallet_child.rs::WalletChildState`):
* `off` / `connecting` / `syncing` / `ready` / `exited`. Nothing here is
* inferred from a timeout, and nothing is invented: a state this build does not
* recognise is reported as unrecognised rather than folded into one that would
* read better.
*/
data class WalletChildInput(
val state: String,
/** A `monero-wallet-rpc` process is alive right now. */
val running: Boolean,
/** A chain source is configured (anything but receive-only). */
val configured: Boolean,
/** The core's label: `receive-only` / `local node` / `remote onion daemon` / `remote daemon`. */
val chainSource: String,
/**
* The configured source runs the chain daemon **inside this app** (Cuprate)
* rather than spawning `monerod` or dialling a remote one — the core's
* `chain_in_process`. When true the line grows a node segment, because there
* is no separate daemon process for the state word to describe.
*/
val chainInProcess: Boolean = false,
/**
* This build carries `cuprate-daemon`, so the in-process node can actually
* start — the core's `node_available`. `false` means the option is stored but
* a start can only fail: say so before the user commits, never after.
*/
val nodeAvailable: Boolean = true,
/**
* The node's own word — the core's `node_state`: `off` / `starting` /
* `syncing` / `ready` / `exited`. **Empty** for every other chain source, and
* empty for an in-process source that has not been read yet.
*/
val nodeState: String = "",
/**
* Blocks the chain daemon had at the last probe — the core's `height`, from
* the wallet RPC or, when that RPC is refused, from the in-process daemon
* over loopback. `0` means unknown: never probed, the child is off/exited, or
* the probe failed. It is **not** caught up, and it is never a wallet-scan
* height.
*
* `ULong` because that is what UniFFI generates for the Rust `u64` (checked
* against `uniffi.onionwire_sdk.WalletChildStatus`, not assumed) — this model
* mirrors that record field for field.
*/
val height: ULong = 0uL,
/** Blocks the daemon was syncing towards — the core's `target_height`. `0` means none reported (also not caught up). */
val targetHeight: ULong = 0uL,
val lastError: String? = null,
)
/**
* What the wallet screen renders for one snapshot.
*
* The five states are the core's; there is no sixth "starting…". A child that
* was started and is gone is [Exited] — never [Off], and never [Ready]: the
* whole point of the control is that the user can see and drive the child.
* [Unread] is not a state of the child at all, it is the first
* `wallet_status()` read still in flight, and it is a word rather than a
* spinner so a stuck read is readable instead of merely animated.
*
* [testTag] and [contentDescription] are the assertable handles, matching
* `Delivery`: a screen reader gets a sentence, never a bare glyph or a bare
* word.
*/
sealed interface WalletChildPhase {
/** Stable handle for Compose semantics and tests. */
val testTag: String
/** Word drawn on the status line. */
val label: String
/** What a screen reader announces. Always a sentence. */
val contentDescription: String
/** A child process is up. */
val live: Boolean
/** A started child is gone. Never `off`, never `ready`. */
val dead: Boolean
/** Nothing read yet. */
data object Unread : WalletChildPhase {
override val testTag: String = "child-unread"
override val label: String = "reading…"
override val contentDescription: String = "Reading the wallet status"
override val live: Boolean = false
override val dead: Boolean = false
}
/** No child has been started, or it was stopped. */
data object Off : WalletChildPhase {
override val testTag: String = "child-off"
override val label: String = "off"
override val contentDescription: String = "The wallet is off"
override val live: Boolean = false
override val dead: Boolean = false
}
/** The process exists; its wallet RPC has not answered yet. */
data object Connecting : WalletChildPhase {
override val testTag: String = "child-connecting"
override val label: String = "connecting"
override val contentDescription: String =
"The wallet is starting; its RPC has not answered yet"
override val live: Boolean = true
override val dead: Boolean = false
}
/** The wallet answered; the chain is behind the tip. */
data object Syncing : WalletChildPhase {
override val testTag: String = "child-syncing"
override val label: String = "syncing"
override val contentDescription: String =
"The wallet is answering; the chain is not at the tip yet"
override val live: Boolean = true
override val dead: Boolean = false
}
/** Wallet RPC answered and the chain is at the tip. */
data object Ready : WalletChildPhase {
override val testTag: String = "child-ready"
override val label: String = "ready"
override val contentDescription: String = "The wallet is ready"
override val live: Boolean = true
override val dead: Boolean = false
}
/** A started child has died. [reason] is the core's `last_error`, if any. */
data class Exited(val reason: String?) : WalletChildPhase {
override val testTag: String = "child-exited"
override val label: String = "exited"
override val contentDescription: String = "The wallet process exited"
override val live: Boolean = false
override val dead: Boolean = true
}
/**
* A state string this build does not know. Fail-closed: it is never
* reported as [Ready], so an unrecognised word cannot read as "wallet
* working".
*/
data class Unrecognised(val raw: String) : WalletChildPhase {
override val testTag: String = "child-unrecognised"
override val label: String = "unknown (${shortSendReason(raw, UNRECOGNISED_BUDGET)})"
override val contentDescription: String =
"The wallet reported a state this build does not know"
override val live: Boolean = false
override val dead: Boolean = false
}
}
/** Cells of an unrecognised state word kept on the status line. */
const val UNRECOGNISED_BUDGET: Int = 16
/**
* The in-process node's own word, for the chain sources that have one.
*
* Same fail-closed rule as [WalletChildPhase]: an unrecognised word is never
* [Ready]. [Absent] is not a node state at all — it is "this chain source has no
* node segment on the line", which is true of receive-only, a spawned `monerod`
* and a remote daemon, and also of an in-process source the core has not reported
* a node word for yet. Nothing is inferred to fill it in.
*/
sealed interface NodePhase {
/** Stable handle for Compose semantics and tests. */
val testTag: String
/** Word drawn after `node`, or empty for [Absent]. */
val label: String
/** What a screen reader announces. Always a sentence. */
val contentDescription: String
/** No node segment: not an in-process chain source. */
data object Absent : NodePhase {
override val testTag: String = "node-absent"
override val label: String = ""
override val contentDescription: String = "No on-device node"
}
/** The app's own node is not running. */
data object Off : NodePhase {
override val testTag: String = "node-off"
override val label: String = "off"
override val contentDescription: String = "The on-device node is off"
}
/** The node is up; its loopback RPC has not answered yet. */
data object Starting : NodePhase {
override val testTag: String = "node-starting"
override val label: String = "starting"
override val contentDescription: String =
"The on-device node is starting; its RPC has not answered yet"
}
/** The node answers; its chain is not at the tip. */
data object Syncing : NodePhase {
override val testTag: String = "node-syncing"
override val label: String = "syncing"
override val contentDescription: String =
"The on-device node is syncing; the chain is not at the tip yet"
}
/** The node answers and its chain is at the tip. */
data object Ready : NodePhase {
override val testTag: String = "node-ready"
override val label: String = "ready"
override val contentDescription: String = "The on-device node is ready"
}
/** A started node is gone. */
data object Exited : NodePhase {
override val testTag: String = "node-exited"
override val label: String = "exited"
override val contentDescription: String = "The on-device node exited"
}
/** A node word this build does not know. Fail-closed: never [Ready]. */
data class Unrecognised(val raw: String) : NodePhase {
override val testTag: String = "node-unrecognised"
override val label: String = "unknown (${shortSendReason(raw, UNRECOGNISED_BUDGET)})"
override val contentDescription: String =
"The on-device node reported a state this build does not know"
}
}
/**
* Maps the core's `node_state` onto a [NodePhase].
*
* [NodePhase.Absent] for a source that has no node (or no word yet); anything the
* five words do not cover is [NodePhase.Unrecognised] — never [NodePhase.Ready].
*/
fun nodePhase(input: WalletChildInput?): NodePhase {
if (input == null || !input.chainInProcess) return NodePhase.Absent
return when (val state = input.nodeState.trim().lowercase()) {
"" -> NodePhase.Absent
"off" -> NodePhase.Off
"starting" -> NodePhase.Starting
"syncing" -> NodePhase.Syncing
"ready" -> NodePhase.Ready
"exited" -> NodePhase.Exited
else -> NodePhase.Unrecognised(state)
}
}
/**
* Maps the core's `state` word onto a [WalletChildPhase]. Case- and
* whitespace-tolerant; anything else is [WalletChildPhase.Unrecognised].
*/
fun walletChildPhase(input: WalletChildInput?): WalletChildPhase {
if (input == null) return WalletChildPhase.Unread
return when (val state = input.state.trim().lowercase()) {
"off" -> WalletChildPhase.Off
"connecting" -> WalletChildPhase.Connecting
"syncing" -> WalletChildPhase.Syncing
"ready" -> WalletChildPhase.Ready
"exited" -> WalletChildPhase.Exited(input.lastError?.takeIf { it.isNotBlank() })
else -> WalletChildPhase.Unrecognised(state)
}
}
/**
* `off · receive-only`, `exited · remote daemon — spawn monero-wallet-rpc: No
* such file or directory`.
*
* The chain-source label is the core's own (`WalletChildStatus.chain_source`),
* rendered verbatim: `receive-only`, `local node`, `remote onion daemon`,
* `remote daemon`. The trailing failure text is the core's `last_error`, cut
* and sanitized by the same rule chat rows use.
*/
fun walletChildLine(input: WalletChildInput?): String {
val phase = walletChildPhase(input)
val source = input?.chainSource?.takeIf { it.isNotBlank() } ?: "no chain source"
val node = nodePhase(input)
val height = input?.height ?: 0uL
val target = input?.targetHeight ?: 0uL
val why = input?.lastError?.takeIf { it.isNotBlank() }
return buildString {
append(phase.label)
append(" · ")
append(source)
// Only an in-process source has a node of its own to name. The node word
// is the core's, rendered as-is — there is no second state machine here.
if (node !is NodePhase.Absent) {
append(" · node ")
append(node.label)
}
// The daemon's own height, when it reported one: `sync h/t`, the segment
// the core's own line uses. No percent, no progress bar, no ETA — `0/0`
// is unknown (the probe failed, or the daemon is not up), not "0%", and
// when both are zero the segment is absent rather than printed as `0/0`.
if (height > 0uL || target > 0uL) {
append(" · sync ")
append(height.toString())
append('/')
append(target.toString())
}
when {
why != null -> append(" — ").append(shortSendReason(why))
phase is WalletChildPhase.Exited -> append(" — the child process is gone")
}
}
}
/**
* The whole status row as one screen-reader sentence: the phase's own sentence,
* then the same line the eye reads — including the daemon's `sync h/t` when the
* core reported one. A screen reader is never told less than the sighted user,
* and it is a sentence either way.
*/
fun walletChildStatusDescription(input: WalletChildInput?): String =
"${walletChildPhase(input).contentDescription}. ${walletChildLine(input)}"
/**
* A `.onion` daemon is only reachable through the `arti` SOCKS child, and this
* build does not ship one — say that before the user presses Start rather than
* after the spawn fails.
*/
const val ONION_NEEDS_ARTI_NOTICE: String =
"A .onion daemon needs the arti SOCKS child, which this build does not bundle."
/** Shown while the first `wallet_status()` read is still in flight. */
const val READING_CHILD_NOTICE: String = "Reading the wallet status…"
const val STARTING_CHILD_NOTICE: String =
"Start is running. Status stays off until the on-device node answers — that can take a minute, and is not a dead button."
/**
* The alert banner the on-device node is offered with, **before** Start.
*
* Cuprate's own user book says *"do NOT use cuprated for any serious purposes"*,
* its `monerod` RPC parity is incomplete (Cuprate issue #278, and the four gaps
* measured in this repo are in `docs/cuprate-launch-spike.md`), and mainnet is
* unvalidated. The title is the banner's; the two sentences are the body — one
* copy of the caveat, never a second one elsewhere on the screen, so the two
* can never drift apart.
*/
const val CUPRATE_ON_DEVICE_TITLE: String = "Experimental On-Device Node (Cuprate)"
const val CUPRATE_ON_DEVICE_BODY: String =
"Pre-production software with incomplete RPC parity (#278). Do not use for significant " +
"funds. Mainnet is unvalidated, and Cuprate's own user book says do NOT use cuprated " +
"for any serious purposes."
/**
* This build was compiled without the `cuprate-daemon` feature, so the stored
* on-device chain source can be read back but can never start. Mirrors the core's
* own refusal (`onionwire::cuprate::NO_FEATURE_MSG`) rather than inventing a
* second wording for the same fact.
*/
const val CUPRATE_NOT_IN_BUILD_NOTICE: String =
"This build has no in-process chain daemon, so the on-device node cannot start."
/**
* Free space the chain store's filesystem must have before the on-device node is
* started.
*
* A **floor**, not a sync estimate, and deliberately so: nothing in this stack
* exposes one. `WalletChildStatus` carries no size field, and Cuprate's own
* restricted RPC reports a hardcoded 5 GiB `database_size` placeholder (see
* `src/cuprate.rs`), so a number taken from the node would be fiction. What can be
* measured honestly is the free space on the filesystem the fjall store grows
* into, and the device can be told when that is not enough.
*/
const val CHAIN_TESTNET_FLOOR_BYTES: Long = 3L * 1024 * 1024 * 1024
const val CHAIN_MAINNET_PRUNED_FLOOR_BYTES: Long = 64L * 1024 * 1024 * 1024
const val CHAIN_MAINNET_FULL_FLOOR_BYTES: Long = 280L * 1024 * 1024 * 1024
/** Testnet floor, kept so existing tests still name one constant. */
const val CHAIN_FREE_SPACE_FLOOR_BYTES: Long = CHAIN_TESTNET_FLOOR_BYTES
fun chainStorageFloorBytes(mainnet: Boolean, prune: Boolean): Long = when {
!mainnet -> CHAIN_TESTNET_FLOOR_BYTES
prune -> CHAIN_MAINNET_PRUNED_FLOOR_BYTES
else -> CHAIN_MAINNET_FULL_FLOOR_BYTES
}
/**
* What the chain store costs, in the user's terms: the free space this device
* actually has, and what the node does *not* tell us.
*/
fun chainStorageLine(freeBytes: Long?, mainnet: Boolean = false, prune: Boolean = false): String {
val kind = when {
!mainnet -> "a synced testnet store"
prune -> "a pruned mainnet store (tens of GiB)"
else -> "a full mainnet store (hundreds of GiB)"
}
return when {
freeBytes == null ->
"chain store: free space on this device could not be read."
else ->
"chain store: ${formatBytes(freeBytes)} free on this device — $kind " +
"grows into it. The node reports no size estimate of its own."
}
}
/**
* Why the on-device node must not be started on this device, or `null` when it
* may. Fail-closed on an unreadable filesystem: an unknown free space is not
* reported as enough.
*/
fun chainStorageBlockedReason(
freeBytes: Long?,
mainnet: Boolean = false,
prune: Boolean = false,
): String? {
val floor = chainStorageFloorBytes(mainnet, prune)
return when {
freeBytes == null ->
"Free space on the chain store's filesystem could not be read, so it is not known to fit."
freeBytes < floor ->
"Not enough space for the chain store: ${formatBytes(freeBytes)} free, and the " +
"on-device node needs at least ${formatBytes(floor)}."
else -> null
}
}
enum class CuprateMode {
MainnetPruned,
MainnetFull,
Testnet,
}
fun selectedCuprateMode(inProcess: Boolean, mainnet: Boolean, prune: Boolean): CuprateMode? =
when {
!inProcess -> null
!mainnet -> CuprateMode.Testnet
prune -> CuprateMode.MainnetPruned
else -> CuprateMode.MainnetFull
}
/**
* Tapping a mode used to only persist `ChainConfig`, which looked like a no-op
* besides the storage line. Start when the storage floor would allow Start,
* **the Start gate itself would allow it**, and a launch is not already in
* flight.
*
* [startBlocked] is the same reason the Start button is disabled by
* (`startGateReason`). A mode tap stores the source either way, but persisting
* a choice must never launch a child the gate would refuse — the old
* storage-only predicate is exactly how an auto-start slipped past a stored
* binary that could not run.
*/
fun shouldStartAfterSelectingChain(
storageBlocked: String?,
starting: Boolean,
startBlocked: String? = null,
): Boolean = storageBlocked == null && startBlocked == null && !starting
/**
* Bytes as a screen-sized string. Binary units (a "GB" that is really a GiB is how
* a store that needs 3 GiB ends up on a device with 2.8).
*/
fun formatBytes(bytes: Long): String = when {
bytes >= 1L shl 30 -> String.format(Locale.US, "%.1f GiB", bytes.toDouble() / (1L shl 30))
bytes >= 1L shl 20 -> String.format(Locale.US, "%.0f MiB", bytes.toDouble() / (1L shl 20))
else -> "$bytes B"
}
/**
* A block height with thousands separators: `3794383` → `3,794,383`.
*
* Hand-grouped rather than `String.format("%,d")` on purpose: the grouped
* format is locale-dependent (some locales use a period or a non-breaking
* space), and a block height is a number in a monospace column, not prose. The
* screen and its test must print the same string everywhere.
*/
fun formatBlockCount(blocks: ULong): String {
val digits = blocks.toString()
val out = StringBuilder(digits.length + digits.length / 3)
digits.forEachIndexed { i, c ->
if (i > 0 && (digits.length - i) % 3 == 0) out.append(',')
out.append(c)
}
return out.toString()
}
/**
* What the node card's progress header renders for one height / target pair.
*
* [percentText] and [blockText] are null when there is nothing honest to say —
* and `target == 0` is exactly that: the daemon reporting **no target** is not
* evidence of being caught up (`src/wallet.rs` returns `0` for a height it does
* not have, and Cuprate omits the target even at the tip). A percentage invented
* from a zero target would read as progress; an unknown target is said in words.
*/
data class SyncProgress(
/** 0f..1f of the track to fill. `0f` whenever the target is unknown. */
val fraction: Float,
/** `12.8%`, or null when the daemon reported no target. */
val percentText: String?,
/** `Block 485,253 of 3,794,383`, or null when neither number is known. */
val blockText: String?,
)
fun syncProgress(height: ULong, target: ULong): SyncProgress {
if (height == 0uL && target == 0uL) return SyncProgress(0f, null, null)
if (target == 0uL) {
return SyncProgress(
fraction = 0f,
percentText = null,
blockText = "Block ${formatBlockCount(height)} of an unknown target",
)
}
val fraction = (height.toDouble() / target.toDouble()).coerceIn(0.0, 1.0)
return SyncProgress(
fraction = fraction.toFloat(),
percentText = String.format(Locale.US, "%.1f%%", fraction * 100.0),
blockText = "Block ${formatBlockCount(height)} of ${formatBlockCount(target)}",
)
}
/**
* The balance line, with the core's two sentinels translated into words.
*
* `walletBalance()` does not throw: it answers `off` (no chain source is
* configured at all) or `err` (configured, but the read failed — no wallet file
* open, or the process is down) and a formatted amount otherwise. Printing
* either sentinel raw is what put the string `wallet off` on the wallet screen;
* printing the same word for both is worse, because they are fixed in different
* places. The sentinels themselves are the core's contract and are not touched
* here — this is the display only.
*/
fun noWalletBalanceHeadline(balance: String?): String = when (balance) {
null -> "…"
"off" -> "No Wallet Loaded"
"err" -> "Balance unavailable"
else -> balance
}
/** `Mainnet Pruned` / `Mainnet Full` / `Testnet` — the three stored modes, as words. */
fun chainModeLabel(mainnet: Boolean, prune: Boolean): String = when {
!mainnet -> "Testnet"
prune -> "Mainnet Pruned"
else -> "Mainnet Full"
}
/**
* How the node card's header reads. [tone] is the status dot's colour class, not
* a decoration: it is the caller's statement about the core's own word.
*/
enum class NodeStatusTone {
/** Nothing is running, and nothing is wrong. */
Idle,
/** Up, or on its way up. */
Busy,
/** Answered and at the tip. */
Good,
/** A state the app cannot read, or a process that is gone. */
Bad,
}
data class NodeStatusHead(val title: String, val tone: NodeStatusTone)
/**
* The header sentence for the node card, from the core's `state` alone.
*
* Fail-closed exactly as [walletChildPhase] is: an unrecognised state gets
* [NodeStatusTone.Bad] and never reads as ready. A running child that has not
* answered is `Connecting…`, not `Ready` — the RPC has not spoken yet.
*/
fun nodeStatusHead(
input: WalletChildInput?,
inProcess: Boolean = false,
mainnet: Boolean = false,
prune: Boolean = false,
): NodeStatusHead {
val mode = if (inProcess) " (${chainModeLabel(mainnet, prune)})" else ""
return when (walletChildPhase(input)) {
WalletChildPhase.Unread -> NodeStatusHead("Reading wallet status", NodeStatusTone.Idle)
WalletChildPhase.Off ->
NodeStatusHead(if (inProcess) "Node Idle$mode" else "Wallet Offline", NodeStatusTone.Idle)
WalletChildPhase.Connecting -> NodeStatusHead("Connecting…", NodeStatusTone.Busy)
WalletChildPhase.Syncing ->
NodeStatusHead(if (inProcess) "Syncing Node$mode" else "Syncing Wallet", NodeStatusTone.Busy)
WalletChildPhase.Ready -> NodeStatusHead("Wallet Ready", NodeStatusTone.Good)
is WalletChildPhase.Exited -> NodeStatusHead("Wallet Stopped", NodeStatusTone.Bad)
is WalletChildPhase.Unrecognised -> NodeStatusHead("Unknown wallet state", NodeStatusTone.Bad)
}
}
/**
* Why **Start** is not actionable, or `null` when it is.
*
* Ordered by what the user can act on: a binary this build does not carry is
* not fixable from this screen, a missing chain source is. Every branch names
* the actual condition — there is no generic "starting…" state to hide behind.
*/
fun startBlockedReason(
bins: WalletChildBinaryPaths,
input: WalletChildInput?,
onionDaemon: Boolean = false,
starting: Boolean = false,
): String? = when {
bins.walletRpc == null -> NO_WALLET_RPC_MESSAGE
starting -> STARTING_CHILD_NOTICE
input == null -> READING_CHILD_NOTICE
// Unreachable from the wallet screen: while the wallet runs the lifecycle
// control *is* Stop, so Start is never offered. Kept as a pure predicate so
// a stale status read cannot turn the one control into a no-op tap.
input.running -> "The wallet is already running."
!input.configured -> NO_CHAIN_SOURCE_NOTICE
// The stored source is the app's own node but this build has no daemon: the
// option is readable and unstoppable, so say it before the user presses Start.
input.chainInProcess && !input.nodeAvailable -> CUPRATE_NOT_IN_BUILD_NOTICE
onionDaemon && bins.arti == null -> ONION_NEEDS_ARTI_NOTICE
else -> null
}
/** The stored config names no chain source, so there is no daemon to dial. */
const val NO_CHAIN_SOURCE_NOTICE: String =
"No chain source yet: the wallet needs a daemon to dial."
/**
* Whether [path] is a file this process may `exec`, measured the way the kernel
* will measure it at spawn time. A missing file and an existing file without
* the execute bit are both "cannot run here" — they differ only in errno.
*
* Never throws: a path the filesystem refuses to answer for is not executable.
*/
fun isExecutableWalletBin(path: String): Boolean =
runCatching { File(path).let { it.isFile && it.canExecute() } }.getOrDefault(false)
/**
* The absolute path the stored config should keep instead of [storedBin], or
* `null` when the stored path is already runnable here (or there is nothing
* better to offer).
*
* This is the repair rule behind the self-heal. A record written by an older
* install can carry the bare name `monero-wallet-rpc` (or nothing at all),
* which nothing in an APK sandbox resolves on `PATH`; the spawn then dies with
* `ENOENT` and the screen had no way to say why. When this build *does* carry
* the binary at a resolved absolute path, that path replaces the unusable one.
*
* It never overwrites a path the user pointed at that actually runs: an
* existing, executable file is left alone even when it is not the bundled one.
*/
fun walletBinHealPath(
storedBin: String?,
resolvedBin: String?,
executable: (String) -> Boolean = ::isExecutableWalletBin,
): String? {
val resolved = resolvedBin?.takeIf { it.isNotBlank() } ?: return null
val stored = storedBin?.trim().orEmpty()
if (stored.isNotEmpty() && executable(stored)) return null
return resolved
}
/**
* Why the **stored** `ChainConfig.walletRpcBin` will not produce a child, or
* `null` when it will. [startBlockedReason] only ever sees the *resolved*
* binaries, so a stale path saved by an older install passed that gate and
* then failed inside `spawn`.
*
* The reason always names the path it is about, so the next failure report
* carries its own cause instead of the opaque `spawn monero-wallet-rpc: No such
* file or directory`. A store that holds no path at all is named as such —
* "stored bin missing" is a distinct condition from "this build ships none".
*/
fun storedWalletBinBlockedReason(
storedBin: String?,
resolvedBin: String?,
executable: (String) -> Boolean = ::isExecutableWalletBin,
): String? {
if (resolvedBin.isNullOrBlank()) return NO_WALLET_RPC_MESSAGE
val stored = storedBin?.trim().orEmpty()
if (stored.isEmpty()) {
return "No wallet binary path is stored for this chain source, so there is nothing to " +
"spawn. This build ships $resolvedBin — pick a chain source to store it."
}
if (executable(stored)) return null
return "The stored wallet binary cannot be run on this device: $stored. " +
"This build ships $resolvedBin."
}
/**
* The full **Start** gate: the eligibility rules above plus the stored binary.
*
* [startBlockedReason] runs first so its established copy and ordering (no
* binary in this build, start in flight, no chain source) is unchanged; the
* stored-path check is the new second half. Together they make a populated
* `bins` insufficient on its own — which was the hole that let a bare stored
* name through.
*/
fun startGateReason(
bins: WalletChildBinaryPaths,
input: WalletChildInput?,
storedWalletBin: String?,
onionDaemon: Boolean = false,
starting: Boolean = false,
executable: (String) -> Boolean = ::isExecutableWalletBin,
): String? =
startBlockedReason(bins, input, onionDaemon, starting)
?: storedWalletBinBlockedReason(storedWalletBin, bins.walletRpc, executable)
/**
* Why **Create wallet** / **Import wallet** cannot be offered yet, or `null`
* when they can.
*
* Both are RPC calls (`create_wallet` / `restore_deterministic_wallet`) against
* the running child. With no child the call cannot succeed, and the core's
* refusal is the desktop TUI's `wallet not configured — open F7 …` — a key that
* does not exist on a phone. Collecting a passphrase only to print that is the
* second dead end this screen must not offer.
*/
fun walletSetupBlockedReason(input: WalletChildInput?): String? =
when (walletChildPhase(input)) {
WalletChildPhase.Unread -> READING_CHILD_NOTICE
WalletChildPhase.Off -> WALLET_SETUP_NEEDS_CHILD
WalletChildPhase.Connecting -> WALLET_SETUP_STARTING
is WalletChildPhase.Exited, is WalletChildPhase.Unrecognised -> WALLET_SETUP_NEEDS_CHILD
WalletChildPhase.Syncing, WalletChildPhase.Ready -> null
}
/** Shown on the disabled Create / Import controls when no wallet process is up. */
const val WALLET_SETUP_NEEDS_CHILD: String =
"Create and Import need the wallet process running. Start it on the node card first."
/** Shown while the child is up but its RPC has not answered yet. */
const val WALLET_SETUP_STARTING: String =
"The wallet is still starting. Wait until it answers, then create or import."
/** Tone of the one failure banner a card may paint. */
enum class WalletFailureTone {
/** Information about a state the app is in, not a failed call. */
Info,
/** A call actually failed. */
Error,
}
/**
* The banner a card should paint for a display-ready failure string, or `null`
* when it should paint none.
*
* [WALLET_NOT_OPEN_TEXT] is documented as a *state*, not a failure — a running
* child with no wallet file open answers every read with the daemon's `-13`,
* and that is exactly what first-run looks like. It nevertheless reached the
* node card's red `Wallet error` banner, duplicating the `No wallet open` info
* banner directly above it. This decision is keyed on the *mapped* text only:
* the mapping in [walletFailureText] is untouched, so nothing raw becomes
* visible, and only the paint changes.
*
* - [walletOpen] true: the state has ended, so a stale no-wallet sentence is
* dropped entirely.
* - [openHintVisible] true: the info banner above already says it — one
* sentence, once.
* - otherwise the sentence is still information, so it is painted as
* [WalletFailureTone.Info] rather than red.
*/
fun walletFailureBanner(
text: String?,
openHintVisible: Boolean,
walletOpen: Boolean,
): WalletFailureBanner? {
val shown = text?.takeIf { it.isNotBlank() } ?: return null
return if (shown == WALLET_NOT_OPEN_TEXT) {
when {
walletOpen -> null
openHintVisible -> null
else -> WalletFailureBanner(shown, WalletFailureTone.Info, "No wallet open")
}
} else {
WalletFailureBanner(shown, WalletFailureTone.Error, "Wallet error")
}
}
/** One banner: its sentence, its tone, and its title. */
data class WalletFailureBanner(
val text: String,
val tone: WalletFailureTone,
val title: String,
)
/**
* Why **Stop** is not actionable, or `null` when it is. `stop_wallet_child` is
* idempotent in the core, so this is only about not offering a no-op button.
*/
fun stopBlockedReason(input: WalletChildInput?): String? = when {
input == null -> READING_CHILD_NOTICE
!input.running -> "No wallet is running."
else -> null
}
/**
* Does this daemon host name a Tor onion service? Mirrors
* `wallet::is_onion_host` — the core's own rule, so the screen and the spawn
* path agree on which daemons need the SOCKS child.
*/
fun isOnionHost(host: String): Boolean = host.trim().lowercase().endsWith(".onion")
/**
* Parse the one text field the chain-source editor offers (`host:port`) into a
* daemon address, or `null` when it is not one.
*
* Deliberately strict: the core rejects an empty host or port 0 anyway, and a
* silently-guessed port is how a wallet ends up dialing the wrong daemon. An
* IPv6 literal in brackets is accepted; a bare IPv6 address is not, because
* `::1:18089` has no unambiguous split.
*/
fun parseDaemonAddress(raw: String): DaemonAddress? {
val text = raw.trim()
if (text.isEmpty()) return null
val host: String
val portText: String
if (text.startsWith("[")) {
val end = text.indexOf(']')
if (end <= 1) return null
host = text.substring(1, end)
val rest = text.substring(end + 1)
if (!rest.startsWith(":")) return null
portText = rest.substring(1)
} else {
// A bare IPv6 literal has no unambiguous split: `::1:18089` is either
// the host `::1` on 18089 or the host `::1:18089`. Bracket it.
if (text.count { it == ':' } != 1) return null
val cut = text.lastIndexOf(':')
host = text.substring(0, cut)
portText = text.substring(cut + 1)
}
val port = portText.toIntOrNull() ?: return null
if (host.isBlank() || port !in 1..65535) return null
return DaemonAddress(host, port)
}
/** A daemon address the user typed. */
data class DaemonAddress(val host: String, val port: Int) {
/** The single-line form the field holds. */
val text: String get() = "$host:$port"
}

View file

@ -0,0 +1,983 @@
package com.siriusdevops.onionwire.ui
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.view.WindowManager
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.siriusdevops.onionwire.WireViewModel
import com.siriusdevops.onionwire.ui.components.Label
import com.siriusdevops.onionwire.ui.components.Mono
import com.siriusdevops.onionwire.ui.components.OwAlertBanner
import com.siriusdevops.onionwire.ui.components.OwAlertVariant
import com.siriusdevops.onionwire.ui.components.OwButton
import com.siriusdevops.onionwire.ui.components.OwButtonRow
import com.siriusdevops.onionwire.ui.components.OwButtonVariant
import com.siriusdevops.onionwire.ui.components.OwCard
import com.siriusdevops.onionwire.ui.components.OwPill
import com.siriusdevops.onionwire.ui.components.OwSectionTitle
import com.siriusdevops.onionwire.ui.components.OwTopBar
import kotlinx.coroutines.launch
import uniffi.onionwire_sdk.WalletKeys
import uniffi.onionwire_sdk.WalletRow
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
// ---------------------------------------------------------------------------
// The rules this screen renders from, as pure Kotlin so `WalletManagerTest`
// covers them on the JVM without a device. Same shape as `SeedBackupGate` and
// `WalletChildStatusText`: the composables below only lay these decisions out.
// ---------------------------------------------------------------------------
/**
* A catalogue row's label: the user's name for the wallet, or the file name
* when there is none.
*
* `WalletRow.name` is documented as `None` when the wallet was never named and
* "never an empty string", but a blank string is treated as absent here too —
* a row labelled with spaces is a row the user cannot identify.
*/
internal fun walletRowLabel(name: String?, filename: String): String =
name?.takeIf { it.isNotBlank() } ?: filename
/**
* A row's creation date, from the store's unix seconds.
*
* `created_at <= 0` is not a date: the store assigns it on insert, so anything
* else is a row that predates that — say so rather than render 1970.
*/
internal fun walletRowDate(createdAt: Long): String {
if (createdAt <= 0L) return "date unknown"
return Instant.ofEpochSecond(createdAt)
.atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ISO_LOCAL_DATE)
}
/**
* Whether the wallet process has a wallet open that the RPC answers for.
*
* The core's `state` is the only honest signal available here: `connecting`
* means its wallet RPC has not answered, `off`/`exited` mean there is no child
* at all, and `syncing`/`ready` mean it answered — the chain being behind is
* irrelevant to whether the open wallet's keys can be read. A `null` state is
* "nothing read yet", which is not readable.
*/
internal fun walletChildReadable(state: String?): Boolean =
state == "ready" || state == "syncing"
/**
* Whether the open wallet's secrets may be offered for the row named
* [rowFilename].
*
* Both halves are load-bearing:
*
* - **active**: the seed and the private keys come from `query_key` against
* the file the child currently has open, so they belong to exactly one
* wallet. A non-active row's buttons stay dead instead of quietly opening
* that wallet under the user — switching is a deliberate tap, not a side
* effect of asking for a backup.
* - **readable**: with no child running there is no file open, and
* `wallet_seed()` / `wallet_keys()` can only fail. Offering a button that
* always errors is worse than saying why it is off.
*/
internal fun walletSecretsEnabled(
activeFilename: String?,
rowFilename: String,
walletReadable: Boolean,
): Boolean = walletReadable && activeFilename != null && activeFilename == rowFilename
/**
* Why the secret actions are off, in words — or `null` when they are on.
*
* The two reasons are different states of the world and are not collapsed:
* "this is not the open wallet" is fixed by tapping the row, "the child is not
* running" is fixed on the wallet screen. The first wording is the card's own.
*/
internal fun walletSecretsBlockedReason(
isActive: Boolean,
walletReadable: Boolean,
): String? = when {
!isActive -> "Open this wallet to view its backup."
!walletReadable -> "The wallet is not running — start it on the wallet screen to read the backup."
else -> null
}
// ---------------------------------------------------------------------------
// A wallet that needs its passphrase, and never the daemon's own words
// ---------------------------------------------------------------------------
/**
* The daemon's own phrase for "this RPC has no wallet file open"
* (`monero-wallet-rpc` answers `-13 No wallet file`).
*
* Matched case-insensitively anywhere in a failure string: the wallet client
* strips the JSON envelope and keeps only `error.message`, so the bare sentence
* is what actually reaches Kotlin — sometimes wrapped in the core's own
* `wallet file X is not open — …` prefix.
*/
private val NO_WALLET_FILE = Regex("no wallet file", RegexOption.IGNORE_CASE)
/**
* A bare wallet-RPC error code. `-13` is
* `WALLET_RPC_ERROR_CODE_NO_WALLET_FILE`; the lookarounds keep it from firing
* on a longer number or on a negative offset like `-135`.
*/
private val RAW_RPC_CODE = Regex("""(?<![\d-])-13(?!\d)""")
/**
* A JSON envelope — the raw RPC answer itself rather than a sentence about it.
* Either an object/array, or a quoted key of the JSON-RPC error shape.
*/
private val RAW_JSON = Regex("""[{}]|\[\s*\{|"(error|code|message|result|jsonrpc)"\s*:""")
/**
* Shown instead of the daemon's `-13` / `No wallet file` / JSON answer.
*
* A state the app is *in*, not a failure of the last call — the wallet screen
* renders it as an info banner, never as a red error line.
*/
const val WALLET_NOT_OPEN_TEXT: String =
"Open or create a wallet to enable balance, address, and backup controls."
/** Shown instead of a raw JSON refusal that names no condition the user can act on. */
const val WALLET_DAEMON_REFUSED_TEXT: String =
"The wallet daemon refused that request and gave no readable reason. Check the wallet " +
"on the wallet screen, then try again."
/**
* The desktop TUI's refusal, in the phone's words.
*
* `src/wallet.rs::NOT_CONFIGURED_MSG` is written for the Linux TUI: "wallet not
* configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC". Neither `F7`
* nor an environment variable exists on the phone, and the actual condition is
* simply that no wallet child is running. Printing that string was the second
* dead end on the device: a user who typed a passphrase into Create got told to
* press a key that is not on the device.
*/
const val WALLET_RPC_NOT_RUNNING_TEXT: String =
"The wallet process is not running, so there is nothing to open a wallet on. " +
"Start it on the node card, then create or import."
/**
* The TUI's unconfigured copy, and nothing else: the F7 hint, the phrase
* "wallet not configured", or an instruction to set `ONIONWIRE_WALLET_RPC`.
* All three describe the same fact — no wallet RPC to dial — and none of them
* is actionable on a phone.
*/
private val TUI_WALLET_NOT_CONFIGURED = Regex(
"""open\s*f7|wallet not configured|ONIONWIRE_WALLET_RPC""",
RegexOption.IGNORE_CASE,
)
/**
* A failure string safe to put on screen, or `null` when there is nothing to
* show.
*
* The wallet daemon answers in JSON, and the wallet client hands the parsed
* `error.message` straight up the stack: `-13 No wallet file` reaches Kotlin as
* the bare sentence, and a failure that never got that far can still arrive as
* the envelope itself. Neither is a sentence about this app, so both are
* replaced — the user gets told whether a wallet is open and what to do about
* it, which is the only thing that changes what they tap next.
*
* Anything else is passed through verbatim: the core's own refusals ("no saved
* wallet in onionwire-9", "node stopped: …", "wallet file X is not open — the
* RPC refused its passphrase (…)") are already written for a person and carry
* no secret. This is a *display* filter, not an error channel — nothing here
* decides whether an action succeeded.
*
* Fail-closed by construction: an over-eager match only downgrades a readable
* message to a plainer one. It can never leak the raw string it did not
* recognise as raw.
*/
internal fun walletFailureText(raw: String?): String? {
val text = raw?.trim().orEmpty()
return when {
text.isEmpty() -> null
// Before the JSON / -13 filters: the TUI's refusal is a plain sentence
// the raw pass-through would otherwise let reach the phone verbatim.
TUI_WALLET_NOT_CONFIGURED.containsMatchIn(text) -> WALLET_RPC_NOT_RUNNING_TEXT
NO_WALLET_FILE.containsMatchIn(text) || RAW_RPC_CODE.containsMatchIn(text) ->
WALLET_NOT_OPEN_TEXT
RAW_JSON.containsMatchIn(text) -> WALLET_DAEMON_REFUSED_TEXT
else -> text
}
}
/**
* `lastError` as the wallet screen should paint it, given the child's `state`.
*
* Defense in depth behind the core's own fix: the 2s probe dials a wallet RPC
* that may not have bound its port yet, and that transient refusal
* (`wallet connect:` / `wallet write:`) is not a fact about the wallet — the
* child is still `connecting` and the next tick usually clears it. Painting it
* red in that window tells the user a start that is going to succeed has
* failed.
*
* Only `connecting` is suppressed, and only for those two prefixes. The same
* string once the child is `exited` / `syncing` / `off` means it accepted a
* connection and then stopped answering, which is exactly what the user needs
* to see. This mirrors the core's `error_is_unreachable` predicate verbatim —
* a bare `Connection refused` from anything else is not matched.
*
* Everything else goes through [walletFailureText], unchanged.
*/
internal fun displayLastError(state: String, raw: String?): String? {
val text = raw?.trim().orEmpty()
if (text.isEmpty()) return null
val connecting = state.trim().equals("connecting", ignoreCase = true)
if (connecting && (text.startsWith("wallet connect:") || text.startsWith("wallet write:"))) {
return null
}
return walletFailureText(text)
}
/**
* Whether the manager screen must ask for a wallet-file passphrase.
*
* `needs_passphrase` is the core's own word for "a saved wallet is configured,
* and this install holds no passphrase that opens it" — a wallet created before
* the passphrase was sealed, or created on another install. It is not a start
* failure, and the child keeps running.
*
* `walletOpen` is the second half of the same statement and wins: a child that
* has a wallet file open has nothing to ask for, whatever the flag said a
* moment ago. Both come from one `WalletChildStatus`, so there is no second
* source of truth about which wallet is open.
*/
internal fun walletPassphrasePromptVisible(needsPassphrase: Boolean, walletOpen: Boolean): Boolean =
needsPassphrase && !walletOpen
/**
* Whether the prompt's submit is actionable.
*
* A file name is required because the open is per-file (`open_wallet` on the
* file the child is pointed at); a blank passphrase is refused by the core
* anyway, so the button stays dead rather than round-tripping a guaranteed
* failure. An in-flight open is not re-submitted: it restarts the wallet process.
*/
internal fun walletPassphraseSubmitEnabled(
activeFilename: String?,
typed: String,
inFlight: Boolean,
): Boolean = !inFlight && activeFilename != null && typed.isNotEmpty()
/**
* Why the prompt cannot be submitted yet, in words — or `null` when it can.
*
* The two reasons are different states of the world and are not collapsed:
* nothing typed is the user's own gap, no pointed-at file is the child's.
*/
internal fun walletPassphraseBlockedReason(
activeFilename: String?,
typed: String,
): String? = when {
activeFilename == null ->
"No wallet file is open yet — open one from the list below."
typed.isEmpty() -> "Type the passphrase for this wallet file."
else -> null
}
/**
* Why the wallet process has nothing open, in this app's words — or `null` when
* it has a wallet open, or nothing is running to hold one.
*
* A live `monero-wallet-rpc` is not a usable wallet: it starts with no wallet
* file open, and every read then answers `-13 No wallet file`. The status line
* reports the child's state, not that, so the screen says it here and names the
* one screen that fixes it. `needsPassphrase` is the case where the child is
* pointed at a file this install holds no passphrase for — the fix is a typed
* passphrase, not a different wallet, and the prompt lives on the manager
* screen.
*/
internal fun walletChildOpenHint(
childRunning: Boolean,
walletOpen: Boolean,
needsPassphrase: Boolean,
): String? = when {
!childRunning || walletOpen -> null
needsPassphrase ->
"The wallet needs its passphrase: open it on the Saved wallets screen, where the " +
"prompt is."
else ->
"Select a saved wallet or create a new one to view your balance and transact."
}
/**
* The saved-wallet catalogue: every wallet this install remembers, which one is
* open now, and — for that one — its recovery phrase and private keys.
*
* Three properties are deliberate and are the whole point of the screen:
*
* - The catalogue is re-read on entry and on Refresh, never cached from app
* start, so a wallet created on the wallet screen after this screen was
* first opened shows up without restarting the app.
* - A tap opens a row's file through `open_wallet(filename)` and reloads, so
* the in-use marker moves. The core refuses a name outside the catalogue,
* and its refusal is shown verbatim.
* - The secrets belong to the **open** wallet only. They are read on an
* explicit tap, are never shown for a row that is not the open one, and are
* never logged, persisted, put in a `testTag`/`contentDescription`, or held
* in saved state (`remember`, not `rememberSaveable`, and cleared on
* dispose).
*/
@Composable
fun WalletManagerScreen(
vm: WireViewModel,
onBack: () -> Unit,
) {
val child by vm.walletChild.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
/** `null` is "not read yet"; an empty list is a catalogue with no rows. */
var rows by remember { mutableStateOf<List<WalletRow>?>(null) }
/** The file name the core reports as open, or null when it reports none. */
var active by remember { mutableStateOf<String?>(null) }
/** A catalogue/active-wallet read failure, distinct from an empty list. */
var listError by remember { mutableStateOf<String?>(null) }
/** A failed open, verbatim from the core. */
var actionError by remember { mutableStateOf<String?>(null) }
/** The file name currently being opened, so the row can say so. */
var opening by remember { mutableStateOf<String?>(null) }
// The wallet-file passphrase, for a wallet this install holds none for.
// Masked on screen, never copied (there is no copy action, exactly as the
// seed card has none), never logged, never persisted, and wiped when the
// screen goes — see the `DisposableEffect` below.
var passphrase by remember { mutableStateOf("") }
var passphraseError by remember { mutableStateOf<String?>(null) }
var openingWithPassphrase by remember { mutableStateOf(false) }
// The seed on the blocking card, and the typed confirm word. Neither is
// persisted: a spend key lives in this composition and nowhere else.
var seed by remember { mutableStateOf<String?>(null) }
var seedConfirm by remember { mutableStateOf("") }
// The open wallet's private keys, only ever set by an explicit tap on
// "Private keys". Null means no card.
var keys by remember { mutableStateOf<WalletKeys?>(null) }
var keysError by remember { mutableStateOf<String?>(null) }
suspend fun reload() {
vm.wallets().fold(
onSuccess = {
rows = it
listError = null
},
onFailure = {
rows = null
listError = walletFailureText(it.message ?: it.toString())
},
)
vm.activeWalletFilename().fold(
onSuccess = { active = it },
onFailure = {
// Same store as the list: a failure here is a read failure, not
// "no wallet is open", and it must not be rendered as one.
active = null
if (listError == null) {
listError = walletFailureText(it.message ?: it.toString())
}
},
)
}
/** Open a row's file, then re-read so the in-use marker moves. */
fun open(filename: String) {
if (opening != null) return
scope.launch {
actionError = null
opening = filename
vm.openWallet(filename).fold(
onSuccess = { reload() },
onFailure = { actionError = walletFailureText(it.message ?: it.toString()) },
)
opening = null
}
}
/**
* "Open this wallet": the one-time passphrase for a wallet this install
* holds none for.
*
* `openWalletWithPassphrase` is the parent card's binding. It is a per-file
* call, so it is handed the file the child is already pointed at — the same
* `active_wallet_filename()` the list marks in use, not a second idea of
* which wallet is open. The core seals the passphrase only once a live
* daemon has accepted it, so a wrong one leaves the prompt up rather than
* looking fixed.
*/
fun openWithPassphrase() {
val file = active ?: return
if (openingWithPassphrase || passphrase.isEmpty()) return
scope.launch {
passphraseError = null
openingWithPassphrase = true
vm.openWalletWithPassphrase(file, passphrase).fold(
onSuccess = {
// The secret has done its job. Drop it before anything else
// can see it, then re-read: the live probe in the ViewModel
// is what flips `needs_passphrase` and takes this card off
// the screen.
passphrase = ""
reload()
},
onFailure = { passphraseError = walletFailureText(it.message ?: it.toString()) },
)
openingWithPassphrase = false
}
}
/**
* "Recovery phrase": re-read the open wallet's 25 words and put them on the
* existing blocking card. Same treatment as the wallet screen's "Back up
* seed" — one gate, one card, no second ungated display.
*/
fun showPhrase() {
scope.launch {
actionError = null
vm.walletSeed().fold(
onSuccess = {
seed = it
seedConfirm = ""
},
onFailure = { actionError = walletFailureText(it.message ?: it.toString()) },
)
}
}
/**
* "Private keys": read the open wallet's keys once, on this tap. Failure is
* shown where the card would be, so a wallet that cannot answer says so
* instead of looking like an empty one.
*/
fun showKeys() {
scope.launch {
actionError = null
keysError = null
vm.walletKeys().fold(
onSuccess = { keys = it },
onFailure = { keysError = walletFailureText(it.message ?: it.toString()) },
)
}
}
LaunchedEffect(Unit) {
// The cached child read never dials, so the screen paints; the live
// probe after it is what tells the truth about whether a wallet is
// open, which is what the secret actions hang on.
vm.paintWalletChildCached()
reload()
vm.refreshWalletChild()
}
// Nothing here is `rememberSaveable`, so leaving the screen drops the
// composition's state — including the seed, the keys and the wallet-file
// passphrase. Dropping the reference is the strongest wipe a Kotlin String
// allows (see `SeedBackupCard`); this makes it explicit rather than
// incidental.
DisposableEffect(Unit) {
onDispose {
seed = null
seedConfirm = ""
keys = null
keysError = null
passphrase = ""
passphraseError = null
}
}
// Screenshots and the recents thumbnail. This screen renders a spend key and
// asks for the passphrase that opens a wallet file, so it takes the same
// `FLAG_SECURE` treatment the seed path wants — set while this composition is
// up, cleared when it goes, so no other screen inherits it. (No screen in
// this app set the flag before this change; see the PR body.)
val view = LocalView.current
DisposableEffect(view) {
val window = view.context.findActivity()?.window
window?.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
onDispose { window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) }
}
val walletReadable = walletChildReadable(child?.state)
Scaffold(
// Root owns systemBars ∪ ime, exactly as the wallet screen does (see
// `screenContentInsets`).
contentWindowInsets = WindowInsets(0, 0, 0, 0),
containerColor = OwColors.Canvas,
topBar = {
OwTopBar(
title = "Saved wallets",
// A pushed sub-screen, so the chevron — never the word "Back".
onBack = onBack,
actions = {
OwButton(
text = "Refresh",
variant = OwButtonVariant.Outline,
onClick = {
scope.launch {
vm.refreshWalletChild()
reload()
}
},
)
},
)
},
) { pad ->
Column(
Modifier
.padding(pad)
.fillMaxSize()
.screenContentInsets()
.verticalScroll(rememberScrollState()),
) {
// The blocking seed card, when a phrase is on screen: the whole
// body, exactly as on the wallet screen. Done is dead until the
// confirm word is typed, and the app-bar Back still leaves.
val shownSeed = seed
if (shownSeed != null) {
SeedBackupCard(
seed = shownSeed,
typed = seedConfirm,
onTyped = { seedConfirm = it },
onDone = {
vm.confirmWalletSeed(seedConfirm)
seed = null
seedConfirm = ""
},
)
actionError?.let { ErrorText(it) }
return@Column
}
keys?.let { k ->
PrivateKeysCard(
keys = k,
warning = vm.spendAuthorityWarning(),
onDone = { keys = null },
)
}
keysError?.let { message ->
OwAlertBanner(
variant = OwAlertVariant.Error,
title = "Could not read the open wallet's private keys",
description = message,
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 8.dp)
.testTag("wallet-keys-error"),
action = {
OwButton(
text = "Dismiss",
variant = OwButtonVariant.Outline,
onClick = { keysError = null },
)
},
)
}
actionError?.let { ErrorText(it) }
// The one-time passphrase for a wallet this install holds none for.
// A wallet created before the passphrase was sealed reports
// `needs_passphrase` and answers every read with `-13 No wallet
// file`, so without this the row tap looks like it did nothing.
if (walletPassphrasePromptVisible(
needsPassphrase = child?.needsPassphrase == true,
walletOpen = child?.walletOpen == true,
)
) {
WalletPassphraseCard(
filename = active,
typed = passphrase,
onTyped = {
passphrase = it
passphraseError = null
},
inFlight = openingWithPassphrase,
childRunning = child?.running == true,
blockedReason = walletPassphraseBlockedReason(active, passphrase),
error = passphraseError,
onSubmit = { openWithPassphrase() },
)
}
val listed = rows
when {
// A read failure is not an empty catalogue, and the two must
// not read alike: one is "the store did not answer", the other
// is "you have no wallets yet".
listError != null -> OwAlertBanner(
variant = OwAlertVariant.Error,
title = "Could not read the wallet catalogue",
description = listError ?: "",
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 8.dp)
.testTag("wallet-list-error"),
action = {
OwButton(
text = "Retry",
variant = OwButtonVariant.Outline,
onClick = { scope.launch { reload() } },
)
},
)
listed == null -> Text(
"Loading…",
style = MaterialTheme.typography.bodyMedium,
color = OwColors.TextSecondary,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
listed.isEmpty() -> OwCard(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
) {
OwSectionTitle("No saved wallets yet")
Spacer(Modifier.height(6.dp))
Text(
"Wallets this install remembers show up here. Create or import one " +
"on the wallet screen and it appears on the next look.",
style = MaterialTheme.typography.bodySmall,
color = OwColors.TextSecondary,
)
Spacer(Modifier.height(12.dp))
OwButton(
text = "Create or import a wallet",
variant = OwButtonVariant.Primary,
onClick = onBack,
modifier = Modifier.fillMaxWidth(),
)
}
else -> {
Label(
"${listed.size} SAVED ${if (listed.size == 1) "WALLET" else "WALLETS"}",
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
listed.forEach { row ->
val isActive = active != null && active == row.walletFilename
WalletRowCard(
row = row,
isActive = isActive,
secretsEnabled = walletSecretsEnabled(
activeFilename = active,
rowFilename = row.walletFilename,
walletReadable = walletReadable,
),
blockedReason = walletSecretsBlockedReason(
isActive = isActive,
walletReadable = walletReadable,
),
opening = opening == row.walletFilename,
onOpen = { open(row.walletFilename) },
onShowPhrase = { showPhrase() },
onShowKeys = { showKeys() },
)
}
}
}
}
}
}
/**
* One catalogue row: what it is called, which file it is, when it was created,
* and whether it is the open one.
*
* The open row is not tappable. Re-opening it would stop and restart a running
* wallet process onto the file it already has open — a slow no-op whose only
* effect is to make the screen look like it did something.
*/
@Composable
private fun WalletRowCard(
row: WalletRow,
isActive: Boolean,
secretsEnabled: Boolean,
blockedReason: String?,
opening: Boolean,
onOpen: () -> Unit,
onShowPhrase: () -> Unit,
onShowKeys: () -> Unit,
) {
OwCard(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 6.dp)
.then(if (isActive) Modifier else Modifier.clickable(enabled = !opening, onClick = onOpen)),
) {
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
walletRowLabel(row.name, row.walletFilename),
style = MaterialTheme.typography.titleMedium,
color = OwColors.TextPrimary,
modifier = Modifier.weight(1f),
)
Spacer(Modifier.width(8.dp))
when {
isActive -> OwPill(
text = "In use",
textColor = OwColors.Accent,
container = OwColors.InfoTint,
borderColor = OwColors.InfoBorder,
dotColor = OwColors.Accent,
)
opening -> OwPill(text = "Opening…", textColor = OwColors.TextSecondary)
else -> OwPill(text = "Tap to open", textColor = OwColors.TextSecondary)
}
}
Spacer(Modifier.height(8.dp))
Label("FILE")
Mono(row.walletFilename)
Spacer(Modifier.height(4.dp))
Text(
"Created ${walletRowDate(row.createdAt)}",
style = MaterialTheme.typography.bodySmall,
color = OwColors.TextSecondary,
)
Spacer(Modifier.height(10.dp))
OwButtonRow {
OwButton(
text = "Recovery phrase",
variant = OwButtonVariant.Outline,
enabled = secretsEnabled,
onClick = onShowPhrase,
modifier = Modifier.weight(1f),
)
OwButton(
text = "Private keys",
variant = OwButtonVariant.Outline,
enabled = secretsEnabled,
onClick = onShowKeys,
modifier = Modifier.weight(1f),
)
}
blockedReason?.let {
Spacer(Modifier.height(6.dp))
Text(
it,
style = MaterialTheme.typography.labelSmall,
color = OwColors.TextMuted,
)
}
}
}
/**
* The one-time passphrase for a wallet file this install holds no passphrase
* for.
*
* Masked, and with no copy action at all — the same rule as [SeedBackupCard],
* for the same reason: the Android clipboard is readable by every other app and
* by the clipboard history on Android 13+, and this string opens a spend-capable
* wallet file. It is never logged, never persisted, and the caller drops it when
* the screen goes.
*
* Submit is dead while the wallet is not running: the core verifies a
* passphrase against a live daemon and refuses to seal an unverified one, so a
* tap there could only fail. When it *is* up — including `connecting`, whose RPC
* has not answered yet — the core restarts it onto the file with this
* passphrase, which is exactly the fix.
*/
@Composable
private fun WalletPassphraseCard(
filename: String?,
typed: String,
onTyped: (String) -> Unit,
inFlight: Boolean,
childRunning: Boolean,
blockedReason: String?,
error: String?,
onSubmit: () -> Unit,
) {
OwCard(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
.testTag("wallet-passphrase-card"),
) {
OwSectionTitle("This wallet needs its passphrase")
Spacer(Modifier.height(6.dp))
Text(
"The wallet is pointed at ${filename ?: "a wallet file"} but this install " +
"holds no passphrase that opens it — the wallet was created before the " +
"passphrase was stored, or on another device. Type it once: the wallet " +
"opens, and later starts reopen it on their own.",
style = MaterialTheme.typography.bodySmall,
color = OwColors.TextSecondary,
)
Spacer(Modifier.height(12.dp))
OutlinedTextField(
value = typed,
onValueChange = onTyped,
singleLine = true,
// Masked on screen: this string opens a spend-capable wallet.
visualTransformation = PasswordVisualTransformation(),
label = { Text("wallet passphrase") },
modifier = Modifier
.fillMaxWidth()
.testTag("wallet-passphrase-input"),
)
Spacer(Modifier.height(6.dp))
Text(
"Never copied to the clipboard, never logged, and dropped when you leave this screen.",
style = MaterialTheme.typography.labelSmall,
color = OwColors.TextSecondary,
)
if (!childRunning) {
Spacer(Modifier.height(8.dp))
OwAlertBanner(
variant = OwAlertVariant.Info,
title = "The wallet is not running",
description = "Start it on the wallet screen, then come back.",
)
}
error?.let {
Spacer(Modifier.height(8.dp))
OwAlertBanner(
variant = OwAlertVariant.Error,
title = "Could not open this wallet",
description = it,
)
}
blockedReason?.let {
Spacer(Modifier.height(8.dp))
OwAlertBanner(
variant = OwAlertVariant.Info,
title = "Not ready to open",
description = it,
)
}
Spacer(Modifier.height(12.dp))
OwButton(
text = if (inFlight) "Opening…" else "Open this wallet",
variant = OwButtonVariant.Primary,
enabled = childRunning && walletPassphraseSubmitEnabled(filename, typed, inFlight),
onClick = onSubmit,
modifier = Modifier
.fillMaxWidth()
.testTag("wallet-passphrase-submit"),
)
}
}
/**
* The open wallet's private keys, shown only after an explicit tap.
*
* The view key is always there; the spend key only when the wallet has one.
* A view-only wallet says so in words — it has no spend key, and rendering
* that as a failure would teach the user to read a normal wallet as a broken
* one. The values are spend secrets: no `testTag`, no `contentDescription`,
* no logging, no persistence, and the card is dropped when the screen goes.
*/
@Composable
private fun PrivateKeysCard(
keys: WalletKeys,
warning: String,
onDone: () -> Unit,
) {
OwCard(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
.testTag("wallet-private-keys-card"),
) {
OwSectionTitle("Private keys of the open wallet")
Spacer(Modifier.height(6.dp))
Text(warning, style = MaterialTheme.typography.bodySmall, color = OwColors.Danger)
Spacer(Modifier.height(12.dp))
Label("VIEW KEY")
// Mono, and deliberately no testTag: a handle on a spend secret is a
// handle an automation can read back.
Mono(keys.viewKey, modifier = Modifier.fillMaxWidth())
Spacer(Modifier.height(10.dp))
val spend = keys.spendKey
if (spend != null) {
Label("SPEND KEY")
Mono(spend, modifier = Modifier.fillMaxWidth())
} else {
Text(
"View-only wallet — no spend key.",
style = MaterialTheme.typography.bodyMedium,
color = OwColors.TextSecondary,
)
}
Spacer(Modifier.height(12.dp))
OwButton(
text = "Done",
variant = OwButtonVariant.Outline,
onClick = onDone,
modifier = Modifier.fillMaxWidth(),
)
}
}
/**
* A display-ready failure line, as a banner. Never carries a secret; callers
* pass errors.
*
* "No wallet is open" is not a failure — it is a state the app is in, and it
* gets the info banner and its own title. Only a real refusal is red.
*/
@Composable
private fun ErrorText(text: String) {
val notOpen = text == WALLET_NOT_OPEN_TEXT
OwAlertBanner(
variant = if (notOpen) OwAlertVariant.Info else OwAlertVariant.Error,
title = if (notOpen) "No wallet open" else "Something went wrong",
description = text,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
}
/**
* The Activity behind a view's context, for the window flags.
*
* `view.context` is the Activity for a `setContent` root, but a wrapped context
* (a themed wrapper, a `ContextThemeWrapper` from a host) is a real case and
* silently skipping `FLAG_SECURE` because of it would be a silent leak.
*/
private tailrec fun Context.findActivity(): Activity? = when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,103 @@
package com.siriusdevops.onionwire.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.siriusdevops.onionwire.R
import com.siriusdevops.onionwire.ui.OwColors
import com.siriusdevops.onionwire.ui.OwRadius
/** Banner severity. Three states, matching the status colours exactly. */
enum class OwAlertVariant { Warning, Error, Info }
/**
* A contextual banner: status icon, one-line title, one- or two-line body.
*
* Replaces the raw red and grey paragraphs that used to trail the wallet and
* invite screens. A state the app is *in* (no wallet open, node experimental) is
* an info or warning banner; only a real failure gets [OwAlertVariant.Error].
*/
@Composable
fun OwAlertBanner(
variant: OwAlertVariant,
title: String,
description: String? = null,
modifier: Modifier = Modifier,
action: (@Composable () -> Unit)? = null,
) {
val text: Color = when (variant) {
OwAlertVariant.Warning -> OwColors.Warning
OwAlertVariant.Error -> OwColors.Danger
OwAlertVariant.Info -> OwColors.TextPrimary
}
val tint: Color = when (variant) {
OwAlertVariant.Warning -> OwColors.WarningTint
OwAlertVariant.Error -> OwColors.DangerTint
OwAlertVariant.Info -> OwColors.InfoTint
}
val border: Color = when (variant) {
OwAlertVariant.Warning -> OwColors.WarningBorder
OwAlertVariant.Error -> OwColors.DangerBorder
OwAlertVariant.Info -> OwColors.InfoBorder
}
val iconRes = when (variant) {
OwAlertVariant.Warning -> R.drawable.ic_ow_warning
OwAlertVariant.Error -> R.drawable.ic_ow_warning
OwAlertVariant.Info -> R.drawable.ic_ow_info
}
val iconTint = when (variant) {
OwAlertVariant.Info -> OwColors.Accent
else -> text
}
Row(
modifier = modifier
.fillMaxWidth()
.clip(RoundedCornerShape(OwRadius.Control))
.background(tint)
.border(1.dp, border, RoundedCornerShape(OwRadius.Control))
.padding(horizontal = 14.dp, vertical = 12.dp),
horizontalArrangement = Arrangement.Start,
) {
Icon(
painter = painterResource(iconRes),
contentDescription = null,
tint = iconTint,
modifier = Modifier.padding(top = 1.dp).size(18.dp),
)
Spacer(Modifier.width(10.dp))
Column(Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.titleSmall, color = text)
if (!description.isNullOrBlank()) {
Spacer(Modifier.height(3.dp))
Text(
description,
style = MaterialTheme.typography.bodySmall,
color = if (variant == OwAlertVariant.Info) OwColors.TextSecondary else text,
)
}
if (action != null) {
Spacer(Modifier.height(10.dp))
action()
}
}
}
}

View file

@ -0,0 +1,79 @@
package com.siriusdevops.onionwire.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.siriusdevops.onionwire.R
import com.siriusdevops.onionwire.ui.OwColors
/**
* The app's one top bar.
*
* Deliberately not `TopAppBar`: that component is a fixed height single line, and
* this header carries a second row (the `● Tor active` pill). A custom column
* also keeps the status-bar inset inside the bar's own background instead of
* padding the screen underneath it.
*
* On a sub-screen the navigation slot is a chevron icon button, never the word
* "Back".
*/
@Composable
fun OwTopBar(
title: String,
modifier: Modifier = Modifier,
onBack: (() -> Unit)? = null,
status: (@Composable () -> Unit)? = null,
actions: @Composable RowScope.() -> Unit = {},
) {
Column(
modifier = modifier
.fillMaxWidth()
.background(OwColors.Canvas)
.statusBarsPadding()
.padding(start = 16.dp, end = 16.dp, top = 10.dp, bottom = 10.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
if (onBack != null) {
OwIconButton(
iconRes = R.drawable.ic_ow_chevron_left,
contentDescription = "Back",
onClick = onBack,
tint = OwColors.TextPrimary,
background = OwColors.SurfaceInteractive,
)
Spacer(Modifier.width(12.dp))
}
Text(
title,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = OwColors.TextPrimary,
modifier = Modifier.weight(1f),
)
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
content = actions,
)
}
if (status != null) {
Spacer(Modifier.height(8.dp))
status()
}
}
}

View file

@ -0,0 +1,127 @@
package com.siriusdevops.onionwire.ui.components
import androidx.annotation.DrawableRes
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.siriusdevops.onionwire.R
import com.siriusdevops.onionwire.ui.OwColors
import com.siriusdevops.onionwire.ui.OwSize
/**
* The three top-level destinations.
*
* Chats is home. The node lives inside Wallet (that is where its card already
* is), so the third tab is the security/settings surface: identity, saved
* wallets, rotation, wipe, and — behind progressive disclosure — the SDK line
* that used to sit under the roster.
*/
enum class OwTab(val label: String, @param:DrawableRes val icon: Int) {
Chats("Chats", R.drawable.ic_ow_chat),
Wallet("Wallet", R.drawable.ic_ow_wallet),
// Tab labels stay short: the destination is Node & Settings (that is the
// screen title), but a 10sp label in a third of the bar has no room for it.
Settings("Settings", R.drawable.ic_ow_sliders),
}
/**
* Persistent bottom navigation.
*
* 64dp of canvas with a single 1dp top border — no elevation shadow, no
* translucent scrim. The navigation-bar inset is applied here, so screens inside
* the shell must not also pad for it (see `LocalBottomBarPresent`).
*/
@Composable
fun OwBottomTabBar(
selected: OwTab,
onSelect: (OwTab) -> Unit,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier
.fillMaxWidth()
.background(OwColors.Canvas),
) {
OwDivider()
Row(
modifier = Modifier
.fillMaxWidth()
.navigationBarsPadding()
.height(OwSize.TabBar),
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically,
) {
OwTab.entries.forEach { tab ->
TabItem(
tab = tab,
selected = tab == selected,
onClick = { onSelect(tab) },
modifier = Modifier.weight(1f),
)
}
}
}
}
@Composable
private fun TabItem(
tab: OwTab,
selected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
val tint: Color = if (selected) OwColors.Accent else OwColors.TextMuted
Column(
modifier = modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.semantics {
role = Role.Tab
this.selected = selected
}
.padding(vertical = 8.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Box(contentAlignment = Alignment.Center) {
Icon(
painter = painterResource(tab.icon),
contentDescription = null,
tint = tint,
modifier = Modifier.size(22.dp),
)
}
Spacer(Modifier.height(4.dp))
Text(
tab.label,
style = MaterialTheme.typography.labelSmall,
fontSize = 10.sp,
fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium,
color = tint,
)
}
}

View file

@ -0,0 +1,145 @@
package com.siriusdevops.onionwire.ui.components
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.siriusdevops.onionwire.ui.OwColors
import com.siriusdevops.onionwire.ui.OwRadius
import com.siriusdevops.onionwire.ui.OwSize
/**
* The four button tiers. There is no fifth: a screen that needs something
* quieter than [Outline] uses a text action, not a new shape.
*/
enum class OwButtonVariant {
/** Solid accent, canvas-coloured semibold text. One per screen region. */
Primary,
/** Solid interactive surface, no border. */
Secondary,
/** Transparent with the one border. */
Outline,
/** Tinted crimson with a crimson border. Destructive actions only. */
Destructive,
}
/**
* The app's button.
*
* Heights and radii come from the spec, not from Material's 40dp default: a
* 48dp target is comfortable and consistent, and a 12dp squircle replaces the
* 999dp pill that made every alpha action look identical.
*/
@Composable
fun OwButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
variant: OwButtonVariant = OwButtonVariant.Primary,
enabled: Boolean = true,
leadingIconRes: Int? = null,
content: (@Composable androidx.compose.foundation.layout.RowScope.() -> Unit)? = null,
) {
val height = when (variant) {
OwButtonVariant.Outline -> OwSize.ButtonCompact
else -> OwSize.Button
}
val container = when (variant) {
OwButtonVariant.Primary -> OwColors.Accent
OwButtonVariant.Secondary -> OwColors.SurfaceInteractive
OwButtonVariant.Outline -> Color.Transparent
OwButtonVariant.Destructive -> OwColors.DangerTint
}
val contentColor = when (variant) {
OwButtonVariant.Primary -> OwColors.Canvas
OwButtonVariant.Secondary -> OwColors.TextPrimary
OwButtonVariant.Outline -> OwColors.TextPrimary
OwButtonVariant.Destructive -> OwColors.Danger
}
val weight = if (variant == OwButtonVariant.Primary) FontWeight.SemiBold else FontWeight.Medium
// A local val, not the parameter: a parameter captured by the Button's
// content lambda cannot be smart-cast, and the nullable-call error reads as
// a Compose problem when it is only a Kotlin capture rule.
val customContent = content
Button(
onClick = onClick,
enabled = enabled,
modifier = modifier.height(height),
shape = RoundedCornerShape(OwRadius.Control),
border = when (variant) {
OwButtonVariant.Outline -> BorderStroke(1.dp, OwColors.Border)
OwButtonVariant.Destructive -> BorderStroke(1.dp, OwColors.DangerBorder)
else -> null
},
colors = ButtonDefaults.buttonColors(
containerColor = container,
contentColor = contentColor,
disabledContainerColor = when (variant) {
OwButtonVariant.Outline -> Color.Transparent
OwButtonVariant.Primary -> OwColors.SurfaceInteractive
OwButtonVariant.Secondary -> OwColors.Surface
OwButtonVariant.Destructive -> OwColors.Surface
},
disabledContentColor = OwColors.TextMuted,
),
elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp, pressedElevation = 0.dp),
contentPadding = ButtonDefaults.ContentPadding,
) {
if (customContent != null) {
customContent()
} else {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
if (leadingIconRes != null) {
Icon(
painter = painterResource(leadingIconRes),
contentDescription = null,
modifier = Modifier.size(18.dp),
)
Spacer(Modifier.width(8.dp))
}
Text(text, style = MaterialTheme.typography.labelLarge, fontWeight = weight)
}
}
}
}
/**
* Two buttons sharing a row: the primary action takes the space, the secondary
* one takes what it needs. Used by the identity bar and the empty state.
*/
@Composable
fun OwButtonRow(
modifier: Modifier = Modifier,
content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,
) {
Row(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
content = content,
)
}

View file

@ -0,0 +1,93 @@
package com.siriusdevops.onionwire.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.siriusdevops.onionwire.ui.OwColors
import com.siriusdevops.onionwire.ui.OwRadius
/**
* A typed-confirmation dialog for an irreversible action.
*
* The typed word is not theatre: "Rotate identity" cuts every friend who is
* offline off the current locator, and "Wipe all chats" deletes every message
* body. Both are one stray tap away from a menu, so the dialog asks for the
* word the user is about to lose.
*
* [confirmationWord] is echoed in the field label; the confirm button stays
* disabled until it is typed (case-insensitively) — same contract the old inline
* confirm strip had, now with a real scrim behind it.
*/
@Composable
fun OwConfirmDialog(
title: String,
body: String,
confirmationWord: String,
confirmLabel: String,
destructive: Boolean,
onConfirm: () -> Unit,
onDismiss: () -> Unit,
) {
var typed by remember { mutableStateOf("") }
val armed = typed.trim().equals(confirmationWord, ignoreCase = true)
AlertDialog(
onDismissRequest = onDismiss,
shape = RoundedCornerShape(OwRadius.Card),
containerColor = OwColors.Surface,
titleContentColor = OwColors.TextPrimary,
textContentColor = OwColors.TextSecondary,
title = { Text(title, style = MaterialTheme.typography.titleMedium) },
text = {
Column {
Text(body, style = MaterialTheme.typography.bodyMedium)
Spacer(Modifier.height(14.dp))
OutlinedTextField(
value = typed,
onValueChange = { typed = it },
singleLine = true,
label = { Text("Type $confirmationWord") },
modifier = Modifier.fillMaxWidth(),
)
}
},
confirmButton = {
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
TextButton(onClick = onDismiss) {
Text("Cancel", color = OwColors.TextSecondary)
}
TextButton(
onClick = onConfirm,
enabled = armed,
) {
Text(
confirmLabel,
color = when {
!armed -> OwColors.TextMuted
destructive -> OwColors.Danger
else -> OwColors.Accent
},
)
}
}
},
modifier = Modifier.padding(horizontal = 8.dp),
)
}

View file

@ -0,0 +1,69 @@
package com.siriusdevops.onionwire.ui.components
import androidx.compose.foundation.layout.Box
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.siriusdevops.onionwire.R
import com.siriusdevops.onionwire.ui.OwColors
import com.siriusdevops.onionwire.ui.OwRadius
/**
* The `⋮` overflow on the messenger and settings bars.
*
* Serious and rare actions live here instead of on the home screen: rotating the
* identity cuts every offline friend off the current locator, and deleting the
* message history is irreversible. Neither belongs next to "Invite".
*
* The menu is a component rather than inline code so the destructive verbs have
* exactly one home — a new screen that wants the overflow gets the same list,
* not a second copy with different wording.
*/
@Composable
fun OwOverflowMenu(
onOpenProfile: () -> Unit,
onOpenWallets: () -> Unit,
onRotate: () -> Unit,
onWipe: () -> Unit,
modifier: Modifier = Modifier,
) {
var open by remember { mutableStateOf(false) }
Box(modifier) {
OwIconButton(
iconRes = R.drawable.ic_ow_more_vert,
contentDescription = "More actions",
onClick = { open = true },
)
DropdownMenu(
expanded = open,
onDismissRequest = { open = false },
containerColor = OwColors.SurfaceInteractive,
shape = androidx.compose.foundation.shape.RoundedCornerShape(OwRadius.Control),
) {
DropdownMenuItem(
text = { Text("Your profile", color = OwColors.TextPrimary) },
onClick = { open = false; onOpenProfile() },
)
DropdownMenuItem(
text = { Text("Saved wallets", color = OwColors.TextPrimary) },
onClick = { open = false; onOpenWallets() },
)
DropdownMenuItem(
text = { Text("Rotate identity", color = OwColors.TextPrimary) },
onClick = { open = false; onRotate() },
)
DropdownMenuItem(
text = { Text("Delete message history", color = OwColors.Danger) },
onClick = { open = false; onWipe() },
)
}
}
}

View file

@ -0,0 +1,78 @@
package com.siriusdevops.onionwire.ui.components
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.qrcode.QRCodeWriter
import com.siriusdevops.onionwire.ui.OwColors
import com.siriusdevops.onionwire.ui.OwRadius
/**
* Renders [payload] as a QR code.
*
* The invite is a locator plus a prekey — long, and it has to survive a person
* pointing a phone at a screen, so the modules are drawn at full contrast on a
* light plate rather than tinted to match the dark theme.
*
* A payload zxing cannot encode (too long for version 40) renders as an empty
* plate; callers always show the copyable text as well, so a failed encode is
* degraded, not fatal.
*/
@Composable
fun OwQrCode(
payload: String,
modifier: Modifier = Modifier,
size: Dp = 200.dp,
) {
val matrix = remember(payload) {
runCatching {
QRCodeWriter().encode(
payload,
BarcodeFormat.QR_CODE,
0,
0,
mapOf(EncodeHintType.MARGIN to 0),
)
}.getOrNull()
}
Box(
modifier = modifier
.size(size)
.clip(RoundedCornerShape(OwRadius.Control))
.background(OwColors.TextPrimary),
contentAlignment = Alignment.Center,
) {
if (matrix != null) {
Canvas(Modifier.size(size)) {
val cells = matrix.width.toFloat()
val cellW = this.size.width / cells
val cellH = this.size.height / matrix.height.toFloat()
for (y in 0 until matrix.height) {
for (x in 0 until matrix.width) {
if (matrix.get(x, y)) {
drawRect(
color = Color(0xFF0A0C0E),
topLeft = Offset(x * cellW, y * cellH),
size = Size(cellW + 0.5f, cellH + 0.5f),
)
}
}
}
}
}
}
}

View file

@ -0,0 +1,104 @@
package com.siriusdevops.onionwire.ui.components
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.siriusdevops.onionwire.ui.OwColors
import com.siriusdevops.onionwire.ui.OwRadius
/**
* Horizontal segmented control: one track, [OwColors.SurfaceInteractive], 4dp of
* inside padding, 12dp radius.
*
* This replaces the stacks of full-width pill buttons that made "Pruned / Full /
* Testnet" read as three unrelated actions rather than one choice with three
* values. The selected segment is an accent fill with canvas text.
*/
@Composable
fun OwSegmentedControl(
options: List<String>,
selectedIndex: Int,
onSelect: (Int) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
/**
* Optional per-segment `testTag`s, one per option. Additive: omitted (the
* default) leaves every existing call site byte-identical. It exists because
* a merged "Pruned / Full / Testnet" track has no per-value handle otherwise,
* and the wallet screen's tests address each segment by the tag it had when
* the three options were three stacked buttons.
*/
testTags: List<String?> = emptyList(),
) {
Row(
modifier = modifier
.fillMaxWidth()
.clip(RoundedCornerShape(OwRadius.Control))
.background(OwColors.SurfaceInteractive)
.padding(4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
options.forEachIndexed { index, label ->
val selected = index == selectedIndex
val container by animateColorAsState(
targetValue = if (selected) OwColors.Accent else OwColors.SurfaceInteractive,
animationSpec = tween(durationMillis = 160),
label = "segment-container",
)
val textColor by animateColorAsState(
targetValue = when {
selected -> OwColors.Canvas
enabled -> OwColors.TextSecondary
else -> OwColors.TextMuted
},
animationSpec = tween(durationMillis = 160),
label = "segment-text",
)
val tag = testTags.getOrNull(index)
Box(
modifier = Modifier
.weight(1f)
.height(36.dp)
.clip(RoundedCornerShape(9.dp))
.background(container)
.then(if (tag != null) Modifier.testTag(tag) else Modifier)
.clickable(enabled = enabled && !selected) { onSelect(index) }
.semantics {
role = Role.Tab
this.selected = selected
},
contentAlignment = Alignment.Center,
) {
Text(
label,
style = MaterialTheme.typography.labelLarge,
fontSize = 13.sp,
fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium,
color = textColor,
)
}
}
}
}

View file

@ -0,0 +1,260 @@
package com.siriusdevops.onionwire.ui.components
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.siriusdevops.onionwire.ui.MonoStyle
import com.siriusdevops.onionwire.ui.OwColors
import com.siriusdevops.onionwire.ui.OwRadius
import com.siriusdevops.onionwire.ui.OwSize
/**
* A section card: [OwColors.Surface], 16dp radius, one 1dp border, 16dp of
* padding. Every non-list block on every screen is one of these.
*/
@Composable
fun OwCard(
modifier: Modifier = Modifier,
padding: Dp = 16.dp,
content: @Composable ColumnScope.() -> Unit,
) {
Column(
modifier = modifier
.clip(RoundedCornerShape(OwRadius.Card))
.background(OwColors.Surface)
.border(1.dp, OwColors.Border, RoundedCornerShape(OwRadius.Card))
.padding(padding),
content = content,
)
}
/** Small tracked label, secondary colour. Never monospace. */
@Composable
fun Label(text: String, modifier: Modifier = Modifier) {
Text(
text,
modifier = modifier,
style = MaterialTheme.typography.labelSmall,
color = OwColors.TextSecondary,
)
}
/**
* Cryptographic material and numbers only: pubkeys, truncated locators, seeds,
* `host:port`, block heights. Never a sentence.
*/
@Composable
fun Mono(text: String, modifier: Modifier = Modifier, color: Color = OwColors.TextPrimary) {
Text(text, modifier = modifier, style = MonoStyle.copy(color = color))
}
/** Section heading inside a card. */
@Composable
fun OwSectionTitle(text: String, modifier: Modifier = Modifier) {
Text(
text,
modifier = modifier,
style = MaterialTheme.typography.titleMedium,
color = OwColors.TextPrimary,
)
}
/** A 7dp status dot. Colour is the caller's statement, not decoration. */
@Composable
fun OwStatusDot(color: Color, modifier: Modifier = Modifier) {
Box(modifier.size(7.dp).clip(CircleShape).background(color))
}
/** Small status badge — the one place a 999dp radius is correct. */
@Composable
fun OwPill(
text: String,
modifier: Modifier = Modifier,
textColor: Color = OwColors.TextSecondary,
container: Color = OwColors.SurfaceInteractive,
borderColor: Color? = null,
dotColor: Color? = null,
) {
Row(
modifier = modifier
.clip(RoundedCornerShape(OwRadius.Pill))
.background(container)
.then(
if (borderColor != null) {
Modifier.border(1.dp, borderColor, RoundedCornerShape(OwRadius.Pill))
} else {
Modifier
},
)
.padding(horizontal = 10.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
if (dotColor != null) OwStatusDot(dotColor)
Text(text, style = MaterialTheme.typography.labelSmall, color = textColor, fontSize = 11.sp)
}
}
/**
* The header status pill: `● Tor active`.
*
* Shown while the app is in `Phase.Ready`, which is exactly when the node (and
* therefore Arti) is up. It says nothing about reachability after the app
* leaves the foreground — the keep-alive state is a separate row on the
* settings screen, because that is the honest place for it.
*/
@Composable
fun TorStatusPill(modifier: Modifier = Modifier) {
OwPill(
text = "Tor active",
modifier = modifier,
textColor = OwColors.Accent,
container = OwColors.InfoTint,
borderColor = OwColors.InfoBorder,
dotColor = OwColors.Accent,
)
}
/**
* A 36x36 icon button on an interactive surface. Used for Lock, back chevrons
* and the overflow trigger.
*/
@Composable
fun OwIconButton(
iconRes: Int,
contentDescription: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
tint: Color = OwColors.TextPrimary,
background: Color = OwColors.SurfaceInteractive,
size: Dp = OwSize.IconButton,
) {
Box(
modifier = modifier
.size(size)
.clip(RoundedCornerShape(OwRadius.Control))
.background(background)
.clickable(onClick = onClick)
.semantics { this.contentDescription = contentDescription },
contentAlignment = Alignment.Center,
) {
Icon(
painter = painterResource(iconRes),
contentDescription = null,
tint = tint,
modifier = Modifier.size(18.dp),
)
}
}
/**
* A deterministic 5x5 identicon derived from the identity fingerprint.
*
* Not a security feature: it is a stable visual handle so "your identity" is
* recognisable at a glance without reading 64 hex characters. It renders the
* seed it was given — it never invents a value, and two devices showing the
* same fingerprint show the same picture.
*/
@Composable
fun Identicon(seed: String, modifier: Modifier = Modifier, size: Dp = 40.dp) {
val palette = listOf(OwColors.Accent, OwColors.TextSecondary, OwColors.TextMuted)
val cells = identiconCells(seed)
Box(
modifier = modifier
.size(size)
.clip(CircleShape)
.background(OwColors.SurfaceInteractive),
contentAlignment = Alignment.Center,
) {
Canvas(Modifier.size(size * 0.62f)) {
val cell = this.size.minDimension / 5f
val pad = (this.size.minDimension - cell * 5f) / 2f
cells.forEach { (x, y, tone) ->
drawRect(
color = palette[tone % palette.size],
topLeft = Offset(pad + x * cell, pad + y * cell),
size = Size(cell, cell),
)
}
}
}
}
/**
* The left half of a 5-wide grid plus its mirror, as (column, row, tone)
* triples. Pure and cheap: the same seed always yields the same picture.
*/
internal fun identiconCells(seed: String): List<Triple<Int, Int, Int>> {
if (seed.isEmpty()) return emptyList()
val bytes = seed.map { it.code }.toIntArray()
var i = 0
val out = mutableListOf<Triple<Int, Int, Int>>()
for (row in 0 until 5) {
for (col in 0 until 3) {
val v = bytes[i % bytes.size]
i++
// A cell exists when the byte says so; tone varies the shade.
if (v % 3 != 0) {
val tone = (v / 3) % 3
out += Triple(col, row, tone)
val mirrored = 4 - col
if (mirrored != col) out += Triple(mirrored, row, tone)
}
}
}
return out
}
/** The one hairline rule. */
@Composable
fun OwDivider(modifier: Modifier = Modifier, color: Color = OwColors.Border) {
Box(modifier.fillMaxWidth().height(1.dp).background(color))
}
/** Border stroke helper so screens never hardcode the token twice. */
val OwCardBorder: BorderStroke = BorderStroke(1.dp, OwColors.Border)
/** Convenience for the many `Icon(painterResource(...))` call sites. */
@Composable
fun OwIcon(
iconRes: Int,
contentDescription: String?,
tint: Color = OwColors.TextPrimary,
size: Dp = 20.dp,
) {
Icon(
painter = painterResource(iconRes),
contentDescription = contentDescription,
tint = tint,
modifier = Modifier.size(size),
)
}

View file

@ -0,0 +1,30 @@
package com.siriusdevops.onionwire.wallet
import android.os.StatFs
import java.io.File
/**
* Free space on the filesystem the in-process chain store grows into.
*
* The chain source this is for is Cuprate's fjall store under
* `$ONIONWIRE_HOME/chain` (`WireViewModel.home` is `filesDir/onionwire`), which is
* the same filesystem as `filesDir` — so `StatFs` on the app's own data directory
* answers the question the user is actually being asked: *will this fit here?*
*
* It is a **measurement, not an estimate**: nothing in the SDK exposes a chain
* size (`WalletChildStatus` has no size field, and Cuprate's restricted RPC
* reports a hardcoded 5 GiB placeholder — `src/cuprate.rs`). The floor the screen
* applies to this number is [com.siriusdevops.onionwire.ui.CHAIN_FREE_SPACE_FLOOR_BYTES],
* and it is documented there as a floor rather than a sync estimate.
*
* `null` means "could not be read", and the screen treats that as fail-closed: an
* unknown free space is not reported as enough. Kept out of the JVM unit tests on
* purpose — `StatFs` is an Android class, so the pure formatting and the gate live
* in `ui/WalletChildStatusText.kt` where they are covered without a device.
*/
object ChainStorage {
/** Free bytes on [path]'s filesystem, or `null` when it cannot be read. */
fun freeBytes(path: File): Long? = runCatching { StatFs(path.absolutePath).availableBytes }
.getOrNull()
}

View file

@ -0,0 +1,101 @@
package com.siriusdevops.onionwire.wallet
import java.io.File
/**
* The app-owned wallet-child executables, as the APK actually carries them.
*
* **Why `jniLibs` and not an asset.** Since Android 10 (API 29) an app may not
* `exec()` a file it wrote into its own data directory: the SELinux policy has
* no `execute` on `app_data_file`, so `filesDir/libmonerowalletrpc.so` copied
* out of `assets/` with the exec bit set is still refused by the kernel — the
* classic "copy it to app-private storage" recipe died with `targetSdk 29`.
* The one directory Android does hand out executable is
* `ApplicationInfo.nativeLibraryDir`: the package manager unpacks the
* `lib/<abi>/` entries from the APK there at install time with the exec bit
* intact. A plain
* executable therefore has to be named `lib*.so` and shipped through
* `jniLibs`, and that unpack only happens when the manifest says
* `android:extractNativeLibs="true"` (`packaging.jniLibs.useLegacyPackaging`
* in `app/build.gradle.kts`). With `extractNativeLibs="false"` — the AGP 8
* default — the `.so` stays inside the APK and there is nothing on disk to run.
*
* The names here are the paths handed to the core as `ChainConfig.wallet_rpc_bin`
* and `ChainConfig.arti_bin`; the core spawns exactly the path it is given and
* never falls back to `PATH` (nothing in an APK sandbox resolves a bare
* `monero-wallet-rpc`).
*/
object WalletChildBinaries {
/** `jniLibs/<abi>/` entry name for `monero-wallet-rpc`. */
const val WALLET_RPC_LIB: String = "libmonerowalletrpc.so"
/**
* Wallet file name inside `$ONIONWIRE_HOME/wallet`. Mirrors the core's
* `wallet::DEFAULT_WALLET_FILENAME`, so a config saved from here and a
* config the core defaults to name the same file.
*/
const val WALLET_FILENAME: String = "onionwire"
/**
* `jniLibs/<abi>/` entry name for the `arti` SOCKS child. **Not bundled in
* this build** — a `.onion` daemon needs a separate Rust binary, which is a
* follow-up (see `android/MONERO_BINARIES.md`). The constant exists so the
* screen can name the path it would use, and so the absence is checkable
* rather than assumed.
*/
const val ARTI_LIB: String = "libarti.so"
/**
* Resolve the bundled binaries under [nativeLibraryDir].
*
* A null/blank directory (or a missing file) means this install does not
* carry the binary — the screen says so instead of offering a Start that
* can only fail.
*/
fun resolve(nativeLibraryDir: String?): WalletChildBinaryPaths =
WalletChildBinaryPaths(
walletRpc = existing(nativeLibraryDir, WALLET_RPC_LIB),
arti = existing(nativeLibraryDir, ARTI_LIB),
)
/**
* The absolute path the core is handed for an entry, whether or not the
* file is present.
*
* Used for `arti_bin` on a clearnet/loopback daemon: the core validates
* that `arti_bin` is non-empty for any non-receive-only source but only
* ever spawns it for a `.onion` host, so the value is inert there. Naming
* the path the binary *would* occupy is deliberate — passing a real binary
* that is not `arti` (say, `monero-wallet-rpc`) would be spawned as the
* SOCKS child the moment the user typed an `.onion` host, which is worse
* than an honest `ENOENT`.
*/
fun expectedPath(nativeLibraryDir: String?, entry: String): String {
val dir = nativeLibraryDir?.takeIf { it.isNotBlank() } ?: return ""
return File(dir, entry).absolutePath
}
private fun existing(nativeLibraryDir: String?, entry: String): String? {
val dir = nativeLibraryDir?.takeIf { it.isNotBlank() } ?: return null
val file = File(dir, entry)
return if (file.isFile) file.absolutePath else null
}
}
/** What this install can actually spawn. */
data class WalletChildBinaryPaths(
val walletRpc: String?,
val arti: String?,
) {
val walletRpcBundled: Boolean get() = walletRpc != null
val artiBundled: Boolean get() = arti != null
}
/**
* Shown when this install carries no `monero-wallet-rpc`. One string, used by
* both the status line and the Start gate, so the two can never disagree about
* why the button is dead.
*/
const val NO_WALLET_RPC_MESSAGE: String =
"monero-wallet-rpc is not bundled in this build, so there is nothing to start."

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

View file

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#0B0B10"
android:pathData="M0,0h108v108h-108z" />
</vector>

View file

@ -1,41 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Onion bulb. Adaptive-icon foreground: keep art inside the 66dp safe zone. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<!-- bulb -->
<path
android:fillColor="#7C4DFF"
android:pathData="M54,28 C72,28 82,46 82,62 C82,78 69,88 54,88 C39,88 26,78 26,62 C26,46 36,28 54,28 Z" />
<!-- sprout -->
<path
android:strokeColor="#38F2C7"
android:strokeWidth="3"
android:strokeLineCap="round"
android:pathData="M54,28 L54,18" />
<!-- layers -->
<path
android:strokeColor="#38F2C7"
android:strokeWidth="2.5"
android:strokeLineCap="round"
android:fillColor="#00000000"
android:pathData="M38,40 C33,54 35,74 48,84" />
<path
android:strokeColor="#38F2C7"
android:strokeWidth="2.5"
android:strokeLineCap="round"
android:fillColor="#00000000"
android:pathData="M70,40 C75,54 73,74 60,84" />
<path
android:strokeColor="#0B0B10"
android:strokeWidth="2.5"
android:strokeLineCap="round"
android:fillColor="#00000000"
android:pathData="M54,32 L54,86" />
</vector>

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="M10.8,4 H13.2 V10.8 H20 V13.2 H13.2 V20 H10.8 V13.2 H4 V10.8 H10.8 Z" />
</vector>

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="M4,3 H20 A3,3 0 0 1 23,6 V15 A3,3 0 0 1 20,18 H12 L7,22 V18 H4 A3,3 0 0 1 1,15 V6 A3,3 0 0 1 4,3 Z" />
</vector>

View file

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round"
android:pathData="M14.5,4.5 L7.5,12 L14.5,19.5" />
</vector>

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.8"
android:pathData="M9,8 H18 A2,2 0 0 1 20,10 V20 A2,2 0 0 1 18,22 H9 A2,2 0 0 1 7,20 V10 A2,2 0 0 1 9,8 Z" />
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.8"
android:pathData="M4,16 H3 A1,1 0 0 1 2,15 V4 A1,1 0 0 1 3,3 H14 A1,1 0 0 1 15,4 V5" />
</vector>

View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.8"
android:pathData="M12,2 A10,10 0 1 1 11.99,2 Z" />
<path
android:fillColor="#FF000000"
android:pathData="M11,10 H13 V17.5 H11 Z M11,6 H13 V8.5 H11 Z" />
</vector>

View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.8"
android:pathData="M7,10 V7 A5,5 0 0 1 17,7 V10" />
<path
android:fillColor="#FF000000"
android:pathData="M5,10 H19 A1,1 0 0 1 20,11 V21 A1,1 0 0 1 19,22 H5 A1,1 0 0 1 4,21 V11 A1,1 0 0 1 5,10 Z" />
</vector>

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="M12,4 A2,2 0 1 0 12,8 A2,2 0 1 0 12,4 Z M12,10 A2,2 0 1 0 12,14 A2,2 0 1 0 12,10 Z M12,16 A2,2 0 1 0 12,20 A2,2 0 1 0 12,16 Z" />
</vector>

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.8"
android:pathData="M12,3 A4,4 0 1 1 11.99,3 Z" />
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.8"
android:pathData="M4,21 C4,16.6 7.6,13.5 12,13.5 C16.4,13.5 20,16.6 20,21" />
</vector>

View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="2"
android:pathData="M4,4 H10 V10 H4 Z M14,4 H20 V10 H14 Z M4,14 H10 V20 H4 Z" />
<path
android:fillColor="#FF000000"
android:pathData="M14,14 H17 V17 H14 Z M19,18 H21 V20 H19 Z M14,20 H16.5 V22 H14 Z M19.5,14 H21 V16 H19.5 Z" />
</vector>

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.8"
android:pathData="M12,3 V15 M12,3 L8,7 M12,3 L16,7" />
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.8"
android:pathData="M5,12 V19 A2,2 0 0 0 7,21 H17 A2,2 0 0 0 19,19 V12" />
</vector>

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.6"
android:pathData="M12,2 L20,5 V11 C20,16.4 16.6,20.8 12,22 C7.4,20.8 4,16.4 4,11 V5 Z" />
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.6"
android:pathData="M8.5,11.5 L11,14 L15.5,9.5" />
</vector>

View file

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.8"
android:pathData="M3,6 H7.5 M12.5,6 H21 M3,12 H14.5 M19.5,12 H21 M3,18 H4.5 M9.5,18 H21" />
<path
android:fillColor="#FF000000"
android:pathData="M10,3.5 A2.5,2.5 0 1 0 10,8.5 A2.5,2.5 0 1 0 10,3.5 Z" />
<path
android:fillColor="#FF000000"
android:pathData="M17,9.5 A2.5,2.5 0 1 0 17,14.5 A2.5,2.5 0 1 0 17,9.5 Z" />
<path
android:fillColor="#FF000000"
android:pathData="M7,15.5 A2.5,2.5 0 1 0 7,20.5 A2.5,2.5 0 1 0 7,15.5 Z" />
</vector>

View file

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Single colour; tinted at the call site. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.8"
android:pathData="M4,6 H18 A2,2 0 0 1 20,8 V10 H16 A3,3 0 0 0 16,16 H20 V18 A2,2 0 0 1 18,20 H4 A2,2 0 0 1 2,18 V8 A2,2 0 0 1 4,6 Z" />
</vector>

View file

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire design-system icon. Outline only: a filled triangle would lose
its knock-out once the call site tints the drawable. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.8"
android:strokeLineJoin="round"
android:pathData="M12,3 L22,20.5 H2 Z" />
<path
android:fillColor="#00000000"
android:strokeColor="#FF000000"
android:strokeWidth="1.8"
android:strokeLineCap="round"
android:pathData="M12,9 V14.5 M12,17 V17.2" />
</vector>

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Status-bar icon for the keep-alive notification. Notification icons are
alpha masks, so this is a flat white silhouette: an onion bulb with a sprout.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M12,2.6c-0.7,1.2 -1.1,2.3 -1.1,3.2 0,0.5 0.5,0.9 1.1,0.9s1.1,-0.4 1.1,-0.9c0,-0.9 -0.4,-2 -1.1,-3.2z" />
<path
android:fillColor="#FFFFFFFF"
android:pathData="M12,6.4c-2.2,2 -3.6,4.6 -3.6,7.3 0,3.9 1.6,7.3 3.6,7.3s3.6,-3.4 3.6,-7.3c0,-2.7 -1.4,-5.3 -3.6,-7.3zM12,8.2c1.1,1.3 2.1,3 2.1,5.5 0,1.5 -0.5,2.9 -1,3.3 -0.6,-0.4 -1.1,-1.8 -1.1,-3.3 0,-2.5 1,-4.2 2.1,-5.5z" />
</vector>

View file

@ -1,5 +1,19 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- OnionWire launcher icon (adaptive).
The artwork lives in drawable-nodpi/onionwire_app_icon.png as a single
432x432 full-bleed bitmap: the networked-onion logo at 62% of the canvas
(inside the 66dp/108dp adaptive-icon safe zone) over a seamless blurred
backdrop of itself. It is used as the background layer, so the launcher
mask can crop the outer edge of the artwork without ever clipping the
logo. The foreground layer is transparent on purpose: the whole icon is
the bitmap.
Do not point android:icon at a bitmap in this directory again. A bitmap
under mipmap-anydpi-v26 is a *legacy* icon: it is not an adaptive icon, so
the launcher pads it into the mask with its own plate and it scales wrong
on high-density screens. -->
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" /> <background android:drawable="@drawable/onionwire_app_icon" />
<foreground android:drawable="@drawable/ic_launcher_foreground" /> <foreground android:drawable="@android:color/transparent" />
</adaptive-icon> </adaptive-icon>

View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Round variant for launchers that ask for android:roundIcon (Pixel
Launcher, Samsung One UI). Must render the same artwork as ic_launcher.xml
— a stale roundIcon is exactly how an "old icon" survives an icon change,
because those launchers prefer roundIcon over icon. -->
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/onionwire_app_icon" />
<foreground android:drawable="@android:color/transparent" />
</adaptive-icon>

View file

@ -1,4 +1,22 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<string name="app_name">OnionWire</string> <string name="app_name">OnionWire</string>
<!--
Foreground keep-alive. The notification text is the only place the user
can see what is still running once the screen is off, so it names the
moving parts instead of saying "running in the background".
-->
<string name="keep_alive_channel_name">Node keep-alive</string>
<string name="keep_alive_channel_description">Shown while OnionWire keeps your onion address reachable in the background.</string>
<string name="keep_alive_title">OnionWire is reachable</string>
<string name="keep_alive_title_opening">OnionWire is starting</string>
<string name="keep_alive_text">Tor and the outbox are running so peers can deliver messages.</string>
<string name="keep_alive_text_opening">Bootstrapping Tor. This can take minutes — keep the device awake.</string>
<string name="keep_alive_text_onion">Tor and the outbox are running so peers can reach %1$s…</string>
<string name="keep_alive_stop">Stop keep-alive</string>
<string name="keep_alive_note_off">Reachable only while this app is open.</string>
<string name="keep_alive_note_on">Kept alive — Tor and the outbox run until you tap Lock.</string>
<string name="keep_alive_note_hidden">Kept alive, but notifications are blocked, so the status notice is hidden. Android still lists the service in the Task Manager.</string>
<string name="keep_alive_note_unavailable">Not kept alive (%1$s). The node stops when the app does.</string>
</resources> </resources>

View file

@ -0,0 +1,108 @@
package com.siriusdevops.onionwire
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.currentTime
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* The wallet screen's refresh loop.
*
* `Wire` has no seam a JVM test can fake: `requireWire()` reads
* `NodeHost.requireOpen()`, a process-global that only `openWire()` — i.e. a
* real Arti bootstrap — sets, and `Wire` itself is the generated UniFFI
* interface. So the loop takes its two reads as parameters, and these tests
* drive it with recording lambdas to pin the two things that make the
* `sync h/t` segment live:
*
* - the cheap cached read paints once, and every tick after it is the live
* probe (`Wire::wallet_child_refresh`), not the cached status read
* (`Wire::wallet_status`) that only re-reads what the last probe left behind;
* - the ticks are serialized by construction — a probe slower than the tick
* delays the next one instead of overlapping it, so no two
* `wallet_child_refresh` calls are ever in flight against one wallet child.
*
* The binding of `live` to `WireViewModel.refreshWalletChild()` (and `cached`
* to `paintWalletChildCached()`) is the two lines in
* `WireViewModel.openWalletChild()`, and the source there is the evidence for
* it — nothing in this test can observe a `NodeHost` that is not open.
*
* Time is virtual, so the 2s cadence is free to assert. Note the scheduler's
* rule: `advanceTimeBy(n)` runs what is scheduled strictly before `n`, not the
* task at `n` itself.
*/
class WalletChildRefreshLoopTest {
@Test
fun the_first_paint_is_the_cached_read_and_every_tick_after_it_is_live() = runTest {
var cached = 0
var live = 0
val job = launch {
walletChildRefreshLoop(tickMs = TICK_MS, cached = { cached++ }, live = { live++ })
}
// Four ticks of virtual time: probes at 2s, 4s and 6s; the 8s one has
// not fired yet.
advanceTimeBy(4 * TICK_MS)
assertEquals("the cheap read paints once, and only once", 1, cached)
assertEquals("every tick after the paint is a live probe", 3, live)
assertEquals("and they land on the tick, not back to back", 4 * TICK_MS, currentTime)
job.cancel()
advanceTimeBy(10 * TICK_MS)
assertEquals("cancelling the loop is what stops the dialing", 3, live)
}
@Test
fun a_probe_slower_than_the_tick_is_never_overlapped() = runTest {
var inFlight = 0
var maxInFlight = 0
var probes = 0
val job = launch {
walletChildRefreshLoop(
tickMs = TICK_MS,
cached = {},
live = {
inFlight++
if (inFlight > maxInFlight) maxInFlight = inFlight
delay(5 * TICK_MS) // a probe five ticks long
inFlight--
probes++
},
)
}
// Probe 1 at 2s runs to 12s, probe 2 at 14s to 24s, probe 3 at 26s to
// 36s: each of them pushes the next tick out by its own length.
advanceTimeBy(19 * TICK_MS)
assertEquals("two concurrent wallet_child_refresh probes is a race", 1, maxInFlight)
assertEquals("three probes done, none of them skipped or doubled", 3, probes)
assertEquals(19 * TICK_MS, currentTime)
job.cancel()
}
@Test
fun cancelling_the_loop_stops_the_probes() = runTest {
var live = 0
val job = launch {
walletChildRefreshLoop(tickMs = TICK_MS, cached = {}, live = { live++ })
}
advanceTimeBy(3 * TICK_MS)
assertEquals("two ticks have gone by", 2, live)
job.cancel()
advanceTimeBy(10 * TICK_MS)
assertEquals("leaving the wallet screen stops the dialing", 2, live)
}
private companion object {
const val TICK_MS = 2_000L
}
}

View file

@ -0,0 +1,157 @@
package com.siriusdevops.onionwire.crypto
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
/**
* Exercises the real envelope code — [StoreSecret] has no `android.*` imports,
* so a JVM AES key stands in for the AndroidKeystore key.
*
* What this does NOT cover (see the PR description): the AndroidKeyStore provider
* itself (`KeyGenerator` + `KeyGenParameterSpec`, StrongBox fallback, and
* `KeyInfo.isInsideSecureHardware`). Those are device-only APIs; the unit-test
* JVM has no such provider.
*/
class StoreSecretTest {
private fun aesKey(): SecretKey =
KeyGenerator.getInstance("AES").apply { init(StoreSecret.KEY_BITS) }.generateKey()
private val passphrase = "correct horse battery staple".toCharArray()
@Test
fun seal_open_round_trips() {
val key = aesKey()
val blob = StoreSecret.seal(key, passphrase)
val out = StoreSecret.open(key, blob)
try {
assertArrayEquals(passphrase, out)
} finally {
StoreSecret.wipe(out)
}
}
@Test
fun round_trips_non_ascii_and_whitespace() {
val key = aesKey()
val weird = " ünïcödé 🔑 \n\ttab ".toCharArray()
val out = StoreSecret.open(key, StoreSecret.seal(key, weird))
try {
assertArrayEquals(weird, out)
} finally {
StoreSecret.wipe(out)
}
}
@Test
fun blob_does_not_contain_the_plaintext() {
val key = aesKey()
val blob = StoreSecret.seal(key, passphrase)
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
assertFalse(
"ciphertext must not contain the passphrase",
blob.containsSubsequence(needle),
)
assertTrue(blob.size > needle.size)
}
@Test
fun blob_carries_the_envelope_magic() {
val blob = StoreSecret.seal(aesKey(), passphrase)
assertEquals("OWSEAL1\n", String(blob.copyOfRange(0, 8), Charsets.US_ASCII))
// Magic(8) + IV length(1) + IV(12) + tag(16)
assertEquals(8 + 1 + StoreSecret.IV_BYTES + 16, blob.size - String(passphrase).toByteArray(Charsets.UTF_8).size)
}
@Test
fun each_seal_uses_a_fresh_iv() {
val key = aesKey()
val a = StoreSecret.seal(key, passphrase)
val b = StoreSecret.seal(key, passphrase)
assertNotEquals(
"identical ciphertext means the IV was reused",
a.toList(),
b.toList(),
)
}
@Test
fun wrong_key_fails_closed() {
val blob = StoreSecret.seal(aesKey(), passphrase)
try {
StoreSecret.open(aesKey(), blob)
fail("expected SecretUnavailable")
} catch (e: SecretUnavailable) {
assertTrue(e.message!!.contains("authenticate"))
}
}
@Test
fun tampered_ciphertext_fails_the_gcm_tag() {
val key = aesKey()
val blob = StoreSecret.seal(key, passphrase)
blob[blob.size - 1] = (blob[blob.size - 1].toInt() xor 0x01).toByte()
try {
StoreSecret.open(key, blob)
fail("expected SecretUnavailable")
} catch (_: SecretUnavailable) {
}
}
@Test
fun truncated_blob_fails_closed() {
val key = aesKey()
val blob = StoreSecret.seal(key, passphrase)
try {
StoreSecret.open(key, blob.copyOfRange(0, 10))
fail("expected SecretUnavailable")
} catch (_: SecretUnavailable) {
}
}
@Test
fun garbage_blob_fails_closed() {
try {
StoreSecret.open(aesKey(), "not an envelope".toByteArray())
fail("expected SecretUnavailable")
} catch (e: SecretUnavailable) {
assertTrue(e.message!!.contains("truncated") || e.message!!.contains("envelope"))
}
}
@Test
fun seal_refuses_an_empty_passphrase() {
try {
StoreSecret.seal(aesKey(), CharArray(0))
fail("expected IllegalArgumentException")
} catch (_: IllegalArgumentException) {
}
}
@Test
fun wipe_zeroes() {
val bytes = byteArrayOf(1, 2, 3)
StoreSecret.wipe(bytes)
assertArrayEquals(ByteArray(3), bytes)
val chars = charArrayOf('a', 'b')
StoreSecret.wipe(chars)
assertArrayEquals(CharArray(2), chars)
}
private fun ByteArray.containsSubsequence(needle: ByteArray): Boolean {
if (needle.isEmpty() || needle.size > size) return false
outer@ for (i in 0..size - needle.size) {
for (j in needle.indices) if (this[i + j] != needle[j]) continue@outer
return true
}
return false
}
}

View file

@ -0,0 +1,167 @@
package com.siriusdevops.onionwire.crypto
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
/**
* File-level behaviour of [StoredPassphraseStore] with the real envelope from
* [StoreSecret] and a JVM AES key standing in for the Keystore key.
*
* The Keystore itself is device-only; what is proven here is that nothing
* plaintext reaches the file, that a lost key degrades instead of crashing,
* and that a lost key does not delete the user's blob.
*/
class StoredPassphraseStoreTest {
@get:Rule
val tmp = TemporaryFolder()
private val passphrase = "correct horse battery staple".toCharArray()
/** Stands in for the AndroidKeystore key: real AES-GCM, JVM-held key. */
private class JvmKeyCipher(private val key: SecretKey) : PassphraseCipher {
var deleted = false
var backingQueried = 0
override fun seal(plaintext: CharArray): ByteArray = StoreSecret.seal(key, plaintext)
override fun open(blob: ByteArray): CharArray {
if (deleted) throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
return StoreSecret.open(key, blob)
}
override fun keyPresent(): Boolean = !deleted
override fun backing(): KeyBacking {
backingQueried++
return KeyBacking.SOFTWARE
}
override fun deleteKey() {
deleted = true
}
}
private fun jvmKey(): SecretKey =
KeyGenerator.getInstance("AES").apply { init(StoreSecret.KEY_BITS) }.generateKey()
private fun store(cipher: PassphraseCipher) =
StoredPassphraseStore(tmp.newFile("store-passphrase.bin").also { it.delete() }, cipher)
@Test
fun save_then_load_round_trips() {
val store = store(JvmKeyCipher(jvmKey()))
store.save(passphrase)
val loaded = store.load()
assertTrue(loaded is StoredPassphraseStore.Load.Loaded)
val out = (loaded as StoredPassphraseStore.Load.Loaded).passphrase
try {
assertArrayEquals(passphrase, out)
} finally {
StoreSecret.wipe(out)
}
}
@Test
fun on_disk_blob_is_not_the_plaintext() {
val store = store(JvmKeyCipher(jvmKey()))
store.save(passphrase)
val raw = java.io.File(store.path).readBytes()
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
assertFalse(
"the passphrase must not appear in the file",
raw.toString(Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)),
)
assertTrue("expected the OWSEAL envelope", raw.size > needle.size + 20)
assertEquals("OWSEAL1\n", String(raw.copyOfRange(0, 8), Charsets.US_ASCII))
}
@Test
fun no_temp_file_is_left_behind() {
val store = store(JvmKeyCipher(jvmKey()))
store.save(passphrase)
val dir = requireNotNull(java.io.File(store.path).parentFile)
val leftovers = dir.listFiles()!!.filter { it.name.endsWith(".tmp") }
assertTrue("temp files left: $leftovers", leftovers.isEmpty())
}
@Test
fun save_overwrites_the_previous_blob() {
val store = store(JvmKeyCipher(jvmKey()))
store.save("first".toCharArray())
store.save("second".toCharArray())
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
try {
assertArrayEquals("second".toCharArray(), loaded.passphrase)
} finally {
StoreSecret.wipe(loaded.passphrase)
}
}
@Test
fun absent_when_nothing_was_ever_stored() {
val store = store(JvmKeyCipher(jvmKey()))
assertFalse(store.exists())
assertEquals(StoredPassphraseStore.Load.Absent, store.load())
}
@Test
fun lost_key_reports_unavailable_and_keeps_the_blob() {
val cipher = JvmKeyCipher(jvmKey())
val store = store(cipher)
store.save(passphrase)
cipher.deleteKey() // device reset / key invalidated
val loaded = store.load()
assertTrue(loaded is StoredPassphraseStore.Load.Unavailable)
assertTrue(
(loaded as StoredPassphraseStore.Load.Unavailable).reason.contains("gone"),
)
assertTrue("a failed read must not delete the blob", store.exists())
}
@Test
fun corrupt_blob_reports_unavailable_instead_of_throwing() {
val store = store(JvmKeyCipher(jvmKey()))
store.save(passphrase)
java.io.File(store.path).writeBytes("OWSEAL1\n not really a ciphertext".toByteArray())
val loaded = store.load()
assertTrue(loaded is StoredPassphraseStore.Load.Unavailable)
}
@Test
fun forget_deletes_the_blob_and_the_key() {
val cipher = JvmKeyCipher(jvmKey())
val store = store(cipher)
store.save(passphrase)
assertTrue(store.exists())
store.forget()
assertFalse(store.exists())
assertFalse(cipher.keyPresent())
assertEquals(StoredPassphraseStore.Load.Absent, store.load())
}
@Test
fun backing_is_reported_from_the_cipher() {
val cipher = JvmKeyCipher(jvmKey())
val store = store(cipher)
store.save(passphrase)
assertEquals(KeyBacking.SOFTWARE, store.backing())
assertEquals(1, cipher.backingQueried)
}
}

View file

@ -0,0 +1,29 @@
package com.siriusdevops.onionwire.keepalive
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The keep-alive used to refuse to start until [NodeHost.current] was set —
* which is only after Tor has published. Bootstrap itself ran on the UI
* ViewModel scope, so closing the activity cancelled `openWire` and the
* spinner vanished with no onion.
*/
class KeepAlivePolicyTest {
@Test
fun bootstrap_in_flight_is_work_the_service_must_hold() {
assertTrue(keepAliveHasWork(nodeOpen = false, bootstrapInFlight = true))
}
@Test
fun a_live_node_is_work_the_service_must_hold() {
assertTrue(keepAliveHasWork(nodeOpen = true, bootstrapInFlight = false))
}
@Test
fun locked_and_idle_is_not_work() {
assertFalse(keepAliveHasWork(nodeOpen = false, bootstrapInFlight = false))
}
}

View file

@ -0,0 +1,130 @@
package com.siriusdevops.onionwire.keepalive
import com.siriusdevops.onionwire.keepalive.NodeAction.Flush
import com.siriusdevops.onionwire.keepalive.NodeAction.Keep
import com.siriusdevops.onionwire.keepalive.NodeAction.Stop
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The service-lifetime state machine, no device required: [NodeLifetime] is
* pure. Every case here is a transition the app actually produces — unlock,
* background, task swipe, notification Stop, explicit Lock, re-unlock.
*/
class NodeLifetimeTest {
@Test
fun ui_detach_with_no_keep_alive_stops_the_node() {
val l = NodeLifetime()
l.onOpened()
assertEquals(Stop, l.onUnanchored(NodeAnchor.UI))
assertTrue(l.isOpen) // the caller still has to run flush+shutdown
}
@Test
fun keep_alive_anchor_survives_ui_detach_and_only_flushes() {
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
// Task swiped: the activity is gone, the service is not.
assertEquals(Flush, l.onUnanchored(NodeAnchor.UI))
assertFalse(l.anchoredBy(NodeAnchor.UI))
assertTrue(l.anchoredBy(NodeAnchor.KEEP_ALIVE))
}
@Test
fun losing_the_last_anchor_stops_the_node() {
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
l.onUnanchored(NodeAnchor.UI)
// Notification Stop, or the system killing the service.
assertEquals(Stop, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
}
@Test
fun service_stopping_while_the_ui_is_up_keeps_the_node() {
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
assertEquals(Flush, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
assertTrue(l.anchoredBy(NodeAnchor.UI))
assertTrue(l.isOpen)
}
@Test
fun repeated_anchor_loss_is_idempotent() {
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
l.onUnanchored(NodeAnchor.UI)
// The Stop action and onDestroy both report the same loss.
assertEquals(Stop, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
l.onClosed()
assertEquals(Keep, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
}
@Test
fun lock_drops_every_anchor() {
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
assertEquals(Stop, l.onLocked())
assertFalse(l.isOpen)
assertFalse(l.anchoredBy(NodeAnchor.KEEP_ALIVE))
assertFalse(l.anchoredBy(NodeAnchor.UI))
l.onClosed()
}
@Test
fun re_unlock_after_lock_starts_from_a_clean_slate() {
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
l.onLocked()
l.onClosed()
// Second unlock: only the UI anchors, so backgrounding really stops.
assertEquals(Keep, l.onOpened())
assertFalse(l.anchoredBy(NodeAnchor.KEEP_ALIVE))
assertEquals(Stop, l.onUnanchored(NodeAnchor.UI))
}
@Test
fun re_unlock_while_the_keep_alive_still_holds_the_node_adopts_it() {
// Process relaunch with the service still up: the ViewModel adopts the
// live node and never calls onOpened(), so the KEEP_ALIVE anchor (and
// the node) is untouched by the new UI attaching.
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
l.onUnanchored(NodeAnchor.UI)
assertTrue(l.isOpen)
assertTrue(l.anchoredBy(NodeAnchor.KEEP_ALIVE))
assertFalse(l.anchoredBy(NodeAnchor.UI))
// The adopted UI leaves again: still flush, still alive.
assertEquals(Flush, l.onUnanchored(NodeAnchor.UI))
assertTrue(l.isOpen)
assertEquals(Stop, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
}
@Test
fun transitions_on_a_closed_node_do_nothing() {
val l = NodeLifetime()
assertEquals(Keep, l.onUnanchored(NodeAnchor.UI))
assertEquals(Keep, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
assertEquals(Keep, l.onLocked())
assertEquals(Keep, l.onAnchored(NodeAnchor.KEEP_ALIVE)) // service up, still locked
}
}

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

@ -0,0 +1,278 @@
package com.siriusdevops.onionwire.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The SDK's outbox rows turned into chat-row wording: `queued (try 3/8, retry
* 45s)`.
*
* These assert the pure model `ChatScreen` renders from — the same shape as
* `MessageDeliveryTest` — so the retry wording, the fail-closed join and the
* "a failed row never shows a countdown" rule are all covered on the JVM
* without a device.
*/
class OutboxDetailTest {
private fun out(delivery: String?) = ChatRowInput("out", delivery)
private fun row(
messageId: Long,
status: String,
attempts: UInt = 0u,
nextAttemptAt: Long = 0L,
) = OutboxRowInput(messageId, status, attempts, nextAttemptAt)
// --- retry_in_text: the three buckets, mirroring src/tui.rs -------------
@Test
fun retry_in_text_is_now_at_or_before_the_next_attempt_time() {
assertEquals("retry now", retryInText(0L))
assertEquals("retry now", retryInText(-45L))
}
@Test
fun retry_in_text_counts_seconds_below_a_minute() {
assertEquals("retry 1s", retryInText(1L))
assertEquals("retry 45s", retryInText(45L))
assertEquals("retry 59s", retryInText(59L))
}
@Test
fun retry_in_text_rounds_minutes_up_from_the_first_minute() {
// 60s is one minute, not "retry 1s" and not "retry 0m".
assertEquals("retry 1m", retryInText(60L))
// Anything over the boundary rounds up, so the app never promises an
// attempt sooner than the store will make one.
assertEquals("retry 2m", retryInText(61L))
assertEquals("retry 10m", retryInText(600L))
assertEquals("retry 25m", retryInText(1500L))
// The core's backoff caps at 30 minutes.
assertEquals("retry 30m", retryInText(1800L))
}
// --- the queued row's own numbers ---------------------------------------
@Test
fun a_queued_row_renders_the_tui_wording() {
val details = outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(7L, "queued", attempts = 3u, nextAttemptAt = 1_000L + 45L)),
maxAttempts = 8u,
now = 1_000L,
)
val detail = requireNotNull(details.single())
assertEquals("queued (try 3/8, retry 45s)", detail.text)
assertEquals("◷ queued (try 3/8, retry 45s)", deliveryMarkerText(Delivery.Queued, detail))
}
@Test
fun the_denominator_comes_from_the_core_not_a_constant_here() {
val detail = requireNotNull(
outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(1L, "queued", attempts = 3u, nextAttemptAt = 0L)),
maxAttempts = 12u,
now = 0L,
).single(),
)
assertEquals("queued (try 3/12, retry now)", detail.text)
}
@Test
fun an_overdue_attempt_reads_retry_now() {
val detail = requireNotNull(
outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(1L, "queued", attempts = 1u, nextAttemptAt = 900L)),
maxAttempts = 8u,
now = 1_000L,
).single(),
)
assertEquals("queued (try 1/8, retry now)", detail.text)
}
@Test
fun the_countdown_is_computed_from_the_absolute_time_the_store_holds() {
val first = requireNotNull(
outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(1L, "queued", attempts = 2u, nextAttemptAt = 1_000L + 600L)),
maxAttempts = 8u,
now = 1_000L,
).single(),
)
assertEquals("queued (try 2/8, retry 10m)", first.text)
// Same row, one minute later: the wording moves with `now`.
val later = requireNotNull(
outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(1L, "queued", attempts = 2u, nextAttemptAt = 1_000L + 600L)),
maxAttempts = 8u,
now = 1_060L,
).single(),
)
assertEquals("queued (try 2/8, retry 9m)", later.text)
}
// --- the states that must not show a countdown --------------------------
@Test
fun a_failed_row_shows_no_countdown() {
// A terminal row keeps the last time it was scheduled for. Rendering
// that as "retry 15m" would promise an attempt that will never happen.
val details = outboxDetails(
rows = listOf(out("failed: connection timed out")),
outbox = listOf(row(4L, "failed", attempts = 8u, nextAttemptAt = 1_900L)),
maxAttempts = 8u,
now = 1_000L,
)
assertNull(details.single())
val d = requireNotNull(parseDelivery("out", "failed: connection timed out"))
assertEquals("✗ failed: connection timed out", deliveryMarkerText(d, details.single()))
assertEquals("Failed: connection timed out", deliveryAnnouncement(d, details.single()))
}
@Test
fun a_sending_row_shows_no_countdown() {
val details = outboxDetails(
rows = listOf(out("sending")),
outbox = listOf(row(4L, "sending", attempts = 2u, nextAttemptAt = 1_900L)),
maxAttempts = 8u,
now = 1_000L,
)
assertNull(details.single())
val d = requireNotNull(parseDelivery("out", "sending"))
assertEquals("» sending", deliveryMarkerText(d, details.single()))
}
@Test
fun delivered_and_inbound_rows_never_take_an_outbox_row() {
// No outbox rows at all: an accepted send and an inbound row are quiet.
val details = outboxDetails(
rows = listOf(ChatRowInput("in", null), out("sent")),
outbox = emptyList(),
maxAttempts = 8u,
now = 1_000L,
)
assertEquals(listOf(null, null), details)
}
// --- the join is positional, so it has to prove itself ------------------
@Test
fun details_are_attached_to_the_pending_row_in_order() {
val rows = listOf(out("sent"), ChatRowInput("in", null), out("queued"), out("failed: no route"))
val details = outboxDetails(
rows = rows,
outbox = listOf(
row(12L, "queued", attempts = 1u, nextAttemptAt = 1_030L),
row(15L, "failed", attempts = 8u, nextAttemptAt = 1_500L),
),
maxAttempts = 8u,
now = 1_000L,
)
assertNull(details[0])
assertNull(details[1])
assertEquals("queued (try 1/8, retry 30s)", requireNotNull(details[2]).text)
assertNull(details[3])
}
@Test
fun the_join_ignores_the_row_order_the_core_returned() {
val details = outboxDetails(
rows = listOf(out("queued"), out("queued")),
outbox = listOf(
row(20L, "queued", attempts = 1u, nextAttemptAt = 1_010L),
row(10L, "queued", attempts = 2u, nextAttemptAt = 1_020L),
),
maxAttempts = 8u,
now = 1_000L,
)
// Sorted by messageId, so the older message owns the 20s row.
assertEquals("queued (try 2/8, retry 20s)", requireNotNull(details[0]).text)
assertEquals("queued (try 1/8, retry 10s)", requireNotNull(details[1]).text)
}
@Test
fun a_row_count_that_does_not_match_the_pending_sends_drops_every_detail() {
// The app cannot prove which message owns which row, so it says nothing
// rather than showing the wrong attempt count.
val details = outboxDetails(
rows = listOf(out("queued"), out("queued")),
outbox = listOf(row(1L, "queued", attempts = 3u, nextAttemptAt = 1_010L)),
maxAttempts = 8u,
now = 1_000L,
)
assertEquals(listOf(null, null), details)
}
@Test
fun a_status_that_contradicts_the_message_drops_every_detail() {
// Positional join + the SDK's own per-message status is the check: the
// first message is queued, the row in its slot says failed.
val details = outboxDetails(
rows = listOf(out("queued"), out("queued")),
outbox = listOf(
row(1L, "failed", attempts = 8u, nextAttemptAt = 1_010L),
row(2L, "queued", attempts = 1u, nextAttemptAt = 1_010L),
),
maxAttempts = 8u,
now = 1_000L,
)
assertEquals(listOf(null, null), details)
}
@Test
fun a_status_this_build_does_not_know_drops_every_detail() {
val details = outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(1L, "spooling", attempts = 1u, nextAttemptAt = 1_010L)),
maxAttempts = 8u,
now = 1_000L,
)
assertEquals(listOf(null), details)
}
@Test
fun an_unknown_delivery_on_a_pending_row_is_treated_as_pending() {
// parseDelivery maps an unrecognised outgoing status to Queued (never
// delivered), so the row still wants its outbox row.
val detail = requireNotNull(
outboxDetails(
rows = listOf(out("spooling")),
outbox = listOf(row(1L, "queued", attempts = 1u, nextAttemptAt = 1_000L)),
maxAttempts = 8u,
now = 1_000L,
).single(),
)
assertEquals("queued (try 1/8, retry now)", detail.text)
}
// --- a11y ---------------------------------------------------------------
@Test
fun the_announcement_keeps_the_sentence_and_adds_the_numbers() {
val detail = requireNotNull(
outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(1L, "queued", attempts = 3u, nextAttemptAt = 1_045L)),
maxAttempts = 8u,
now = 1_000L,
).single(),
)
val said = deliveryAnnouncement(Delivery.Queued, detail)
assertEquals(
"Queued, not delivered yet: retrying their onion (try 3/8, retry 45s)",
said,
)
// Never a bare glyph, and never only numbers.
assertTrue(said.any { it.isLetter() })
assertTrue(!said.contains("◷"))
}
}

View file

@ -0,0 +1,254 @@
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
/**
* The profile screen's rules, on the JVM.
*
* These are the decisions `ProfileScreen` renders from: whether Save is live,
* whether a typed address can be written at all, which bio a save actually
* persists, and what the status line says after pushing to the roster. Pure
* logic — no Robolectric, no Compose test dependency, no device — same shape as
* `SeedBackupGateTest` and `RosterIdTest`.
*
* The address check is injected (`profileAddressProblem` takes the predicate),
* so the contract under test is the screen's, not UniFFI's: `check_address`'s
* own behaviour is covered by the SDK's Rust tests.
*/
class ProfileDraftTest {
/** A loaded profile, i.e. what the store held when the screen opened. */
private val loaded = ProfileDraft(
nickname = "lance",
bio = "gardener, mostly drip irrigation",
address = "44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft3XjrpDtQGv7SqSsaBYBb98uNbr2VBBEt7f2wfn3RVGQBEP3A",
)
// --- the save button's rule ---------------------------------------------
@Test
fun save_is_dead_until_the_first_read_lands() {
// `loaded == null` is "the screen has not read the store yet", not "the
// form is unchanged" — writing before the read would fight the store.
assertFalse(profileSaveEnabled(null, loaded))
assertFalse(profileSaveEnabled(null, ProfileDraft()))
}
@Test
fun save_is_dead_while_the_form_is_unchanged() {
assertFalse(profileSaveEnabled(loaded, loaded.copy()))
}
@Test
fun save_is_live_as_soon_as_any_field_differs() {
assertTrue(profileSaveEnabled(loaded, loaded.copy(nickname = "lance2")))
assertTrue(profileSaveEnabled(loaded, loaded.copy(bio = "something else")))
assertTrue(profileSaveEnabled(loaded, loaded.copy(address = "")))
}
@Test
fun an_empty_nickname_is_a_real_edit_and_is_allowed() {
// Picked deliberately: the core accepts an empty `display_name` (it only
// bounds the length and forbids newlines), the TUI's `/profile` accepts
// it, and the roster already falls back to the fingerprint. So clearing
// a nickname must be saveable rather than hidden behind a disabled
// button the user cannot explain.
val cleared = loaded.copy(nickname = "")
assertTrue(profileSaveEnabled(loaded, cleared))
assertEquals("", cleared.normalized().nickname)
}
@Test
fun whitespace_around_a_field_is_not_a_change() {
// A trailing space from a paste or an autocorrect habit must not offer a
// save that would write the same value back.
val padded = loaded.copy(nickname = " lance ", address = "${loaded.address}\n")
assertFalse(profileSaveEnabled(loaded, padded))
}
@Test
fun normalising_strips_only_the_edges() {
// Interior whitespace is the user's: a bio may well want it.
val n = ProfileDraft(" a b ", " x y ", " addr ").normalized()
assertEquals("a b", n.nickname)
assertEquals("x y", n.bio)
assertEquals("addr", n.address)
}
// --- the address check ---------------------------------------------------
/** Stands in for `uniffi.onionwire_sdk.checkAddress`: anything but "" ok. */
private val accepts: (String) -> Result<Unit> = { Result.success(Unit) }
/** The core's own words, copied from `pay::check_address`. */
private val rejects: (String) -> Result<Unit> =
{ Result.failure(IllegalStateException("invalid Monero address")) }
@Test
fun an_empty_address_is_allowed_and_is_never_checked() {
var calls = 0
val counted: (String) -> Result<Unit> = { calls++; Result.success(Unit) }
// Empty clears the profile address, which the core permits — and
// `check_address("")` would fail, so the predicate must not even run.
assertNull(profileAddressProblem("", counted))
assertNull(profileAddressProblem(" ", counted))
assertEquals(0, calls)
}
@Test
fun a_valid_address_passes() {
assertNull(profileAddressProblem(loaded.address, accepts))
}
@Test
fun an_invalid_address_is_refused_with_the_cores_own_words() {
assertEquals(
"invalid Monero address",
profileAddressProblem("not-an-address", rejects),
)
}
@Test
fun the_check_sees_the_value_that_would_be_written() {
// The screen saves `normalized()`, so the check must see the trimmed
// address, not the raw field — otherwise a paste with a trailing space
// passes the pre-check and then fails inside the core.
var seen: String? = null
val spy: (String) -> Result<Unit> = { seen = it; Result.success(Unit) }
assertNull(profileAddressProblem(" ${loaded.address} ", spy))
assertEquals(loaded.address, seen)
}
@Test
fun a_failure_without_a_message_still_reports_something() {
val blank: (String) -> Result<Unit> =
{ Result.failure(RuntimeException()) }
val problem = profileAddressProblem("x", blank)
assertTrue(problem != null && problem.isNotEmpty())
}
// --- the bio is carried, not owned --------------------------------------
@Test
fun an_untouched_bio_writes_back_what_the_store_holds_now() {
// The TUI edited the bio since this screen loaded. The phone save did
// not touch the field, so the store's value must win — blanking it here
// is exactly the regression this rule exists to prevent.
assertEquals(
"set in the TUI after this screen opened",
bioToWrite(
draftBio = loaded.bio,
loadedBio = loaded.bio,
storedBio = "set in the TUI after this screen opened",
),
)
}
@Test
fun an_edited_bio_writes_what_the_user_typed() {
assertEquals(
"typed on the phone",
bioToWrite(
draftBio = "typed on the phone",
loadedBio = loaded.bio,
storedBio = "set in the TUI after this screen opened",
),
)
}
@Test
fun padding_a_bio_is_not_an_edit() {
// Same normalisation as the dirty check: a trailing space is not a
// reason to override a bio someone set elsewhere.
assertEquals(
loaded.bio,
bioToWrite("${loaded.bio} ", loaded.bio, loaded.bio),
)
}
// --- labels ---------------------------------------------------------------
@Test
fun a_friend_is_labelled_by_petname_else_by_short_id() {
val fp = "654c4a382299b364d1345cf69961e1d529659122fc1550c7c75c537b2a30aa99"
assertEquals("Bob", friendLabel("Bob", fp))
assertEquals(shortId(fp), friendLabel(null, fp))
// A roster row with a blank petname renders the fingerprint too.
assertEquals(shortId(fp), friendLabel(" ", fp))
}
// --- the status line ------------------------------------------------------
@Test
fun an_empty_roster_reports_a_plain_save() {
// The TUI's word for "written locally, sent to nobody".
assertEquals("profile saved", profileStatusLine(emptyList()))
}
@Test
fun a_clean_push_names_the_count() {
val one = profileStatusLine(listOf(ProfilePushOutcome("Bob")))
assertEquals("profile saved · sent to 1 friend", one)
val three = profileStatusLine(
listOf(
ProfilePushOutcome("Bob"),
ProfilePushOutcome("Ann"),
ProfilePushOutcome("654c4a…aa99"),
),
)
assertEquals("profile saved · sent to 3 friends", three)
}
@Test
fun a_failed_push_still_starts_with_the_local_write() {
// The split that matters: the store was written, one peer was not
// reached. A status line that reads as a failed save sends the user
// back to re-do a write that already happened.
val line = profileStatusLine(
listOf(
ProfilePushOutcome("Bob"),
ProfilePushOutcome("Ann", "connect failed"),
),
)
assertTrue(line.startsWith("profile saved"))
assertTrue(line.contains("sent to 1 of 2 friends"))
assertTrue(line.contains("failed: Ann: connect failed"))
}
@Test
fun every_failure_is_listed_by_name() {
val line = profileStatusLine(
listOf(
ProfilePushOutcome("Bob", "connect failed"),
ProfilePushOutcome("654c4a…aa99", "friend missing prekey"),
),
)
assertTrue(line.contains("sent to 0 of 2 friends"))
assertTrue(line.contains("Bob: connect failed"))
assertTrue(line.contains("654c4a…aa99: friend missing prekey"))
}
// --- the empty-address consequence, on screen -----------------------------
@Test
fun an_empty_address_says_nobody_can_pay() {
val text = profileAddressNotice("")
assertTrue(text.contains("clears the profile address"))
// The consequence, not the process name: the copy no longer says
// "wallet child" anywhere a user can read it.
assertTrue(text.contains("running wallet"))
assertTrue(text.contains("nobody can send you an invoice"))
}
@Test
fun a_filled_address_says_it_is_validated_before_the_write() {
val text = profileAddressNotice(loaded.address)
assertTrue(text.contains("Validated"))
assertTrue(text.contains("refused"))
}
}

View file

@ -0,0 +1,84 @@
package com.siriusdevops.onionwire.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* `shortId`, the roster's collapsed identity line, on the JVM.
*
* The collapsed card shows the fingerprint through this function, and the
* expanded one shows the raw value; the two must never disagree about what the
* fingerprint *is*, so the abbreviation has to be a pure slice of the input
* with nothing invented. Pure logic, no Robolectric — same shape as
* `SeedBackupGateTest` and `WalletChildStatusTextTest`.
*/
class RosterIdTest {
/** An ed25519 pubkey as the core prints it: 64 lowercase hex characters. */
private val fingerprint =
"9f2c41ab77de03b5c8e1f0a6d4b39c2e5a7f81c0d3e6b492af17c5d80e3b6a49"
// --- the long case -------------------------------------------------------
@Test
fun a_long_fingerprint_becomes_head_ellipsis_tail() {
assertEquals("9f2c41…6a49", shortId(fingerprint))
}
@Test
fun the_abbreviation_is_a_slice_of_the_input_not_a_re_encoding() {
// The head and the tail must be literally the input's own characters:
// a summary that cannot be checked against the full value is worse than
// no summary.
val short = shortId(fingerprint)
assertEquals(fingerprint.take(6), short.substringBefore("…"))
assertEquals(fingerprint.takeLast(4), short.substringAfter("…"))
// Nothing invented to pad the middle: 6 + "…" + 4.
assertEquals(11, short.length)
}
@Test
fun head_and_tail_are_call_sites_choice() {
assertEquals("9f2c…6a49", shortId(fingerprint, head = 4, tail = 4))
assertEquals("9f2c41ab77…3b6a49", shortId(fingerprint, head = 10, tail = 6))
}
// --- the short case ------------------------------------------------------
@Test
fun a_string_shorter_than_head_tail_plus_one_is_returned_unchanged() {
// head + tail + 1 == 11 here, so anything of 10 characters or fewer has
// no middle worth hiding.
assertEquals("abcdefghij", shortId("abcdefghij"))
assertEquals("abc", shortId("abc"))
assertEquals("a", shortId("a"))
}
@Test
fun the_first_length_that_abbreviates_is_head_tail_plus_one() {
// The boundary, both sides: 10 unchanged, 11 abbreviated to the same
// length with the middle character collapsed.
assertEquals("abcdefghij", shortId("abcdefghij"))
assertEquals("abcdef…hijk", shortId("abcdefghijk"))
}
// --- the empty case ------------------------------------------------------
@Test
fun an_empty_string_stays_empty() {
// `ready.fingerprint` is always populated in practice, but the function
// must not turn "nothing" into "…" on a card that is already on screen.
assertEquals("", shortId(""))
}
// --- the shape the card relies on ---------------------------------------
@Test
fun the_ellipsis_is_the_single_character_one() {
// U+2026, not three dots: the collapsed line is monospace and a
// three-dot tail is four cells where the design budgeted one.
assertTrue(shortId(fingerprint).contains("\u2026"))
assertEquals(1, shortId(fingerprint).count { it == '\u2026' })
}
}

View file

@ -0,0 +1,45 @@
package com.siriusdevops.onionwire.ui
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* `shortOnion`, the roster's locator abbreviation, on the JVM.
*
* A v3 onion locator must never be soft-wrapped or reduced to a middle slice
* that hides `.onion`: the suffix is what tells a reader this is an onion
* address at all, and the full value is available on the profile and invite
* screens. Pure logic, no Robolectric — same shape as `RosterIdTest`.
*/
class RosterOnionTest {
private val v3 =
"abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwxyz234567.onion"
@Test
fun a_v3_locator_keeps_its_suffix() {
val short = shortOnion(v3)
assertEquals(true, short.endsWith(".onion"))
assertEquals(v3.take(10), short.substringBefore("\u2026"))
assertEquals(v3.removeSuffix(".onion").takeLast(6), short.removeSuffix(".onion").substringAfter("\u2026"))
}
@Test
fun the_suffix_is_never_the_part_that_is_cut() {
// Even with an aggressive abbreviation the reader still sees `….onion`.
val body = v3.removeSuffix(".onion")
val short = shortOnion(v3, head = 3, tail = 2)
assertEquals(body.take(3) + "\u2026" + body.takeLast(2) + ".onion", short)
}
@Test
fun a_short_value_is_returned_unchanged() {
assertEquals("abc.onion", shortOnion("abc.onion"))
assertEquals("", shortOnion(""))
}
@Test
fun a_value_with_no_suffix_is_not_mangled() {
assertEquals("not-an-onion", shortOnion("not-an-onion"))
}
}

View file

@ -0,0 +1,176 @@
package com.siriusdevops.onionwire.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The seed-backup gate's rules, on the JVM.
*
* These are the decisions the wallet screen renders from: whether the created
* seed card is still blocking, whether the persistent warning is up, and
* whether the receive address is on screen at all. Pure logic, so no
* Robolectric and no Compose test dependency — same shape as
* `WalletChildStatusTextTest` and `OutboxDetailTest`.
*/
class SeedBackupGateTest {
/** A wallet the child can actually read: `wallet_balance` returned a value. */
private val readable = true
/** `wallet_balance` said "off" (no chain source) or "err" (nothing open). */
private val notReadable = false
// --- the confirm word is the TUI's word ---------------------------------
@Test
fun the_confirm_word_is_the_tui_word() {
// `src/tui.rs` `WalletSetup::CreateSeed` compares against "SEEN". A
// second convention here would be a different gate than the TUI's.
assertEquals("SEEN", SeedBackupGate.CONFIRM_WORD)
}
@Test
fun a_correct_word_releases_the_block_whatever_its_case_or_padding() {
assertTrue(SeedBackupGate.accepts("SEEN"))
// The TUI compares with `eq_ignore_ascii_case`.
assertTrue(SeedBackupGate.accepts("seen"))
assertTrue(SeedBackupGate.accepts("SeEn"))
// A soft keyboard auto-capitalises and a paste can carry whitespace.
assertTrue(SeedBackupGate.accepts(" seen "))
}
@Test
fun a_blank_or_wrong_word_stays_blocked() {
assertFalse(SeedBackupGate.accepts(""))
assertFalse(SeedBackupGate.accepts(" "))
assertFalse(SeedBackupGate.accepts("SEE"))
// A prefix is not the word: the TUI only fires on the whole match.
assertFalse(SeedBackupGate.accepts("SEENN"))
assertFalse(SeedBackupGate.accepts("seen."))
// The other word in this flow is the spend-authority one.
assertFalse(SeedBackupGate.accepts("SPEND"))
}
@Test
fun done_is_dead_until_the_word_is_right() {
assertFalse(SeedBackupGate.confirmEnabled(""))
assertFalse(SeedBackupGate.confirmEnabled("SEENN"))
assertTrue(SeedBackupGate.confirmEnabled("SEEN"))
assertTrue(SeedBackupGate.confirmEnabled("seen"))
}
// --- the state transitions ----------------------------------------------
@Test
fun a_create_starts_unbacked() {
assertFalse(SeedBackupGate.afterWallet(WalletKeyOrigin.Created))
}
@Test
fun an_import_is_backed_up_without_the_gate() {
// The user pasted the seed to get here, so there is nothing to confirm.
assertTrue(SeedBackupGate.afterWallet(WalletKeyOrigin.Imported))
}
@Test
fun a_successful_confirm_marks_the_wallet_backed_up() {
val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created)
assertTrue(SeedBackupGate.afterConfirm("SEEN", created))
}
@Test
fun a_wrong_word_leaves_an_unbacked_wallet_unbacked() {
assertFalse(SeedBackupGate.afterConfirm("", false))
assertFalse(SeedBackupGate.afterConfirm("nope", false))
}
@Test
fun a_wrong_word_cannot_un_confirm_a_backed_up_wallet() {
// Done is disabled for a wrong word, but the flag must not be a way to
// walk a confirmed wallet back into the hidden-address state.
assertTrue(SeedBackupGate.afterConfirm("", true))
assertTrue(SeedBackupGate.afterConfirm("SPEND", true))
}
@Test
fun a_new_create_resets_a_confirmed_wallet_to_unbacked() {
// Create -> confirm -> create again: the second wallet file has its own
// seed, and nobody has read it yet.
val first =
SeedBackupGate.afterConfirm("SEEN", SeedBackupGate.afterWallet(WalletKeyOrigin.Created))
assertTrue(first)
assertFalse(SeedBackupGate.afterWallet(WalletKeyOrigin.Created))
}
// --- what the screen does with the flag ---------------------------------
@Test
fun a_created_wallet_keeps_the_strip_up_until_the_word_is_typed() {
val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created)
assertTrue(SeedBackupGate.warningVisible(created, readable))
val confirmed = SeedBackupGate.afterConfirm("seen", created)
assertFalse(SeedBackupGate.warningVisible(confirmed, readable))
}
@Test
fun an_imported_wallet_never_shows_the_strip() {
val backedUp = SeedBackupGate.afterWallet(WalletKeyOrigin.Imported)
assertFalse(SeedBackupGate.warningVisible(backedUp, readable))
assertFalse(SeedBackupGate.warningVisible(backedUp, notReadable))
}
@Test
fun a_created_wallet_keeps_the_strip_up_even_before_its_balance_reads() {
// A create is proof a wallet exists, so a child that has not answered
// yet must not be read as "no wallet to warn about".
assertTrue(SeedBackupGate.warningVisible(false, notReadable))
}
@Test
fun the_receive_address_is_hidden_while_the_seed_is_unconfirmed() {
assertFalse(SeedBackupGate.receiveAddressVisible(false, readable))
assertTrue(SeedBackupGate.receiveAddressVisible(true, readable))
}
@Test
fun a_created_wallet_hides_its_receive_address_until_the_word_is_typed() {
val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created)
assertFalse(SeedBackupGate.receiveAddressVisible(created, readable))
val confirmed = SeedBackupGate.afterConfirm("seen", created)
assertTrue(SeedBackupGate.receiveAddressVisible(confirmed, readable))
}
@Test
fun an_install_that_never_created_a_wallet_here_waits_for_a_readable_wallet() {
// `null` is "nothing stored": an install that predates the flag, or one
// that has only configured a chain source. `wallet_balance` returns
// "err" for a configured chain whose child has no wallet open, and a
// first-run user is in exactly that state — nagging them about a seed
// they do not have is the false positive this rule exists to prevent.
assertFalse(SeedBackupGate.warningVisible(null, notReadable))
assertTrue(SeedBackupGate.receiveAddressVisible(null, notReadable))
}
@Test
fun an_unconfirmed_wallet_that_predates_the_flag_is_warned_about_once_it_reads() {
// The user this gate is for: they created a wallet on an older build,
// so nothing is stored, but the child can read the wallet. That is a
// real wallet whose seed nobody has confirmed.
assertTrue(SeedBackupGate.warningVisible(null, readable))
assertFalse(SeedBackupGate.receiveAddressVisible(null, readable))
}
@Test
fun the_strip_says_why_the_address_is_gone() {
// The hiding is only fair if the strip names it; assert the strip is
// not empty and actually mentions the seed and the receive address.
val text = SeedBackupGate.WARNING
assertTrue(text.contains("seed"))
assertTrue(text.contains("receive address"))
assertTrue(text.contains("recovered"))
}
}

View file

@ -0,0 +1,39 @@
package com.siriusdevops.onionwire.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
/**
* IME Done and the Open button must share one submit: the keyboard's action
* key used to dismiss the IME and never call unlock, so bootstrap never
* started. Empty stays a no-op (the SDK would fail closed; we never open).
*/
class UnlockSubmitTest {
@Test
fun empty_passphrase_does_not_submit() {
assertNull(unlockSubmit("", remember = true))
assertNull(unlockSubmit("", remember = false))
}
@Test
fun typed_passphrase_is_handed_over_with_the_remember_flag() {
assertEquals(
UnlockSubmit(passphrase = "correct horse", remember = true),
unlockSubmit("correct horse", remember = true),
)
assertEquals(
UnlockSubmit(passphrase = "correct horse", remember = false),
unlockSubmit("correct horse", remember = false),
)
}
@Test
fun interior_spaces_are_part_of_the_passphrase_not_trimmed() {
assertEquals(
UnlockSubmit(passphrase = " lead", remember = false),
unlockSubmit(" lead", remember = false),
)
}
}

View file

@ -0,0 +1,760 @@
package com.siriusdevops.onionwire.ui
import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE
import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The wallet-child status line the screen renders from
* `Wire::wallet_status()`.
*
* These assert the pure model — the same shape as `MessageDeliveryTest` and
* `OutboxDetailTest` — so the rules that matter are covered on the JVM without
* a device: every core state has its own word, a died child never reads as
* `off` and never as `ready`, an unknown state is never `ready`, and Start is
* only offered when there is something to spawn.
*/
class WalletChildStatusTextTest {
private fun input(
state: String,
running: Boolean = false,
configured: Boolean = true,
chainSource: String = "remote daemon",
chainInProcess: Boolean = false,
nodeAvailable: Boolean = true,
nodeState: String = "",
height: ULong = 0uL,
targetHeight: ULong = 0uL,
lastError: String? = null,
) = WalletChildInput(
state = state,
running = running,
configured = configured,
chainSource = chainSource,
chainInProcess = chainInProcess,
nodeAvailable = nodeAvailable,
nodeState = nodeState,
height = height,
targetHeight = targetHeight,
lastError = lastError,
)
private val bundled = WalletChildBinaryPaths(walletRpc = "/lib/libmonerowalletrpc.so", arti = null)
private val noBinary = WalletChildBinaryPaths(walletRpc = null, arti = null)
// --- every core state has its own word ---------------------------------
@Test
fun each_core_state_maps_to_its_own_phase() {
assertTrue(walletChildPhase(input("off")) is WalletChildPhase.Off)
assertTrue(walletChildPhase(input("connecting")) is WalletChildPhase.Connecting)
assertTrue(walletChildPhase(input("syncing")) is WalletChildPhase.Syncing)
assertTrue(walletChildPhase(input("ready")) is WalletChildPhase.Ready)
assertTrue(walletChildPhase(input("exited")) is WalletChildPhase.Exited)
}
@Test
fun nothing_read_yet_is_not_off() {
val phase = walletChildPhase(null)
assertTrue(phase is WalletChildPhase.Unread)
assertEquals("reading…", phase.label)
}
@Test
fun state_matching_tolerates_case_and_padding() {
assertTrue(walletChildPhase(input(" READY ")) is WalletChildPhase.Ready)
assertTrue(walletChildPhase(input("Exited")) is WalletChildPhase.Exited)
}
// --- a died child is never "off" and never "ready" ---------------------
@Test
fun exited_is_its_own_state_and_never_off_or_ready() {
val phase = walletChildPhase(input("exited", lastError = "spawn monero-wallet-rpc: No such file"))
assertTrue(phase is WalletChildPhase.Exited)
assertTrue("a died child is dead", phase.dead)
assertFalse("a died child is not off", phase is WalletChildPhase.Off)
assertFalse("a died child is not ready", phase is WalletChildPhase.Ready)
assertFalse("a died child is not live", phase.live)
}
@Test
fun exited_keeps_the_cores_reason() {
val phase = walletChildPhase(input("exited", lastError = "child exited with status 1"))
assertEquals("child exited with status 1", (phase as WalletChildPhase.Exited).reason)
}
// --- an unknown state is never ready -----------------------------------
@Test
fun an_unknown_state_is_never_ready() {
val phase = walletChildPhase(input("wobbling"))
assertTrue(phase is WalletChildPhase.Unrecognised)
assertFalse("an unknown state must not read as ready", phase is WalletChildPhase.Ready)
assertTrue(phase.label.startsWith("unknown"))
}
@Test
fun an_unknown_state_word_is_cut_and_sanitized() {
val raw = "wobbling\u0000\u0007" + "x".repeat(80)
val phase = walletChildPhase(input(raw)) as WalletChildPhase.Unrecognised
assertFalse("controls must not reach the screen", phase.label.contains('\u0000'))
assertTrue("the word is capped", phase.label.length < raw.length)
}
// --- the status line names the chain source ----------------------------
@Test
fun the_line_names_the_chain_source_the_core_reported() {
assertEquals("off · receive-only", walletChildLine(input("off", chainSource = "receive-only")))
assertEquals(
"ready · remote onion daemon",
walletChildLine(input("ready", running = true, chainSource = "remote onion daemon")),
)
assertEquals(
"connecting · local node",
walletChildLine(input("connecting", running = true, chainSource = "local node")),
)
}
@Test
fun the_line_says_when_there_is_no_chain_source() {
assertEquals("off · no chain source", walletChildLine(input("off", chainSource = " ")))
}
@Test
fun the_line_carries_the_cores_failure_text() {
val line = walletChildLine(
input("off", lastError = "spawn monero-wallet-rpc: Permission denied"),
)
assertTrue(line, line.contains("Permission denied"))
assertTrue("the state word survives", line.startsWith("off · "))
}
@Test
fun an_exited_child_with_no_reason_still_says_it_is_gone() {
val line = walletChildLine(input("exited", lastError = null))
assertTrue(line, line.contains("gone"))
}
@Test
fun a_long_failure_text_is_cut_like_a_chat_row() {
val line = walletChildLine(input("off", lastError = "a: b: " + "y".repeat(400)))
assertTrue(line, line.length < 120)
}
// --- Start is only offered when there is something to spawn ------------
@Test
fun start_is_blocked_when_the_build_carries_no_binary() {
val why = startBlockedReason(noBinary, input("off"))
assertEquals(NO_WALLET_RPC_MESSAGE, why)
}
@Test
fun start_is_blocked_before_the_first_read() {
assertEquals(READING_CHILD_NOTICE, startBlockedReason(bundled, null))
}
@Test
fun start_is_blocked_with_no_chain_source() {
val why = startBlockedReason(bundled, input("off", configured = false, chainSource = "receive-only"))
assertNotNull(why)
assertTrue(why!!, why.contains("chain source"))
}
@Test
fun start_is_blocked_while_the_child_is_already_running() {
val why = startBlockedReason(bundled, input("ready", running = true))
assertNotNull(why)
assertTrue(why!!, why.contains("already running"))
}
@Test
fun start_is_blocked_for_an_onion_daemon_without_the_socks_child() {
val why = startBlockedReason(bundled, input("off"), onionDaemon = true)
assertEquals(ONION_NEEDS_ARTI_NOTICE, why)
}
@Test
fun start_is_allowed_for_a_clearnet_daemon_with_the_binary_present() {
assertNull(startBlockedReason(bundled, input("off")))
}
@Test
fun start_is_blocked_while_start_is_in_flight() {
assertEquals(
STARTING_CHILD_NOTICE,
startBlockedReason(bundled, input("off"), starting = true),
)
}
@Test
fun start_is_allowed_again_after_the_child_exited() {
assertNull(
"a died child must be restartable",
startBlockedReason(bundled, input("exited", lastError = "child exited with status 1")),
)
}
// --- Stop ---------------------------------------------------------------
@Test
fun stop_is_blocked_when_nothing_is_running() {
assertTrue(stopBlockedReason(input("off"))!!.contains("No wallet is running"))
assertTrue(stopBlockedReason(input("exited"))!!.contains("No wallet is running"))
assertEquals(READING_CHILD_NOTICE, stopBlockedReason(null))
}
@Test
fun stop_is_allowed_while_a_child_is_up() {
assertNull(stopBlockedReason(input("connecting", running = true)))
assertNull(stopBlockedReason(input("syncing", running = true)))
assertNull(stopBlockedReason(input("ready", running = true)))
}
// --- onion detection mirrors the core ----------------------------------
@Test
fun onion_detection_matches_the_cores_rule() {
assertTrue(isOnionHost("abcdefghijklmnop.onion"))
assertTrue(isOnionHost("ABCDEFGH.ONION"))
assertTrue(isOnionHost(" abcdefgh.onion "))
assertFalse(isOnionHost("onion.example.com"))
assertFalse(isOnionHost("127.0.0.1"))
assertFalse(isOnionHost("node.onion.example.com"))
}
// --- the daemon address field ------------------------------------------
@Test
fun daemon_address_parses_host_and_port() {
assertEquals(DaemonAddress("127.0.0.1", 18089), parseDaemonAddress("127.0.0.1:18089"))
assertEquals(DaemonAddress("abc.onion", 18081), parseDaemonAddress(" abc.onion:18081 "))
assertEquals(DaemonAddress("node.example.com", 18089), parseDaemonAddress("node.example.com:18089"))
assertEquals(DaemonAddress("::1", 18089), parseDaemonAddress("[::1]:18089"))
}
@Test
fun daemon_address_rejects_what_it_cannot_split_honestly() {
assertNull(parseDaemonAddress(""))
assertNull(parseDaemonAddress("node.example.com"))
assertNull(parseDaemonAddress(":18089"))
assertNull(parseDaemonAddress("node.example.com:"))
assertNull(parseDaemonAddress("node.example.com:0"))
assertNull(parseDaemonAddress("node.example.com:70000"))
assertNull(parseDaemonAddress("node.example.com:eight"))
assertNull("a bare IPv6 has no unambiguous split", parseDaemonAddress("::1:18089"))
}
@Test
fun daemon_address_round_trips_through_its_text_form() {
val parsed = parseDaemonAddress("127.0.0.1:18089")!!
assertEquals("127.0.0.1:18089", parsed.text)
}
// --- the on-device node (Cuprate) ---------------------------------------
private fun node(
state: String = "syncing",
chainSource: String = "in-process node",
nodeState: String,
nodeAvailable: Boolean = true,
running: Boolean = true,
height: ULong = 0uL,
targetHeight: ULong = 0uL,
) = input(
state = state,
running = running,
chainSource = chainSource,
chainInProcess = true,
nodeAvailable = nodeAvailable,
nodeState = nodeState,
height = height,
targetHeight = targetHeight,
)
@Test
fun each_core_node_state_maps_to_its_own_phase() {
assertTrue(nodePhase(node(nodeState = "off")) is NodePhase.Off)
assertTrue(nodePhase(node(nodeState = "starting")) is NodePhase.Starting)
assertTrue(nodePhase(node(nodeState = "syncing")) is NodePhase.Syncing)
assertTrue(nodePhase(node(nodeState = "ready")) is NodePhase.Ready)
assertTrue(nodePhase(node(nodeState = "exited")) is NodePhase.Exited)
}
@Test
fun only_an_in_process_source_has_a_node_segment() {
assertTrue(nodePhase(input("ready", running = true)) is NodePhase.Absent)
assertTrue(nodePhase(null) is NodePhase.Absent)
// In-process, but the core has not reported a node word yet: no segment,
// rather than an invented one.
assertTrue(nodePhase(node(nodeState = "")) is NodePhase.Absent)
}
@Test
fun an_unknown_node_state_is_never_ready() {
val phase = nodePhase(node(nodeState = "mining"))
assertTrue(phase is NodePhase.Unrecognised)
assertFalse("an unknown node word must not read as ready", phase is NodePhase.Ready)
assertTrue(phase.label.startsWith("unknown"))
}
@Test
fun the_line_grows_a_node_segment_for_the_in_process_source() {
assertEquals(
"syncing · in-process node · node syncing",
walletChildLine(node(state = "syncing", nodeState = "syncing")),
)
assertEquals(
"ready · in-process node · node ready",
walletChildLine(node(state = "ready", nodeState = "ready")),
)
}
@Test
fun the_line_has_no_node_segment_for_the_other_sources() {
assertFalse(walletChildLine(input("ready", running = true)).contains("node "))
assertFalse(walletChildLine(input("off", chainSource = "receive-only")).contains("node "))
}
// --- the daemon's sync height on the line --------------------------------
@Test
fun no_sync_segment_when_the_daemon_reported_nothing() {
// `0/0` is unknown — the probe failed or the daemon is not up — so the
// line says nothing rather than printing a number it does not have.
val line = walletChildLine(input("off", chainSource = "receive-only"))
assertEquals("off · receive-only", line)
// The `sync` *segment*, not the substring: `syncing` is a phase word.
assertFalse("no height is not a height of zero", line.contains(" · sync "))
assertFalse(
walletChildLine(node(nodeState = "starting")).contains(" · sync "),
)
}
@Test
fun the_line_carries_the_daemons_height_and_target() {
assertEquals(
"connecting · in-process mainnet pruned · node starting · sync 1160/3090939",
walletChildLine(
node(
state = "connecting",
chainSource = "in-process mainnet pruned",
nodeState = "starting",
height = 1160uL,
targetHeight = 3_090_939uL,
),
),
)
}
@Test
fun a_zero_target_still_prints_as_zero_and_never_as_a_percent() {
val line = walletChildLine(
node(
state = "syncing",
chainSource = "in-process mainnet pruned",
nodeState = "syncing",
height = 4549uL,
targetHeight = 0uL,
),
)
assertEquals(
"syncing · in-process mainnet pruned · node syncing · sync 4549/0",
line,
)
assertFalse("no percent is invented", line.contains("%"))
}
@Test
fun the_height_sits_before_the_failure_text() {
val line = walletChildLine(
input("off", height = 7uL, lastError = "spawn monero-wallet-rpc: Permission denied"),
)
assertTrue(line, line.startsWith("off · remote daemon · sync 7/0 — "))
assertTrue(line, line.contains("Permission denied"))
}
@Test
fun the_spoken_row_says_the_same_height_the_eye_reads() {
val input = node(
state = "connecting",
chainSource = "in-process mainnet pruned",
nodeState = "starting",
height = 1160uL,
targetHeight = 3_090_939uL,
)
val spoken = walletChildStatusDescription(input)
assertTrue(spoken, spoken.contains("sync 1160/3090939"))
assertTrue(
"a screen reader is told the same as the eye",
spoken.endsWith(walletChildLine(input)),
)
assertTrue("it is still a sentence", spoken.startsWith("The wallet is starting"))
}
@Test
fun start_is_blocked_when_the_build_has_no_in_process_daemon() {
val why = startBlockedReason(
bundled,
node(state = "off", nodeState = "off", nodeAvailable = false, running = false),
)
assertEquals(CUPRATE_NOT_IN_BUILD_NOTICE, why)
assertNull(
"a build that carries the daemon is not blocked",
startBlockedReason(
bundled,
node(state = "off", nodeState = "off", nodeAvailable = true, running = false),
),
)
}
@Test
fun the_on_device_banner_is_titled_and_says_what_it_costs() {
// The banner's title is the plan's exact string; the body keeps every
// honesty bound the old single-sentence warning carried.
assertEquals("Experimental On-Device Node (Cuprate)", CUPRATE_ON_DEVICE_TITLE)
val body = CUPRATE_ON_DEVICE_BODY
assertTrue("it names the software", body.contains("Cuprate"))
assertTrue("it names the parity gap", body.contains("#278"))
assertTrue("it quotes the user book", body.contains("do NOT use cuprated"))
assertTrue("it says mainnet is unvalidated", body.contains("Mainnet is unvalidated"))
assertTrue("it says not to hold funds", body.contains("Do not use for significant funds"))
assertTrue("it is a sentence, not a glyph", body.trim().endsWith("."))
}
// --- storage honesty ----------------------------------------------------
@Test
fun storage_is_blocked_when_free_space_is_unreadable() {
assertTrue(chainStorageBlockedReason(null)!!.contains("could not be read"))
}
@Test
fun storage_is_blocked_below_the_floor() {
val why = chainStorageBlockedReason(CHAIN_FREE_SPACE_FLOOR_BYTES - 1)
assertNotNull(why)
assertTrue(why!!, why.contains("Not enough space"))
assertTrue("the number is on screen", why.contains("3.0 GiB"))
}
@Test
fun storage_is_allowed_at_and_above_the_floor() {
assertNull(chainStorageBlockedReason(CHAIN_FREE_SPACE_FLOOR_BYTES))
assertNull(chainStorageBlockedReason(64L * 1024 * 1024 * 1024))
}
@Test
fun mainnet_pruned_needs_more_than_testnet() {
val forty = 40L * 1024 * 1024 * 1024
assertNull(chainStorageBlockedReason(forty, mainnet = false, prune = false))
val why = chainStorageBlockedReason(forty, mainnet = true, prune = true)
assertNotNull(why)
assertTrue(why!!, why.contains("64.0 GiB"))
assertNull(
chainStorageBlockedReason(
CHAIN_MAINNET_PRUNED_FLOOR_BYTES,
mainnet = true,
prune = true,
),
)
}
@Test
fun mainnet_full_needs_more_than_pruned() {
val why = chainStorageBlockedReason(
CHAIN_MAINNET_PRUNED_FLOOR_BYTES,
mainnet = true,
prune = false,
)
assertNotNull(why)
assertTrue(why!!, why.contains("280.0 GiB"))
}
@Test
fun selecting_pruned_highlights_that_mode() {
assertEquals(
CuprateMode.MainnetPruned,
selectedCuprateMode(inProcess = true, mainnet = true, prune = true),
)
assertEquals(
CuprateMode.MainnetFull,
selectedCuprateMode(inProcess = true, mainnet = true, prune = false),
)
assertEquals(
CuprateMode.Testnet,
selectedCuprateMode(inProcess = true, mainnet = false, prune = false),
)
assertNull(selectedCuprateMode(inProcess = false, mainnet = true, prune = true))
}
@Test
fun selecting_a_mode_starts_unless_storage_or_an_in_flight_start_blocks_it() {
assertTrue(shouldStartAfterSelectingChain(storageBlocked = null, starting = false))
assertFalse(
shouldStartAfterSelectingChain(storageBlocked = "Not enough space", starting = false),
)
assertFalse(shouldStartAfterSelectingChain(storageBlocked = null, starting = true))
}
@Test
fun the_storage_line_reports_the_measured_number() {
val line = chainStorageLine(41L * 1024 * 1024 * 1024)
assertTrue(line, line.contains("41.0 GiB"))
assertTrue("it says what the number is not", line.contains("no size estimate"))
assertTrue(
"an unreadable filesystem says so",
chainStorageLine(null).contains("could not be read"),
)
}
@Test
fun bytes_are_formatted_in_binary_units() {
assertEquals("512 B", formatBytes(512))
assertEquals("2 MiB", formatBytes(2L * 1024 * 1024))
assertEquals("1.5 GiB", formatBytes(3L * 1024 * 1024 * 1024 / 2))
assertEquals("3.0 GiB", formatBytes(CHAIN_FREE_SPACE_FLOOR_BYTES))
}
// --- the node card's progress header (plan P4.3) -------------------------
@Test
fun block_counts_group_by_three_regardless_of_locale() {
assertEquals("0", formatBlockCount(0uL))
assertEquals("999", formatBlockCount(999uL))
assertEquals("1,000", formatBlockCount(1_000uL))
assertEquals("485,253", formatBlockCount(485_253uL))
assertEquals("3,794,383", formatBlockCount(3_794_383uL))
assertEquals("12,345,678", formatBlockCount(12_345_678uL))
}
@Test
fun the_progress_header_says_percent_and_formatted_blocks() {
val p = syncProgress(485_253uL, 3_794_383uL)
assertEquals("12.8%", p.percentText)
assertEquals("Block 485,253 of 3,794,383", p.blockText)
assertTrue("a fraction of the track", p.fraction > 0.12f && p.fraction < 0.13f)
}
@Test
fun a_caught_up_node_fills_the_track_and_does_not_overflow() {
val atTip = syncProgress(3_794_383uL, 3_794_383uL)
assertEquals("100.0%", atTip.percentText)
assertEquals(1f, atTip.fraction)
// A daemon one block ahead of the target it reported must not render
// 108% — the bar clamps and the text is the clamped number.
val ahead = syncProgress(4_100_000uL, 3_794_383uL)
assertEquals("100.0%", ahead.percentText)
assertEquals(1f, ahead.fraction)
}
@Test
fun an_unknown_target_is_never_a_percentage() {
// `target_height == 0` is "the daemon reported no target" — Cuprate
// omits it even at the tip. Printing 100% there would claim synced.
val p = syncProgress(4_549uL, 0uL)
assertNull("no percent from a zero target", p.percentText)
assertEquals(0f, p.fraction)
assertEquals("Block 4,549 of an unknown target", p.blockText)
assertFalse("no percent string leaks", p.blockText!!.contains("%"))
}
@Test
fun no_numbers_means_no_progress_row() {
val p = syncProgress(0uL, 0uL)
assertNull(p.percentText)
assertNull(p.blockText)
assertEquals(0f, p.fraction)
}
@Test
fun the_three_modes_are_named_the_way_the_stored_choice_reads() {
assertEquals("Mainnet Pruned", chainModeLabel(mainnet = true, prune = true))
assertEquals("Mainnet Full", chainModeLabel(mainnet = true, prune = false))
assertEquals("Testnet", chainModeLabel(mainnet = false, prune = false))
}
@Test
fun the_node_header_never_reads_ready_without_the_cores_word() {
assertEquals("Wallet Offline", nodeStatusHead(input("off", configured = false)).title)
assertEquals("Connecting…", nodeStatusHead(input("connecting", running = true)).title)
assertEquals(NodeStatusTone.Busy, nodeStatusHead(input("connecting", running = true)).tone)
assertTrue(
"a running child that has not answered is not ready",
nodeStatusHead(input("connecting", running = true)).tone != NodeStatusTone.Good,
)
assertEquals(NodeStatusTone.Good, nodeStatusHead(input("ready", running = true)).tone)
assertEquals(NodeStatusTone.Bad, nodeStatusHead(input("mining", running = true)).tone)
assertEquals(
"an unknown state is never green",
NodeStatusTone.Bad,
nodeStatusHead(input("mining", running = true)).tone,
)
assertEquals("Wallet Stopped", nodeStatusHead(input("exited")).title)
assertEquals("Reading wallet status", nodeStatusHead(null).title)
}
@Test
fun the_node_header_names_the_mode_only_for_the_on_device_node() {
assertEquals(
"Syncing Node (Mainnet Pruned)",
nodeStatusHead(
node(state = "syncing", chainSource = "in-process mainnet pruned", nodeState = "syncing"),
inProcess = true,
mainnet = true,
prune = true,
).title,
)
assertEquals(
"Node Idle (Testnet)",
nodeStatusHead(input("off", configured = false), inProcess = true, mainnet = false).title,
)
assertEquals(
"Syncing Wallet",
nodeStatusHead(input("syncing", running = true, chainSource = "remote daemon")).title,
)
}
// --- the stored wallet binary: heal before spawn, then gate on it -------
private val hostsBundled = "/data/app/~~abc/onionwire-1/lib/arm64/libmonerowalletrpc.so"
@Test
fun a_stored_bare_name_is_repaired_to_the_bundled_absolute_path() {
// A record written by an older install: a bare name nothing in an APK
// sandbox resolves on PATH. The repair is the absolute path this
// install actually carries.
assertEquals(hostsBundled, walletBinHealPath("monero-wallet-rpc", hostsBundled) { false })
assertEquals("an empty stored bin is healed too", hostsBundled, walletBinHealPath("", hostsBundled) { false })
assertEquals("and a missing field", hostsBundled, walletBinHealPath(null, hostsBundled) { false })
}
@Test
fun a_stored_path_that_actually_runs_is_never_overwritten() {
val userBin = "/data/user/0/com.siriusdevops.onionwire/files/monero-wallet-rpc"
assertNull(
"a real executable file the user pointed at is left alone",
walletBinHealPath(userBin, hostsBundled) { it == userBin },
)
assertNull(
"a bundled path already stored needs no write",
walletBinHealPath(hostsBundled, hostsBundled) { it == hostsBundled },
)
}
@Test
fun no_bundled_binary_means_there_is_nothing_to_repair_with() {
assertNull(walletBinHealPath("monero-wallet-rpc", null) { false })
assertNull(walletBinHealPath("monero-wallet-rpc", " ") { false })
}
@Test
fun a_stored_bin_missing_on_the_device_blocks_start_and_names_the_path() {
val why = startGateReason(bundled, input("off"), "monero-wallet-rpc") { false }
assertNotNull("a stored path that cannot run must block Start", why)
assertTrue("the reason names the stored path it is about", why!!.contains("monero-wallet-rpc"))
assertTrue("and the path this build does carry", why.contains(bundled.walletRpc!!))
assertTrue("and says it cannot run", why.contains("cannot be run"))
assertFalse(
"a gate that refuses never lets a mode tap auto-start",
shouldStartAfterSelectingChain(storageBlocked = null, starting = false, startBlocked = why),
)
}
@Test
fun an_absent_resolved_bin_blocks_with_the_resolved_absence_message() {
// Nothing in this build to spawn: the established string, unchanged.
val why = startGateReason(noBinary, input("off"), "/stale/libmonerowalletrpc.so") { false }
assertEquals(NO_WALLET_RPC_MESSAGE, why)
assertFalse(shouldStartAfterSelectingChain(null, false, why))
}
@Test
fun a_runnable_stored_bin_passes_the_gate() {
assertNull(startGateReason(bundled, input("off"), bundled.walletRpc) { it == bundled.walletRpc })
assertNull(storedWalletBinBlockedReason(bundled.walletRpc, bundled.walletRpc) { true })
}
@Test
fun the_gate_keeps_the_established_start_ordering() {
// Reading the status still wins over a stored-path complaint: the
// existing copy and its order were not rewritten to make room.
assertEquals(READING_CHILD_NOTICE, startGateReason(bundled, null, null) { false })
assertEquals(
NO_CHAIN_SOURCE_NOTICE,
startGateReason(bundled, input("off", configured = false, chainSource = "receive-only"), null) { false },
)
}
@Test
fun a_mode_tap_stores_the_source_but_cannot_auto_start_what_the_gate_refuses() {
assertTrue(shouldStartAfterSelectingChain(storageBlocked = null, starting = false))
assertTrue(
shouldStartAfterSelectingChain(storageBlocked = null, starting = false, startBlocked = null),
)
assertFalse(
shouldStartAfterSelectingChain(
storageBlocked = null,
starting = false,
startBlocked = "The stored wallet binary cannot be run on this device: …",
),
)
}
@Test
fun create_and_import_are_blocked_without_a_running_child() {
assertEquals(WALLET_SETUP_NEEDS_CHILD, walletSetupBlockedReason(input("off")))
assertEquals(WALLET_SETUP_NEEDS_CHILD, walletSetupBlockedReason(input("exited", lastError = "spawn …")))
assertEquals(WALLET_SETUP_NEEDS_CHILD, walletSetupBlockedReason(input("mining")))
assertEquals(WALLET_SETUP_STARTING, walletSetupBlockedReason(input("connecting", running = true)))
assertEquals(READING_CHILD_NOTICE, walletSetupBlockedReason(null))
assertNull(
"a syncing wallet answers RPC, so a create is fine",
walletSetupBlockedReason(input("syncing", running = true)),
)
assertNull(walletSetupBlockedReason(input("ready", running = true)))
}
// --- the no-wallet-open state is information, not a failure ------------
@Test
fun the_no_wallet_open_state_is_information_never_the_red_failure() {
// The `No wallet open` info banner owns this sentence; printing it a
// second time in red is the duplicate the device report caught.
assertNull(
"already said once by the info banner above",
walletFailureBanner(WALLET_NOT_OPEN_TEXT, openHintVisible = true, walletOpen = false),
)
val alone = walletFailureBanner(WALLET_NOT_OPEN_TEXT, openHintVisible = false, walletOpen = false)
assertNotNull(alone)
assertEquals(WalletFailureTone.Info, alone!!.tone)
assertEquals("No wallet open", alone.title)
assertEquals(WALLET_NOT_OPEN_TEXT, alone.text)
assertNull(
"the state ended when a wallet was opened",
walletFailureBanner(WALLET_NOT_OPEN_TEXT, openHintVisible = false, walletOpen = true),
)
}
@Test
fun a_real_failure_still_paints_red() {
val refused = walletFailureText("wallet connect: Connection refused (os error 111)")!!
val banner = walletFailureBanner(refused, openHintVisible = true, walletOpen = false)!!
assertEquals("a refusal is still a failure", WalletFailureTone.Error, banner.tone)
assertEquals("Wallet error", banner.title)
assertEquals(refused, banner.text)
val exited = walletFailureText("spawn monero-wallet-rpc: No such file or directory (os error 2)")!!
assertEquals(WalletFailureTone.Error, walletFailureBanner(exited, false, false)!!.tone)
assertNull(walletFailureBanner(null, true, false))
assertNull(walletFailureBanner(" ", true, false))
}
}

View file

@ -0,0 +1,503 @@
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
import uniffi.onionwire_sdk.WalletChildStatus
/**
* The saved-wallets screen's rules, on the JVM.
*
* These are the decisions the screen renders from: what a catalogue row is
* called, whether the child has a wallet open at all, and whether the two
* secret actions may be offered for a given row. Pure logic, so no Robolectric
* and no Compose test dependency — same shape as `SeedBackupGateTest` and
* `WalletChildStatusTextTest`.
*/
class WalletManagerTest {
private val openFile = "onionwire-main"
private val otherFile = "onionwire-second"
/** The core's `wallet_status().state` for a child that answered. */
private val readable = true
/** No child, or one whose wallet RPC has not answered. */
private val notReadable = false
// --- what a row is called -----------------------------------------------
@Test
fun a_named_wallet_is_labelled_with_its_name() {
assertEquals("spending", walletRowLabel("spending", openFile))
}
@Test
fun an_unnamed_wallet_falls_back_to_its_file_name() {
assertEquals(openFile, walletRowLabel(null, openFile))
}
@Test
fun a_blank_name_counts_as_absent() {
// `WalletRow.name` is documented as never an empty string, but a
// whitespace label is a row the user cannot identify either way.
assertEquals(openFile, walletRowLabel("", openFile))
assertEquals(openFile, walletRowLabel(" ", openFile))
}
@Test
fun a_name_is_not_trimmed_out_of_the_label() {
// Only the *blank* case falls back. A name with padding is still the
// user's name and is shown as stored.
assertEquals(" spending ", walletRowLabel(" spending ", openFile))
}
// --- is the child reading a wallet at all --------------------------------
@Test
fun only_an_answered_wallet_rpc_counts_as_readable() {
// `connecting` is "the RPC has not answered"; `off` and `exited` are
// "there is no child". None of them can answer a key query.
assertTrue(walletChildReadable("ready"))
assertTrue(walletChildReadable("syncing"))
assertFalse(walletChildReadable("connecting"))
assertFalse(walletChildReadable("off"))
assertFalse(walletChildReadable("exited"))
}
@Test
fun nothing_read_yet_is_not_readable() {
assertFalse(walletChildReadable(null))
}
@Test
fun a_behind_chain_still_counts_as_readable() {
// Syncing means the RPC answered: the wallet's keys do not need the
// chain to be caught up.
assertTrue(walletChildReadable("syncing"))
}
// --- whether the secret actions are offered ------------------------------
@Test
fun the_open_wallets_secrets_are_offered() {
assertTrue(walletSecretsEnabled(openFile, openFile, readable))
}
@Test
fun another_wallets_secrets_are_not_offered() {
// The seed and the keys come from the file the child has open. A row
// that is not the open one must not read as its own backup.
assertFalse(walletSecretsEnabled(openFile, otherFile, readable))
}
@Test
fun nothing_open_means_no_secrets_for_any_row() {
assertFalse(walletSecretsEnabled(null, openFile, readable))
}
@Test
fun the_open_wallet_offers_no_secrets_while_the_child_is_not_reading_it() {
// Active but no answer: `wallet_seed()` / `wallet_keys()` can only
// fail, so the buttons stay dead rather than always erroring.
assertFalse(walletSecretsEnabled(openFile, openFile, notReadable))
assertFalse(walletSecretsEnabled(openFile, otherFile, notReadable))
assertFalse(walletSecretsEnabled(null, openFile, notReadable))
}
// --- and why they are off, in words --------------------------------------
@Test
fun an_enabled_row_has_nothing_to_explain() {
assertNull(walletSecretsBlockedReason(isActive = true, walletReadable = readable))
}
@Test
fun a_row_that_is_not_open_says_to_open_it() {
val why = walletSecretsBlockedReason(isActive = false, walletReadable = readable)
assertEquals("Open this wallet to view its backup.", why)
}
@Test
fun an_open_wallet_with_no_child_says_the_child_is_not_running() {
val why = walletSecretsBlockedReason(isActive = true, walletReadable = notReadable)
assertTrue(why != null && why.contains("not running"))
// The two reasons are different fixes and must not read alike.
assertFalse(why == walletSecretsBlockedReason(isActive = false, walletReadable = readable))
}
// --- the created-at column ----------------------------------------------
@Test
fun a_stored_created_at_renders_as_a_date() {
// 2021-01-01T00:00:00Z.
val rendered = walletRowDate(1609459200L)
assertTrue("got '$rendered'", Regex("""\d{4}-\d{2}-\d{2}""").matches(rendered))
}
@Test
fun a_later_created_at_sorts_after_an_earlier_one() {
// The store hands the rows back oldest-first; the rendered date must
// not invert that order in the list.
assertTrue(walletRowDate(1700000000L) > walletRowDate(1609459200L))
}
@Test
fun a_row_with_no_assigned_created_at_says_so() {
// The store assigns `created_at` on insert, so 0 is a row that predates
// that — not 1970, and not "today".
assertEquals("date unknown", walletRowDate(0L))
assertEquals("date unknown", walletRowDate(-1L))
}
// --- a wallet this install holds no passphrase for -----------------------
//
// `needs_passphrase` is the core's own word for "a saved wallet is
// configured and nothing here opens it" — the pre-parent-change wallet. The
// prompt is the only way it becomes openable, so the decision to show it is
// asserted here rather than in a Compose test.
@Test
fun a_wallet_with_no_stored_passphrase_asks_for_one() {
assertTrue(walletPassphrasePromptVisible(needsPassphrase = true, walletOpen = false))
}
@Test
fun an_open_wallet_is_never_asked_for_its_passphrase() {
assertFalse(walletPassphrasePromptVisible(needsPassphrase = false, walletOpen = true))
}
@Test
fun an_open_wallet_wins_over_a_stale_needs_passphrase_flag() {
// One `WalletChildStatus` carries both, and "there is a wallet open" is
// the stronger statement: asking for a passphrase the child has already
// used would look like the open failed.
assertFalse(walletPassphrasePromptVisible(needsPassphrase = true, walletOpen = true))
}
@Test
fun a_child_with_nothing_to_open_asks_for_nothing() {
// No child, or one never pointed at a file: there is no passphrase to
// ask for yet, and the list below is what the user acts on.
assertFalse(walletPassphrasePromptVisible(needsPassphrase = false, walletOpen = false))
}
@Test
fun the_prompt_can_be_submitted_once_a_file_and_a_passphrase_are_known() {
assertTrue(
walletPassphraseSubmitEnabled(activeFilename = openFile, typed = "pw", inFlight = false),
)
}
@Test
fun a_blank_passphrase_leaves_submit_dead() {
assertFalse(
walletPassphraseSubmitEnabled(activeFilename = openFile, typed = "", inFlight = false),
)
}
@Test
fun submit_is_dead_while_an_open_is_in_flight() {
// Re-submitting restarts the wallet child: one open at a time.
assertFalse(
walletPassphraseSubmitEnabled(activeFilename = openFile, typed = "pw", inFlight = true),
)
}
@Test
fun no_pointed_at_file_means_submit_is_dead_and_says_why() {
assertFalse(
walletPassphraseSubmitEnabled(activeFilename = null, typed = "pw", inFlight = false),
)
val why = walletPassphraseBlockedReason(activeFilename = null, typed = "pw")
assertTrue("got '$why'", why != null && why.contains("No wallet file is open yet"))
// The two reasons are different fixes and must not read alike.
assertFalse(why == walletPassphraseBlockedReason(activeFilename = openFile, typed = ""))
}
@Test
fun a_typed_passphrase_with_a_file_has_nothing_to_explain() {
assertNull(walletPassphraseBlockedReason(activeFilename = openFile, typed = "pw"))
}
@Test
fun nothing_typed_is_the_other_reason() {
val why = walletPassphraseBlockedReason(activeFilename = openFile, typed = "")
assertTrue("got '$why'", why != null && why.contains("Type the passphrase"))
}
// --- the daemon's own words never reach the screen -----------------------
/** The three things a user must never be shown, in one place. */
private fun assertNoRawRpc(text: String) {
assertFalse("raw RPC code on screen: $text", text.contains("-13"))
assertFalse("daemon phrase on screen: $text", text.contains("No wallet file"))
assertFalse("JSON on screen: $text", text.contains("{"))
assertFalse("JSON on screen: $text", text.contains("\"error\""))
}
@Test
fun the_daemons_no_wallet_file_never_reaches_the_screen() {
// What actually arrives: `parse_json_rpc` keeps `error.message` and
// drops the envelope, so the bare sentence is the common case.
val shown = walletFailureText("No wallet file")
assertEquals(WALLET_NOT_OPEN_TEXT, shown)
assertNoRawRpc(shown!!)
}
@Test
fun a_bare_rpc_code_never_reaches_the_screen() {
val shown = walletFailureText("wallet rpc error -13")
assertEquals(WALLET_NOT_OPEN_TEXT, shown)
assertNoRawRpc(shown!!)
}
@Test
fun a_raw_json_answer_never_reaches_the_screen() {
val raw = """{"error": {"code": -13, "message": "No wallet file"}}"""
val shown = walletFailureText(raw)
assertNoRawRpc(shown!!)
// The envelope is replaced, and because this one *is* the no-wallet-file
// answer the user gets the actionable text rather than the generic one.
assertEquals(WALLET_NOT_OPEN_TEXT, shown)
}
@Test
fun a_json_answer_is_replaced_even_when_it_names_another_code() {
val shown = walletFailureText("""{"error":{"code":-1,"message":"busy"}}""")
assertEquals(WALLET_DAEMON_REFUSED_TEXT, shown)
assertNoRawRpc(shown!!)
}
@Test
fun a_wrapped_daemon_phrase_is_still_replaced() {
// The core's open path prefixes the RPC's own message, and the prefix
// is no excuse to hand the daemon's words to the user.
val shown = walletFailureText(
"wallet file onionwire-1 is not open — the RPC refused its passphrase (No wallet file)",
)
assertEquals(WALLET_NOT_OPEN_TEXT, shown)
assertNoRawRpc(shown!!)
}
@Test
fun the_core_own_refusals_are_passed_through() {
// These are written for a person, carry no secret, and are the whole
// point of the message — replacing them would hide the reason.
val refusal = "no saved wallet in onionwire-9"
assertEquals(refusal, walletFailureText(refusal))
val stopped = "node stopped: wallet_keys called on a shut-down node"
assertEquals(stopped, walletFailureText(stopped))
}
@Test
fun a_number_that_merely_starts_with_minus_thirteen_is_not_a_code() {
assertEquals("offset -135", walletFailureText("offset -135"))
assertEquals("height -1300", walletFailureText("height -1300"))
}
@Test
fun nothing_to_show_is_null() {
assertNull(walletFailureText(null))
assertNull(walletFailureText(""))
assertNull(walletFailureText(" "))
}
@Test
fun the_replacement_texts_carry_no_raw_rpc_of_their_own() {
assertNoRawRpc(WALLET_NOT_OPEN_TEXT)
assertNoRawRpc(WALLET_DAEMON_REFUSED_TEXT)
}
// --- a connect refusal while the child is coming up -----------------------
@Test
fun connecting_connect_refusal_is_not_shown() {
// The Rust half stops storing this string in the first place; this is
// the display seam's own belt: a probe that dialled a port the child
// has not bound yet says nothing about whether the wallet is broken.
val raw = "wallet connect: Connection refused (os error 111)"
assertNull(displayLastError("connecting", raw))
assertNull(displayLastError(" connecting ", "wallet write: Connection reset"))
}
@Test
fun a_connect_refusal_after_connecting_is_still_shown() {
// Past `connecting` the same string means the child accepted a
// connection once and then died. Hiding that would hide a real failure.
val raw = "wallet connect: Connection refused (os error 111)"
assertEquals(raw, displayLastError("exited", raw))
assertEquals(raw, displayLastError("syncing", raw))
assertEquals(raw, displayLastError("off", raw))
}
@Test
fun display_last_error_still_rewrites_no_wallet_file() {
assertEquals(WALLET_NOT_OPEN_TEXT, displayLastError("connecting", "No wallet file"))
assertEquals(WALLET_NOT_OPEN_TEXT, displayLastError("syncing", "wallet rpc error -13"))
}
// --- "there is no wallet open", on the wallet screen ---------------------
@Test
fun a_live_child_with_no_wallet_says_what_to_do() {
val hint = walletChildOpenHint(
childRunning = true,
walletOpen = false,
needsPassphrase = false,
)
// The §4.1 replacement copy, verbatim: a live wallet with no file open
// is a state, not an error.
assertEquals(
"Select a saved wallet or create a new one to view your balance and transact.",
hint,
)
assertNoRawRpc(hint!!)
}
@Test
fun a_child_that_needs_a_passphrase_says_where_the_prompt_is() {
val hint = walletChildOpenHint(
childRunning = true,
walletOpen = false,
needsPassphrase = true,
)
assertTrue("got '$hint'", hint != null && hint.contains("Saved wallets"))
assertNoRawRpc(hint!!)
}
@Test
fun an_open_wallet_has_no_hint() {
assertNull(walletChildOpenHint(childRunning = true, walletOpen = true, needsPassphrase = false))
// An open wallet wins over a stale flag, same as the prompt.
assertNull(walletChildOpenHint(childRunning = true, walletOpen = true, needsPassphrase = true))
}
@Test
fun no_running_child_has_no_hint() {
// The status line already says off/exited and Start is right there.
assertNull(walletChildOpenHint(childRunning = false, walletOpen = false, needsPassphrase = true))
}
// --- the status line itself, from the record the screen renders -----------
/**
* The child's record as the SDK hands it over, for the state this card
* exists for: a live `connecting` child pointed at a wallet file this
* install holds no passphrase for. Its probe answers `-13 No wallet file`
* and `parse_json_rpc` keeps only `error.message`, so the bare sentence is
* what the core reports as `last_error`.
*/
private fun sdkStatus(
state: String = "connecting",
running: Boolean = true,
walletOpen: Boolean = false,
needsPassphrase: Boolean = true,
lastError: String? = "No wallet file",
) = WalletChildStatus(
state = state,
running = running,
walletOpen = walletOpen,
needsPassphrase = needsPassphrase,
configured = true,
chainSource = "remote daemon",
chainInProcess = false,
nodeAvailable = false,
nodeState = "",
height = 0uL,
targetHeight = 0uL,
lastError = lastError,
)
@Test
fun the_status_line_never_renders_the_daemons_own_words() {
// The render path, not the filter in isolation: the SDK record the
// poller lands is what the status line is drawn from, and the same
// field feeds the screen-reader sentence.
assertNoRawRpc(walletChildLine(sdkStatus().toInput()))
assertNoRawRpc(walletChildStatusDescription(sdkStatus().toInput()))
}
@Test
fun a_raw_rpc_envelope_on_the_status_line_is_replaced_too() {
// A failure that never reached the parser arrives as the envelope.
val raw = """{"error": {"code": -13, "message": "No wallet file"}}"""
assertNoRawRpc(walletChildLine(sdkStatus(lastError = raw).toInput()))
}
@Test
fun the_status_line_still_says_the_state_and_the_source() {
// Filtering the trailing text must not cost the line its own words.
val line = walletChildLine(sdkStatus().toInput())
assertTrue("got '$line'", line.startsWith("connecting · remote daemon"))
}
@Test
fun an_open_wallet_has_nothing_left_to_filter() {
val line = walletChildLine(
sdkStatus(state = "ready", walletOpen = true, needsPassphrase = false, lastError = null)
.toInput(),
)
assertEquals("ready · remote daemon", line)
}
@Test
fun the_cores_own_reason_for_a_dead_child_still_reaches_the_line() {
// The other side of the same seam: a reason written for a person is
// passed through, so the filter is not a mute button.
val line = walletChildLine(
sdkStatus(state = "exited", running = false, needsPassphrase = false,
lastError = "spawn monero-wallet-rpc: No such file").toInput(),
)
assertTrue("got '$line'", line.contains("No such file"))
assertNoRawRpc(line)
}
@Test
fun filtering_the_sdk_record_twice_changes_nothing() {
// The sticky error card runs the same filter over the same field, so
// the replacement must survive a second pass unchanged.
val once = sdkStatus().toInput().lastError
assertEquals(WALLET_NOT_OPEN_TEXT, once)
assertEquals(once, walletFailureText(once))
}
@Test
fun wallet_reads_reload_only_once_the_child_is_answering() {
// `walletBalance()` answers `"err"` — it does not throw — while the
// child is still dialling, so reloading in that window is what pins the
// headline on `Balance unavailable`. Reload only when the child has answered.
assertFalse(shouldReloadWalletReads(null))
assertFalse(shouldReloadWalletReads("off"))
assertFalse(shouldReloadWalletReads("connecting"))
assertFalse(shouldReloadWalletReads("exited"))
assertTrue(shouldReloadWalletReads("syncing"))
assertTrue(shouldReloadWalletReads("ready"))
assertTrue(shouldReloadWalletReads(" Ready "))
}
@Test
fun the_tui_not_configured_copy_is_mapped_and_never_rendered_verbatim() {
// `src/wallet.rs::NOT_CONFIGURED_MSG` is the desktop TUI's refusal. A
// phone has no F7 key and no ONIONWIRE_WALLET_RPC, so that sentence is
// the second dead end the device report caught: a passphrase was typed
// into Create, and the screen answered with a keyboard shortcut.
val tui = "wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC"
val shown = walletFailureText(tui)
assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, shown)
assertFalse("no F7 reaches the screen", shown!!.contains("F7"))
assertFalse("no env var name either", shown.contains("ONIONWIRE_WALLET_RPC"))
assertTrue("the phone sentence says what to do", shown.contains("Start it on the node card"))
// Each fragment alone is the same fact and is mapped too; case and
// spacing are not load-bearing.
assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, walletFailureText("Open F7"))
assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, walletFailureText("Wallet Not Configured"))
assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, walletFailureText("set ONIONWIRE_WALLET_RPC"))
// And it is idempotent: the sticky error card re-filters its own text.
assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, walletFailureText(shown))
}
}

View file

@ -0,0 +1,45 @@
package com.siriusdevops.onionwire.ui.components
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The identicon is a rendering of the identity fingerprint, so it has to be a
* function of that value and nothing else: same fingerprint, same picture, on
* every device and every launch. Pure (a list of cells), no Compose runtime.
*/
class IdenticonTest {
private val fingerprint =
"9f2c41ab77de03b5c8e1f0a6d4b39c2e5a7f81c0d3e6b492af17c5d80e3b6a49"
@Test
fun the_same_seed_always_produces_the_same_cells() {
assertEquals(identiconCells(fingerprint), identiconCells(fingerprint))
}
@Test
fun the_picture_is_mirrored_about_the_middle_column() {
val cells = identiconCells(fingerprint)
val columns = cells.map { it.first }
cells.forEach { (col, row, tone) ->
assertTrue(
"column $col row $row is not mirrored",
cells.any { it.first == 4 - col && it.second == row && it.third == tone },
)
}
assertTrue(columns.all { it in 0..4 })
}
@Test
fun a_different_seed_produces_a_different_picture() {
val other = fingerprint.reversed()
assertTrue(identiconCells(fingerprint) != identiconCells(other))
}
@Test
fun an_empty_seed_draws_nothing() {
assertEquals(emptyList<Triple<Int, Int, Int>>(), identiconCells(""))
}
}

View file

@ -9,11 +9,16 @@ composeBom = "2025.12.01"
jna = "5.19.1" jna = "5.19.1"
coroutines = "1.11.0" coroutines = "1.11.0"
junit = "4.13.2" junit = "4.13.2"
androidxTestJunit = "1.3.0"
androidxTestRunner = "1.7.0"
zxing = "3.5.3"
[libraries] [libraries]
androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" } androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" }
jna = { module = "net.java.dev.jna:jna", version.ref = "jna" } jna = { module = "net.java.dev.jna:jna", version.ref = "jna" }
junit = { module = "junit:junit", version.ref = "junit" } junit = { module = "junit:junit", version.ref = "junit" }
androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestJunit" }
androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidxTestRunner" }
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" } kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" } androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }
@ -26,6 +31,7 @@ compose-ui-graphics = { module = "androidx.compose.ui:ui-graphics" }
compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" } compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" }
compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" } compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" }
compose-material3 = { module = "androidx.compose.material3:material3" } compose-material3 = { module = "androidx.compose.material3:material3" }
zxing = { module = "com.google.zxing:core", version.ref = "zxing" }
[plugins] [plugins]
android-application = { id = "com.android.application", version.ref = "agp" } android-application = { id = "com.android.application", version.ref = "agp" }

View file

@ -0,0 +1 @@
d9126788030ecd1ccdb40c7764e66e9a14d158a147ad335b256f0577681b5ad4 app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so

View file

@ -52,10 +52,127 @@ val onionwireAbis: List<String> = (findProperty("onionwire.abis") as String?)
?.split(',')?.map(String::trim)?.filter(String::isNotEmpty) ?.split(',')?.map(String::trim)?.filter(String::isNotEmpty)
?: listOf("arm64-v8a") ?: listOf("arm64-v8a")
/**
* Rust features for the **Android** target build.
*
* `cuprate-daemon` is what puts the in-process Monero chain daemon (Cuprate) in
* the APK — the SDK crate's passthrough to the core
* (`cuprate-daemon = ["onionwire/cuprate-daemon"]`), so `WalletChildStatus.node_available`
* is `true` on the device and `ChainChoice.InProcessCuprate` can actually start.
*
* Deliberately **not** applied to `cargoHostLib` / `uniffiBindgen`: those build a
* host cdylib only so `uniffi-bindgen --library` can dlopen it, the cuprated graph
* (152 crates plus a C++ RandomX build) buys nothing there, and the UniFFI surface
* does not fork on a cargo feature. The Kotlin bindings are byte-identical either
* way, which is what `crates/onionwire-sdk`'s own tests cover.
*/
val onionwireRustFeatures: List<String> = listOf("cuprate-daemon")
/** `arm64-v8a` -> the Rust triple, the sysroot dir name and the builtins archive. */
data class AndroidTarget(
val abi: String,
val triple: String,
/** Sysroot library dir under `.../sysroot/usr/lib/`. */
val sysrootLib: String,
/** `libclang_rt.builtins-<this>.a`, from the NDK clang resource dir. */
val builtins: String,
/** NDK clang driver prefix: `<this><api>-clang`. */
val clangPrefix: String,
)
val androidTargets: Map<String, AndroidTarget> = listOf(
AndroidTarget("arm64-v8a", "aarch64-linux-android", "aarch64-linux-android", "aarch64-android", "aarch64-linux-android"),
AndroidTarget("x86_64", "x86_64-linux-android", "x86_64-linux-android", "x86_64-android", "x86_64-linux-android"),
AndroidTarget("armeabi-v7a", "armv7-linux-androideabi", "arm-linux-androideabi", "arm-android", "armv7a-linux-androideabi"),
AndroidTarget("x86", "i686-linux-android", "i686-linux-android", "i386-android", "i686-linux-android"),
).associateBy(AndroidTarget::abi)
/** The NDK's host tag (`linux-x86_64`, `darwin-x86_64`, …) — exactly one prebuilt tree. */
val ndkHostTag: String = ndkDir.resolve("toolchains/llvm/prebuilt").listFiles()
?.filter(File::isDirectory)?.singleOrNull()?.name
?: error("expected exactly one NDK prebuilt toolchain under $ndkDir/toolchains/llvm/prebuilt")
/** The NDK clang resource dir (`lib/clang/<version>/lib/linux`) — exactly one version. */
val ndkClangLibDir: File = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/lib/clang")
.listFiles()?.filter(File::isDirectory)?.singleOrNull()
?.resolve("lib/linux")
?: error("expected exactly one clang resource dir under $ndkDir/toolchains/llvm/prebuilt/$ndkHostTag/lib/clang")
/**
* Per-ABI link flags for the Android build.
*
* RandomX is C++ and its aarch64 JIT calls `__clear_cache`, and `randomx-rs`'s
* build script emits `rustc-link-lib=static=stdc++` against the NDK's *stub*
* `libstdc++.a`. Without libc++ and the compiler-rt builtins on the link line the
* build dies on `__cxa_allocate_exception` / `std::runtime_error` / `typeinfo`
* (and `__clear_cache`) undefined. `cargo ndk --link-builtins` covers only the
* builtins, not libc++ — and `-static-libstdc++` is ignored by NDK clang — so the
* whole set is spelled out. Recipe and evidence: `docs/cuprate-android-spike.md`.
*
* Exported as `CARGO_TARGET_<TRIPLE>_RUSTFLAGS` rather than `RUSTFLAGS`: a global
* rustflags would also apply to build scripts and proc macros, which are
* **host**-targeted, and `-lc++_static` there breaks the host link.
*
* The same variables also *replace* any `target.<triple>.rustflags` in
* `~/.cargo/config.toml`, so the sysroot `-L` it carried is repeated here.
*/
fun linkFlags(target: AndroidTarget): String {
val sysrootLib = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/sysroot/usr/lib/${target.sysrootLib}")
// The *dynamic* libc/libm/libdl stubs live in a per-API subdirectory; the
// arch directory above holds the static `libc.a` and the libc++ archives.
// Both must be on the search path, and this one must come first: `-lc`
// resolves to whichever the linker finds first, and bionic linked
// statically into a shared object is a landmine — its `getauxval` reads an
// auxv vector only the dynamic linker fills in, so the first C++ static
// initializer that asks for it (RandomX's, from `cuprate-daemon`) null-derefs
// inside `dlopen` and takes the process with it.
val sysrootStubLib = sysrootLib.resolve(onionwireApiLevel.toString())
require(sysrootStubLib.resolve("libc.so").isFile) {
"no dynamic libc stub at $sysrootStubLib/libc.so — NDK $onionwireNdkVersion layout changed? " +
"Linking the arch dir alone would pull in the static libc.a."
}
return listOf(
// Hygiene on a hand-written link line: lld defaults to --no-as-needed,
// which records a DT_NEEDED for every `-l` mentioned even when nothing
// is taken from it. (`libstdc++.so` survives this anyway — randomx-rs's
// cmake half asks for it and it satisfies symbols the static libc++
// archives were already scanned for. That shim is present on every
// Android release to date; the device run in the PR loads it.)
"-C", "link-arg=-Wl,--as-needed",
"-C", "link-arg=-L$sysrootStubLib",
"-C", "link-arg=-L$sysrootLib",
"-C", "link-arg=-L$ndkClangLibDir",
"-C", "link-arg=-lclang_rt.builtins-${target.builtins}",
"-C", "link-arg=-lc++_static",
"-C", "link-arg=-lc++abi",
"-C", "link-arg=-Wl,--exclude-libs,libc++_static.a",
"-C", "link-arg=-Wl,--exclude-libs,libc++abi.a",
).joinToString(" ")
}
/** The NDK clang driver for one ABI at [onionwireApiLevel]. */
private fun clangDriver(target: AndroidTarget): File =
ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/bin/${target.clangPrefix}$onionwireApiLevel-clang")
val jniLibsDir = layout.buildDirectory.dir("rustJniLibs") val jniLibsDir = layout.buildDirectory.dir("rustJniLibs")
val uniffiKotlinDir = layout.buildDirectory.dir("generated/uniffi") val uniffiKotlinDir = layout.buildDirectory.dir("generated/uniffi")
/** Host cdylib. UniFFI's `--library` mode dlopens it, so it must be host-arch. */ // cargo honors CARGO_TARGET_DIR when set (CI sibling container). UniFFI's
// --library path must match, or bindgen dies with ENOENT after a green compile.
val cargoTargetDir: File = System.getenv("CARGO_TARGET_DIR")?.let(::File)
?: sdkCrateDir.resolve("target")
val hostCdylib: File = cargoTargetDir.resolve("release/libonionwire_sdk.so")
/**
* Host cdylib. UniFFI's `--library` mode dlopens it, so it must be host-arch.
*
* Feature-free **on purpose**: this exists only to emit the Kotlin bindings, and
* `cuprate-daemon` would drag the whole Cuprate graph (152 crates + a C++ RandomX
* build) through a host compile that never runs the daemon. The UniFFI surface
* does not fork on a cargo feature — `ChainChoice.InProcessCuprate` is present in
* both — so the generated Kotlin is the same. `onionwireRustFeatures` is for
* [cargoBuildAndroid] only.
*/
val cargoHostLib by tasks.registering(Exec::class) { val cargoHostLib by tasks.registering(Exec::class) {
group = "onionwire" group = "onionwire"
description = "Builds libonionwire_sdk.so for the host (used only to emit bindings)." description = "Builds libonionwire_sdk.so for the host (used only to emit bindings)."
@ -76,7 +193,7 @@ val uniffiBindgen by tasks.registering(Exec::class) {
commandLine( commandLine(
cargoExe, "run", "--release", "--bin", "uniffi-bindgen", "--", cargoExe, "run", "--release", "--bin", "uniffi-bindgen", "--",
"generate", "generate",
"--library", "target/release/libonionwire_sdk.so", "--library", hostCdylib.absolutePath,
"--language", "kotlin", "--language", "kotlin",
"--no-format", "--no-format",
"--config", "uniffi.toml", "--config", "uniffi.toml",
@ -93,10 +210,38 @@ val cargoBuildAndroid by tasks.registering(Exec::class) {
inputs.file(sdkCrateDir.resolve("Cargo.lock")) inputs.file(sdkCrateDir.resolve("Cargo.lock"))
inputs.dir(repoRoot.resolve("src")) inputs.dir(repoRoot.resolve("src"))
inputs.file(repoRoot.resolve("Cargo.toml")) inputs.file(repoRoot.resolve("Cargo.toml"))
// The feature set is an input: `-Ponionwire.features=` … there is no knob
// (a build that silently dropped `cuprate-daemon` would ship an APK whose
// on-device node can only fail), but the task must not stay "up to date"
// across a change to this list.
inputs.property("rustFeatures", onionwireRustFeatures)
outputs.dir(jniLibsDir) outputs.dir(jniLibsDir)
environment("ANDROID_HOME", androidSdkDir.absolutePath) environment("ANDROID_HOME", androidSdkDir.absolutePath)
environment("ANDROID_NDK_HOME", ndkDir.absolutePath) environment("ANDROID_NDK_HOME", ndkDir.absolutePath)
environment("NDK_HOME", ndkDir.absolutePath) environment("NDK_HOME", ndkDir.absolutePath)
// `cmake-rs` (RandomX's C++ half) aborts with "Neither the NDK or a standalone
// toolchain was found" unless ANDROID_NDK itself is exported — NDK_HOME and
// ANDROID_NDK_HOME are not enough, and `randomx-rs`'s build script then panics
// inside `cmake`.
environment("ANDROID_NDK", ndkDir.absolutePath)
environment("ANDROID_NDK_ROOT", ndkDir.absolutePath)
// Per-ABI link env. The clang driver is named explicitly because
// `~/.cargo/config.toml` on the dev machines pins the *API 21* wrapper for
// `aarch64-linux-android`, and API 21 fails this link (`pthread_atfork` is
// API 23+); `cargo-ndk`'s own linker wrapper is bypassed on purpose so the
// `-Wl,…` args below reach clang as link args.
onionwireAbis.forEach { abi ->
val target = androidTargets[abi]
?: error("no Android target mapping for ABI '$abi' — add it to androidTargets in sdk/build.gradle.kts")
val rustFlagsVar = "CARGO_TARGET_${target.triple.uppercase().replace('-', '_')}_RUSTFLAGS"
val linkerVar = "CARGO_TARGET_${target.triple.uppercase().replace('-', '_')}_LINKER"
val linker = clangDriver(target)
require(linker.canExecute()) {
"NDK clang driver for $abi not found at $linker — NDK $onionwireNdkVersion incomplete?"
}
environment(rustFlagsVar, linkFlags(target))
environment(linkerVar, linker.absolutePath)
}
commandLine( commandLine(
buildList { buildList {
add(cargoExe); add("ndk") add(cargoExe); add("ndk")
@ -104,8 +249,20 @@ val cargoBuildAndroid by tasks.registering(Exec::class) {
add("--platform"); add(onionwireApiLevel.toString()) add("--platform"); add(onionwireApiLevel.toString())
add("-o"); add(jniLibsDir.get().asFile.absolutePath) add("-o"); add(jniLibsDir.get().asFile.absolutePath)
add("build"); add("--release"); add("--lib") add("build"); add("--release"); add("--lib")
if (onionwireRustFeatures.isNotEmpty()) {
add("--features"); add(onionwireRustFeatures.joinToString(","))
}
} }
) )
// The CI log has to show the feature actually requested, not merely the task
// name: "the feature is in the artifact" is checked against this line.
doFirst {
logger.lifecycle(
"cargo ndk build for ${onionwireAbis.joinToString()} " +
"features=${onionwireRustFeatures.joinToString(",").ifEmpty { "(none)" }} " +
"api=$onionwireApiLevel ndk=$onionwireNdkVersion",
)
}
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@ -158,6 +315,42 @@ tasks.withType<KotlinCompile>().configureEach {
dependsOn(uniffiBindgen) dependsOn(uniffiBindgen)
} }
tasks.matching { it.name == "preBuild" }.configureEach { /**
dependsOn(cargoBuildAndroid, uniffiBindgen) * Fails the build if the SDK's shared object did not link bionic dynamically.
*
* `linkFlags()` spells the NDK search path out by hand, and `-L` order decides
* whether `-lc` resolves to the per-API `libc.so` stub or to the arch
* directory's `libc.a`. Static bionic inside a `.so` leaves `getauxval` reading
* an auxv vector only the dynamic linker fills in, so the first C++ static
* initializer that asks for CPU features null-derefs inside `dlopen` — a crash
* with no Java stack, at the first SDK call, on every ABI. Reading the built
* ELF is the only check that catches it before a device does.
*/
val verifyDynamicLibc by tasks.registering {
group = "verification"
description = "Asserts libonionwire_sdk.so links libc.so dynamically (no static bionic)."
dependsOn(cargoBuildAndroid)
val libsDir = jniLibsDir
val abis = onionwireAbis
val readelf = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/bin/llvm-readelf")
doLast {
abis.forEach { abi ->
val so = libsDir.get().asFile.resolve(abi).resolve("libonionwire_sdk.so")
check(so.isFile) { "no $so to verify — did cargoBuildAndroid run for $abi?" }
val proc = ProcessBuilder(readelf.absolutePath, "-d", so.absolutePath)
.redirectErrorStream(true)
.start()
val dump = proc.inputStream.bufferedReader().use { it.readText() }
check(proc.waitFor() == 0) { "$readelf failed on $so:\n$dump" }
check(dump.lineSequence().any { it.contains("(NEEDED)") && it.contains("libc.so") }) {
"$so has no libc.so in DT_NEEDED — it linked the static libc.a. " +
"That is the `-L` order in linkFlags() regressing; a device crashes " +
"with a null deref in getauxval the first time the SDK is dlopen'd.\n$dump"
}
}
}
}
tasks.matching { it.name == "preBuild" }.configureEach {
dependsOn(cargoBuildAndroid, uniffiBindgen, verifyDynamicLibc)
} }

File diff suppressed because it is too large Load diff

View file

@ -2,28 +2,38 @@
name = "onionwire-sdk" name = "onionwire-sdk"
version = "0.1.0" version = "0.1.0"
edition = "2024" edition = "2024"
rust-version = "1.91" # Follows the root crate. The SDK builds onionwire with `default-features =
# false` (no `cuprate-daemon`), which would still compile on 1.91, but cargo
# checks the path dependency's `rust-version` anyway, and that floor is 1.98.
rust-version = "1.98"
description = "OnionWire Android/Kotlin SDK: in-process Arti onion transport, Noise IK, identity = ed25519 pubkey." description = "OnionWire Android/Kotlin SDK: in-process Arti onion transport, Noise IK, identity = ed25519 pubkey."
license = "MIT" license = "MIT"
publish = false publish = false
# Standalone workspace on purpose. # Standalone workspace on purpose: the SDK carries its own lockfile and its own
# # crate set (Android: `static-sqlite`, rustls TLS), so it path-depends on the
# Arti's TLS backends (`native-tls` vs `rustls`) are non-additive: exactly one
# may be enabled per feature resolution. The Linux TUI crate keeps native-tls,
# Android has no OpenSSL in the NDK and needs rustls. Two separate workspaces
# keep the two resolutions from colliding — this crate path-depends on the
# root package without joining its feature graph. # root package without joining its feature graph.
[workspace] [workspace]
resolver = "2"
[lib] [lib]
name = "onionwire_sdk" name = "onionwire_sdk"
crate-type = ["cdylib", "lib"] crate-type = ["cdylib", "lib"]
[features]
default = []
# The in-process Monero chain daemon (Cuprate). Off by default: it pulls a
# pinned `cuprated` git revision, ~152 crates and a C++ RandomX cross-build
# (+11.8 MiB on an aarch64 release binary). Without it the SDK can still store
# and read back a `ChainChoice.InProcessCuprate` setting — starting one fails
# with the core's "rebuild with --features cuprate-daemon" message.
cuprate-daemon = ["onionwire/cuprate-daemon"]
[dependencies] [dependencies]
onionwire = { path = "../..", default-features = false, features = ["rustls"] } onionwire = { path = "../..", default-features = false, features = ["rustls"] }
# `static-sqlite`: Android has no system libsqlite3 to link against. # `static-sqlite`: Android has no system libsqlite3 to link against.
arti-client = { version = "0.46", default-features = false, features = [ arti-client = { version = "0.49", default-features = false, features = [
"tokio", "tokio",
"onion-service-client", "onion-service-client",
"onion-service-service", "onion-service-service",

View file

@ -5,7 +5,7 @@ runs on. An Android peer and a Linux peer that exchange invites interoperate —
there is one protocol, not two. there is one protocol, not two.
This is **not** a WebView wrapper and **not** a client for a hosted service. This is **not** a WebView wrapper and **not** a client for a hosted service.
Each install runs Arti in-process (`arti-client` 0.46, `onion-service-client` + Each install runs Arti in-process (`arti-client` 0.49, `onion-service-client` +
`onion-service-service`), hosts its own v3 onion service, and dials friends' `onion-service-service`), hosts its own v3 onion service, and dials friends'
onions directly. There is no `tor` binary, no torrc, no Orbot as the pipe. onions directly. There is no `tor` binary, no torrc, no Orbot as the pipe.
@ -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
@ -27,7 +27,7 @@ onions directly. There is no `tor` binary, no torrc, no Orbot as the pipe.
onionwire:v1:k=<ed25519 pubkey hex64>:o=<v3 onion address>:spk=<x25519 prekey hex64>:sig=<ed25519 sig hex128> onionwire:v1:k=<ed25519 pubkey hex64>:o=<v3 onion address>:spk=<x25519 prekey hex64>:sig=<ed25519 sig hex128>
``` ```
* `sig` is a signature over the concatenation `k ‖ o ‖ spk` as raw ASCII bytes. * `sig` is ed25519 over `onionwire-invite-v1` + `0x00`-separated `k`, `o`, `spk` (hex/onion as they appear in the string). Decode still accepts the legacy raw concatenation so old invites verify. See [docs/PROTOCOL.md](../../docs/PROTOCOL.md).
* A malformed, unsigned, or tampered invite is rejected before anything is stored. * A malformed, unsigned, or tampered invite is rejected before anything is stored.
* **Same `k` never creates a second friend.** It updates the stored locator on * **Same `k` never creates a second friend.** It updates the stored locator on
the existing row. That is the whole point of keying the roster on the pubkey. the existing row. That is the whole point of keying the roster on the pubkey.
@ -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,12 +90,47 @@ 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.
val out: RotateOutcome = wire.rotateOnion() // out.notified / out.friends val out: RotateOutcome = wire.rotateOnion() // out.notified / out.friends
// 6. Saved wallets, and which one is open.
val wallets: List<WalletRow> = wire.wallets() // a store read: never dials
val active: String? = wire.activeWalletFilename() // the open file, or null
val open = wallets.firstOrNull { it.walletFilename == active }
wire.openWallet("onionwire-2") // may restart a running wallet child; a name
// outside the catalogue is refused
// A wallet child is up but its file is not open -> the child answers `-13 No
// wallet file` to every read. `walletStatus()` says which:
val st: WalletChildStatus = wire.walletStatus()
if (st.running && !st.walletOpen && st.needsPassphrase) {
val pass = askForTheWalletPassphrase() // your own input surface, echo off
wire.openWalletWithPassphrase(active!!, pass) // stored (sealed) on success;
// a refused passphrase is an
// error and is NOT stored
}
val keys: WalletKeys = wire.walletKeys() // the OPEN wallet's private keys
// keys.spendKey == null -> a view-only wallet (the RPC's -29 watch-only answer).
// That is not an error. The seed (`walletSeed()`) and these keys always belong
// to `activeWalletFilename()`: to show another wallet's backup, open it first.
// Both are spend secrets — show them from an explicit user action only, never
// log them, never persist them.
// 7. Your own profile (nickname, bio, Monero address).
val me: SelfProfile = wire.selfProfile()
wire.setSelfProfile("ada", "on the wire", "4AdUnd...") // validated on write
wire.pushSelfProfile(friend.pubkeyHex) // signed `prf`, one-shot and fail-closed
``` ```
All peer references are lowercase hex strings so nothing Rust-shaped leaks into All peer references are lowercase hex strings so nothing Rust-shaped leaks into
@ -116,7 +153,7 @@ output.
## Why this crate has its own Cargo workspace ## Why this crate has its own Cargo workspace
Arti's TLS backends are **non-additive**: exactly one of `native-tls` and Arti's TLS backends are **non-additive**: exactly one of `native-tls` and
`rustls` may be enabled in a given feature resolution. The Linux TUI keeps `rustls` may be enabled in a given feature resolution. The root crate defaults
`native-tls` (OpenSSL, as it always has). Android has no OpenSSL in the NDK, so to `rustls` (Linux TUI and releases), so this crate does not differ from the
this crate selects `rustls` plus `static-sqlite` (no system `libsqlite3` on root on TLS; it does add `static-sqlite`, because Android has no system
Android). Two separate workspaces keep the two resolutions from colliding. `libsqlite3`. Two separate workspaces keep the two resolutions from colliding.

File diff suppressed because it is too large Load diff

163
docs/ARTI_UPGRADE.md Normal file
View file

@ -0,0 +1,163 @@
# Upgrading the Arti / Tor crates
The in-process Tor stack is the largest attack surface in OnionWire. Arti's
onion services are still **experimental** and OnionWire does not fall back to a
C-tor subprocess, so an upstream fix only reaches users when we bump these
crates, rebuild, and cut a release.
## What is pinned
Direct dependencies that come from the Arti repository, exactly as
`Cargo.toml` has them:
| crate | requirement | features in `Cargo.toml` |
|---|---|---|
| `arti-client` | `0.49` | `default-features = false`; `tokio`, `onion-service-client`, `onion-service-service`, `compression` |
| `tor-cell` | `0.49` | — |
| `tor-hsservice` | `0.49` | — |
| `tor-rtcompat` | `0.49` | `tokio` |
| `safelog` | `0.10` | — |
`snow`, `rusqlite`, `ratatui`, and the rest are unrelated to Arti and are not
part of a Tor upgrade. `safelog` lives in the Arti repository and moves in
lockstep with the `tor-*` set: a stale direct `safelog` pin puts two copies in
the graph, and `HsId::display_redacted` then resolves against the wrong trait
(`error[E0599]: no method named display_redacted`). The SDK workspace
(`crates/onionwire-sdk`) has its own `arti-client` pin and lockfile; bump it
too.
Two crate features re-expose Arti's TLS backends, which Arti marks
**non-additive** — exactly one may be selected per build graph:
* `rustls` (**default**) → every build: the Linux TUI, the released binaries and
the Android SDK. No system OpenSSL is needed for TLS; the root `Cargo.toml`
pins rustls's `ring` feature so the crypto provider resolves from crate
features (without it the rustls backend compiles with no provider).
* `native-tls` → opt-in only, via OpenSSL.
Published Arti releases move all of the crates above together in lockstep.
Bump them as **one set**. A mixed set (e.g. `arti-client` 0.47 with
`tor-hsservice` 0.49) is not a configuration anyone tests upstream, and cargo
will usually refuse or silently pick one `tor-*` version and mismatched
`tor-*` internals fail at runtime.
## Toolchain floor
**rustc 1.98+.** `Cargo.toml` sets `edition = "2024"` and `rust-version = "1.98"`.
Arti 0.49 itself requires only 1.92; the higher floor is the default
`cuprate-daemon` feature (`tapes` calls `VecDeque::pop_front_if`, stable since
1.93). CI builds inside `rust:1.98-bookworm`
(`RUST_IMAGE` in `.forgejo/workflows/ci.yml` and `release.yml`).
A bump may raise the floor. Take the actual MSRV from the upstream release
notes / the crate's own `rust-version`, then raise it in the same PR:
* `rust-version` in `Cargo.toml`,
* `RUST_IMAGE` in `.forgejo/workflows/ci.yml` **and** `.forgejo/workflows/release.yml`,
* the "Rust 1.98+" line in `README.md`.
## How this gets noticed
`.forgejo/workflows/arti-watch.yml` runs daily (and on demand) and asks
crates.io for the newest stable version of each crate above. If the
major.minor moved past the pin, it files one Forgejo issue titled
`Arti upstream: <crate> <pin> → <new>`. It is deduped on that title across open
and closed issues, so re-running it never files a second issue and never
comments. It changes nothing: no `Cargo.toml`, no lockfile, no commit.
Test the alert path without waiting for upstream (it compares real crates.io
data against a pretend pin):
```
# Actions → arti-watch → Run workflow, simulate_pin = arti-client=0.45
python3 scripts/arti-watch.py --dry-run --cargo-toml Cargo.toml --simulate-pin arti-client=0.45
```
**What the watcher does not cover.** It does not subscribe to Tor Project
security announcements — a fix that ships without a crates.io version bump is
invisible to it. It will not catch a yanked crate, and it will not catch a
vulnerability in a version that has not changed. Watch
<https://blog.torproject.org/> and <https://forum.torproject.org/> yourself, and
treat a Tor security advisory as an instruction to bump **now**, ahead of any
issue the watcher files.
## Procedure
1. Read the upstream release notes (Arti tags: <https://gitlab.torproject.org/tpo/core/arti/-/releases>)
and the CHANGELOG for breaking API changes. Check the new MSRV.
2. Branch from `main`; bump every Arti-repository pin in `[dependencies]` of
`Cargo.toml` together (`arti-client`, `tor-cell`, `tor-hsservice`,
`tor-rtcompat`, and `safelog`), the matching `arti-client` pin in
`crates/onionwire-sdk/Cargo.toml`, and `rust-version` if the floor moved.
3. Refresh the lockfile (CI builds with `--locked` and `Cargo.lock` is
committed):
```
cargo update -p arti-client -p tor-cell -p tor-hsservice -p tor-rtcompat -p safelog
git diff --stat Cargo.lock
```
Expect the whole `tor-*` family to move in the diff. A single `tor-*` crate
moving alone is a sign the set is not actually lockstep — stop and look.
Then refresh the SDK workspace's separate lockfile:
```
( cd crates/onionwire-sdk && cargo update -p arti-client )
```
4. Build and run the offline suite:
```
cargo test --locked
cargo clippy --locked --all-targets -- -D warnings
```
5. Re-check the workarounds in `src/hs.rs`. They exist because Arti's publish
path is slow and its circuit timeouts misbehave on hidden-service circuits,
and an upstream fix or behaviour change can make any of them wrong:
| constant | why | guard |
|---|---|---|
| `PUBLISH_WAIT` (360s) | a 180s wait cut a working HsDir upload while status was still `Bootstrapping`; Arti's per-HsDir `OVERALL_UPLOAD_TIMEOUT` is 5 min | `tests/hs.rs::publish_wait_covers_hsdir_retries` |
| `CBT_MIN_TIMEOUT_MS` / `CBT_INITIAL_TIMEOUT_MS` (≥ 10s) | learned circuit-build timeouts can drop to ~1s and kill 4-hop vanguard HsDir circuits | `tests/hs.rs::cbt_min_timeout_floor_is_at_least_10s`, `cbt_initial_timeout_matches_the_floor` |
| `PREEMPTIVE_PREDICTED_PORTS` (empty) | Arti's default predicted 80/443 exit circuits starve IPT + HsDir builds; OnionWire never exits | `tests/hs.rs::no_preemptive_exit_ports` |
| `hs_is_ready` probe semantics | combined status stays `Bootstrapping` after descriptors are already fetchable | `tests/hs.rs::bootstrapping_is_not_ready_until_a_probe_connects` |
Do not paper over a slow publish by raising `PUBLISH_WAIT` — first make sure
the rend handler is spawned *before* the probe wait, or the probe cannot
succeed at all.
6. Run the live two-node test on a networked machine. This is the only test that
proves the hidden service actually publishes and that a second node can
reach it:
```
cargo test --locked --test tor_hs -- --ignored --nocapture
```
It needs minutes of real Tor network. `two_node_byte_pipe_restart_and_dormant`
covers: onion publish (first-run `hs status: Bootstrapping` spam is HsDir
descriptor upload, not a hang), probe-connect against a live HS, a byte pipe
in both directions, restart, and the dormant/offline path.
7. Confirm the fail-closed path by hand if the publish wait changed at all:
with the publish wait still 360s, if Arti cannot publish the onion the
process must exit (no C-tor fallback). Chat to a *reachable-HS but down peer*
is queued locally (`src/outbox.rs`) and retried; file transfer and payment
frames still fail immediately. There is no **server-side** outbox.
8. Rebuild the Android target. The root crate defaults to `rustls` now, so this
is less about exercising a non-default feature than about proving the default
still cross-compiles where OpenSSL does not exist:
```
scripts/build-android-local.sh
```
9. Verify the ciphertext claim still holds after the bump: send a message
between the two nodes, then
```
grep -r "<a distinctive message body>" <nodes' Arti state dirs and sqlite files>
```
must find nothing. The bodies live in sqlite as ciphertext, and nothing about
the plaintext should appear in Arti's state directory.
10. Open a PR against `main` describing: crates bumped, MSRV, the live-test
output, and anything upstream changed that touches `src/hs.rs`. Do not push
`main`. Releases are **manual and batched**: dispatch
`.forgejo/workflows/release.yml` (`dry_run=true` first). A merge does not
mint a release. See [RELEASING.md](RELEASING.md).
## Rolling back
Revert the version bump and the lockfile stanza together, re-run step 3's
`cargo update` only if the revert leaves the lockfile inconsistent, and re-run
`cargo test --locked` plus the live two-node test. Never leave `Cargo.toml` and
`Cargo.lock` out of step: CI builds with `--locked` and will fail, which is the
intent.

950
docs/PROTOCOL.md Normal file
View file

@ -0,0 +1,950 @@
# OnionWire protocol (v1)
This is the wire protocol. A second implementation should be able to
interoperate from this document without reading the Rust.
It is **not** an IETF RFC. It describes what this repository speaks today
(frame versions 1 and 2, invite schemes `onionwire:v2` (emit) and
`onionwire:v1` (decode only)). There has been no public third-party audit.
Arti onion services are experimental upstream.
Related: [threat model](THREAT_MODEL.md), [audit notes](SECURITY_AUDIT.md).
## What this is not
OnionWire is not Tox, not Tox-over-Tor, not XMPP, and not “a messenger plus a
SOCKS proxy.”
| | Tox (including ToT) | OnionWire v1 |
|---|---|---|
| Discovery | DHT + bootstrap nodes | Out-of-band invite only |
| After lookup | Direct IP or TCP relay (SOCKS if you forced it) | v3 onion ↔ v3 onion |
| Address | Tox ID lives in the DHT | ed25519 pubkey is identity; onion is a locator |
| Offline send | Expected (relays / retry) | Queued locally, retried peer-to-peer (no relay) |
| Mixed clearnet | ToT can still talk to non-Tor Tox | No clearnet peers |
There is no directory, no name server, no introduction point of our own, and no
UDP at the application layer.
## Roles and keys
Each install holds:
- **Identity** — ed25519 keypair. The 32-byte public key **is** the person.
Roster primary key. Displayed as 64 lowercase hex chars (the fingerprint).
- **Prekey** — x25519 keypair. This is the Noise IK *static*. It is long-lived
— rotate it with `F8`, which hard-cuts every stored session. Rotating the
onion (`F4`) does **not** rotate it.
- **KEM key** — ML-KEM-768 (FIPS 203) keypair. The 1184-byte encapsulation key
travels in a v2 invite as `kem=`; the 64-byte decapsulation seed lives in the
SQLCipher store beside `identity_sk`. `F8` rotates it together with the
prekey, with the same hard cut (stored ratchet state is dropped and every
friend re-pastes the invite).
- **Onion** — Tor v3 address. Locator only. Disposable.
A friend is `{identity_pk, current_onion, current_prekey_pk, kem_pk?}`. Pasting
the same identity `k` updates the locator, prekey and KEM key on that row. It
never creates a second person. `kem_pk` is absent only for a friend added from
a legacy `onionwire:v1` invite; such a friend is **classical** (see
[No downgrade](#no-downgrade)).
Petnames, chat history, and the optional Monero wallet RPC are local. They are
not on the wire.
## Transport
1. Each peer publishes a Tor v3 onion service (in-process Arti in this tree).
2. Application port is **80**.
3. The sender opens a Tor circuit to `(friend.onion, 80)`, runs the handshake,
sends **one** application frame, and drops the circuit.
4. File transfer is N independent sessions (one handshake per chunk). There is
no multiplexed long-lived stream in v1.
If the onion is down, a **chat** send is persisted to the local outbox and
retried by a background worker with exponential backoff (30s, doubling, capped
at 30 min; 8 attempts, then terminal `Failed`). There is no server and no
store-and-forward relay: each attempt is a fresh handshake straight to
`(friend.onion, 80)`, exactly as above. Retries fire on a timer, on
unlock/foreground, and whenever that peer is heard from (successful handshake or
a connect to that onion). A protocol failure — signature mismatch, unknown
frame, oversize — is not a transport failure and is never queued.
File transfer and payment frames stay fail-closed: they are one-shot and are
**not** queued. The locator-push path retries for 180 seconds and then gives up.
Incoming rendezvous accepts are token-bucket limited: 30 per 60s, burst 10.
Excess is dropped before handshake. That is availability, not anonymity.
## Framing
Every Noise handshake message and every ciphertext is wrapped:
```
uint8 version = 1 (normal) | 2 (PQ handshake prelude)
uint32 length = big-endian body length
uint8 body[length]
```
- `version = 1` is Noise msg 1, msg 2, an identity proof, or one application
ciphertext. It is unchanged from v1 of this document.
- `version = 2` is the **PQ handshake prelude**. Its body is `uint16 ct_len`
(big-endian) followed by exactly `ct_len` bytes of ML-KEM-768 ciphertext.
`ct_len` MUST be 1088. The prelude may only be the first frame of a session;
the initiator sends exactly one, then Noise msg 1 with `version = 1`.
`read_frame` (used after the opening frame) rejects `version = 2`.
- `length` MUST be ≤ 65535. Check the length **before** allocating the body.
- Other `version` values are a hard fail (close the stream).
- Length that does not match the bytes on the wire is a hard fail.
`length` still reveals the exact ciphertext size. Chat hides it by padding the
plaintext to a bucket before encryption (see [Length buckets](#length-buckets)).
Other frame types are not padded.
## Length buckets
Normative for chat. A chat line is padded to one fixed ladder **before** the
ratchet encrypts it, so the padding is inside ChaCha20-Poly1305, inside the
Noise session, and authenticated by both. An observer sees a ciphertext whose
length is one of the ladder values (plus constant overhead), never the body
length.
Ladder — padded-plaintext sizes in bytes:
```
256, 512, 1024, 2048, 4096, 8192, 16384, 32768
```
Ratchet plaintext encoding:
```
uint16 pad_len big-endian
uint8 body[..] the chat line
uint8 fill[pad_len] random bytes, contents ignored
```
- The padded plaintext MUST be exactly the smallest ladder value that is at
least `2 + body_len`. `pad_len = bucket - 2 - body_len`.
- Empty and short bodies both pad to 256; a 254-byte body fits the 256 bucket
with `pad_len = 0`.
- `fill` is fresh random bytes. Its contents carry no meaning.
- A body larger than 32766 bytes does not fit the ladder and MUST fail closed
(it is a protocol error, never queued).
Receiver rules:
- The total decrypted length is **not** required to be a ladder value. Only the
header is normative, so a peer with a different ladder still interoperates.
- `pad_len` is the only authority for the body length. A receiver MUST NOT trim
trailing zeros, strip a repeated fill byte, or otherwise infer the boundary
from content: a body that legitimately ends in the same byte as the fill
round-trips unchanged.
- A plaintext shorter than 2 bytes, or one whose `pad_len` exceeds
`len - 2`, MUST be rejected as a hard failure before anything is appended,
rendered, or persisted. The ratchet state is not advanced.
- Unpadded frames are not accepted as if they were a bucket: if the first two
bytes do not describe a consistent `pad_len`, the frame fails closed.
- Padding is a plaintext-layer change and is independent of the `rat ` frame
version: a classical (`0x01`) and a hybrid (`0x02`) frame carry the same
padded plaintext. See [Ratchet (chat layer)](#ratchet-chat-layer) for the
header each version adds.
The ladder floor stays at **256** even though a hybrid frame's floor is over
2.6 KB. The ladder schedules the *plaintext*, and a hybrid step's size is
dominated by its 2312-byte header — the 256 bucket is a rounding error there,
so raising the floor would not conceal the header and would only inflate
classical (`0x01`) chat, which is still the epoch-0 and legacy-friend path. A
second, version-specific ladder would double the normative surface for no
privacy gain; the bucket boundaries remain observable within each size class
either way.
Minimum observable size depends on the `rat ` header version:
- Classical (`0x01`): `rat ` 4 + version 1 + header 40 + nonce 12 + bucket 256
+ tag 16 = **329-byte `rat ` frame**; the Noise transport adds its 16-byte
tag and the framing header adds 5 bytes, so the smallest classical chat frame
on the wire is **350 bytes**.
- Hybrid (`0x02`): `rat ` 4 + version 1 + header 2312 + nonce 12 + bucket 256
+ tag 16 = **2601-byte `rat ` frame**, i.e. **2622 bytes on the wire**. The
2272 extra header bytes are the sender's ML-KEM-768 ratchet key and the
ciphertext to the receiver's; the 256-byte bucket applies unchanged inside
them.
Both floors hold whatever the body length. The 32768 bucket yields a
32862-byte classical frame and a 35113-byte hybrid frame, both under the 65535
Noise body cap.
The ML-KEM-768 ciphertext appears in two places: the one-shot handshake prelude
(`version = 2`, 1095 bytes once per session), and every `rat ` header after the
first hybrid ratchet step (`kem_pub[1184] || kem_ct[1088]`). Epoch 0 of a chat
is always classical, so the first `rat ` frame of a friend relationship uses
the 40-byte header.
`fil ` chunks are deliberately **not** padded. They are raw file bytes paced
through the accept token bucket, and padding them would either cut the usable
chunk size or spend the 65535 frame cap on fill; the chunk size stays as
specified under `fil ` — file chunk.
This hides length, not timing: one Noise session per message, retry cadence and
circuit timing are unchanged and remain accepted costs (see
`docs/THREAT_MODEL.md`).
## Handshake
Noise pattern: `Noise_IK_25519_ChaChaPoly_BLAKE2s`
Prologue (both sides, before the first Noise handshake message):
- **Classical** (no PQ prelude, friend row has no `kem_pk`): `onionwire-v1`
(12 ASCII bytes, no NUL).
- **Hybrid** (a PQ prelude was sent/received): the exact byte layout
```
"onionwire-v2" || 0x00 || ct || 0x00 || ss_kem
```
where `onionwire-v2` is 12 ASCII bytes, `ct` is the 1088-byte ML-KEM-768
ciphertext from the prelude, and `ss_kem` is the 32-byte shared secret.
Initiator: `(ct, ss_kem) = ML-KEM-768.Encapsulate(friend.kem_pk)`.
Responder: `ss_kem = ML-KEM-768.Decapsulate(own_dk, ct)`. Both therefore
commit to the ciphertext and to the PQ secret: a modified `ct` changes the
prologue (and decapsulates to implicit-rejection garbage), so the Noise
handshake fails before msg 2.
Handshake payloads are empty. A non-empty decrypted handshake payload is a
hard fail.
### Sequence
Initiator knows the responder’s identity pubkey (pinned), x25519 prekey and
(if `kem_pk` is present) ML-KEM key from the invite (or roster).
0. **PQ prelude** — only when the responder’s roster row has `kem_pk`:
initiator → responder, one `version = 2` frame carrying the ML-KEM
ciphertext. If the row has no `kem_pk`, no prelude is sent and the prologue
is `onionwire-v1`.
1. **IK msg 1** — initiator → responder (framed, `version = 1`). Responder’s
Noise static is the invite `spk`.
2. Responder looks up the remote static in the roster **by prekey**.
Unknown prekey → close. This is how the answerer learns who is calling.
It then compares the friend row with how the session opened (see
[No downgrade](#no-downgrade)) and only then sends msg 2.
3. **IK msg 2** — responder → initiator (framed).
4. Both sides enter transport mode. Handshake hash `h` is 32 bytes (BLAKE2s).
5. **Identity proof, initiator first** — transport-encrypt a 96-byte proof,
send as one frame.
6. **Identity proof, responder** — same, one frame.
Proof encoding (96 bytes):
```
bytes[32] identity_pk // ed25519
bytes[64] ed25519_sign(identity_sk, h)
```
Verify:
- proof length is exactly 96
- `identity_pk` equals the **pinned** identity (initiator: invite/roster `k`;
responder: roster row found via prekey)
- `ed25519_verify(identity_pk, h, sig)` succeeds
Any mismatch is a fingerprint failure. Do not send application data. Do not
retry with a different key.
After proofs, the initiator sends **one** transport frame of application
ciphertext and closes. The responder decrypts that one frame and closes.
Compromise of the long-term x25519 prekey does not decrypt past transport
(IK + ephemeral). It does allow future impersonation at the Noise layer until
the peer notices the identity proof failing — so the proof is not optional.
With a PQ prelude, the transport secrets also mix `ss_kem`; a later
cryptographically relevant quantum adversary that recorded the session still
needs ML-KEM-768 broken to recover the Noise transport keys.
### No downgrade
The rule comes from the roster row, never from what arrives on the wire:
- friend row has `kem_pk` → **always** send the prelude; the responder requires
one. A `version = 1` opening from that peer is rejected with `prelude
required` before msg 2, the identity proofs, and any application frame.
- friend row has no `kem_pk` (added from a legacy v1 invite) → classical
session with the `onionwire-v1` prologue. The UI labels the friend as lacking
PQ protection.
- A prelude is not accepted for a friend row with no `kem_pk`: the responder
rejects it with `unexpected prelude` before msg 2, so the wire cannot upgrade
a classical row. `kem_pk` only enters a row from a signed v2 invite.
A v1-only build dialling a v2 install cannot parse `version = 2` as an opening
frame and hard-fails, and a v2 build will not send a prelude to a v1 peer.
That mixed-fleet break is accepted; there is no fallback path.
## Application plaintext
After decrypt, classify the plaintext:
| Prefix (4 bytes) | Kind | If unknown / invalid |
|---|---|---|
| `rat ` | Double Ratchet chat frame (see Ratchet) | drop |
| `loc ` | locator update | drop |
| `prf ` | profile | drop |
| `inv ` | Monero invoice | drop |
| `rcp ` | Monero receipt claim | drop |
| `tip ` | Monero tip (receipt + memo) | drop |
| `png ` | ping (reserved; classify and drop) | drop |
| `fil ` | file chunk | drop |
| `[a-z][a-z][a-z] ` | unknown typed frame | **drop** (not chat) |
| anything else | chat | store as a chat line |
`rat ` is classified before the `[a-z]{3} ` catch-all, so a peer that does not
implement the ratchet drops a chat frame instead of rendering ciphertext as a
chat line. Older builds that stored `rat `-prefixed bytes as chat are obsolete;
upgrade both sides.
A peer that does not implement a typed prefix MUST still drop
`[a-z]{3}<space>…` rather than render it as chat.
Chat MUST NOT begin with three lowercase ASCII letters and a space. (Inside a
`rat ` frame the plaintext is a chat line and is not re-classified.)
Hex on the wire is lowercase on encode; decode accepts either case. No `0x`
prefix.
### Application-frame signatures
`loc`, `prf`, `inv`, `rcp`, and `tip` each carry an ed25519 signature over the
**fields**, not the 4-byte typed prefix. Encode MUST sign the domain-separated
form (type tag, then each field, `0x00` separators). Verify MUST accept that
form and, for mixed-version peers, the legacy untagged LF-joined layout.
Anything else fails closed. Do not emit the legacy layout.
The invite string is separate and uses `onionwire-invite-v2` (see Invite).
Legacy acceptance is one switch, `LEGACY_SIGS`, default **on**. Every fallback
listed below reads it; with it off, verification accepts only the emitted
(tagged) form. It is a local capability constant, not a wire field: it is never
sent, and a peer cannot negotiate it.
| frame | emitted | accepted inbound |
| --- | --- | --- |
| invite | `onionwire-invite-v2`, `0x00`-separated over `k`, `o`, `spk`, `kem` | same; `onionwire:v1` over `onionwire-invite-v1` `0x00`-separated `k`,`o`,`spk`, or over `k \|\| o \|\| spk` (legacy only) |
| `loc ` | `"onionwire-loc-v1"` `0x00` `onion` `0x00` `ts` | same; `onion \|\| LF \|\| ts` (legacy only) |
| `prf ` | `"onionwire-prf-v1"` `0x00` `name` `0x00` `bio` `0x00` `xmr_addr` `0x00` `ts` | same; the four fields joined by LF (not yet gated — see below) |
| `inv ` | `"onionwire-inv-v1"` `0x00` `amount_atomic` `0x00` `address` `0x00` `memo` `0x00` `ts` | same; the four fields joined by LF (legacy only) |
| `rcp ` | `"onionwire-rcp-v1"` `0x00` `txid` `0x00` `amount_atomic` `0x00` `address` `0x00` `ts` | same; the four fields joined by LF (legacy only) |
| `tip ` | `"onionwire-tip-v1"` `0x00` `txid` `0x00` `amount_atomic` `0x00` `address` `0x00` `memo` `0x00` `ts` | same; the five fields joined by LF (legacy only) |
The tag suffixes do say `-v1`; that is the tag's own version, not the invite
string version.
`prf ` is the one frame whose legacy fallback is not yet gated: it is accepted
unconditionally in this revision and moving it under `LEGACY_SIGS` is a
separate change.
**Mixed-fleet consequence.** Older builds verify only the untagged bytes, so
they reject every tagged signature from a new sender — including `tip `, which
older builds emitted and verified untagged. That direction needs the peer
updated before tips flow. The reverse works while `LEGACY_SIGS` is on: a new
build verifies an old sender's untagged `loc`/`prf`/`inv`/`rcp`/`tip` and an
`onionwire:v1` invite. Turning the switch off is a fleet-wide cutover, not a
per-peer choice.
### `loc ` — locator update
Sent when the sender rotated their onion and the receiver is reachable.
```
loc <onion>\n<ts>\n<sig_hex>
```
- `onion` — v3 onion (56 base32 `a-z2-7` chars + `.onion`)
- `ts` — unix seconds, decimal ASCII
- `sig_hex` — 64-byte ed25519, 128 hex chars
- the `loc ` prefix is **not** signed
**Current signature (encode this):**
```
ed25519_sign(identity_sk,
"onionwire-loc-v1" || 0x00 || onion || 0x00 || ascii(ts))
```
**Legacy accept:** a signature over `onion || LF || ascii(ts)` is still
accepted on verify while `LEGACY_SIGS` is on, so old loc frames verify. New loc
frames MUST use the domain-separated form. Do not emit legacy.
Apply only if **all** of:
- the Noise session’s peer identity is already in the roster
- signature verifies under that identity
- `ts` is strictly greater than the stored `onion_updated_at`
Otherwise drop. Unknown pubkeys are not inserted from `loc`. There is no
directory: if you rotated while they were offline, they cannot find you until
they paste a new invite.
### `prf ` — profile
```
prf <display_name>\n<bio>\n<xmr_addr>\n<ts>\n<sig_hex>
```
Limits: name ≤ 64 bytes, bio ≤ 512 bytes. No newlines in those fields.
`xmr_addr` may be empty; if non-empty it MUST be a checksummed Monero address
(see invoices). The `prf ` prefix is **not** signed.
**Current signature (encode this):**
```
ed25519_sign(identity_sk,
"onionwire-prf-v1" || 0x00 || name || 0x00 || bio || 0x00 || xmr_addr || 0x00 || ascii(ts))
```
**Legacy accept:** a signature over the four fields joined by LF is still
accepted on verify. New profile frames MUST use the domain-separated form.
Do not emit legacy. This fallback is not yet read through `LEGACY_SIGS`.
Apply only for an existing friend, valid signature, newer `ts`. Not a public
profile. Not a directory.
### `inv ` — invoice (we want to receive)
```
inv <amount_atomic>\n<address>\n<memo>\n<ts>\n<sig_hex>
```
`amount_atomic` is decimal piconero (integer string, > 0). `address` is a
Monero mainnet/stagenet standard, subaddress, or integrated address with a
valid Keccak checksum. The `inv ` prefix is **not** signed.
**Current signature (encode this):**
```
ed25519_sign(identity_sk,
"onionwire-inv-v1" || 0x00 || amount_atomic || 0x00 || address || 0x00 || memo || 0x00 || ascii(ts))
```
**Legacy accept:** a signature over the four fields joined by LF is still
accepted on verify while `LEGACY_SIGS` is on. New invoices MUST use the
domain-separated form. Do not emit legacy.
The frame is a signed claim, not a payment. It is one-shot: if the peer onion
is down, the send fails. There is no queued invoice.
### `rcp ` — receipt claim (we paid)
```
rcp <txid>\n<amount_atomic>\n<address>\n<ts>\n<sig_hex>
```
The `rcp ` prefix is **not** signed.
**Current signature (encode this):**
```
ed25519_sign(identity_sk,
"onionwire-rcp-v1" || 0x00 || txid || 0x00 || amount_atomic || 0x00 || address || 0x00 || ascii(ts))
```
**Legacy accept:** a signature over the four fields joined by LF is still
accepted on verify while `LEGACY_SIGS` is on. New receipts MUST use the
domain-separated form. Do not emit legacy.
Signature proves which friend sent the claim. It does **not** prove money
moved. Local `verified=1` only if a user-hosted `monero-wallet-rpc` returns
one transfer row with the same non-empty `txid`, `amount`, and `address`
(conjunction, not OR). RPC down or an unsynced daemon → stay unverified.
Wallet RPC is loopback HTTP Digest; it is not this protocol.
### `tip ` — tip (we paid, with memo)
Sent after a chain transfer, together with `rcp `. One-shot.
```
tip <txid>\n<amount_atomic>\n<address>\n<memo>\n<ts>\n<sig_hex>
```
The `tip ` prefix is **not** signed.
**Current signature (encode this):**
```
ed25519_sign(identity_sk,
"onionwire-tip-v1" || 0x00 || txid || 0x00 || amount_atomic || 0x00 ||
address || 0x00 || memo || 0x00 || ascii(ts))
```
**Legacy accept:** a signature over the five fields joined by LF is still
accepted on verify while `LEGACY_SIGS` is on. New tips MUST use the
domain-separated form. Do not emit legacy.
`memo` MUST NOT contain newlines. Same address and amount rules as invoices.
A peer that does not implement `tip ` MUST drop it as an unknown typed prefix,
not render it as chat.
### `png ` — ping (reserved)
Classified as ping and dropped. No ping body is defined in v1. Implementations
MUST NOT emit `png ` and MUST drop it inbound.
### `fil ` — file chunk
Cap: 1 MiB reconstructed file. No resume. One Noise session per chunk.
The sender is responsible for fitting the receiver's documented rendezvous
budget (30 accepts / 60s, burst 10). Chunks MUST be paced so the average
interval between send attempts stays at least 3s. A sender MAY retry an
individual chunk a bounded number of times (this tree: 3). Exhausting retries
fails the transfer. No outbox, no resume, no continuation under a new
`xfer_id`.
```
fil <xfer_id_hex>\n<filename>\n<sha256_hex>\n<idx>/<total>\n<raw bytes>
```
- `xfer_id` — 16 random bytes (32 hex)
- `filename` — 1–128 bytes, no `/`, NUL, newline, `.`, or `..`; no C0/C1 controls or bidi/format marks (U+202A–U+202E, U+2066–U+2069, U+200E, U+200F, U+200B, U+200C)
- `sha256` — SHA-256 of the **entire** file (64 hex), repeated on every chunk
- `idx` is 0-based; `total` ≥ 1; `idx < total`
- last line is raw chunk bytes (not hex), length chosen so the framed Noise
ciphertext stays ≤ 65535 (account for a 16-byte Poly1305 tag plus ASCII header)
Chunks MUST arrive in order for a given `xfer_id`. A bad chunk or hash
mismatch deletes the partial. Empty files are one chunk. Successful receive
is a chat line `[file] name (N bytes)`, never the raw frame.
### Chat
A chat send is ratcheted: the wire form of a chat message is a `rat ` frame
(see “Ratchet (chat layer)”), and the plaintext inside that frame is the chat
line below, padded to a length bucket first (see
[Length buckets](#length-buckets)). A bare chat frame with no typed prefix is
still accepted inbound as a chat line (older peers), but MUST NOT be emitted.
UTF-8 is not enforced for chat text: invalid bytes become U+FFFD (the
implementation does not drop the row). Control and bidi formatting
characters are stripped at ingest and at render: C0 0x00–0x1F except
tab and newline, DEL (0x7F), C1 U+0080–U+009F, U+202A–U+202E,
U+2066–U+2069, U+200E, U+200F, U+200B, U+200C. U+200D (ZWJ) is kept
so emoji sequences stay intact. `fil ` filenames must not contain
those characters (tab and newline included). Displayed as a line.
A chat line is at most 32766 bytes (the largest bucket minus the 2-byte
`pad_len` header); a longer body is a protocol error, not a queued message. See
[Length buckets](#length-buckets).
## Ratchet (chat layer)
Chat is the only application payload that is ratcheted. A chat send is
Double-Ratchet encrypted first, and the resulting `rat ` frame is the
application plaintext that a normal one-shot Noise session carries (handshake,
one application frame, close — see Transport). Nothing else changes about the
session.
The ratchet header is **inside** the Noise transport message, never in clear on
the wire. A plaintext header (`dh_pub || N || PN`) would hand an observer
per-message counters and ratchet-key changes for no benefit — the Noise session
already hides the frame, so the header is authenticated as AEAD associated data
instead.
### Frame
```
"rat " 4 bytes (0x72 0x61 0x74 0x20)
version 1 byte 0x01 (classical) or 0x02 (hybrid)
-- version 0x01: classical header, 40 bytes
header 40 bytes dh_pub[32] || N uint32 BE || PN uint32 BE
nonce 12 bytes random, per message
ciphertext n+16 ChaCha20-Poly1305 ciphertext || tag
-- version 0x02: hybrid header, 2312 bytes
header 2312 bytes dh_pub[32] || N uint32 BE || PN uint32 BE
|| kem_pub[1184] || kem_ct[1088]
nonce 12 bytes random, per message
ciphertext n+16 ChaCha20-Poly1305 ciphertext || tag
```
- `dh_pub` — the sender's current X25519 ratchet public key (32 bytes).
- `N` — the index of this message in the sender's current sending chain,
counting from 0.
- `PN` — how many messages the sender sent in its *previous* sending chain.
- `kem_pub` — the sender's current ML-KEM-768 ratchet encapsulation key
(1184 bytes).
- `kem_ct` — an ML-KEM-768 ciphertext (1088 bytes) that the sender
encapsulated to the *receiver's current* ratchet KEM key. It is repeated on
every frame of a chain a hybrid step established, so a lost first frame does
not wedge the chain.
- Associated data is the whole header for the version in use, exactly as
serialized above. A tampered `dh_pub`, `N`, `PN`, `kem_pub` or `kem_ct`
therefore fails closed.
- The ChaCha20-Poly1305 key is the message key from `KDF_CK`. The 12-byte nonce
is random per message, not a chain counter.
- A chat frame's minimum size depends on the header version, not the body: an
empty chat line still pads to the 256-byte bucket. Version `0x01` is 329
bytes (5 + 40 + 12 + 256 + 16); version `0x02` is 2601 bytes
(5 + 2312 + 12 + 256 + 16). A hybrid message therefore carries 2272 more
header bytes than a classical one. See [Length buckets](#length-buckets).
- On the wire those become 350 bytes for `0x01` (329 + the Noise 16-byte tag +
the 5-byte framing header) and 2622 bytes for `0x02`. The 350-byte floor is
the classical case only.
- A `rat ` frame with no padding at all cannot occur for chat; the bare frame
overhead (empty ciphertext plaintext) is 73 bytes for `0x01`
(5 + 40 + 12 + 16) and 2345 bytes for `0x02` (5 + 2312 + 12 + 16).
- A receiver MUST reject a frame without the `rat ` prefix, a version other than
`0x01`/`0x02`, or a frame shorter than its version's minimum.
- The frame must fit the Noise body cap (65535 bytes, including the 16-byte
Poly1305 tag), so a `rat ` frame is at most 65519 bytes. A maximal hybrid
plaintext is therefore 63174 bytes, still far above the chat line limit.
- A `rat ` frame is one Noise body: the `fil ` chunk-pacing rules do not apply,
and the receive token bucket counts rendezvous accepts, not bytes, so the
larger hybrid header changes neither.
Because the header rides inside Noise, an observer sees one opaque ciphertext
per message: no message counts, no ratchet keys, and nothing that marks a first
message of a chain versus a later one.
### KDFs
Signal's constructions, with a second domain for hybrid steps:
```
KDF_RK(root, dh_out): # v1: epoch 0, classical friends
okm = HKDF-SHA256(salt = root, ikm = dh_out,
info = "onionwire-ratchet-v1-kdfrk", L = 64)
new_root = okm[0..32]
chain_key = okm[32..64]
KDF_RK_hybrid(root, dh_out, ss_kem): # v2: every hybrid ratchet step
okm = HKDF-SHA256(salt = root, ikm = dh_out || ss_kem,
info = "onionwire-ratchet-v2-kdfrk", L = 64)
new_root = okm[0..32]
chain_key = okm[32..64]
KDF_CK(chain_key):
message_key = HMAC-SHA256(chain_key, 0x01)
next_chain_key = HMAC-SHA256(chain_key, 0x02)
```
`HKDF` is RFC 5869 with SHA-256, `HMAC` is SHA-256. The two `KDF_RK` forms
differ in **both** input shape and info string on purpose: `ikm` is 32 bytes for
v1 and `dh_out || ss_kem` (64 bytes) for v2, and the domain strings are
distinct. There is no way to derive a v2 chain without a real `ss_kem`, and a
classical derivation can never be mistaken for a hybrid one.
Each side of an epoch derives its chains from one shared input with `KDF_RK`
called **twice**:
```
epoch_chains(root, shared) -> (new_root, ck_lo, ck_hi): # v1
(root1, ck_lo) = KDF_RK(root, shared)
(root2, ck_hi) = KDF_RK(root1, shared)
new_root = root2
epoch_chains_hybrid(root, dh_out, ss_kem) -> (new_root, ck_lo, ck_hi): # v2
(root1, ck_lo) = KDF_RK_hybrid(root, dh_out, ss_kem)
(root2, ck_hi) = KDF_RK_hybrid(root1, dh_out, ss_kem)
new_root = root2
```
`lo` is the lexicographically lower of the pair's two ratchet public keys and
`hi` the higher, comparing the 32 raw bytes. The chain a peer sends on is
`ck_lo` if `sender_pub <= receiver_pub`, else `ck_hi`; the receiving chain is the
other one. The epoch's chains are a pure function of the *unordered* pair, and
the second `KDF_RK` call's root is the epoch's new root.
### Bootstrap
The bootstrap epoch is derived, never exchanged: the Noise handshake is frozen
and carries no payload, so there is no wire field to hand over an initial
ratchet public key. Both peers instead derive it from key material they already
have from the invite/roster (identity pubkey and signed prekey):
```
shared = X25519(my_prekey_sk, peer_prekey_pk) // 32 bytes
hk = HKDF-SHA256(salt = "onionwire-ratchet-v1-bootstrap",
ikm = shared)
root_key = hk.expand("root", 32)
my_secret = hk.expand("ratchet-key" || my_identity_pk, 32)
peer_secret = hk.expand("ratchet-key" || peer_identity_pk, 32)
my_ratchet = keypair(my_secret) // x25519 secret/public + ML-KEM-768
peer_ratchet = keypair(peer_secret) // derived by both sides, same values
state = bootstrap(root_key, my_ratchet,
peer_ratchet.x25519_pub,
peer_ratchet.kem_pub if the friend row carries kem_pk else None)
```
`HKDF.expand` above is the RFC 5869 expand step (no second extract). The two
identity public keys are public (invite/roster), so either peer computes its own
secrets and the peer's, and both agree with no new wire field. The ML-KEM half of
each initial ratchet keypair is derived from that keypair's X25519 secret, so the
peer's KEM ratchet public key needs no wire field either:
```
kem_seed = HKDF-SHA256(salt = "ratchet-kem", ikm = x25519_secret).expand("seed", 64)
kem_pub = ML-KEM-768 encapsulation key from kem_seed
```
Then:
```
shared = DH(my_secret, remote_pub)
(new_root, ck_lo, ck_hi) = epoch_chains(root_key, shared) // v1: epoch 0 is classical
send_ck = chain_for(my_pub, remote_pub) // ck_lo or ck_hi
recv_ck = chain_for(remote_pub, my_pub)
send_n = recv_n = 0, PN = 0, established = false
```
Fresh entropy enters at the first DH ratchet step; the bootstrap epoch itself is
prekey-bound (see [THREAT_MODEL.md](THREAT_MODEL.md)).
### Hybrid ratchet steps, and why epoch 0 stays classical
Every ratchet keypair is now `{x25519, ML-KEM-768}`. On a step the peer that
rotates encapsulates to the receiver's **current** ratchet KEM key and puts
`kem_pub` (its new key) and `kem_ct` (that ciphertext) in the header. The
receiver decapsulates with the key it already holds, so both sides feed
`KDF_RK_hybrid` the same `(X25519 DH, ss_kem)` pair and derive the same chains.
No extra round trip is added: the KEM material rides on the rotation frame
itself, and is repeated on every later frame of that chain so a lost first frame
is harmless.
**Epoch 0 cannot be per-session, so it stays classical.** Epoch 0's root is
derived from the two long-lived signed prekeys precisely so that neither side
needs a wire field and both converge even when both send first. The hybrid Noise
session does carry an `ss_kem` (see Transport), but each chat message is its own
one-shot Noise session: a fresh encapsulation, therefore a different `ss_kem` for
every dial, and *different* sessions for the two peers' first sends. Binding the
epoch-0 root to that secret would make the root a function of which session
carried which message, so:
- two peers sending first would derive different epoch-0 roots and could not
read each other at all, and
- even a single direction would break at the second message, because message 2
would arrive on a different Noise session with a different `ss_kem` while the
receiver still holds the root from message 1.
There is no way to keep both "no wire field, both-send-first convergence" and a
per-session secret in epoch 0 without replacing the one-shot session model, which
is out of scope. Epoch 0 is therefore derived exactly as before, with the v1
`KDF_RK`, and the KEM secret enters at the **first rotation after
`established`**. The first rotation is hybrid even for the bootstrap tie-break
rotation: that is what closes the window two round trips in.
Consequences, stated exactly:
- Every frame sent before the first hybrid step (the whole of epoch 0, in both
directions, plus any outbox row encoded on it) is protected by X25519 only. A
harvest-now adversary who later breaks X25519 can read those frames. This is
the residual window and it does not shrink with more messages, only with the
first rotation.
- Every frame on a chain established by a hybrid step additionally requires the
ML-KEM-768 secret. Breaking X25519 alone does not open it.
- A frame that carries a new `dh_pub` but no KEM section is **rejected**
(`hybrid step required`); a KEM section on a non-KEM friend is rejected too.
There is no classical fallback once a session has KEM material.
**Convergence when both peers send first.** Either peer may send immediately on
the bootstrap epoch, so two peers can each build a sending chain before either
has received anything. Because the epoch's two chains come from the unordered
pair, both derive both directions and each sends on its own, with no
initiator/responder role. The only tie-break needed is for the *first* rotation:
the peer whose ratchet public key is lexicographically lower rotates — but only
after it has received a bootstrap-epoch frame (see `established` below); the
other adopts that new key as a normal DH step and only then rotates. From the
second epoch on, every rotation is a reply to an adopted key, so no tie-break is
needed and the ratchet alternates.
**Why it stays in lockstep.** A DH ratchet step happens only on a frame whose
`dh_pub` has not been adopted yet, and the side that steps is the side that
receives. A peer cannot rotate twice without having received the other side's
rotation first, so at most one rotation is ever in flight, and both peers feed
`KDF_RK` the same `(root, dh)` pairs in the same causal order.
### Receiving
On a decrypted `rat ` frame (the outer Noise session has already been verified,
so the peer identity is pinned):
1. Parse; reject a bad prefix or version, and a frame shorter than its
version's minimum (73 bytes for `0x01`, 2345 for `0x02`).
2. If `(dh_pub, N)` is in the skipped-key store: open with that key, **delete it**
from the store, deliver. A replay of the same frame then fails closed because
the key is gone.
3. Else if `dh_pub` equals the adopted remote ratchet public key, this is the
current receiving chain:
- `N < recv_n` → reject (message key already used).
- `N - recv_n > MAX_SKIP` → reject.
- Derive message keys for `recv_n .. N` into the skipped store, derive the
key for `N`, open, set `recv_n = N + 1`.
- On the *first* frame received in this state (`established == false`): set
`established`, and if `my_pub < remote_pub`, rotate the sending chain —
fresh `{x25519, ml-kem}` keypair; for a hybrid friend encapsulate to
`remote_kem_pub` and derive with `epoch_chains_hybrid(root, DH(new_secret,
remote_pub), ss)`, for a classical friend `epoch_chains(root, DH(...))`;
new sending chain for `new_pub → remote_pub`; `PN = old send_n`;
`send_n = 0`. The receiving chain is untouched.
4. Else it is a ratchet key not adopted yet: run a full DH ratchet step. A
session that holds `remote_kem_pub` rejects a frame with no KEM section, and
a session without KEM material rejects a frame that has one.
### DH ratchet step
On a frame whose `dh_pub` differs from the adopted remote public key:
1. **Retire the current receiving chain.** `PN` is how many messages the peer
sent in it, so:
- `PN < recv_n` → reject (used message key).
- `PN - recv_n > MAX_SKIP` → reject.
- Derive `recv_n .. PN` into the skipped store, tagged with the retired
remote public key, so stragglers of the old chain still decrypt.
2. **Receiving half of the step**, on the pair `(my current secret, frame.dh_pub)`:
`shared = DH(my_secret, frame.dh_pub)`. For a hybrid step also
`ss_kem = ML-KEM.Decaps(my_current_ratchet_kem_secret, frame.kem_ct)`, then
`(root_a, ck_lo, ck_hi) = epoch_chains_hybrid(root, shared, ss_kem)`;
otherwise `(root_a, ck_lo, ck_hi) = epoch_chains(root, shared)`.
`recv_ck = chain_for(frame.dh_pub, my_pub)`, then open the frame with this
chain exactly as in step 3 above (it must be within `MAX_SKIP` of index 0).
3. **Sending half:** generate a fresh ratchet keypair `{x25519, ml-kem}`. For a
hybrid step encapsulate to `frame.kem_pub` (`(kem_ct, ss_kem) =
ML-KEM.Encaps(frame.kem_pub)`), derive
`(root, ck_lo, ck_hi) = epoch_chains_hybrid(root_a, DH(new_secret,
frame.dh_pub), ss_kem)` and keep `kem_ct` in the state so every frame of the
new sending chain carries it; otherwise `epoch_chains(root_a, DH(...))`.
`send_ck = chain_for(new_pub, frame.dh_pub)`, `remote_pub = frame.dh_pub`,
`remote_kem_pub = frame.kem_pub`, `PN = old send_n`, `send_n = 0`,
`established = true`, `recv_hybrid = frame has a KEM section`.
4. The frame is opened with the *new* receiving chain's message key. If the AEAD
open fails, nothing is applied: the state must be byte-identical to before
the frame. (A tampered `kem_ct` yields a different `ss_kem` through ML-KEM's
implicit rejection, and the AEAD then fails; a tampered `kem_pub` is inside
the AAD, so it fails the same way.)
The next frame this side sends therefore carries the new `dh_pub`, which is what
lets the peer step too.
### Bounds and replay
- `MAX_SKIP = 2000`. Checked on both jumps: `N - recv_n` on the current chain
and `PN - recv_n` while retiring one. `jump == 2000` is accepted,
`jump == 2001` is rejected (`MaxSkipExceeded`) and leaves the state untouched.
- `MAX_SKIPPED_KEYS = 2000` stored message keys. When the store is at the cap,
inserting a new key evicts the **oldest-inserted** entry first — insertion
order, not `N` order.
- A skipped key is removed the moment it decrypts a frame, so a replayed frame
fails closed (`UsedMessageKey` or an AEAD failure).
- Every bound is validated before any state mutation. A rejected or tampered
frame must leave the state byte-identical.
### State at rest
`ratchet_sessions` in the SQLCipher store: one row per friend
(`friend_id` primary key, `FOREIGN KEY` → `friends.id` `ON DELETE CASCADE`,
`state BLOB NOT NULL`, `updated_at`). The blob is version byte `0x02` followed by
the implementation's serialized ratchet state:
```
0 version 0x02
1..211 fixed prefix: root, local secret/public, remote public,
send_ck/send_n, recv_ck/recv_n, PN, established, flags,
skipped-count
then remote ratchet KEM public key (1184 bytes) if flag 0x01
then pending KEM ciphertext (1088 bytes) if flag 0x02
(flag 0x04 marks a receiving chain established hybrid)
then skipped keys, dh_pub[32] || n u32 BE || message key[32]
```
The state is device-local: it is **never** transmitted, and its layout is not
part of this wire protocol. The store is encrypted as a whole, so the blob is
ciphertext on disk.
**Hard cut.** Version `0x01` is the pre-hybrid layout, which had no KEM ratchet
key and no pending ciphertext. It is **dropped, not migrated**: on load, a v1
blob is deleted and the session re-bootstraps from the two prekeys, exactly the
way an `F8` prekey rotation drops state. Nothing is half-read, and epoch 0 comes
back identical because its derivation did not change. A *corrupt* v2 blob or one
written by a **newer** version is reported as an error instead — those are not an
old format, and silently resetting them would be a downgrade. The same cut
applies to any peer whose prekey or KEM key changes.
### Not ratcheted
`loc `, `prf `, `inv `, `rcp `, `tip `, `png ` and `fil ` frames — and every
file chunk — keep the one-shot Noise shape: one handshake per application frame,
no ratchet, no persistent session. Only chat is ratcheted.
### Prekey change resets the epoch
A peer whose prekey changes invalidates the bootstrap epoch on both sides, and
the stale state is dropped locally, so the next chat frame starts a fresh
bootstrap epoch. Frames sent under the dropped epoch are not readable
afterwards. There is no key-confirmation exchange and no in-band reset command;
the new invite is the signal.
## Invite (out of band)
Not a QR graphic. A single ASCII string, max 4096 characters:
```
onionwire:v2:k=<64 hex>:o=<v3 onion>:spk=<64 hex>:kem=<base64url pk>:sig=<128 hex>
```
Field order in the string is not significant; duplicate or unknown fields are
rejected. `k` is the identity pubkey, `spk` the x25519 prekey, `o` the current
locator, and `kem` the ML-KEM-768 encapsulation key (1184 bytes) encoded as
unpadded base64url (1579 characters). A v2 invite is about 1.9 KB, still well
under the 4096-character cap.
**Current signature (encode this):**
```
ed25519_sign(identity_sk,
"onionwire-invite-v2" || 0x00 || k_ascii || 0x00 || o_ascii || 0x00 ||
spk_ascii || 0x00 || kem_ascii)
```
`k_ascii` / `spk_ascii` are the hex strings as they appear in the invite
(lowercase); `kem_ascii` is the base64url field value after `kem=`. Because the
signature covers `kem_ascii`, removing the field or substituting a different
key fails verification — that is the anti-strip/anti-substitution property.
**Legacy accept (`onionwire:v1`):** a v1 invite has no `kem` field. Decode
accepts it while `LEGACY_SIGS` is on and yields a friend with no `kem_pk`, i.e.
a classical peer; with the switch off a v1 invite fails closed. A v1
signature is accepted in either historical form: the tagged
`"onionwire-invite-v1" || 0x00 || k || 0x00 || o || 0x00 || spk` or the raw
concatenation `k || o || spk` (no tag, no separators), so old invites keep
verifying. `onionwire:v2` MUST have `kem=` and MUST verify over the v2 domain;
a v2 body relabelled v1 does not verify.
Encode MUST emit `onionwire:v2` only. Unknown `k`: prompt. Same `k`: update
locator, prekey and KEM key on that row (never a second friend), and drop the
stored ratchet state if either key changed.
## What v1 will not grow into
No DHT, no directory server, no hosted/server-side outbox, no XMPP/Prosody, no
C-tor fallback, no multi-device, no A/V, no STUN/ICE/WebRTC, no system DNS for
friends.
A **local-only** chat retry queue is in v1. It is not a mailbox and it never
leaves the device. “No outbox” in this document means **no server-side**
store-and-forward.
Those are how Tox-over-Tor leaks (UDP DHT, mixed clearnet, “just one direct
path”). They are out of scope, not postponed.
## Versioning
- Frame `version` 1 (normal), frame `version` 2 (PQ prelude), invite
`onionwire:v2` (emit) and invite `onionwire:v1` (decode only) are this
document.
- A new handshake prologue or a new invite scheme is a breaking change. The
hybrid prologue and the prelude are exactly that: v1 peers cannot talk to a
friend that has a `kem_pk`.
- New typed prefixes (`xyz `) are backward compatible if old peers drop them.
- The `rat ` frame has its own version byte (`0x01` classical, `0x02` hybrid).
A different ratchet frame layout or a different KDF is a breaking change for
chat only: peers that disagree cannot read each other's chat, and every other
frame keeps working. A `0x02` frame from a peer whose roster row says
`classical`, or a `0x01` step from a hybrid peer, is rejected.

35
docs/README.md Normal file
View file

@ -0,0 +1,35 @@
# OnionWire docs
Read these in order if you are evaluating the protocol without the Rust:
1. **[PROTOCOL.md](PROTOCOL.md)** — wire format, handshake, invite, frames.
This is the document a second implementation would use.
2. **[THREAT_MODEL.md](THREAT_MODEL.md)** — what v1 claims, and what it
refuses to claim.
3. **[SECURITY_AUDIT.md](SECURITY_AUDIT.md)** — in-house review notes and
which findings are still open. **Not** a public third-party audit.
Operator / product docs:
- **[../README.md](../README.md)** — install, run, real flags, F-key map,
wallet/chain source, releases.
- **[TUI.md](TUI.md)** — screens and keybindings as the TUI actually handles them.
- **[WALLET.md](WALLET.md)** — loopback wallet RPC, chain source, spend-authority
warning, receipt verification.
- **[RELEASING.md](RELEASING.md)** — manual, batched releases (not one per merge),
the reproducible build recipe, and the signing key.
- **[VERIFY.md](VERIFY.md)** — checking a download: the dependency graph, the
wallet's real exposure, rebuilding a release and comparing bytes, and what
none of that proves.
- **[ARTI_UPGRADE.md](ARTI_UPGRADE.md)** — how to bump the in-process Tor crates.
Android build notes: [android/README.md](../android/README.md). SDK:
[crates/onionwire-sdk/README.md](../crates/onionwire-sdk/README.md).
Decision records and spike reports (history — not living operator docs):
- [arti-socks-feasibility.md](arti-socks-feasibility.md)
- [option-a-recommendation.md](option-a-recommendation.md)
- [cuprate-launch-spike.md](cuprate-launch-spike.md)
- [cuprate-android-spike.md](cuprate-android-spike.md)
- [payment-integration-plan.md](payment-integration-plan.md)

Some files were not shown because too many files have changed in this diff Show more