Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7665da997e | |||
|
|
90d982b369 |
||
| 488eb94e28 | |||
| 717a33b4c2 | |||
| 83e9527a5f | |||
| 3092b9d63e | |||
|
|
3aafaefae8 |
||
| dddf74f274 | |||
| a0b704cd09 | |||
|
|
a375ef9d1e |
||
|
|
3cd70ca9b5 |
||
| b5f3829c23 | |||
| 7c1da42e7b | |||
|
|
9d93fb5cfa |
||
| fb45143695 | |||
|
|
6216475b13 |
||
| 20d2d00e4d | |||
| 76f6661171 | |||
| 890620763f | |||
|
|
9b3a0ad177 |
||
|
|
ef149ac496 |
||
|
|
0d0b0b975d |
||
|
|
1d7cbd8503 |
||
|
|
dc45d9cb81 |
||
|
|
5a4701992e |
||
|
|
7d86fd6a03 |
||
|
|
a7b7792b3f |
||
|
|
b65c990014 |
||
|
|
0283e6bf48 |
||
|
|
5f2a6a184f |
||
| 4e8342b2d8 | |||
| 4cf0a09ceb | |||
| 713dbd9006 | |||
| d3f1a44ef6 | |||
| 56c0b67cdf | |||
| d1a8aeccd0 | |||
| d3a28a5c1c | |||
| af9077046b | |||
|
|
8f959e937f |
||
|
|
b8c52ca97d |
||
| 1b562ca149 | |||
|
|
625879e000 |
||
|
|
d64114ca1c |
||
|
|
53d7f47b89 |
||
| 36969a7e95 | |||
|
|
99ea4e17ac |
||
| 08bf6649df | |||
|
|
46baf67a14 |
||
| 5d10cb3d00 | |||
|
|
37b08595a4 |
||
| bd806a1f50 | |||
|
|
57d1bb0bd2 |
||
| 4216a6731f | |||
|
|
7a3c0055b3 |
||
|
|
b22abd7b2b |
||
| fec68e31ff | |||
|
|
7fa3edcdb4 |
||
| e26813809a | |||
|
|
c741b660e4 |
||
| 00bb95675f | |||
|
|
37690e3d48 |
||
| 9b827fc001 | |||
|
|
99581bec5e |
||
| a0b79d457d | |||
|
|
601f640f78 |
||
| 1031092192 | |||
|
|
7391c5b7a4 |
||
| d89539e8b0 | |||
| 174923f80f | |||
|
|
14a0d22b20 |
||
|
|
4e13242a44 |
||
|
|
a466c43764 |
||
| c550a197ac | |||
|
|
1e3eceabcb |
||
|
|
6c1fc5008a |
||
|
|
c776ea3e0c |
||
|
|
c877375ea5 |
||
| 02f8e4d914 | |||
| 06367b2949 | |||
|
|
5cdfbacf10 |
||
|
|
a37712f3af |
||
|
|
404ceea0f8 |
||
| 9f3745cd1d | |||
| d93e9c3276 | |||
| dca69bad6f | |||
| 0149e105b0 | |||
|
|
3bec3bffbf |
||
| b78e0fcb55 | |||
| fa58930678 | |||
| 73130b443f | |||
| 4ff5af3fab | |||
| 863adc22dd | |||
|
|
a9cb0d5758 | ||
|
|
cc1201d876 |
||
|
|
5fcd4ed643 |
||
|
|
041179eb89 |
||
| a1f5c878d3 | |||
|
|
f6a7daf892 |
||
| 6d815b0fe8 | |||
|
|
2f3d5d69c3 |
||
|
|
4136f36dd4 |
||
|
|
081bdfac3e |
||
|
|
f5e310fdf4 |
||
|
|
052879fa39 |
||
| 9322d885f8 | |||
|
|
971d8b3894 |
||
|
|
9eb054b10f |
||
| 25e4c67181 | |||
| 685ce89b29 | |||
| c1fda00080 | |||
| 3ddd370b3d | |||
| 01d3294282 | |||
|
|
6edcd65e96 |
||
|
|
8d80a4fd55 |
||
|
|
b4f8bb809c |
||
|
|
59175f6931 |
||
|
|
3f84021abb |
||
|
|
ed29131a67 |
||
| c5725856ad | |||
| dc8c3933cd | |||
| 460a5afb12 | |||
|
|
775f2e88be |
||
|
|
812c259f46 |
||
| 573bf4bf8d | |||
| 181c13647a | |||
| 0e866c096a | |||
|
|
b6447f76d6 |
||
|
|
5f19a56be3 |
||
|
|
a9117b8991 |
||
|
|
511c9e921d |
||
|
|
8986724848 |
||
|
|
d96de1d7f0 |
||
| dd7c749373 | |||
| 5f1500191e | |||
| 49756d2a2d | |||
| 948d9b4b0c | |||
|
|
0043fa0b34 |
||
|
|
99a4ab640e |
||
|
|
467510f096 |
||
| 2256d036d5 | |||
|
|
118191c541 |
||
| 94d29b8354 | |||
|
|
145036fda8 |
||
| 3769bd9a42 | |||
|
|
cb411da813 |
||
| b805bd4ad9 | |||
|
|
0a8105584f |
||
| 53b5e6c762 | |||
|
|
c65946bfd5 |
||
| d2d49d27c5 | |||
|
|
4d2528351b |
||
| fa0e4b2f6c | |||
| 803567635f | |||
|
|
f95c1e7ca7 |
||
|
|
db12f4838b |
||
| 69a7b106ee | |||
|
|
e697045515 |
||
| d203594294 | |||
|
|
0a91744924 |
||
| bc74b4f4af | |||
|
|
c00c9d4151 |
||
| fb87903137 | |||
|
|
a7daf2c768 |
||
| 0c21eb7bf0 | |||
|
|
3868452a4a |
||
| 82d6dd9082 | |||
| 95ca45dc17 | |||
|
|
5080652e3b |
||
| cd1acd3c0d | |||
|
|
0acf89a0b4 |
||
| 2df10124ef | |||
| 87196e2297 | |||
| 04fa7ec7f1 | |||
| 0c00c6f912 | |||
|
|
c1d13178b6 |
||
|
|
e9b4156cf5 |
||
| ca4c2c4562 | |||
|
|
519f0e66c3 |
||
|
|
cbe889024b |
||
|
|
b8fefe9c18 |
||
| 5ae9a8f7aa | |||
| 8cbdcbbd94 | |||
| b46d858a4d | |||
|
|
c3116eb19e |
||
|
|
2fa3466019 |
||
|
|
b1a6796742 |
||
|
|
eefa7e5cc6 |
||
|
|
86e20223cf |
||
| 14f9284463 | |||
| b99d96a145 | |||
|
|
3b44cb0faf |
||
|
|
0131803f9c |
||
|
|
9a1f50eadf |
||
| 5c43254111 | |||
| e3fb723a91 | |||
|
|
396e468f1a |
||
| 77f577fcf9 | |||
|
|
fcdabf8d13 |
||
| 0af97e144a | |||
|
|
c5e2cae694 |
||
|
|
294cedfbff |
||
| 8626da225b | |||
|
|
3860c3d56d |
||
|
|
9afa22a0bf |
||
|
|
adcf52b8e4 |
||
|
|
0a2bcf93a2 |
||
|
|
e6b6bc8dd6 |
||
| 773dacb062 | |||
|
|
e89dd9eaee |
||
| 25e029ed4e | |||
|
|
ffea4bf9df |
||
| 8ba1cf4c6c | |||
|
|
0134396588 |
||
| 143bf6e0d0 | |||
|
|
c5af978d14 |
||
|
|
d8a2ee35aa |
||
|
|
440a37caf0 |
||
|
|
11a021acb3 |
||
|
|
db208be05c |
||
|
|
bcf7ec31c1 |
||
| 462b5765bd | |||
| 4623f78a69 | |||
|
|
518ef30232 |
||
|
|
99a941b437 |
||
|
|
8949da1213 |
||
|
|
1b2c63b9b6 |
||
| 2f6f737106 | |||
| 2b7a306d43 | |||
|
|
186ec7436d |
||
| 24b5c93c43 | |||
| 724e0427b0 | |||
| 049b612169 | |||
|
|
b76bf46100 |
||
|
|
2cf9e8c7c6 |
||
| 407b11f2f8 | |||
| deaa8a7cfa | |||
|
|
bfbbdbf14f |
||
|
|
bcee6a72a6 |
||
| 4a06d794f1 | |||
| ba3c39cfe1 | |||
| fa53237968 | |||
|
|
6827b87a29 |
||
|
|
69672809ab |
||
|
|
dff37fe00e |
||
|
|
1aec007601 |
||
|
|
6f267a6aba |
||
| ad1b994c08 | |||
|
|
2ec88b0ce5 |
||
| 918fa4d8a8 | |||
|
|
e0bd4e4218 |
||
| 564036813a | |||
|
|
12db06b2ed |
||
|
|
c090f16dab |
||
| 598270b519 |
171 changed files with 49482 additions and 4106 deletions
|
|
@ -18,6 +18,22 @@ name: android-ci
|
||||||
# detection, and a gate that mis-detects hands out a green check for a suite
|
# 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
|
# that never ran. Here the runner's own paths filter decides — same mechanism
|
||||||
# ci.yml already uses.
|
# 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:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
|
|
@ -32,8 +48,7 @@ on:
|
||||||
pull_request:
|
pull_request:
|
||||||
paths:
|
paths:
|
||||||
- "android/**"
|
- "android/**"
|
||||||
- "crates/**"
|
- "crates/onionwire-sdk/**"
|
||||||
- "src/**"
|
|
||||||
- "Cargo.toml"
|
- "Cargo.toml"
|
||||||
- "Cargo.lock"
|
- "Cargo.lock"
|
||||||
- "scripts/build-android-local.sh"
|
- "scripts/build-android-local.sh"
|
||||||
|
|
@ -55,7 +70,11 @@ env:
|
||||||
ONIONWIRE_ANDROID_ABI: arm64-v8a
|
ONIONWIRE_ANDROID_ABI: arm64-v8a
|
||||||
ANDROID_IMAGE: debian:bookworm
|
ANDROID_IMAGE: debian:bookworm
|
||||||
ANDROID_CMDLINE_TOOLS_URL: https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
|
ANDROID_CMDLINE_TOOLS_URL: https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
|
||||||
RUST_TOOLCHAIN: "1.91"
|
# 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
|
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
|
# Distinct container prefix: run ids are per-workflow, so this workflow and
|
||||||
# android-release.yml can both be holding a container named "<prefix>-<n>".
|
# android-release.yml can both be holding a container named "<prefix>-<n>".
|
||||||
|
|
@ -72,10 +91,30 @@ jobs:
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: https://code.forgejo.org/actions/checkout@v4
|
uses: https://code.forgejo.org/actions/checkout@v4
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
- 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
|
- name: Record runner resources
|
||||||
|
if: steps.staleness.outputs.skip != 'true'
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "${GITHUB_WORKSPACE}"
|
cd "${GITHUB_WORKSPACE}"
|
||||||
|
|
@ -86,6 +125,7 @@ jobs:
|
||||||
ls -l /var/run/docker.sock || true
|
ls -l /var/run/docker.sock || true
|
||||||
|
|
||||||
- name: Ensure docker CLI
|
- name: Ensure docker CLI
|
||||||
|
if: steps.staleness.outputs.skip != 'true'
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
if ! command -v docker >/dev/null 2>&1; then
|
if ! command -v docker >/dev/null 2>&1; then
|
||||||
|
|
@ -101,6 +141,7 @@ jobs:
|
||||||
|
|
||||||
- name: Build APK + AAR (debug-signed) in bookworm container
|
- name: Build APK + AAR (debug-signed) in bookworm container
|
||||||
id: build
|
id: build
|
||||||
|
if: steps.staleness.outputs.skip != 'true'
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "${GITHUB_WORKSPACE}"
|
cd "${GITHUB_WORKSPACE}"
|
||||||
|
|
@ -111,8 +152,13 @@ jobs:
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
export DEBIAN_FRONTEND=noninteractive
|
export DEBIAN_FRONTEND=noninteractive
|
||||||
apt-get update
|
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 \
|
apt-get install -y --no-install-recommends \
|
||||||
openjdk-17-jdk-headless python3 unzip curl ca-certificates file build-essential pkg-config git
|
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
|
if [ ! -x /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager ]; then
|
||||||
mkdir -p /opt/android-sdk/cmdline-tools
|
mkdir -p /opt/android-sdk/cmdline-tools
|
||||||
curl -fsSL "$ANDROID_CMDLINE_TOOLS_URL" -o /tmp/cmdline-tools.zip
|
curl -fsSL "$ANDROID_CMDLINE_TOOLS_URL" -o /tmp/cmdline-tools.zip
|
||||||
|
|
@ -141,6 +187,12 @@ jobs:
|
||||||
rustc --version
|
rustc --version
|
||||||
cargo ndk --version
|
cargo ndk --version
|
||||||
du -sh /opt/android-sdk /cargo /cargo-target /gradle || true
|
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
|
# No keystore here on purpose: this is a verification build, not a
|
||||||
# release build. The script warns that Gradle fell back to the debug
|
# release build. The script warns that Gradle fell back to the debug
|
||||||
# key; that warning is expected in this job.
|
# key; that warning is expected in this job.
|
||||||
|
|
@ -161,9 +213,40 @@ jobs:
|
||||||
echo "=== unzip lib ==="
|
echo "=== unzip lib ==="
|
||||||
unzip -l "$apk" | grep -E 'lib/.+\.so' || true
|
unzip -l "$apk" | grep -E 'lib/.+\.so' || true
|
||||||
unzip -l "$apk" | grep "lib/$abi/libonionwire_sdk.so"
|
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 ==="
|
echo "=== classes.dex + Compose entrypoints ==="
|
||||||
unzip -l "$apk" | grep -E 'classes[0-9]*\.dex' | head -n3
|
unzip -l "$apk" | grep -E 'classes[0-9]*\.dex' | head -n3
|
||||||
echo "=== sha256 ==="
|
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" )
|
( 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) ==="
|
echo "=== apksigner (expect debug cert: this is a verification build) ==="
|
||||||
apksigner verify --print-certs "$apk" | sed -n '1,6p'
|
apksigner verify --print-certs "$apk" | sed -n '1,6p'
|
||||||
|
|
@ -171,6 +254,12 @@ jobs:
|
||||||
aapt dump badging "$apk" | sed -n '1,20p' || true
|
aapt dump badging "$apk" | sed -n '1,20p' || true
|
||||||
echo "=== sizes ==="
|
echo "=== sizes ==="
|
||||||
wc -c "$apk" "$aar"
|
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
|
} | tee dist/android-ci-verify.log
|
||||||
INNER
|
INNER
|
||||||
chmod +x .ci-android-verify.sh
|
chmod +x .ci-android-verify.sh
|
||||||
|
|
@ -178,8 +267,21 @@ jobs:
|
||||||
docker volume create "$CARGO_VOLUME" >/dev/null
|
docker volume create "$CARGO_VOLUME" >/dev/null
|
||||||
docker volume create "$TARGET_VOLUME" >/dev/null
|
docker volume create "$TARGET_VOLUME" >/dev/null
|
||||||
docker volume create "$GRADLE_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 rm -f "$BUILD_CONTAINER" >/dev/null 2>&1 || true
|
||||||
docker pull "$ANDROID_IMAGE"
|
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 \
|
docker create --name "$BUILD_CONTAINER" -i \
|
||||||
-e CARGO_TERM_COLOR=never \
|
-e CARGO_TERM_COLOR=never \
|
||||||
-e CARGO_BUILD_JOBS="$CARGO_BUILD_JOBS" \
|
-e CARGO_BUILD_JOBS="$CARGO_BUILD_JOBS" \
|
||||||
|
|
@ -193,7 +295,7 @@ jobs:
|
||||||
-e ONIONWIRE_REQUIRE_RELEASE_KEY=false \
|
-e ONIONWIRE_REQUIRE_RELEASE_KEY=false \
|
||||||
-e RUST_TOOLCHAIN="$RUST_TOOLCHAIN" \
|
-e RUST_TOOLCHAIN="$RUST_TOOLCHAIN" \
|
||||||
-e ANDROID_CMDLINE_TOOLS_URL="$ANDROID_CMDLINE_TOOLS_URL" \
|
-e ANDROID_CMDLINE_TOOLS_URL="$ANDROID_CMDLINE_TOOLS_URL" \
|
||||||
-e GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.jvmargs=-Xmx1024m -XX:MaxMetaspaceSize=384m -Dfile.encoding=UTF-8" \
|
-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 "$SDK_VOLUME":/opt/android-sdk \
|
||||||
-v "$CARGO_VOLUME":/cargo \
|
-v "$CARGO_VOLUME":/cargo \
|
||||||
-v "$TARGET_VOLUME":/cargo-target \
|
-v "$TARGET_VOLUME":/cargo-target \
|
||||||
|
|
@ -217,6 +319,7 @@ jobs:
|
||||||
ls -l dist/
|
ls -l dist/
|
||||||
|
|
||||||
- name: Verify artifacts
|
- name: Verify artifacts
|
||||||
|
if: steps.staleness.outputs.skip != 'true'
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "${GITHUB_WORKSPACE}"
|
cd "${GITHUB_WORKSPACE}"
|
||||||
|
|
|
||||||
|
|
@ -61,7 +61,9 @@ env:
|
||||||
ONIONWIRE_REQUIRE_RELEASE_KEY: "true"
|
ONIONWIRE_REQUIRE_RELEASE_KEY: "true"
|
||||||
ANDROID_IMAGE: debian:bookworm
|
ANDROID_IMAGE: debian:bookworm
|
||||||
ANDROID_CMDLINE_TOOLS_URL: https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
|
ANDROID_CMDLINE_TOOLS_URL: https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
|
||||||
RUST_TOOLCHAIN: "1.91"
|
# 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
|
DOCKER_STATIC_URL: https://download.docker.com/linux/static/stable/x86_64/docker-27.5.1.tgz
|
||||||
BUILD_CONTAINER: onionwire-android-${{ github.run_id }}
|
BUILD_CONTAINER: onionwire-android-${{ github.run_id }}
|
||||||
SDK_VOLUME: onionwire-android-sdk
|
SDK_VOLUME: onionwire-android-sdk
|
||||||
|
|
@ -225,8 +227,13 @@ jobs:
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
export DEBIAN_FRONTEND=noninteractive
|
export DEBIAN_FRONTEND=noninteractive
|
||||||
apt-get update
|
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 \
|
apt-get install -y --no-install-recommends \
|
||||||
openjdk-17-jdk-headless python3 unzip curl ca-certificates file build-essential pkg-config git
|
openjdk-17-jdk-headless python3 unzip curl ca-certificates file build-essential pkg-config git \
|
||||||
|
cmake
|
||||||
mkdir -p /root/.android
|
mkdir -p /root/.android
|
||||||
cp /src/.ci-android/onionwire-release.jks /root/.android/onionwire-release.jks
|
cp /src/.ci-android/onionwire-release.jks /root/.android/onionwire-release.jks
|
||||||
cp /src/.ci-android/onionwire-release.env /root/.android/onionwire-release.env
|
cp /src/.ci-android/onionwire-release.env /root/.android/onionwire-release.env
|
||||||
|
|
@ -263,6 +270,8 @@ jobs:
|
||||||
rustc --version
|
rustc --version
|
||||||
cargo ndk --version
|
cargo ndk --version
|
||||||
du -sh /opt/android-sdk /cargo /cargo-target /gradle || true
|
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"
|
scripts/build-android-local.sh "$ONIONWIRE_VERSION"
|
||||||
version="$ONIONWIRE_VERSION"
|
version="$ONIONWIRE_VERSION"
|
||||||
abi="${ONIONWIRE_ANDROID_ABI:-arm64-v8a}"
|
abi="${ONIONWIRE_ANDROID_ABI:-arm64-v8a}"
|
||||||
|
|
@ -289,8 +298,19 @@ jobs:
|
||||||
docker volume create "$CARGO_VOLUME" >/dev/null
|
docker volume create "$CARGO_VOLUME" >/dev/null
|
||||||
docker volume create "$TARGET_VOLUME" >/dev/null
|
docker volume create "$TARGET_VOLUME" >/dev/null
|
||||||
docker volume create "$GRADLE_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 rm -f "$BUILD_CONTAINER" >/dev/null 2>&1 || true
|
||||||
docker pull "$ANDROID_IMAGE"
|
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 \
|
docker create --name "$BUILD_CONTAINER" -i \
|
||||||
-e CARGO_TERM_COLOR=never \
|
-e CARGO_TERM_COLOR=never \
|
||||||
-e CARGO_BUILD_JOBS="$CARGO_BUILD_JOBS" \
|
-e CARGO_BUILD_JOBS="$CARGO_BUILD_JOBS" \
|
||||||
|
|
@ -306,7 +326,7 @@ jobs:
|
||||||
-e ONIONWIRE_VERSION="$VERSION" \
|
-e ONIONWIRE_VERSION="$VERSION" \
|
||||||
-e RUST_TOOLCHAIN="$RUST_TOOLCHAIN" \
|
-e RUST_TOOLCHAIN="$RUST_TOOLCHAIN" \
|
||||||
-e ANDROID_CMDLINE_TOOLS_URL="$ANDROID_CMDLINE_TOOLS_URL" \
|
-e ANDROID_CMDLINE_TOOLS_URL="$ANDROID_CMDLINE_TOOLS_URL" \
|
||||||
-e GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.jvmargs=-Xmx1024m -XX:MaxMetaspaceSize=384m -Dfile.encoding=UTF-8" \
|
-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 "$SDK_VOLUME":/opt/android-sdk \
|
||||||
-v "$CARGO_VOLUME":/cargo \
|
-v "$CARGO_VOLUME":/cargo \
|
||||||
-v "$TARGET_VOLUME":/cargo-target \
|
-v "$TARGET_VOLUME":/cargo-target \
|
||||||
|
|
@ -378,7 +398,14 @@ jobs:
|
||||||
needs: android
|
needs: android
|
||||||
# Pi runner, not docker-amd64: POST /releases from amd64 dind returns 422
|
# 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.
|
# with an empty body (core run 116). This job only curls the Forgejo API.
|
||||||
if: needs.android.result == 'success' && needs.android.outputs.dry_run != 'true'
|
# `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
|
runs-on: docker
|
||||||
timeout-minutes: 20
|
timeout-minutes: 20
|
||||||
steps:
|
steps:
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,12 @@ name: ci
|
||||||
# build (docs, android, scripts, sibling workflows, markdown). No required
|
# build (docs, android, scripts, sibling workflows, markdown). No required
|
||||||
# status checks on main, so a missing run is not a merge trap.
|
# status checks on main, so a missing run is not a merge trap.
|
||||||
# workflow_dispatch has no path filter — it always runs the suite.
|
# 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]
|
||||||
|
|
@ -27,21 +33,39 @@ on:
|
||||||
- ".forgejo/workflows/ci.yml"
|
- ".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: it resolves the root crate with
|
# The SDK job gets its own target volume: `crates/onionwire-sdk` is a
|
||||||
# `rustls` instead of `native-tls`, so sharing a target dir would thrash both
|
# separate cargo workspace with its own lockfile and its own crate set, so
|
||||||
# jobs' feature-unified artifacts.
|
# sharing a target dir with the root job would thrash both.
|
||||||
SDK_CARGO_TARGET_VOLUME: onionwire-target-ci-sdk
|
SDK_CARGO_TARGET_VOLUME: onionwire-target-ci-sdk
|
||||||
SDK_BUILD_CONTAINER: onionwire-ci-sdk-${{ github.run_id }}
|
SDK_BUILD_CONTAINER: onionwire-ci-sdk-${{ github.run_id }}
|
||||||
|
|
||||||
|
|
@ -53,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}"
|
||||||
|
|
@ -65,13 +118,14 @@ 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'
|
||||||
|
|
@ -80,12 +134,22 @@ jobs:
|
||||||
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
|
# `crates/onionwire-sdk` is a SEPARATE cargo workspace: its own Cargo.lock and
|
||||||
# a path dependency on the root crate, resolved with `rustls` instead of
|
# a path dependency on the root crate. The `test` job above therefore never
|
||||||
# `native-tls`. The `test` job above therefore never compiles it, so a
|
# compiles it, so a root-crate signature change (`Node::send` gaining the
|
||||||
# root-crate signature change (`Node::send` gaining the outbox result, the
|
# outbox result, the SQLCipher passphrase entry points) breaks the Android SDK
|
||||||
# SQLCipher passphrase entry points) breaks the Android SDK — and the tagged
|
# — and the tagged release AAR, since android-release.yml only builds on
|
||||||
# release AAR, since android-release.yml only builds on `v*.*.*` — while both
|
# `v*.*.*` — while both the root suites and local `cargo test` stay green.
|
||||||
# the root suites and local `cargo test` stay green. Build it here.
|
# 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:
|
sdk:
|
||||||
runs-on: docker
|
runs-on: docker
|
||||||
timeout-minutes: 120
|
timeout-minutes: 120
|
||||||
|
|
@ -93,7 +157,26 @@ 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
|
||||||
|
# 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
|
- name: cargo test + clippy for crates/onionwire-sdk on aarch64
|
||||||
|
if: steps.staleness.outputs.skip != 'true'
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "${GITHUB_WORKSPACE}"
|
cd "${GITHUB_WORKSPACE}"
|
||||||
|
|
@ -105,11 +188,12 @@ 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 "$SDK_CARGO_TARGET_VOLUME":/target \
|
-v "$SDK_CARGO_TARGET_VOLUME":/target \
|
||||||
-w /src \
|
-w /src \
|
||||||
"$RUST_IMAGE" \
|
"$RUST_IMAGE" \
|
||||||
sh -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src/crates/onionwire-sdk \
|
sh -euxc 'mkdir -p /src /target/tmp && tar xzf - -C /src && cd /src/crates/onionwire-sdk \
|
||||||
&& apt-get update \
|
&& apt-get update \
|
||||||
&& apt-get install -y --no-install-recommends pkg-config libssl-dev \
|
&& apt-get install -y --no-install-recommends pkg-config libssl-dev \
|
||||||
&& rustup component add clippy \
|
&& rustup component add clippy \
|
||||||
|
|
|
||||||
99
.forgejo/workflows/fuzz.yml
Normal file
99
.forgejo/workflows/fuzz.yml
Normal 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
|
||||||
|
|
@ -45,7 +45,20 @@ concurrency:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
CARGO_TERM_COLOR: never
|
CARGO_TERM_COLOR: never
|
||||||
RUST_IMAGE: rust:1.91-bookworm
|
# Same floor as ci.yml: the release binary has `cuprate-daemon` on by default,
|
||||||
|
# and `tapes` does not build on 1.91 (`VecDeque::pop_front_if`, stable in 1.93).
|
||||||
|
# Pinned by DIGEST, not by tag. `rust:1.98-bookworm` floats: a rustc patch
|
||||||
|
# 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 —
|
# 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.
|
# 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
|
||||||
|
|
@ -189,7 +202,10 @@ jobs:
|
||||||
timeout-minutes: 120
|
timeout-minutes: 120
|
||||||
env:
|
env:
|
||||||
TARGET: aarch64-unknown-linux-gnu
|
TARGET: aarch64-unknown-linux-gnu
|
||||||
CARGO_TARGET_VOLUME: onionwire-target-aarch64
|
# 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
|
BUILD_CONTAINER: onionwire-release-${{ github.run_id }}-aarch64
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout source
|
- name: Checkout source
|
||||||
|
|
@ -200,48 +216,76 @@ jobs:
|
||||||
- name: Show runner arch
|
- name: Show runner arch
|
||||||
run: uname -m && echo "target=$TARGET"
|
run: uname -m && echo "target=$TARGET"
|
||||||
|
|
||||||
- name: Build ${{ env.TARGET }} in a rust container
|
- 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: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "${GITHUB_WORKSPACE}"
|
cd "${GITHUB_WORKSPACE}"
|
||||||
echo "workspace: $GITHUB_WORKSPACE"
|
echo "workspace: $GITHUB_WORKSPACE"
|
||||||
docker volume create "$CARGO_REGISTRY_VOLUME" > /dev/null
|
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 volume create "$CARGO_TARGET_VOLUME" > /dev/null
|
||||||
docker rm -f "$BUILD_CONTAINER" > /dev/null 2>&1 || true
|
docker rm -f "$BUILD_CONTAINER" > /dev/null 2>&1 || true
|
||||||
docker create --name "$BUILD_CONTAINER" -i \
|
docker create --name "$BUILD_CONTAINER" -i \
|
||||||
-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 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_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 /out && tar xzf - -C /src && cd /src && bash /src/scripts/reproducible-build.sh'
|
||||||
&& apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=20 -o Acquire::https::Timeout=20 -o Acquire::ForceIPv4=true update \
|
|
||||||
&& apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=20 -o Acquire::https::Timeout=20 -o Acquire::ForceIPv4=true 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 \
|
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees \
|
||||||
--exclude=./.ci-tools . \
|
--exclude=./.ci-tools . \
|
||||||
| docker start -a -i "$BUILD_CONTAINER"
|
| docker start -a -i "$BUILD_CONTAINER"
|
||||||
mkdir -p dist
|
mkdir -p dist
|
||||||
docker cp "$BUILD_CONTAINER:/target/release/onionwire" "dist/onionwire-$TARGET"
|
# 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 rm -f "$BUILD_CONTAINER" > /dev/null
|
||||||
|
docker volume rm "$CARGO_TARGET_VOLUME" > /dev/null
|
||||||
|
|
||||||
- name: Pack and checksum
|
- name: Verify the recipe's dist output
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "${GITHUB_WORKSPACE}/dist"
|
cd "${GITHUB_WORKSPACE}/dist"
|
||||||
bytes=$(wc -c < "onionwire-$TARGET")
|
|
||||||
if [ "$bytes" -eq 0 ]; then
|
|
||||||
echo "refusing empty binary onionwire-$TARGET" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
file "onionwire-$TARGET"
|
|
||||||
sha256sum "onionwire-$TARGET" > "onionwire-$TARGET.sha256"
|
|
||||||
sha256sum -c "onionwire-$TARGET.sha256"
|
|
||||||
ls -l
|
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
|
- name: Upload dist artifact
|
||||||
uses: https://code.forgejo.org/actions/upload-artifact@v3
|
uses: https://code.forgejo.org/actions/upload-artifact@v3
|
||||||
|
|
@ -257,7 +301,10 @@ jobs:
|
||||||
timeout-minutes: 120
|
timeout-minutes: 120
|
||||||
env:
|
env:
|
||||||
TARGET: x86_64-unknown-linux-gnu
|
TARGET: x86_64-unknown-linux-gnu
|
||||||
CARGO_TARGET_VOLUME: onionwire-target-x86_64
|
# 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
|
BUILD_CONTAINER: onionwire-release-${{ github.run_id }}-x86_64
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout source
|
- name: Checkout source
|
||||||
|
|
@ -283,48 +330,76 @@ jobs:
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Build ${{ env.TARGET }} in a rust container
|
- 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: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "${GITHUB_WORKSPACE}"
|
cd "${GITHUB_WORKSPACE}"
|
||||||
echo "workspace: $GITHUB_WORKSPACE"
|
echo "workspace: $GITHUB_WORKSPACE"
|
||||||
docker volume create "$CARGO_REGISTRY_VOLUME" > /dev/null
|
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 volume create "$CARGO_TARGET_VOLUME" > /dev/null
|
||||||
docker rm -f "$BUILD_CONTAINER" > /dev/null 2>&1 || true
|
docker rm -f "$BUILD_CONTAINER" > /dev/null 2>&1 || true
|
||||||
docker create --name "$BUILD_CONTAINER" -i \
|
docker create --name "$BUILD_CONTAINER" -i \
|
||||||
-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 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_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 /out && tar xzf - -C /src && cd /src && bash /src/scripts/reproducible-build.sh'
|
||||||
&& apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=20 -o Acquire::https::Timeout=20 -o Acquire::ForceIPv4=true update \
|
|
||||||
&& apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=20 -o Acquire::https::Timeout=20 -o Acquire::ForceIPv4=true 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 \
|
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees \
|
||||||
--exclude=./.ci-tools . \
|
--exclude=./.ci-tools . \
|
||||||
| docker start -a -i "$BUILD_CONTAINER"
|
| docker start -a -i "$BUILD_CONTAINER"
|
||||||
mkdir -p dist
|
mkdir -p dist
|
||||||
docker cp "$BUILD_CONTAINER:/target/release/onionwire" "dist/onionwire-$TARGET"
|
# 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 rm -f "$BUILD_CONTAINER" > /dev/null
|
||||||
|
docker volume rm "$CARGO_TARGET_VOLUME" > /dev/null
|
||||||
|
|
||||||
- name: Pack and checksum
|
- name: Verify the recipe's dist output
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "${GITHUB_WORKSPACE}/dist"
|
cd "${GITHUB_WORKSPACE}/dist"
|
||||||
bytes=$(wc -c < "onionwire-$TARGET")
|
|
||||||
if [ "$bytes" -eq 0 ]; then
|
|
||||||
echo "refusing empty binary onionwire-$TARGET" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
file "onionwire-$TARGET"
|
|
||||||
sha256sum "onionwire-$TARGET" > "onionwire-$TARGET.sha256"
|
|
||||||
sha256sum -c "onionwire-$TARGET.sha256"
|
|
||||||
ls -l
|
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
|
- name: Upload dist artifact
|
||||||
uses: https://code.forgejo.org/actions/upload-artifact@v3
|
uses: https://code.forgejo.org/actions/upload-artifact@v3
|
||||||
|
|
@ -341,7 +416,11 @@ jobs:
|
||||||
# Pi runner, not docker-amd64: the amd64 dind runner is capacity=1 and
|
# 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
|
# 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
|
# already created the tag over the public API (version job), so publish
|
||||||
# uses that same path. This job only curls the Forgejo API — no docker CLI.
|
# 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
|
# 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
|
# after a successful publish (act treats needs.publish.result as unset, so
|
||||||
# != success) and Early-terminated on run 135. Do not restore that job.
|
# != success) and Early-terminated on run 135. Do not restore that job.
|
||||||
|
|
@ -371,6 +450,91 @@ jobs:
|
||||||
with:
|
with:
|
||||||
path: artifacts
|
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
|
- name: Publish both binaries to one release
|
||||||
if: needs.version.outputs.dry_run != 'true' && needs.aarch64.result == 'success' && needs.x86_64.result == 'success'
|
if: needs.version.outputs.dry_run != 'true' && needs.aarch64.result == 'success' && needs.x86_64.result == 'success'
|
||||||
env:
|
env:
|
||||||
|
|
@ -379,32 +543,30 @@ jobs:
|
||||||
TAG: ${{ needs.version.outputs.tag }}
|
TAG: ${{ needs.version.outputs.tag }}
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
mkdir -p dist
|
# dist/ is staged and signed by the two steps above; this step only
|
||||||
find artifacts -type f -print
|
# refuses to upload a hole in it.
|
||||||
for target in aarch64-unknown-linux-gnu x86_64-unknown-linux-gnu; do
|
find dist -type f -print
|
||||||
src=$(find artifacts -type f -name "onionwire-$target" -print -quit)
|
|
||||||
sum=$(find artifacts -type f -name "onionwire-$target.sha256" -print -quit)
|
|
||||||
if [ -z "$src" ] || [ -z "$sum" ]; then
|
|
||||||
echo "missing artifact for $target" >&2
|
|
||||||
find artifacts -type f >&2 || true
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
cp "$src" "dist/onionwire-$target"
|
|
||||||
cp "$sum" "dist/onionwire-$target.sha256"
|
|
||||||
done
|
|
||||||
missing=0
|
missing=0
|
||||||
for f in \
|
for f in \
|
||||||
dist/onionwire-aarch64-unknown-linux-gnu \
|
dist/onionwire-aarch64-unknown-linux-gnu \
|
||||||
dist/onionwire-aarch64-unknown-linux-gnu.sha256 \
|
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 \
|
||||||
dist/onionwire-x86_64-unknown-linux-gnu.sha256
|
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
|
do
|
||||||
|
if [ ! -s "$f" ]; then
|
||||||
|
echo "refusing to publish missing or empty asset $f" >&2
|
||||||
|
missing=1
|
||||||
|
continue
|
||||||
|
fi
|
||||||
bytes=$(wc -c < "$f")
|
bytes=$(wc -c < "$f")
|
||||||
echo "on disk: $f $bytes bytes"
|
echo "on disk: $f $bytes bytes"
|
||||||
if [ "$bytes" -eq 0 ]; then
|
|
||||||
echo "refusing empty asset $f" >&2
|
|
||||||
missing=1
|
|
||||||
fi
|
|
||||||
file "$f" || true
|
file "$f" || true
|
||||||
done
|
done
|
||||||
if [ "$missing" -ne 0 ]; then
|
if [ "$missing" -ne 0 ]; then
|
||||||
|
|
@ -416,8 +578,15 @@ jobs:
|
||||||
.ci-tools/scripts/release-body.md \
|
.ci-tools/scripts/release-body.md \
|
||||||
dist/onionwire-aarch64-unknown-linux-gnu \
|
dist/onionwire-aarch64-unknown-linux-gnu \
|
||||||
dist/onionwire-aarch64-unknown-linux-gnu.sha256 \
|
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 \
|
||||||
dist/onionwire-x86_64-unknown-linux-gnu.sha256
|
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
|
- name: Delete tag we created if this job failed
|
||||||
if: failure() && needs.version.outputs.created_tag == 'true' && needs.version.outputs.dry_run != 'true'
|
if: failure() && needs.version.outputs.created_tag == 'true' && needs.version.outputs.dry_run != 'true'
|
||||||
|
|
|
||||||
2392
Cargo.lock
generated
2392
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
65
Cargo.toml
65
Cargo.toml
|
|
@ -2,41 +2,66 @@
|
||||||
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-sqlcipher-vendored-openssl"] }
|
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"
|
||||||
|
|
@ -50,7 +75,17 @@ sha2 = "0.10"
|
||||||
md-5 = "0.10"
|
md-5 = "0.10"
|
||||||
rpassword = "7"
|
rpassword = "7"
|
||||||
zeroize = { version = "1", features = ["derive"] }
|
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 }
|
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"
|
||||||
|
|
|
||||||
512
README.md
512
README.md
|
|
@ -1,74 +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.1** — Linux TUI + Android SDK/APK. 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, and 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 still fail closed. Optional Monero payments: `/pay` invoices (receive), `/tip` payments (send), and a full in-app wallet create/import (`F6` wallet screen, `/wallet create`, `/wallet import`). Arti onion services are still experimental. The whole store is encrypted at rest with SQLCipher; message bodies add a row-bound AEAD layer on top.
|
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).
|
**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`) does **not** release on a merge. Releases are manual and batched: a maintainer runs the workflow at a stopping point (Actions → release → Run workflow, `dry_run=true` first), which tags the next `v*.*.*` version and publishes both Linux binaries — aarch64 on the Pi runner, x86_64 on the amd64 runner — to one [Forgejo release](https://forgejo.siriusdevops.com/sirius/onionwire/releases), with the Android APK + AAR attached to that same tag. Policy and inputs: [docs/RELEASING.md](docs/RELEASING.md). `scripts/build-release-local.sh` remains the offline x86_64 fallback. This Forgejo does not serve `/releases/latest/download/…` (404); pin the tag.
|
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/download/v0.2.1/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/download/v0.2.1/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/download/v0.2.1/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/download/v0.2.1/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
|
||||||
|
|
@ -81,28 +123,35 @@ 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
|
```bash
|
||||||
onionwire
|
onionwire
|
||||||
|
|
@ -110,73 +159,136 @@ 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. 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).
|
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 screen (receive QR, balance, transfers) |
|
| `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.
|
||||||
|
|
||||||
## Local outbox (chat) and fail closed
|
## Local outbox (chat) and fail closed
|
||||||
|
|
||||||
**Chat** to an unreachable onion is written to a local `outbox` row next to its
|
**Chat** to an unreachable onion is written to a local `outbox` row and retried
|
||||||
`messages` row and retried in-process while the app runs (exponential backoff,
|
in-process while the app runs (exponential backoff from 30s, cap 30 min, stop
|
||||||
cap 30 min between attempts, stop after 8 attempts or a terminal failure). There
|
after 8 attempts or a terminal failure — `src/outbox.rs`). There is **no**
|
||||||
is **no** server-side queue and **no** store-and-forward relay — a queued message
|
server-side queue and **no** store-and-forward relay — a queued message never
|
||||||
never leaves the device, and it dies with the device. Two consequences are real and are accepted:
|
leaves the device, and it dies with the device.
|
||||||
|
|
||||||
- **Device seizure.** A pending (never-delivered) message sits in the same SQLCipher store as the rest of the history, under the same per-row AEAD and the same passphrase-derived key — no weaker, but also no shorter-lived. Seizure *with* the passphrase reveals messages that were never actually sent, including ones the sender may have moved on from; seizure without it reveals nothing in this store. `/wipe` clears outbox rows with the rest of chat history; `/wipe-all` removes them with the data dir. Neither is a forensic erase — SSD wear-leveling can keep copies. Roster and identity stay.
|
- **Device seizure.** A pending message sits in the same SQLCipher store as the
|
||||||
- **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. An observer of your Tor client (or the network in front of it) sees a repeating connection attempt to one onion on a predictable cadence — it does not learn the plaintext or the recipient identity, but it can infer that you have an undelivered message for someone, and roughly when you composed it. The backoff is per-row, capped at one attempt per 30 min per message, and stops after 8 attempts or on a terminal failure.
|
rest of the history. Seizure *with* the passphrase reveals messages that were
|
||||||
|
never sent; seizure without it reveals nothing in this store. `/wipe` clears
|
||||||
Delivery markers in the TUI and Android chat UI are the store's own statuses:
|
outbox rows with chat history; `/wipe-all` removes them with the data dir.
|
||||||
|
Neither is a forensic erase.
|
||||||
| Row state | Marker |
|
- **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.
|
||||||
| delivered | `you: ping ✓` |
|
|
||||||
| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` |
|
|
||||||
| sending | `you: pong » sending` |
|
|
||||||
| failed | `you: pong ✗ failed: connection timed out` |
|
|
||||||
| inbound | `them: pong` (no marker) |
|
|
||||||
|
|
||||||
The footer shows `{n} queued` while any row is outstanding. `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` / `retry now` comes from the stored absolute `next_attempt_at`. Failed reasons are sanitized, cut to the tail of the `a: b: c` chain, and capped at 24 cells.
|
|
||||||
|
|
||||||
Still **fail closed** (no queue, no retry):
|
Still **fail closed** (no queue, no retry):
|
||||||
|
|
||||||
|
|
@ -185,137 +297,118 @@ Still **fail closed** (no queue, no retry):
|
||||||
- Arti cannot publish the onion (no C-tor fallback)
|
- Arti cannot publish the onion (no C-tor fallback)
|
||||||
- no DHT, no name server, no hosted chat server
|
- no DHT, no name server, no hosted chat server
|
||||||
|
|
||||||
## Chat ratchet (per friend, on device)
|
## Chat ratchet
|
||||||
|
|
||||||
Chat is ratcheted on top of the Noise session: each chat send is
|
Chat is ratcheted on top of the Noise session: each chat send is Double-Ratchet
|
||||||
Double-Ratchet encrypted first, and the resulting `rat ` frame is what the
|
encrypted first, and the resulting `rat ` frame is what the one-shot Noise
|
||||||
one-shot Noise session carries. Forward secrecy is per chain, and a snapshot of
|
session carries. Wire format: [docs/PROTOCOL.md](docs/PROTOCOL.md).
|
||||||
one side's state stops reading the conversation at the next DH ratchet step.
|
|
||||||
The wire format and the honest limits are in
|
|
||||||
[docs/PROTOCOL.md](docs/PROTOCOL.md) and
|
|
||||||
[docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
|
|
||||||
|
|
||||||
- Per-friend state lives in the encrypted store (`ratchet_sessions`, one row per
|
- Per-friend state lives in the encrypted store (`ratchet_sessions`). Nothing
|
||||||
friend). Nothing about it is transmitted, so the "no relay, no server queue"
|
about it is transmitted.
|
||||||
rule is unchanged.
|
- **Only chat is ratcheted.** `loc`, `prf`, `inv`, `rcp`, `tip`, `png`, and
|
||||||
- Message numbers, ratchet keys and chain state ride *inside* the Noise
|
`fil` keep the one-shot Noise shape.
|
||||||
ciphertext; there is nothing new to observe on the wire.
|
- **Chat length is bucketed.** The chat line is padded inside the ratchet
|
||||||
- **Only chat is ratcheted.** `loc`, `prf`, `inv`, `rcp`, `tip` and file chunks
|
ciphertext to one fixed ladder size (256 B to 32 KiB), so the wire shows a
|
||||||
keep the one-shot Noise shape.
|
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
|
- Out-of-order delivery works (bounded skipped keys: 2000 per chain jump, 2000
|
||||||
stored, oldest-first eviction; a used key is deleted, so a replay fails
|
stored). A queued chat message re-sends the *same* `rat ` frame.
|
||||||
closed). A queued chat message re-sends the *same* `rat ` frame, so an outbox
|
- `/wipe` clears chat, payments and outbox but **keeps** ratchet state. `/wipe-all`
|
||||||
retry never burns a second chain key.
|
removes the data dir.
|
||||||
- `/wipe` clears chat, payments and outbox rows but **keeps** the ratchet state
|
- There is no `/reset`. State drops when the friend's prekey or ML-KEM key
|
||||||
(roster and identity stay), so chat continues on the same epoch. `/wipe-all`
|
changes (you `F3`-paste a refreshed invite).
|
||||||
removes the data dir and the state with it.
|
- **Ratchet steps are hybrid; epoch 0 is not.** Every rotation after the
|
||||||
- **Session reset.** There is no `/reset` command and no in-band reset in
|
bootstrap mixes an ML-KEM-768 secret into the chain KDF, so a later X25519
|
||||||
v0.2.1. The state is dropped automatically when the friend's prekey changes —
|
break does not open a hybrid chain. The bootstrap epoch is still derived only
|
||||||
i.e. when you `F3`-paste a refreshed invite — and the next chat frame
|
from the two X25519 prekeys — a per-session KEM secret cannot be folded in
|
||||||
bootstraps a fresh epoch. That re-paste is the only recovery path today.
|
without breaking both-send-first convergence — so messages sent before the
|
||||||
- **Desync today is quiet.** An inbound `rat ` frame that does not authenticate
|
first rotation stay X25519-only at the ratchet layer, and classical (v1)
|
||||||
is logged as `rat dropped (<reason>)` on stderr and dropped: no chat row, no
|
friends have no PQ layer at all. No full post-quantum forward secrecy is
|
||||||
TUI marker, nothing stored. A send-side failure surfaces as the usual
|
claimed; see [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
|
||||||
`send failed: …` status note. There is no in-app "ratchet desynced" banner
|
- An inbound `rat ` frame that does not authenticate is logged as
|
||||||
yet, so a desync is diagnosed from the terminal the app was started in.
|
`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. File transfer is **not** covered by the chat 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 (opt-in)
|
## Monero (opt-in)
|
||||||
|
|
||||||
Chat does not need a wallet. Spend is opt-in at wallet create/restore; default
|
Chat does not need a wallet. Spend is opt-in at wallet create/restore. Optional
|
||||||
is no spend key, no seed on the device. Optional JSON-RPC to `monero-wallet-rpc` on
|
JSON-RPC to `monero-wallet-rpc` on **loopback only** (you run it, or the app
|
||||||
loopback (you run it, or the app spawns it). Chain source is your choice: a
|
spawns it). Chain source is your choice: spawned local `monerod`, in-process
|
||||||
spawned local `monerod`, or a daemon address you supply. The wallet **must**
|
Cuprate (opt-in feature, **unvalidated on mainnet**), or a daemon address you
|
||||||
use `--rpc-login`; OnionWire refuses an open RPC (HTTP 200 without a Digest
|
type. The wallet **must** use `--rpc-login`; OnionWire refuses an open RPC and
|
||||||
challenge) and refuses URLs with no credentials.
|
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`, `/tip`, and `F6` 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).
|
||||||
**Prefer a view-only wallet.** OnionWire only needs invoices and receipt checks
|
|
||||||
(`create_address` / `get_transfers`); it does not need spend authority. Set
|
|
||||||
`ONIONWIRE_WALLET_NO_SPEND=1` (or `true` / `yes` / `on`) to refuse `/tip`
|
|
||||||
locally before any RPC dial — `/pay` and receipt verification keep working.
|
|
||||||
Details: [docs/WALLET.md](docs/WALLET.md).
|
|
||||||
|
|
||||||
Payment frame summary:
|
|
||||||
|
|
||||||
| Command | Wire frame | What it does |
|
| Command | Wire frame | What it does |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `/pay <xmr> [memo]` | `inv ` | Invoice to receive. We want to be paid. Uses a wallet subaddress if RPC is up, else the profile `xmr_addr`. |
|
| `/pay <xmr> [memo]` | `inv ` | Invoice to receive. Subaddress if RPC is up, else profile `xmr_addr`. |
|
||||||
| `/tip <xmr> [memo]` | `rcp ` + `tip ` | Pay the selected friend. Sends a Monero `transfer`, then a signed receipt claim and a tip frame. Disabled under `ONIONWIRE_WALLET_NO_SPEND`. |
|
| `/tip <xmr> [memo]` | `rcp ` + `tip ` | Chain `transfer`, then signed receipt and tip. One-shot. Disabled under `ONIONWIRE_WALLET_NO_SPEND`. |
|
||||||
|
|
||||||
- `/pay` sends a signed `inv` frame one-shot (both sides must be online).
|
Peer onion down → `/pay` and `/tip` fail. A queued invoice does not exist.
|
||||||
- `/tip` does the chain transfer first, then sends a signed `rcp` frame **and** a `tip` frame — both one-shot. Peer onion down → fails after the transfer. Not queued.
|
|
||||||
|
|
||||||
## In-app wallet (create / import)
|
`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`.
|
||||||
|
|
||||||
`/wallet create` (F6 then `c`) generates a new spend-capable wallet on the RPC
|
`monero-wallet-rpc` keeps a wallet open only for the life of one process, so the
|
||||||
(`create_wallet`), then shows the 25-word seed **once** for backup
|
app opens the configured file itself after the child is up (`open_wallet`) — and
|
||||||
(`query_key mnemonic`). Type `SPEND` to accept the spend-authority warning, set a
|
the passphrase that does it is kept, sealed in the store beside the RPC creds.
|
||||||
wallet passphrase, write the seed down, type `SEEN`. The seed is never pasted into
|
That is deliberate and it means the store passphrase is enough to spend; see
|
||||||
the composer or chat history — collect it on the dedicated screen.
|
[docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) and
|
||||||
|
[docs/WALLET.md](docs/WALLET.md). A wallet the app holds no passphrase for still
|
||||||
`/wallet import` (F6 then `i`) restores from an existing 25-word seed via
|
starts — the status reports `needs passphrase` and the app prompts for it once.
|
||||||
`restore_deterministic_wallet`. This is the only path that takes a user-supplied
|
|
||||||
secret. The seed is collected on its own screen.
|
|
||||||
|
|
||||||
Both paths require the wallet RPC to be started with `--wallet-dir` (not only
|
|
||||||
`--wallet-file`); the in-app filename is `onionwire`.
|
|
||||||
|
|
||||||
**Spend-authority warning** — unavoidable at create/restore:
|
|
||||||
|
|
||||||
> An OnionWire instance pointed at a spend-capable `monero-wallet-rpc` is a local spend authority. Any process that can read the RPC credentials (env var, `/proc/<pid>/environ`, shell history, a stored URL) can spend the wallet's balance, and `/tip` gives a chat peer a supported path to ask for a transfer. Prefer a view-only wallet or a separate low-balance hot wallet for spend.
|
|
||||||
|
|
||||||
The wallet screen (`F6`) shows a receive address (fresh subaddress when the wallet is up, else the profile `xmr_addr`), the current balance, and up to 8 recent transfers. Press `r` (or Enter) to toggle a QR code of the receive address. `Esc` returns to the chat.
|
|
||||||
|
|
||||||
## 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 ` / `tip ` / `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
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
@ -323,117 +416,78 @@ If you set `ONIONWIRE_HOME`, delete that directory instead.
|
||||||
|
|
||||||
## Seized laptop
|
## Seized laptop
|
||||||
|
|
||||||
The whole sqlite file is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). A 32-byte key is derived from the store passphrase with Argon2id over a per-install 16-byte salt in `store_salt` (mode 0600, in `ONIONWIRE_HOME`) and handed to SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) as the first statement after open. The file header, schema, `self.identity_sk`, friend public keys, locators, profiles and payment rows are all ciphertext on disk, so a disk grep of `onionwire.db` must not yield the message log, your identity key or your roster. A wrong or empty passphrase fails closed before any write; an encrypted store whose `store_salt` is missing refuses to open instead of guessing. v0.2.1 plaintext installs upgrade in place on the first open with the right passphrase; a wrong one leaves the plaintext file untouched.
|
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.
|
||||||
|
|
||||||
Chat bodies carry a second, row-bound layer: ChaCha20-Poly1305 (`nonce || ciphertext` in `messages.plaintext`) with AAD `owmsg1 || friend_id_le64 || dir || 0x00 || row_id_le64`, plus a random 32-byte data key in `store_meta` wrapped with Argon2id from the same passphrase. Whole-file encryption does not stop someone who can write the file from moving one row's ciphertext into another row; the row-bound AAD does, and it stays. Unlock is fail-closed: wrong or empty passphrase does not open chat. Empty-AAD v0.2 blobs are rewrapped once on unlock; `list_messages` never falls back to empty AAD.
|
Threat model: [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
|
||||||
|
|
||||||
At-rest encryption is not a defense against a live compromise: while OnionWire runs, the passphrase, the db key and decrypted rows are in process memory, and SQLCipher's page cache holds decrypted pages. Secret material (Noise/Ed25519/X25519 ephemerals, store key copies, TUI passphrase buffer) is zeroized with the `zeroize` crate when dropped; that shrinks the window, it does not close it. It also does not stop an attacker who has your passphrase. Pending outbox rows live in the same encrypted store as delivered chat — seizure *with* the passphrase can reveal messages that never left the device. `/wipe` deletes chat, payments and outbox history; it is not a forensic erase — SSD wear-leveling can keep copies. `/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 peer and a Linux peer that exchange invites interoperate — one protocol, not two.
|
Same repository, same protocol. An Android peer and a Linux peer that exchange
|
||||||
|
invites interoperate.
|
||||||
|
|
||||||
- **SDK** — `onionwire-sdk-<version>.aar`. UniFFI Kotlin bindings over the same Rust crate the TUI runs on, plus `libonionwire_sdk.so` for `arm64-v8a`. `Wire.send()` returns `SendState.Sent` | `SendState.Queued`; chat rows carry `delivery` and `id`; `Wire.outbox(pubkey)` exposes attempt count and next attempt time so the UI can render `queued (try n/8, retry 45s)` without inventing a countdown. Explicit Tor lifecycle bindings (`shutdown`/`flush`/`torState`) stop, flush, and report observable Tor state. Another Android app can depend on the AAR directly.
|
- **SDK** — `onionwire-sdk-<version>.aar`. UniFFI Kotlin over the same Rust crate
|
||||||
- **Payment surface** — `sendInvoice(pubkey, amountXmr, memo)` for `/pay`-style invoices, `sendTip(pubkey, amountXmr, memo)` for `/tip`-style payments (chain transfer + signed `rcp` + `tip`), `walletBalance()`, `walletReceiveAddress()`, `walletRecentTransfers(cap)`, `createWallet(password)` (returns the 25-word seed once), `importWallet(password, seed)`, and `spendAuthorityWarning()`. All payments are one-shot; none are queued. See [crates/onionwire-sdk/README.md](crates/onionwire-sdk/README.md).
|
the TUI runs. See [crates/onionwire-sdk/README.md](crates/onionwire-sdk/README.md).
|
||||||
- **APK** — `onionwire-<version>-android-arm64-v8a.apk`. Kotlin + Jetpack Compose + Material 3 messenger that depends on `:sdk` and nothing else. Per-row delivery markers and a chat-level outbox footer match the TUI vocabulary. A foreground keep-alive service (ongoing notification) keeps the in-process Arti onion published and the outbox retry worker alive through Doze while the user wants the node reachable. The store passphrase can be remembered as an AES-256-GCM blob wrapped by the **Android Keystore** (StrongBox first, TEE/software fallback, labelled honestly). A Compose wallet route (receive QR, balance, transfers, create/import) and roster bottom actions are wired without dropping wipe-chat.
|
- **APK** — `onionwire-<version>-android-arm64-v8a.apk`. Kotlin + Jetpack Compose.
|
||||||
|
Build notes: [android/README.md](android/README.md). The UI is a design-token
|
||||||
|
system (one accent, 16px cards, three-tab shell: Chats / Wallet / Node &
|
||||||
|
Settings) rather than per-screen styling; see *App shell* in that README.
|
||||||
|
|
||||||
It is not a WebView, and `src/tui.rs` is untouched. The APK build itself is
|
The APK build is amd64-only. After the Linux `release` workflow finishes,
|
||||||
amd64-only — 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/workflows/android-release.yml`](.forgejo/workflows/android-release.yml)
|
Forgejo release.
|
||||||
is **dispatch-only** on this Forgejo (a CI-created tag does not wake it): after
|
|
||||||
the Linux `release` workflow finishes, dispatch `android-release` with that tag
|
|
||||||
so the amd64 job builds the APK/AAR and the Pi job attaches them (+ `.sha256`)
|
|
||||||
to the same Forgejo release. If that tag's release already exists and is missing
|
|
||||||
the APK, the workflow **joins** it instead of minting patch+1. Publish does not
|
|
||||||
run from amd64 dind: `POST /releases` from that egress returns 422 with an empty
|
|
||||||
body.
|
|
||||||
|
|
||||||
```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.2.1 scripts/build-android-local.sh # + upload to that release
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Every asset has a matching `.sha256` so `sha256sum -c` works. CI signs with the
|
|
||||||
repo-owned release keystore. A local run without those env vars still
|
|
||||||
debug-signs for sideload, not 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)
|
||||||
|
|
||||||
Releases are **manual and batched**: no merge publishes anything, and neither
|
Manual and batched: no merge publishes anything, and neither does a tag push.
|
||||||
does a tag push. Cut one when a batch of work has reached a stopping point —
|
Full procedure: [docs/RELEASING.md](docs/RELEASING.md).
|
||||||
CI green on `main`, the feature set landed, no half-merged stack. Full policy
|
|
||||||
and procedure: [`docs/RELEASING.md`](docs/RELEASING.md) — it is two dispatches,
|
|
||||||
`release` (tag + Linux binaries) then `android-release` with that tag (APK +
|
|
||||||
AAR): on this Forgejo neither a tag push nor `workflow_call` can wake the
|
|
||||||
Android job.
|
|
||||||
|
|
||||||
Actions → release → Run workflow:
|
Actions → **release** → Run workflow:
|
||||||
|
|
||||||
| Input | Meaning |
|
| Input | Meaning |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `dry_run` | build + checksum both Linux binaries, no tag, no publish. Run this first. |
|
| `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`. |
|
| `bump` | `patch` / `minor` / `major` off the newest `v*.*.*` tag. Default `minor`. |
|
||||||
| `version` | explicit `X.Y.Z` (or `vX.Y.Z`) — overrides `bump`. |
|
| `version` | explicit `X.Y.Z` — overrides `bump`. |
|
||||||
| `tag` | rebuild / re-publish an existing tag instead of minting one. |
|
| `tag` | rebuild / re-publish an existing tag. |
|
||||||
|
|
||||||
Pass `tag` **or** `version`, not both; an unparseable version is rejected
|
Then dispatch **android-release** with `tag=<that tag>` to attach the APK + AAR.
|
||||||
rather than guessed at. The workflow computes the version, creates the tag over
|
|
||||||
the API (refusing to move an existing tag), builds aarch64 on the Pi runner and
|
|
||||||
x86_64 on the amd64 runner, and publishes all four assets (`onionwire-<target>`
|
|
||||||
+ `.sha256`) to one release. Then dispatch `android-release` with that tag to
|
|
||||||
attach the APK + AAR to the same release (it has no automatic trigger on this
|
|
||||||
Forgejo — see `docs/RELEASING.md`). If a build or the publish fails, the core
|
|
||||||
run deletes the tag it created. Do not push tags by hand —
|
|
||||||
`release.yml` has no tag-push trigger, so a hand-pushed tag would build
|
|
||||||
nothing.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# optional: keep Cargo.toml in sync with the tag the workflow will mint
|
FORGEJO_TOKEN=<pat> scripts/build-release-local.sh v0.7.0
|
||||||
# (the workflow does not edit Cargo.toml)
|
|
||||||
|
|
||||||
# offline x86_64 fallback (idempotent — safe to re-run)
|
|
||||||
FORGEJO_TOKEN=<pat> scripts/build-release-local.sh v0.2.1
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Workflows (Forgejo Actions, `.forgejo/workflows/`):
|
Do not run `cargo publish`; `publish = false`.
|
||||||
|
|
||||||
- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — two jobs on the Pi runner (`docker` label), serialized by `onionwire-ci-pi`. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk` (separate cargo workspace — own `Cargo.lock`, root crate by path, `rustls` instead of `native-tls` — so a root signature change cannot silently break the Android SDK). Both run on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite.
|
|
||||||
- [`.forgejo/workflows/android-ci.yml`](.forgejo/workflows/android-ci.yml) — the android side of CI, on the `docker-amd64` runner: builds `:sdk:assembleRelease` + `:app:assembleRelease` with the same script the release uses (`scripts/build-android-local.sh`, Rust for `aarch64-linux-android` via cargo-ndk + UniFFI bindings) and verifies the packaged `libonionwire_sdk.so`, checksums and APK badging. Debug keystore, no publish, no tag. Runs on `main` and PRs when `android/`, `src/`, `crates/`, `Cargo.toml`, `Cargo.lock` or `scripts/build-android-local.sh` change. Same concurrency group **and** the same runner volumes as `android-release.yml`, so a PR build never fights a release build over the SDK/NDK, cargo and Gradle caches.
|
|
||||||
- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — manual, batched release (`workflow_dispatch` only: `dry_run`, `bump`, `version`, `tag`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release, fail-closed tag delete on failure. Dispatch [`android-release.yml`](.forgejo/workflows/android-release.yml) with that tag to add the APK + AAR (no automatic trigger fires on this Forgejo; it is `workflow_dispatch` only). Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`.
|
|
||||||
- [`.forgejo/workflows/android-release.yml`](.forgejo/workflows/android-release.yml) — amd64-only Android build (dispatch-only on this Forgejo; wakes from an explicit `tag=` input, not a tag push).
|
|
||||||
|
|
||||||
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, a **server-side** outbox / store-and-forward relay, multi-device, DHT / name server, QR codes, A/V. The **local** chat retry queue is in; it never leaves the device. Protocol lock: [docs/PROTOCOL.md](docs/PROTOCOL.md).
|
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
|
||||||
|
|
||||||
MIT
|
MIT
|
||||||
|
|
|
||||||
259
android/CUPRATE_DAEMON.md
Normal file
259
android/CUPRATE_DAEMON.md
Normal 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
191
android/MONERO_BINARIES.md
Normal 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.
|
||||||
|
|
@ -11,6 +11,14 @@ 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. Same wire protocol: [docs/PROTOCOL.md](../docs/PROTOCOL.md).
|
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
|
||||||
|
|
||||||
* JDK 17+ (built and tested on JDK 21)
|
* JDK 17+ (built and tested on JDK 21)
|
||||||
|
|
@ -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.1.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
|
||||||
|
|
||||||
|
|
@ -148,9 +176,11 @@ Release APKs are signed with a **repo-owned keystore**, not the debug key.
|
||||||
present (`~/.android/onionwire-release.jks` + `.env`, mode 600). Local and
|
present (`~/.android/onionwire-release.jks` + `.env`, mode 600). Local and
|
||||||
CI APKs then verify as the same cert and can upgrade in place.
|
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
|
* If the env file is missing, Gradle **warns** and signs with the debug
|
||||||
keystore so a laptop build still installs. CI sets
|
keystore so a laptop build still installs. CI's `android-release.yml` sets
|
||||||
`ONIONWIRE_REQUIRE_RELEASE_KEY=true` and **fails closed** instead — a
|
`ONIONWIRE_REQUIRE_RELEASE_KEY=true` and **fails closed** instead — a
|
||||||
per-machine debug key would make every CI APK uninstallable over the last.
|
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
|
* Never commit a keystore, password, or `android/local.properties`. This is
|
||||||
not a Play upload key; nothing here should be uploaded to Play.
|
not a Play upload key; nothing here should be uploaded to Play.
|
||||||
|
|
||||||
|
|
@ -162,23 +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/android-release.yml` runs on `docker-amd64` (T480 dind).
|
Chain traffic is **off** until the user opens Wallet, picks a source, and
|
||||||
The job image is `node:20-bullseye` (EOL) — **do not apt-get there**. The
|
presses Start. Receive-only is the default: no `monero-wallet-rpc` child, no
|
||||||
toolchain runs in a sibling `debian:bookworm` container
|
daemon, no P2P.
|
||||||
(stdin-tar + `docker cp`, same pattern as the Rust CI job).
|
|
||||||
Any push to `main` that touches Android **sources or build config**
|
|
||||||
(`android/app/**`, `android/sdk/**`, Gradle files — not `android/README.md`)
|
|
||||||
workflow) builds `onionwire-<version>-android-arm64-v8a.apk` and
|
|
||||||
`onionwire-sdk-<version>.aar`, verifies them, and attaches them to the Forgejo
|
|
||||||
release for that tag. Version is the latest `v*.*.*` tag plus patch, or
|
|
||||||
**v0.1.0** when there are no tags. `versionName` matches the tag;
|
|
||||||
`versionCode` is `major*10000 + minor*100 + patch` (so 0.1.0 → 100).
|
|
||||||
|
|
||||||
`workflow_dispatch` with `dry_run=true` builds and checksums without creating
|
The app owns `monero-wallet-rpc` (issue #107). It is still a **child process**,
|
||||||
a tag or publishing. `scripts/build-android-local.sh` remains the offline
|
exec'd from `applicationInfo.nativeLibraryDir/libmonerowalletrpc.so`. Cuprate
|
||||||
fallback; it does not create tags.
|
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
|
||||||
|
|
||||||
|
|
@ -187,17 +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
|
crypto/ # Keystore-wrapped store passphrase
|
||||||
|
keepalive/ # NodeHost, KeepAliveService, policy, lifetime
|
||||||
|
wallet/ # ChainStorage, WalletChildBinaries
|
||||||
ui/ # Compose screens (M3)
|
ui/ # Compose screens (M3)
|
||||||
src/test/ # JVM tests (envelope, store, invite flow)
|
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/androidTest/ # device-only: AndroidKeyStore
|
||||||
|
src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so
|
||||||
```
|
```
|
||||||
|
|
|
||||||
|
|
@ -102,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"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,8 @@ package com.siriusdevops.onionwire.crypto
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import android.security.keystore.KeyGenParameterSpec
|
||||||
|
import android.security.keystore.KeyProperties
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
import androidx.test.platform.app.InstrumentationRegistry
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
|
@ -12,9 +14,13 @@ import org.junit.Assert.assertFalse
|
||||||
import org.junit.Assert.assertNotEquals
|
import org.junit.Assert.assertNotEquals
|
||||||
import org.junit.Assert.assertTrue
|
import org.junit.Assert.assertTrue
|
||||||
import org.junit.Assert.fail
|
import org.junit.Assert.fail
|
||||||
|
import org.junit.Before
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
import org.junit.runner.RunWith
|
import org.junit.runner.RunWith
|
||||||
import java.io.File
|
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
|
* The device half of the Keystore story. The unit-test JVM has no
|
||||||
|
|
@ -28,6 +34,13 @@ import java.io.File
|
||||||
* `KeyInfo`/`isInsideSecureHardware`/`securityLevel` report — the point of
|
* `KeyInfo`/`isInsideSecureHardware`/`securityLevel` report — the point of
|
||||||
* [key_backing_is_reported_and_logged] is to print the truth, not to assert a
|
* [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.
|
* 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)
|
@RunWith(AndroidJUnit4::class)
|
||||||
class KeystorePassphraseCipherTest {
|
class KeystorePassphraseCipherTest {
|
||||||
|
|
@ -39,6 +52,20 @@ class KeystorePassphraseCipherTest {
|
||||||
|
|
||||||
private val passphrase = "correct horse battery staple".toCharArray()
|
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
|
@After
|
||||||
fun tearDown() {
|
fun tearDown() {
|
||||||
cipher.deleteKey()
|
cipher.deleteKey()
|
||||||
|
|
@ -93,12 +120,14 @@ class KeystorePassphraseCipherTest {
|
||||||
val strongBoxAdvertised = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
|
val strongBoxAdvertised = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
|
||||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
||||||
val backing = cipher.backing()
|
val backing = cipher.backing()
|
||||||
|
val gate = cipher.unlockGateReport()
|
||||||
|
|
||||||
Log.i(
|
Log.i(
|
||||||
"OnionWireKeystore",
|
TAG,
|
||||||
"alias=${KeystorePassphraseCipher.ALIAS} backing=$backing " +
|
"alias=${KeystorePassphraseCipher.ALIAS} backing=$backing " +
|
||||||
"strongBoxAdvertised=$strongBoxAdvertised " +
|
"strongBoxAdvertised=$strongBoxAdvertised " +
|
||||||
"sdk=${Build.VERSION.SDK_INT} device=${Build.MANUFACTURER} ${Build.MODEL}",
|
"sdk=${Build.VERSION.SDK_INT} device=${Build.MANUFACTURER} ${Build.MODEL} " +
|
||||||
|
"gate=${gate.describe()}",
|
||||||
)
|
)
|
||||||
|
|
||||||
if (strongBoxAdvertised) {
|
if (strongBoxAdvertised) {
|
||||||
|
|
@ -115,7 +144,9 @@ class KeystorePassphraseCipherTest {
|
||||||
fun open_does_not_require_user_authentication() {
|
fun open_does_not_require_user_authentication() {
|
||||||
// The card's contract: unlocking must not need a fingerprint. If the
|
// The card's contract: unlocking must not need a fingerprint. If the
|
||||||
// key had been created with setUserAuthenticationRequired(true), this
|
// key had been created with setUserAuthenticationRequired(true), this
|
||||||
// open() would throw UserNotAuthenticatedException.
|
// 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))
|
val out = cipher.open(cipher.seal(passphrase))
|
||||||
StoreSecret.wipe(out)
|
StoreSecret.wipe(out)
|
||||||
assertTrue(cipher.keyPresent())
|
assertTrue(cipher.keyPresent())
|
||||||
|
|
@ -147,4 +178,273 @@ class KeystorePassphraseCipherTest {
|
||||||
} catch (_: SecretUnavailable) {
|
} 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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,35 +8,61 @@ 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.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.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.WalletManagerScreen
|
||||||
import com.siriusdevops.onionwire.ui.WalletScreen
|
import com.siriusdevops.onionwire.ui.WalletScreen
|
||||||
import com.siriusdevops.onionwire.ui.OnionWireTheme
|
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(
|
||||||
|
|
@ -59,7 +85,7 @@ private fun AppRoot(vm: WireViewModel = viewModel()) {
|
||||||
// Asked in context: the notification is the keep-alive's only visible
|
// 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
|
// 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
|
// first launch. Denial is not fatal — the service runs either way and the
|
||||||
// roster says the notice is hidden.
|
// settings screen says the notice is hidden.
|
||||||
val askNotifications = rememberLauncherForActivityResult(
|
val askNotifications = rememberLauncherForActivityResult(
|
||||||
ActivityResultContracts.RequestPermission(),
|
ActivityResultContracts.RequestPermission(),
|
||||||
) { vm.onNotificationPermissionChanged() }
|
) { vm.onNotificationPermissionChanged() }
|
||||||
|
|
@ -85,73 +111,167 @@ private fun AppRoot(vm: WireViewModel = viewModel()) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 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, keepAliveNote: String?) {
|
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
|
||||||
RosterScreen(
|
// status bar from being padded twice and leaves the only inset this
|
||||||
fingerprint = ready.fingerprint,
|
// level owns — the tab bar's height — in `pad`.
|
||||||
onion = ready.onion,
|
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
||||||
sdkVersion = ready.sdkVersion,
|
containerColor = MaterialTheme.colorScheme.background,
|
||||||
friends = friends,
|
bottomBar = {
|
||||||
keepAliveNote = keepAliveNote,
|
if (tab != null) {
|
||||||
onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") },
|
OwBottomTabBar(selected = tab, onSelect = { nav.selectTab(it) })
|
||||||
onShare = { nav.navigate("share") },
|
}
|
||||||
onPaste = { nav.navigate("paste") },
|
},
|
||||||
onRotate = { nav.navigate("rotate") },
|
) { pad ->
|
||||||
onWipe = { scope.launch { vm.wipeMessages() } },
|
CompositionLocalProvider(LocalBottomBarPresent provides (tab != null)) {
|
||||||
onLock = vm::lock,
|
NavHost(
|
||||||
onOpenWallet = { nav.navigate("wallet") },
|
navController = nav,
|
||||||
)
|
startDestination = Routes.Chats,
|
||||||
}
|
modifier = Modifier.padding(bottom = pad.calculateBottomPadding()),
|
||||||
|
) {
|
||||||
|
composable(Routes.Chats) {
|
||||||
|
RosterScreen(
|
||||||
|
fingerprint = ready.fingerprint,
|
||||||
|
friends = friends,
|
||||||
|
invite = vm::invite,
|
||||||
|
onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") },
|
||||||
|
onShare = { nav.navigate(Routes.Share) },
|
||||||
|
onPaste = { nav.navigate(Routes.Paste) },
|
||||||
|
onRotate = { nav.navigate(Routes.Rotate) },
|
||||||
|
onWipe = { scope.launch { vm.wipeMessages() } },
|
||||||
|
onOpenProfile = { nav.navigate(Routes.Profile) },
|
||||||
|
onLock = vm::lock,
|
||||||
|
onOpenWallets = { nav.navigate(Routes.Wallets) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
composable("share") {
|
composable(Routes.Wallet) {
|
||||||
ShareInviteScreen(ownerInvite = vm::invite, onBack = { nav.popBackStack() })
|
// 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("paste") {
|
composable(Routes.Settings) {
|
||||||
PasteInviteScreen(
|
SettingsScreen(
|
||||||
onDecode = vm::decode,
|
sdkVersion = ready.sdkVersion,
|
||||||
onAdd = vm::addFriend,
|
keepAliveNote = keepAliveNote,
|
||||||
onBack = { nav.popBackStack() },
|
onOpenProfile = { nav.navigate(Routes.Profile) },
|
||||||
)
|
onOpenWallets = { nav.navigate(Routes.Wallets) },
|
||||||
}
|
onRotate = { nav.navigate(Routes.Rotate) },
|
||||||
|
onWipe = { scope.launch { vm.wipeMessages() } },
|
||||||
|
onLock = vm::lock,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
composable("rotate") {
|
composable(Routes.Share) {
|
||||||
RotateScreen(
|
ShareInviteScreen(ownerInvite = vm::invite, onBack = { nav.popBackStack() })
|
||||||
currentOnion = ready.onion,
|
}
|
||||||
onRotate = {
|
|
||||||
val out = vm.rotateOnion()
|
|
||||||
out.notified.toInt() to out.friends.toInt()
|
|
||||||
},
|
|
||||||
onBack = { nav.popBackStack() },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
composable("wallet") {
|
composable(Routes.Paste) {
|
||||||
WalletScreen(vm = vm, onBack = { nav.popBackStack() })
|
PasteInviteScreen(
|
||||||
}
|
onDecode = vm::decode,
|
||||||
|
onAdd = vm::addFriend,
|
||||||
|
onBack = { nav.popBackStack() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
composable(
|
composable(Routes.Rotate) {
|
||||||
route = "chat/{pk}",
|
RotateScreen(
|
||||||
arguments = listOf(navArgument("pk") { type = NavType.StringType }),
|
currentOnion = ready.onion,
|
||||||
) { entry ->
|
onRotate = {
|
||||||
val pk = entry.arguments?.getString("pk").orEmpty()
|
val out = vm.rotateOnion()
|
||||||
val friend = friends.firstOrNull { it.pubkeyHex == pk }
|
out.notified.toInt() to out.friends.toInt()
|
||||||
ChatScreen(
|
},
|
||||||
vm = vm,
|
onBack = { nav.popBackStack() },
|
||||||
peer = pk,
|
)
|
||||||
title = friend?.petname?.takeIf { it.isNotBlank() }
|
}
|
||||||
?: friend?.fingerprint
|
|
||||||
?: pk.take(16),
|
composable(Routes.Wallets) {
|
||||||
fingerprint = friend?.fingerprint ?: pk.take(16),
|
WalletManagerScreen(vm = vm, onBack = { nav.popBackStack() })
|
||||||
onion = friend?.onion.orEmpty(),
|
}
|
||||||
onBack = { nav.popBackStack() },
|
|
||||||
)
|
composable(Routes.Profile) {
|
||||||
|
ProfileScreen(vm = vm, onBack = { nav.popBackStack() })
|
||||||
|
}
|
||||||
|
|
||||||
|
composable(
|
||||||
|
route = Routes.Chat,
|
||||||
|
arguments = listOf(navArgument("pk") { type = NavType.StringType }),
|
||||||
|
) { chatEntry ->
|
||||||
|
val pk = chatEntry.arguments?.getString("pk").orEmpty()
|
||||||
|
val friend = friends.firstOrNull { it.pubkeyHex == pk }
|
||||||
|
ChatScreen(
|
||||||
|
vm = vm,
|
||||||
|
peer = pk,
|
||||||
|
title = friend?.petname?.takeIf { it.isNotBlank() }
|
||||||
|
?: friend?.fingerprint
|
||||||
|
?: pk.take(16),
|
||||||
|
fingerprint = friend?.fingerprint ?: pk.take(16),
|
||||||
|
onion = friend?.onion.orEmpty(),
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
package com.siriusdevops.onionwire
|
package com.siriusdevops.onionwire
|
||||||
|
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.SharedPreferences
|
||||||
import androidx.core.app.NotificationManagerCompat
|
import androidx.core.app.NotificationManagerCompat
|
||||||
import androidx.lifecycle.AndroidViewModel
|
import androidx.lifecycle.AndroidViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
|
|
@ -11,6 +13,17 @@ import com.siriusdevops.onionwire.crypto.StoredPassphraseStore
|
||||||
import com.siriusdevops.onionwire.keepalive.KeepAliveService
|
import com.siriusdevops.onionwire.keepalive.KeepAliveService
|
||||||
import com.siriusdevops.onionwire.keepalive.KeepAliveStatus
|
import com.siriusdevops.onionwire.keepalive.KeepAliveStatus
|
||||||
import com.siriusdevops.onionwire.keepalive.NodeHost
|
import com.siriusdevops.onionwire.keepalive.NodeHost
|
||||||
|
import com.siriusdevops.onionwire.ui.SeedBackupGate
|
||||||
|
import com.siriusdevops.onionwire.ui.WalletKeyOrigin
|
||||||
|
import com.siriusdevops.onionwire.ui.NO_CHAIN_SOURCE_NOTICE
|
||||||
|
import com.siriusdevops.onionwire.ui.storedWalletBinBlockedReason
|
||||||
|
import com.siriusdevops.onionwire.ui.walletBinHealPath
|
||||||
|
import com.siriusdevops.onionwire.ui.walletFailureText
|
||||||
|
import com.siriusdevops.onionwire.wallet.ChainStorage
|
||||||
|
import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE
|
||||||
|
import com.siriusdevops.onionwire.wallet.WalletChildBinaries
|
||||||
|
import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.currentCoroutineContext
|
import kotlinx.coroutines.currentCoroutineContext
|
||||||
|
|
@ -22,16 +35,23 @@ import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.isActive
|
import kotlinx.coroutines.isActive
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
import uniffi.onionwire_sdk.ChainChoice
|
||||||
|
import uniffi.onionwire_sdk.ChainConfig
|
||||||
import uniffi.onionwire_sdk.ChatMessage
|
import uniffi.onionwire_sdk.ChatMessage
|
||||||
import uniffi.onionwire_sdk.FriendInfo
|
import uniffi.onionwire_sdk.FriendInfo
|
||||||
import uniffi.onionwire_sdk.InviteInfo
|
import uniffi.onionwire_sdk.InviteInfo
|
||||||
import uniffi.onionwire_sdk.OutboxRow
|
import uniffi.onionwire_sdk.OutboxRow
|
||||||
import uniffi.onionwire_sdk.RotateOutcome
|
import uniffi.onionwire_sdk.RotateOutcome
|
||||||
|
import uniffi.onionwire_sdk.SelfProfile
|
||||||
import uniffi.onionwire_sdk.SendState
|
import uniffi.onionwire_sdk.SendState
|
||||||
import uniffi.onionwire_sdk.TransferRow
|
import uniffi.onionwire_sdk.TransferRow
|
||||||
|
import uniffi.onionwire_sdk.WalletChildStatus
|
||||||
|
import uniffi.onionwire_sdk.WalletKeys
|
||||||
|
import uniffi.onionwire_sdk.WalletRow
|
||||||
import uniffi.onionwire_sdk.Wire
|
import uniffi.onionwire_sdk.Wire
|
||||||
import uniffi.onionwire_sdk.decodeInvite
|
import uniffi.onionwire_sdk.decodeInvite
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
sealed interface Phase {
|
sealed interface Phase {
|
||||||
/** No identity unlocked. Nothing Tor-related is running. */
|
/** No identity unlocked. Nothing Tor-related is running. */
|
||||||
|
|
@ -144,10 +164,13 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
// is already open would be theatre, and unlocking again would race the
|
// is already open would be theatre, and unlocking again would race the
|
||||||
// live node for the sqlite file.
|
// live node for the sqlite file.
|
||||||
val existing = NodeHost.current()
|
val existing = NodeHost.current()
|
||||||
if (existing != null) {
|
when {
|
||||||
viewModelScope.launch { adopt(existing) }
|
existing != null -> viewModelScope.launch { adopt(existing) }
|
||||||
} else {
|
NodeHost.isOpening() -> {
|
||||||
refreshUnlockState()
|
_phase.value = Phase.Opening
|
||||||
|
viewModelScope.launch { resumeOpening() }
|
||||||
|
}
|
||||||
|
else -> refreshUnlockState()
|
||||||
}
|
}
|
||||||
|
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
|
|
@ -301,17 +324,23 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_phase.value = Phase.Opening
|
_phase.value = Phase.Opening
|
||||||
|
NodeHost.noteOpening()
|
||||||
|
// Hold the process from this tap, not after Tor publishes: otherwise
|
||||||
|
// closing the activity cancels viewModelScope and kills bootstrap.
|
||||||
|
KeepAliveService.start(getApplication(), "")
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
// The SDK open is dispatched to Dispatchers.IO inside NodeHost:
|
|
||||||
// cold start is minutes of Tor bootstrap, which the main thread
|
|
||||||
// does not survive.
|
|
||||||
val w = NodeHost.open(home, secret.concatToString())
|
val w = NodeHost.open(home, secret.concatToString())
|
||||||
if (storeAfterwards) store(secret)
|
if (storeAfterwards) store(secret)
|
||||||
adopt(w)
|
adopt(w)
|
||||||
startKeepAlive(w)
|
startKeepAlive(w)
|
||||||
|
} catch (t: CancellationException) {
|
||||||
|
throw t
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
_phase.value = Phase.Failed(t.message ?: t.toString())
|
_phase.value = Phase.Failed(t.message ?: t.toString())
|
||||||
|
if (!NodeHost.hasWorkForKeepAlive()) {
|
||||||
|
KeepAliveService.stop(getApplication())
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
StoreSecret.wipe(secret)
|
StoreSecret.wipe(secret)
|
||||||
}
|
}
|
||||||
|
|
@ -331,13 +360,32 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
runCatching { refreshFriends() }
|
runCatching { refreshFriends() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Re-attach after the activity died mid-bootstrap. */
|
||||||
|
private suspend fun resumeOpening() {
|
||||||
|
try {
|
||||||
|
val w = NodeHost.awaitOpen()
|
||||||
|
adopt(w)
|
||||||
|
startKeepAlive(w)
|
||||||
|
} catch (t: CancellationException) {
|
||||||
|
throw t
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
_phase.value = Phase.Failed(t.message ?: t.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Starts the foreground keep-alive. Always reached from a user-visible
|
* Starts the foreground keep-alive. Always reached from a user-visible
|
||||||
* unlock, so the API 31+ background-start restriction does not apply; if
|
* unlock, so the API 31+ background-start restriction does not apply; if
|
||||||
* the system refuses anyway, [NodeHost] records why and the roster says so.
|
* the system refuses anyway, [NodeHost] records why and the roster says so.
|
||||||
*/
|
*/
|
||||||
private suspend fun startKeepAlive(w: Wire) {
|
private suspend fun startKeepAlive(w: Wire) {
|
||||||
if (NodeHost.keepAlive.value is KeepAliveStatus.On) return
|
// Announced even when the keep-alive is already `On`: it was anchored at
|
||||||
|
// the Open tap with an empty locator, so the notice says "OnionWire is
|
||||||
|
// starting". The POST_NOTIFICATIONS callback happens to re-announce on a
|
||||||
|
// fresh install, but on a device that already granted notifications
|
||||||
|
// there is no callback at all — the notice would then claim bootstrap
|
||||||
|
// forever. Same notification id, so this replaces it with the address
|
||||||
|
// the user can actually hand out.
|
||||||
KeepAliveService.start(getApplication(), w.onion())
|
KeepAliveService.start(getApplication(), w.onion())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -529,6 +577,33 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
|
|
||||||
suspend fun decode(invite: String): InviteInfo = decodeInvite(invite)
|
suspend fun decode(invite: String): InviteInfo = decodeInvite(invite)
|
||||||
|
|
||||||
|
// --- This identity's own profile ---------------------------------------
|
||||||
|
// The phone's half of the TUI's `/profile`. `setSelfProfile` only writes
|
||||||
|
// locally; friends keep showing the old profile until `pushSelfProfile`
|
||||||
|
// reaches each of them, which is why the screen reports the two separately.
|
||||||
|
|
||||||
|
/** The stored profile (nickname, bio, address). A store read; never dials. */
|
||||||
|
suspend fun selfProfile(): Result<SelfProfile> =
|
||||||
|
runCatching { requireWire().selfProfile() }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replace the stored profile. Validated in the core before it is written:
|
||||||
|
* a rejected edit leaves the previous profile untouched.
|
||||||
|
*/
|
||||||
|
suspend fun setSelfProfile(
|
||||||
|
displayName: String,
|
||||||
|
bio: String,
|
||||||
|
xmrAddr: String,
|
||||||
|
): Result<Unit> = runCatching { requireWire().setSelfProfile(displayName, bio, xmrAddr) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send the signed profile to one friend so their view of this identity is
|
||||||
|
* current. One-shot and fail-closed: an unreachable peer is a failure for
|
||||||
|
* that peer, and nothing is queued for them.
|
||||||
|
*/
|
||||||
|
suspend fun pushSelfProfile(pubkeyHex: String): Result<Unit> =
|
||||||
|
runCatching { requireWire().pushSelfProfile(pubkeyHex) }
|
||||||
|
|
||||||
// --- Wallet & payments -------------------------------------------------
|
// --- Wallet & payments -------------------------------------------------
|
||||||
// These mirror the SDK surface added for the wallet screen. Payment sends
|
// These mirror the SDK surface added for the wallet screen. Payment sends
|
||||||
// are one-shot: if the peer's onion is unreachable, `send_*` fails now.
|
// are one-shot: if the peer's onion is unreachable, `send_*` fails now.
|
||||||
|
|
@ -551,15 +626,557 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
suspend fun sendTip(pubkeyHex: String, amountXmr: String, memo: String = ""): Result<Unit> =
|
suspend fun sendTip(pubkeyHex: String, amountXmr: String, memo: String = ""): Result<Unit> =
|
||||||
runCatching { requireWire().sendTip(pubkeyHex, amountXmr, memo) }
|
runCatching { requireWire().sendTip(pubkeyHex, amountXmr, memo) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a wallet and read its seed once. The seed-backup flag is reset
|
||||||
|
* here, not by the screen: every successful create is a new seed nobody has
|
||||||
|
* read, and a caller that forgot to reset it would leave a spend key
|
||||||
|
* unrecoverable. See [SeedBackupGate.afterWallet].
|
||||||
|
*/
|
||||||
suspend fun createWallet(password: String): Result<String> =
|
suspend fun createWallet(password: String): Result<String> =
|
||||||
runCatching { requireWire().createWallet(password) }
|
runCatching { requireWire().createWallet(password) }
|
||||||
|
.onSuccess { setWalletSeedConfirmed(SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Import a wallet from a user-supplied seed. That seed is already on paper —
|
||||||
|
* the user just pasted it — so the wallet counts as backed up without the
|
||||||
|
* confirm step.
|
||||||
|
*/
|
||||||
suspend fun importWallet(password: String, seed: String): Result<Unit> =
|
suspend fun importWallet(password: String, seed: String): Result<Unit> =
|
||||||
runCatching { requireWire().importWallet(password, seed) }
|
runCatching { requireWire().importWallet(password, seed) }
|
||||||
|
.onSuccess { setWalletSeedConfirmed(SeedBackupGate.afterWallet(WalletKeyOrigin.Imported)) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-read the open wallet's 25-word seed, for the "Back up seed" recovery
|
||||||
|
* path. A spend key: only ever called from that explicit user action, shown
|
||||||
|
* on the blocking card, and dropped. Never logged and never persisted.
|
||||||
|
*/
|
||||||
|
suspend fun walletSeed(): Result<String> =
|
||||||
|
runCatching { requireWire().walletSeed() }
|
||||||
|
|
||||||
|
// --- Wallet catalogue, the open wallet, and its secrets ----------------
|
||||||
|
// The saved-wallets screen's reads. The catalogue is a store read that
|
||||||
|
// never dials, so it goes to [Dispatchers.IO] like the other store reads in
|
||||||
|
// this file — a SQLCipher decrypt on the main thread is an ANR waiting for a
|
||||||
|
// slow device.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every wallet this install remembers, oldest first.
|
||||||
|
*
|
||||||
|
* A store read: it works with the wallet child stopped or never configured,
|
||||||
|
* and "no wallets" is an empty list rather than a failure — the caller must
|
||||||
|
* not render the two alike.
|
||||||
|
*/
|
||||||
|
suspend fun wallets(): Result<List<WalletRow>> =
|
||||||
|
withContext(Dispatchers.IO) { runCatching { requireWire().wallets() } }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The file name of the wallet the child currently has open, or null when it
|
||||||
|
* has none. The catalogue's in-use marker is this and nothing else.
|
||||||
|
*/
|
||||||
|
suspend fun activeWalletFilename(): Result<String?> =
|
||||||
|
withContext(Dispatchers.IO) { runCatching { requireWire().activeWalletFilename() } }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Point the wallet child at a catalogue wallet's file.
|
||||||
|
*
|
||||||
|
* Slow on purpose: a live child is stopped and started again onto the new
|
||||||
|
* file. The core refuses a name the catalogue does not hold, and that
|
||||||
|
* refusal is surfaced verbatim to the caller.
|
||||||
|
*/
|
||||||
|
suspend fun openWallet(filename: String): Result<Unit> =
|
||||||
|
withContext(Dispatchers.IO) { runCatching { requireWire().openWallet(filename) } }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open a saved wallet with a passphrase the user just typed, and remember it
|
||||||
|
* (sealed) once the wallet daemon has accepted it.
|
||||||
|
*
|
||||||
|
* This is what ends a `needs_passphrase` status — a wallet created before
|
||||||
|
* the passphrase was sealed, or created on another install. The core refuses
|
||||||
|
* an empty passphrase, a name the catalogue does not hold, and an install
|
||||||
|
* with no configured wallet RPC, all before it dials anything; a passphrase
|
||||||
|
* the daemon refuses is **not** stored, so the wallet stays `needs_passphrase`
|
||||||
|
* and the prompt stays up rather than looking fixed.
|
||||||
|
*
|
||||||
|
* The passphrase goes to a UniFFI `String` parameter, so one immutable copy
|
||||||
|
* exists for the life of the call — the same limit `openWith` documents for
|
||||||
|
* the store passphrase. It is never logged, never persisted here (the core
|
||||||
|
* seals it), and the caller drops its own reference. The live probe on
|
||||||
|
* success is a one-shot read, not a second poller: the wallet screen still
|
||||||
|
* owns the only loop.
|
||||||
|
*/
|
||||||
|
suspend fun openWalletWithPassphrase(filename: String, passphrase: String): Result<Unit> =
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
runCatching { requireWire().openWalletWithPassphrase(filename, passphrase) }
|
||||||
|
}.onSuccess {
|
||||||
|
// One live probe, so `needs_passphrase` flips and the prompt comes
|
||||||
|
// off the screen without waiting for the next tick of a loop that is
|
||||||
|
// only running while the wallet screen is up.
|
||||||
|
refreshWalletChild()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The **open** wallet's private keys, for the saved-wallets screen.
|
||||||
|
*
|
||||||
|
* Both values are spend secrets: only ever called from an explicit tap,
|
||||||
|
* never logged, never persisted, and dropped when the screen goes. There is
|
||||||
|
* deliberately no accessor for another catalogue row's keys — the only way
|
||||||
|
* to read a saved wallet's keys is to open it first.
|
||||||
|
*/
|
||||||
|
suspend fun walletKeys(): Result<WalletKeys> =
|
||||||
|
withContext(Dispatchers.IO) { runCatching { requireWire().walletKeys() } }
|
||||||
|
|
||||||
fun spendAuthorityWarning(): String = runCatching {
|
fun spendAuthorityWarning(): String = runCatching {
|
||||||
requireWire().spendAuthorityWarning()
|
requireWire().spendAuthorityWarning()
|
||||||
}.getOrElse {
|
}.getOrElse {
|
||||||
"this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed."
|
"this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed."
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Seed backup gate --------------------------------------------------
|
||||||
|
// Whether the open wallet's seed has been confirmed written down. This is
|
||||||
|
// NOT a secret — it is a boolean in app-local prefs, deliberately kept out
|
||||||
|
// of the Keystore-wrapped store under `filesDir/secrets`, which holds the
|
||||||
|
// passphrase and nothing else.
|
||||||
|
//
|
||||||
|
// The flow is nullable, and the null is load-bearing: nothing stored means
|
||||||
|
// "this install has never created or imported a wallet through this build",
|
||||||
|
// which is not the same as "the user created one and has not confirmed it".
|
||||||
|
// See [SeedBackupGate.warningVisible] for why the screen needs both.
|
||||||
|
|
||||||
|
private val seedBackupPrefs: SharedPreferences =
|
||||||
|
app.getSharedPreferences(SEED_BACKUP_PREFS, Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
private val _walletSeedConfirmed = MutableStateFlow(
|
||||||
|
if (seedBackupPrefs.contains(SEED_BACKED_UP_KEY)) {
|
||||||
|
seedBackupPrefs.getBoolean(SEED_BACKED_UP_KEY, false)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The stored seed-backup flag: `false` unconfirmed, `true` confirmed or
|
||||||
|
* imported, `null` nothing stored (an install that predates the flag).
|
||||||
|
*/
|
||||||
|
val walletSeedConfirmed: StateFlow<Boolean?> = _walletSeedConfirmed.asStateFlow()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One confirm step from the blocking seed card. The gate decides: a wrong
|
||||||
|
* word leaves the flag where it was, so this can never un-confirm a wallet.
|
||||||
|
*/
|
||||||
|
fun confirmWalletSeed(typed: String) {
|
||||||
|
setWalletSeedConfirmed(SeedBackupGate.afterConfirm(typed, _walletSeedConfirmed.value == true))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun setWalletSeedConfirmed(confirmed: Boolean) {
|
||||||
|
seedBackupPrefs.edit().putBoolean(SEED_BACKED_UP_KEY, confirmed).apply()
|
||||||
|
_walletSeedConfirmed.value = confirmed
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- App-owned wallet child (issue #107) -------------------------------
|
||||||
|
// The app owns `monero-wallet-rpc` instead of asking the user to start one
|
||||||
|
// and export `ONIONWIRE_WALLET_RPC`. The core's own states are surfaced
|
||||||
|
// verbatim: off / connecting / syncing / ready / exited. Nothing here
|
||||||
|
// invents a "starting…" state, and a child that died is never folded into
|
||||||
|
// "off" — see `ui/WalletChildStatusText.kt`.
|
||||||
|
|
||||||
|
/** The last `wallet_status()` snapshot, or null before the first read. */
|
||||||
|
private val _walletChild = MutableStateFlow<WalletChildStatus?>(null)
|
||||||
|
val walletChild: StateFlow<WalletChildStatus?> = _walletChild.asStateFlow()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The last failed start/stop/read, display-ready. Sticky on purpose, like
|
||||||
|
* [ChatState.error]: a transient store read that fails once must not blink
|
||||||
|
* off the screen on the next successful tick.
|
||||||
|
*/
|
||||||
|
private val _walletChildError = MutableStateFlow<String?>(null)
|
||||||
|
val walletChildError: StateFlow<String?> = _walletChildError.asStateFlow()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start is in flight. Core status stays `off` until Cuprate/`monerod` answers,
|
||||||
|
* so the screen must not wait on that snapshot to show that the tap landed.
|
||||||
|
*/
|
||||||
|
private val startInFlight = AtomicBoolean(false)
|
||||||
|
private val _walletChildStarting = MutableStateFlow(false)
|
||||||
|
val walletChildStarting: StateFlow<Boolean> = _walletChildStarting.asStateFlow()
|
||||||
|
|
||||||
|
/** The stored chain source + binary settings, for prefilling the editor. */
|
||||||
|
private val _chainSource = MutableStateFlow<ChainConfig?>(null)
|
||||||
|
val chainSource: StateFlow<ChainConfig?> = _chainSource.asStateFlow()
|
||||||
|
|
||||||
|
private var walletChildPoller: Job? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What this install can actually spawn. Read from
|
||||||
|
* `applicationInfo.nativeLibraryDir` — the only directory Android hands out
|
||||||
|
* executable — so the screen can say "not bundled" instead of offering a
|
||||||
|
* Start that can only fail.
|
||||||
|
*/
|
||||||
|
fun bundledBinaries(): WalletChildBinaryPaths =
|
||||||
|
WalletChildBinaries.resolve(
|
||||||
|
getApplication<Application>().applicationInfo.nativeLibraryDir,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the one wallet-child refresh loop for the wallet screen. Re-entering
|
||||||
|
* the screen while the loop is alive is a no-op: navigating to the wallet
|
||||||
|
* and back must never stack a second poller.
|
||||||
|
*/
|
||||||
|
fun openWalletChild() {
|
||||||
|
if (walletChildPoller?.isActive == true) return
|
||||||
|
walletChildPoller = viewModelScope.launch {
|
||||||
|
walletChildRefreshLoop(
|
||||||
|
tickMs = WALLET_CHILD_TICK_MS,
|
||||||
|
// The first paint is the cached read: it never dials, so the
|
||||||
|
// screen has a record to render while the first probe is still
|
||||||
|
// in flight.
|
||||||
|
cached = ::paintWalletChildCached,
|
||||||
|
// Every tick after that is a live probe, so `height` /
|
||||||
|
// `target_height` move on their own instead of only when a
|
||||||
|
// chain-mode button is tapped.
|
||||||
|
live = ::refreshWalletChild,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stops the loop when the wallet screen leaves. */
|
||||||
|
fun closeWalletChild() {
|
||||||
|
walletChildPoller?.cancel()
|
||||||
|
walletChildPoller = null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drops the last failure. The user has acted on it. */
|
||||||
|
fun clearWalletChildError() {
|
||||||
|
_walletChildError.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The first paint: one `wallet_status()` read.
|
||||||
|
*
|
||||||
|
* `Wire::wallet_status` is synchronous in Rust and re-reads the sealed
|
||||||
|
* wallet-child record out of the SQLCipher store, so it goes to
|
||||||
|
* [Dispatchers.IO] — a store decrypt on the main thread is an ANR waiting
|
||||||
|
* for a slow device. It never dials and never spawns, so it is the right
|
||||||
|
* read to have a record on screen — and the wrong one to poll with.
|
||||||
|
*/
|
||||||
|
suspend fun paintWalletChildCached() = readWalletChild { requireWire().walletStatus() }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One tick: a live probe, `Wire::wallet_child_refresh()`.
|
||||||
|
*
|
||||||
|
* `Wire::wallet_status` above only re-reads what the last probe left behind,
|
||||||
|
* so polling it pins the `sync h/t` segment on whatever the last
|
||||||
|
* start/stop saw. This one 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 the chain's height and target move between ticks.
|
||||||
|
*
|
||||||
|
* It never spawns a child, and the core short-circuits with the cached
|
||||||
|
* snapshot when there is no live child, so it cannot invent `ready` for a
|
||||||
|
* wallet that is not there. Not free, though: the tick stays on the order of
|
||||||
|
* seconds rather than frames.
|
||||||
|
*
|
||||||
|
* Failure is folded into the sticky [walletChildError], same as the cached
|
||||||
|
* read: a probe that fails once must not blink the previous error off the
|
||||||
|
* screen.
|
||||||
|
*/
|
||||||
|
suspend fun refreshWalletChild() = readWalletChild { requireWire().walletChildRefresh() }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs one of the two reads on [Dispatchers.IO] and lands it in the wallet
|
||||||
|
* state. `requireWire()` throws when the node is locked, so it is called
|
||||||
|
* *inside* the [runCatching] — a locked node has to surface as
|
||||||
|
* [walletChildError], not as a crash on the tick.
|
||||||
|
*/
|
||||||
|
private suspend fun readWalletChild(read: suspend () -> WalletChildStatus) {
|
||||||
|
val result = withContext(Dispatchers.IO) { runCatching { read() } }
|
||||||
|
result.fold(
|
||||||
|
onSuccess = { _walletChild.value = it },
|
||||||
|
onFailure = { _walletChildError.value = walletFailureText(it.message ?: it.toString()) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Re-reads the stored chain source so the editor can prefill from it. */
|
||||||
|
suspend fun refreshChainSource() {
|
||||||
|
val read = withContext(Dispatchers.IO) { runCatching { requireWire().chainSource() } }
|
||||||
|
read.onSuccess { _chainSource.value = it }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves a daemon the user typed, then leaves it to [startWalletChild] to
|
||||||
|
* spawn against it. `set_chain_source` only stores: the core validates the
|
||||||
|
* config before anything is written and a rejected config leaves the stored
|
||||||
|
* one — and any running child — untouched.
|
||||||
|
*
|
||||||
|
* [bins] is what this install resolved; the paths handed to the core are
|
||||||
|
* absolute, because nothing in an APK sandbox resolves a bare
|
||||||
|
* `monero-wallet-rpc` on `PATH`.
|
||||||
|
*/
|
||||||
|
suspend fun saveRemoteDaemon(
|
||||||
|
host: String,
|
||||||
|
port: Int,
|
||||||
|
bins: WalletChildBinaryPaths,
|
||||||
|
): Result<Unit> {
|
||||||
|
val rpc = bins.walletRpc
|
||||||
|
?: return Result.failure(IllegalStateException(NO_WALLET_RPC_MESSAGE))
|
||||||
|
return withContext(Dispatchers.IO) {
|
||||||
|
runCatching {
|
||||||
|
requireWire().setChainSource(
|
||||||
|
ChainConfig(
|
||||||
|
kind = ChainChoice.REMOTE,
|
||||||
|
monerodBin = "",
|
||||||
|
monerodDatadir = "",
|
||||||
|
host = host,
|
||||||
|
port = port.toUShort(),
|
||||||
|
walletRpcBin = rpc,
|
||||||
|
// Inert unless the host is a `.onion`; the screen refuses
|
||||||
|
// an onion daemon outright while no `arti` is bundled.
|
||||||
|
artiBin = expectedArtiPath(),
|
||||||
|
walletFilename = WalletChildBinaries.WALLET_FILENAME,
|
||||||
|
mainnet = false,
|
||||||
|
prune = false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}.onSuccess {
|
||||||
|
_walletChildError.value = null
|
||||||
|
refreshChainSource()
|
||||||
|
refreshWalletChild()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Back to receive-only: no child, no daemon, no chain traffic. The binary
|
||||||
|
* paths are still stored so switching back to a daemon does not need them
|
||||||
|
* re-derived.
|
||||||
|
*/
|
||||||
|
suspend fun setReceiveOnly(bins: WalletChildBinaryPaths): Result<Unit> =
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
runCatching {
|
||||||
|
requireWire().setChainSource(
|
||||||
|
ChainConfig(
|
||||||
|
kind = ChainChoice.NONE,
|
||||||
|
monerodBin = "",
|
||||||
|
monerodDatadir = "",
|
||||||
|
host = "",
|
||||||
|
port = 0u,
|
||||||
|
walletRpcBin = bins.walletRpc.orEmpty(),
|
||||||
|
artiBin = expectedArtiPath(),
|
||||||
|
walletFilename = WalletChildBinaries.WALLET_FILENAME,
|
||||||
|
mainnet = false,
|
||||||
|
prune = false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}.onSuccess {
|
||||||
|
_walletChildError.value = null
|
||||||
|
refreshChainSource()
|
||||||
|
refreshWalletChild()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The third chain source: the chain daemon **inside this app** (Cuprate), no
|
||||||
|
* `monerod` binary and no remote operator. Stores the setting; [startWalletChild]
|
||||||
|
* is what launches the node *and* the wallet child (one call in the core).
|
||||||
|
*
|
||||||
|
* `monerodDatadir` is left empty on purpose: the SDK resolves that to
|
||||||
|
* `$ONIONWIRE_HOME/chain/{testnet,mainnet-pruned,mainnet-full}` from
|
||||||
|
* [mainnet] and [prune], so Kotlin never invents an absolute path.
|
||||||
|
*/
|
||||||
|
suspend fun setInProcessCuprate(
|
||||||
|
bins: WalletChildBinaryPaths,
|
||||||
|
mainnet: Boolean,
|
||||||
|
prune: Boolean,
|
||||||
|
): Result<Unit> =
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
runCatching {
|
||||||
|
requireWire().setChainSource(
|
||||||
|
ChainConfig(
|
||||||
|
kind = ChainChoice.IN_PROCESS_CUPRATE,
|
||||||
|
monerodBin = "",
|
||||||
|
monerodDatadir = "",
|
||||||
|
host = "",
|
||||||
|
port = 0u,
|
||||||
|
walletRpcBin = bins.walletRpc.orEmpty(),
|
||||||
|
// Inert for this source: an in-process node is loopback
|
||||||
|
// clearnet, so the core never spawns the SOCKS child.
|
||||||
|
artiBin = expectedArtiPath(),
|
||||||
|
walletFilename = WalletChildBinaries.WALLET_FILENAME,
|
||||||
|
mainnet = mainnet,
|
||||||
|
prune = prune,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}.onSuccess {
|
||||||
|
_walletChildError.value = null
|
||||||
|
refreshChainSource()
|
||||||
|
refreshWalletChild()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Free bytes on the filesystem the in-process chain store grows into, or
|
||||||
|
* `null` when it cannot be read. The screen shows this before the user commits
|
||||||
|
* to a store on the device; it is a measurement, not an estimate.
|
||||||
|
*/
|
||||||
|
fun chainFreeBytes(): Long? = ChainStorage.freeBytes(home)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Repairs a stored `walletRpcBin` this device cannot execute, and reports
|
||||||
|
* whether it wrote anything back.
|
||||||
|
*
|
||||||
|
* A wallet-child record written by an older install can carry the bare name
|
||||||
|
* `monero-wallet-rpc` (or an empty string). Nothing in an APK sandbox
|
||||||
|
* resolves a bare name on `PATH`, so `start_wallet_child` spawns it and dies
|
||||||
|
* with `No such file or directory` — while the Start gate, which only ever
|
||||||
|
* looked at the *resolved* bundle, stayed green. This re-points the stored
|
||||||
|
* record at the absolute `nativeLibraryDir` path this install actually
|
||||||
|
* carries, before anything is spawned.
|
||||||
|
*
|
||||||
|
* What it deliberately does not do:
|
||||||
|
* - it never changes `kind`, host, port, mode, datadir or wallet filename —
|
||||||
|
* a repair of the binary is not a change of chain source;
|
||||||
|
* - it does nothing for receive-only (`ChainChoice.NONE`), which stores a
|
||||||
|
* bin it never spawns;
|
||||||
|
* - it never overwrites a stored path that exists and is executable, even
|
||||||
|
* when that path is not the bundled binary — a user who pointed at a real
|
||||||
|
* file keeps it;
|
||||||
|
* - it never fails loudly: a repair that cannot be made leaves the stored
|
||||||
|
* record alone, and the gate then names the path it will try to spawn.
|
||||||
|
*/
|
||||||
|
suspend fun healStoredWalletBin(bins: WalletChildBinaryPaths): Result<Boolean> =
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
runCatching {
|
||||||
|
val wire = requireWire()
|
||||||
|
val stored = runCatching { wire.chainSource() }.getOrNull()
|
||||||
|
?: return@runCatching false
|
||||||
|
if (stored.kind == ChainChoice.NONE) return@runCatching false
|
||||||
|
val healed = walletBinHealPath(stored.walletRpcBin, bins.walletRpc)
|
||||||
|
?: return@runCatching false
|
||||||
|
wire.setChainSource(
|
||||||
|
ChainConfig(
|
||||||
|
kind = stored.kind,
|
||||||
|
monerodBin = stored.monerodBin,
|
||||||
|
monerodDatadir = stored.monerodDatadir,
|
||||||
|
host = stored.host,
|
||||||
|
port = stored.port,
|
||||||
|
walletRpcBin = healed,
|
||||||
|
artiBin = stored.artiBin,
|
||||||
|
walletFilename = stored.walletFilename,
|
||||||
|
mainnet = stored.mainnet,
|
||||||
|
prune = stored.prune,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}.onSuccess { healed ->
|
||||||
|
if (healed) {
|
||||||
|
refreshChainSource()
|
||||||
|
refreshWalletChild()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Kick off start on [viewModelScope] so leaving the composition does not
|
||||||
|
* cancel Cuprate launch. Returns immediately; watch [walletChildStarting]
|
||||||
|
* and [walletChildError]. Core status stays `off` until the node answers.
|
||||||
|
*
|
||||||
|
* Self-heals the stored binary first, then re-reads that stored record and
|
||||||
|
* refuses to spawn when it still names a path this device cannot run. The
|
||||||
|
* screen's gate is the primary door, but an auto-start from a mode tap is
|
||||||
|
* not the only caller: this is the last place that can stop a doomed spawn,
|
||||||
|
* and the reason it writes is the named path rather than the core's opaque
|
||||||
|
* `spawn monero-wallet-rpc: …`.
|
||||||
|
*/
|
||||||
|
fun startWalletChild() {
|
||||||
|
if (!startInFlight.compareAndSet(false, true)) return
|
||||||
|
_walletChildStarting.value = true
|
||||||
|
_walletChildError.value = null
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val bins = bundledBinaries()
|
||||||
|
healStoredWalletBin(bins)
|
||||||
|
val stored = withContext(Dispatchers.IO) {
|
||||||
|
runCatching { requireWire().chainSource() }.getOrNull()
|
||||||
|
}
|
||||||
|
if (stored == null || stored.kind == ChainChoice.NONE) {
|
||||||
|
_walletChildError.value = NO_CHAIN_SOURCE_NOTICE
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
val blocked = storedWalletBinBlockedReason(stored.walletRpcBin, bins.walletRpc)
|
||||||
|
if (blocked != null) {
|
||||||
|
_walletChildError.value = blocked
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
val started = withContext(Dispatchers.IO) {
|
||||||
|
runCatching { requireWire().startWalletChild() }
|
||||||
|
}
|
||||||
|
started.fold(
|
||||||
|
onSuccess = { _walletChild.value = it },
|
||||||
|
onFailure = {
|
||||||
|
_walletChildError.value = walletFailureText(it.message ?: it.toString())
|
||||||
|
},
|
||||||
|
)
|
||||||
|
} finally {
|
||||||
|
startInFlight.set(false)
|
||||||
|
_walletChildStarting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stops the child and its siblings. Idempotent in the core. */
|
||||||
|
suspend fun stopWalletChild(): Result<Unit> {
|
||||||
|
_walletChildError.value = null
|
||||||
|
val stopped = withContext(Dispatchers.IO) {
|
||||||
|
runCatching { requireWire().stopWalletChild() }
|
||||||
|
}
|
||||||
|
stopped.fold(
|
||||||
|
onSuccess = { refreshWalletChild() },
|
||||||
|
onFailure = { _walletChildError.value = walletFailureText(it.message ?: it.toString()) },
|
||||||
|
)
|
||||||
|
return stopped
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The absolute path the core would be handed for the `arti` SOCKS child. */
|
||||||
|
private fun expectedArtiPath(): String = WalletChildBinaries.expectedPath(
|
||||||
|
getApplication<Application>().applicationInfo.nativeLibraryDir,
|
||||||
|
WalletChildBinaries.ARTI_LIB,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The wallet-child refresh loop: one [cached] paint so the screen has something
|
||||||
|
* to render, then a live [live] probe every [tickMs].
|
||||||
|
*
|
||||||
|
* The reads are parameters only so the JVM test tree can drive this loop
|
||||||
|
* without a `Wire` — `NodeHost.requireOpen()` is a process-global the unit test
|
||||||
|
* cannot prime. The two call sites in [WireViewModel.openWalletChild] bind them
|
||||||
|
* to the cached read and to the live probe.
|
||||||
|
*
|
||||||
|
* Serialized by construction, and that is the point: the loop suspends on each
|
||||||
|
* read before it sleeps, so a probe slower than [tickMs] delays the next tick
|
||||||
|
* instead of overlapping it. Do not turn this into a `Flow` with
|
||||||
|
* `collectLatest`, and do not `launch` the probe: two concurrent
|
||||||
|
* `wallet_child_refresh` calls against one wallet child is a racing probe.
|
||||||
|
*/
|
||||||
|
suspend fun walletChildRefreshLoop(
|
||||||
|
tickMs: Long,
|
||||||
|
cached: suspend () -> Unit,
|
||||||
|
live: suspend () -> Unit,
|
||||||
|
) {
|
||||||
|
cached()
|
||||||
|
while (currentCoroutineContext().isActive) {
|
||||||
|
delay(tickMs)
|
||||||
|
live()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cadence of the wallet-child refresh loop, in milliseconds. */
|
||||||
|
private const val WALLET_CHILD_TICK_MS: Long = 2_000
|
||||||
|
|
||||||
|
/**
|
||||||
|
* App-local prefs file for the seed-backup flag. Not a secret, so it is a plain
|
||||||
|
* prefs file rather than anything under `filesDir/secrets`.
|
||||||
|
*/
|
||||||
|
private const val SEED_BACKUP_PREFS: String = "wallet_seed_backup"
|
||||||
|
|
||||||
|
/** Key inside [SEED_BACKUP_PREFS]: has the open wallet's seed been written down? */
|
||||||
|
private const val SEED_BACKED_UP_KEY: String = "backed_up"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,15 @@
|
||||||
package com.siriusdevops.onionwire.crypto
|
package com.siriusdevops.onionwire.crypto
|
||||||
|
|
||||||
|
import android.app.KeyguardManager
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.security.keystore.KeyGenParameterSpec
|
import android.security.keystore.KeyGenParameterSpec
|
||||||
import android.security.keystore.KeyInfo
|
import android.security.keystore.KeyInfo
|
||||||
import android.security.keystore.KeyProperties
|
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.KeyStore
|
||||||
import java.security.ProviderException
|
import java.security.ProviderException
|
||||||
import javax.crypto.KeyGenerator
|
import javax.crypto.KeyGenerator
|
||||||
|
|
@ -13,7 +17,7 @@ import javax.crypto.SecretKey
|
||||||
import javax.crypto.SecretKeyFactory
|
import javax.crypto.SecretKeyFactory
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* AES-256-GCM key held by the Android Keystore under [ALIAS].
|
* 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
|
* The key material is never readable by this process (`SecretKey.encoded` is
|
||||||
* null for AndroidKeyStore keys) — that is the whole point: pulling
|
* null for AndroidKeyStore keys) — that is the whole point: pulling
|
||||||
|
|
@ -28,32 +32,99 @@ import javax.crypto.SecretKeyFactory
|
||||||
* fingerprint to unlock the node would turn "fail closed" into "unusable
|
* 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
|
* unattended", and the SDK's contract is that an unlock either opens the node
|
||||||
* or reports why it did not.
|
* 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 {
|
class KeystorePassphraseCipher(private val context: Context) :
|
||||||
|
PassphraseCipher,
|
||||||
|
PassphraseKeyMigration {
|
||||||
|
|
||||||
private var cached: SecretKey? = null
|
private var cached: ActiveKey? = null
|
||||||
|
|
||||||
override fun seal(plaintext: CharArray): ByteArray =
|
/** Why this process's attempt at an unlock-gated key failed, if it did. */
|
||||||
StoreSecret.seal(loadOrCreateKey(), plaintext)
|
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,
|
* 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
|
* 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.
|
* 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 {
|
override fun open(blob: ByteArray): CharArray {
|
||||||
val key = cached ?: existingKey()
|
val active = activeKey()
|
||||||
?: throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
|
?: throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
|
||||||
return StoreSecret.open(key, blob)
|
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 = (cached ?: existingKey()) != null
|
override fun keyPresent(): Boolean = activeKey() != null
|
||||||
|
|
||||||
override fun backing(): KeyBacking {
|
override fun backing(): KeyBacking {
|
||||||
val key = cached ?: existingKey() ?: return KeyBacking.UNKNOWN
|
val key = activeKey() ?: return KeyBacking.UNKNOWN
|
||||||
val info = try {
|
val info = try {
|
||||||
SecretKeyFactory.getInstance(key.algorithm, PROVIDER)
|
SecretKeyFactory.getInstance(key.secret.algorithm, PROVIDER)
|
||||||
.getKeySpec(key, KeyInfo::class.java) as KeyInfo
|
.getKeySpec(key.secret, KeyInfo::class.java) as KeyInfo
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
// Some OEM Keystore implementations refuse getKeySpec. Report
|
// Some OEM Keystore implementations refuse getKeySpec. Report
|
||||||
// UNKNOWN rather than guessing hardware backing.
|
// UNKNOWN rather than guessing hardware backing.
|
||||||
|
|
@ -71,47 +142,189 @@ class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher
|
||||||
return if (inSecureHardware) KeyBacking.HARDWARE else KeyBacking.SOFTWARE
|
return if (inSecureHardware) KeyBacking.HARDWARE else KeyBacking.SOFTWARE
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Deletes both aliases: `forget()` must leave nothing that can decrypt. */
|
||||||
override fun deleteKey() {
|
override fun deleteKey() {
|
||||||
cached = null
|
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 {
|
try {
|
||||||
keyStore().deleteEntry(ALIAS)
|
keyStore().deleteEntry(ALIAS)
|
||||||
} catch (_: Exception) {
|
} catch (e: Exception) {
|
||||||
// Nothing usable to delete.
|
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")
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun existingKey(): SecretKey? {
|
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 }
|
cached?.let { return it }
|
||||||
val key = try {
|
existingKey(ALIAS_UNLOCK_GATED)?.let { return ActiveKey(it, gated = true).also { k -> cached = k } }
|
||||||
keyStore().getKey(ALIAS, null) as? SecretKey
|
existingKey(ALIAS)?.let { return ActiveKey(it, gated = false).also { k -> cached = k } }
|
||||||
} catch (_: Exception) {
|
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
|
null
|
||||||
}
|
}
|
||||||
cached = key
|
|
||||||
return key
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun loadOrCreateKey(): SecretKey = cached ?: existingKey() ?: createKey()
|
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 createKey(): SecretKey {
|
private fun recordGateRefusal(e: Exception) {
|
||||||
val strongBoxAdvertised =
|
gateRefusal = "${e.javaClass.simpleName}: ${e.message}"
|
||||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
|
Log.w(
|
||||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
TAG,
|
||||||
if (strongBoxAdvertised) {
|
"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 {
|
try {
|
||||||
return generate(strongBox = true).also { cached = it }
|
return generate(alias, strongBox = true, unlockGated = unlockGated)
|
||||||
} catch (_: ProviderException) {
|
} catch (e: ProviderException) {
|
||||||
// StrongBoxUnavailableException is a ProviderException: the chip
|
// StrongBoxUnavailableException is a ProviderException: the chip
|
||||||
// exists but its slots are full, or it refuses AES-256. Fall
|
// exists but its slots are full, or it refuses AES-256. Fall
|
||||||
// through to a normal Keystore key instead of failing unlock.
|
// 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(strongBox = false).also { cached = it }
|
return generate(alias, strongBox = false, unlockGated = unlockGated)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun generate(strongBox: Boolean): SecretKey {
|
private fun generate(alias: String, strongBox: Boolean, unlockGated: Boolean): SecretKey {
|
||||||
val builder = KeyGenParameterSpec.Builder(
|
val builder = KeyGenParameterSpec.Builder(
|
||||||
ALIAS,
|
alias,
|
||||||
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
|
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
|
||||||
)
|
)
|
||||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||||
|
|
@ -119,7 +332,14 @@ class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher
|
||||||
.setKeySize(StoreSecret.KEY_BITS)
|
.setKeySize(StoreSecret.KEY_BITS)
|
||||||
// Our IV comes from Cipher.init, and the Keystore supplies it.
|
// Our IV comes from Cipher.init, and the Keystore supplies it.
|
||||||
.setRandomizedEncryptionRequired(true)
|
.setRandomizedEncryptionRequired(true)
|
||||||
|
// Locked decision: no fingerprint gate on an unattended node.
|
||||||
.setUserAuthenticationRequired(false)
|
.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) {
|
if (strongBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||||
builder.setIsStrongBoxBacked(true)
|
builder.setIsStrongBoxBacked(true)
|
||||||
}
|
}
|
||||||
|
|
@ -130,10 +350,114 @@ class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher
|
||||||
|
|
||||||
private fun keyStore(): KeyStore = KeyStore.getInstance(PROVIDER).apply { load(null) }
|
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 {
|
companion object {
|
||||||
const val PROVIDER = "AndroidKeyStore"
|
const val PROVIDER = "AndroidKeyStore"
|
||||||
|
|
||||||
/** One key per app: the passphrase it wraps is the only secret here. */
|
/** 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"
|
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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,27 @@ import java.io.IOException
|
||||||
* The blob is the envelope from [StoreSecret] — magic + IV + ciphertext + tag.
|
* The blob is the envelope from [StoreSecret] — magic + IV + ciphertext + tag.
|
||||||
* There is no second copy, no SharedPreferences mirror, and nothing outside the
|
* There is no second copy, no SharedPreferences mirror, and nothing outside the
|
||||||
* app's data dir.
|
* 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(
|
class StoredPassphraseStore(
|
||||||
private val file: File,
|
private val file: File,
|
||||||
|
|
@ -26,34 +47,53 @@ class StoredPassphraseStore(
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Something is stored but cannot be read: the Keystore key is gone or
|
* Something is stored but cannot be read: the Keystore key is gone or
|
||||||
* invalidated, or the file is corrupt. Fall back to typing.
|
* unusable, the device is locked, or the file is corrupt. Fall back to
|
||||||
|
* typing.
|
||||||
*/
|
*/
|
||||||
data class Unavailable(val reason: String) : Load
|
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
|
fun exists(): Boolean = file.isFile && file.length() > 0L
|
||||||
|
|
||||||
/** Where the wrapping key actually lives. See [PassphraseCipher.backing]. */
|
/** Where the wrapping key actually lives. See [PassphraseCipher.backing]. */
|
||||||
fun backing(): KeyBacking = cipher.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. */
|
/** Path for diagnostics in tests. Never logged with its contents. */
|
||||||
val path: String get() = file.absolutePath
|
val path: String get() = file.absolutePath
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Encrypts and replaces the stored blob. Atomic-ish: written to a sibling
|
* Encrypts and replaces the stored blob, then retires a pre-gate key.
|
||||||
* temp file and renamed, so a crash mid-write cannot leave half a blob.
|
*
|
||||||
|
* 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) {
|
fun save(passphrase: CharArray) {
|
||||||
require(passphrase.isNotEmpty()) { "refusing to store an empty passphrase" }
|
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)
|
val blob = cipher.seal(passphrase)
|
||||||
try {
|
try {
|
||||||
file.parentFile?.mkdirs()
|
val migration = migrator()
|
||||||
val tmp = File(file.parentFile, file.name + ".tmp")
|
val gated = migration?.unlockGateInEffect() == true
|
||||||
tmp.writeBytes(blob)
|
writeVerified(blob, passphrase, if (gated) migration else null)
|
||||||
if (!tmp.renameTo(file)) {
|
// The replacement blob is durable and proven. Only now may the
|
||||||
file.writeBytes(blob)
|
// pre-gate alias go: deleting it earlier would strand a blob.
|
||||||
tmp.delete()
|
if (gated) migration?.retireLegacyKey()
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
StoreSecret.wipe(blob)
|
StoreSecret.wipe(blob)
|
||||||
}
|
}
|
||||||
|
|
@ -62,6 +102,10 @@ class StoredPassphraseStore(
|
||||||
/**
|
/**
|
||||||
* Reads and decrypts the blob. The returned array is the caller's to wipe.
|
* 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
|
* A failed decrypt does **not** delete the blob: a transient Keystore
|
||||||
* failure must not silently destroy the user's only copy. Use [forget] to
|
* failure must not silently destroy the user's only copy. Use [forget] to
|
||||||
* drop it deliberately.
|
* drop it deliberately.
|
||||||
|
|
@ -73,13 +117,15 @@ class StoredPassphraseStore(
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
return Load.Unavailable("the stored passphrase file could not be read (${e.message})")
|
return Load.Unavailable("the stored passphrase file could not be read (${e.message})")
|
||||||
}
|
}
|
||||||
return try {
|
val passphrase = try {
|
||||||
Load.Loaded(cipher.open(blob))
|
cipher.open(blob)
|
||||||
} catch (e: SecretUnavailable) {
|
} catch (e: SecretUnavailable) {
|
||||||
Load.Unavailable(e.message ?: "the stored passphrase did not authenticate")
|
return Load.Unavailable(e.message ?: "the stored passphrase did not authenticate")
|
||||||
} finally {
|
} finally {
|
||||||
StoreSecret.wipe(blob)
|
StoreSecret.wipe(blob)
|
||||||
}
|
}
|
||||||
|
migrateOnSuccessfulUnlock(passphrase)
|
||||||
|
return Load.Loaded(passphrase)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Drops the ciphertext and the Keystore key. Irreversible. */
|
/** Drops the ciphertext and the Keystore key. Irreversible. */
|
||||||
|
|
@ -88,4 +134,71 @@ class StoredPassphraseStore(
|
||||||
File(file.parentFile, file.name + ".tmp").delete()
|
File(file.parentFile, file.name + ".tmp").delete()
|
||||||
cipher.deleteKey()
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
|
@ -44,8 +44,10 @@ class KeepAliveService : Service() {
|
||||||
return START_NOT_STICKY
|
return START_NOT_STICKY
|
||||||
}
|
}
|
||||||
|
|
||||||
if (NodeHost.current() == null) {
|
if (!NodeHost.hasWorkForKeepAlive()) {
|
||||||
// Nothing to keep alive. A notification here would be a lie.
|
// 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()
|
stopSelf()
|
||||||
return START_NOT_STICKY
|
return START_NOT_STICKY
|
||||||
}
|
}
|
||||||
|
|
@ -125,14 +127,20 @@ class KeepAliveService : Service() {
|
||||||
)
|
)
|
||||||
// Never the full v3 locator: a notification body is lock-screen public.
|
// Never the full v3 locator: a notification body is lock-screen public.
|
||||||
val short = onion.take(ONION_PREFIX)
|
val short = onion.take(ONION_PREFIX)
|
||||||
val text = if (short.isEmpty()) {
|
val opening = short.isEmpty() && NodeHost.isOpening()
|
||||||
getString(R.string.keep_alive_text)
|
val title = if (opening) {
|
||||||
|
getString(R.string.keep_alive_title_opening)
|
||||||
} else {
|
} else {
|
||||||
getString(R.string.keep_alive_text_onion, short)
|
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)
|
return NotificationCompat.Builder(this, CHANNEL_ID)
|
||||||
.setSmallIcon(R.drawable.ic_stat_onion)
|
.setSmallIcon(R.drawable.ic_stat_onion)
|
||||||
.setContentTitle(getString(R.string.keep_alive_title))
|
.setContentTitle(title)
|
||||||
.setContentText(text)
|
.setContentText(text)
|
||||||
.setContentIntent(open)
|
.setContentIntent(open)
|
||||||
.addAction(0, getString(R.string.keep_alive_stop), stop)
|
.addAction(0, getString(R.string.keep_alive_stop), stop)
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,15 @@
|
||||||
package com.siriusdevops.onionwire.keepalive
|
package com.siriusdevops.onionwire.keepalive
|
||||||
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Deferred
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.async
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import uniffi.onionwire_sdk.Wire
|
import uniffi.onionwire_sdk.Wire
|
||||||
import uniffi.onionwire_sdk.openWire
|
import uniffi.onionwire_sdk.openWire
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
@ -45,8 +46,8 @@ sealed interface KeepAliveStatus {
|
||||||
* service would have kept a notification up for a node the UI had already
|
* service would have kept a notification up for a node the UI had already
|
||||||
* killed. Neither side owns the node now; the policy does.
|
* killed. Neither side owns the node now; the policy does.
|
||||||
*
|
*
|
||||||
* Threading: every mutation runs on the main thread except the SDK call inside
|
* Threading: [open] runs on [scope] (IO). [wire] is volatile so the main
|
||||||
* [open], which is dispatched to [Dispatchers.IO] and hops back.
|
* thread can read [current] while bootstrap completes off-main.
|
||||||
*/
|
*/
|
||||||
object NodeHost {
|
object NodeHost {
|
||||||
|
|
||||||
|
|
@ -60,8 +61,23 @@ object NodeHost {
|
||||||
|
|
||||||
private val lifetime = NodeLifetime()
|
private val lifetime = NodeLifetime()
|
||||||
|
|
||||||
|
@Volatile
|
||||||
private var wire: Wire? = null
|
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
|
* 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()`
|
* node holds the sqlite file and Arti's state lock until `shutdown()`
|
||||||
|
|
@ -75,6 +91,21 @@ object NodeHost {
|
||||||
/** The live node, or null when locked. */
|
/** The live node, or null when locked. */
|
||||||
fun current(): Wire? = wire
|
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. */
|
/** The live node, or a hard error. Callers are UI paths that require unlock. */
|
||||||
fun requireOpen(): Wire = wire ?: error("locked")
|
fun requireOpen(): Wire = wire ?: error("locked")
|
||||||
|
|
||||||
|
|
@ -82,15 +113,37 @@ object NodeHost {
|
||||||
* Opens the node and anchors it to the UI.
|
* Opens the node and anchors it to the UI.
|
||||||
*
|
*
|
||||||
* Suspends inside Arti's bootstrap — minutes on a cold start — so this must
|
* Suspends inside Arti's bootstrap — minutes on a cold start — so this must
|
||||||
* never run on the main thread. Callers are `viewModelScope` coroutines.
|
* 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 {
|
suspend fun open(home: File, passphrase: String): Wire {
|
||||||
stopping?.join()
|
stopping?.join()
|
||||||
val opened = withContext(Dispatchers.IO) { openWire(home.absolutePath, passphrase) }
|
wire?.let { return it }
|
||||||
wire = opened
|
bootstrap?.let { return it.await() }
|
||||||
_keepAlive.value = KeepAliveStatus.Off
|
val job = scope.async {
|
||||||
lifetime.onOpened()
|
val opened = openWire(home.absolutePath, passphrase)
|
||||||
return opened
|
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. */
|
/** The UI is going away: finish, task swipe, or process death. */
|
||||||
|
|
@ -123,7 +176,12 @@ object NodeHost {
|
||||||
* stops the keep-alive first — a service that is still running would
|
* stops the keep-alive first — a service that is still running would
|
||||||
* re-anchor a node that no longer exists.
|
* re-anchor a node that no longer exists.
|
||||||
*/
|
*/
|
||||||
fun lock(): NodeAction = apply(lifetime.onLocked())
|
fun lock(): NodeAction {
|
||||||
|
bootstrap?.cancel()
|
||||||
|
bootstrap = null
|
||||||
|
claimedOpening = false
|
||||||
|
return apply(lifetime.onLocked())
|
||||||
|
}
|
||||||
|
|
||||||
private fun apply(action: NodeAction): NodeAction {
|
private fun apply(action: NodeAction): NodeAction {
|
||||||
when (action) {
|
when (action) {
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,6 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.foundation.text.KeyboardActions
|
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.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
|
||||||
|
|
@ -51,6 +50,9 @@ 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.KeyboardCapitalization
|
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||||
import androidx.compose.ui.unit.dp
|
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 androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import com.siriusdevops.onionwire.WireViewModel
|
import com.siriusdevops.onionwire.WireViewModel
|
||||||
import uniffi.onionwire_sdk.SendState
|
import uniffi.onionwire_sdk.SendState
|
||||||
|
|
@ -59,7 +61,7 @@ import uniffi.onionwire_sdk.SendState
|
||||||
@Composable
|
@Composable
|
||||||
fun ChatScreen(
|
fun ChatScreen(
|
||||||
vm: WireViewModel,
|
vm: WireViewModel,
|
||||||
/** The peer's ed25519 pubkey hex — the key the open chat's poller runs for. */
|
/** The peer's public key, hex — the key the open chat's poller runs for. */
|
||||||
peer: String,
|
peer: String,
|
||||||
title: String,
|
title: String,
|
||||||
fingerprint: String,
|
fingerprint: String,
|
||||||
|
|
@ -184,7 +186,11 @@ 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,
|
||||||
|
|
@ -382,7 +388,8 @@ fun ChatScreen(
|
||||||
// Always drawn, never swapped out for a spinner: a button that
|
// Always drawn, never swapped out for a spinner: a button that
|
||||||
// changes size under the thumb — or disappears — is how "I hit
|
// changes size under the thumb — or disappears — is how "I hit
|
||||||
// send and nothing happened" gets reported.
|
// send and nothing happened" gets reported.
|
||||||
Button(
|
OwButton(
|
||||||
|
text = "Send",
|
||||||
enabled = draft.isNotBlank() && pending == null,
|
enabled = draft.isNotBlank() && pending == null,
|
||||||
onClick = send,
|
onClick = send,
|
||||||
modifier = Modifier.testTag("chat-send"),
|
modifier = Modifier.testTag("chat-send"),
|
||||||
|
|
|
||||||
|
|
@ -8,8 +8,18 @@ import androidx.compose.foundation.layout.systemBars
|
||||||
import androidx.compose.foundation.layout.union
|
import androidx.compose.foundation.layout.union
|
||||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.staticCompositionLocalOf
|
||||||
import androidx.compose.ui.Modifier
|
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
|
* The bottom + horizontal window insets one screen's content root must apply
|
||||||
* itself.
|
* itself.
|
||||||
|
|
@ -25,7 +35,9 @@ import androidx.compose.ui.Modifier
|
||||||
*
|
*
|
||||||
* The IME's bottom inset already covers the navigation bar, so the two are
|
* The IME's bottom inset already covers the navigation bar, so the two are
|
||||||
* unioned (per-side `max`), never summed: keyboard height while typing,
|
* unioned (per-side `max`), never summed: keyboard height while typing,
|
||||||
* navigation-bar height otherwise, and no double padding in between.
|
* 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
|
* 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
|
* bar's own measured height, and the app bar carries its own status-bar inset
|
||||||
|
|
@ -38,8 +50,15 @@ import androidx.compose.ui.Modifier
|
||||||
* composable reads — call it from a composable (every call site is one).
|
* composable reads — call it from a composable (every call site is one).
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun Modifier.screenContentInsets(): Modifier =
|
fun Modifier.screenContentInsets(): Modifier {
|
||||||
windowInsetsPadding(
|
val sides = if (LocalBottomBarPresent.current) {
|
||||||
WindowInsets.systemBars.union(WindowInsets.ime)
|
WindowInsetsSides.Horizontal
|
||||||
|
} else {
|
||||||
|
WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom
|
||||||
|
}
|
||||||
|
return windowInsetsPadding(
|
||||||
|
WindowInsets.systemBars.only(sides)
|
||||||
|
.union(WindowInsets.ime)
|
||||||
.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom),
|
.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom),
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,9 @@
|
||||||
package com.siriusdevops.onionwire.ui
|
package com.siriusdevops.onionwire.ui
|
||||||
|
|
||||||
import android.content.ClipData
|
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
|
||||||
|
|
@ -11,20 +14,13 @@ 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
|
||||||
|
|
@ -32,15 +28,37 @@ 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.ClipEntry
|
import androidx.compose.ui.platform.ClipEntry
|
||||||
import androidx.compose.ui.platform.LocalClipboard
|
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) }
|
||||||
|
|
@ -56,18 +74,11 @@ fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) {
|
||||||
}
|
}
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = { OwTopBar(title = "Your invite", onBack = onBack) },
|
||||||
TopAppBar(
|
|
||||||
title = { Text("Your invite") },
|
|
||||||
navigationIcon = { IconButton(onClick = onBack) { Text("<") } },
|
|
||||||
colors = TopAppBarDefaults.topAppBarColors(
|
|
||||||
containerColor = MaterialTheme.colorScheme.background,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
// The root applies systemBars + IME itself (see `screenContentInsets`),
|
// The root applies systemBars + IME itself (see `screenContentInsets`),
|
||||||
// so Scaffold must not also pad for the navigation bar.
|
// so Scaffold must not also pad for the navigation bar.
|
||||||
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
||||||
|
containerColor = OwColors.Canvas,
|
||||||
) { pad ->
|
) { pad ->
|
||||||
Column(
|
Column(
|
||||||
Modifier
|
Modifier
|
||||||
|
|
@ -75,70 +86,123 @@ fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) {
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.screenContentInsets()
|
.screenContentInsets()
|
||||||
.verticalScroll(rememberScrollState())
|
.verticalScroll(rememberScrollState())
|
||||||
.padding(16.dp),
|
.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(
|
||||||
scope.launch {
|
text = if (copied) "Copied" else "Copy invite",
|
||||||
clipboard.setClipEntry(
|
onClick = {
|
||||||
ClipEntry(ClipData.newPlainText("onionwire invite", invite!!)),
|
scope.launch {
|
||||||
)
|
val clip = ClipData.newPlainText("onionwire invite", payload)
|
||||||
copied = true
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
}
|
clip.description.extras = PersistableBundle().apply {
|
||||||
}) { Text(if (copied) "Copied" else "Copy") }
|
putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
clipboard.setClipEntry(ClipEntry(clip))
|
||||||
|
copied = true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
leadingIconRes = R.drawable.ic_ow_copy,
|
||||||
|
)
|
||||||
|
OwButton(
|
||||||
|
text = "Done",
|
||||||
|
variant = OwButtonVariant.Outline,
|
||||||
|
onClick = onBack,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
Spacer(Modifier.height(20.dp))
|
Spacer(Modifier.height(24.dp))
|
||||||
Text("What is in it", style = MaterialTheme.typography.titleSmall)
|
OwCard(Modifier.fillMaxWidth()) {
|
||||||
Spacer(Modifier.height(6.dp))
|
Text(
|
||||||
Mono("k ed25519 identity pubkey — who you are")
|
"What is in it",
|
||||||
Mono("o current onion locator — where you are now")
|
style = MaterialTheme.typography.titleSmall,
|
||||||
Mono("spk x25519 signed prekey — session start material")
|
color = OwColors.TextPrimary,
|
||||||
Mono("sig signature over k‖o‖spk — reject if it fails")
|
)
|
||||||
Spacer(Modifier.height(12.dp))
|
Spacer(Modifier.height(8.dp))
|
||||||
Text(
|
InviteField("k", "ed25519 identity pubkey — who you are")
|
||||||
"The onion in here goes stale when you rotate. The key does not. " +
|
InviteField("o", "current onion locator — where you are now")
|
||||||
"If you re-share later, the same k updates their entry — it never " +
|
InviteField("spk", "x25519 signed prekey — session start material")
|
||||||
"creates a second friend.",
|
InviteField("sig", "signature over k‖o‖spk — reject if it fails")
|
||||||
style = MaterialTheme.typography.bodySmall,
|
Spacer(Modifier.height(10.dp))
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
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,
|
||||||
|
|
@ -155,19 +219,12 @@ fun PasteInviteScreen(
|
||||||
val adding = flow.adding
|
val adding = flow.adding
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = { OwTopBar(title = "Add contact", onBack = onBack) },
|
||||||
TopAppBar(
|
|
||||||
title = { Text("Add a friend") },
|
|
||||||
navigationIcon = { IconButton(onClick = onBack) { Text("<") } },
|
|
||||||
colors = TopAppBarDefaults.topAppBarColors(
|
|
||||||
containerColor = MaterialTheme.colorScheme.background,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
// Same inset handoff as the chat composer: with the keyboard up, the
|
// Same inset handoff as the chat composer: with the keyboard up, the
|
||||||
// Verify / Approve buttons under the invite field must still be
|
// Verify / Approve buttons under the invite field must still be
|
||||||
// reachable by scrolling, not by dismissing the keyboard.
|
// reachable by scrolling, not by dismissing the keyboard.
|
||||||
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
||||||
|
containerColor = OwColors.Canvas,
|
||||||
) { pad ->
|
) { pad ->
|
||||||
Column(
|
Column(
|
||||||
Modifier
|
Modifier
|
||||||
|
|
@ -175,90 +232,83 @@ fun PasteInviteScreen(
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.screenContentInsets()
|
.screenContentInsets()
|
||||||
.verticalScroll(rememberScrollState())
|
.verticalScroll(rememberScrollState())
|
||||||
.padding(16.dp),
|
.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(
|
Label("THEY ARE")
|
||||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
Spacer(Modifier.height(2.dp))
|
||||||
),
|
Mono(shortId(p.pubkeyHex, head = 12, tail = 8))
|
||||||
modifier = Modifier.fillMaxWidth(),
|
Spacer(Modifier.height(6.dp))
|
||||||
) {
|
Text(
|
||||||
Column(Modifier.padding(12.dp)) {
|
"Compare this fingerprint with them over a second channel " +
|
||||||
Label("THEY ARE")
|
"before you trust it.",
|
||||||
Mono(p.pubkeyHex)
|
style = MaterialTheme.typography.bodySmall,
|
||||||
Spacer(Modifier.height(8.dp))
|
color = OwColors.TextSecondary,
|
||||||
Text(
|
)
|
||||||
"fingerprint ${p.pubkeyHex.take(16)}… — compare this with them " +
|
Spacer(Modifier.height(10.dp))
|
||||||
"over a second channel before you trust it.",
|
OwDivider()
|
||||||
style = MaterialTheme.typography.bodySmall,
|
Spacer(Modifier.height(10.dp))
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
Label("REACHABLE AT")
|
||||||
)
|
Spacer(Modifier.height(2.dp))
|
||||||
Spacer(Modifier.height(8.dp))
|
Mono(shortOnion(p.onion))
|
||||||
Label("REACHABLE AT")
|
|
||||||
Mono(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))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -130,8 +130,13 @@ fun parseDelivery(direction: String, delivery: String?): Delivery? {
|
||||||
/**
|
/**
|
||||||
* Chat-level delivery summary derived from the rendered rows.
|
* Chat-level delivery summary derived from the rendered rows.
|
||||||
*
|
*
|
||||||
* Mirrors `src/tui.rs::OutboxSummary`: `Queued` + `Sending` are "still coming",
|
* The *counting* rule mirrors `src/tui.rs::OutboxSummary`: `Queued` + `Sending`
|
||||||
* `Failed` is terminal and keeps a fail-closed statement on screen.
|
* 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(
|
data class OutboxSummary(
|
||||||
val queued: Int = 0,
|
val queued: Int = 0,
|
||||||
|
|
|
||||||
|
|
@ -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."
|
||||||
|
}
|
||||||
|
|
@ -1,8 +1,14 @@
|
||||||
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
|
||||||
|
|
@ -11,240 +17,363 @@ 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>,
|
||||||
keepAliveNote: String?,
|
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,
|
||||||
onOpenWallet: () -> 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
|
// The content root below consumes systemBars ∪ ime itself (see
|
||||||
// `screenContentInsets`); zeroing the Scaffold's own insets keeps the
|
// `screenContentInsets`), and the tab bar above this screen consumes the
|
||||||
// navigation bar from being applied twice and lets the wipe-confirm
|
// navigation-bar inset; zeroing the Scaffold's own insets is what keeps
|
||||||
// strip sit above the keyboard instead of under it.
|
// the list from being padded twice.
|
||||||
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
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().screenContentInsets()) {
|
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(
|
|
||||||
"sdk $sdkVersion · identity = ed25519 pubkey",
|
|
||||||
style = MaterialTheme.typography.labelSmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
if (keepAliveNote != null) {
|
|
||||||
Spacer(Modifier.height(10.dp))
|
|
||||||
Text(
|
|
||||||
keepAliveNote,
|
|
||||||
style = MaterialTheme.typography.labelSmall,
|
|
||||||
color = MaterialTheme.colorScheme.primary,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
}
|
onShare = onShare,
|
||||||
|
)
|
||||||
|
|
||||||
Spacer(Modifier.height(8.dp))
|
Spacer(Modifier.height(12.dp))
|
||||||
Row(
|
|
||||||
modifier = 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 = onOpenWallet) { Text("Wallet") }
|
|
||||||
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()) {
|
||||||
Column(
|
EmptyRoster(
|
||||||
Modifier.fillMaxSize().padding(24.dp),
|
modifier = Modifier.weight(1f),
|
||||||
verticalArrangement = Arrangement.Center,
|
onPaste = onPaste,
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
onShare = onShare,
|
||||||
) {
|
)
|
||||||
Text("No friends yet", style = MaterialTheme.typography.titleMedium)
|
|
||||||
Spacer(Modifier.height(8.dp))
|
|
||||||
Text(
|
|
||||||
"Share your invite over a channel you already trust, or paste " +
|
|
||||||
"someone else's. Invites are not discoverable — nothing is published.",
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
// weight(1f), not fillMaxSize(): the list must yield height to
|
|
||||||
// its siblings (the action row and the wipe-confirm strip above
|
|
||||||
// it) when the IME shrinks the window, instead of claiming all
|
|
||||||
// of it and pushing them off the bottom.
|
|
||||||
LazyColumn(Modifier.weight(1f).fillMaxWidth()) {
|
LazyColumn(Modifier.weight(1f).fillMaxWidth()) {
|
||||||
items(friends, key = { it.pubkeyHex }) { f ->
|
items(friends, key = { it.pubkeyHex }) { f ->
|
||||||
FriendRow(f) { onOpenChat(f) }
|
FriendRow(f) { onOpenChat(f) }
|
||||||
HorizontalDivider()
|
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(
|
||||||
|
modifier = modifier.fillMaxWidth().padding(horizontal = 24.dp),
|
||||||
|
verticalArrangement = Arrangement.Center,
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.width(64.dp)
|
||||||
|
.height(64.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(OwColors.Surface),
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
Text(
|
||||||
|
"No contacts yet",
|
||||||
|
style = MaterialTheme.typography.titleMedium.copy(fontSize = 18.sp, lineHeight = 24.sp),
|
||||||
|
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,
|
||||||
) {
|
) {
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Column(Modifier.weight(1f)) {
|
||||||
Text(
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
f.petname?.takeIf { it.isNotBlank() } ?: f.fingerprint,
|
|
||||||
style = MaterialTheme.typography.titleSmall,
|
|
||||||
)
|
|
||||||
if (!f.lastConnectOk) {
|
|
||||||
Spacer(Modifier.height(0.dp))
|
|
||||||
Text(
|
Text(
|
||||||
" locator stale",
|
f.petname?.takeIf { it.isNotBlank() } ?: f.fingerprint,
|
||||||
style = MaterialTheme.typography.labelSmall,
|
style = MaterialTheme.typography.titleSmall,
|
||||||
color = MaterialTheme.colorScheme.error,
|
color = OwColors.TextPrimary,
|
||||||
)
|
)
|
||||||
|
if (!f.lastConnectOk) {
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
OwStatusDot(OwColors.Warning)
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text(
|
||||||
|
"locator stale",
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = OwColors.Warning,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
Spacer(Modifier.height(3.dp))
|
||||||
Spacer(Modifier.height(2.dp))
|
Text(
|
||||||
Text(
|
shortId(f.fingerprint),
|
||||||
f.fingerprint,
|
style = MonoStyle,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
color = OwColors.TextSecondary,
|
||||||
fontFamily = FontFamily.Monospace,
|
)
|
||||||
color = MaterialTheme.colorScheme.primary,
|
Text(
|
||||||
)
|
shortOnion(f.onion),
|
||||||
Text(
|
style = MonoStyle.copy(color = OwColors.TextMuted),
|
||||||
f.onion,
|
|
||||||
style = MaterialTheme.typography.labelSmall,
|
|
||||||
fontFamily = FontFamily.Monospace,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun Label(text: String) {
|
|
||||||
Text(
|
|
||||||
text,
|
|
||||||
style = MaterialTheme.typography.labelSmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun Mono(text: String) {
|
|
||||||
Text(
|
|
||||||
text,
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
fontFamily = FontFamily.Monospace,
|
|
||||||
color = MaterialTheme.colorScheme.onSurface,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun ConfirmStrip(
|
|
||||||
text: String,
|
|
||||||
confirm: String,
|
|
||||||
onConfirm: () -> Unit,
|
|
||||||
onCancel: () -> Unit,
|
|
||||||
) {
|
|
||||||
var typed by remember { mutableStateOf("") }
|
|
||||||
Card(
|
|
||||||
modifier = Modifier.fillMaxWidth().padding(12.dp),
|
|
||||||
colors = CardDefaults.cardColors(
|
|
||||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
|
||||||
),
|
|
||||||
) {
|
|
||||||
Column(Modifier.padding(12.dp)) {
|
|
||||||
Text(text, style = MaterialTheme.typography.bodySmall)
|
|
||||||
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") }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
Text("›", style = MaterialTheme.typography.titleMedium, color = OwColors.TextMuted)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clipboard handling for the invite.
|
||||||
|
*
|
||||||
|
* The invite is a locator plus a prekey: it is a secret-ish string that opens a
|
||||||
|
* conversation with you, so the clip is marked sensitive (API 33+) — it will not
|
||||||
|
* 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))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The compact stand-in for a long identity string: `head` characters, an
|
||||||
|
* ellipsis, then `tail` characters. Pure, so the roster's line and its unit test
|
||||||
|
* agree on what "short" means.
|
||||||
|
*
|
||||||
|
* A string no longer than the abbreviation is returned unchanged — the
|
||||||
|
* 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A v3 onion locator shortened for a roster row, with the `.onion` suffix kept
|
||||||
|
* visible: `abcdefghij…uvwxyz.onion`.
|
||||||
|
*
|
||||||
|
* The suffix is the part that tells a reader this is an onion address at all, so
|
||||||
|
* 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
|
||||||
|
* cannot be copied reliably.
|
||||||
|
*/
|
||||||
|
fun shortOnion(onion: String, head: Int = 10, tail: Int = 6): String {
|
||||||
|
val suffix = ".onion"
|
||||||
|
if (onion.isEmpty()) return onion
|
||||||
|
if (!onion.endsWith(suffix)) return onion
|
||||||
|
val body = onion.removeSuffix(suffix)
|
||||||
|
if (body.length <= head + tail + 1) return onion
|
||||||
|
return body.take(head) + "…" + body.takeLast(tail) + suffix
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,6 @@ 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
|
||||||
|
|
@ -29,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.
|
||||||
|
|
@ -54,7 +59,13 @@ 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,
|
||||||
),
|
),
|
||||||
|
|
@ -99,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()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -141,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,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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."
|
||||||
|
}
|
||||||
|
|
@ -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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ 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.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
|
||||||
|
|
@ -27,6 +28,7 @@ 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
|
||||||
|
|
@ -61,10 +63,19 @@ fun UnlockScreen(
|
||||||
// Only meaningful under OneTap: reveal the form without giving up the
|
// Only meaningful under OneTap: reveal the form without giving up the
|
||||||
// stored passphrase.
|
// stored passphrase.
|
||||||
var typeInstead by remember { mutableStateOf(false) }
|
var typeInstead by remember { mutableStateOf(false) }
|
||||||
|
val keyboard = LocalSoftwareKeyboardController.current
|
||||||
|
|
||||||
val oneTap = unlock as? Unlock.OneTap
|
val oneTap = unlock as? Unlock.OneTap
|
||||||
val failed = phase is Phase.Failed
|
val failed = phase is Phase.Failed
|
||||||
val showForm = oneTap == null || typeInstead || 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
|
||||||
|
|
@ -151,7 +162,11 @@ fun UnlockScreen(
|
||||||
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(),
|
||||||
|
|
@ -189,13 +204,7 @@ fun UnlockScreen(
|
||||||
|
|
||||||
Spacer(Modifier.height(20.dp))
|
Spacer(Modifier.height(20.dp))
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = { submit() },
|
||||||
val typed = pass
|
|
||||||
// Drop the plaintext from Compose state the moment
|
|
||||||
// it is handed over; the ViewModel wipes its copy.
|
|
||||||
pass = ""
|
|
||||||
onUnlock(typed, storePassphrase)
|
|
||||||
},
|
|
||||||
enabled = pass.isNotEmpty(),
|
enabled = pass.isNotEmpty(),
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
) { Text("Open") }
|
) { Text("Open") }
|
||||||
|
|
|
||||||
|
|
@ -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)
|
||||||
|
}
|
||||||
|
|
@ -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"
|
||||||
|
}
|
||||||
|
|
@ -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
|
|
@ -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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -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),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -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() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -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()
|
||||||
|
}
|
||||||
|
|
@ -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."
|
||||||
BIN
android/app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so
Executable file
BIN
android/app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so
Executable file
Binary file not shown.
11
android/app/src/main/res/drawable/ic_ow_add.xml
Normal file
11
android/app/src/main/res/drawable/ic_ow_add.xml
Normal 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>
|
||||||
11
android/app/src/main/res/drawable/ic_ow_chat.xml
Normal file
11
android/app/src/main/res/drawable/ic_ow_chat.xml
Normal 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>
|
||||||
15
android/app/src/main/res/drawable/ic_ow_chevron_left.xml
Normal file
15
android/app/src/main/res/drawable/ic_ow_chevron_left.xml
Normal 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>
|
||||||
18
android/app/src/main/res/drawable/ic_ow_copy.xml
Normal file
18
android/app/src/main/res/drawable/ic_ow_copy.xml
Normal 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>
|
||||||
16
android/app/src/main/res/drawable/ic_ow_info.xml
Normal file
16
android/app/src/main/res/drawable/ic_ow_info.xml
Normal 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>
|
||||||
16
android/app/src/main/res/drawable/ic_ow_lock.xml
Normal file
16
android/app/src/main/res/drawable/ic_ow_lock.xml
Normal 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>
|
||||||
11
android/app/src/main/res/drawable/ic_ow_more_vert.xml
Normal file
11
android/app/src/main/res/drawable/ic_ow_more_vert.xml
Normal 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>
|
||||||
18
android/app/src/main/res/drawable/ic_ow_person.xml
Normal file
18
android/app/src/main/res/drawable/ic_ow_person.xml
Normal 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>
|
||||||
16
android/app/src/main/res/drawable/ic_ow_qr.xml
Normal file
16
android/app/src/main/res/drawable/ic_ow_qr.xml
Normal 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>
|
||||||
18
android/app/src/main/res/drawable/ic_ow_share.xml
Normal file
18
android/app/src/main/res/drawable/ic_ow_share.xml
Normal 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>
|
||||||
18
android/app/src/main/res/drawable/ic_ow_shield.xml
Normal file
18
android/app/src/main/res/drawable/ic_ow_shield.xml
Normal 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>
|
||||||
22
android/app/src/main/res/drawable/ic_ow_sliders.xml
Normal file
22
android/app/src/main/res/drawable/ic_ow_sliders.xml
Normal 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>
|
||||||
13
android/app/src/main/res/drawable/ic_ow_wallet.xml
Normal file
13
android/app/src/main/res/drawable/ic_ow_wallet.xml
Normal 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>
|
||||||
21
android/app/src/main/res/drawable/ic_ow_warning.xml
Normal file
21
android/app/src/main/res/drawable/ic_ow_warning.xml
Normal 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>
|
||||||
|
|
@ -10,7 +10,9 @@
|
||||||
<string name="keep_alive_channel_name">Node keep-alive</string>
|
<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_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">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">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_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_stop">Stop keep-alive</string>
|
||||||
<string name="keep_alive_note_off">Reachable only while this app is open.</string>
|
<string name="keep_alive_note_off">Reachable only while this app is open.</string>
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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(""))
|
||||||
|
}
|
||||||
|
}
|
||||||
1
android/monero-binaries.sha256
Normal file
1
android/monero-binaries.sha256
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
d9126788030ecd1ccdb40c7764e66e9a14d158a147ad335b256f0577681b5ad4 app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so
|
||||||
|
|
@ -52,6 +52,108 @@ 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")
|
||||||
|
|
||||||
|
|
@ -61,7 +163,16 @@ val cargoTargetDir: File = System.getenv("CARGO_TARGET_DIR")?.let(::File)
|
||||||
?: sdkCrateDir.resolve("target")
|
?: sdkCrateDir.resolve("target")
|
||||||
val hostCdylib: File = cargoTargetDir.resolve("release/libonionwire_sdk.so")
|
val hostCdylib: File = cargoTargetDir.resolve("release/libonionwire_sdk.so")
|
||||||
|
|
||||||
/** Host cdylib. UniFFI's `--library` mode dlopens it, so it must be host-arch. */
|
/**
|
||||||
|
* 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)."
|
||||||
|
|
@ -99,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")
|
||||||
|
|
@ -110,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",
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
@ -164,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)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
2341
crates/onionwire-sdk/Cargo.lock
generated
2341
crates/onionwire-sdk/Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -2,16 +2,16 @@
|
||||||
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
|
||||||
# Arti's TLS backends (`native-tls` vs `rustls`) are non-additive: exactly one
|
# crate set (Android: `static-sqlite`, rustls TLS), so it path-depends on the
|
||||||
# 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"
|
resolver = "2"
|
||||||
|
|
@ -20,10 +20,20 @@ resolver = "2"
|
||||||
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",
|
||||||
|
|
|
||||||
|
|
@ -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.
|
||||||
|
|
||||||
|
|
@ -104,6 +104,33 @@ val msgs: List<ChatMessage> = wire.messages(friend.pubkeyHex)
|
||||||
// 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
|
||||||
|
|
@ -126,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
|
|
@ -12,31 +12,41 @@ Direct dependencies that come from the Arti repository, exactly as
|
||||||
|
|
||||||
| crate | requirement | features in `Cargo.toml` |
|
| crate | requirement | features in `Cargo.toml` |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `arti-client` | `0.46` | `default-features = false`; `tokio`, `onion-service-client`, `onion-service-service`, `compression` |
|
| `arti-client` | `0.49` | `default-features = false`; `tokio`, `onion-service-client`, `onion-service-service`, `compression` |
|
||||||
| `tor-cell` | `0.46` | — |
|
| `tor-cell` | `0.49` | — |
|
||||||
| `tor-hsservice` | `0.46` | — |
|
| `tor-hsservice` | `0.49` | — |
|
||||||
| `tor-rtcompat` | `0.46` | `tokio` |
|
| `tor-rtcompat` | `0.49` | `tokio` |
|
||||||
|
| `safelog` | `0.10` | — |
|
||||||
|
|
||||||
`snow`, `rusqlite`, `ratatui`, and the rest are unrelated to Arti and are not
|
`snow`, `rusqlite`, `ratatui`, and the rest are unrelated to Arti and are not
|
||||||
part of a Tor upgrade.
|
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
|
Two crate features re-expose Arti's TLS backends, which Arti marks
|
||||||
**non-additive** — exactly one may be selected per build graph:
|
**non-additive** — exactly one may be selected per build graph:
|
||||||
|
|
||||||
* `native-tls` (default) → Linux TUI build, via OpenSSL.
|
* `rustls` (**default**) → every build: the Linux TUI, the released binaries and
|
||||||
* `rustls` → the Android SDK crate (`crates/onionwire-sdk`), because the NDK has
|
the Android SDK. No system OpenSSL is needed for TLS; the root `Cargo.toml`
|
||||||
no OpenSSL.
|
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 four crates together in lockstep. Bump them as
|
Published Arti releases move all of the crates above together in lockstep.
|
||||||
**one set**. A mixed set (e.g. `arti-client` 0.47 with `tor-hsservice` 0.46) is
|
Bump them as **one set**. A mixed set (e.g. `arti-client` 0.47 with
|
||||||
not a configuration anyone tests upstream, and cargo will usually refuse or
|
`tor-hsservice` 0.49) is not a configuration anyone tests upstream, and cargo
|
||||||
silently pick one `tor-*` version and mismatched `tor-*` internals fail at
|
will usually refuse or silently pick one `tor-*` version and mismatched
|
||||||
runtime.
|
`tor-*` internals fail at runtime.
|
||||||
|
|
||||||
## Toolchain floor
|
## Toolchain floor
|
||||||
|
|
||||||
**rustc 1.91+.** `Cargo.toml` sets `edition = "2024"` and `rust-version = "1.91"`;
|
**rustc 1.98+.** `Cargo.toml` sets `edition = "2024"` and `rust-version = "1.98"`.
|
||||||
the Arti 0.46 crates require 1.91. CI builds inside `rust:1.91-bookworm`
|
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`).
|
(`RUST_IMAGE` in `.forgejo/workflows/ci.yml` and `release.yml`).
|
||||||
|
|
||||||
A bump may raise the floor. Take the actual MSRV from the upstream release
|
A bump may raise the floor. Take the actual MSRV from the upstream release
|
||||||
|
|
@ -44,8 +54,7 @@ notes / the crate's own `rust-version`, then raise it in the same PR:
|
||||||
|
|
||||||
* `rust-version` in `Cargo.toml`,
|
* `rust-version` in `Cargo.toml`,
|
||||||
* `RUST_IMAGE` in `.forgejo/workflows/ci.yml` **and** `.forgejo/workflows/release.yml`,
|
* `RUST_IMAGE` in `.forgejo/workflows/ci.yml` **and** `.forgejo/workflows/release.yml`,
|
||||||
* the "Rust 1.91+" line in `README.md` (owned by another PR right now — add it
|
* the "Rust 1.98+" line in `README.md`.
|
||||||
when that lands, or ask the owner).
|
|
||||||
|
|
||||||
## How this gets noticed
|
## How this gets noticed
|
||||||
|
|
||||||
|
|
@ -76,16 +85,22 @@ issue the watcher files.
|
||||||
|
|
||||||
1. Read the upstream release notes (Arti tags: <https://gitlab.torproject.org/tpo/core/arti/-/releases>)
|
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.
|
and the CHANGELOG for breaking API changes. Check the new MSRV.
|
||||||
2. Branch from `main`; bump all four requirements in `[dependencies]` of
|
2. Branch from `main`; bump every Arti-repository pin in `[dependencies]` of
|
||||||
`Cargo.toml` together, and `rust-version` if the floor moved.
|
`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
|
3. Refresh the lockfile (CI builds with `--locked` and `Cargo.lock` is
|
||||||
committed):
|
committed):
|
||||||
```
|
```
|
||||||
cargo update -p arti-client -p tor-cell -p tor-hsservice -p tor-rtcompat
|
cargo update -p arti-client -p tor-cell -p tor-hsservice -p tor-rtcompat -p safelog
|
||||||
git diff --stat Cargo.lock
|
git diff --stat Cargo.lock
|
||||||
```
|
```
|
||||||
Expect the whole `tor-*` family to move in the diff. A single `tor-*` crate
|
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.
|
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:
|
4. Build and run the offline suite:
|
||||||
```
|
```
|
||||||
cargo test --locked
|
cargo test --locked
|
||||||
|
|
@ -116,10 +131,13 @@ issue the watcher files.
|
||||||
descriptor upload, not a hang), probe-connect against a live HS, a byte pipe
|
descriptor upload, not a hang), probe-connect against a live HS, a byte pipe
|
||||||
in both directions, restart, and the dormant/offline path.
|
in both directions, restart, and the dormant/offline path.
|
||||||
7. Confirm the fail-closed path by hand if the publish wait changed at all:
|
7. Confirm the fail-closed path by hand if the publish wait changed at all:
|
||||||
with the write timeout still 360s, a peer whose onion is down must fail the
|
with the publish wait still 360s, if Arti cannot publish the onion the
|
||||||
send. There is no outbox in v1 — the message must not be silently queued.
|
process must exit (no C-tor fallback). Chat to a *reachable-HS but down peer*
|
||||||
8. Rebuild the Android target — Arti's TLS backends are non-additive, and this
|
is queued locally (`src/outbox.rs`) and retried; file transfer and payment
|
||||||
is the build that exercises the `rustls` feature:
|
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
|
scripts/build-android-local.sh
|
||||||
```
|
```
|
||||||
|
|
@ -132,7 +150,9 @@ issue the watcher files.
|
||||||
the plaintext should appear in Arti's state directory.
|
the plaintext should appear in Arti's state directory.
|
||||||
10. Open a PR against `main` describing: crates bumped, MSRV, the live-test
|
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
|
output, and anything upstream changed that touches `src/hs.rs`. Do not push
|
||||||
`main`; releases are minted by `.forgejo/workflows/release.yml` from a merge.
|
`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
|
## Rolling back
|
||||||
|
|
||||||
|
|
|
||||||
571
docs/PROTOCOL.md
571
docs/PROTOCOL.md
|
|
@ -4,8 +4,9 @@ This is the wire protocol. A second implementation should be able to
|
||||||
interoperate from this document without reading the Rust.
|
interoperate from this document without reading the Rust.
|
||||||
|
|
||||||
It is **not** an IETF RFC. It describes what this repository speaks today
|
It is **not** an IETF RFC. It describes what this repository speaks today
|
||||||
(`frame::VERSION` 1, invite scheme `onionwire:v1`). There has been no public
|
(frame versions 1 and 2, invite schemes `onionwire:v2` (emit) and
|
||||||
third-party audit. Arti onion services are experimental upstream.
|
`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).
|
Related: [threat model](THREAT_MODEL.md), [audit notes](SECURITY_AUDIT.md).
|
||||||
|
|
||||||
|
|
@ -32,12 +33,20 @@ Each install holds:
|
||||||
- **Identity** — ed25519 keypair. The 32-byte public key **is** the person.
|
- **Identity** — ed25519 keypair. The 32-byte public key **is** the person.
|
||||||
Roster primary key. Displayed as 64 lowercase hex chars (the fingerprint).
|
Roster primary key. Displayed as 64 lowercase hex chars (the fingerprint).
|
||||||
- **Prekey** — x25519 keypair. This is the Noise IK *static*. It is long-lived
|
- **Prekey** — x25519 keypair. This is the Noise IK *static*. It is long-lived
|
||||||
in v1. Rotating the onion (`F4`) does **not** rotate it.
|
— 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.
|
- **Onion** — Tor v3 address. Locator only. Disposable.
|
||||||
|
|
||||||
A friend is `{identity_pk, current_onion, current_prekey_pk}`. Pasting the same
|
A friend is `{identity_pk, current_onion, current_prekey_pk, kem_pk?}`. Pasting
|
||||||
identity `k` updates the locator (and prekey) on that row. It never creates a
|
the same identity `k` updates the locator, prekey and KEM key on that row. It
|
||||||
second person.
|
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
|
Petnames, chat history, and the optional Monero wallet RPC are local. They are
|
||||||
not on the wire.
|
not on the wire.
|
||||||
|
|
@ -45,7 +54,7 @@ not on the wire.
|
||||||
## Transport
|
## Transport
|
||||||
|
|
||||||
1. Each peer publishes a Tor v3 onion service (in-process Arti in this tree).
|
1. Each peer publishes a Tor v3 onion service (in-process Arti in this tree).
|
||||||
2. Application port is **80** (`HS_PORT`).
|
2. Application port is **80**.
|
||||||
3. The sender opens a Tor circuit to `(friend.onion, 80)`, runs the handshake,
|
3. The sender opens a Tor circuit to `(friend.onion, 80)`, runs the handshake,
|
||||||
sends **one** application frame, and drops the circuit.
|
sends **one** application frame, and drops the circuit.
|
||||||
4. File transfer is N independent sessions (one handshake per chunk). There is
|
4. File transfer is N independent sessions (one handshake per chunk). There is
|
||||||
|
|
@ -57,12 +66,11 @@ 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
|
store-and-forward relay: each attempt is a fresh handshake straight to
|
||||||
`(friend.onion, 80)`, exactly as above. Retries fire on a timer, on
|
`(friend.onion, 80)`, exactly as above. Retries fire on a timer, on
|
||||||
unlock/foreground, and whenever that peer is heard from (successful handshake or
|
unlock/foreground, and whenever that peer is heard from (successful handshake or
|
||||||
`connect_onion()`). A protocol failure — signature mismatch, unknown frame,
|
a connect to that onion). A protocol failure — signature mismatch, unknown
|
||||||
oversize — is not a transport failure and is never queued.
|
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
|
File transfer and payment frames stay fail-closed: they are one-shot and are
|
||||||
**not** queued. The locator-push path still retries for 180 seconds and then
|
**not** queued. The locator-push path retries for 180 seconds and then gives up.
|
||||||
gives up.
|
|
||||||
|
|
||||||
Incoming rendezvous accepts are token-bucket limited: 30 per 60s, burst 10.
|
Incoming rendezvous accepts are token-bucket limited: 30 per 60s, burst 10.
|
||||||
Excess is dropped before handshake. That is availability, not anonymity.
|
Excess is dropped before handshake. That is availability, not anonymity.
|
||||||
|
|
@ -72,34 +80,154 @@ Excess is dropped before handshake. That is availability, not anonymity.
|
||||||
Every Noise handshake message and every ciphertext is wrapped:
|
Every Noise handshake message and every ciphertext is wrapped:
|
||||||
|
|
||||||
```
|
```
|
||||||
uint8 version = 1
|
uint8 version = 1 (normal) | 2 (PQ handshake prelude)
|
||||||
uint32 length = big-endian body length
|
uint32 length = big-endian body length
|
||||||
uint8 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.
|
- `length` MUST be ≤ 65535. Check the length **before** allocating the body.
|
||||||
- Other `version` values are a hard fail (close the stream).
|
- 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 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
|
## Handshake
|
||||||
|
|
||||||
Noise pattern: `Noise_IK_25519_ChaChaPoly_BLAKE2s`
|
Noise pattern: `Noise_IK_25519_ChaChaPoly_BLAKE2s`
|
||||||
|
|
||||||
Prologue (both sides, before the first handshake message): `onionwire-v1`
|
Prologue (both sides, before the first Noise handshake message):
|
||||||
(13 ASCII bytes, no NUL).
|
|
||||||
|
- **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
|
Handshake payloads are empty. A non-empty decrypted handshake payload is a
|
||||||
hard fail.
|
hard fail.
|
||||||
|
|
||||||
### Sequence
|
### Sequence
|
||||||
|
|
||||||
Initiator knows the responder’s identity pubkey (pinned) and x25519 prekey
|
Initiator knows the responder’s identity pubkey (pinned), x25519 prekey and
|
||||||
from the invite (or roster).
|
(if `kem_pk` is present) ML-KEM key from the invite (or roster).
|
||||||
|
|
||||||
1. **IK msg 1** — initiator → responder (framed). Responder’s Noise static is
|
0. **PQ prelude** — only when the responder’s roster row has `kem_pk`:
|
||||||
the invite `spk`.
|
initiator → responder, one `version = 2` frame carrying the ML-KEM
|
||||||
2. Responder looks up `get_remote_static()` in the roster **by prekey**.
|
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.
|
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).
|
3. **IK msg 2** — responder → initiator (framed).
|
||||||
4. Both sides enter transport mode. Handshake hash `h` is 32 bytes (BLAKE2s).
|
4. Both sides enter transport mode. Handshake hash `h` is 32 bytes (BLAKE2s).
|
||||||
5. **Identity proof, initiator first** — transport-encrypt a 96-byte proof,
|
5. **Identity proof, initiator first** — transport-encrypt a 96-byte proof,
|
||||||
|
|
@ -129,6 +257,27 @@ ciphertext and closes. The responder decrypts that one frame and closes.
|
||||||
Compromise of the long-term x25519 prekey does not decrypt past transport
|
Compromise of the long-term x25519 prekey does not decrypt past transport
|
||||||
(IK + ephemeral). It does allow future impersonation at the Noise layer until
|
(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.
|
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
|
## Application plaintext
|
||||||
|
|
||||||
|
|
@ -136,13 +285,14 @@ After decrypt, classify the plaintext:
|
||||||
|
|
||||||
| Prefix (4 bytes) | Kind | If unknown / invalid |
|
| Prefix (4 bytes) | Kind | If unknown / invalid |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| `rat ` | Double Ratchet chat frame (see Ratchet) | drop |
|
||||||
| `loc ` | locator update | drop |
|
| `loc ` | locator update | drop |
|
||||||
| `prf ` | profile | drop |
|
| `prf ` | profile | drop |
|
||||||
| `inv ` | Monero invoice | drop |
|
| `inv ` | Monero invoice | drop |
|
||||||
| `rcp ` | Monero receipt claim | drop |
|
| `rcp ` | Monero receipt claim | drop |
|
||||||
| `png ` | ping (reserved) | drop |
|
| `tip ` | Monero tip (receipt + memo) | drop |
|
||||||
|
| `png ` | ping (reserved; classify and drop) | drop |
|
||||||
| `fil ` | file chunk | drop |
|
| `fil ` | file chunk | drop |
|
||||||
| `rat ` | Double Ratchet chat frame (see Ratchet) | drop |
|
|
||||||
| `[a-z][a-z][a-z] ` | unknown typed frame | **drop** (not chat) |
|
| `[a-z][a-z][a-z] ` | unknown typed frame | **drop** (not chat) |
|
||||||
| anything else | chat | store as a chat line |
|
| anything else | chat | store as a chat line |
|
||||||
|
|
||||||
|
|
@ -152,8 +302,7 @@ chat line. Older builds that stored `rat `-prefixed bytes as chat are obsolete;
|
||||||
upgrade both sides.
|
upgrade both sides.
|
||||||
|
|
||||||
A peer that does not implement a typed prefix MUST still drop
|
A peer that does not implement a typed prefix MUST still drop
|
||||||
`[a-z]{3}<space>…` rather than render it as chat. Mixed-version 0.1.2 clients
|
`[a-z]{3}<space>…` rather than render it as chat.
|
||||||
that stored those as chat are obsolete; upgrade both sides.
|
|
||||||
|
|
||||||
Chat MUST NOT begin with three lowercase ASCII letters and a space. (Inside a
|
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.)
|
`rat ` frame the plaintext is a chat line and is not re-classified.)
|
||||||
|
|
@ -163,17 +312,42 @@ prefix.
|
||||||
|
|
||||||
### Application-frame signatures
|
### Application-frame signatures
|
||||||
|
|
||||||
`loc`, `prf`, `inv`, and `rcp` each carry an ed25519 signature over the
|
`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
|
**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 (type tag, then each field, `0x00` separators). Verify MUST accept that
|
||||||
form and, for mixed-version peers, the legacy untagged LF-joined layout.
|
form and, for mixed-version peers, the legacy untagged LF-joined layout.
|
||||||
Anything else fails closed. Do not emit the legacy layout.
|
Anything else fails closed. Do not emit the legacy layout.
|
||||||
|
|
||||||
The invite string is separate and keeps `onionwire-invite-v1` (see Invite).
|
The invite string is separate and uses `onionwire-invite-v2` (see Invite).
|
||||||
|
|
||||||
Older builds verify only the untagged bytes, so they reject tagged signatures
|
Legacy acceptance is one switch, `LEGACY_SIGS`, default **on**. Every fallback
|
||||||
(fail closed, no downgrade). Mixed-version fleets break outbound application
|
listed below reads it; with it off, verification accepts only the emitted
|
||||||
frames from a new sender to an old receiver until both sides are updated.
|
(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
|
### `loc ` — locator update
|
||||||
|
|
||||||
|
|
@ -196,8 +370,8 @@ ed25519_sign(identity_sk,
|
||||||
```
|
```
|
||||||
|
|
||||||
**Legacy accept:** a signature over `onion || LF || ascii(ts)` is still
|
**Legacy accept:** a signature over `onion || LF || ascii(ts)` is still
|
||||||
accepted on verify so old loc frames verify. New loc frames MUST use the
|
accepted on verify while `LEGACY_SIGS` is on, so old loc frames verify. New loc
|
||||||
domain-separated form. Do not emit legacy.
|
frames MUST use the domain-separated form. Do not emit legacy.
|
||||||
|
|
||||||
Apply only if **all** of:
|
Apply only if **all** of:
|
||||||
|
|
||||||
|
|
@ -228,7 +402,7 @@ ed25519_sign(identity_sk,
|
||||||
|
|
||||||
**Legacy accept:** a signature over the four fields joined by LF is still
|
**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.
|
accepted on verify. New profile frames MUST use the domain-separated form.
|
||||||
Do not emit legacy.
|
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
|
Apply only for an existing friend, valid signature, newer `ts`. Not a public
|
||||||
profile. Not a directory.
|
profile. Not a directory.
|
||||||
|
|
@ -251,10 +425,11 @@ ed25519_sign(identity_sk,
|
||||||
```
|
```
|
||||||
|
|
||||||
**Legacy accept:** a signature over the four fields joined by LF is still
|
**Legacy accept:** a signature over the four fields joined by LF is still
|
||||||
accepted on verify. New invoices MUST use the domain-separated form. Do not
|
accepted on verify while `LEGACY_SIGS` is on. New invoices MUST use the
|
||||||
emit legacy.
|
domain-separated form. Do not emit legacy.
|
||||||
|
|
||||||
The frame is a signed claim, not a payment.
|
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 ` — receipt claim (we paid)
|
||||||
|
|
||||||
|
|
@ -272,14 +447,45 @@ ed25519_sign(identity_sk,
|
||||||
```
|
```
|
||||||
|
|
||||||
**Legacy accept:** a signature over the four fields joined by LF is still
|
**Legacy accept:** a signature over the four fields joined by LF is still
|
||||||
accepted on verify. New receipts MUST use the domain-separated form. Do not
|
accepted on verify while `LEGACY_SIGS` is on. New receipts MUST use the
|
||||||
emit legacy.
|
domain-separated form. Do not emit legacy.
|
||||||
|
|
||||||
Signature proves which friend sent the claim. It does **not** prove money
|
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
|
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`
|
one transfer row with the same non-empty `txid`, `amount`, and `address`
|
||||||
(conjunction, not OR). RPC down → stay unverified. Wallet RPC is loopback
|
(conjunction, not OR). RPC down or an unsynced daemon → stay unverified.
|
||||||
HTTP Digest; it is not this protocol.
|
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
|
### `fil ` — file chunk
|
||||||
|
|
||||||
|
|
@ -287,11 +493,10 @@ Cap: 1 MiB reconstructed file. No resume. One Noise session per chunk.
|
||||||
|
|
||||||
The sender is responsible for fitting the receiver's documented rendezvous
|
The sender is responsible for fitting the receiver's documented rendezvous
|
||||||
budget (30 accepts / 60s, burst 10). Chunks MUST be paced so the average
|
budget (30 accepts / 60s, burst 10). Chunks MUST be paced so the average
|
||||||
interval between send attempts stays at least 3s — a margin under the 0.5/s
|
interval between send attempts stays at least 3s. A sender MAY retry an
|
||||||
refill; pacing at exactly 2s sits on the refill boundary and drains under
|
individual chunk a bounded number of times (this tree: 3). Exhausting retries
|
||||||
jitter. A sender MAY retry an individual chunk a bounded number of times.
|
fails the transfer. No outbox, no resume, no continuation under a new
|
||||||
Exhausting retries fails the transfer. No outbox, no resume, no continuation
|
`xfer_id`.
|
||||||
under a new `xfer_id`.
|
|
||||||
|
|
||||||
```
|
```
|
||||||
fil <xfer_id_hex>\n<filename>\n<sha256_hex>\n<idx>/<total>\n<raw bytes>
|
fil <xfer_id_hex>\n<filename>\n<sha256_hex>\n<idx>/<total>\n<raw bytes>
|
||||||
|
|
@ -311,9 +516,10 @@ is a chat line `[file] name (N bytes)`, never the raw frame.
|
||||||
### Chat
|
### Chat
|
||||||
|
|
||||||
A chat send is ratcheted: the wire form of a chat message is a `rat ` frame
|
A chat send is ratcheted: the wire form of a chat message is a `rat ` frame
|
||||||
(see “Ratchet (v1 chat layer)”), and the plaintext inside that frame is the chat
|
(see “Ratchet (chat layer)”), and the plaintext inside that frame is the chat
|
||||||
line below. A bare chat frame with no typed prefix is still accepted inbound as
|
line below, padded to a length bucket first (see
|
||||||
a chat line (v0.2.1 peers), but MUST NOT be emitted.
|
[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
|
UTF-8 is not enforced for chat text: invalid bytes become U+FFFD (the
|
||||||
implementation does not drop the row). Control and bidi formatting
|
implementation does not drop the row). Control and bidi formatting
|
||||||
|
|
@ -322,9 +528,11 @@ 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
|
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
|
so emoji sequences stay intact. `fil ` filenames must not contain
|
||||||
those characters (tab and newline included). Displayed as a line.
|
those characters (tab and newline included). Displayed as a line.
|
||||||
No length limit beyond the frame cap.
|
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 (v1 chat layer)
|
## Ratchet (chat layer)
|
||||||
|
|
||||||
Chat is the only application payload that is ratcheted. A chat send is
|
Chat is the only application payload that is ratcheted. A chat send is
|
||||||
Double-Ratchet encrypted first, and the resulting `rat ` frame is the
|
Double-Ratchet encrypted first, and the resulting `rat ` frame is the
|
||||||
|
|
@ -333,9 +541,7 @@ one application frame, close — see Transport). Nothing else changes about the
|
||||||
session.
|
session.
|
||||||
|
|
||||||
The ratchet header is **inside** the Noise transport message, never in clear on
|
The ratchet header is **inside** the Noise transport message, never in clear on
|
||||||
the wire. That is a deliberate divergence from the shape this layer came from:
|
the wire. A plaintext header (`dh_pub || N || PN`) would hand an observer
|
||||||
the plan assumed a plaintext header (`dh_pub || N || PN`) ahead of the
|
|
||||||
ciphertext, which was rejected because a plaintext header would hand an observer
|
|
||||||
per-message counters and ratchet-key changes for no benefit — the Noise session
|
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
|
already hides the frame, so the header is authenticated as AEAD associated data
|
||||||
instead.
|
instead.
|
||||||
|
|
@ -344,26 +550,53 @@ instead.
|
||||||
|
|
||||||
```
|
```
|
||||||
"rat " 4 bytes (0x72 0x61 0x74 0x20)
|
"rat " 4 bytes (0x72 0x61 0x74 0x20)
|
||||||
version 1 byte 0x01
|
version 1 byte 0x01 (classical) or 0x02 (hybrid)
|
||||||
header 40 bytes dh_pub[32] || N uint32 BE || PN uint32 BE
|
-- version 0x01: classical header, 40 bytes
|
||||||
nonce 12 bytes random, per message
|
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
|
ciphertext n+16 ChaCha20-Poly1305 ciphertext || tag
|
||||||
```
|
```
|
||||||
|
|
||||||
- `dh_pub` — the sender's current ratchet public key (X25519, 32 bytes).
|
- `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,
|
- `N` — the index of this message in the sender's current sending chain,
|
||||||
counting from 0.
|
counting from 0.
|
||||||
- `PN` — how many messages the sender sent in its *previous* sending chain.
|
- `PN` — how many messages the sender sent in its *previous* sending chain.
|
||||||
- Associated data is the 40-byte header, exactly as serialized above
|
- `kem_pub` — the sender's current ML-KEM-768 ratchet encapsulation key
|
||||||
(`dh_pub || N as u32 BE || PN as u32 BE`). A tampered `dh_pub`, `N` or `PN`
|
(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.
|
therefore fails closed.
|
||||||
- The ChaCha20-Poly1305 key is the message key from `KDF_CK`. The 12-byte nonce
|
- The ChaCha20-Poly1305 key is the message key from `KDF_CK`. The 12-byte nonce
|
||||||
is random per message, not a chain counter.
|
is random per message, not a chain counter.
|
||||||
- Minimum frame (empty plaintext) is 73 bytes: 5 + 40 + 12 + 16.
|
- 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
|
- A receiver MUST reject a frame without the `rat ` prefix, a version other than
|
||||||
`0x01`, or less than 73 bytes.
|
`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
|
- 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.
|
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
|
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
|
per message: no message counts, no ratchet keys, and nothing that marks a first
|
||||||
|
|
@ -371,29 +604,45 @@ message of a chain versus a later one.
|
||||||
|
|
||||||
### KDFs
|
### KDFs
|
||||||
|
|
||||||
Signal's constructions, unchanged:
|
Signal's constructions, with a second domain for hybrid steps:
|
||||||
|
|
||||||
```
|
```
|
||||||
KDF_RK(root, dh_out):
|
KDF_RK(root, dh_out): # v1: epoch 0, classical friends
|
||||||
okm = HKDF-SHA256(salt = root, ikm = dh_out,
|
okm = HKDF-SHA256(salt = root, ikm = dh_out,
|
||||||
info = "onionwire-ratchet-v1-kdfrk", L = 64)
|
info = "onionwire-ratchet-v1-kdfrk", L = 64)
|
||||||
new_root = okm[0..32]
|
new_root = okm[0..32]
|
||||||
chain_key = okm[32..64]
|
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):
|
KDF_CK(chain_key):
|
||||||
message_key = HMAC-SHA256(chain_key, 0x01)
|
message_key = HMAC-SHA256(chain_key, 0x01)
|
||||||
next_chain_key = HMAC-SHA256(chain_key, 0x02)
|
next_chain_key = HMAC-SHA256(chain_key, 0x02)
|
||||||
```
|
```
|
||||||
|
|
||||||
`HKDF` is RFC 5869 with SHA-256 (`hkdf` 0.12), `HMAC` is SHA-256 (`hmac`
|
`HKDF` is RFC 5869 with SHA-256, `HMAC` is SHA-256. The two `KDF_RK` forms
|
||||||
0.12). Each side of an epoch derives its chains from one shared DH output with
|
differ in **both** input shape and info string on purpose: `ikm` is 32 bytes for
|
||||||
`KDF_RK` called **twice**:
|
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):
|
epoch_chains(root, shared) -> (new_root, ck_lo, ck_hi): # v1
|
||||||
(root1, ck_lo) = KDF_RK(root, shared)
|
(root1, ck_lo) = KDF_RK(root, shared)
|
||||||
(root2, ck_hi) = KDF_RK(root1, shared)
|
(root2, ck_hi) = KDF_RK(root1, shared)
|
||||||
new_root = root2
|
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
|
`lo` is the lexicographically lower of the pair's two ratchet public keys and
|
||||||
|
|
@ -417,16 +666,30 @@ root_key = hk.expand("root", 32)
|
||||||
my_secret = hk.expand("ratchet-key" || my_identity_pk, 32)
|
my_secret = hk.expand("ratchet-key" || my_identity_pk, 32)
|
||||||
peer_secret = hk.expand("ratchet-key" || peer_identity_pk, 32)
|
peer_secret = hk.expand("ratchet-key" || peer_identity_pk, 32)
|
||||||
|
|
||||||
state = bootstrap(root_key, my_keypair(my_secret), X25519_pub(peer_secret))
|
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
|
`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
|
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. Then:
|
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)
|
shared = DH(my_secret, remote_pub)
|
||||||
(new_root, ck_lo, ck_hi) = epoch_chains(root_key, shared)
|
(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
|
send_ck = chain_for(my_pub, remote_pub) // ck_lo or ck_hi
|
||||||
recv_ck = chain_for(remote_pub, my_pub)
|
recv_ck = chain_for(remote_pub, my_pub)
|
||||||
send_n = recv_n = 0, PN = 0, established = false
|
send_n = recv_n = 0, PN = 0, established = false
|
||||||
|
|
@ -435,6 +698,52 @@ send_n = recv_n = 0, PN = 0, established = false
|
||||||
Fresh entropy enters at the first DH ratchet step; the bootstrap epoch itself is
|
Fresh entropy enters at the first DH ratchet step; the bootstrap epoch itself is
|
||||||
prekey-bound (see [THREAT_MODEL.md](THREAT_MODEL.md)).
|
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
|
**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
|
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
|
has received anything. Because the epoch's two chains come from the unordered
|
||||||
|
|
@ -457,7 +766,8 @@ rotation first, so at most one rotation is ever in flight, and both peers feed
|
||||||
On a decrypted `rat ` frame (the outer Noise session has already been verified,
|
On a decrypted `rat ` frame (the outer Noise session has already been verified,
|
||||||
so the peer identity is pinned):
|
so the peer identity is pinned):
|
||||||
|
|
||||||
1. Parse; reject bad prefix, version or a frame under 73 bytes.
|
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**
|
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
|
from the store, deliver. A replay of the same frame then fails closed because
|
||||||
the key is gone.
|
the key is gone.
|
||||||
|
|
@ -468,11 +778,15 @@ so the peer identity is pinned):
|
||||||
- Derive message keys for `recv_n .. N` into the skipped store, derive the
|
- Derive message keys for `recv_n .. N` into the skipped store, derive the
|
||||||
key for `N`, open, set `recv_n = N + 1`.
|
key for `N`, open, set `recv_n = N + 1`.
|
||||||
- On the *first* frame received in this state (`established == false`): set
|
- On the *first* frame received in this state (`established == false`): set
|
||||||
`established`, and if `my_pub < remote_pub`, rotate the sending chain
|
`established`, and if `my_pub < remote_pub`, rotate the sending chain —
|
||||||
(fresh keypair; `epoch_chains(root, DH(new_secret, remote_pub))`; new
|
fresh `{x25519, ml-kem}` keypair; for a hybrid friend encapsulate to
|
||||||
sending chain for `new_pub → remote_pub`; `PN = old send_n`; `send_n = 0`).
|
`remote_kem_pub` and derive with `epoch_chains_hybrid(root, DH(new_secret,
|
||||||
The receiving chain is untouched.
|
remote_pub), ss)`, for a classical friend `epoch_chains(root, DH(...))`;
|
||||||
4. Else it is a ratchet key not adopted yet: run a full DH ratchet step.
|
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
|
### DH ratchet step
|
||||||
|
|
||||||
|
|
@ -485,18 +799,26 @@ On a frame whose `dh_pub` differs from the adopted remote public key:
|
||||||
- Derive `recv_n .. PN` into the skipped store, tagged with the retired
|
- Derive `recv_n .. PN` into the skipped store, tagged with the retired
|
||||||
remote public key, so stragglers of the old chain still decrypt.
|
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)`:
|
2. **Receiving half of the step**, on the pair `(my current secret, frame.dh_pub)`:
|
||||||
`shared = DH(my_secret, frame.dh_pub)`,
|
`shared = DH(my_secret, frame.dh_pub)`. For a hybrid step also
|
||||||
`(root_a, ck_lo, ck_hi) = epoch_chains(root, shared)`,
|
`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
|
`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).
|
chain exactly as in step 3 above (it must be within `MAX_SKIP` of index 0).
|
||||||
3. **Sending half:** generate a fresh ratchet keypair,
|
3. **Sending half:** generate a fresh ratchet keypair `{x25519, ml-kem}`. For a
|
||||||
`shared = DH(new_secret, frame.dh_pub)`,
|
hybrid step encapsulate to `frame.kem_pub` (`(kem_ct, ss_kem) =
|
||||||
`(root, ck_lo, ck_hi) = epoch_chains(root_a, shared)`,
|
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`,
|
`send_ck = chain_for(new_pub, frame.dh_pub)`, `remote_pub = frame.dh_pub`,
|
||||||
`PN = old send_n`, `send_n = 0`, `established = true`.
|
`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
|
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
|
open fails, nothing is applied: the state must be byte-identical to before
|
||||||
the frame.
|
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
|
The next frame this side sends therefore carries the new `dh_pub`, which is what
|
||||||
lets the peer step too.
|
lets the peer step too.
|
||||||
|
|
@ -518,12 +840,32 @@ lets the peer step too.
|
||||||
|
|
||||||
`ratchet_sessions` in the SQLCipher store: one row per friend
|
`ratchet_sessions` in the SQLCipher store: one row per friend
|
||||||
(`friend_id` primary key, `FOREIGN KEY` → `friends.id` `ON DELETE CASCADE`,
|
(`friend_id` primary key, `FOREIGN KEY` → `friends.id` `ON DELETE CASCADE`,
|
||||||
`state BLOB NOT NULL`, `updated_at`). The blob is version byte `0x01` followed by
|
`state BLOB NOT NULL`, `updated_at`). The blob is version byte `0x02` followed by
|
||||||
the implementation's serialized `RatchetState` (root, keypairs, both chain keys
|
the implementation's serialized ratchet state:
|
||||||
and counters, `established`, and the skipped-key store). 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
|
0 version 0x02
|
||||||
disk.
|
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
|
### Not ratcheted
|
||||||
|
|
||||||
|
|
@ -544,42 +886,65 @@ the new invite is the signal.
|
||||||
Not a QR graphic. A single ASCII string, max 4096 characters:
|
Not a QR graphic. A single ASCII string, max 4096 characters:
|
||||||
|
|
||||||
```
|
```
|
||||||
onionwire:v1:k=<64 hex>:o=<v3 onion>:spk=<64 hex>:sig=<128 hex>
|
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
|
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
|
rejected. `k` is the identity pubkey, `spk` the x25519 prekey, `o` the current
|
||||||
locator.
|
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):**
|
**Current signature (encode this):**
|
||||||
|
|
||||||
```
|
```
|
||||||
ed25519_sign(identity_sk,
|
ed25519_sign(identity_sk,
|
||||||
"onionwire-invite-v1" || 0x00 || k_ascii || 0x00 || o_ascii || 0x00 || spk_ascii)
|
"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
|
`k_ascii` / `spk_ascii` are the hex strings as they appear in the invite
|
||||||
(lowercase).
|
(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:** a signature over the raw concatenation `k || o || spk`
|
**Legacy accept (`onionwire:v1`):** a v1 invite has no `kem` field. Decode
|
||||||
(no domain tag, no separators) is still accepted on decode so old invites
|
accepts it while `LEGACY_SIGS` is on and yields a friend with no `kem_pk`, i.e.
|
||||||
verify. New invites MUST use the domain-separated form. Do not emit legacy.
|
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.
|
||||||
|
|
||||||
Unknown `k`: prompt. Same `k`: update onion and prekey only.
|
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
|
## What v1 will not grow into
|
||||||
|
|
||||||
No DHT, no hosted server, no XMPP, no store-and-forward, no multi-device, no
|
No DHT, no directory server, no hosted/server-side outbox, no XMPP/Prosody, no
|
||||||
A/V, no STUN/ICE/WebRTC, no SOCKS/C-tor fallback, no system DNS for friends.
|
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
|
Those are how Tox-over-Tor leaks (UDP DHT, mixed clearnet, “just one direct
|
||||||
path”). They are out of scope, not postponed.
|
path”). They are out of scope, not postponed.
|
||||||
|
|
||||||
## Versioning
|
## Versioning
|
||||||
|
|
||||||
- Frame `version` 1 and invite `onionwire:v1` are this document.
|
- Frame `version` 1 (normal), frame `version` 2 (PQ prelude), invite
|
||||||
- A new handshake prologue or a new invite scheme is a breaking change.
|
`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.
|
- New typed prefixes (`xyz `) are backward compatible if old peers drop them.
|
||||||
- The `rat ` frame has its own version byte (`0x01`). A different ratchet frame
|
- The `rat ` frame has its own version byte (`0x01` classical, `0x02` hybrid).
|
||||||
layout or a different KDF is a breaking change for chat only: peers that
|
A different ratchet frame layout or a different KDF is a breaking change for
|
||||||
disagree cannot read each other's chat, and every other frame keeps working.
|
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.
|
||||||
|
|
|
||||||
|
|
@ -9,8 +9,27 @@ Read these in order if you are evaluating the protocol without the Rust:
|
||||||
3. **[SECURITY_AUDIT.md](SECURITY_AUDIT.md)** — in-house review notes and
|
3. **[SECURITY_AUDIT.md](SECURITY_AUDIT.md)** — in-house review notes and
|
||||||
which findings are still open. **Not** a public third-party audit.
|
which findings are still open. **Not** a public third-party audit.
|
||||||
|
|
||||||
Operator / product docs stay in the [root README](../README.md). Android
|
Operator / product docs:
|
||||||
build notes: [android/README.md](../android/README.md). SDK:
|
|
||||||
|
- **[../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).
|
[crates/onionwire-sdk/README.md](../crates/onionwire-sdk/README.md).
|
||||||
Maintainers cutting a release: [RELEASING.md](RELEASING.md) — manual, batched
|
|
||||||
releases, not one per merge.
|
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)
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,10 @@
|
||||||
# Releasing OnionWire
|
# Releasing OnionWire
|
||||||
|
|
||||||
Policy and procedure for cutting a release. Read
|
How a maintainer cuts a release. This is **not** automatic: a merge to `main`
|
||||||
[`README.md`](../README.md#releases-maintainers) for the short version.
|
does not publish, and a tag push does not publish. Two dispatches, `dry_run`
|
||||||
|
first, Android APK joins the same tag.
|
||||||
|
|
||||||
|
Short version: [`README.md`](../README.md#releases-maintainers).
|
||||||
|
|
||||||
## Policy: manual, batched releases
|
## Policy: manual, batched releases
|
||||||
|
|
||||||
|
|
@ -42,9 +45,31 @@ created if the build or publish fails", and the dry-run path.
|
||||||
The Linux binaries land first; the APK build is the long pole.
|
The Linux binaries land first; the APK build is the long pole.
|
||||||
6. **Check the assets.** Open the release page (or
|
6. **Check the assets.** Open the release page (or
|
||||||
`GET /api/v1/repos/sirius/onionwire/releases/tags/<tag>`) and require a
|
`GET /api/v1/repos/sirius/onionwire/releases/tags/<tag>`) and require a
|
||||||
non-zero `size` for every asset: the two Linux binaries + `.sha256`, the
|
non-zero `size` for every asset. A Linux release is **eleven** assets:
|
||||||
APK + `.sha256`, the AAR + `.sha256`. A green run is not proof — the Pi
|
|
||||||
runner hairpins through Cloudflare and has uploaded 0-byte assets before.
|
| asset | what it is |
|
||||||
|
|---|---|
|
||||||
|
| `onionwire-<target>` ×2 | the two Linux binaries |
|
||||||
|
| `onionwire-<target>.sha256` ×2 | their checksums |
|
||||||
|
| `onionwire-<target>.minisig` ×2 | the binary signatures |
|
||||||
|
| `onionwire-<target>.sha256.minisig` ×2 | the checksum signatures |
|
||||||
|
| `build-info-<target>.txt` ×2 | the recipe record (commit, epoch, toolchain, image digest) |
|
||||||
|
| `onionwire-signing.pub` | the public half of the signing key |
|
||||||
|
|
||||||
|
plus the APK + `.sha256` and the AAR + `.sha256` attached by `android-release`.
|
||||||
|
A green run is not proof — the Pi runner hairpins through Cloudflare and has
|
||||||
|
uploaded 0-byte assets before.
|
||||||
|
|
||||||
|
7. **Spot-check reproducibility.** On any machine with docker and a clone:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
scripts/verify-reproducible.sh <tag>
|
||||||
|
```
|
||||||
|
|
||||||
|
It has to print `RESULT: MATCH`. A `MISMATCH` means the published binary is
|
||||||
|
not what this tag builds to — release-blocking, not cosmetic. Diagnose with
|
||||||
|
the `build-info-<target>.txt` on the release before assuming compromise:
|
||||||
|
a different commit or a moved image digest explains most mismatches.
|
||||||
|
|
||||||
## Inputs
|
## Inputs
|
||||||
|
|
||||||
|
|
@ -72,15 +97,32 @@ Contradictory input is rejected, never guessed at:
|
||||||
and fails. `201` means created; `409` means it was created concurrently and
|
and fails. `201` means created; `409` means it was created concurrently and
|
||||||
this run joins it.
|
this run joins it.
|
||||||
|
|
||||||
`aarch64` (Pi runner) and `x86_64` (amd64 runner) jobs build the binary in a
|
`aarch64` (Pi runner) and `x86_64` (amd64 runner) jobs run
|
||||||
`rust:*-bookworm` container, strip it, refuse an empty binary, write the
|
`scripts/reproducible-build.sh` inside the **digest-pinned** builder image
|
||||||
`.sha256`, and upload it as an artifact.
|
(`RUST_IMAGE` in the workflow). That script owns the whole build: `--locked`,
|
||||||
|
fixed in-container paths, `SOURCE_DATE_EPOCH` from the released commit, the
|
||||||
|
`--remap-path-prefix` set, `strip --strip-all`, the `.sha256`, and the
|
||||||
|
`build-info-<target>.txt` record. The job then only refuses a half-made dist and
|
||||||
|
uploads it — the target volume is created per run and removed afterwards, so the
|
||||||
|
published binary cannot come out of a cache a verifier does not have.
|
||||||
|
|
||||||
`publish` job (Pi runner) downloads both artifacts, refuses any empty file,
|
The `SOURCE_DATE_EPOCH` step reads the committer time of
|
||||||
and calls `scripts/publish-release.sh` to create-or-update the release with all
|
`needs.version.outputs.sha`. It is deliberately not "now": a rebuild of this tag
|
||||||
four Linux assets. If this job fails and the tag was created by *this* run, the
|
in six months has to hand the compiler the same epoch CI handed it.
|
||||||
final step deletes the incomplete release and the tag. A failed `aarch64` or
|
|
||||||
`x86_64` job always fails `publish`, so nothing is published half-built.
|
`publish` job (Pi runner) downloads both artifacts, stages them into `dist/`,
|
||||||
|
signs every asset with `scripts/sign-release.sh` inside the same digest-pinned
|
||||||
|
builder image, and only then calls `scripts/publish-release.sh` to create-or-update
|
||||||
|
the release with all four Linux assets plus the committed public key. Signing runs
|
||||||
|
in a container fed by a **named volume + `docker cp`**, not a bind mount of the
|
||||||
|
workspace: on this runner `$GITHUB_WORKSPACE` is a path inside the job container,
|
||||||
|
while docker resolves a `-v` source on the host — a bind mount therefore arrives
|
||||||
|
empty and the sign script is missing (run 768). Signing is also staged *after*
|
||||||
|
`dist/` is populated, so the files it signs exist; a run with no
|
||||||
|
`MINISIGN_SECRET_KEY` still stops before anything is uploaded. If this job fails
|
||||||
|
and the tag was created by *this* run, the final step deletes the incomplete
|
||||||
|
release and the tag. A failed `aarch64` or `x86_64` job always fails `publish`, so
|
||||||
|
nothing is published half-built.
|
||||||
|
|
||||||
## Android (APK + AAR) on the same tag
|
## Android (APK + AAR) on the same tag
|
||||||
|
|
||||||
|
|
@ -116,15 +158,42 @@ long pole of a release — the Linux binaries land first.
|
||||||
|
|
||||||
### Android CI (not a release)
|
### Android CI (not a release)
|
||||||
|
|
||||||
`android-ci.yml` runs the same gradle targets on the same amd64 runner for every
|
`android-ci.yml` runs the same gradle targets on the same amd64 runner, so an
|
||||||
PR and `main` push that touches `android/`, `src/`, `crates/`, `Cargo.toml`,
|
android-only PR is no longer merged on an empty check list. It signs with the
|
||||||
`Cargo.lock` or `scripts/build-android-local.sh`, so an android-only PR is no
|
**debug** key (`ONIONWIRE_REQUIRE_RELEASE_KEY=false`, no keystore) and
|
||||||
longer merged on an empty check list. It signs with the **debug** key
|
publishes nothing — `apksigner` in that job reports the debug cert, which is
|
||||||
(`ONIONWIRE_REQUIRE_RELEASE_KEY=false`, no keystore) and publishes nothing —
|
expected there and never in `android-release`. It shares
|
||||||
`apksigner` in that job reports the debug cert, which is expected there and
|
`android-release.yml`'s concurrency group and volumes, so the PR build is warm
|
||||||
never in `android-release`. It shares `android-release.yml`'s concurrency group
|
(~9 min) instead of re-downloading a gigabyte of SDK/NDK.
|
||||||
and volumes, so the PR build is warm (~9 min) instead of re-downloading a
|
|
||||||
gigabyte of SDK/NDK.
|
The two triggers are deliberately **not** the same, because the APK embeds the
|
||||||
|
root crate as `libonionwire_sdk.so` and a full build costs ~11 minutes:
|
||||||
|
|
||||||
|
- **`pull_request`** — `android/**`, `crates/onionwire-sdk/**`, `Cargo.toml`,
|
||||||
|
`Cargo.lock`, `scripts/build-android-local.sh`. Client and binding-surface
|
||||||
|
changes get the pre-merge signal.
|
||||||
|
- **`push: [main]`** — the above plus `src/**` and `crates/**`. Every merge of
|
||||||
|
a Rust change still runs the full build, including the in-APK checks that
|
||||||
|
earn their keep (the `target_max_memory` marker gate, the `.so` listing, the
|
||||||
|
sha256 round-trip). Nothing reaches a release untested; a Rust-only PR finds
|
||||||
|
out at merge rather than before it.
|
||||||
|
|
||||||
|
Both `ci.yml` and `android-ci.yml` open with a **staleness gate**: they compare
|
||||||
|
`GITHUB_SHA` against the remote branch tip and skip the build if a newer commit
|
||||||
|
landed while the run sat in the concurrency queue. `cancel-in-progress` is
|
||||||
|
deliberately `false` on both (cancelling a queued run would let two cargo jobs
|
||||||
|
share the Pi's target volume, which produces `Permission denied (os error 13)`
|
||||||
|
on `/target/debug/deps`), so the gate is what removes superseded work. A
|
||||||
|
`git ls-remote` failure runs the job rather than skipping it.
|
||||||
|
|
||||||
|
The `ci / fuzz` job is **not** in `ci.yml` any more — it is
|
||||||
|
`.forgejo/workflows/fuzz.yml`, `schedule`-only at 03:30 UTC plus
|
||||||
|
`workflow_dispatch`. A job cannot narrow a workflow-level path filter, so
|
||||||
|
`fuzz/**` sat beside `src/**` in `ci.yml`'s list and the job ran on nearly
|
||||||
|
every push (80 of 84 recorded runs touched nothing in `fuzz/`), each paying a
|
||||||
|
nightly toolchain install and `cargo install cargo-fuzz` for 15 seconds of
|
||||||
|
fuzzing. Fuzz output is not attached to any PR; check the `fuzz` workflow's
|
||||||
|
run history for it.
|
||||||
|
|
||||||
## Rebuilding an existing tag
|
## Rebuilding an existing tag
|
||||||
|
|
||||||
|
|
@ -138,6 +207,57 @@ Never move or delete a published `v*.*.*` tag by hand, and never create one by
|
||||||
hand: a hand-pushed tag starts nothing (`release.yml` has no tag-push trigger),
|
hand: a hand-pushed tag starts nothing (`release.yml` has no tag-push trigger),
|
||||||
and `release.yml` will refuse to move a tag that exists on another commit.
|
and `release.yml` will refuse to move a tag that exists on another commit.
|
||||||
|
|
||||||
|
## Reproducibility and signing
|
||||||
|
|
||||||
|
Two properties a download can be checked against, and one prerequisite that no
|
||||||
|
one else can do for you.
|
||||||
|
|
||||||
|
### The recipe
|
||||||
|
|
||||||
|
`scripts/reproducible-build.sh` is the single definition of a release build.
|
||||||
|
Everything that can move the output bytes is pinned inside it:
|
||||||
|
|
||||||
|
- the **builder image, by digest**. `rust:1.98-bookworm` floats, and a rustc
|
||||||
|
patch release changes codegen. The digest must be identical in three files —
|
||||||
|
`RUST_IMAGE` in `.forgejo/workflows/release.yml`, and `BUILDER_IMAGE` in both
|
||||||
|
`scripts/verify-reproducible.sh` and `scripts/build-release-local.sh`. Bump all
|
||||||
|
three in **one** commit, and expect the hashes to change: that is a toolchain
|
||||||
|
change, not a compromise.
|
||||||
|
- **fixed absolute paths**, because rustc's `--remap-path-prefix` cannot reach
|
||||||
|
absolute paths compiled in by a C toolchain, and this crate always has one:
|
||||||
|
`rusqlite`'s `bundled-sqlcipher-vendored-openssl` compiles OpenSSL from source
|
||||||
|
and OpenSSL bakes its build paths into the artifact.
|
||||||
|
- **`SOURCE_DATE_EPOCH`** from the released commit's committer date.
|
||||||
|
- **`--locked`**, and `RUSTFLAGS` is replaced rather than extended so an ambient
|
||||||
|
profile setting cannot silently change the bytes.
|
||||||
|
|
||||||
|
### The signing key (one-time, yours to hold)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
minisign -G -W -p scripts/onionwire-signing.pub -s onionwire-signing.key
|
||||||
|
```
|
||||||
|
|
||||||
|
`-W` keeps the secret key unencrypted, because CI cannot answer a prompt and a
|
||||||
|
passphrase stored beside the key protects nothing. Then commit the `.pub`, add
|
||||||
|
the `.key` file's **contents** as the Actions secret `MINISIGN_SECRET_KEY`, and
|
||||||
|
delete the `.key` from your machine.
|
||||||
|
|
||||||
|
**Until that secret exists, releases fail.** The signing step runs *before*
|
||||||
|
publish and exits non-zero without a key, so nothing unsigned reaches the
|
||||||
|
release page. That is deliberate: an unsigned release is indistinguishable from
|
||||||
|
a signed one to anyone who is not checking, which makes it worse than no release.
|
||||||
|
|
||||||
|
`scripts/sign-release.sh` also verifies each signature it just made against the
|
||||||
|
committed public key before returning, so a broken key fails at signing rather
|
||||||
|
than after the assets are public.
|
||||||
|
|
||||||
|
### The local fallback
|
||||||
|
|
||||||
|
`scripts/build-release-local.sh` runs the same pinned container and the same
|
||||||
|
recipe, and requires `MINISIGN_SECRET_KEY` too. It is a fallback for a dead
|
||||||
|
runner, not a way to ship something the verifier cannot reproduce — a host
|
||||||
|
`cargo build` would produce a binary whose hash no one could match.
|
||||||
|
|
||||||
## Version policy
|
## Version policy
|
||||||
|
|
||||||
`MAJOR.MINOR.PATCH` on the tag (`v`-prefixed). The default bump is `minor`: a
|
`MAJOR.MINOR.PATCH` on the tag (`v`-prefixed). The default bump is `minor`: a
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
**This is not a public third-party audit.** It is an in-house review of
|
**This is not a public third-party audit.** It is an in-house review of
|
||||||
commit `2b42864` plus a status check against the current tree. Do not cite it
|
commit `2b42864` plus a status check against the current tree. Do not cite it
|
||||||
as “audited.”
|
as “audited.” OnionWire has not had a public external security assessment.
|
||||||
|
|
||||||
Protocol: [PROTOCOL.md](PROTOCOL.md). Claims: [THREAT_MODEL.md](THREAT_MODEL.md).
|
Protocol: [PROTOCOL.md](PROTOCOL.md). Claims: [THREAT_MODEL.md](THREAT_MODEL.md).
|
||||||
|
|
||||||
|
|
@ -26,10 +26,11 @@ Original pass: rust-dev, no live hidden service / live wallet. Ignored tests
|
||||||
|
|
||||||
- At rest the whole store is SQLCipher (Argon2id key over a 16-byte `store_salt`), so the identity secret key, roster (pubkeys + locators) and chat bodies are ciphertext on disk; chat bodies add a row-bound AEAD layer on top. That is not a defense against a live compromise or an attacker who has the passphrase — see [THREAT_MODEL.md](THREAT_MODEL.md).
|
- At rest the whole store is SQLCipher (Argon2id key over a 16-byte `store_salt`), so the identity secret key, roster (pubkeys + locators) and chat bodies are ciphertext on disk; chat bodies add a row-bound AEAD layer on top. That is not a defense against a live compromise or an attacker who has the passphrase — see [THREAT_MODEL.md](THREAT_MODEL.md).
|
||||||
- Arti onion services are experimental. Fail closed; no C-tor fallback.
|
- Arti onion services are experimental. Fail closed; no C-tor fallback.
|
||||||
- No public third-party audit, no `cargo-audit` gate in CI as of the original pass.
|
- No public third-party audit. This file is not one.
|
||||||
- Invite decode still accepts the legacy concat signature (compatibility).
|
- Invite decode still accepts the legacy concat signature (compatibility).
|
||||||
- Rate limit is availability, not traffic-analysis defense.
|
- Rate limit is availability, not traffic-analysis defense.
|
||||||
- One-shot sessions: no channel binding across file chunks beyond “same Noise peer.”
|
- One-shot sessions: no channel binding across file chunks beyond “same Noise peer.”
|
||||||
|
- The in-process Cuprate chain daemon is opt-in and **unvalidated on mainnet**.
|
||||||
|
|
||||||
## Verified correct (original pass, still the protocol)
|
## Verified correct (original pass, still the protocol)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,10 @@
|
||||||
# OnionWire threat model (v1)
|
# OnionWire threat model (v1)
|
||||||
|
|
||||||
OnionWire is a two-party chat over Tor onion services. There is no chat server.
|
OnionWire is a two-party chat over Tor onion services. There is no chat server.
|
||||||
Wire format: [PROTOCOL.md](PROTOCOL.md). In-house review notes:
|
Identity is an ed25519 pubkey; the onion is a locator only (`F4` rotates the
|
||||||
[SECURITY_AUDIT.md](SECURITY_AUDIT.md) — **not** a public third-party audit.
|
locator, nothing else). Wire format: [PROTOCOL.md](PROTOCOL.md). Wallet:
|
||||||
|
[WALLET.md](WALLET.md). In-house review notes: [SECURITY_AUDIT.md](SECURITY_AUDIT.md)
|
||||||
|
— **not** a public third-party audit. Do not cite that file as “audited.”
|
||||||
|
|
||||||
## Tor relays are not a chat server
|
## Tor relays are not a chat server
|
||||||
|
|
||||||
|
|
@ -16,12 +18,59 @@ A signed `loc` frame (`onion`, `ts`, `sig`) rewrites a friend’s locator **only
|
||||||
|
|
||||||
`F4` changes the locator only. The identity key is unchanged. Anyone who already has your pubkey can still prove they are talking to you, and a later invite paste with the same `k` updates their row. To become a new person, `/wipe-all` (new identity key). There is no in-band unfriend/revoke in v1.
|
`F4` changes the locator only. The identity key is unchanged. Anyone who already has your pubkey can still prove they are talking to you, and a later invite paste with the same `k` updates their row. To become a new person, `/wipe-all` (new identity key). There is no in-band unfriend/revoke in v1.
|
||||||
|
|
||||||
|
## Rotating the prekey is a hard cut, and it is wider than F4
|
||||||
|
|
||||||
|
`F8` rotates the long-lived signed prekey **and the ML-KEM-768 install key**. The identity key and the onion are unchanged, but the prekey is our Noise static **and** the seed of the bootstrap ratchet epoch, and the KEM key is what peers encapsulate to, so once either moves nothing is reachable any more: a friend's dial uses the prekey and `kem=` they pinned from your invite, and their stored epoch is derived from the old prekey. There is no push path for either key — they only travel inside a signed invite — so every friend, online or offline, has to F3-paste the new invite before chat works in either direction again. F8 therefore also drops the local ratchet state for every friend, exactly as a peer's own prekey change does. Rotating the prekey shrinks the forward-secrecy window of the long-lived static; it is not a revocation (the old invite holder still learns nothing new, but they also cannot talk to you).
|
||||||
|
|
||||||
|
## Post-quantum transport does not make messaging post-quantum
|
||||||
|
|
||||||
|
Every Noise session to a v2 friend carries an ML-KEM-768 secret. The
|
||||||
|
initiator sends a `version = 2` prelude with `ct = Encapsulate(friend.kem_pk)`
|
||||||
|
before Noise msg 1, and both sides mix `(ct, ss_kem)` into the Noise prologue
|
||||||
|
(`"onionwire-v2" || 0x00 || ct || 0x00 || ss_kem`). A recorded handshake
|
||||||
|
therefore exposes an X25519 DH and an ML-KEM-768 encapsulation; a future
|
||||||
|
cryptographically relevant quantum adversary has to break ML-KEM-768 as well as
|
||||||
|
X25519 to recover the Noise transport keys. That removes the
|
||||||
|
harvest-now-decrypt-later exposure of the **one-shot transport**.
|
||||||
|
|
||||||
|
What this does **not** buy:
|
||||||
|
|
||||||
|
- **The chat ratchet stays classical.** Chat messages are `rat ` frames
|
||||||
|
(Double Ratchet, `docs/PROTOCOL.md`). The **bootstrap epoch is derived only
|
||||||
|
from the two long-lived X25519 prekeys** (HKDF over their DH, with the
|
||||||
|
identity pubkeys mixed in), so an adversary who records a `rat ` chain and
|
||||||
|
later obtains both prekeys can reconstruct epoch 0 even though the Noise
|
||||||
|
session that carried it was hybrid. Later epoch chains use fresh X25519 DH
|
||||||
|
steps, which are equally quantum-vulnerable. PQ ratchet steps are a separate
|
||||||
|
follow-up, not part of this transport work.
|
||||||
|
- **Identity and invite signatures are ed25519**, still classical. The KEM key
|
||||||
|
is authenticated by a v1-style ed25519 invite signature; an adversary who can
|
||||||
|
forge it can also swap `kem=`. Hybrid transport protects confidentiality, not
|
||||||
|
the long-term authentication root.
|
||||||
|
- **Legacy friends get nothing.** A friend added from an `onionwire:v1` invite
|
||||||
|
has no `kem_pk`; sessions to them are the old classical `onionwire-v1`
|
||||||
|
prologue, and the UI labels that friend as lacking PQ protection. The choice
|
||||||
|
is derived from the roster row, never from the wire: a `kem_pk` friend
|
||||||
|
rejects a prelude-less session with `prelude required` before any application
|
||||||
|
frame, so an active attacker cannot downgrade it.
|
||||||
|
- **Mixed-version fleets break.** A v1-only build cannot open a session with a
|
||||||
|
v2 friend; that is accepted rather than adding a fallback path.
|
||||||
|
|
||||||
## Your store is encrypted
|
## Your store is encrypted
|
||||||
|
|
||||||
The sqlite store is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`).
|
The sqlite store is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`).
|
||||||
A 32-byte key is derived from the store passphrase with Argon2id (same params as
|
A 32-byte key is derived from the store passphrase with Argon2id — m =
|
||||||
identity backup) over a per-install 16-byte salt in `store_salt`, and handed to
|
65_536 KiB (64 MiB), t = 3, p = 1, out = 32 — over a per-install 16-byte salt
|
||||||
SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) — no second KDF pass over it.
|
in `store_salt`, and handed to SQLCipher as a **raw** key (`PRAGMA key =
|
||||||
|
"x'…'"`) — no second KDF pass over it. The identity backup and the
|
||||||
|
message-key wrap in `store_meta` use the same profile. Parameters are
|
||||||
|
versioned with the data: a backup blob names its profile in the header and
|
||||||
|
`store_meta.kdf_profile` names the store's, and an unknown profile id is a
|
||||||
|
clear error, never a silent fallback. Data written with the earlier
|
||||||
|
19_456 KiB / t=2 / p=1 profile still opens: a legacy store is rekeyed and its
|
||||||
|
message key re-wrapped with the current profile on the first successful
|
||||||
|
unlock, and a legacy backup file opens as-is (re-exporting it writes the
|
||||||
|
current profile).
|
||||||
The key is the first statement after open, so the file header, schema, identity
|
The key is the first statement after open, so the file header, schema, identity
|
||||||
secret key, friend public keys, locators, profiles, payment rows and the
|
secret key, friend public keys, locators, profiles, payment rows and the
|
||||||
per-friend ratchet session blobs (`ratchet_sessions`) are all ciphertext on
|
per-friend ratchet session blobs (`ratchet_sessions`) are all ciphertext on
|
||||||
|
|
@ -66,6 +115,16 @@ A chat send to an unreachable onion is written to an `outbox` row next to its `m
|
||||||
|
|
||||||
The queue is bounded in scope: chat only. File transfer and `rcp` frames are one-shot, so a failed payment claim does not sit in the store being retried forever.
|
The queue is bounded in scope: chat only. File transfer and `rcp` frames are one-shot, so a failed payment claim does not sit in the store being retried forever.
|
||||||
|
|
||||||
|
## Reachability: there is no sealed mailbox, and no mutual-online indicator
|
||||||
|
|
||||||
|
**No sealed mailbox.** OnionWire does not implement a server-side message store, a sealed mailbox, or any store-and-forward drop. There is no address a peer can write a message to when you are offline, and nothing that holds a message on your behalf after your device is gone. A mailbox of that kind needs a persistent process that accepts and later replays ciphertext for an absent recipient — exactly the hosted store-and-forward server this threat model rules out (“Tor relays are not a chat server”, “Out of v1”). A sealed box whose key never leaves the user's device is still a server holding the traffic pattern and the ciphertext, and it is still a third party that can be compelled, logged, or silently serve a stale box. That is the design decision, and it is not planned as a follow-up.
|
||||||
|
|
||||||
|
**The chat outbox is local-device retry only.** A message to an unreachable peer is written to the local `outbox` row and re-dialed from this device. It dies with the device: no relay, no friend, no other install ever holds it. Nothing in the outbox is a delivery guarantee.
|
||||||
|
|
||||||
|
**No mutual-online indicator.** OnionWire has no presence, no "peer is online" dot, and no shared online state. Every send is a one-shot Noise IK session to the peer's onion and is closed after one application frame; the peer's availability is only learned from whether *this* dial succeeded. A roster row we have not reached is marked `stale` (from the last connect attempt, `last_connect_ok`) and the footer states the consequence instead of implying presence: `peer unreachable, queued (n/8, retry …)` while an outbox row is outstanding. "They are offline right now" and "they have never been online since my last attempt" are indistinguishable to OnionWire, and the UI does not pretend otherwise.
|
||||||
|
|
||||||
|
**What this costs, stated plainly.** Two devices that are never online at the same time cannot talk, and there is no queue that changes that — the sender's own device is the only queue. Anyone who needs offline delivery must run their own always-on OnionWire install (their own identity, their own onion) to hold the messages, which is a hosted server *they* own and operate, not a service OnionWire provides.
|
||||||
|
|
||||||
## Chat is ratcheted on top of the one-shot Noise session
|
## Chat is ratcheted on top of the one-shot Noise session
|
||||||
|
|
||||||
The Noise IK session is still the transport: handshake, **one** application
|
The Noise IK session is still the transport: handshake, **one** application
|
||||||
|
|
@ -85,13 +144,22 @@ device.
|
||||||
below.
|
below.
|
||||||
- *Post-compromise security after a DH ratchet step.* An attacker holding a
|
- *Post-compromise security after a DH ratchet step.* An attacker holding a
|
||||||
snapshot of one side's state cannot read the conversation past the next DH
|
snapshot of one side's state cannot read the conversation past the next DH
|
||||||
ratchet step: that step feeds a fresh X25519 output into the root, and the
|
ratchet step: that step feeds a fresh X25519 output — and, from the first
|
||||||
snapshot stops producing chain keys. The window is not zero — it lasts until
|
rotation, a fresh ML-KEM-768 secret — into the root, and the snapshot stops
|
||||||
the next step — but no attacker can prevent it closing.
|
producing chain keys. The window is not zero — it lasts until the next step —
|
||||||
- *The ratchet header is not on the wire.* `dh_pub`, `N` and `PN` ride inside
|
but no attacker can prevent it closing.
|
||||||
the Noise ciphertext (authenticated as AEAD associated data), so message
|
- *Quantum-resistant chains from the first rotation.* Every ratchet step mixes a
|
||||||
counts and ratchet-key changes are not observable, and a tampered header fails
|
fresh ML-KEM-768 secret into `KDF_RK` alongside the X25519 output
|
||||||
closed.
|
(`dh_out || ss_kem`, info `onionwire-ratchet-v2-kdfrk`). A harvest-now
|
||||||
|
adversary who records a hybrid chain and later breaks X25519 still needs the
|
||||||
|
ML-KEM-768 secret to walk that chain, which breaking X25519 does not give.
|
||||||
|
Ratchet keypairs are generated as `{x25519, ml-kem}` with the KEM seed derived
|
||||||
|
from the X25519 secret, so the KEM half adds no state to protect.
|
||||||
|
- *The ratchet header is not on the wire.* `dh_pub`, `N`, `PN` and, on hybrid
|
||||||
|
chains, `kem_pub`/`kem_ct` ride inside the Noise ciphertext (authenticated as
|
||||||
|
AEAD associated data), so message counts and ratchet-key changes are not
|
||||||
|
observable, and a tampered header fails closed. A missing KEM section on a
|
||||||
|
step is a hard `hybrid step required` rejection, never a classical fallback.
|
||||||
|
|
||||||
**Honest limits.**
|
**Honest limits.**
|
||||||
|
|
||||||
|
|
@ -101,16 +169,38 @@ device.
|
||||||
oldest-first. A snapshot also carries the current sending and receiving chain
|
oldest-first. A snapshot also carries the current sending and receiving chain
|
||||||
keys, which read the current chain until it advances. This is the price of
|
keys, which read the current chain until it advances. This is the price of
|
||||||
out-of-order delivery, and it is per friend.
|
out-of-order delivery, and it is per friend.
|
||||||
- *The bootstrap epoch is prekey-bound.* The initial root and both initial
|
- *Epoch 0 is classical — this is the remaining harvest-now window.* The
|
||||||
ratchet secrets are HKDF outputs of the X25519 DH between the two long-lived
|
bootstrap root and both initial ratchet secrets are HKDF outputs of the
|
||||||
signed prekeys, and the identity pubkeys that separate them are public. An
|
X25519 DH between the two long-lived signed prekeys, and the identity pubkeys
|
||||||
attacker who has both peers' prekey statics can therefore reconstruct the
|
that separate them are public. A per-session KEM secret cannot be folded into
|
||||||
**first** epoch. What that does not buy is a recorded message: every `rat `
|
epoch 0: each chat message is its own one-shot Noise session, so `ss_kem`
|
||||||
frame travels inside a one-shot Noise session whose ephemerals are not derived
|
differs per dial and per peer, and a root bound to it would make the two peers
|
||||||
from the prekeys, so the prekeys alone do not open stored traffic. From the
|
(or even message 1 and message 2) derive different chains. Epoch 0 is
|
||||||
first DH ratchet step on, fresh X25519 secrets enter and the prekeys derive
|
therefore derived with the classical `KDF_RK`, and the ML-KEM secret enters at
|
||||||
nothing — the bootstrap epoch is the exception, not the rule, and it is the
|
the **first rotation** — two round trips in, at the latest.
|
||||||
reason the state is dropped when a peer's prekey changes.
|
What that leaves exposed, precisely:
|
||||||
|
- The epoch-0 *chain keys* are not post-quantum. A future X25519 break
|
||||||
|
reconstructs the prekey DH, hence the epoch-0 root and every message key on
|
||||||
|
that chain. This covers everything sent before the first hybrid step,
|
||||||
|
including any frame that was encoded on epoch 0 and left in the outbox.
|
||||||
|
- It does **not** by itself open a recorded v2 transcript, because a v2 friend
|
||||||
|
wraps every `rat ` frame in the hybrid Noise session (ML-KEM-768 prelude).
|
||||||
|
The epoch-0 chain keys are a second layer; breaking X25519 alone still leaves
|
||||||
|
that outer layer closed. The exposure becomes real the moment the rat frame
|
||||||
|
itself is accessible — a state snapshot taken at epoch 0, an old client that
|
||||||
|
logged it, or a peer running the classical transport.
|
||||||
|
- For a **classical (v1) friend** there is no PQ layer anywhere: transport and
|
||||||
|
every ratchet step are X25519-only, so the whole conversation is
|
||||||
|
harvest-now-decrypt-later exposed. Hybrid ratchet steps require `kem_pk` on
|
||||||
|
the roster row, which a legacy invite does not carry.
|
||||||
|
- From the first hybrid step on, a state snapshot plus a future X25519 break is
|
||||||
|
not enough: the chain also needs the ML-KEM-768 secret, and the next rotation
|
||||||
|
replaces it. We do **not** claim full post-quantum forward secrecy, because
|
||||||
|
epoch 0 is outside that guarantee.
|
||||||
|
The bootstrap epoch is still the reason state is dropped when a peer's prekey
|
||||||
|
changes, and an attacker holding both prekey statics can reconstruct epoch 0
|
||||||
|
directly (no break needed). A recorded message is not opened by the prekeys
|
||||||
|
alone while the one-shot Noise session an ML-KEM friend used remains intact.
|
||||||
- *No deniability and no non-repudiation claim.* Chat frames are not signed and
|
- *No deniability and no non-repudiation claim.* Chat frames are not signed and
|
||||||
both parties derive the same chain keys, so nothing here would let a third
|
both parties derive the same chain keys, so nothing here would let a third
|
||||||
party decide which of the two authored a chat line. Identity is proven per
|
party decide which of the two authored a chat line. Identity is proven per
|
||||||
|
|
@ -118,15 +208,26 @@ device.
|
||||||
- *No one-time prekeys.* The bootstrap epoch uses the long-lived signed prekey
|
- *No one-time prekeys.* The bootstrap epoch uses the long-lived signed prekey
|
||||||
only, so there is no per-session prekey consumption. A peer prekey change
|
only, so there is no per-session prekey consumption. A peer prekey change
|
||||||
drops the state locally and the next chat frame re-bootstraps; there is no
|
drops the state locally and the next chat frame re-bootstraps; there is no
|
||||||
in-band reset and no key confirmation.
|
in-band reset and no key confirmation. The same is true of your **own**
|
||||||
|
prekey: `F8` rotates it, drops every stored state, and each friend has to
|
||||||
|
re-paste your invite, because a new prekey is never pushed.
|
||||||
- *A compromised endpoint is out of scope.* The ratchet state lives in the same
|
- *A compromised endpoint is out of scope.* The ratchet state lives in the same
|
||||||
SQLCipher file as the chat log, under the same passphrase. Anyone who opens
|
SQLCipher file as the chat log, under the same passphrase. Anyone who opens
|
||||||
the store holds the roots, both chain keys, the skipped keys and the plaintext
|
the store holds the roots, both chain keys, the skipped keys and the plaintext
|
||||||
history. `/wipe` clears chat, payments and outbox rows but **keeps** the
|
history. `/wipe` clears chat, payments and outbox rows but **keeps** the
|
||||||
ratchet state (roster and identity stay), so chat resumes on the same epoch;
|
ratchet state (roster and identity stay), so chat resumes on the same epoch;
|
||||||
`/wipe-all` removes the data dir with it.
|
`/wipe-all` removes the data dir with it.
|
||||||
- *No metadata protection beyond Noise.* One Noise session per message, no
|
- *Length is bucketed; timing is not.* One Noise session per message, and chat
|
||||||
padding: sizes and timing are what they were before the ratchet.
|
plaintext is padded inside the ratchet ciphertext to a fixed ladder (256 B to
|
||||||
|
32 KiB — `docs/PROTOCOL.md`, “Length buckets”), so an observer sees only the
|
||||||
|
bucket and not the body length. That is all it hides: message timing, retry
|
||||||
|
cadence, the one-shot-per-message circuits, and the timing of the handshake
|
||||||
|
are unchanged, and no cover traffic or jitter is generated. The frame header
|
||||||
|
is not padded: a classical `rat ` frame is 350 bytes at its smallest, while a
|
||||||
|
hybrid step's 2312-byte ML-KEM header makes its smallest frame 2622 bytes on
|
||||||
|
the wire. That is a size class, not a message count, and it does not leak the
|
||||||
|
body length inside the bucket. Non-chat frames (`loc `, `prf `, `inv `,
|
||||||
|
`rcp `, `tip `, `fil `) are not padded and still reveal their own sizes.
|
||||||
- *The ratchet does not re-open the "no server-side outbox" lock.* The state is
|
- *The ratchet does not re-open the "no server-side outbox" lock.* The state is
|
||||||
device-local, one row per friend in the encrypted store, and nothing about it
|
device-local, one row per friend in the encrypted store, and nothing about it
|
||||||
is transmitted. The local retry queue's two accepted consequences (device
|
is transmitted. The local retry queue's two accepted consequences (device
|
||||||
|
|
@ -153,6 +254,17 @@ watch-only wallet detected over RPC via `query_key spend_key` → `-29`).
|
||||||
seed-backed spend-capable wallet makes OnionWire a **local spend authority**
|
seed-backed spend-capable wallet makes OnionWire a **local spend authority**
|
||||||
for that file: anyone with the wallet passphrase or the wallet-RPC credentials
|
for that file: anyone with the wallet passphrase or the wallet-RPC credentials
|
||||||
can move the balance, and `/tip` is a supported way for a chat peer to get paid.
|
can move the balance, and `/tip` is a supported way for a chat peer to get paid.
|
||||||
|
Those credentials are sealed with the store data key (SQLCipher plus a per-row
|
||||||
|
AEAD), and so is the **wallet-file passphrase**: it is kept in the same sealed
|
||||||
|
row, because `monero-wallet-rpc` holds a wallet only for the life of one process
|
||||||
|
and reopening the file needs it. That is a deliberate decision with a real
|
||||||
|
consequence — **whoever can unlock the store can spend**: the store passphrase
|
||||||
|
(or its Keystore wrapper) is now sufficient, and there is no second secret
|
||||||
|
standing between a seized unlocked device and the wallet's balance. Nothing else
|
||||||
|
changes: `/tip` still refuses on a view-only wallet before any dial, the
|
||||||
|
spend-authority warning is still unavoidable at create/restore, the passphrase is
|
||||||
|
never logged, never in an error string and never on a process argv, and `/wipe`
|
||||||
|
keeps the wallet file and its passphrase exactly as it kept the file before.
|
||||||
The spend-authority warning is unavoidable at that create/restore step. Loopback
|
The spend-authority warning is unavoidable at that create/restore step. Loopback
|
||||||
binding is not an authorization boundary. Back up the seed; do not leave a
|
binding is not an authorization boundary. Back up the seed; do not leave a
|
||||||
spend-capable wallet on a device you do not trust; a separate hot wallet with a
|
spend-capable wallet on a device you do not trust; a separate hot wallet with a
|
||||||
|
|
@ -164,6 +276,19 @@ already runs, or one the app spawns. Wallet RPC is never dialed over clearnet or
|
||||||
over `.onion` — a remote wallet RPC would move spend authority off the box
|
over `.onion` — a remote wallet RPC would move spend authority off the box
|
||||||
through a channel the messenger’s `--password` gate does not cover.
|
through a channel the messenger’s `--password` gate does not cover.
|
||||||
|
|
||||||
|
**The seed-offset passphrase is a second spend secret, and it is not stored.**
|
||||||
|
An import may be given Monero's optional `seed_offset`: a phrase mixed into the
|
||||||
|
25 words at restore time, so the same words with a different offset open a
|
||||||
|
different wallet (plausible deniability). It is typed once, travels only in the
|
||||||
|
JSON-RPC body (never argv, never logged, never an error string), is never sealed
|
||||||
|
and never persisted — storing it would defeat the point. It is also not a second
|
||||||
|
gate on an already-imported wallet: whoever can unlock the store can still spend
|
||||||
|
the opened file, because the wallet file's own passphrase *is* sealed (previous
|
||||||
|
paragraph). A wrong offset is silent — the RPC succeeds and the wallet is
|
||||||
|
simply a different one — so the app cannot warn about it, and after such an
|
||||||
|
import a later seed backup is the *derived* mnemonic, which opens the wallet
|
||||||
|
without the offset.
|
||||||
|
|
||||||
### Chain source is the user’s choice
|
### Chain source is the user’s choice
|
||||||
|
|
||||||
Scan, receipt verification, and spend need a Monero daemon. The user picks one;
|
Scan, receipt verification, and spend need a Monero daemon. The user picks one;
|
||||||
|
|
@ -177,12 +302,52 @@ the app does not pick a public remote node for them.
|
||||||
Unsynced or not running is an honest “not ready” / unverified state, not a
|
Unsynced or not running is an honest “not ready” / unverified state, not a
|
||||||
fake success.
|
fake success.
|
||||||
|
|
||||||
2. **A daemon address they supply.** The wallet child points `--daemon-address`
|
2. **An in-process daemon** (Cuprate, behind the `cuprate-daemon` feature, on in
|
||||||
|
the Linux TUI/release binary; a `--no-default-features` build does not
|
||||||
|
include it). P2P, consensus and RandomX run in the OnionWire process; nothing is
|
||||||
|
spawned and nothing leaves the device except the chain P2P traffic itself.
|
||||||
|
What that changes: there is **no daemon operator** to trust — your own process
|
||||||
|
is the daemon, so the "operator sees your addresses" question does not exist.
|
||||||
|
The spend key, the chain, and the messenger are then all on one device.
|
||||||
|
What it does not change: the **device is now the trust root for chain data**.
|
||||||
|
Chain state is only as trustworthy as the binary running it, and a
|
||||||
|
compromised device corrupts the chain view along with everything else.
|
||||||
|
Honest limits, stated here rather than in a footnote:
|
||||||
|
- Cuprate is **pre-production**. Its own user book says *"do NOT use cuprated
|
||||||
|
for any serious purposes"*, and its `monerod` RPC parity is incomplete
|
||||||
|
(Cuprate issue #278). This is why the source is an opt-in build feature and
|
||||||
|
a stored user choice, never a default.
|
||||||
|
- Mainnet is **unvalidated**. The TUI can store a mainnet choice (`F6` 1/2);
|
||||||
|
every in-process surface still says `testnet only — mainnet is unvalidated`.
|
||||||
|
Cross-compiled is not device-proven.
|
||||||
|
- Cuprate's own `arti` feature is off (its Tor stack is `arti-client` 0.44,
|
||||||
|
which cannot unify with this crate's 0.49), so the in-process daemon's P2P
|
||||||
|
traffic is **clearnet**: your ISP sees that this device talks to Monero
|
||||||
|
peers. No Tor is on the chain path — Tor is the messenger's transport here,
|
||||||
|
not the chain's.
|
||||||
|
- Inbound P2P is off and the restricted RPC listener is disabled; the
|
||||||
|
unrestricted RPC binds loopback only, and it is the address the wallet
|
||||||
|
child dials. `--trusted-daemon` is still never passed.
|
||||||
|
- The chain database is a separate embedded store (fjall) under the chain
|
||||||
|
data directory, not the SQLCipher store the messenger writes — different
|
||||||
|
file, different exposure: it is not encrypted by that store's key.
|
||||||
|
|
||||||
|
3. **A daemon address they supply.** The wallet child points `--daemon-address`
|
||||||
at that host. Trust follows the address:
|
at that host. Trust follows the address:
|
||||||
- **Loopback** — same privacy as (1); the user owns `monerod`.
|
- **Loopback** — same privacy as (1); the user owns `monerod`.
|
||||||
- **`.onion`** — chain traffic over Tor through a localhost SOCKS5 listener
|
- **`.onion`** — chain traffic over Tor through a localhost SOCKS5 listener
|
||||||
the app provides for the wallet child (not the messenger’s Arti
|
the app provides for the wallet child (not the messenger’s Arti
|
||||||
`connect()`, and not a C-tor fallback for chat). Tor hides the transport.
|
`connect()`, and not a C-tor fallback for chat). That listener is the
|
||||||
|
bundled `arti` **binary** run as a child (`arti proxy -p <port>`) — a
|
||||||
|
second, separate Tor client with its own state and cache dirs, because
|
||||||
|
`arti-client` 0.49 exposes no SOCKS listener API. It is TCP loopback only
|
||||||
|
(`arti proxy -p` binds `127.0.0.1`/`::1`; arti 2.6.0 / `tor-config` 0.49
|
||||||
|
have no Unix-socket listen target — arti#1965), and the port is usable by
|
||||||
|
any local process at the user's privilege level: it is an app-private port,
|
||||||
|
not an access-controlled one. The app gates the spawn on the unlocked store
|
||||||
|
and waits ≤20s for the listener to accept before starting the wallet child,
|
||||||
|
so a dead proxy fails visibly instead of hanging. The SOCKS child stops
|
||||||
|
with the wallet child. Tor hides the transport.
|
||||||
The daemon operator still sees the wallet’s addresses during sync. The
|
The daemon operator still sees the wallet’s addresses during sync. The
|
||||||
host is the trust boundary.
|
host is the trust boundary.
|
||||||
- **Clearnet** — only if the user typed it. Not a default, not implied.
|
- **Clearnet** — only if the user typed it. Not a default, not implied.
|
||||||
|
|
@ -192,6 +357,32 @@ the app does not pick a public remote node for them.
|
||||||
Remote daemons are untrusted (`--trusted-daemon` off). Setup, view-only vs
|
Remote daemons are untrusted (`--trusted-daemon` off). Setup, view-only vs
|
||||||
spend, and RPC credentials: [WALLET.md](WALLET.md).
|
spend, and RPC credentials: [WALLET.md](WALLET.md).
|
||||||
|
|
||||||
|
## The recovery phrase and the private keys are displayable on demand
|
||||||
|
|
||||||
|
Both clients can show the **open** wallet's recovery phrase (`query_key
|
||||||
|
mnemonic`) and its private view and spend keys (`query_key view_key` /
|
||||||
|
`spend_key`), from an explicit user action. That is new exposure the threat model
|
||||||
|
did not previously enumerate: the phone screen — and the Linux TUI window — is
|
||||||
|
now one of the places a spending secret can be read from.
|
||||||
|
|
||||||
|
- The values come from the wallet file the child has **open**. There is no path
|
||||||
|
that reads another saved wallet's secret without opening it first, and none
|
||||||
|
that reads a wallet file directly: the RPC is the only source.
|
||||||
|
- They are never logged, never written to the store or any other file, and never
|
||||||
|
placed in an error string; the records that carry them (`WalletKeys`) redact
|
||||||
|
themselves under `Debug`. They exist in process memory only while a screen
|
||||||
|
shows them.
|
||||||
|
- They are shown only from an explicit user action, never on a refresh path.
|
||||||
|
- What this does **not** stop: a shoulder-surfer, a screen recorder, a
|
||||||
|
screenshot, or a malicious app with screen-capture permission. Whoever reads
|
||||||
|
the screen gets the keys; a view-only wallet leaks only the view key
|
||||||
|
(`spend_key` is `None`), but a spend-capable one leaks everything the file can
|
||||||
|
spend.
|
||||||
|
- The spend-authority warning above still applies and is now easier to reach:
|
||||||
|
the seed that makes a wallet spend-capable can be photographed off the device.
|
||||||
|
Treat any screen that shows a seed or a private key the way you treat the
|
||||||
|
wallet file itself.
|
||||||
|
|
||||||
## Backup file is the identity
|
## Backup file is the identity
|
||||||
|
|
||||||
`/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table.
|
`/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table.
|
||||||
|
|
@ -212,7 +403,11 @@ That socket is the app talking to the wallet process, not to the chain.
|
||||||
**Chain** traffic is the wallet child’s connection to a Monero daemon. It is
|
**Chain** traffic is the wallet child’s connection to a Monero daemon. It is
|
||||||
off unless the user opted into a wallet and chose a chain source: spawned local
|
off unless the user opted into a wallet and chose a chain source: spawned local
|
||||||
`monerod` (loopback), or a daemon address they entered. A `.onion` daemon is
|
`monerod` (loopback), or a daemon address they entered. A `.onion` daemon is
|
||||||
reached through a localhost SOCKS5 proxy used only by that wallet child. A
|
reached through a localhost SOCKS5 proxy used only by that wallet child: the
|
||||||
|
bundled `arti` binary run as `arti proxy -p <port>`, whose `--proxy` target is
|
||||||
|
`127.0.0.1` and whose `.onion` name travels inside the SOCKS request (Monero's
|
||||||
|
SOCKS5 client sends the domain-name form, so no local DNS runs on it). The
|
||||||
|
messenger's in-process Arti client is never handed to the wallet child. A
|
||||||
clearnet daemon address is an explicit user choice — a clearnet socket they
|
clearnet daemon address is an explicit user choice — a clearnet socket they
|
||||||
asked for — not the messenger path and not a hidden default.
|
asked for — not the messenger path and not a hidden default.
|
||||||
|
|
||||||
|
|
@ -234,7 +429,8 @@ the peer already knows the plaintext they sent.
|
||||||
|
|
||||||
## Out of v1
|
## Out of v1
|
||||||
|
|
||||||
Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward
|
Prosody, XMPP, s2s, MAM, carbons, a **sealed mailbox**, a **server-side**
|
||||||
relay, multi-device, DHT / name server, A/V. The local retry queue of the
|
outbox / store-and-forward relay, multi-device, DHT / name server, A/V. The
|
||||||
previous section is not an outbox in the XMPP sense: it never leaves the device.
|
local retry queue of the previous section is not an outbox in the XMPP sense: it
|
||||||
|
never leaves the device, and it is not a mailbox either — see “Reachability”.
|
||||||
|
|
||||||
|
|
|
||||||
817
docs/TUI.md
817
docs/TUI.md
|
|
@ -1,623 +1,288 @@
|
||||||
# OnionWire TUI — visual audit and design spec
|
# OnionWire TUI
|
||||||
|
|
||||||
This card does not change `src/`. Frames come from:
|
Operator map of the Linux terminal UI. Bindings live in `src/tui.rs`
|
||||||
|
(`function_key_for`, `parse_cmd`, per-screen `match` arms). This is not a
|
||||||
|
screenshot dump.
|
||||||
|
|
||||||
```
|
Run `onionwire` in a real terminal. `ONIONWIRE_ASCII` or `NO_COLOR` switches
|
||||||
cargo test --locked --test tui_frames -- --nocapture dump_audit_frames
|
ASCII chrome.
|
||||||
```
|
|
||||||
|
|
||||||
`tests/tui_chrome.rs` still locks helper **names** and **return strings**. Implementation
|
## Screens
|
||||||
must keep `wordmark_banner`, `compact_banner`, `banner_for_width`, `onion_glyph`,
|
|
||||||
`status_footer`, `main_footer_hints`, `help_overlay_text`, `draw_share`, and `Pane`
|
|
||||||
working. Add helpers; do not rename those.
|
|
||||||
|
|
||||||
## Gaps (could not render the live `App` frame)
|
`enum Screen` in `src/tui.rs`:
|
||||||
|
|
||||||
`App`, `App::draw`, `App::draw_main`, and every overlay except `draw_share` are
|
| Screen | How you get there | What it is |
|
||||||
private and need `Arc<Node>` (Arti + store). This presentation-only test cannot
|
|
||||||
construct that.
|
|
||||||
|
|
||||||
| Screen / state | What you get | Why |
|
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Main chat (empty, messages, long line, stale roster, alert) | **RECONSTRUCTED** — same `Layout` constraints as `src/tui.rs` `draw_main` (banner height, 36% roster, composer 3, footer 1) plus the real `banner_for_width` / `status_footer` | `App` private |
|
| `Main` | boot | Roster, chat, composer |
|
||||||
| Help / `/who` overlay | **RECONSTRUCTED** — Rect math copied from private `draw_text_overlay` | private |
|
| `Share` | `F2` | Invite string (`onionwire:v1:…`) |
|
||||||
| Share / invite | **REAL** `draw_share` | public |
|
| `Paste` | `F3` | Paste a friend's invite |
|
||||||
| Profile, paste, approve, rotate, wipe, quit, backup, restore, passphrase | **RECONSTRUCTED** — public `*_screen_text` / `ProfileEditor` copy inside `Block::bordered`, titles taken from `src/tui.rs` | private `draw_*` |
|
| `Approve` | paste of unknown `k` | `y` accept / `n` reject |
|
||||||
| Pay / invoice / file transfer | **No screen exists.** Footer `status_note` only (`invoice sent`, `sending`, `sent file {name}`, `send failed: {e}`) | not a gap in the test — a product finding |
|
| `Rotate` | `F4` | Type `ROTATE` to change the onion locator |
|
||||||
| Tor bootstrap / disconnected HS | Not a TUI screen. `hs status: Bootstrapping` is stderr before `ratatui::init` | out of TUI draw |
|
| `RotatePrekey` | `F8` | Type `ROTATE` to hard-cut the Noise static |
|
||||||
| Color / `NO_COLOR` | Glyph dumps only. Color findings are from reading `src/tui.rs` | TestBackend prints symbols |
|
| `Wipe` | `/wipe` or `/wipe-all` | Type `WIPE` or `WIPEALL` |
|
||||||
|
| `Profile` | `/profile` | Edit name, bio, optional Monero address |
|
||||||
Color, focus-by-border, and RGB-only styling are invisible in these dumps. Treat
|
| `ConfirmKeys` / `Passphrase` | `/backup`, `/restore` | Type `BACKUP`/`RESTORE`, then passphrase |
|
||||||
the reconstruction as the glyph skeleton, not a screenshot of Color.
|
| `Wallet` | `F6` | Receive QR, balance, transfers |
|
||||||
|
| `WalletSelect` | `F6` `w` | Saved wallets, pick one or create one |
|
||||||
## Deliverable 1 — before frames
|
| `WalletSetup` | `F6` `c` / `i`, or `/wallet create` / `import` | Spend warning, seed, optional seed-offset passphrase, import |
|
||||||
|
| `WalletSetupConfig` | `F7` | Node & wallet setup: RPC endpoint, chain source, start/stop, live node state |
|
||||||
Trailing spaces in the live buffer are omitted here. Re-run the command for
|
| `PeerPayments` | `p` on Main (roster or chat) | Peer-scoped `/pay` / `/tip` history |
|
||||||
byte-identical dumps, including 120x40 and 200x60.
|
| `Quit` | `Ctrl-Q` | Type `CLEAR` or `QUIT` |
|
||||||
|
|
||||||
### 80x24 — chrome (`banner_for_width` + `status_footer`, real helpers)
|
Help (`?`) is an overlay, not a screen. `/who` / `F5` is an overlay on Main.
|
||||||
|
|
||||||
```
|
Function keys that fire from Main are:
|
||||||
.-~~-. .-~~-. .-~~-. ONIONWIRE
|
|
||||||
( o )( o )( o ) identity = pubkey onion = locator
|
| Key | `FunctionKey` | Action |
|
||||||
`-..-' `-..-' `-..-' tor messenger no server
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help
|
|
||||||
```
|
|
||||||
|
|
||||||
Same footer with `status_note = "send failed: connection timed out"` — the note
|
|
||||||
**does not appear**. Ident + hints win. Fail-closed copy is gone at 80 and at
|
|
||||||
120 (full onion eats the row). It only survives at 200.
|
|
||||||
|
|
||||||
### 80x24 — RECONSTRUCTED main, empty
|
|
||||||
|
|
||||||
```
|
|
||||||
.-~~-. .-~~-. .-~~-. ONIONWIRE
|
|
||||||
( o )( o )( o ) identity = pubkey onion = locator
|
|
||||||
`-..-' `-..-' `-..-' tor messenger no server
|
|
||||||
┌roster 0───────────────────┐┌chat─────────────────────────────────────────────┐
|
|
||||||
│ ││no friends yet │
|
|
||||||
│ ││F3 paste an invite to add one │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
└───────────────────────────┘└─────────────────────────────────────────────────┘
|
|
||||||
┌composer──────────────────────────────────────────────────────────────────────┐
|
|
||||||
│/wipe /wipe-all /profile /who /pay /tip /file │
|
|
||||||
└──────────────────────────────────────────────────────────────────────────────┘
|
|
||||||
TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help
|
|
||||||
```
|
|
||||||
|
|
||||||
### 80x24 — RECONSTRUCTED main, messages + stale + alert
|
|
||||||
|
|
||||||
```
|
|
||||||
.-~~-. .-~~-. .-~~-. ONIONWIRE
|
|
||||||
( o )( o )( o ) identity = pubkey onion = locator
|
|
||||||
`-..-' `-..-' `-..-' tor messenger no server
|
|
||||||
passphrases do not match
|
|
||||||
┌roster 2 1 stale──────────┐┌chat alice──────────────────────────────────────┐
|
|
||||||
│> alice aaaaaaaa… ││you: ping │
|
|
||||||
│ bob-the-stale-peer bbbbb││them: pong │
|
|
||||||
│ ││them: this is a very long chat line that should │
|
|
||||||
│ ││wrap inside the chat pane instead of running off │
|
|
||||||
│ ││the right edge of an 80-column terminal and │
|
|
||||||
│ ││colliding with the roster border │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
└───────────────────────────┘└─────────────────────────────────────────────────┘
|
|
||||||
┌composer──────────────────────────────────────────────────────────────────────┐
|
|
||||||
│hello from composer │
|
|
||||||
└──────────────────────────────────────────────────────────────────────────────┘
|
|
||||||
sent TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help
|
|
||||||
```
|
|
||||||
|
|
||||||
Roster clips `bob-the-stale-peer bbbbb` mid-glyph. Chat wraps (good). Focus on
|
|
||||||
chat/composer is **not** visible in the glyph dump (color-only in `pane_block`).
|
|
||||||
|
|
||||||
### 80x24 — RECONSTRUCTED main, fail-closed send (note dropped)
|
|
||||||
|
|
||||||
```
|
|
||||||
.-~~-. .-~~-. .-~~-. ONIONWIRE
|
|
||||||
( o )( o )( o ) identity = pubkey onion = locator
|
|
||||||
`-..-' `-..-' `-..-' tor messenger no server
|
|
||||||
┌roster 2 1 stale──────────┐┌chat bob-the-stale-peer─────────────────────────┐
|
|
||||||
│ alice aaaaaaaa… ││no messages │
|
|
||||||
│> bob-the-stale-peer bbbbb││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
└───────────────────────────┘└─────────────────────────────────────────────────┘
|
|
||||||
┌composer──────────────────────────────────────────────────────────────────────┐
|
|
||||||
│/wipe /wipe-all /profile /who /pay /tip /file │
|
|
||||||
└──────────────────────────────────────────────────────────────────────────────┘
|
|
||||||
TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help
|
|
||||||
```
|
|
||||||
|
|
||||||
`status_note` was `send failed: peer onion down`. The before frame above drops it.
|
|
||||||
`tests/tui_frames.rs` `status_footer_drops_send_failed_when_crowded` now asserts
|
|
||||||
the note **is** present at 80, 120, and 200, along with `TOR` / `me:` / `? help`.
|
|
||||||
|
|
||||||
### 80x24 — `draw_share` (real)
|
|
||||||
|
|
||||||
Invite is 346 chars. Inner width 78. Wraps mid-hex. Full v3 onion fits on its
|
|
||||||
own line. No QR blocks (locked).
|
|
||||||
|
|
||||||
```
|
|
||||||
┌(o) invite────────────────────────────────────────────────────────────────────┐
|
|
||||||
│give this string to a friend; they F3 paste it │
|
|
||||||
│ │
|
|
||||||
│fp ea4a6c63… │
|
|
||||||
│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │
|
|
||||||
│ │
|
|
||||||
│onionwire:v1:k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22│
|
|
||||||
│c:o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion:spk=0101010│
|
|
||||||
│101010101010101010101010101010101010101010101010101010101:sig=46caf16b6da95e86│
|
|
||||||
│… │
|
|
||||||
└──────────────────────────────────────────────────────────────────────────────┘
|
|
||||||
```
|
|
||||||
|
|
||||||
### 80x24 — RECONSTRUCTED help overlay (private `draw_text_overlay` math)
|
|
||||||
|
|
||||||
Help is 22 content lines + border. Popup height is `min(lines, height-2)` = 22,
|
|
||||||
so it covers the banner, punches through roster/composer borders, and **clips**
|
|
||||||
`Esc closes this overlay`.
|
|
||||||
|
|
||||||
```
|
|
||||||
.-~~-. .-~~-. .-~~-. ONIONWIRE
|
|
||||||
( o ┌? help─────────────────────────────────────────────────────────┐
|
|
||||||
`-..-' │OnionWire keys │
|
|
||||||
┌roster│ │───────┐
|
|
||||||
│ │Tab / Shift-Tab cycle roster, chat, composer │ │
|
|
||||||
│ │… │ │
|
|
||||||
│ │/backup /path encrypted identity export │ │
|
|
||||||
└──────│/restore /path overwrite self keys │───────┘
|
|
||||||
┌compos│? this help │───────┐
|
|
||||||
│/wipe │Ctrl-Q quit; type CLEAR or QUIT │ │
|
|
||||||
└──────└───────────────────────────────────────────────────────────────┘───────┘
|
|
||||||
TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help
|
|
||||||
```
|
|
||||||
|
|
||||||
### 80x24 — other overlays (copy is real)
|
|
||||||
|
|
||||||
- Profile: `> name:` marker (good). Empty xmr is a blank value, not `(none)`.
|
|
||||||
- Paste: same wrap-mid-hex as share. Error state replaces the hint with the
|
|
||||||
error string (no "what next").
|
|
||||||
- Approve / rotate / wipe / quit / backup / passphrase: full-screen bordered
|
|
||||||
column of copy + typed buffer. Readable. Fine as modal confirmations.
|
|
||||||
- `/who`: overlay Clear is only the popup rect; chat remnants (`d`, `ff`) show
|
|
||||||
in the side gutters. Full onion is shown (good).
|
|
||||||
|
|
||||||
### 120x40 / 200x60
|
|
||||||
|
|
||||||
At 120, `status_footer` shows the **full** 62-char onion and still drops
|
|
||||||
`send failed: …`. At 200 the note survives in front of `TOR`. Banner stays the
|
|
||||||
3-line wordmark (width ≥ 63). Chat pane is large; hierarchy problem is worse
|
|
||||||
(more empty bordered void), not better. Dump: same cargo command.
|
|
||||||
|
|
||||||
## Deliverable 2 — findings
|
|
||||||
|
|
||||||
Walked in `tui-aesthetics` ladder order.
|
|
||||||
|
|
||||||
### 1. Clipping / overlap
|
|
||||||
|
|
||||||
| Sev | Where | Wrong | User impact |
|
|
||||||
|---|---|---|---|
|
|
||||||
| **blocker** | `src/tui.rs:1505` `status_footer` candidate list | Fail-closed `status_note` (`send failed: …`) is skipped when ident+hints fill the row. Proven at 80 and 120. | Peer down looks like success. The product rule is "send visibly fails". |
|
|
||||||
| **major** | `src/tui.rs:1702` `draw_text_overlay` | No `Wrap`. Height clipped to `area.height-2`. At 80x24 help overlaps banner/roster/composer and drops the last line. | `?` is unreadable on the floor size. |
|
|
||||||
| **major** | `src/tui.rs:1355` roster `format!("{name} {fp}")` | No truncate. `bob-the-stale-peer bbbbb` clips inside the 36% pane. | Cannot tell who is selected/stale. |
|
|
||||||
| **major** | `src/tui.rs:1570` `draw_share` (and paste body) | 346-char invite wraps mid-token at inner width 78. | Mouse-select copy is split; easy to miss a continuation line. |
|
|
||||||
| **minor** | `src/tui.rs:1334` alert | Alert is one raw line, no wrap/truncate. | Long error will collide with roster on the next row. |
|
|
||||||
| **nit** | `tests/tui_chrome.rs:15` (and `src/tui.rs:1512`, `1707`) | Width via `chars().count()`. See deliverable 4. | CJK/emoji can wrap in a real terminal while tests stay green. |
|
|
||||||
|
|
||||||
### 2. Hierarchy
|
|
||||||
|
|
||||||
| Sev | Where | Wrong | User impact |
|
|
||||||
|---|---|---|---|
|
|
||||||
| **major** | `src/tui.rs:1314` `draw_main` | Three-line wordmark + two equal bordered panes + bordered composer + footer. Chat is not the primary element. At 80x24, 3 rows of art + 3 composer + 1 footer + 2×2 borders leave the transcript starved. | First glance is ASCII onions, not the conversation. |
|
|
||||||
| **major** | `src/tui.rs:1340` | Roster is 36% of width on every size. | Chat (the primary pane) is the leftover. |
|
|
||||||
| **minor** | every `themed_block` / `pane_block` | Border on every pane, including composer and full-screen modals. | Eye cannot find content; "box drawing UI". |
|
|
||||||
|
|
||||||
### 3. Spacing
|
|
||||||
|
|
||||||
| Sev | Where | Wrong | User impact |
|
|
||||||
|---|---|---|---|
|
|
||||||
| **minor** | `src/tui.rs:1328` banner vs `1367` lists | Banner has no inner pad; list/paragraph sit against borders; footer has no pad. Mixed 0 and 1. | Ragged left edge: chat `no friends yet` vs roster empty. |
|
|
||||||
| **nit** | `src/tui.rs:93` `/file /path` extra space vs other slash rows | Help columns almost align, one extra space. | Looks unfinished. Do **not** change `help_overlay_text` unless `tui_chrome` is updated — the string is locked. Leave the space. |
|
|
||||||
|
|
||||||
### 4. States
|
|
||||||
|
|
||||||
| Sev | Where | Wrong | User impact |
|
|
||||||
|---|---|---|---|
|
|
||||||
| **major** | `src/tui.rs:1349` empty roster | `List` with zero items → blank pane titled `roster 0`. Empty copy lives only in chat. | Looks broken, not empty. |
|
|
||||||
| **major** | pay / tip / file | No pane. Outcome is a footer note that 80/120 may drop. | `/pay` and `/file` feel like they did nothing. |
|
|
||||||
| **minor** | `src/tui.rs:1414` empty composer | Placeholder is the slash cheatsheet, dim color only. | Reads as commands already typed. |
|
|
||||||
| **minor** | `src/tui.rs:1456` `no messages` | One word. No "type below, Enter sends". | Dead pane. |
|
|
||||||
| **nit** | loading | `sending` in footer, 100 ms poll, no spinner. | Correct. Keep. |
|
|
||||||
|
|
||||||
There is no dedicated disconnected screen. Stale friends get a `stale` suffix
|
|
||||||
(`src/tui.rs:1357`) — keep the word, not color-only.
|
|
||||||
|
|
||||||
### 5. Color
|
|
||||||
|
|
||||||
| Sev | Where | Wrong | User impact |
|
|
||||||
|---|---|---|---|
|
|
||||||
| **major** | `src/tui.rs:15-21` | Seven RGB colors. No 16-color map. No `NO_COLOR`. | 16-color and `NO_COLOR` terminals get garbage or still emit ANSI. |
|
|
||||||
| **minor** | `src/tui.rs:1359-1372` | Stale is `C_STALE` plus the word `stale` (ok). Selection is bg+fg+bold+`> ` (ok for roster). | Chat/composer focus is color-only (see focus). |
|
|
||||||
|
|
||||||
Accent RGB `(232,165,75)` is fine as **the** accent. Do not add more hues.
|
|
||||||
|
|
||||||
### 6. Focus
|
|
||||||
|
|
||||||
| Sev | Where | Wrong | User impact |
|
|
||||||
|---|---|---|---|
|
|
||||||
| **major** | `src/tui.rs:1468` `pane_block` | Focused chat/composer: accent border + bold title. No marker. Roster has `> `. | Monochrome / `NO_COLOR`: cannot see focus unless roster. Typing `j`/`k` feels dead. |
|
|
||||||
|
|
||||||
### 7. Motion
|
|
||||||
|
|
||||||
| Sev | Where | Wrong | User impact |
|
|
||||||
|---|---|---|---|
|
|
||||||
| **nit** | `src/tui.rs:24` `TUI_POLL` 100 ms | Full `terminal.draw` every poll even with no keys, so background send can refresh status. | Acceptable. No decorative spinner. Do not redraw faster. |
|
|
||||||
|
|
||||||
### 8. Copy
|
|
||||||
|
|
||||||
| Sev | Where | Wrong | User impact |
|
|
||||||
|---|---|---|---|
|
|
||||||
| **minor** | `src/tui.rs:1583` paste error | Error replaces the paste hint. No "what next". | User sees `bad invite` and an empty buffer. |
|
|
||||||
| **minor** | `src/tui.rs:1415` | Composer placeholder is a command dump, not a verb. | Conflicts with `?` help. |
|
|
||||||
| **nit** | `src/tui.rs:36` | `fingerprint mismatch` is a good short fail-closed string when it actually reaches the footer. | Often dropped (finding 1). |
|
|
||||||
|
|
||||||
### Untrusted text
|
|
||||||
|
|
||||||
`src/tui.rs:1461` `String::from_utf8_lossy(&m.plaintext)` goes into `Paragraph`
|
|
||||||
with wrap, **no** control/bidi strip, **no** ellipsis cap. Profile `bio` /
|
|
||||||
`display_name` and paste buffer are the same class. A separate in-flight PR
|
|
||||||
owns sanitization — do not duplicate it here. Implementation must call that
|
|
||||||
helper (or the agreed strip) on every peer-supplied string before draw.
|
|
||||||
|
|
||||||
## Deliverable 3 — spec (implement this)
|
|
||||||
|
|
||||||
### Pane structure
|
|
||||||
|
|
||||||
One primary element per screen.
|
|
||||||
|
|
||||||
| Screen | Primary | Secondary | Chrome |
|
|
||||||
|---|---|---|---|
|
|
||||||
| Main | Chat transcript | Roster (left, **22 cells** at 80, **28** at 120+, not 36%) | 1-line header, 3-row composer, 1-row status |
|
|
||||||
| Share / paste / approve | The invite string / typed buffer | fp + onion above it | title `(o) invite` etc. Keep `draw_share` public |
|
|
||||||
| Profile | The three fields with `>` on the active one | — | title `(o) profile` |
|
|
||||||
| Rotate / wipe / quit / backup / restore / passphrase | The confirm copy + typed token | — | existing titles |
|
|
||||||
| Help | The help text, **full screen** when `height < 28`, else a centered overlay that **fits** (wrap, scroll if needed, never clip the last line) | — | title `? help` |
|
|
||||||
| `/who` | Profile fields | — | same overlay rules as help |
|
|
||||||
| Pay / file | **None.** Stay on main. Status line carries the result. | — | — |
|
|
||||||
|
|
||||||
`draw_main` at `height <= 24` **must not** spend 3 rows on `wordmark_banner()`.
|
|
||||||
Use a one-line header. Do **not** change `banner_for_width(80)` — chrome tests
|
|
||||||
lock it to the wordmark. Add `main_header_line(width, fp, onion)` or call
|
|
||||||
`compact_banner()` plus ident. At `height >= 40`, the 3-line wordmark **may**
|
|
||||||
sit above the one-line ident; it is optional, not required.
|
|
||||||
|
|
||||||
### Spacing unit
|
|
||||||
|
|
||||||
**1 cell.** Apply as:
|
|
||||||
|
|
||||||
- Header: no box. One space between fields.
|
|
||||||
- Roster / chat: `Block` with `Borders::ALL` **only on those two** (the primary
|
|
||||||
split). Inner text starts one cell after the border (ratatui default).
|
|
||||||
- Composer: **no** outer box. Prefix `> ` when focused, ` ` when not. One
|
|
||||||
blank row is not required; the 3-row slot stays for wrapped input.
|
|
||||||
- Footer: no box. One space between clusters, two spaces between clusters if
|
|
||||||
width ≥ 120.
|
|
||||||
- Overlays: one box around the popup. No nested padding.
|
|
||||||
|
|
||||||
### Palette
|
|
||||||
|
|
||||||
One accent. Semantic color only for state. Pair every color with a glyph or
|
|
||||||
label.
|
|
||||||
|
|
||||||
| Role | RGB (keep) | 16-color | `NO_COLOR` |
|
|
||||||
|---|---|---|---|
|
|
||||||
| accent | `Rgb(232,165,75)` | `Yellow` | default + bold / reverse |
|
|
||||||
| text | `Rgb(196,214,176)` | `White` | default |
|
|
||||||
| dim | `Rgb(98,110,92)` | `DarkGray` | default |
|
|
||||||
| alert | `Rgb(220,80,70)` | `Red` | default + `! ` prefix |
|
|
||||||
| stale | `Rgb(210,180,80)` | `Yellow` | default + ` stale` (already) |
|
|
||||||
| highlight bg | `Rgb(48,42,28)` | `Reverse` | reverse |
|
|
||||||
| border | `Rgb(72,84,64)` | `DarkGray` | default |
|
|
||||||
|
|
||||||
`NO_COLOR` set (empty or any value): no `Style` fg/bg at all. Glyphs and
|
|
||||||
weight only.
|
|
||||||
|
|
||||||
Detection: `std::env::var_os("NO_COLOR")` is Some → no color. Else if the
|
|
||||||
backend is not a TTY or `TERM=dumb` → 16-color or no color, never RGB.
|
|
||||||
Else RGB as today.
|
|
||||||
|
|
||||||
### Glyphs
|
|
||||||
|
|
||||||
| Use | Unicode | ASCII fallback |
|
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| onion / share title | `(o)` (already) | `(o)` |
|
| `F2` | Share | Invite |
|
||||||
| focus | `> ` | `> ` |
|
| `F3` | Paste | Paste invite |
|
||||||
| truncate | `…` (`src/tui.rs:1730`) | `...` (budget 3 cells) |
|
| `F4` | Rotate | Onion locator |
|
||||||
| box | ratatui `Borders::ALL` (light) | `+` `-` `\|` via `border::Set` |
|
| `F5` | Who | Selected friend's profile |
|
||||||
| alert prefix | `! ` | `! ` |
|
| `F6` | Wallet | Wallet screen |
|
||||||
| stale | word `stale` | `stale` |
|
| `F7` | Setup | Node & wallet setup: RPC endpoint, chain source, start/stop |
|
||||||
| delivery: delivered | `✓` | `ok` |
|
| `F8` | RotatePrekey | Prekey hard cut |
|
||||||
| delivery: queued | `◷` | (word) `queued` |
|
|
||||||
| delivery: sending | `»` | (word) `sending` |
|
|
||||||
| delivery: failed | `✗` | (word) `failed` |
|
|
||||||
|
|
||||||
`queued` / `sending` / `failed` always carry their state word, so the ASCII
|
`F7` also fires on the wallet screen, which prints it. There is no `F9` and no
|
||||||
fallback drops the glyph instead of inventing one. Only `✓` is wordless, so it
|
`/settings`: that menu restated F6 and F7. A screen that does not name a
|
||||||
falls back to `ok`. `delivery_glyph()` /
|
function key does not answer one. Other screens handle their own keys (Esc
|
||||||
`tests/tui_spec.rs::delivery_markers_have_exercised_ascii_fallbacks` exercise the
|
back, typed confirms).
|
||||||
fallback path.
|
|
||||||
|
|
||||||
No emoji. `onion_glyph()` stays for callers that already use it; do not put it
|
## Main
|
||||||
on the main header.
|
|
||||||
|
|
||||||
ASCII chrome when `ONIONWIRE_ASCII` is set **or** when `NO_COLOR` is set (same
|
Focus starts on the composer. Footer hints (`main_footer_hints`):
|
||||||
switch is enough; do not add a crate).
|
|
||||||
|
|
||||||
### Focus
|
```
|
||||||
|
Tab F2 F3 F4 F5 Ctrl-Q F6 F7 ? help
|
||||||
|
```
|
||||||
|
|
||||||
Never color alone.
|
Pane-specific (`pane_footer_hints`):
|
||||||
|
|
||||||
- Roster: keep `highlight_symbol("> ")` + bold. Unselected rows start with two
|
| Pane | Hint |
|
||||||
spaces so columns align.
|
|
||||||
- Chat: title becomes `> chat {name}` when focused, ` chat {name}` when not,
|
|
||||||
plus bold on the `> ` title.
|
|
||||||
- Composer: `> ` prefix on the input row when focused (see spacing).
|
|
||||||
- `Tab` cycle unchanged (`Pane` tests lock it).
|
|
||||||
|
|
||||||
### `status_footer` priority (must change)
|
|
||||||
|
|
||||||
Replace the current "first candidate that fits, dropping the note" list.
|
|
||||||
|
|
||||||
Build left-to-right, **never drop** a non-empty `status_note`:
|
|
||||||
|
|
||||||
1. `status_note` (truncate with `…`/`...` to a minimum of 12 cells if needed).
|
|
||||||
2. `TOR me:{8}…` (keep `me:` — chrome tests require it).
|
|
||||||
3. `onion:` + full onion if it fits, else 8-char truncate (keep today's
|
|
||||||
`width >= 110` full-onion rule if it still fits **after** the note).
|
|
||||||
4. Hints from `main_footer_hints()`, dropping from the left of that list.
|
|
||||||
5. Always end with `? help`.
|
|
||||||
|
|
||||||
`? help` and `TOR` and `me:` must still be present at 80 and 120 so
|
|
||||||
`tests/tui_chrome.rs` stays green.
|
|
||||||
|
|
||||||
Fail-closed copy is `send failed: {e}` or `fingerprint mismatch`. Prefix `! `
|
|
||||||
when color is off.
|
|
||||||
|
|
||||||
### Copy — non-happy states
|
|
||||||
|
|
||||||
Do not soften fail-closed into a loader.
|
|
||||||
|
|
||||||
| State | Copy |
|
|
||||||
|---|---|
|
|---|---|
|
||||||
| no friends, roster | list item `no friends` (so the pane is not blank) |
|
| Roster | `j k p pay F3 add F6 wallet F7 setup ? help` |
|
||||||
| no friends, chat | `no friends yet` / `F3 paste an invite to add one` (keep) |
|
| Chat | `j k g G p pay F6 wallet F7 setup ? help` |
|
||||||
| friend, no messages | `no messages` / `type below, Enter sends` |
|
| Composer | `Enter send / commands F6 wallet F7 setup ? help` |
|
||||||
| nothing selected send | `no friend selected` (keep) |
|
|
||||||
| sending | `sending` (keep, no spinner) |
|
|
||||||
| sent | `sent` |
|
|
||||||
| peer down / send err | `send failed: {e}` (visible) |
|
|
||||||
| queued (outbox) | `{n} queued` — replaces the flat `sent`/`send failed` while rows are outstanding |
|
|
||||||
| queued + terminal failure | `{n} queued, send failed: {short}` |
|
|
||||||
| terminal failure | `send failed: {short}` (`{f} failed` when more than one) |
|
|
||||||
| already sending | `already sending` (keep) |
|
|
||||||
| stale friend | `stale` suffix (keep) |
|
|
||||||
| empty composer | `message` as dim placeholder (not the slash list). Slash list stays in `?` |
|
|
||||||
| paste error | `{err}` then `Enter resubmits Esc back` |
|
|
||||||
| unknown slash | `unknown command {cmd}` (keep) |
|
|
||||||
| passphrase mismatch | `passphrases do not match` (keep, alert line) |
|
|
||||||
|
|
||||||
### Before → after mockup (80x24 main)
|
The status line is drawn from the focused pane's hint, and the compactor drops
|
||||||
|
tokens from the front until the line fits, so a key that only appears in
|
||||||
|
`main_footer_hints` never reaches an 80-column terminal. `F6` and `F7` are
|
||||||
|
therefore named in both, at the tail. `p` is named only on roster and chat:
|
||||||
|
the composer types the letter.
|
||||||
|
|
||||||
**After** (target). Header 1 line. Roster 22-ish. Chat primary. Composer no
|
| Key | Action |
|
||||||
box. Fail-closed note kept. Focus marker on composer.
|
|---|---|
|
||||||
|
| `Tab` / `Shift-Tab` | Cycle roster → chat → composer |
|
||||||
|
| `1` / `2` / `3` | Focus roster / chat / composer when not typing |
|
||||||
|
| `j` `k` / arrows | Move or scroll the focused pane |
|
||||||
|
| `g` / `G` | Top / bottom of the focused pane |
|
||||||
|
| Enter | Send chat, or run a `/command` |
|
||||||
|
| `Esc` | Close overlay / clear composer |
|
||||||
|
| `?` | Help (except on Paste, so `?` can be in a payload) |
|
||||||
|
| `Ctrl-Q` | Quit prompt |
|
||||||
|
|
||||||
|
## Composer commands
|
||||||
|
|
||||||
|
`parse_cmd` (`src/tui.rs`). Unknown `/foo` is sent as chat if it does not match.
|
||||||
|
|
||||||
|
| Command | Effect |
|
||||||
|
|---|---|
|
||||||
|
| `/who` | Same as `F5` |
|
||||||
|
| `/profile` | Profile editor |
|
||||||
|
| `/pay <xmr> [memo]` | Invoice (`inv `), one-shot |
|
||||||
|
| `/tip <xmr> [memo]` | Transfer + `rcp ` + `tip `, one-shot |
|
||||||
|
| `/file /path` | File send, 1 MiB, one-shot |
|
||||||
|
| `/wallet create` | Same as `F6` then `c` |
|
||||||
|
| `/wallet import` | Same as `F6` then `i` |
|
||||||
|
| `/backup /path` | Encrypted identity export |
|
||||||
|
| `/restore /path` | Overwrite self keys |
|
||||||
|
| `/wipe` | Type `WIPE` — chat/payments/outbox; identity stays |
|
||||||
|
| `/wipe-all` | Type `WIPEALL` — delete data dir; new person |
|
||||||
|
|
||||||
|
## Share / paste / rotate
|
||||||
|
|
||||||
|
- **F2.** Full invite. `C` copies it (OSC 52). Esc back.
|
||||||
|
- **F3.** Paste buffer, Enter submits. Unknown `k` → Approve (`y`/`n`). Same `k`
|
||||||
|
updates locator and prekey only.
|
||||||
|
- **F4.** Type `ROTATE`. Identity fingerprint unchanged. Online friends get
|
||||||
|
`loc `; offline friends must F3-paste the new invite.
|
||||||
|
- **F8.** Type `ROTATE`. Prekey is the Noise static **and** the ratchet bootstrap
|
||||||
|
seed. Every friend must F3-paste the new invite. Status:
|
||||||
|
`prekey rotated · friends must F3-paste your new invite`.
|
||||||
|
|
||||||
|
## Wallet (`F6`)
|
||||||
|
|
||||||
|
The wallet, not the node: receive, balance, transfers, and create/import. Chain
|
||||||
|
and node configuration is `F7` (`Configures the wallet RPC endpoint and the
|
||||||
|
chain source`), named in the footer so the key is findable from here.
|
||||||
|
|
||||||
|
Footer:
|
||||||
|
|
||||||
```
|
```
|
||||||
onionwire tor me:abcdef01 onion:abcdefgh
|
c create i import r qr w wallets F7 node Esc back ? help
|
||||||
┌friends 2 1 stale┐┌chat alice───────────────────────────────────────────────┐
|
|
||||||
│ alice aaaaaaaa…││you: ping │
|
|
||||||
│> bob bbbbbbbb… s││them: pong │
|
|
||||||
│ ││them: this is a very long chat line that should wrap │
|
|
||||||
│ ││inside the chat pane instead of running off the edge │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
│ ││ │
|
|
||||||
└──────────────────┘└──────────────────────────────────────────────────────────┘
|
|
||||||
> hello from composer
|
|
||||||
! send failed: peer onion down TOR me:abcdef01 ? help
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Roster names truncate with ellipsis, not mid-letter. `stale` may abbreviate to
|
| Key | Effect |
|
||||||
`s` only if the word does not fit; prefer keeping `stale`.
|
|---|---|
|
||||||
|
| `r` or Enter | Toggle receive-address QR |
|
||||||
|
| `w` | Saved wallets (`WalletSelect`) |
|
||||||
|
| `c` | Create wallet (`SPEND` then seed once, type `SEEN`) |
|
||||||
|
| `i` | Import 25-word seed |
|
||||||
|
| `F7` | Node & wallet setup (`WalletSetupConfig`) |
|
||||||
|
| Esc | Back to Main |
|
||||||
|
|
||||||
### Before → after mockup (80x24 help)
|
The child's state and the chain source are shown here, but they are **set** on
|
||||||
|
`F7`: the start/stop/probe keys and the `1`/`2`/`3` in-process picker that used
|
||||||
|
to live on this screen are gone, so there is one place that configures the chain.
|
||||||
|
|
||||||
**After:** full-screen, no punch-through. Last line visible. `help_overlay_text()`
|
The chain line for an in-process source always carries
|
||||||
body unchanged (chrome tests).
|
`testnet only — mainnet is unvalidated` (`cuprate::TESTNET_ONLY`). The default
|
||||||
|
binary includes the in-process daemon. A build compiled without that feature
|
||||||
|
still shows the rebuild message on the chain row, and start fails with that
|
||||||
|
feature name only on such a build.
|
||||||
|
|
||||||
```
|
Create/import require the wallet RPC started with `--wallet-dir`. Filename:
|
||||||
┌? help────────────────────────────────────────────────────────────────────────┐
|
`onionwire`. Seed is never collected on the composer.
|
||||||
│OnionWire keys │
|
|
||||||
│ │
|
|
||||||
│ Tab / Shift-Tab cycle roster, chat, composer │
|
|
||||||
│ 1 / 2 / 3 focus roster / chat / composer │
|
|
||||||
│ j k or Up Down move or scroll focused pane │
|
|
||||||
│ g / G jump to top / bottom │
|
|
||||||
│ Enter send chat to selected friend, or a /command │
|
|
||||||
│ Esc close overlay, go back, clear composer │
|
|
||||||
│ F2 share invite │
|
|
||||||
│ F3 paste invite │
|
|
||||||
│ F4 rotate onion locator │
|
|
||||||
│ F5 selected friend's profile (/who) │
|
|
||||||
│ /profile edit name, bio, Monero address │
|
|
||||||
│ /pay <xmr> [memo] invoice to receive │
|
|
||||||
│ /tip <xmr> [memo] pay selected friend │
|
|
||||||
│ /file /path send file to selected friend (1 MiB) │
|
|
||||||
│ /backup /path encrypted identity export │
|
|
||||||
│ /restore /path overwrite self keys │
|
|
||||||
│ ? this help │
|
|
||||||
│ Ctrl-Q quit; type CLEAR or QUIT │
|
|
||||||
│ │
|
|
||||||
│Esc closes this overlay │
|
|
||||||
└──────────────────────────────────────────────────────────────────────────────┘
|
|
||||||
```
|
|
||||||
|
|
||||||
If the body still overflows 24 rows with the border, **scroll** the paragraph;
|
## Saved wallets (`F6` then `w`)
|
||||||
do not clip. Do not edit the locked help string to shrink it.
|
|
||||||
|
|
||||||
### Left alone (on purpose)
|
`WalletSelect`. One row per persisted wallet — name, identity prefix, locator
|
||||||
|
prefix, creation day — plus the selected row's full identity and locator under
|
||||||
|
the table. `j`/`k` or arrows select, Enter opens the selection, Esc back to
|
||||||
|
Main. Footer: `Esc back j k select Enter open ? help`.
|
||||||
|
|
||||||
- Wire protocol, session, store, send path.
|
The last item is **not** a wallet: `+ create new wallet` starts the same create
|
||||||
- Peer-text sanitization (other PR). Render must call it once it exists.
|
flow as `F6` `c`, so an empty list still has a way forward. An unlabelled wallet
|
||||||
- Fail-closed semantics. Only the **visibility** of the error changes.
|
(`NULL` in the store) reads `(unlabelled)`; a wallet whose onion service is not
|
||||||
- Locked helper names and `help_overlay_text` / wordmark strings.
|
published yet reads `-`; an unknown creation time reads `unknown`. A read that
|
||||||
- No QR. Invite stays a string.
|
failed is named on the screen — that is a different state from `no saved wallets
|
||||||
- No dedicated pay/invoice/file screens in v1.
|
yet`, and the two never share copy.
|
||||||
- No spinner. `TUI_POLL` 100 ms stays.
|
|
||||||
- `docs/PROTOCOL.md` unchanged.
|
|
||||||
- No new crates on the implementation card unless `unicode-width` is approved
|
|
||||||
(deliverable 4).
|
|
||||||
|
|
||||||
## Deliverable 4 — `chars().count()` is not terminal cells
|
Rows are plain display data (`WalletRow`), built by the caller from
|
||||||
|
`Node::list_wallets`; the render path never reads the store. Selection is by
|
||||||
|
row index, not by identity key (two records may share one).
|
||||||
|
|
||||||
`tests/tui_chrome.rs` asserts `line.chars().count() <= width`. Same metric in
|
The list is read when the screen opens — from the start screen and from
|
||||||
`status_footer` (`src/tui.rs:1512`) and `draw_text_overlay` (`src/tui.rs:1707`).
|
`F6` `w` — so a wallet created or imported in this session is offered the next
|
||||||
|
time the screen opens, with no restart. Enter on a wallet row re-points the
|
||||||
|
app-owned wallet child at that row's `wallet_filename` (`Node::open_wallet`,
|
||||||
|
a read-modify-write of the sealed record, so the generated RPC creds survive);
|
||||||
|
a running child is restarted onto the new file, and an idle one picks the
|
||||||
|
change up on its next start.
|
||||||
|
|
||||||
| Input | `chars().count()` | Terminal cells (East Asian Width; emoji Wide) |
|
**Start screen.** An install with at least one saved wallet opens on
|
||||||
|
`WalletSelect`; a fresh install (empty catalogue) opens on the create flow
|
||||||
|
(`WalletSetup::CreateWarn`), so the first run has no dead empty list. The
|
||||||
|
stored identity and locator are catalogue columns, not session state: a locator
|
||||||
|
rotates (`F4`) and identity is the roster key the node already holds, so the
|
||||||
|
live header keeps reading them from the node.
|
||||||
|
|
||||||
|
## Node & wallet setup (`F7`)
|
||||||
|
|
||||||
|
Footer: `Esc back Enter save Ctrl-T test` (plus the status line's own `? help`).
|
||||||
|
The compactor drops tokens from the front, and at 80 columns the status line
|
||||||
|
leaves about 25 cells, so the tail is what the default terminal shows. `Tab` and
|
||||||
|
`?` are universal; the node's own keys (`ctrl-s`, `ctrl-x`, `ctrl-r`) and
|
||||||
|
`Ctrl-U` are named in the body, on the row they act on.
|
||||||
|
Live from Main and from the wallet screen, which prints `F7 node`. Body is
|
||||||
|
`WalletSetupConfigState`, a snapshot taken when the screen opens — the render
|
||||||
|
path never reads the store.
|
||||||
|
|
||||||
|
This is the only screen that sets up the chain: the wallet RPC endpoint, and the
|
||||||
|
node that serves it.
|
||||||
|
|
||||||
|
| Row | Kind | Notes |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `你好` | 2 | **4** (both Wide) |
|
| `url` | text | the wallet RPC endpoint |
|
||||||
| `e\u{0301}` (e + combining acute) | 2 | **1** |
|
| `login` | text | `user:pass`. Never rendered back: the row reads `hidden · set` or `(none)` |
|
||||||
| `🧅` (U+1F9C5) | 1 | **2** |
|
| `view-only` | toggle | `no_spend`; `/tip` is refused before any dial |
|
||||||
|
| `chain` | picker | `space` cycles receive-only, local node, remote daemon, in-process |
|
||||||
|
| `daemon` | text | `host:port`, for the remote daemon |
|
||||||
|
| `monerod` | text | the binary this box spawns for a local node |
|
||||||
|
| `datadir` | text | where the chain is stored. Prefilled with the path already in use; an empty one is refused rather than silently defaulted |
|
||||||
|
| `prune` | toggle | local and in-process sources |
|
||||||
|
| `network` | picker | in-process source: `space` cycles mainnet (`unvalidated`) and testnet |
|
||||||
|
|
||||||
A line of twenty `你` is 20 chars and 40 cells: the test passes at width 80,
|
Under them, a `NODE` section: the live `Node::wallet_child_status` line (state,
|
||||||
the terminal wraps. A combining-mark string can look "too long" to the test and
|
chain source, `sync h/t` once a daemon reports numbers, the last error) and the
|
||||||
still fit.
|
last save/test answer. The live row is the node's answer, never the draft above
|
||||||
|
it, and it is re-read by `Ctrl-R`.
|
||||||
|
|
||||||
**Fix (implementation card, approved-then):** measure in cells. `unicode-width`
|
`Enter` saves and answers on the status row: `saved · not dialled yet — ctrl-s
|
||||||
is already in the lockfile via ratatui but **not** a direct dependency. Do not
|
starts it, ctrl-t tests the endpoint`, or, when a half is refused, `not saved ·
|
||||||
add it on this card. Preferred: depend on `unicode-width` explicitly and assert
|
wallet config: <why> · chain source: <why>` — one line shape either way round,
|
||||||
`UnicodeWidthStr::width(line) <= width as usize`. Until then, keep the existing
|
and the half that did write says so. Both halves are attempted even when one is
|
||||||
`chars().count()` tests green; do not rewrite them to fit a redesign.
|
refused: a wallet-RPC refusal must not silently drop a chain source the user
|
||||||
|
just picked. The endpoint's own validator is `Node::wallet_save_config`
|
||||||
|
(`Wallet::from_config` behind it) — loopback host, login required — and a
|
||||||
|
rejected form is rejected **before** it is written: nothing in the sealed record
|
||||||
|
moves and a running wallet is not re-dialled.
|
||||||
|
|
||||||
`tests/tui_frames.rs` `chars_count_is_not_terminal_cells` documents the three
|
The one exception is an **app-owned** chain source (local `monerod`, in-process
|
||||||
examples without adding a crate.
|
Cuprate) with an empty `url`: the child the app spawns generates its own creds
|
||||||
|
and picks its own port (`creds()` / `pick_port()`,
|
||||||
|
`Node::start_wallet_child_with` replaces the stored client after the spawn), so
|
||||||
|
the `url`/`login` rows describe no endpoint the app dials and an empty pair must
|
||||||
|
not veto the save. A *typed* endpoint with no login is still refused — that is
|
||||||
|
the externally run RPC path (`ONIONWIRE_WALLET_RPC`), where the refusal is true.
|
||||||
|
|
||||||
## After frames (spacing / ASCII / wrap / copy)
|
`Ctrl-T` dials the endpoint and answers with the sanitized `PingResult` line
|
||||||
|
(never the password). `Ctrl-U` clears the focused field, which is how a hidden
|
||||||
|
login gets replaced.
|
||||||
|
|
||||||
Base: `origin/main` after PR #24 (`33beede`). Hierarchy, fail-closed footer,
|
`Ctrl-S` saves and then starts the wallet child — the daemon and, for a local
|
||||||
1-line header, roster width, help overlay, and `NO_COLOR` palette are unchanged
|
source, `monerod` — so the setup screen is also the key that brings the node up.
|
||||||
here. Optional 3-line wordmark at height ≥ 40 was skipped (it fights the 1-line
|
A start that lands on a wallet file with no stored passphrase moves the app to
|
||||||
header without buying hierarchy).
|
the unlock prompt. `Ctrl-X` stops the child. Both go through the same
|
||||||
|
`Node::start_wallet_child` / `stop_wallet_child` the app's own lifecycle uses.
|
||||||
|
|
||||||
### 80x24 — `draw_share` after (field-boundary wrap)
|
The chain row is written only when it was changed. An untouched row leaves the
|
||||||
|
stored source alone, so opening `F7` to fix a port cannot silently undo an
|
||||||
|
in-process Cuprate choice or move a chain datadir. Picking a remote daemon says
|
||||||
|
so in the same frame — `a daemon you do not run sees this wallet's chain
|
||||||
|
traffic` — because that is the pick that moves chain trust off this box. The
|
||||||
|
address must parse as `host:port` first.
|
||||||
|
|
||||||
Invite lines break on `:`. `sig=` hex that does not fit continues as an
|
The default `onionwire` binary includes the in-process daemon. A build without
|
||||||
all-hex line. Joining those lines (no extra spaces) is the original payload.
|
that feature says so on the `chain` row, where the choice is made, rather than
|
||||||
|
offering it and refusing at start: the in-process wording is followed by
|
||||||
|
`NO_FEATURE_MSG` (clamped to the frame width). The pick is still offered — a
|
||||||
|
stored in-process source must still be readable — and that rebuild line appears
|
||||||
|
only on a build that left the feature out.
|
||||||
|
|
||||||
```
|
Esc is the single exit and wipes the login buffer (`Zeroizing<String>`).
|
||||||
┌(o) invite────────────────────────────────────────────────────────────────────┐
|
|
||||||
│give this string to a friend; they F3 paste it │
|
|
||||||
│ │
|
|
||||||
│fp ea4a6c63… │
|
|
||||||
│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │
|
|
||||||
│ │
|
|
||||||
│onionwire:v1: │
|
|
||||||
│k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: │
|
|
||||||
│o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: │
|
|
||||||
│spk=0101010101010101010101010101010101010101010101010101010101010101: │
|
|
||||||
│sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0│
|
|
||||||
│5401b0af934cefea617f71466f406af4bef956847200a8e915190b │
|
|
||||||
└──────────────────────────────────────────────────────────────────────────────┘
|
|
||||||
```
|
|
||||||
|
|
||||||
### 80x24 — ASCII switch (`ONIONWIRE_ASCII=1`)
|
`/profile`, `/backup`, `/restore`, `/wipe` and `/wipe-all` stay composer
|
||||||
|
commands. They are named in help (`?`). There is no settings menu that restates
|
||||||
|
them, and no `F9`.
|
||||||
|
|
||||||
No non-ASCII byte. Truncation marker is `...`. Borders are `+` `-` `|`.
|
## Peer payments (`p` on Main)
|
||||||
|
|
||||||
```
|
Peer-scoped signed invoices and tips, not the wallet's own transfer list.
|
||||||
+(o) invite--------------------------------------------------------------------+
|
`p` opens it from the roster or the chat (the composer types the letter). With
|
||||||
|give this string to a friend; they F3 paste it |
|
no friend selected the screen says `no friend selected`. `j`/`k` or arrows
|
||||||
| |
|
select. Esc back. Footer: `Esc back up/down select ? help`.
|
||||||
|fp ea4a6c63... |
|
|
||||||
|onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion |
|
|
||||||
| |
|
|
||||||
|onionwire:v1: |
|
|
||||||
|k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: |
|
|
||||||
|o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: |
|
|
||||||
|spk=0101010101010101010101010101010101010101010101010101010101010101: |
|
|
||||||
|sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0|
|
|
||||||
|5401b0af934cefea617f71466f406af4bef956847200a8e915190b |
|
|
||||||
+------------------------------------------------------------------------------+
|
|
||||||
```
|
|
||||||
|
|
||||||
### 80x24 / 120x40 — main chrome after
|
## Delivery markers (chat)
|
||||||
|
|
||||||
Same 1-line header, unboxed composer, fail-closed footer as PR #24. Dump:
|
| Row state | Marker |
|
||||||
|
|---|---|
|
||||||
|
| delivered | `✓` |
|
||||||
|
| queued | `◷ queued (try n/8, retry …)` |
|
||||||
|
| sending | `» sending` |
|
||||||
|
| failed | `✗ failed: …` |
|
||||||
|
| inbound | no marker |
|
||||||
|
|
||||||
|
Footer `{n} queued` while anything is outstanding. File transfer and payments
|
||||||
|
have no queue — outcome is a status note (`invoice sent`, `tip sent`,
|
||||||
|
`send failed: …`).
|
||||||
|
|
||||||
|
## Size
|
||||||
|
|
||||||
|
Floor **80×24**. Target **120×40**. Frame dumps:
|
||||||
|
|
||||||
```
|
```
|
||||||
cargo test --locked --test tui_spec -- --nocapture dump_spec_frames
|
cargo test --locked --test tui_spec -- --nocapture dump_spec_frames
|
||||||
|
cargo test --locked --lib f6_and_f7_frames_fit -- --nocapture
|
||||||
|
cargo test --locked --test tui_select -- --nocapture wallet_select_frame_dumps
|
||||||
```
|
```
|
||||||
|
|
||||||
Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is
|
|
||||||
`no messages` / `type below, Enter sends`; paste error is `{err}` then
|
|
||||||
`Enter resubmits Esc back`; alerts truncate to the frame width.
|
|
||||||
|
|
||||||
## Delivery state (outbox) — implemented
|
|
||||||
|
|
||||||
Per-message state, read from the local outbox. The states are the store's own
|
|
||||||
(`Queued` / `Sending` / `Sent` / `Failed`) — no parallel model, no new wire
|
|
||||||
prefix, no server.
|
|
||||||
|
|
||||||
| Row | Marker |
|
|
||||||
|---|---|
|
|
||||||
| delivered | `you: ping ✓` |
|
|
||||||
| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` |
|
|
||||||
| sending | `you: pong » sending` |
|
|
||||||
| failed | `you: pong ✗ failed: connection timed out` |
|
|
||||||
| inbound | `them: pong` (no marker) |
|
|
||||||
|
|
||||||
- `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` /
|
|
||||||
`retry now` comes from the stored absolute `next_attempt_at`.
|
|
||||||
- Failed reasons are sanitized, cut to the tail of the `a: b: c` chain and
|
|
||||||
capped at 24 cells (`short_send_reason`).
|
|
||||||
- Footer while rows are outstanding: `{n} queued`; any terminal failure keeps a
|
|
||||||
fail-closed `send failed: {short}` statement (with `! ` when colour is off).
|
|
||||||
- The tag trails the body and wraps with it, so it is never clipped away.
|
|
||||||
|
|
||||||
Correlation: a delivered row is deleted from the outbox, so an outbound message
|
|
||||||
with no row is `Sent`; pending rows are joined to messages on the row id —
|
|
||||||
`store::Message::id` equals `OutboxEntry::message_id` (`chat_with_delivery`).
|
|
||||||
Two identical bodies are distinct rows with distinct ids, so the marker always
|
|
||||||
lands on the row that actually owns the outbox entry.
|
|
||||||
|
|
||||||
### Size floor / target
|
|
||||||
|
|
||||||
- **Floor: 80x24.** Everything above must render there.
|
|
||||||
- **Target: 120x40.**
|
|
||||||
- `tests/tui_spec.rs::chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping`
|
|
||||||
draws the real `draw_chat` + `status_footer` at 80x24 and asserts every chat
|
|
||||||
and footer row is `<=` the terminal width, that the markers render, and that
|
|
||||||
an over-long message wraps instead of being clipped.
|
|
||||||
- Dump frames: `cargo test --locked --test tui_spec -- --nocapture dump_spec_frames`.
|
|
||||||
|
|
|
||||||
264
docs/VERIFY.md
Normal file
264
docs/VERIFY.md
Normal file
|
|
@ -0,0 +1,264 @@
|
||||||
|
# Verifying OnionWire
|
||||||
|
|
||||||
|
You were told OnionWire is a honeypot, or a trojan that steals Monero. That is a
|
||||||
|
claim about a *binary*, and it deserves an answer you can check yourself in ten
|
||||||
|
minutes rather than an argument you have to take on faith.
|
||||||
|
|
||||||
|
This document is that answer. It is written so that nothing here has to be
|
||||||
|
believed: every section is a command whose output you read yourself.
|
||||||
|
|
||||||
|
If you only do one thing, do [Check 3](#check-3--10-minutes-rebuild-the-release-and-compare-bytes).
|
||||||
|
It is the one that actually settles the question, and it is the thing most
|
||||||
|
projects claiming "the source is public" cannot offer.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What OnionWire can do to your Monero, and what it cannot
|
||||||
|
|
||||||
|
Start with the honest part, because a threat model that only lists the good news
|
||||||
|
is not a threat model.
|
||||||
|
|
||||||
|
**The wallet is optional and chat never needs it.** OnionWire is a messenger.
|
||||||
|
With no wallet configured at all there is no seed, no spend key, and no code
|
||||||
|
path that touches Monero. `docs/WALLET.md` opens with that sentence and it is
|
||||||
|
literally true.
|
||||||
|
|
||||||
|
**By default it cannot spend.** No seed and no spend key are on the device.
|
||||||
|
Receive works from a profile address or a view-only wallet. `/tip` is refused
|
||||||
|
locally, before any network dial, unless spend was explicitly turned on at
|
||||||
|
wallet create/restore. `ONIONWIRE_WALLET_NO_SPEND=1` forces that refusal.
|
||||||
|
|
||||||
|
**A view-only wallet is detected and cannot be spent.** OnionWire probes
|
||||||
|
`query_key` with `key_type=spend_key`; monero answers `-29 WATCH_ONLY`
|
||||||
|
("Cannot retrieve spend key") for a wallet with no spend key, and that answer is
|
||||||
|
what the app keys off. It cannot extract a spend key that is not in the wallet.
|
||||||
|
|
||||||
|
**The wallet RPC is loopback-only, and it demands a login.** OnionWire refuses
|
||||||
|
an RPC URL with no credentials and refuses to run against an open RPC. It never
|
||||||
|
puts wallet RPC on clearnet and never over `.onion`, and it never passes
|
||||||
|
`--trusted-daemon`.
|
||||||
|
|
||||||
|
**The part that is genuinely exposure — read this one.** In *app-owned wallet*
|
||||||
|
mode OnionWire spawns `monero-wallet-rpc` itself and therefore knows the RPC
|
||||||
|
credentials it set. It can read the open wallet's recovery phrase, and it does:
|
||||||
|
`src/wallet.rs` calls `query_key keytype=mnemonic` to drive the backup screen,
|
||||||
|
and `query_key spend_key` / `view_key` for the key-display actions. `docs/THREAT_MODEL.md`
|
||||||
|
says so directly — "the recovery phrase and the private keys are displayable on
|
||||||
|
demand", and a spend-capable wallet makes OnionWire "a local spend authority for
|
||||||
|
that file".
|
||||||
|
|
||||||
|
So: **a malicious build of that path could exfiltrate a seed.** That is not
|
||||||
|
spin, it is the surface. The mitigations are that the seed-read is a user-
|
||||||
|
initiated action on a wallet you chose to give it, that a funded wallet should
|
||||||
|
be a separate hot wallet rather than savings, and that if you want OnionWire to
|
||||||
|
*not* be able to spend, point it at a view-only wallet or run it with no wallet
|
||||||
|
at all. The threat model already recommends exactly this; it is not a
|
||||||
|
concession extracted by criticism.
|
||||||
|
|
||||||
|
The rest of this document is about how you check that the binary you downloaded
|
||||||
|
is the code described above, and not something else.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Check 0 — first, get the file, and know why a download can fail
|
||||||
|
|
||||||
|
Two things break a download from this host, and neither means the release is
|
||||||
|
missing:
|
||||||
|
|
||||||
|
- **`/releases/latest/download/…` is not served by this Forgejo — it is a 404.**
|
||||||
|
The GitHub habit fails here. Always pin the tag:
|
||||||
|
`…/releases/download/v0.7.0/onionwire-x86_64-unknown-linux-gnu`.
|
||||||
|
- **Cloudflare in front of the Forgejo rejects non-browser User-Agents.** A
|
||||||
|
script that sends a default library UA gets `HTTP 403` with the body
|
||||||
|
`error code: 1010` — even with a correct tag and URL. Measured against a real
|
||||||
|
asset on this host: browser UA → `206`, `curl/8.7.1` → `206`,
|
||||||
|
`Python-urllib/3.14` → `403`. Set a real `User-Agent` on any scripted fetch,
|
||||||
|
or use `curl`.
|
||||||
|
|
||||||
|
## Check 1 — 30 seconds: what code is even in the binary
|
||||||
|
|
||||||
|
From a clone, on whatever commit you are interested in:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo tree --locked -e normal --depth 1 # direct dependencies: 27 of them
|
||||||
|
cargo tree --locked -e normal | wc -l # ~523 crates in total
|
||||||
|
```
|
||||||
|
|
||||||
|
The direct list is the one worth reading. All 27 are known crates:
|
||||||
|
|
||||||
|
```
|
||||||
|
argon2 arti-client chacha20poly1305 cuprated ed25519-dalek futures hkdf
|
||||||
|
hmac md-5 qrcode rand ratatui rpassword rusqlite rustls safelog
|
||||||
|
serde_json sha2 sha3 snow tokio toml tor-cell tor-hsservice
|
||||||
|
tor-rtcompat x25519-dalek zeroize
|
||||||
|
```
|
||||||
|
|
||||||
|
Two of those deserve naming, because they are the honest answer to "why is there
|
||||||
|
HTTP in a chat program":
|
||||||
|
|
||||||
|
- **`arti-client`** — Tor, in-process.
|
||||||
|
- **`cuprated`** — the in-process Monero chain node, pinned to a git revision.
|
||||||
|
It is a **default feature**, so the release binary ships it.
|
||||||
|
|
||||||
|
That second one is why the graph contains `hyper`, `axum`, `tower-http` and
|
||||||
|
`http`. Do not take a grep's word for provenance — ask the graph:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo tree --locked -e normal -i http # axum <- cuprate-rpc-interface <- cuprated
|
||||||
|
cargo tree --locked -e normal -i reqwest # "did not match any packages"
|
||||||
|
```
|
||||||
|
|
||||||
|
`axum` and `hyper` are Cuprate's **JSON-RPC server** — the thing that answers a
|
||||||
|
wallet client on loopback. That is a server, not a client. `http`/`httparse`
|
||||||
|
also reach the graph through Arti's directory client, which speaks the Tor
|
||||||
|
directory protocol inside a Tor circuit.
|
||||||
|
|
||||||
|
What is genuinely absent, and worth confirming yourself:
|
||||||
|
|
||||||
|
- **No HTTP client.** `cargo tree -i reqwest` matches nothing: no `reqwest`,
|
||||||
|
`ureq`, `isahc` or `curl` anywhere.
|
||||||
|
- **No telemetry.** No Sentry, analytics or crash-reporting SDK in the graph.
|
||||||
|
|
||||||
|
## Check 2 — 2 minutes: run it with no wallet at all
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ONIONWIRE_WALLET_NO_SPEND=1 ./onionwire
|
||||||
|
```
|
||||||
|
|
||||||
|
Chat, invites, onion rotation and the ratchet all work. Nothing about Monero is
|
||||||
|
reachable. If your concern is specifically "steals Monero", this is the
|
||||||
|
configuration where the concern does not apply.
|
||||||
|
|
||||||
|
**The clearnet traffic you will see, stated plainly.** The release binary's
|
||||||
|
default feature set includes the in-process Cuprate node. If you start a chain
|
||||||
|
source, that node syncs to the Monero P2P network over clearnet, and you will
|
||||||
|
see it in `sudo ss -tupn` or `tcpdump`. That is the node doing its job — it is
|
||||||
|
not the messenger phoning home and it carries no chat data — but it *is* real
|
||||||
|
outbound traffic, and any "no clearnet at all" claim would be false without
|
||||||
|
this sentence.
|
||||||
|
|
||||||
|
If you do not want it:
|
||||||
|
|
||||||
|
- leave the chain source unset and unstarted (`F7`), and let a wallet RPC you
|
||||||
|
run yourself be the only Monero side; or
|
||||||
|
- build without it: `cargo build --release --no-default-features --features rustls`.
|
||||||
|
|
||||||
|
Honest note on that second option: a `--no-default-features` binary is a
|
||||||
|
different build and will not match the published hash. Building it yourself is
|
||||||
|
the trust-minimising move — you just cannot use Check 3 to compare it against a
|
||||||
|
download.
|
||||||
|
|
||||||
|
## Check 3 — 10 minutes: rebuild the release and compare bytes
|
||||||
|
|
||||||
|
This is the real check. It answers the only objection that survives "the source
|
||||||
|
is public": *the binary I downloaded might not be that source.*
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://forgejo.siriusdevops.com/sirius/onionwire
|
||||||
|
cd onionwire
|
||||||
|
git fetch --tags
|
||||||
|
scripts/verify-reproducible.sh v0.7.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Replace `v0.7.0` with the tag you are checking. You need docker; you do not
|
||||||
|
need Rust, or the right glibc, or the right distro. The rebuild happens inside
|
||||||
|
the same builder image, pinned **by digest**, that CI uses, with the source
|
||||||
|
paths, the target path, and `SOURCE_DATE_EPOCH` all fixed by
|
||||||
|
`scripts/reproducible-build.sh`.
|
||||||
|
|
||||||
|
It prints one of:
|
||||||
|
|
||||||
|
```
|
||||||
|
RESULT: MATCH — the published onionwire-x86_64-unknown-linux-gnu is
|
||||||
|
byte-for-byte the output of commit <sha> built with the documented recipe.
|
||||||
|
```
|
||||||
|
|
||||||
|
or `RESULT: MISMATCH` and exits non-zero.
|
||||||
|
|
||||||
|
**What a MATCH proves:** the released binary is exactly what this source
|
||||||
|
compiles to with this recipe. Auditing the source is therefore sufficient —
|
||||||
|
which is the property that was missing before, and the one the "just read the
|
||||||
|
code" argument always quietly assumed.
|
||||||
|
|
||||||
|
**What a MATCH does not prove:** that the source is benign. A project could
|
||||||
|
publish source that does something bad and a binary that faithfully implements
|
||||||
|
it. Reproducibility removes the *builder* from your trust set; it does not
|
||||||
|
remove the *author*. Judging the source is still yours to do — now at least
|
||||||
|
against a binary you know corresponds to it.
|
||||||
|
|
||||||
|
A mismatch is a finding, not a glitch. The release also carries
|
||||||
|
`build-info-<triple>.txt` recording the commit, epoch, toolchain, builder image
|
||||||
|
digest and resulting hash, so you can see whether the release was cut from a
|
||||||
|
different commit or the pinned image moved before you cry foul.
|
||||||
|
|
||||||
|
## Check 4 — verify the release signature
|
||||||
|
|
||||||
|
Every binary and checksum asset is signed with [minisign](https://jedisct1.github.io/minisign/).
|
||||||
|
The public key lives in the repo at `scripts/onionwire-signing.pub` and is also
|
||||||
|
published as a release asset — get it from the repo, not from the same download
|
||||||
|
you are checking, or the signature proves nothing.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
minisign -Vm onionwire-x86_64-unknown-linux-gnu -p onionwire-signing.pub
|
||||||
|
```
|
||||||
|
|
||||||
|
`Signature and comment signature verified` means the file is the one signed by
|
||||||
|
that key. A `.sha256` file next to a binary only proves the download matches the
|
||||||
|
release page; a signature proves the artifact is the one the maintainer signed,
|
||||||
|
even if the release page is later altered.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What is still not proven
|
||||||
|
|
||||||
|
So that nobody over-claims on our behalf:
|
||||||
|
|
||||||
|
- **There is no third-party audit.** `docs/SECURITY_AUDIT.md` is explicitly
|
||||||
|
in-house. It is a starting point for a reviewer, not a substitute for one.
|
||||||
|
- **Reproducible builds pin the build, not the intent.** See above.
|
||||||
|
- **The seed-display capability is by design.** If you consider "an app that can
|
||||||
|
read my seed" unacceptable regardless of what it does with it, then do not
|
||||||
|
give OnionWire a spend-capable wallet. Use a view-only wallet or none. That is
|
||||||
|
a legitimate position and OnionWire supports it without argument.
|
||||||
|
- **A build you compile yourself is stronger than a verified download.** If you
|
||||||
|
want the shortest trust chain, `git clone && cargo build --release` beats both
|
||||||
|
the signature and the reproduction check, because there is no released binary
|
||||||
|
to trust at all.
|
||||||
|
|
||||||
|
If you find a discrepancy, a way to exfiltrate a seed, or a signature that does
|
||||||
|
not verify, that is exactly what these checks are for. Report it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Maintainer: the signing key
|
||||||
|
|
||||||
|
One-time setup, on a machine you control:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
minisign -G -W -p scripts/onionwire-signing.pub -s onionwire-signing.key
|
||||||
|
```
|
||||||
|
|
||||||
|
`-W` means the secret key is not encrypted: CI cannot answer a password prompt,
|
||||||
|
and a passphrase stored beside the key in the same secret store protects nothing.
|
||||||
|
Then:
|
||||||
|
|
||||||
|
1. Commit `scripts/onionwire-signing.pub`.
|
||||||
|
2. Store the **contents** of `onionwire-signing.key` as the Forgejo Actions
|
||||||
|
secret `MINISIGN_SECRET_KEY` (Settings → Actions → Secrets).
|
||||||
|
3. Delete `onionwire-signing.key` from your machine, or keep it somewhere
|
||||||
|
genuinely offline. Anyone holding it can sign a release.
|
||||||
|
|
||||||
|
`scripts/sign-release.sh` fails closed: with no key, or if a signature it just
|
||||||
|
produced does not verify against the committed public key, it exits non-zero and
|
||||||
|
the release is not published. That is deliberate — an unsigned release is worse
|
||||||
|
than a missing one, because it looks the same as a signed one to anyone who is
|
||||||
|
not checking.
|
||||||
|
|
||||||
|
## Maintainer: the builder image digest
|
||||||
|
|
||||||
|
`BUILDER_IMAGE` is pinned by digest in three files that must agree:
|
||||||
|
`.forgejo/workflows/release.yml` (`RUST_IMAGE`), `scripts/verify-reproducible.sh`,
|
||||||
|
and `scripts/build-release-local.sh`. When you bump it, the released hashes are
|
||||||
|
expected to change — that is a toolchain change, not a compromise. Bump all three
|
||||||
|
in one commit so a verifier never rebuilds with a different toolchain than CI
|
||||||
|
shipped.
|
||||||
492
docs/WALLET.md
492
docs/WALLET.md
|
|
@ -8,43 +8,349 @@ receipt checks (`get_transfers`). `/tip` is off.
|
||||||
|
|
||||||
**Spend is opt-in** at wallet create or restore (seed-backed). That makes
|
**Spend is opt-in** at wallet create or restore (seed-backed). That makes
|
||||||
OnionWire a local spend authority for that wallet file — see the spend-authority
|
OnionWire a local spend authority for that wallet file — see the spend-authority
|
||||||
warning below. The threat-model write-up is [THREAT_MODEL.md](THREAT_MODEL.md).
|
warning below. Threat model: [THREAT_MODEL.md](THREAT_MODEL.md). TUI keys:
|
||||||
|
[TUI.md](TUI.md).
|
||||||
|
|
||||||
The app talks to `monero-wallet-rpc` over loopback HTTP Digest only, whether
|
The app talks to `monero-wallet-rpc` over **loopback HTTP Digest only**, and it
|
||||||
that process is one you already run or one the app spawns:
|
can own that process itself:
|
||||||
|
|
||||||
- hand out a receive subaddress for `/pay` invoices (`create_address`),
|
- hand out a receive subaddress for `/pay` invoices (`create_address`),
|
||||||
- read incoming transfers to verify a peer's receipt (`get_transfers`),
|
- read incoming transfers to verify a peer's receipt (`get_transfers`),
|
||||||
- and — only if you opted into spend — `/tip` (`transfer`).
|
- and — only if you opted into spend — `/tip` (`transfer`).
|
||||||
|
|
||||||
**Prefer view-only until you actually want `/tip`.** Everything else in this
|
**Prefer view-only until you actually want `/tip`.**
|
||||||
document explains why, and what breaks when you do.
|
|
||||||
|
|
||||||
## Env vars
|
Wallet RPC is never on clearnet and never over `.onion`. Chain traffic is off
|
||||||
|
unless you opted into a wallet and chose a source. A remote daemon is untrusted
|
||||||
|
(`--trusted-daemon` is never passed).
|
||||||
|
|
||||||
|
## Ports (do not swap these)
|
||||||
|
|
||||||
|
| Port | What it is |
|
||||||
|
|---|---|
|
||||||
|
| **18081** | App-owned **local** daemon unrestricted RPC (`DEFAULT_MONEROD_RPC_PORT` in `src/wallet_child.rs`). Spawned `monerod` and in-process Cuprate both bind `127.0.0.1:18081`. The wallet child dials that. |
|
||||||
|
| **18089** | A daemon's *restricted*-RPC port. It belongs only in examples of a **remote** `--daemon-address` you type. Not the app-owned local port. |
|
||||||
|
| random loopback | App-owned `monero-wallet-rpc` bind (`127.0.0.1:0`, then the port is kept). |
|
||||||
|
|
||||||
|
A doc or config that puts the local child on 18089 is wrong.
|
||||||
|
|
||||||
|
## The app-owned wallet child
|
||||||
|
|
||||||
|
`src/wallet_child.rs` owns the child pair instead of asking you to export an
|
||||||
|
env var:
|
||||||
|
|
||||||
|
- **`monero-wallet-rpc`** is spawned with `--rpc-bind-ip 127.0.0.1`, a **random
|
||||||
|
free loopback port**, a generated `--rpc-login` (`user:pass`, random
|
||||||
|
`[a-z0-9]`), and `--wallet-dir $ONIONWIRE_HOME/wallet`. A bare name is the
|
||||||
|
executable of that name next to the OnionWire binary, when that file is
|
||||||
|
executable; otherwise `PATH`. An absolute path is spawned as given (Android's
|
||||||
|
bundled library, or a path the operator set). No `--wallet-file` and
|
||||||
|
no `--password`: argv is world-readable to the same user through `ps`, so the
|
||||||
|
wallet is opened **over RPC** (`open_wallet`) once the child is up, and never
|
||||||
|
named on the command line.
|
||||||
|
- **`monerod`** is spawned when the chain source is *local*:
|
||||||
|
`--non-interactive --data-dir <datadir> --rpc-bind-ip 127.0.0.1 --rpc-bind-port
|
||||||
|
18081`. The wallet child dials `127.0.0.1:18081`.
|
||||||
|
- **Start waits up to 5s for `127.0.0.1:18081` to accept before spawning
|
||||||
|
`monero-wallet-rpc`, and up to 5s for that child's own port before
|
||||||
|
`open_wallet`.** A closed port fails the start. A connect refusal while state is
|
||||||
|
still `connecting` is not shown as an error.
|
||||||
|
- **`arti`** is spawned as a SOCKS child only when the chain source is a
|
||||||
|
`.onion` daemon: `arti proxy -p <port>`.
|
||||||
|
- `--trusted-daemon` is never passed.
|
||||||
|
- Wallet dir `0700`, wallet file `0600`.
|
||||||
|
- The child is watched by polling (`try_wait`). `stop()` kills children on
|
||||||
|
shutdown. Nothing promises “always running”, and Android will not.
|
||||||
|
|
||||||
|
Generated `user:pass` is sealed with the store data key in the SQLCipher
|
||||||
|
`wallet_child` table. It never appears in `ONIONWIRE_WALLET_RPC`.
|
||||||
|
|
||||||
|
`monero-wallet-rpc` starts with **no wallet open** and keeps one open only for
|
||||||
|
the life of its process, so a restart (app relaunch, Lock/unlock, a wallet
|
||||||
|
re-point) would otherwise answer every read with `-13 No wallet file` while the
|
||||||
|
file sits on disk. After the child is up the app therefore issues `open_wallet`
|
||||||
|
for the configured catalogue row.
|
||||||
|
|
||||||
|
That needs the passphrase, and the app **keeps it**: the passphrase you type at
|
||||||
|
create/import (or the one you enter once for a wallet that predates this) is
|
||||||
|
sealed with the store data key in the SQLCipher `wallet_config` row, beside the
|
||||||
|
RPC creds, under its own AAD. It is never logged, never put in an error string,
|
||||||
|
and never on a process argv. The consequence is deliberate and stated in
|
||||||
|
[THREAT_MODEL.md](THREAT_MODEL.md): **the store passphrase is now sufficient to
|
||||||
|
spend** — an attacker who has it can open the wallet file and move the balance,
|
||||||
|
without a second secret. The spend-authority warning at create/restore is
|
||||||
|
unchanged and is not made weaker by this.
|
||||||
|
|
||||||
|
Wipe semantics: `/wipe` keeps the wallet file and its passphrase (the file
|
||||||
|
survives `/wipe` today); `/wipe-all` removes the data dir, as before.
|
||||||
|
|
||||||
|
If the stored passphrase does not open the configured file — a wallet the
|
||||||
|
catalogue holds but whose passphrase changed, or one created on another install —
|
||||||
|
the app reports it against that file and does **not** overwrite the stored one.
|
||||||
|
The child is stopped rather than left answering `-13`, and the status reports
|
||||||
|
`needs passphrase`; open the file once with its real passphrase
|
||||||
|
(`open_wallet_with_passphrase`, or the TUI/Android prompt) and it is remembered.
|
||||||
|
|
||||||
|
Nothing spawns the child at boot. `Node::start_wallet_child` is the only start
|
||||||
|
path. The desktop TUI drives it from `F7` (`Ctrl-S` / `Ctrl-X`), which is also
|
||||||
|
the screen that picks the chain source:
|
||||||
|
|
||||||
|
| Key | Effect |
|
||||||
|
|---|---|
|
||||||
|
| `Ctrl-S` | Save the form, then start the child and probe it once. A child whose wallet file needs a passphrase opens the passphrase prompt instead of leaving every read at `-13`. |
|
||||||
|
| `Ctrl-X` | Stop it (idempotent). |
|
||||||
|
| `Ctrl-R` | Re-read the live node line (`off` / `connecting` / `syncing` / `ready` / `exited`). |
|
||||||
|
| `Enter` | Save the endpoint and chain source without dialling or starting anything. |
|
||||||
|
| `chain` row + `space` | Receive-only / local `monerod` / remote daemon / in-process Cuprate. In a build without `cuprate-daemon` the row carries the `rebuild with --features cuprate-daemon` wording; the pick is still offered. |
|
||||||
|
| `network` row + `space` | In-process network: mainnet (unvalidated) or testnet. |
|
||||||
|
|
||||||
|
State shown: `off` / `connecting` / `syncing` / `ready` / `exited`, plus a
|
||||||
|
chain-source label, plus `wallet locked` while a catalogue wallet is configured
|
||||||
|
but not open in the child's RPC. `ready` is never reported for a child that has
|
||||||
|
died. A live child is not a usable wallet: `wallet_status()` carries
|
||||||
|
`wallet_open` and `needs_passphrase` so a client can tell "the wallet is open"
|
||||||
|
from "the child is up and waiting for a passphrase".
|
||||||
|
|
||||||
|
Once a probe has read the daemon, the line can include `sync <height>/<target>`
|
||||||
|
— the **daemon's** height and the tip it is syncing towards (wallet RPC
|
||||||
|
`get_info`, or the local daemon's `get_info` when wallet RPC does not answer).
|
||||||
|
`sync 0/0` or no segment means **unknown**, not caught up.
|
||||||
|
|
||||||
|
`start` is idempotent: a live child is reported, not respawned. A start that
|
||||||
|
fails part way is **all or nothing**: whatever that call spawned — the in-process
|
||||||
|
daemon, a `monerod`, the SOCKS child, the wallet RPC — is stopped before the
|
||||||
|
error is handed back (`WalletChild::start_with_creds`), because the caller
|
||||||
|
receives the error rather than the client, so a daemon left running would have no
|
||||||
|
owner and no handle, and would hold `18081` against the next start. The same
|
||||||
|
contract is asserted one level up
|
||||||
|
(`node::tests::a_missing_binary_fails_the_start_and_leaves_no_child`), and what a
|
||||||
|
retry reuses is the chain **datadir** on disk, never a process that outlived its
|
||||||
|
owner.
|
||||||
|
|
||||||
|
A save on an app-owned source needs no `url`/`login`: the child the app spawns
|
||||||
|
generates its own RPC creds and picks its own port, and
|
||||||
|
`Node::start_wallet_child_with` replaces the stored client after the spawn. A
|
||||||
|
typed endpoint with no login is still refused (`Wallet::from_config`), and the
|
||||||
|
screen reports both halves of a save on one line. See `docs/TUI.md`.
|
||||||
|
|
||||||
|
## Chain source
|
||||||
|
|
||||||
|
You pick one. OnionWire does not pick a public remote node for you.
|
||||||
|
|
||||||
|
```
|
||||||
|
ChainSource::None receive-only; no child, no daemon
|
||||||
|
ChainSource::Local { monerod_bin, datadir } spawn monerod on this box (port 18081)
|
||||||
|
ChainSource::InProcessCuprate { datadir, … } daemon inside this app (port 18081)
|
||||||
|
ChainSource::Remote { host, port } a daemon address you typed
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **Local `monerod`.** Chain traffic stays on the box.
|
||||||
|
2. **In-process Cuprate.** No `monerod` binary. Wallet child still dials
|
||||||
|
`127.0.0.1:18081`. See below.
|
||||||
|
3. **A daemon address you supply** — becomes `--daemon-address` on the wallet
|
||||||
|
child. Loopback if you already run `monerod`. `.onion` if you want chain
|
||||||
|
traffic over Tor. Clearnet only if you type it — never a default. Restricted
|
||||||
|
RPC on `18089` is a common remote example, but you supply the port.
|
||||||
|
|
||||||
|
Settings live in the sealed `wallet_child` record (`ChildConfig`: `source`,
|
||||||
|
`wallet_rpc_bin`, `arti_bin`, `wallet_filename`). Core:
|
||||||
|
`Node::wallet_child_config` / `set_wallet_child_config`, then
|
||||||
|
`start_wallet_child` / `stop_wallet_child` / `wallet_child_status` /
|
||||||
|
`wallet_child_refresh`.
|
||||||
|
|
||||||
|
### The in-process chain daemon (`cuprate-daemon`)
|
||||||
|
|
||||||
|
```
|
||||||
|
cargo build --release --bin onionwire
|
||||||
|
```
|
||||||
|
|
||||||
|
That is the Linux TUI/release build. It includes the in-process daemon.
|
||||||
|
`--features cuprate-daemon` still selects it; that flag is no longer required
|
||||||
|
for the TUI. A build with `--no-default-features` does not include the daemon.
|
||||||
|
|
||||||
|
- **On in the Linux TUI default.** `cuprated` is pre-1.0, not on crates.io
|
||||||
|
(placeholder crates), git-pinned. Without the feature, a stored in-process
|
||||||
|
source can still be read back, but start fails with
|
||||||
|
`this build has no in-process chain daemon — rebuild with --features cuprate-daemon`.
|
||||||
|
- **Pre-production.** Cuprate's own user book says do not use `cuprated` for
|
||||||
|
serious purposes. RPC parity is incomplete (`docs/cuprate-launch-spike.md`).
|
||||||
|
- **Mainnet is unvalidated.** The TUI stores the in-process network on `F7`'s
|
||||||
|
`network` row (mainnet or testnet) and the store's shape on its `prune` row.
|
||||||
|
Every in-process surface still prints `testnet only — mainnet is unvalidated`
|
||||||
|
(`cuprate::TESTNET_ONLY`).
|
||||||
|
Cross-compiled is not device-proven. Pointing a mainnet wallet at it is not
|
||||||
|
something this build claims to do.
|
||||||
|
- **No Tor on the chain path.** Cuprate's `arti` feature is off (arti-client
|
||||||
|
0.44 vs this crate's 0.49). P2P is **clearnet**. OnionWire's Arti is the
|
||||||
|
messenger only.
|
||||||
|
- **Inbound P2P off**, restricted RPC listener disabled. Unrestricted RPC is
|
||||||
|
loopback 18081. `--trusted-daemon` still never passed.
|
||||||
|
- Chain lives under `$ONIONWIRE_HOME/chain/…` (split dirs so pruned mainnet
|
||||||
|
cannot mix with full). Database is **fjall**, not SQLCipher.
|
||||||
|
- Not a child process: dropping the node shuts it down. `x` / `stop_wallet_child`
|
||||||
|
asks it to stop with the wallet child.
|
||||||
|
|
||||||
|
### Chain traffic over Tor (`.onion` daemons)
|
||||||
|
|
||||||
|
A `.onion` daemon cannot be dialled directly. The wallet child is an external
|
||||||
|
C++ binary, so it reaches Tor through a SOCKS proxy the app provides:
|
||||||
|
|
||||||
|
- Bundled `arti` binary: `arti proxy -p <random free loopback port>`. A second
|
||||||
|
Tor client, not the messenger's in-process one. No C-tor.
|
||||||
|
- Listener is TCP loopback only. Any local process at your privilege can use it.
|
||||||
|
- Wallet child: `--proxy socks5://127.0.0.1:<port>` and
|
||||||
|
`--daemon-address <onion>:<port>`. The `socks5://` scheme is required (Monero
|
||||||
|
defaults to SOCKS4a for a bare `host:port`). No local DNS on the onion target.
|
||||||
|
- Own state/cache: `$ONIONWIRE_HOME/wallet/arti-socks/{state,cache}`.
|
||||||
|
- Wait up to 20s for the SOCKS listener before spawning the wallet child.
|
||||||
|
- SOCKS child stops with the wallet child.
|
||||||
|
|
||||||
|
**Tor hides the transport, not the host.** The daemon operator still sees the
|
||||||
|
wallet's addresses during sync.
|
||||||
|
|
||||||
|
### Readiness — receipt verification needs a synced wallet
|
||||||
|
|
||||||
|
`chain_ready()` compares the wallet's **own scanned height** with the **chain
|
||||||
|
tip**. Both halves must answer:
|
||||||
|
|
||||||
|
1. the wallet RPC's `get_height` reports `height > 0`. That is
|
||||||
|
`monero-wallet-rpc`'s own method; `get_info` does **not** exist there — it
|
||||||
|
answers `-32601 Method not found`, so readiness never asks for it.
|
||||||
|
2. the chain daemon reports a tip, and the wallet is at it or within **2
|
||||||
|
blocks**. The tip moves every ~2 minutes and the two numbers are two reads,
|
||||||
|
not one snapshot, so a strict equality flaps; two blocks of slack does not
|
||||||
|
hide a real lag.
|
||||||
|
|
||||||
|
The tip comes from `daemon_get_height` (`GET /get_height` — one spelling that
|
||||||
|
works on monerod and Cuprate) against `ChildConfig::daemon_probe_addr()`:
|
||||||
|
|
||||||
|
- local `monerod` / in-process Cuprate → `127.0.0.1:18081`;
|
||||||
|
- a **clearnet** remote daemon the user typed → that host. The wallet child
|
||||||
|
already dials it, so one `get_height` is the same exposure, not a new path;
|
||||||
|
- a **`.onion`** daemon → **not dialled** without the SOCKS child: a direct dial
|
||||||
|
would resolve the name on clearnet DNS and leak. Readiness stays false
|
||||||
|
(height-only); the status row reads syncing. A documented limit, not a bug;
|
||||||
|
- receive-only, or an externally run wallet RPC with no chain source → nothing
|
||||||
|
to ask, so not ready.
|
||||||
|
|
||||||
|
Unknown is **not caught up**. A daemon that does not answer, a wallet with no
|
||||||
|
file open (`-13 No wallet file`), and a missing height all read *not ready*,
|
||||||
|
never a silent pass. "No wallet open" is a state, not an error banner.
|
||||||
|
|
||||||
|
Until then, **receipt verification stays `verified=0`**. An unsynced wallet
|
||||||
|
cannot see the chain. That is an honest limit, not a UI bug.
|
||||||
|
|
||||||
|
Loopback management calls (`get_address`, `query_key`, create/import) get 5s.
|
||||||
|
Calls that wait on the chain (`get_transfers`, `transfer`) get 60s
|
||||||
|
(`CHAIN_RPC_TIMEOUT`). Readiness is not a chain wait: it is one local
|
||||||
|
`get_height` plus one bounded daemon probe.
|
||||||
|
|
||||||
|
## Env vars (migration path)
|
||||||
|
|
||||||
| Variable | Meaning |
|
| Variable | Meaning |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. |
|
| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]` for an **externally run** `monero-wallet-rpc`. Unset → no wallet; chat still works; `/pay` falls back to profile `xmr_addr`. The app-owned child does not use this. |
|
||||||
| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when you do not want the password in the URL. Ignored if the URL carries userinfo. |
|
| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when the URL has no userinfo. |
|
||||||
| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → view-only deployment: `/tip` is refused locally, before any RPC dial. `/pay` and receipt verification keep working. |
|
| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → `/tip` refused locally before any RPC dial. |
|
||||||
|
|
||||||
`README.md` carries the operator summary; this file is the long form.
|
Boot precedence: **stored config → env → disabled**. Stored config that cannot
|
||||||
|
be used (non-loopback, `.onion`, missing login) is reported and falls back to
|
||||||
|
env rather than dialling the bad endpoint.
|
||||||
|
|
||||||
|
`Store::save_wallet_config` / `Node::wallet_save_config` exist, and the `F7`
|
||||||
|
screen (`WalletSetupConfig`) writes them: the endpoint, its login, the chain
|
||||||
|
source, and (for a local node) its datadir and network. It is also the only
|
||||||
|
screen that starts and stops the child (`Ctrl-S` / `Ctrl-X`). `F6` and `F9`
|
||||||
|
show state, the env vars are the headless path. The not-configured refusal says
|
||||||
|
`wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC`
|
||||||
|
(`src/wallet.rs`), and that key is real.
|
||||||
|
|
||||||
|
A save validated by `Node::wallet_save_config` (loopback host, login required)
|
||||||
|
re-points the wallet without a restart; a rejected form writes nothing.
|
||||||
|
|
||||||
|
`/pay` and `/tip` run `wallet_readiness` before send:
|
||||||
|
|
||||||
|
1. not configured → the F7-worded message above
|
||||||
|
2. `/tip` on view-only / `ONIONWIRE_WALLET_NO_SPEND` → refused **before any dial**
|
||||||
|
3. configured but not connected → `wallet not connected — check endpoint, login, daemon`
|
||||||
|
4. otherwise ready (`/pay` is fine on view-only)
|
||||||
|
|
||||||
|
## Android / SDK
|
||||||
|
|
||||||
|
UniFFI: `set_chain_source(ChainConfig)` / `chain_source()`,
|
||||||
|
`start_wallet_child()`, `stop_wallet_child()`, `wallet_status()` (cached read:
|
||||||
|
no dial, for first paint) and `wallet_child_refresh()` (a live probe of the
|
||||||
|
same record — it dials the loopback wallet RPC and asks the configured daemon
|
||||||
|
for its tip (the wallet's `get_height` is the other half), so poll it on the
|
||||||
|
order of seconds).
|
||||||
|
Pass absolute paths for `wallet_rpc_bin` / `arti_bin` (`nativeLibraryDir`); the
|
||||||
|
core never resolves a binary the caller named explicitly.
|
||||||
|
|
||||||
|
`ChainChoice.InProcessCuprate` is the in-process variant. Empty
|
||||||
|
`monerod_datadir` resolves to `$ONIONWIRE_HOME/chain`. `start_wallet_child()`
|
||||||
|
launches the node *and* the wallet child. `wallet_status()` carries
|
||||||
|
`chain_in_process`, `node_available`, and `node_state`.
|
||||||
|
|
||||||
|
Monero ships **no Android binaries**. Any vendored blob's provenance doc must
|
||||||
|
say so. Cross-compiled is not device-proven. See `android/MONERO_BINARIES.md`.
|
||||||
|
|
||||||
|
### The wallet catalogue, and which wallet is open
|
||||||
|
|
||||||
|
`wallets()` lists every wallet this install remembers (oldest first), each row
|
||||||
|
carrying the `wallet_filename` the child opens, its label, the owning identity
|
||||||
|
pubkey as hex, and the locator. `active_wallet_filename()` returns the file the
|
||||||
|
child is **currently pointed at** (or `None` on a fresh install), so a picker can
|
||||||
|
mark the open row. `open_wallet(filename)` switches to a catalogue row: a
|
||||||
|
running child is stopped and restarted onto the new file, an idle one is only
|
||||||
|
re-pointed (the change applies at the next `start_wallet_child`), and a file the
|
||||||
|
catalogue does not hold is refused — the catalogue is the only directory this app
|
||||||
|
keeps wallets in. The restarted child then opens that file with the stored
|
||||||
|
passphrase; when this install has none for it, the call still succeeds and the
|
||||||
|
status says `needs_passphrase` — that is what the prompt is for, and
|
||||||
|
`open_wallet_with_passphrase(filename, passphrase)` is the API behind it. It
|
||||||
|
stores the passphrase only after a live daemon has opened the file with it.
|
||||||
|
|
||||||
|
## Secrets belong to the open wallet
|
||||||
|
|
||||||
|
The seed (`wallet_seed()`, `query_key mnemonic`) and the private keys
|
||||||
|
(`wallet_keys()` → `query_key view_key` / `query_key spend_key`) are answered by
|
||||||
|
the wallet file the child has **open**, so they always belong to the row
|
||||||
|
`active_wallet_filename()` names. There is deliberately no accessor that reads
|
||||||
|
another saved wallet's seed or keys without opening it: show a backups screen,
|
||||||
|
then `open_wallet(...)` the row — the UI must say *which* wallet it is showing.
|
||||||
|
`WalletKeys.spend_key` is `None` for a view-only wallet (the RPC's `-29`), which
|
||||||
|
is an answer, not an error.
|
||||||
|
|
||||||
|
Both values are spend secrets. They are displayable on demand in the TUI and in
|
||||||
|
the Android app, are never logged, never written to the store or to disk, and
|
||||||
|
never put into an error string (the core's `WalletKeys` `Debug` redacts them).
|
||||||
|
The exposure this creates is enumerated in
|
||||||
|
[THREAT_MODEL.md](THREAT_MODEL.md), "The recovery phrase and the private keys
|
||||||
|
are displayable on demand".
|
||||||
|
|
||||||
## Create vs import
|
## Create vs import
|
||||||
|
|
||||||
Create does **not** take a private key. `/wallet create` (TUI: F6 then `c`) asks
|
`/wallet create` (`F6` then `c`) → `create_wallet`, then seed **once**
|
||||||
the RPC to generate a new spend-capable wallet (`create_wallet`), then shows the
|
(`query_key mnemonic`). Type `SPEND`, set a passphrase, write the seed, type
|
||||||
seed **once** for backup (`query_key mnemonic`). Type `SPEND` to accept the
|
`SEEN`. The passphrase you set is sealed in the store (above), so the wallet
|
||||||
spend-authority warning, set a passphrase, write the seed down, type `SEEN`.
|
reopens on the next start without asking for it again.
|
||||||
|
|
||||||
Import is the only path that takes an existing secret: `/wallet import` (F6 then
|
`/wallet import` (`F6` then `i`) → `restore_deterministic_wallet` from a
|
||||||
`i`) pastes the 25-word seed into `restore_deterministic_wallet`. Do not put the
|
25-word seed. Do not put the seed on the composer. The import also takes an
|
||||||
seed on the composer line — it would sit in chat history.
|
optional **seed-offset passphrase** — a second spend secret mixed into the words
|
||||||
|
at restore time, not the wallet-file passphrase. It is never sealed, never
|
||||||
|
stored, never logged and never on an argv: blank `Enter` skips it, and a wrong
|
||||||
|
offset is *not* an error — the RPC succeeds and opens a different wallet. After
|
||||||
|
an import that used one, `query_key mnemonic` is the mnemonic of the keys the
|
||||||
|
wallet actually holds (the derived seed), so a later seed backup restores this
|
||||||
|
wallet **without** the offset; the original words plus the offset are the other
|
||||||
|
backup, and the app keeps neither.
|
||||||
|
|
||||||
The RPC must be started with `--wallet-dir` (not only `--wallet-file`) or create
|
RPC must be started with `--wallet-dir` (not only `--wallet-file`). A created
|
||||||
and import fail. The in-app filename is `onionwire`.
|
wallet gets its own file name (`onionwire-1`, `onionwire-2`, …): `wallet_filename`
|
||||||
|
is UNIQUE in the catalogue, so a second create must not reuse the first file.
|
||||||
|
|
||||||
## Recommended topology
|
## Recommended topology (view-only)
|
||||||
|
|
||||||
```
|
```
|
||||||
wallet host (this machine)
|
wallet host (this machine)
|
||||||
|
|
@ -57,55 +363,19 @@ and import fail. The in-app filename is `onionwire`.
|
||||||
└──────────────────────────────────────────────────────────────┘
|
└──────────────────────────────────────────────────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
Loopback is the only address OnionWire will dial for **wallet RPC**. `.onion`
|
Loopback is the only address OnionWire will dial for **wallet RPC**.
|
||||||
wallet-RPC URLs are rejected: there is no Arti dial for the wallet process, and
|
|
||||||
a remote wallet RPC would move spend authority off the box.
|
|
||||||
|
|
||||||
## Chain source
|
|
||||||
|
|
||||||
The wallet needs a daemon for scan, verify, and spend. You pick one; OnionWire
|
|
||||||
does not pick a public remote node for you.
|
|
||||||
|
|
||||||
1. **Spawn a local `monerod`** (pruned on-device). Chain traffic stays on the
|
|
||||||
box. You accept disk, first sync, and (on Android) the daemon not always
|
|
||||||
running.
|
|
||||||
2. **A daemon address you supply** — `--daemon-address` on the wallet child.
|
|
||||||
Loopback if you already run `monerod`. `.onion` if you want chain traffic
|
|
||||||
over Tor (wallet child `--proxy` to a localhost SOCKS listener; the daemon
|
|
||||||
operator still sees addresses). Clearnet only if you type it — ISP sees
|
|
||||||
Monero-node traffic; not a default.
|
|
||||||
|
|
||||||
Remote daemons are untrusted (`--trusted-daemon` off). Unsynced or unreachable
|
|
||||||
→ receipts stay unverified and spend is refused. That is the honest state.
|
|
||||||
|
|
||||||
## Create a view-only wallet
|
## Create a view-only wallet
|
||||||
|
|
||||||
Either path produces a wallet file with the view key only. Keep the seed /
|
Keep the seed / spend key on a machine that is **not** running OnionWire.
|
||||||
spend key on a machine that is **not** running OnionWire.
|
|
||||||
|
|
||||||
With `monero-wallet-cli` (`--generate-from-view-key` prompts for the *standard*
|
|
||||||
address the view key belongs to, then the secret view key):
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
monero-wallet-cli --generate-from-view-key "$HOME/.onionwire-viewonly" \
|
monero-wallet-cli --generate-from-view-key "$HOME/.onionwire-viewonly" \
|
||||||
--daemon-address "$YOUR_MONEROD:18089" --restore-height "$BIRTH_HEIGHT"
|
--daemon-address "$YOUR_MONEROD:18089" --restore-height "$BIRTH_HEIGHT"
|
||||||
# Standard address: 4...
|
|
||||||
# Secret view key: <hex>
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Or through a running RPC that was started with `--wallet-dir` (`generate_from_keys`
|
`18089` here is the **remote** daemon's restricted RPC, an address you type —
|
||||||
without `spendkey` writes a watch-only wallet):
|
not the app-owned 18081.
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -u onionwire:secret http://127.0.0.1:18083/json_rpc \
|
|
||||||
-H 'Content-Type: application/json' \
|
|
||||||
-d '{"jsonrpc":"2.0","id":"0","method":"generate_from_keys","params":{
|
|
||||||
"filename":"viewonly","password":"walletpass",
|
|
||||||
"address":"4...","viewkey":"<hex>","restore_height":<height>}}'
|
|
||||||
# → "Watch-only wallet has been generated successfully."
|
|
||||||
```
|
|
||||||
|
|
||||||
Then serve it:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
monero-wallet-rpc --wallet-file "$HOME/.onionwire-viewonly" \
|
monero-wallet-rpc --wallet-file "$HOME/.onionwire-viewonly" \
|
||||||
|
|
@ -117,78 +387,46 @@ export ONIONWIRE_WALLET_RPC_LOGIN=onionwire:secret
|
||||||
export ONIONWIRE_WALLET_NO_SPEND=1
|
export ONIONWIRE_WALLET_NO_SPEND=1
|
||||||
```
|
```
|
||||||
|
|
||||||
Restore the wallet from a height *at or before* its first incoming transaction
|
Restore from a height at or before the first incoming transaction.
|
||||||
— a view-only wallet cannot rescan cheaply from height 0.
|
|
||||||
|
|
||||||
## What works, what does not
|
## What works, what does not
|
||||||
|
|
||||||
| Feature | View-only | Spend-capable |
|
| Feature | View-only | Spend-capable |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `/pay <xmr>` invoice subaddress (`create_address`) | works | works |
|
| `/pay <xmr>` invoice subaddress (`create_address`) | works | works |
|
||||||
| Receipt verification (`get_transfers`) | works | works |
|
| Receipt verification (`get_transfers`) | works, if daemon is synced | works, if daemon is synced |
|
||||||
| Profile `xmr_addr` fallback when RPC is down | works | works |
|
| Profile `xmr_addr` fallback when RPC is down | works | works |
|
||||||
| `/tip <xmr>` (`transfer`) | **cannot work** | works |
|
| `/tip <xmr>` (`transfer`) | **cannot work** | works |
|
||||||
| OnionWire copies your spend key into its own process | never | never (it stays in the wallet file / RPC) |
|
| OnionWire copies your spend key into its own process | never | never (it stays in the wallet file / RPC) |
|
||||||
|
| Show the backup (seed via `query_key mnemonic`) | **no seed to show** (the RPC answers `-29`) | works |
|
||||||
|
| Show the private keys (`wallet_keys`) | view key only, `spend_key` is `None` | view + spend key |
|
||||||
|
|
||||||
With `ONIONWIRE_WALLET_NO_SPEND=1` a `/tip` is refused before the RPC is
|
`ONIONWIRE_WALLET_NO_SPEND=1` refuses `/tip` before RPC with:
|
||||||
contacted, with:
|
|
||||||
|
|
||||||
```
|
```
|
||||||
wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work
|
wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work
|
||||||
```
|
```
|
||||||
|
|
||||||
Without the flag, `/tip` against a view-only wallet fails at the wallet and
|
View-only detection after a failed `transfer`: `query_key` `spend_key` → `-29`
|
||||||
OnionWire then asks the wallet directly whether it can spend (see below), so you
|
watch-only. The spend key is discarded immediately. OnionWire never probes a
|
||||||
get the same sentence instead of a raw RPC error.
|
healthy wallet for this.
|
||||||
|
|
||||||
## How OnionWire detects view-only over RPC
|
|
||||||
|
|
||||||
The signal people usually reach for is `query_key` with `key_type=mnemonic`. It
|
|
||||||
works, but it is the wrong key to ask for: on a spend-capable wallet it hands
|
|
||||||
over the whole seed (full spend ability) over loopback HTTP, and it answers
|
|
||||||
`-43` for wallets that have no mnemonic at all. The spend key is narrower and
|
|
||||||
just as unambiguous:
|
|
||||||
|
|
||||||
```
|
|
||||||
query_key {"key_type":"spend_key"}
|
|
||||||
spend-capable → result.key = <hex secret spend key>
|
|
||||||
view-only → error code -29, "The wallet is watch-only. Cannot retrieve spend key."
|
|
||||||
```
|
|
||||||
|
|
||||||
(`query_key key_type=mnemonic` returns `-29` for a view-only wallet too, so the
|
|
||||||
two agree — OnionWire asks for the spend key because it is the smaller secret.)
|
|
||||||
|
|
||||||
- Method: [`query_key`](https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#query_key)
|
|
||||||
- `-29` is `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in
|
|
||||||
[`wallet_rpc_server_error_codes.h`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h)
|
|
||||||
- The view-only branch is `on_query_key` in
|
|
||||||
[`wallet_rpc_server.cpp`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp)
|
|
||||||
|
|
||||||
OnionWire only calls this **after** a `transfer` has already failed — it never
|
|
||||||
probes a healthy wallet — and it discards `result.key` immediately. There is no
|
|
||||||
RPC method that reports "view-only" as a plain field; `query_key` is the
|
|
||||||
documented signal and this is its only cost: a spend-capable wallet answers with
|
|
||||||
its spend key over loopback HTTP, which is one more reason to run view-only.
|
|
||||||
|
|
||||||
Fail-closed details: if the probe cannot answer (wallet down, `--restricted-rpc`
|
|
||||||
answers `-7 DENIED` instead), OnionWire surfaces the wallet's own error
|
|
||||||
unchanged. It never guesses "view-only" from an unrelated failure.
|
|
||||||
|
|
||||||
## Why loopback still needs authentication
|
## Why loopback still needs authentication
|
||||||
|
|
||||||
`--rpc-bind-ip 127.0.0.1` keeps the port off the network; it does **not** keep it
|
`--rpc-bind-ip 127.0.0.1` keeps the port off the network; it does **not** keep
|
||||||
away from other users or processes on the same machine. Any local process can
|
it away from other processes on the same machine.
|
||||||
`connect(127.0.0.1:18083)`.
|
|
||||||
|
|
||||||
- OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and
|
OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and
|
||||||
refuses URLs without credentials. Unset the credentials and the wallet is open
|
refuses URLs without credentials. Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over
|
||||||
to every local process — with a spend-capable wallet file, that is a
|
userinfo in the URL. Do not log the password.
|
||||||
one-curl drain of your balance.
|
|
||||||
- `--rpc-login` is HTTP Digest (MD5), so the password is not sent in cleartext,
|
`monero-wallet-rpc` mints its Digest nonce **per TCP connection** (epee's
|
||||||
but Digest gives no confidentiality: a local attacker who can sniff loopback
|
`http_custom_handler` owns the auth state), so the challenge and the
|
||||||
can replay it. Treat loopback as trusted-ish, not safe.
|
authenticated retry have to ride the same socket — a retry on a fresh connection
|
||||||
- Do not log the password, and do not put it in a shell history you share.
|
is refused with 401 no matter how correct the login is. OnionWire does exactly
|
||||||
Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over userinfo in the URL.
|
that. A `wallet RPC HTTP HTTP/1.1 401 Unauthorized` status therefore means one
|
||||||
|
thing: the login does not match the child's `--rpc-login`. Regenerate the child
|
||||||
|
(and its sealed creds) rather than retrying.
|
||||||
|
|
||||||
## The spend-authority warning
|
## The spend-authority warning
|
||||||
|
|
||||||
|
|
@ -198,27 +436,17 @@ local spend authority: any process that can read the RPC credentials (env var,
|
||||||
balance, and `/tip` gives a chat peer a supported path to ask for a transfer.
|
balance, and `/tip` gives a chat peer a supported path to ask for a transfer.
|
||||||
|
|
||||||
That is why view-only plus `ONIONWIRE_WALLET_NO_SPEND=1` is the recommended
|
That is why view-only plus `ONIONWIRE_WALLET_NO_SPEND=1` is the recommended
|
||||||
default:
|
default. If you want tips, use a **separate hot wallet with a small balance**,
|
||||||
|
not your savings wallet.
|
||||||
|
|
||||||
- the wallet file holds no spend key, so a stolen wallet file cannot be used to
|
## Payments are one-shot
|
||||||
move funds;
|
|
||||||
- the RPC credentials grant only receive-address and history reads;
|
|
||||||
- `/tip` fails locally with a plain message, so nothing in the UI pretends the
|
|
||||||
spend path exists.
|
|
||||||
|
|
||||||
If you want tips to work, understand that you are deliberately making the
|
`/pay` and `/tip` fail when the peer onion is down. There is no queued invoice.
|
||||||
OnionWire process able to spend. Give it a **separate hot wallet with a small
|
File transfer is the same rule.
|
||||||
balance**, not your savings wallet.
|
|
||||||
|
|
||||||
## References
|
## References
|
||||||
|
|
||||||
- Monero Wallet RPC reference:
|
- Monero Wallet RPC: <https://www.getmonero.org/resources/developer-guides/wallet-rpc.html>
|
||||||
<https://www.getmonero.org/resources/developer-guides/wallet-rpc.html>
|
- `WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29` in the Monero tree
|
||||||
- `on_query_key` (view-only → `-29`):
|
- Spike history (not operator docs): [cuprate-launch-spike.md](cuprate-launch-spike.md),
|
||||||
<https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp>
|
[arti-socks-feasibility.md](arti-socks-feasibility.md)
|
||||||
- `WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29`:
|
|
||||||
<https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h>
|
|
||||||
- `--generate-from-view-key` (incoming-only wallet):
|
|
||||||
<https://github.com/monero-project/monero/blob/master/src/simplewallet/simplewallet.cpp>
|
|
||||||
- `generate_from_keys` (watch-only when `spendkey` is omitted):
|
|
||||||
<https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#generate_from_keys>
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,9 @@
|
||||||
# Arti SOCKS Feasibility Report
|
# Arti SOCKS Feasibility Report
|
||||||
|
|
||||||
|
**Status:** shipped as Option A (bundled `arti` binary as SOCKS child for
|
||||||
|
`.onion` daemons). Living doc: [WALLET.md](WALLET.md). Verdict below is the
|
||||||
|
historical finding; do not rewrite it.
|
||||||
|
|
||||||
**Date:** 2026-09-13
|
**Date:** 2026-09-13
|
||||||
**Scope:** Can OnionWire's in-process `arti-client` 0.46.0 expose a SOCKS5 listener for an external process (monero-wallet-rpc child) to route its daemon traffic through Tor?
|
**Scope:** Can OnionWire's in-process `arti-client` 0.46.0 expose a SOCKS5 listener for an external process (monero-wallet-rpc child) to route its daemon traffic through Tor?
|
||||||
**Verdict:** **Not directly.** The `arti-client` library does not expose a configurable SOCKS proxy listener. See options below.
|
**Verdict:** **Not directly.** The `arti-client` library does not expose a configurable SOCKS proxy listener. See options below.
|
||||||
|
|
|
||||||
194
docs/cuprate-android-spike.md
Normal file
194
docs/cuprate-android-spike.md
Normal file
|
|
@ -0,0 +1,194 @@
|
||||||
|
# Cuprate on Android aarch64 — cross-compile spike
|
||||||
|
|
||||||
|
**Status:** shipped as history. In-process Cuprate is an opt-in `cuprate-daemon`
|
||||||
|
feature; mainnet remains unvalidated. Living doc: [WALLET.md](WALLET.md). Do not
|
||||||
|
read this spike as current operator procedure.
|
||||||
|
|
||||||
|
**Question (kanban `t_8293d96d`):** do the native dependencies of the in-process
|
||||||
|
Cuprate daemon (`randomx-rs`, `fjall`, sqlite, the C++ RandomX build) cross-compile
|
||||||
|
for the Android NDK target `aarch64-linux-android`? If they do not, §7a's Phase 1
|
||||||
|
("Cuprate in-process instead of a `monerod` subprocess" on Android) keeps only its
|
||||||
|
desktop half and the mobile SDK story loses the point of it.
|
||||||
|
|
||||||
|
**Verdict: yes.** `cargo check --release --target aarch64-linux-android` exits 0 on
|
||||||
|
the Cuprate PoC tree, and a *full link* of the resulting Android binary also
|
||||||
|
succeeds (`ld.lld` verdict: ELF 64-bit ARM aarch64 PIE, Android 26, NDK r28c).
|
||||||
|
The cross-compile needs a specific environment and four extra link arguments; both
|
||||||
|
are spelled out below. All of it is build plumbing — no Cuprate or RandomX source
|
||||||
|
change was needed, and no host-arch object leaked into the artifacts.
|
||||||
|
|
||||||
|
## Environment used
|
||||||
|
|
||||||
|
- Host: Arch x86_64, cargo/rustc 1.98.1, 16 cores.
|
||||||
|
- `aarch64-linux-android` std installed via rustup (`~/.cargo/bin` **must** win the
|
||||||
|
`PATH` lookup — see gotcha 1).
|
||||||
|
- NDK r28c at `/home/lancelot/Android/Sdk/ndk/28.2.13676358` (matches
|
||||||
|
`ndkVersion` in `android/sdk/build.gradle.kts`).
|
||||||
|
- API level **26** (matches `minSdk = 26` in `android/app/build.gradle.kts`).
|
||||||
|
- Spike tree: the `cuprate-poc` manifest (`cuprated` git dep at `4f8fcd1b`,
|
||||||
|
`randomx-rs` git dep at `76c2385`, `arti-client` 0.46 + `tor-hsservice`), copied
|
||||||
|
to `/var/tmp/cuprate-android-poc` so it does not race the testnet card editing the
|
||||||
|
shared `/home/lancelot/.hermes/tmp/cuprate-poc`.
|
||||||
|
|
||||||
|
## Recipe
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export PATH="$HOME/.cargo/bin:/usr/bin:/bin" # rustup cargo/rustc, not the system ones
|
||||||
|
export ANDROID_NDK=/home/lancelot/Android/Sdk/ndk/28.2.13676358
|
||||||
|
export ANDROID_NDK_ROOT="$ANDROID_NDK" ANDROID_NDK_HOME="$ANDROID_NDK"
|
||||||
|
eval "$(cargo ndk-env -t arm64-v8a -P 26)" # CC_/CXX_/AR_/CLANG_PATH for cc-rs + bindgen
|
||||||
|
export CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER=\
|
||||||
|
"$ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android26-clang"
|
||||||
|
export CARGO_TARGET_DIR=/var/tmp/<task>-target TMPDIR=/var/tmp/<task>-tmp
|
||||||
|
|
||||||
|
cargo check --release --target aarch64-linux-android # exit 0
|
||||||
|
```
|
||||||
|
|
||||||
|
Linking a real binary (what Gradle will do) needs the C++ runtime and the compiler-rt
|
||||||
|
builtins on the link line, because RandomX is C++ and its aarch64 JIT calls
|
||||||
|
`__clear_cache`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo rustc --release --target aarch64-linux-android -- \
|
||||||
|
-C link-arg=-L$ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/aarch64-linux-android \
|
||||||
|
-C link-arg=-L$ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/lib/clang/19/lib/linux \
|
||||||
|
-C link-arg=-lclang_rt.builtins-aarch64-android \
|
||||||
|
-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
|
||||||
|
```
|
||||||
|
|
||||||
|
## Evidence
|
||||||
|
|
||||||
|
`cargo check --release --target aarch64-linux-android` (cold target dir, same tree):
|
||||||
|
|
||||||
|
```
|
||||||
|
Compiling ... 152 crates ...
|
||||||
|
Finished `release` profile [optimized] target(s) in 43.66s
|
||||||
|
### EXIT=0
|
||||||
|
```
|
||||||
|
|
||||||
|
Full build + link, same env:
|
||||||
|
|
||||||
|
```
|
||||||
|
Finished `release` profile [optimized] target(s) in 1m 56s
|
||||||
|
### EXIT=0
|
||||||
|
$ file /var/tmp/cuprate-android-target/aarch64-linux-android/release/cuprate-poc
|
||||||
|
ELF 64-bit LSB pie executable, ARM aarch64, version 1 (SYSV), dynamically linked,
|
||||||
|
interpreter /system/bin/linker64, for Android 26, built by NDK r28c (13676358), not stripped
|
||||||
|
```
|
||||||
|
|
||||||
|
RandomX specifically — the C++ half that could not be hand-waved:
|
||||||
|
|
||||||
|
- `out/lib/librandomx.a` exists; member `aes_hash.cpp.o` is `ELF64 / AArch64`
|
||||||
|
(`readelf -h`) — real cross-built objects, not a host archive.
|
||||||
|
- `CMakeFiles/randomx.dir/src/` contains `jit_compiler_a64.cpp.o` **and**
|
||||||
|
`jit_compiler_a64_static.S.o`, i.e. the ARM64 JIT path was selected
|
||||||
|
(`CMakeCache.txt`: `CMAKE_SYSTEM_PROCESSOR=aarch64`, `-DHAVE_HWCAP`).
|
||||||
|
- Flags actually used: `-march=armv8-a+crypto` (from RandomX's ARMv8 branch). The
|
||||||
|
`DARCH=native` that `randomx-rs`'s `build.rs` passes is a **no-op** — RandomX's
|
||||||
|
`CMakeLists.txt` never reads `DARCH`, so `ARCH` stays `default`. That is lucky and
|
||||||
|
worth knowing: had `-march=native` applied, the ARM64 branch would have targeted
|
||||||
|
the *host* CPU while cross-compiling.
|
||||||
|
|
||||||
|
Cost on the desktop: cold `cargo check` for this graph ≈ 44 s / 694 MB of target dir;
|
||||||
|
`cargo build --release` through to a linked binary ≈ 2 min with the dependency graph
|
||||||
|
mostly warm / 1.7 GB (the RandomX C++ build is 26 top-level sources plus the aarch64 JIT).
|
||||||
|
The release demo binary is 51 MB unstripped.
|
||||||
|
|
||||||
|
## Gotchas (each one cost a run)
|
||||||
|
|
||||||
|
1. **`PATH` order decides which toolchain answers.** With `/usr/bin` ahead of
|
||||||
|
`~/.cargo/bin` the system rustc answers and the build dies with
|
||||||
|
`error[E0463]: can't find crate for 'std' … the aarch64-linux-android target may
|
||||||
|
not be installed`, even though rustup has it.
|
||||||
|
2. **Plain `cargo check --target aarch64-linux-android` is not enough**: cc-rs cannot
|
||||||
|
find `aarch64-linux-android-clang` and `libsqlite3-sys` (bundled sqlite) fails
|
||||||
|
first. `cargo ndk-env` is what supplies `CC_/CXX_/AR_` for the target; the
|
||||||
|
per-target `linker` in `~/.cargo/config.toml` covers only the Rust link step, not
|
||||||
|
the C toolchain (same trap the global `[build] target` used to cause).
|
||||||
|
3. **CMake needs the NDK env var too.** `cmake-rs` does pass
|
||||||
|
`-DCMAKE_SYSTEM_NAME=Android -DCMAKE_SYSTEM_PROCESSOR=aarch64`, but CMake's
|
||||||
|
`Android-Determine.cmake` still aborts with *"Android: Neither the NDK or a
|
||||||
|
standalone toolchain was found"* unless `ANDROID_NDK` (or `ANDROID_NDK_ROOT`) is
|
||||||
|
exported. `randomx-rs`'s build script then panics inside `cmake-0.1.58`.
|
||||||
|
4. **`cargo-ndk-env`'s linker wrapper is broken on this toolchain**:
|
||||||
|
`CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER` points at `cargo-ndk` itself, and rustc
|
||||||
|
calls linkers with `-Wl,…`, which that binary re-parses as a *cargo* invocation
|
||||||
|
(`error: unexpected argument '-W' found`, then it prints a
|
||||||
|
`rustup target install armv7-linux-androideabi` hint that has nothing to do with
|
||||||
|
the failure). Point the linker at the NDK clang driver instead, as above. The
|
||||||
|
broken run also leaves a stale **directory** named `librandomx_rs-<hash>.so` in
|
||||||
|
`<target>/release/deps/`, and the next cargo run then dies with *"the generated
|
||||||
|
executable … conflicts with the existing directory"* — `rmdir` it.
|
||||||
|
5. **The C++ runtime is not linked for you.** `randomx-rs`'s `build.rs` emits
|
||||||
|
`rustc-link-lib=static=stdc++`, and the NDK's `libstdc++.a` is a stub, so the final
|
||||||
|
link fails with `__cxa_allocate_exception` / `std::runtime_error` / `typeinfo`
|
||||||
|
undefined. `-static-libstdc++` does **not** fix it — NDK clang reports
|
||||||
|
*"argument unused during compilation"* and ignores it. Link `-lc++_static
|
||||||
|
-lc++abi` explicitly. Separately, `__clear_cache` (RandomX aarch64 JIT) is only in
|
||||||
|
`libclang_rt.builtins-aarch64-android.a`, so that library path and `-l` are needed
|
||||||
|
too (this is what `cargo ndk --link-builtins` exists for).
|
||||||
|
6. **API level matters.** With the NDK default (`-P 21`) the link fails on
|
||||||
|
`pthread_atfork`, referenced by `rand`'s fork handler; `pthread_atfork` is API 23+.
|
||||||
|
Use `-P 26` to match the app's `minSdk`. OnionWire's own
|
||||||
|
`~/.cargo/config.toml` already hints at 26 (`-Wl,-L…/sysroot/usr/lib/aarch64-linux-android/26`).
|
||||||
|
|
||||||
|
## What this means for the payment plan
|
||||||
|
|
||||||
|
- §7a Phase 1 survives the Android lens: the Cuprate-in-process daemon
|
||||||
|
(`cuprated` + RandomX + fjall) compiles **and links** for `aarch64-linux-android`.
|
||||||
|
What remains for Android is packaging plumbing in the Gradle/`cargo ndk` build —
|
||||||
|
the C++ runtime and builtins flags above have to be wired into
|
||||||
|
`android/sdk/build.gradle.kts`'s `cargoBuildAndroid` (or expressed as
|
||||||
|
`CARGO_TARGET_AARCH64_LINUX_ANDROID_RUSTFLAGS`), not a Cuprate feature gap.
|
||||||
|
- `RANDOMX_DIR` / `DARCH` in `randomx-rs`'s build script are not a cross-compile
|
||||||
|
hazard today only because `DARCH` is inert. If the fork ever honours it, a
|
||||||
|
`-march=native` Android build would be a silent host-arch miscompile.
|
||||||
|
- Dependency cost is worth restating for the Android AAR: the `cuprated` graph adds
|
||||||
|
`axum`/`hyper`/`fjall`/RandomX on top of this crate's own. That is build time and
|
||||||
|
binary size, not a correctness problem, but it is real on a phone.
|
||||||
|
The **two `arti` families** the spike tree built were an artifact of the PoC
|
||||||
|
manifest enabling `cuprated`'s default `arti` feature: OnionWire pins
|
||||||
|
`default-features = false` for `cuprated`, so its arti-client 0.44 is **not** in
|
||||||
|
this crate's graph — one Tor stack per process (see `docs/WALLET.md`).
|
||||||
|
- Throwaway harness (not committed, per spike policy):
|
||||||
|
`/var/tmp/cuprate-android-poc/{check-acceptance.sh,check-cold.sh,build-android.sh,link-android.sh}`
|
||||||
|
and the logs next to them (`/var/tmp/cuprate-android-{checkcold,accept,ndk2,link6}.log`).
|
||||||
|
|
||||||
|
## Proven in-repo (2026-09-18, card `t_04975420`)
|
||||||
|
|
||||||
|
The spike above ran on a throwaway PoC tree. The same two commands were re-run in
|
||||||
|
this repository, against `cuprated` at the same pinned revision
|
||||||
|
(`4f8fcd1bf468f566fcd89c460d50de4adb6825bf`) and behind this crate's
|
||||||
|
`cuprate-daemon` feature, with the environment from *Recipe* above:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ cargo check --locked --release --target aarch64-linux-android --features cuprate-daemon
|
||||||
|
Finished `release` profile [optimized] target(s) in 1m 50s
|
||||||
|
CHECK_EXIT=0
|
||||||
|
|
||||||
|
$ cargo rustc --locked --release --target aarch64-linux-android \
|
||||||
|
--features cuprate-daemon --bin onionwire -- <the link args above>
|
||||||
|
Finished `release` profile [optimized] target(s) in 2m 05s
|
||||||
|
LINK_EXIT=0
|
||||||
|
$ file <target>/aarch64-linux-android/release/onionwire
|
||||||
|
ELF 64-bit LSB pie executable, ARM aarch64, version 1 (SYSV), dynamically linked,
|
||||||
|
interpreter /system/bin/linker64, for Android 26, built by NDK r28c (13676358),
|
||||||
|
not stripped
|
||||||
|
```
|
||||||
|
|
||||||
|
`cargo rustc` needs `--bin onionwire` (or `--lib`) because this crate has both
|
||||||
|
targets and rustc link args may only go to one of them — the PoC had a single bin,
|
||||||
|
so this is new to the real tree.
|
||||||
|
|
||||||
|
Sizes, same target and link args, `llvm-strip`ed:
|
||||||
|
|
||||||
|
| build | stripped |
|
||||||
|
|---|---|
|
||||||
|
| without the feature | 24,725,704 bytes |
|
||||||
|
| `--features cuprate-daemon` | 37,053,472 bytes |
|
||||||
|
|
||||||
|
That is a delta of **12,327,768 bytes (≈ +11.8 MiB)**, the number
|
||||||
|
`docs/WALLET.md` quotes.
|
||||||
156
docs/cuprate-launch-spike.md
Normal file
156
docs/cuprate-launch-spike.md
Normal file
|
|
@ -0,0 +1,156 @@
|
||||||
|
# Cuprate in-process launch spike (Phase 1, Spike A)
|
||||||
|
|
||||||
|
**Status:** shipped as history. Production app-owned daemon RPC is **18081**,
|
||||||
|
not the spike's 18089 unrestricted example. Living doc: [WALLET.md](WALLET.md).
|
||||||
|
|
||||||
|
**Question:** does `cuprated::Node::launch(config).await` start a real Monero chain daemon
|
||||||
|
*inside the OnionWire process* on testnet, and does the resulting JSON-RPC endpoint at
|
||||||
|
`127.0.0.1:18089` answer `get_info`, `get_height` and `get_block` the way `monerod` does —
|
||||||
|
i.e. is the §7a Phase 1 shape (Cuprate in-process for chain, `monero-wallet-rpc` as a
|
||||||
|
subprocess pointing at it) worth building?
|
||||||
|
|
||||||
|
**Verdict: VALIDATED, with four `get_info`/error-path parity gaps to fix or work around.**
|
||||||
|
|
||||||
|
Status: exploration only. Nothing in `src/` changes here, and no `cuprated` dependency is
|
||||||
|
added to the repo by this spike. Compile-level feasibility was already proven by the
|
||||||
|
preceding card; this card proves **runtime** feasibility (launch, RPC, P2P, sync, shutdown).
|
||||||
|
|
||||||
|
## Method
|
||||||
|
|
||||||
|
Throwaway spike crate (not in this repo): `/home/lancelot/.hermes/tmp/cuprate-poc/`
|
||||||
|
(`src/main.rs`, `run-1.log`, `run-2.log`, `rpc-evidence/`).
|
||||||
|
|
||||||
|
* `cuprated` git dep at the rev already in the POC lock file:
|
||||||
|
`4f8fcd1bf468f566fcd89c460d50de4adb6825bf` (`cuprated` 0.1.0-preview, features `["arti"]`),
|
||||||
|
alongside `arti-client` 0.46. Both `arti-client` 0.44.0 (pulled by Cuprate) and 0.46.0
|
||||||
|
(OnionWire's pin) resolve side by side in the one lock file (693 packages), and
|
||||||
|
`tor-hsservice` likewise carries 0.44.0 and 0.46.0.
|
||||||
|
* The node is launched **in-process**: `Node::launch(config).await` inside a `#[tokio::main]`.
|
||||||
|
No `cuprated` binary, no `monerod`, no subprocess of any kind for the chain.
|
||||||
|
* Config: `network = "Testnet"`, `target_max_memory = 2 GB`, `fast_sync = true`,
|
||||||
|
`p2p.tor_net.enabled = false` (so no Arti bootstrap in this spike),
|
||||||
|
`p2p.clear_net.enable_inbound = false`, unrestricted RPC on `127.0.0.1:18089`,
|
||||||
|
restricted RPC on `127.0.0.1:28089`, data dir under the spike tree.
|
||||||
|
* RPC probes are raw HTTP/1.1 over `tokio::net::TcpStream` (no HTTP client dependency),
|
||||||
|
with `cuprated::logging::init_logging` enabled so cuprated's own tracing lands in the log.
|
||||||
|
* CUPRATE's own `get_info` reports the network as `"nettype":"testnet"`, `"testnet":true`.
|
||||||
|
|
||||||
|
## Results
|
||||||
|
|
||||||
|
### Launch and listener
|
||||||
|
|
||||||
|
```
|
||||||
|
==== LAUNCH OK in 953.837093ms (resume, data dir with 1160 blocks)
|
||||||
|
==== LAUNCH OK in 2.842708694s (cold, empty data dir)
|
||||||
|
==== network=Testnet in-process chain_height=1
|
||||||
|
==== RPC socket 127.0.0.1:18089 accepting connections
|
||||||
|
```
|
||||||
|
|
||||||
|
Both RPC ports (`18089` unrestricted, `28089` restricted) were bound and accepting TCP within
|
||||||
|
0.2 s of `Node::launch` returning. Dropping the `Node` handle shuts the node down and the
|
||||||
|
process exits cleanly (no hung tokio tasks, no orphan process).
|
||||||
|
|
||||||
|
### The three endpoints the card asked for
|
||||||
|
|
||||||
|
| Probe | Status | Payload |
|
||||||
|
|---|---|---|
|
||||||
|
| `POST /json_rpc {"method":"get_info"}` | 200 | full daemon-info JSON, `"status":"OK"`, `nettype: testnet`, `height`, `target_height`, `synchronized`, `top_block_hash`, `difficulty`, `cumulative_difficulty`, `block_size_limit`, `version: "0.1.0-preview-release"` |
|
||||||
|
| `GET /get_info` | 200 | same object (both the JSON-RPC route and the URI route are served, as monerod does) |
|
||||||
|
| `GET /get_height` | 200 | `{"status":"OK","hash":"7458280c…","height":23758}` |
|
||||||
|
| `POST /json_rpc {"method":"get_block_count"}` | 200 | `{"count":23758}` |
|
||||||
|
| `POST /json_rpc {"method":"get_block","params":{"height":H}}` | 200 | `blob` (hex block), `block_header` (monerod-shaped: `height`, `hash`, `prev_hash`, `reward`, `timestamp`, `num_txes`, `difficulty`, `cumulative_difficulty`, `long_term_weight`, `major_version`, `minor_version`, …), `miner_tx_hash`, `tx_hashes`, `json` |
|
||||||
|
|
||||||
|
`get_block` succeeded for heights **0, 1, 2 and 1000** (after sync): e.g. height 1000 returned
|
||||||
|
a 640-hex-char blob with `block_header.height = 1000`, and the genesis block returned
|
||||||
|
`block_header.hash = 48ca7cd3…`, the same hash `/get_height` reported at height 1.
|
||||||
|
|
||||||
|
Two naming facts worth recording, because the card's wording ("get_height via /json_rpc")
|
||||||
|
does not match either daemon:
|
||||||
|
|
||||||
|
* `get_height` is **not** a JSON-RPC 2.0 method in monerod — it is registered as a URI
|
||||||
|
endpoint only (`MAP_URI_AUTO_JON2("/get_height", …)` and `"/getheight"` in
|
||||||
|
`src/rpc/core_rpc_server.h:92-93`), while the JSON-RPC method is
|
||||||
|
`MAP_JON_RPC("get_block_count", …)` (line 134). Cuprate mirrors exactly that split:
|
||||||
|
`/get_height` answers, `{"method":"get_height"}` over `/json_rpc` is rejected 422
|
||||||
|
("unknown variant `get_height`"), and `get_block_count` answers. This is parity, not a gap.
|
||||||
|
* Cuprate's router also carries the monerod aliases (`/getinfo`, `/getheight`,
|
||||||
|
`/getblockcount`, `/gethashes.bin`, …).
|
||||||
|
|
||||||
|
### Real testnet P2P sync in-process
|
||||||
|
|
||||||
|
```
|
||||||
|
INFO net{zone="ClearNet"}: Starting outbound connection maintainer, target outbound connections: 32
|
||||||
|
INFO net{zone="ClearNet"}:connect_to_random_seeds: Failed to connect to seed node 51.79.173.165:28080: Connection refused
|
||||||
|
INFO incoming_block_batch{start_height=17968 len=100}: Successfully added block batch fast_sync=false
|
||||||
|
...
|
||||||
|
t+ 0s height=1160 target_height=0 in-process_chain_height=1160
|
||||||
|
t+ 40s height=4549 target_height=3090939 in-process_chain_height=4549
|
||||||
|
t+ 80s height=14068 target_height=3090939 in-process_chain_height=14068
|
||||||
|
t+ 120s height=23758 target_height=3090939 in-process_chain_height=23758
|
||||||
|
```
|
||||||
|
|
||||||
|
Testnet sync runs from inside the OnionWire-style process at roughly **200 blocks/s**
|
||||||
|
(~23.7k blocks in 120 s against a 3.09M-block target), and the RPC `height` tracks the
|
||||||
|
in-process `node.blockchain.context().chain_height` at every sample — the RPC reads live
|
||||||
|
chain state, so a wallet child pointed at it sees progress as it happens.
|
||||||
|
|
||||||
|
### Binary cost
|
||||||
|
|
||||||
|
Spike binary (arti 0.46 + cuprated + tokio + harness), release, stripped:
|
||||||
|
**33,256,328 bytes (31.7 MiB)**; unstripped 48,489,392 bytes. This is consistent with the
|
||||||
|
earlier +5.6 MB stripped delta over OnionWire's own 25.6 MB release binary.
|
||||||
|
|
||||||
|
## Parity gaps observed (must be handled before Phase 1 lands)
|
||||||
|
|
||||||
|
1. **Out-of-range `get_block` returns a bare HTTP 500 with an empty body.** Requesting
|
||||||
|
`height = chain_height + 1_000_000` produced `HTTP/1.1 500 Internal Server Error` with a
|
||||||
|
zero-byte body. monerod answers HTTP 200 with an epee JSON-RPC error object instead:
|
||||||
|
`error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT;
|
||||||
|
error_resp.message = "Requested block height: N greater than current top block height: M"`
|
||||||
|
(`src/rpc/core_rpc_server.cpp`, `on_get_block`). A wallet child or our own `wallet.rs`
|
||||||
|
has to treat a 500-with-no-body as an error it cannot decode, where monerod gave it a
|
||||||
|
machine-readable code.
|
||||||
|
2. **`get_info` always reports zero peers**, including while actively downloading blocks:
|
||||||
|
`outgoing_connections_count = 0`, `incoming_connections_count = 0` in every sample while
|
||||||
|
`height` climbed 1,160 → 23,758. monerod reports live counts there. Any UI that shows
|
||||||
|
peer count or "connected" from `get_info` will show zero on a syncing node.
|
||||||
|
3. **Restricted `get_info` returns placeholder values**: `database_size = 5368709120`
|
||||||
|
(exactly 5 GiB, `0x1_4000_0000`) and `version = ""`, where the unrestricted server on the
|
||||||
|
same process/DB returned the real size and `"0.1.0-preview-release"`. `free_space` is
|
||||||
|
`18446744073709551615` (u64::MAX) on both servers — a placeholder, not a measurement.
|
||||||
|
`monero-wallet-rpc` polling the restricted endpoint would show a bogus database size and
|
||||||
|
a blank version.
|
||||||
|
4. **Version string** is the pre-release label `0.1.0-preview-release`; anything doing a
|
||||||
|
monerod version comparison against it will not recognise it.
|
||||||
|
|
||||||
|
Not tested here (out of scope for this card): `get_transfers`-shaped flows through a real
|
||||||
|
`monero-wallet-rpc`, mainnet sync, prune behaviour, Tor zone, and field-by-field equality
|
||||||
|
against a live `monerod` (no `monerod` binary on this host — the comparison above is against
|
||||||
|
monerod's source, `core_rpc_server.h` / `core_rpc_server.cpp`).
|
||||||
|
|
||||||
|
## Recommendation
|
||||||
|
|
||||||
|
Phase 1 is **viable**: the chain daemon genuinely runs in-process, its RPC is monerod-shaped
|
||||||
|
for the three endpoints a wallet needs, and real testnet P2P sync works with no external
|
||||||
|
binary. Before wiring `monero-wallet-rpc` to it:
|
||||||
|
|
||||||
|
* decide how to handle the 500-on-bad-height path (fix upstream, or treat 5xx as a typed
|
||||||
|
error in `src/wallet.rs`);
|
||||||
|
* do not source peer count, database size, free space or version from `get_info` for UI
|
||||||
|
claims — the restricted server returns placeholders, and the daemon reports zero peers;
|
||||||
|
* keep the pre-production warning honest in `docs/WALLET.md` / `docs/THREAT_MODEL.md`:
|
||||||
|
Cuprate's own user book says not to use `cuprated` for anything serious, and RPC parity
|
||||||
|
(`Cuprate/cuprate#278`) is still open.
|
||||||
|
|
||||||
|
## Reproduction
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd /home/lancelot/.hermes/tmp/cuprate-poc
|
||||||
|
CARGO_TARGET_DIR=/home/lancelot/.hermes/tmp/cuprate-poc-target \
|
||||||
|
TMPDIR=/home/lancelot/.hermes/tmp/cuprate-poc-tmp \
|
||||||
|
cargo run --release --offline
|
||||||
|
```
|
||||||
|
|
||||||
|
The run log (`run-2.log`) and every raw RPC response body (`rpc-evidence/`) are kept in the
|
||||||
|
spike directory; the data dir (`data/testnet/`) is a 53 MB fjall store after 23.7k testnet
|
||||||
|
blocks, so restarting the spike resumes instead of re-syncing.
|
||||||
301
docs/design/pq-bootstrap-epoch.md
Normal file
301
docs/design/pq-bootstrap-epoch.md
Normal file
|
|
@ -0,0 +1,301 @@
|
||||||
|
# ADR: a post-quantum bootstrap epoch (epoch 0)
|
||||||
|
|
||||||
|
**Status:** proposed. This is a decision record: it recommends a direction and
|
||||||
|
changes no code. The protocol and threat-model wording it depends on is already
|
||||||
|
on `main`; this file does not restate it.
|
||||||
|
|
||||||
|
**Decision:** accept the window (Option C). Revisit when the one-shot session
|
||||||
|
model changes, or when a one-time prekey can reach the peer without a new wire
|
||||||
|
field.
|
||||||
|
|
||||||
|
Related: [PROTOCOL.md](../PROTOCOL.md) ("Hybrid ratchet steps, and why epoch 0
|
||||||
|
stays classical") and [THREAT_MODEL.md](../THREAT_MODEL.md) ("Epoch 0 is
|
||||||
|
classical — this is the remaining harvest-now window").
|
||||||
|
|
||||||
|
## 1. Context: the invariant, stated exactly
|
||||||
|
|
||||||
|
Epoch 0 is the ratchet state a friend pair starts from. It is derived, not
|
||||||
|
negotiated:
|
||||||
|
|
||||||
|
1. **Each chat message is its own one-shot Noise session.** `Node::send` encodes
|
||||||
|
exactly one `rat ` frame and hands those bytes to the outbox
|
||||||
|
(`src/node.rs:1905`, `src/outbox.rs:168`). Sending again opens a new Noise
|
||||||
|
session to the same onion. There is no connection, stream, or session object
|
||||||
|
that outlives one application frame.
|
||||||
|
2. **The Noise handshake carries no application payload.** It is frozen at
|
||||||
|
`Noise_IK_25519_ChaChaPoly_BLAKE2s`, so no field can hand the peer an initial
|
||||||
|
ratchet key (`src/node.rs:2316`).
|
||||||
|
3. **Either peer may send first.** Two peers can each build a sending chain
|
||||||
|
before either has received anything. The resolution is per-direction chains
|
||||||
|
over the *unordered pair* of ratchet public keys, so authorship of a direction
|
||||||
|
is decided by key order rather than by who spoke first
|
||||||
|
(`src/ratchet.rs:94-116`).
|
||||||
|
4. **Therefore epoch 0 must be a pure function of material both sides already
|
||||||
|
have**: the X25519 DH of the two long-lived signed prekeys, with each side's
|
||||||
|
initial ratchet keypair seeded by
|
||||||
|
`HKDF(info = "ratchet-key" || pubkey)`
|
||||||
|
(`src/node.rs:2325-2370`). No wire field, no round trip, no per-session
|
||||||
|
secret. This is the invariant the three options are measured against.
|
||||||
|
|
||||||
|
The consequence, already documented and not re-argued here: epoch 0 is derived
|
||||||
|
with the classical `KDF_RK` and the ML-KEM secret enters at the **first
|
||||||
|
rotation** (`src/ratchet.rs:66-73`, `docs/PROTOCOL.md:683`). Every frame sent
|
||||||
|
before that point is X25519-only at the ratchet layer.
|
||||||
|
|
||||||
|
Two facts bound how much that costs, and they matter for the ranking:
|
||||||
|
|
||||||
|
- **For a v2 friend the `rat ` frame rides inside a hybrid Noise session.** A
|
||||||
|
recorded transcript is not opened by an X25519 break alone; the ML-KEM-768
|
||||||
|
prelude has to be broken too, and it is per-dial. Epoch 0 becomes the exposed
|
||||||
|
layer when the rat frame is separated from the session that carried it — a
|
||||||
|
state snapshot, an outbox row at rest, a logging client, or a classical peer
|
||||||
|
(`docs/THREAT_MODEL.md:163-192`).
|
||||||
|
- **The ML-KEM half of a ratchet keypair is derived from the X25519 secret**
|
||||||
|
(`src/ratchet.rs:56-63`, `src/ratchet.rs:326`). It adds no independent secret
|
||||||
|
to epoch 0, so "every keypair is hybrid" does not mean the bootstrap epoch is.
|
||||||
|
|
||||||
|
## 2. Options
|
||||||
|
|
||||||
|
Each subsection has the same shape: mechanism, wire cost, convergence, effect on
|
||||||
|
the outbox and stored/replayed frames, test surface, and cost in slice-days. One
|
||||||
|
slice-day is one focused working day for one agent in this repo, including tests
|
||||||
|
and the doc updates the change would force.
|
||||||
|
|
||||||
|
### Option A — one-time prekey batch in the invite
|
||||||
|
|
||||||
|
**Mechanism.** The invite carries N ML-KEM-768 one-time prekeys (OPKs) in
|
||||||
|
addition to the long-lived `kem=`. The peer consumes one per dial or per epoch,
|
||||||
|
depending on which layer the OPK is meant to protect — that ambiguity is the
|
||||||
|
first finding below. The threat model already lists "No one-time prekeys" as an
|
||||||
|
honest limit (`docs/THREAT_MODEL.md:199-203`), so this is the option that would
|
||||||
|
close a named gap; the size and convergence findings are what kill it.
|
||||||
|
|
||||||
|
**What the invite gains.** A new version, necessarily. The v2 signature domain is
|
||||||
|
`onionwire-invite-v2 || 0x00 || k || 0x00 || o || 0x00 || spk || 0x00 || kem`
|
||||||
|
(`src/qr.rs:38`), and `parse_fields` rejects any unrecognised field with
|
||||||
|
`unknown field` (`src/qr.rs`, `parse_fields`). So an `opk=` field on a v2 string
|
||||||
|
is a decode error, not an ignored extra: the batch is `onionwire:v3`, a new
|
||||||
|
signature domain, and a new field in the signed message.
|
||||||
|
|
||||||
|
**Size, numerically.** A v2 invite is 1930 characters for a 56-character v3
|
||||||
|
onion. Each ML-KEM-768 OPK is 1184 bytes, which is 1579 base64url characters
|
||||||
|
plus a 5-character `:opk=` prefix — **1584 characters each**. The decoder caps
|
||||||
|
input at `MAX_INVITE = 4096` (`src/qr.rs:30`), and the TUI renders the invite
|
||||||
|
through `qrcode` 0.14.1 at its default `EcLevel::M` (`src/tui.rs:2818`), whose
|
||||||
|
byte capacity is **2331 characters** (measured against the pinned crate, not
|
||||||
|
recalled). Therefore:
|
||||||
|
|
||||||
|
| Invite | chars | fits `MAX_INVITE` | fits one QR at M |
|
||||||
|
|---|---|---|---|
|
||||||
|
| v2 today | 1930 | yes | yes |
|
||||||
|
| v3, 1 OPK | 3514 | yes | **no** |
|
||||||
|
| v3, 2 OPKs | 5098 | **no** | no |
|
||||||
|
| v3, 4 OPKs | 8266 | no | no |
|
||||||
|
|
||||||
|
A batch that could survive more than one use cannot be carried by this invite at
|
||||||
|
all: two OPKs already exceed the decoder's own cap, and one already exceeds what
|
||||||
|
the QR path can render. The invite would have to move to a file/NFC transfer, or
|
||||||
|
the QR would have to be dropped, before the batch is even representable.
|
||||||
|
|
||||||
|
**What is consumed, and when.** This is where the option loses its premise. If
|
||||||
|
the OPK is consumed at the **transport** layer (one per Noise dial), it is one
|
||||||
|
per message: a retry after a queued send is a new dial and burns another, and a
|
||||||
|
batch of N is exhausted after N dials with no replenishment path — the peer has
|
||||||
|
the invite, not a directory, so the next invite paste is the only refill. If it
|
||||||
|
is consumed at the **ratchet** layer, it is one per epoch, and the secret has to
|
||||||
|
reach the peer: ML-KEM encapsulation is randomised, so the sender must transmit
|
||||||
|
a 1088-byte ciphertext. That is exactly Option B's wire field. **A does not fix
|
||||||
|
epoch 0 without B**; on its own it only improves the transport handshake, which
|
||||||
|
already carries a per-dial ML-KEM secret in the v2 prelude.
|
||||||
|
|
||||||
|
**Unused prekeys.** They are decapsulation keys stored for the life of the
|
||||||
|
install, with no expiry and no ratchet benefit. A state snapshot hands them over,
|
||||||
|
so they become an additional long-lived secret rather than a forward-secrecy
|
||||||
|
win. The roster already drops state when a peer's prekey changes
|
||||||
|
(`src/node.rs:2385-2395`); a batch would need its own consumption cursor, its own
|
||||||
|
versioned blob, and a rule for when a partly-consumed batch is abandoned.
|
||||||
|
|
||||||
|
**Wire cost.** Invite only, if the OPK is used at the transport layer (+1584
|
||||||
|
characters per prekey, and the QR stops working at one). Invite *and* frame
|
||||||
|
(+1088 header bytes per epoch-0 frame, repeated until the first rotation) if used
|
||||||
|
at the ratchet layer — at which point it is B.
|
||||||
|
|
||||||
|
**Convergence.** At the transport layer, unchanged: each Noise session's two
|
||||||
|
endpoints both know that session's `ss_kem`, so per-dial secrets are fine there.
|
||||||
|
At the ratchet layer, A *breaks* convergence on its own: both peers encapsulate
|
||||||
|
to the same OPK, get different secrets (fresh randomness on each side), and
|
||||||
|
derive different epoch-0 roots. Only one direction's ciphertext can be the
|
||||||
|
authoritative one, and carrying it is a wire field.
|
||||||
|
|
||||||
|
**Outbox and replayed frames.** A stored `rat ` frame is replayed byte-for-byte
|
||||||
|
over a fresh Noise session (`src/outbox.rs:161-175`; the retry loop must not
|
||||||
|
advance the sending chain twice, so the frame is encoded once). Transport-layer
|
||||||
|
OPK consumption therefore drains the batch on retries, not on delivered
|
||||||
|
messages. Ratchet-layer consumption requires the receiver to retain the OPK
|
||||||
|
private key until every queued row encrypted under it is delivered or
|
||||||
|
terminally failed — unbounded retention, which contradicts "one-time".
|
||||||
|
|
||||||
|
**Test surface.** Invite v3 round-trip and signature domain; rejection of `opk=`
|
||||||
|
on v2; batch exhaustion and the fallback to `kem=`; QR capacity (the invite
|
||||||
|
render path currently has no graceful path for "too long for one symbol");
|
||||||
|
retry-burns-a-prekey; a both-send-first test showing the two roots diverge if the
|
||||||
|
ratchet layer is attempted without a field.
|
||||||
|
|
||||||
|
**Cost (estimate).** 5–7 slice-days for the invite/transport version of A (invite v3,
|
||||||
|
signed field, store pool, consumption cursor, tests, docs). It buys a
|
||||||
|
transport-layer improvement that is already covered by the per-dial prelude, and
|
||||||
|
leaves epoch 0 exactly as it is. The ratchet-layer variant is B plus this cost.
|
||||||
|
|
||||||
|
### Option B — per-session epoch derivation with an extra wire field
|
||||||
|
|
||||||
|
**Mechanism.** Add material to the ratchet header and derive the epoch from it.
|
||||||
|
The natural shape is a new version byte (`0x03` classical + field, `0x04` hybrid
|
||||||
|
+ field) because `0x01` and `0x02` are already taken and the header is the AEAD
|
||||||
|
associated data, so its exact shape is load-bearing
|
||||||
|
(`src/ratchet.rs:1-40`, `src/ratchet.rs:585-601`). The field would be a 32-byte
|
||||||
|
salt, or a 1088-byte ML-KEM ciphertext if it carries a prekey secret.
|
||||||
|
|
||||||
|
**Wire cost.** 32 bytes per frame (salt) or 1088 bytes per frame (ciphertext),
|
||||||
|
repeated on every frame of the epoch-0 chain because the first frame can be lost.
|
||||||
|
The classical header goes 40 → 72 bytes, the hybrid header 2312 → 3400, and the
|
||||||
|
documented minimum frame sizes (350 classical, 2622 hybrid,
|
||||||
|
`docs/THREAT_MODEL.md:217-220`) all move. The minimum-size tests and the padding
|
||||||
|
ladder's interaction with the floor would have to be re-derived, not just
|
||||||
|
re-numbered.
|
||||||
|
|
||||||
|
**Convergence.** This is the option's fatal case. The field arrives *in* the
|
||||||
|
frame, so neither side has the other's field before its first send. Two designs
|
||||||
|
are available and neither restores the invariant:
|
||||||
|
|
||||||
|
- *Sender-chosen salt, per direction.* Each side derives its own sending chain
|
||||||
|
from its own salt. That works for the first message in each direction, but the
|
||||||
|
epoch's shared root advance now depends on two salts, and the side that rotates
|
||||||
|
first — the tie-break side rotates on its first *decrypt*
|
||||||
|
(`src/ratchet.rs:624-630`) — may have seen only one of them. The root is no
|
||||||
|
longer a pure function of the pair, so the lockstep argument in
|
||||||
|
`src/ratchet.rs:100-116` no longer holds and the peers can diverge at the
|
||||||
|
first rotation.
|
||||||
|
- *Salt derived from the Noise session secret.* Then the two peers' first sends
|
||||||
|
ride different sessions with different secrets, and message 2 rides a third
|
||||||
|
session, so a stored and retried frame cannot be re-derived at all — see the
|
||||||
|
outbox row.
|
||||||
|
|
||||||
|
A public salt in the header adds no secrecy, because it is transmitted in clear
|
||||||
|
inside the Noise transport. It would only bind the chain to a random value,
|
||||||
|
which is not the threat. So B is either a no-op against harvest-now, or it is a
|
||||||
|
salt that breaks convergence, or it is a KEM ciphertext that reintroduces A's
|
||||||
|
consumption and retention problems.
|
||||||
|
|
||||||
|
**Outbox and replayed frames.** A salt lives in the stored frame, so a verbatim
|
||||||
|
replay is consistent. A ciphertext likewise survives the replay, but the
|
||||||
|
receiver must still hold the matching private key when the retry lands — so the
|
||||||
|
"one-time" key is retained until the outbox row is delivered or fails, and
|
||||||
|
`DEFAULT_MAX_ATTEMPTS` (8) with a 30-minute backoff cap means that retention is
|
||||||
|
measured in hours at minimum. This is the same retention conflict as A, now on
|
||||||
|
the frame path.
|
||||||
|
|
||||||
|
**Test surface.** New version bytes and header layout; AAD coverage of the new
|
||||||
|
field; the both-send-first matrix re-derived (the existing convergence tests in
|
||||||
|
`src/ratchet.rs` and `tests/ratchet_wire.rs` assert the current argument, not just
|
||||||
|
the happy path); `STATE_VERSION` 2 → 3 with a v2 blob dropped exactly like v1
|
||||||
|
(`src/ratchet.rs:163`, `src/node.rs:2385-2395`); cross-version interop, since a
|
||||||
|
friend with a v2 invite has no field to send — downgrade is decided by the
|
||||||
|
roster, never by what arrives on the wire, so these are two different epoch
|
||||||
|
shapes that must never be negotiated dynamically; padding floor and minimum-frame
|
||||||
|
constants.
|
||||||
|
|
||||||
|
**Cost (estimate).** 8–12 slice-days, and it leaves the ambiguous root-advance rule open
|
||||||
|
(that is the item in "Not solved by this doc").
|
||||||
|
|
||||||
|
### Option C — accept the window, keep the honesty bounds
|
||||||
|
|
||||||
|
**Mechanism.** No change. Epoch 0 stays prekey-derived and classical; the KEM
|
||||||
|
secret enters at the first rotation; the docs keep saying so in the three places
|
||||||
|
they already do (`src/ratchet.rs:66-73`, `docs/PROTOCOL.md:683-720`,
|
||||||
|
`docs/THREAT_MODEL.md:163-192`).
|
||||||
|
|
||||||
|
**What has to be true for this to stay acceptable.** These are the conditions the
|
||||||
|
decision rests on; if one stops holding, the trigger in §3 fires.
|
||||||
|
|
||||||
|
- *The first rotation is prompt.* It happens on the first inbound frame after
|
||||||
|
`established`, and the lower-key side also rotates immediately on that decrypt
|
||||||
|
(`src/ratchet.rs:624-630`). A peer that sends and never receives stays on
|
||||||
|
epoch 0 by definition; the window closes with the first reply, not with time.
|
||||||
|
- *Nothing claims otherwise.* "Post-quantum transport, classical bootstrap
|
||||||
|
epoch" is the ceiling. `docs/THREAT_MODEL.md:25` and
|
||||||
|
`docs/THREAT_MODEL.md:163` are the sentences that must not drift, and
|
||||||
|
README/marketing copy inherits them.
|
||||||
|
- *A state snapshot is already the whole game.* The ratchet state lives in the
|
||||||
|
same SQLCipher file as the plaintext history, and `docs/THREAT_MODEL.md:205-209`
|
||||||
|
says a snapshot carries both chain keys, the skipped keys, and the history.
|
||||||
|
Epoch 0 is therefore not the weakest link at rest: an attacker with the store
|
||||||
|
reads the messages, not the chain. The epoch-0 exposure is about frames outside
|
||||||
|
the store — captured traffic and delivered outbox rows — not about the device.
|
||||||
|
- *Outbox exposure stays bounded by delivery.* A row encoded on epoch 0 carries
|
||||||
|
epoch-0 keys until it is delivered or terminally fails
|
||||||
|
(`docs/THREAT_MODEL.md:176`). The queue is local, bounded by
|
||||||
|
`DEFAULT_MAX_ATTEMPTS`, and never handed to a third party, so this is the same
|
||||||
|
window as a live epoch-0 message, not a new one.
|
||||||
|
- *The roster still decides downgrade.* A v1 friend has no PQ layer anywhere;
|
||||||
|
that is a roster fact, not a wire negotiation
|
||||||
|
(`docs/THREAT_MODEL.md:183-187`).
|
||||||
|
|
||||||
|
**Wire cost.** Zero. **Convergence.** Unchanged, and covered by the existing
|
||||||
|
both-send-first and cross-peer tests. **Outbox and stored frames.** Unchanged;
|
||||||
|
the verbatim-replay property stays exact. **Test surface.** No new tests; the
|
||||||
|
existing ones already pin the invariant. **Cost.** 0 slice-days. The standing
|
||||||
|
cost is one honest sentence in the docs, which is already paid.
|
||||||
|
|
||||||
|
## 3. Comparison and decision
|
||||||
|
|
||||||
|
| | A — OPK batch | B — epoch field | C — accept |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Wire cost | +1584 chars/invite (QR dies at 1) | +32 or +1088 B/frame, new versions | 0 |
|
||||||
|
| Fixes epoch 0? | no (transport only; needs B for ratchet) | only as a public salt, which is not the threat | n/a |
|
||||||
|
| Convergence | breaks it at the ratchet layer | ambiguous root advance; breaks lockstep | unchanged |
|
||||||
|
| Outbox / replay | drains batch on retries; unbounded OPK retention | verbatim replay OK, retention unbounded | unchanged, bounded by delivery |
|
||||||
|
| Test surface | invite v3, pool, QR capacity, divergence | header, state v3, both-send-first matrix, floors | none |
|
||||||
|
| Slice-days (est.) | 5–7 (and buys no epoch-0 fix) | 8–12 | 0 |
|
||||||
|
|
||||||
|
**Decision: C.** A does not make epoch 0 post-quantum — it adds invite mass and a
|
||||||
|
consumption problem, and the part that would touch the ratchet is B's wire field,
|
||||||
|
which cannot converge under both-send-first without an ambiguous root rule. C
|
||||||
|
costs nothing, keeps the one property the design actually relies on (a root that
|
||||||
|
is a pure function of the prekey pair), and the exposure it accepts is already
|
||||||
|
shadowed for v2 friends by the per-dial hybrid Noise session.
|
||||||
|
|
||||||
|
**Revisit triggers**, in priority order. Any one of these reopens this ADR; none
|
||||||
|
is a reason to start work now:
|
||||||
|
|
||||||
|
1. **The one-shot session model changes.** If chat ever gets a session that
|
||||||
|
outlives one frame, the blocker in §1 disappears and epoch 0 can take a
|
||||||
|
per-session secret. This is the real trigger.
|
||||||
|
2. **A delivery path for a prekey ciphertext exists without a new field.** E.g.
|
||||||
|
the handshake gains an application payload. Then A becomes viable at the
|
||||||
|
ratchet layer.
|
||||||
|
3. **The invite stops being QR-first.** If invites move to file/NFC and the
|
||||||
|
`MAX_INVITE` cap can move with them, a batch is at least representable — still
|
||||||
|
subject to the replenishment problem, so this alone is not enough.
|
||||||
|
4. **Any doc or release note claims post-quantum messaging.** That is a
|
||||||
|
documentation failure to fix immediately, not a reason to ship A or B.
|
||||||
|
|
||||||
|
**Consequences.** No code changes. The next card on this topic is not A or B; if
|
||||||
|
one is proposed anyway, it must answer B's root-advance question and the QR
|
||||||
|
capacity finding in A before it can be scoped. The docs on `main` continue to be
|
||||||
|
the authority on what is and is not post-quantum.
|
||||||
|
|
||||||
|
## 4. Not solved by this doc
|
||||||
|
|
||||||
|
- **In-band revocation / unfriend.** There is no revoke frame; the roster drops
|
||||||
|
a friend locally, and the peer keeps the current onion until F4
|
||||||
|
(`docs/THREAT_MODEL.md:19`).
|
||||||
|
- **Prekey or KEM rotation without a new invite.** F8 rotates the signed prekey
|
||||||
|
and the ML-KEM install key, and every friend must paste the new invite; there
|
||||||
|
is no push path (`docs/THREAT_MODEL.md:21-24`). Option A makes this worse, not
|
||||||
|
better: a batch has no refill channel, so it inherits the same hard cut.
|
||||||
|
- **Option B's open question.** Which input advances the epoch root when two
|
||||||
|
per-direction salts exist and the first rotator has seen only one of them. A
|
||||||
|
future B proposal has to answer that before it can be implemented; this doc
|
||||||
|
does not.
|
||||||
|
- **Guard discovery.** The long-lived v3 onion and Arti's vanguards-lite are a
|
||||||
|
separate opsec gap and are not addressed by any of the three options.
|
||||||
|
|
@ -1,5 +1,8 @@
|
||||||
# Recommendation: Option A — bundle the `arti` binary as a SOCKS subprocess
|
# Recommendation: Option A — bundle the `arti` binary as a SOCKS subprocess
|
||||||
|
|
||||||
|
**Status:** shipped. The wallet child uses `arti proxy -p` for `.onion` daemons.
|
||||||
|
Living doc: [WALLET.md](WALLET.md). This file is the decision record.
|
||||||
|
|
||||||
## What Option A is
|
## What Option A is
|
||||||
|
|
||||||
Run the `arti` CLI (not `arti-client`) as a child process doing `arti proxy -p <port>`. The wallet child points `--proxy 127.0.0.1:<port>` at it. The messenger continues using in-process `arti-client`. Two Tor clients in one app: one in-process for the messenger, one subprocess for SOCKS.
|
Run the `arti` CLI (not `arti-client`) as a child process doing `arti proxy -p <port>`. The wallet child points `--proxy 127.0.0.1:<port>` at it. The messenger continues using in-process `arti-client`. Two Tor clients in one app: one in-process for the messenger, one subprocess for SOCKS.
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,11 @@
|
||||||
# OnionWire payment integration — next steps
|
# OnionWire payment integration — next steps
|
||||||
|
|
||||||
|
**Status:** largely shipped (child wallet, `/pay` `/tip`, F6 create/import, F9
|
||||||
|
menu). Still open on desktop: no TUI editor for a stored external RPC URL or a
|
||||||
|
typed remote daemon host (API exists; error copy still says “F7”). Living docs:
|
||||||
|
[WALLET.md](WALLET.md), [TUI.md](TUI.md). This file is the plan as written; do
|
||||||
|
not rewrite the conclusion.
|
||||||
|
|
||||||
**Audience:** dev profiles (rust-dev for core/SDK/TUI, apk-dev for Android), with CI as a cross-cutting concern.
|
**Audience:** dev profiles (rust-dev for core/SDK/TUI, apk-dev for Android), with CI as a cross-cutting concern.
|
||||||
**Goal:** turn the existing `inv`/`rcp`/`tip` wire frames and the existing `monero-wallet-rpc` HTTP Digest client into a real in-app payment flow on both TUI and Android, with the wallet fully owned by the app (bundled binaries), chain backends opt-in (local pruned node, or remote onion daemon), clearnet refused, Tor for the messenger and for any remote-daemon chain traffic.
|
**Goal:** turn the existing `inv`/`rcp`/`tip` wire frames and the existing `monero-wallet-rpc` HTTP Digest client into a real in-app payment flow on both TUI and Android, with the wallet fully owned by the app (bundled binaries), chain backends opt-in (local pruned node, or remote onion daemon), clearnet refused, Tor for the messenger and for any remote-daemon chain traffic.
|
||||||
|
|
||||||
|
|
@ -214,11 +220,17 @@ A rust-dev card may explore baking a Monero chain daemon directly into the Onion
|
||||||
|
|
||||||
- **`rust-dev`: Spike — embed `cuprated` (git dep) alongside `arti-client` 0.46, verify `Node::launch(Config).await` compiles and the documented usage (`node.blockchain.context().chain_height`) type-checks.** PROOF OF CONCEPT: `cargo check` passed (exit 0) with 575 packages; `arti-client` 0.44 (Cuprate) and 0.46 (OnionWire) coexisted. `cuprated::Node::launch(config: impl Into<Arc<Config>>) -> Result<Node, anyhow::Error>` is accessible. `Node` fields: `blockchain`, `txpool`, `clearnet`, `tor`, `config`, `task_executor`; implements `Drop` → `shutdown()`. Config is at `cuprated::config::Config`. See `references/cuprate-integration.md` for full test log.
|
- **`rust-dev`: Spike — embed `cuprated` (git dep) alongside `arti-client` 0.46, verify `Node::launch(Config).await` compiles and the documented usage (`node.blockchain.context().chain_height`) type-checks.** PROOF OF CONCEPT: `cargo check` passed (exit 0) with 575 packages; `arti-client` 0.44 (Cuprate) and 0.46 (OnionWire) coexisted. `cuprated::Node::launch(config: impl Into<Arc<Config>>) -> Result<Node, anyhow::Error>` is accessible. `Node` fields: `blockchain`, `txpool`, `clearnet`, `tor`, `config`, `task_executor`; implements `Drop` → `shutdown()`. Config is at `cuprated::config::Config`. See `references/cuprate-integration.md` for full test log.
|
||||||
|
|
||||||
- **`rust-dev`: If spike passes, actually launch Node::launch on testnet/fakchain, verify sync starts and monerod-compatible JSON-RPC (get_info, get_height) responds with the chain data OnionWire needs for receipt verification.**
|
- **`rust-dev`: If spike passes, actually launch Node::launch on testnet/fakchain, verify sync starts and monerod-compatible JSON-RPC (get_info, get_height) responds with the chain data OnionWire needs for receipt verification.** PROOF: in-process launch on testnet works — `Node::launch` returns in ~2.8 s cold, the unrestricted RPC on `127.0.0.1:18089` answers `get_info` / `/get_height` / `get_block` (heights 0, 1, 2, 1000 all retrievable) with monerod-shaped payloads, and the node synced 0 → 23,758 testnet blocks in ~120 s over its own clearnet P2P. Four parity gaps are recorded (bare HTTP 500 on out-of-range `get_block`, `get_info` peer counts always 0, restricted `get_info` placeholder `database_size`/`version`, and the `0.1.0-preview` version label) in [docs/cuprate-launch-spike.md](cuprate-launch-spike.md). Verdict: Phased Phase 1 is viable, with those gaps handled before `monero-wallet-rpc` is pointed at it.
|
||||||
- **`rust-dev`: If launch spike passes, assess wallet gap.** Since Cuprate has no wallet layer, determine whether to (a) keep `monero-wallet-rpc` as a subprocess and point it at the in-process Cuprate daemon (halves Android binary spawning), or (b) also adopt `monero-oxide`/`monero-wallet` as an in-process wallet to eliminate all subprocesses.
|
- **`rust-dev`: If launch spike passes, assess wallet gap.** Since Cuprate has no wallet layer, determine whether to (a) keep `monero-wallet-rpc` as a subprocess and point it at the in-process Cuprate daemon (halves Android binary spawning), or (b) also adopt `monero-oxide`/`monero-wallet` as an in-process wallet to eliminate all subprocesses.
|
||||||
|
|
||||||
This card does **not** pre-empt the existing subprocess-based cards in §9 — those remain the default path until Cuprate proves itself in-process.
|
This card does **not** pre-empt the existing subprocess-based cards in §9 — those remain the default path until Cuprate proves itself in-process.
|
||||||
|
|
||||||
|
**Strategic recommendation (hybrid phased approach):**
|
||||||
|
|
||||||
|
- **Phase 1:** Use Cuprate in-process for the chain daemon (P2P + consensus + RandomX). Keep `monero-wallet-rpc` as a subprocess pointing at the in-process Cuprate node over localhost RPC. Cuprate's RPC mirrors `monerod`'s, so `monero-wallet-rpc` talks to it using the same JSON-RPC calls. This eliminates the ~52 MB `monerod` binary while preserving all wallet code. Binary overhead: +5.6 MB stripped. Android: bundle only `monero-wallet-rpc` (~4 MB/ABI) instead of both `monerod` (~52 MB) + `monero-wallet-rpc`. The Android cross-compile is **verified**: `cargo check --release --target aarch64-linux-android` exits 0 and the binary links as an Android 26 aarch64 ELF — env recipe and the required C++/builtins link args in [`cuprate-android-spike.md`](cuprate-android-spike.md).
|
||||||
|
|
||||||
|
- **Phase 2 (future):** Only after Phase 1 is stable, consider replacing `monero-wallet-rpc` with the [`monero-wallet`](https://crates.io/crates/monero-wallet) crate (from the monero-oxide workspace). This is a transaction construction library, not a full wallet — replacing wallet-rpc requires reimplementing seed/key storage, address derivation, balance tracking, and output selection. Major effort.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8. Key risks to flag in the card descriptions
|
## 8. Key risks to flag in the card descriptions
|
||||||
|
|
|
||||||
1079
docs/tui-wallet-ux-review.md
Normal file
1079
docs/tui-wallet-ux-review.md
Normal file
File diff suppressed because it is too large
Load diff
9
fuzz/.gitignore
vendored
Normal file
9
fuzz/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
# Build output and crash artifacts are not source.
|
||||||
|
target/
|
||||||
|
artifacts/
|
||||||
|
coverage/
|
||||||
|
# The working corpus is machine-local: libFuzzer grows it on every run, and
|
||||||
|
# that growth is noise in a diff. The hand-built regression inputs live in
|
||||||
|
# seeds/ and are copied into corpus/ by scripts/run-fuzz.sh; fold a reproducer
|
||||||
|
# from artifacts/ into seeds/ once the bug behind it is fixed.
|
||||||
|
corpus/
|
||||||
6352
fuzz/Cargo.lock
generated
Normal file
6352
fuzz/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
44
fuzz/Cargo.toml
Normal file
44
fuzz/Cargo.toml
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
[package]
|
||||||
|
name = "onionwire-fuzz"
|
||||||
|
version = "0.0.0"
|
||||||
|
publish = false
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[package.metadata]
|
||||||
|
cargo-fuzz = true
|
||||||
|
|
||||||
|
# Detach from the parent package: this crate is nightly-only and must never be
|
||||||
|
# part of a normal `cargo build` / `cargo test` of the root crate.
|
||||||
|
[workspace]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
libfuzzer-sys = "0.4"
|
||||||
|
onionwire = { path = ".." }
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "ratchet_frame"
|
||||||
|
path = "fuzz_targets/ratchet_frame.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "qr_decode"
|
||||||
|
path = "fuzz_targets/qr_decode.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "dispatch_classify"
|
||||||
|
path = "fuzz_targets/dispatch_classify.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "file_decode"
|
||||||
|
path = "fuzz_targets/file_decode.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
26
fuzz/README.md
Normal file
26
fuzz/README.md
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
# Fuzzing OnionWire
|
||||||
|
|
||||||
|
Structured fuzzing for the four parsers that eat untrusted peer input. A crash
|
||||||
|
here is a remote-triggerable panic, so a reproducer must be fixed in `src/` and
|
||||||
|
then folded into `fuzz/seeds/<target>/` as a regression input.
|
||||||
|
|
||||||
|
| target | entry points |
|
||||||
|
|---|---|
|
||||||
|
| `ratchet_frame` | `ratchet::RatchetState::from_bytes`, `RatchetState::decrypt` (the `rat ` frame parser) |
|
||||||
|
| `qr_decode` | `qr::decode` (pasted/scanned invite strings) |
|
||||||
|
| `dispatch_classify` | `dispatch::classify` (routes a `rat ` frame to the ratchet parser) |
|
||||||
|
| `file_decode` | `file::decode` (`fil ` chunk frames) |
|
||||||
|
|
||||||
|
Nothing in `src/` changes for this: every target calls the shipped public API.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
rustup toolchain install nightly --profile minimal
|
||||||
|
cargo install cargo-fuzz
|
||||||
|
scripts/run-fuzz.sh # all four, 60s each
|
||||||
|
FUZZ_SECS=300 scripts/run-fuzz.sh ratchet_frame
|
||||||
|
```
|
||||||
|
|
||||||
|
`fuzz/corpus/` is gitignored (libFuzzer grows it locally); `fuzz/seeds/` is
|
||||||
|
committed and copied in by the script. Crash reproducers land in
|
||||||
|
`fuzz/artifacts/<target>/`. Needs rustup's `cargo` on `PATH` — the `+nightly`
|
||||||
|
directive does not work through a distro `cargo` package.
|
||||||
26
fuzz/fuzz_targets/dispatch_classify.rs
Normal file
26
fuzz/fuzz_targets/dispatch_classify.rs
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
//! Untrusted decrypted plaintext against the application dispatch classifier.
|
||||||
|
//!
|
||||||
|
//! `dispatch::classify` runs on every inbound message before anything else
|
||||||
|
//! looks at it, and its `Ratchet` arm is what routes a `rat `-prefixed message
|
||||||
|
//! into the ratchet parser (`src/ratchet.rs` `Frame::parse`). It takes raw
|
||||||
|
//! bytes — never a `&str` — so all 255 byte values are in scope, and it must
|
||||||
|
//! classify (or `Drop`) every input without panicking.
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
use onionwire::dispatch::{self, Kind};
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let kind = dispatch::classify(data);
|
||||||
|
|
||||||
|
// Total and deterministic: every input maps to exactly one variant, and the
|
||||||
|
// answer is stable across calls (no interior state, no ordering dependence).
|
||||||
|
assert_eq!(kind, dispatch::classify(data));
|
||||||
|
|
||||||
|
// The routing invariant that matters: the `rat ` prefix is never shadowed by
|
||||||
|
// the `[a-z]{3} ` catch-all, so a ratchet frame always reaches the ratchet
|
||||||
|
// parser rather than being dropped as an unknown prefix.
|
||||||
|
if data.starts_with(b"rat ") {
|
||||||
|
assert_eq!(kind, Kind::Ratchet);
|
||||||
|
}
|
||||||
|
});
|
||||||
26
fuzz/fuzz_targets/file_decode.rs
Normal file
26
fuzz/fuzz_targets/file_decode.rs
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
//! Untrusted file-chunk bytes against the chunk decoder.
|
||||||
|
//!
|
||||||
|
//! A peer can send a `fil ` chunk at any time; `file::decode` header-parses it
|
||||||
|
//! (hex transfer id, filename, hex sha256, `idx/total`, then the payload) before
|
||||||
|
//! anything is written to disk. It must return `None` for every malformed
|
||||||
|
//! chunk and never panic — including on absurd `idx`/`total` and on filenames
|
||||||
|
//! that fail `safe_name`.
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
use onionwire::file;
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
if let Some(chunk) = file::decode(data) {
|
||||||
|
// A chunk it accepted must survive an encode round-trip and decode
|
||||||
|
// back to the same header, byte for byte.
|
||||||
|
let re = file::encode(&chunk);
|
||||||
|
let again = file::decode(&re).expect("encoded chunk must decode");
|
||||||
|
assert_eq!(again.xfer_id, chunk.xfer_id);
|
||||||
|
assert_eq!(again.filename, chunk.filename);
|
||||||
|
assert_eq!(again.sha256, chunk.sha256);
|
||||||
|
assert_eq!(again.idx, chunk.idx);
|
||||||
|
assert_eq!(again.total, chunk.total);
|
||||||
|
assert_eq!(again.data, chunk.data);
|
||||||
|
}
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue