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 |
76 changed files with 8281 additions and 2493 deletions
|
|
@ -398,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:
|
||||||
|
|
|
||||||
|
|
@ -57,7 +57,7 @@ env:
|
||||||
# feature 'vec_deque_pop_if'`, after the job has already built the rest of
|
# 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
|
# 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
|
# and in the Android workflows. `--no-default-features` still builds on 1.91
|
||||||
# (Arti 0.46's floor); the default build does not, so the image follows the
|
# (Arti 0.49's floor); the default build does not, so the image follows the
|
||||||
# default build.
|
# default build.
|
||||||
RUST_IMAGE: rust:1.98-bookworm
|
RUST_IMAGE: rust:1.98-bookworm
|
||||||
CARGO_REGISTRY_VOLUME: onionwire-cargo-registry
|
CARGO_REGISTRY_VOLUME: onionwire-cargo-registry
|
||||||
|
|
|
||||||
|
|
@ -416,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.
|
||||||
|
|
@ -446,49 +450,13 @@ jobs:
|
||||||
with:
|
with:
|
||||||
path: artifacts
|
path: artifacts
|
||||||
|
|
||||||
- name: Sign the release assets (minisign, fail closed)
|
- name: Stage both arch artifacts into dist
|
||||||
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:
|
|
||||||
MINISIGN_SECRET_KEY: ${{ secrets.MINISIGN_SECRET_KEY }}
|
|
||||||
RELEASE_TAG: ${{ needs.version.outputs.tag }}
|
|
||||||
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
|
|
||||||
# minisign comes from the same pinned image the builds used, so our
|
|
||||||
# signature and the verifier's check are the same implementation.
|
|
||||||
docker run --rm \
|
|
||||||
-v "${GITHUB_WORKSPACE}:/work" \
|
|
||||||
-e MINISIGN_SECRET_KEY \
|
|
||||||
-e RELEASE_TAG \
|
|
||||||
-w /work \
|
|
||||||
"$RUST_IMAGE" \
|
|
||||||
bash -c 'apt-get update -qq && apt-get install -y -qq --no-install-recommends minisign >/dev/null \
|
|
||||||
&& bash .ci-tools/scripts/sign-release.sh \
|
|
||||||
dist/onionwire-aarch64-unknown-linux-gnu \
|
|
||||||
dist/onionwire-aarch64-unknown-linux-gnu.sha256 \
|
|
||||||
dist/onionwire-x86_64-unknown-linux-gnu \
|
|
||||||
dist/onionwire-x86_64-unknown-linux-gnu.sha256'
|
|
||||||
# The public key ships as an asset too, so a verifier can get it from
|
|
||||||
# the release; getting it from the repo instead is stronger, and
|
|
||||||
# docs/VERIFY.md says so.
|
|
||||||
cp .ci-tools/scripts/onionwire-signing.pub dist/onionwire-signing.pub
|
|
||||||
|
|
||||||
- name: Publish both binaries to one release
|
|
||||||
if: needs.version.outputs.dry_run != 'true' && needs.aarch64.result == 'success' && needs.x86_64.result == 'success'
|
|
||||||
env:
|
|
||||||
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
|
|
||||||
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
|
||||||
TAG: ${{ needs.version.outputs.tag }}
|
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
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
|
mkdir -p dist
|
||||||
find artifacts -type f -print
|
find artifacts -type f -print
|
||||||
for target in aarch64-unknown-linux-gnu x86_64-unknown-linux-gnu; do
|
for target in aarch64-unknown-linux-gnu x86_64-unknown-linux-gnu; do
|
||||||
|
|
@ -502,6 +470,82 @@ jobs:
|
||||||
cp "$src" "dist/$name"
|
cp "$src" "dist/$name"
|
||||||
done
|
done
|
||||||
done
|
done
|
||||||
|
ls -l dist
|
||||||
|
|
||||||
|
- name: Sign the release assets (minisign, fail closed)
|
||||||
|
if: needs.version.outputs.dry_run != 'true' && needs.aarch64.result == 'success' && needs.x86_64.result == 'success'
|
||||||
|
env:
|
||||||
|
MINISIGN_SECRET_KEY: ${{ secrets.MINISIGN_SECRET_KEY }}
|
||||||
|
RELEASE_TAG: ${{ needs.version.outputs.tag }}
|
||||||
|
SIGN_VOLUME: onionwire-sign-${{ github.run_id }}
|
||||||
|
SIGN_CONTAINER: onionwire-sign-${{ github.run_id }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
# Signing runs BEFORE publish on purpose. A run without the key stops
|
||||||
|
# here, so nothing unsigned ever reaches the release page: an unsigned
|
||||||
|
# release is indistinguishable from a signed one to anyone who is not
|
||||||
|
# checking, which makes it worse than no release at all.
|
||||||
|
if [ -z "${MINISIGN_SECRET_KEY:-}" ]; then
|
||||||
|
echo "MINISIGN_SECRET_KEY is not set — add it in Settings -> Actions -> Secrets." >&2
|
||||||
|
echo "See docs/VERIFY.md, \"Maintainer: the signing key\"." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
# NO `-v "${GITHUB_WORKSPACE}:/work"`: GITHUB_WORKSPACE is a path
|
||||||
|
# INSIDE this job container, but docker resolves a bind mount's source
|
||||||
|
# on the HOST, where it does not exist. Docker then creates an empty
|
||||||
|
# /work and the sign script is simply absent (run 768: "bash:
|
||||||
|
# .ci-tools/scripts/sign-release.sh: No such file or directory").
|
||||||
|
# Same pattern as the build jobs: named volume + docker cp in/out.
|
||||||
|
# minisign still comes from the same pinned image the builds used, so
|
||||||
|
# our signature and the verifier's check are the same implementation.
|
||||||
|
cleanup() {
|
||||||
|
docker rm -f "$SIGN_CONTAINER" >/dev/null 2>&1 || true
|
||||||
|
docker volume rm "$SIGN_VOLUME" >/dev/null 2>&1 || true
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
docker volume create "$SIGN_VOLUME" >/dev/null
|
||||||
|
docker rm -f "$SIGN_CONTAINER" >/dev/null 2>&1 || true
|
||||||
|
docker create --name "$SIGN_CONTAINER" \
|
||||||
|
-e MINISIGN_SECRET_KEY \
|
||||||
|
-e RELEASE_TAG \
|
||||||
|
-v "$SIGN_VOLUME:/work" \
|
||||||
|
-w /work \
|
||||||
|
"$RUST_IMAGE" \
|
||||||
|
bash -c 'apt-get update -qq && apt-get install -y -qq --no-install-recommends minisign >/dev/null \
|
||||||
|
&& bash /work/scripts/sign-release.sh \
|
||||||
|
/work/dist/onionwire-aarch64-unknown-linux-gnu \
|
||||||
|
/work/dist/onionwire-aarch64-unknown-linux-gnu.sha256 \
|
||||||
|
/work/dist/onionwire-x86_64-unknown-linux-gnu \
|
||||||
|
/work/dist/onionwire-x86_64-unknown-linux-gnu.sha256'
|
||||||
|
docker cp .ci-tools/scripts "$SIGN_CONTAINER:/work/scripts"
|
||||||
|
docker cp dist/. "$SIGN_CONTAINER:/work/dist/"
|
||||||
|
docker start -a "$SIGN_CONTAINER"
|
||||||
|
docker cp "$SIGN_CONTAINER:/work/dist/." dist/
|
||||||
|
# Verify the signatures came back out before anything is published.
|
||||||
|
for f in \
|
||||||
|
dist/onionwire-aarch64-unknown-linux-gnu.minisig \
|
||||||
|
dist/onionwire-aarch64-unknown-linux-gnu.sha256.minisig \
|
||||||
|
dist/onionwire-x86_64-unknown-linux-gnu.minisig \
|
||||||
|
dist/onionwire-x86_64-unknown-linux-gnu.sha256.minisig
|
||||||
|
do
|
||||||
|
[ -s "$f" ] || { echo "signing produced no $f" >&2; exit 1; }
|
||||||
|
done
|
||||||
|
# The public key ships as an asset too, so a verifier can get it from
|
||||||
|
# the release; getting it from the repo instead is stronger, and
|
||||||
|
# docs/VERIFY.md says so.
|
||||||
|
cp .ci-tools/scripts/onionwire-signing.pub dist/onionwire-signing.pub
|
||||||
|
|
||||||
|
- name: Publish both binaries to one release
|
||||||
|
if: needs.version.outputs.dry_run != 'true' && needs.aarch64.result == 'success' && needs.x86_64.result == 'success'
|
||||||
|
env:
|
||||||
|
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
|
||||||
|
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||||
|
TAG: ${{ needs.version.outputs.tag }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
# dist/ is staged and signed by the two steps above; this step only
|
||||||
|
# refuses to upload a hole in it.
|
||||||
|
find dist -type f -print
|
||||||
missing=0
|
missing=0
|
||||||
for f in \
|
for f in \
|
||||||
dist/onionwire-aarch64-unknown-linux-gnu \
|
dist/onionwire-aarch64-unknown-linux-gnu \
|
||||||
|
|
|
||||||
790
Cargo.lock
generated
790
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
14
Cargo.toml
14
Cargo.toml
|
|
@ -2,7 +2,7 @@
|
||||||
name = "onionwire"
|
name = "onionwire"
|
||||||
version = "0.2.1"
|
version = "0.2.1"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
# 1.98, not 1.91. Arti 0.46 builds on 1.91, but the default feature set includes
|
# 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
|
# `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
|
# `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`
|
# the Android workflows actually build that graph with. `--no-default-features`
|
||||||
|
|
@ -36,26 +36,26 @@ rustls = ["arti-client/rustls"]
|
||||||
# Cuprate's own `arti` feature stays OFF (and is off in its default feature set,
|
# 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
|
# 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
|
# second, older Tor stack (arti-client 0.44, which cannot unify with this
|
||||||
# crate's 0.46) next to OnionWire's. The in-process daemon runs clearnet-only;
|
# 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.
|
# OnionWire's Arti is the only Tor in the process.
|
||||||
cuprate-daemon = ["dep:cuprated", "dep:toml"]
|
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
|
# Direct dependency only to select rustls's crypto provider: Arti pulls rustls in
|
||||||
# through `tor-rtcompat` with `default-features = false`, and rustls 0.23
|
# 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
|
# resolves its provider from its OWN `ring`/`aws-lc-rs` features, so without this
|
||||||
|
|
|
||||||
22
README.md
22
README.md
|
|
@ -3,7 +3,7 @@
|
||||||
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 an ed25519 public key; the onion is only a locator.
|
No hosted server. Identity is an ed25519 public key; the onion is only a locator.
|
||||||
|
|
||||||
Current tagged release: **v0.5.0**. Linux TUI + Android SDK/APK. Two people add
|
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;
|
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.
|
~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
|
Chat is Noise IK over your own v3 onion; when the friend was added from a v2
|
||||||
|
|
@ -61,8 +61,8 @@ resulting hash) next to its `.sha256`.
|
||||||
**x86_64:**
|
**x86_64:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.5.0/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.5.0/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
|
||||||
|
|
@ -71,8 +71,8 @@ chmod +x onionwire-x86_64-unknown-linux-gnu
|
||||||
**aarch64:**
|
**aarch64:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.5.0/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.5.0/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
|
||||||
|
|
@ -103,7 +103,7 @@ format (`<hash> onionwire-<target>`).
|
||||||
### Option B — build from source
|
### Option B — build from source
|
||||||
|
|
||||||
Needs [Rust](https://rustup.rs/) **1.98+** (`edition = "2024"`; `Cargo.toml`
|
Needs [Rust](https://rustup.rs/) **1.98+** (`edition = "2024"`; `Cargo.toml`
|
||||||
`rust-version = "1.98"`). Arti 0.46 itself builds on 1.91, but the default
|
`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
|
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`.
|
(`tapes` calls `VecDeque::pop_front_if`, stable since 1.93). Do not install `tor`.
|
||||||
|
|
||||||
|
|
@ -134,7 +134,7 @@ system OpenSSL headers or `pkg-config` are required — Arti's TLS backend is
|
||||||
`rustls`.
|
`rustls`.
|
||||||
|
|
||||||
The crate version in `Cargo.toml` is **not** bumped by the release workflow. The
|
The crate version in `Cargo.toml` is **not** bumped by the release workflow. The
|
||||||
tag (`v0.5.0`) is the version users download; `onionwire --version` prints
|
tag (`v0.7.0`) is the version users download; `onionwire --version` prints
|
||||||
`CARGO_PKG_VERSION` from the tree that was built.
|
`CARGO_PKG_VERSION` from the tree that was built.
|
||||||
|
|
||||||
### Two instances on one machine
|
### Two instances on one machine
|
||||||
|
|
@ -433,7 +433,9 @@ invites interoperate.
|
||||||
- **SDK** — `onionwire-sdk-<version>.aar`. UniFFI Kotlin over the same Rust crate
|
- **SDK** — `onionwire-sdk-<version>.aar`. UniFFI Kotlin over the same Rust crate
|
||||||
the TUI runs. 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.
|
- **APK** — `onionwire-<version>-android-arm64-v8a.apk`. Kotlin + Jetpack Compose.
|
||||||
Build notes: [android/README.md](android/README.md).
|
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.
|
||||||
|
|
||||||
The APK build is amd64-only. After the Linux `release` workflow finishes,
|
The APK build is amd64-only. After the Linux `release` workflow finishes,
|
||||||
dispatch `android-release` with that tag so the APK/AAR attach to the same
|
dispatch `android-release` with that tag so the APK/AAR attach to the same
|
||||||
|
|
@ -441,7 +443,7 @@ Forgejo release.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
scripts/build-android-local.sh # -> dist/, with .sha256
|
scripts/build-android-local.sh # -> dist/, with .sha256
|
||||||
PUBLISH_TAG=v0.5.0 scripts/build-android-local.sh # + upload to that release
|
PUBLISH_TAG=v0.7.0 scripts/build-android-local.sh # + upload to that release
|
||||||
```
|
```
|
||||||
|
|
||||||
## Releases (maintainers)
|
## Releases (maintainers)
|
||||||
|
|
@ -461,7 +463,7 @@ Actions → **release** → Run workflow:
|
||||||
Then dispatch **android-release** with `tag=<that tag>` to attach the APK + AAR.
|
Then dispatch **android-release** with `tag=<that tag>` to attach the APK + AAR.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
FORGEJO_TOKEN=<pat> scripts/build-release-local.sh v0.5.0
|
FORGEJO_TOKEN=<pat> scripts/build-release-local.sh v0.7.0
|
||||||
```
|
```
|
||||||
|
|
||||||
Do not run `cargo publish`; `publish = false`.
|
Do not run `cargo publish`; `publish = false`.
|
||||||
|
|
|
||||||
|
|
@ -344,6 +344,20 @@ 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**
|
(`rust-version = "1.98"`). Job timeout is **90** minutes on `android-release.yml` and **120**
|
||||||
on `android-ci.yml`.
|
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
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
@ -363,25 +377,33 @@ android/
|
||||||
build.gradle.kts
|
build.gradle.kts
|
||||||
src/main/AndroidManifest.xml
|
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 # UI-side Wire handle; wallet-child poller
|
WireViewModel.kt # UI-side Wire handle; wallet-child poller
|
||||||
crypto/ # Keystore-wrapped store passphrase
|
crypto/ # Keystore-wrapped store passphrase
|
||||||
keepalive/ # NodeHost, KeepAliveService, policy, lifetime
|
keepalive/ # NodeHost, KeepAliveService, policy, lifetime
|
||||||
wallet/ # ChainStorage, WalletChildBinaries
|
wallet/ # ChainStorage, WalletChildBinaries
|
||||||
ui/ # Compose screens (M3)
|
ui/ # Compose screens (M3)
|
||||||
|
components/ # design system: OwButton, OwSegmentedControl,
|
||||||
|
# OwAlertBanner, OwCard, OwTopBar, OwBottomTabBar,
|
||||||
|
# OwConfirmDialog, OwQrCode, Identicon
|
||||||
WalletScreen.kt
|
WalletScreen.kt
|
||||||
|
WalletManagerScreen.kt
|
||||||
WalletChildStatusText.kt
|
WalletChildStatusText.kt
|
||||||
ChatScreen.kt
|
ChatScreen.kt
|
||||||
RosterScreen.kt
|
RosterScreen.kt # Chats tab: identity bar + roster
|
||||||
InviteScreens.kt
|
SettingsScreen.kt # Node & Settings tab
|
||||||
|
ProfileScreen.kt
|
||||||
|
InviteScreens.kt # share (QR + text) and paste-a-contact
|
||||||
InviteAddFlow.kt
|
InviteAddFlow.kt
|
||||||
OutboxDetail.kt
|
OutboxDetail.kt
|
||||||
MessageDelivery.kt
|
MessageDelivery.kt
|
||||||
UnlockScreen.kt
|
UnlockScreen.kt
|
||||||
UnlockSubmit.kt
|
UnlockSubmit.kt
|
||||||
|
SeedBackupGate.kt
|
||||||
RotateScreen.kt
|
RotateScreen.kt
|
||||||
Insets.kt
|
Insets.kt # systemBars ∪ ime, minus the tab-bar inset
|
||||||
Theme.kt
|
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/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
|
src/main/jniLibs/arm64-v8a/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,37 +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.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.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(
|
||||||
|
|
@ -61,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() }
|
||||||
|
|
@ -87,36 +111,113 @@ 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
|
||||||
|
// status bar from being padded twice and leaves the only inset this
|
||||||
|
// level owns — the tab bar's height — in `pad`.
|
||||||
|
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
||||||
|
containerColor = MaterialTheme.colorScheme.background,
|
||||||
|
bottomBar = {
|
||||||
|
if (tab != null) {
|
||||||
|
OwBottomTabBar(selected = tab, onSelect = { nav.selectTab(it) })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) { pad ->
|
||||||
|
CompositionLocalProvider(LocalBottomBarPresent provides (tab != null)) {
|
||||||
|
NavHost(
|
||||||
|
navController = nav,
|
||||||
|
startDestination = Routes.Chats,
|
||||||
|
modifier = Modifier.padding(bottom = pad.calculateBottomPadding()),
|
||||||
|
) {
|
||||||
|
composable(Routes.Chats) {
|
||||||
RosterScreen(
|
RosterScreen(
|
||||||
fingerprint = ready.fingerprint,
|
fingerprint = ready.fingerprint,
|
||||||
onion = ready.onion,
|
|
||||||
sdkVersion = ready.sdkVersion,
|
|
||||||
friends = friends,
|
friends = friends,
|
||||||
keepAliveNote = keepAliveNote,
|
invite = vm::invite,
|
||||||
onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") },
|
onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") },
|
||||||
onShare = { nav.navigate("share") },
|
onShare = { nav.navigate(Routes.Share) },
|
||||||
onPaste = { nav.navigate("paste") },
|
onPaste = { nav.navigate(Routes.Paste) },
|
||||||
onRotate = { nav.navigate("rotate") },
|
onRotate = { nav.navigate(Routes.Rotate) },
|
||||||
onWipe = { scope.launch { vm.wipeMessages() } },
|
onWipe = { scope.launch { vm.wipeMessages() } },
|
||||||
onOpenProfile = { nav.navigate("profile") },
|
onOpenProfile = { nav.navigate(Routes.Profile) },
|
||||||
onLock = vm::lock,
|
onLock = vm::lock,
|
||||||
onOpenWallet = { nav.navigate("wallet") },
|
onOpenWallets = { nav.navigate(Routes.Wallets) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
composable("share") {
|
composable(Routes.Wallet) {
|
||||||
|
// A top-level tab, so no back chevron — same shape as the
|
||||||
|
// Chats and Node & Settings destinations. The catalogue
|
||||||
|
// sub-screen still gets one from its own top bar.
|
||||||
|
WalletScreen(
|
||||||
|
vm = vm,
|
||||||
|
onOpenWallets = { nav.navigate(Routes.Wallets) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
composable(Routes.Settings) {
|
||||||
|
SettingsScreen(
|
||||||
|
sdkVersion = ready.sdkVersion,
|
||||||
|
keepAliveNote = keepAliveNote,
|
||||||
|
onOpenProfile = { nav.navigate(Routes.Profile) },
|
||||||
|
onOpenWallets = { nav.navigate(Routes.Wallets) },
|
||||||
|
onRotate = { nav.navigate(Routes.Rotate) },
|
||||||
|
onWipe = { scope.launch { vm.wipeMessages() } },
|
||||||
|
onLock = vm::lock,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
composable(Routes.Share) {
|
||||||
ShareInviteScreen(ownerInvite = vm::invite, onBack = { nav.popBackStack() })
|
ShareInviteScreen(ownerInvite = vm::invite, onBack = { nav.popBackStack() })
|
||||||
}
|
}
|
||||||
|
|
||||||
composable("paste") {
|
composable(Routes.Paste) {
|
||||||
PasteInviteScreen(
|
PasteInviteScreen(
|
||||||
onDecode = vm::decode,
|
onDecode = vm::decode,
|
||||||
onAdd = vm::addFriend,
|
onAdd = vm::addFriend,
|
||||||
|
|
@ -124,7 +225,7 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
composable("rotate") {
|
composable(Routes.Rotate) {
|
||||||
RotateScreen(
|
RotateScreen(
|
||||||
currentOnion = ready.onion,
|
currentOnion = ready.onion,
|
||||||
onRotate = {
|
onRotate = {
|
||||||
|
|
@ -135,27 +236,19 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
composable("wallet") {
|
composable(Routes.Wallets) {
|
||||||
WalletScreen(
|
|
||||||
vm = vm,
|
|
||||||
onBack = { nav.popBackStack() },
|
|
||||||
onOpenWallets = { nav.navigate("wallets") },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
composable("wallets") {
|
|
||||||
WalletManagerScreen(vm = vm, onBack = { nav.popBackStack() })
|
WalletManagerScreen(vm = vm, onBack = { nav.popBackStack() })
|
||||||
}
|
}
|
||||||
|
|
||||||
composable("profile") {
|
composable(Routes.Profile) {
|
||||||
ProfileScreen(vm = vm, onBack = { nav.popBackStack() })
|
ProfileScreen(vm = vm, onBack = { nav.popBackStack() })
|
||||||
}
|
}
|
||||||
|
|
||||||
composable(
|
composable(
|
||||||
route = "chat/{pk}",
|
route = Routes.Chat,
|
||||||
arguments = listOf(navArgument("pk") { type = NavType.StringType }),
|
arguments = listOf(navArgument("pk") { type = NavType.StringType }),
|
||||||
) { entry ->
|
) { chatEntry ->
|
||||||
val pk = entry.arguments?.getString("pk").orEmpty()
|
val pk = chatEntry.arguments?.getString("pk").orEmpty()
|
||||||
val friend = friends.firstOrNull { it.pubkeyHex == pk }
|
val friend = friends.firstOrNull { it.pubkeyHex == pk }
|
||||||
ChatScreen(
|
ChatScreen(
|
||||||
vm = vm,
|
vm = vm,
|
||||||
|
|
@ -170,3 +263,15 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,9 @@ 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.SeedBackupGate
|
||||||
import com.siriusdevops.onionwire.ui.WalletKeyOrigin
|
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.ui.walletFailureText
|
||||||
import com.siriusdevops.onionwire.wallet.ChainStorage
|
import com.siriusdevops.onionwire.wallet.ChainStorage
|
||||||
import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE
|
import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE
|
||||||
|
|
@ -1015,10 +1018,72 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
*/
|
*/
|
||||||
fun chainFreeBytes(): Long? = ChainStorage.freeBytes(home)
|
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
|
* Kick off start on [viewModelScope] so leaving the composition does not
|
||||||
* cancel Cuprate launch. Returns immediately; watch [walletChildStarting]
|
* cancel Cuprate launch. Returns immediately; watch [walletChildStarting]
|
||||||
* and [walletChildError]. Core status stays `off` until the node answers.
|
* 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() {
|
fun startWalletChild() {
|
||||||
if (!startInFlight.compareAndSet(false, true)) return
|
if (!startInFlight.compareAndSet(false, true)) return
|
||||||
|
|
@ -1026,6 +1091,20 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
_walletChildError.value = null
|
_walletChildError.value = null
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
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) {
|
val started = withContext(Dispatchers.IO) {
|
||||||
runCatching { requireWire().startWalletChild() }
|
runCatching { requireWire().startWalletChild() }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
try {
|
val store = try {
|
||||||
keyStore().deleteEntry(ALIAS)
|
keyStore()
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
// Nothing usable to delete.
|
return
|
||||||
|
}
|
||||||
|
for (alias in listOf(ALIAS_UNLOCK_GATED, ALIAS)) {
|
||||||
|
try {
|
||||||
|
store.deleteEntry(alias)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// Nothing usable to delete under that alias.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun existingKey(): SecretKey? {
|
// ---------------------------------------------------------------- report
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What can honestly be said about the device-unlock gate on the live key.
|
||||||
|
* See the class doc: there is no platform getter for the flag itself.
|
||||||
|
*/
|
||||||
|
fun unlockGateReport(): UnlockGateReport {
|
||||||
|
val active = activeKey()
|
||||||
|
return UnlockGateReport(
|
||||||
|
supported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P,
|
||||||
|
sdkInt = Build.VERSION.SDK_INT,
|
||||||
|
keyIsUnlockGated = active?.gated == true,
|
||||||
|
legacyKeyPending = existingKey(ALIAS) != null,
|
||||||
|
backing = if (active == null) KeyBacking.UNKNOWN else backing(),
|
||||||
|
gateRefusal = gateRefusal,
|
||||||
|
migrationFailure = migrationFailure,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun logBranch(branch: String) {
|
||||||
|
Log.i(
|
||||||
|
TAG,
|
||||||
|
"wrap key: branch=$branch sdk=${Build.VERSION.SDK_INT} " +
|
||||||
|
"manufacturer=${Build.MANUFACTURER} model=${Build.MODEL}",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --------------------------------------------------- PassphraseKeyMigration
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the key [seal] just wrapped with is the unlock-gated one. False
|
||||||
|
* on API 26–27 and on a device whose Keystore refused the flag — in both
|
||||||
|
* cases there is nothing to migrate to, and the caller must not delete the
|
||||||
|
* pre-gate key.
|
||||||
|
*/
|
||||||
|
override fun unlockGateInEffect(): Boolean =
|
||||||
|
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && existingKey(ALIAS_UNLOCK_GATED) != null
|
||||||
|
|
||||||
|
override fun legacyKeyPending(): Boolean = existingKey(ALIAS) != null
|
||||||
|
|
||||||
|
/** Decrypts [blob] with the unlock-gated key alone — never the fallback. */
|
||||||
|
override fun openWithUnlockGate(blob: ByteArray): CharArray {
|
||||||
|
val key = existingKey(ALIAS_UNLOCK_GATED)
|
||||||
|
?: throw SecretUnavailable("no unlock-gated key exists to prove the blob against")
|
||||||
|
return try {
|
||||||
|
StoreSecret.open(key, blob)
|
||||||
|
} catch (e: SecretUnavailable) {
|
||||||
|
throw gateMessage(e, gatedKeyInPlay = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes [ALIAS]. [StoredPassphraseStore] calls this only after the
|
||||||
|
* replacement blob is on disk and has been opened back under the new key;
|
||||||
|
* a blob wrapped by this alias becomes undecryptable the moment it runs.
|
||||||
|
*/
|
||||||
|
override fun retireLegacyKey() {
|
||||||
|
if (!legacyKeyPending()) return
|
||||||
|
try {
|
||||||
|
keyStore().deleteEntry(ALIAS)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
noteMigrationFailure("could not delete the pre-gate key under $ALIAS (${e.message})")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (cached?.gated == false) cached = null
|
||||||
|
Log.i(TAG, "retired the pre-gate Keystore key under $ALIAS; only $ALIAS_UNLOCK_GATED remains")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun noteMigrationFailure(reason: String) {
|
||||||
|
migrationFailure = reason
|
||||||
|
Log.w(TAG, "unlock-gated key migration did not complete: $reason (blob and pre-gate key kept)")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ keys
|
||||||
|
|
||||||
|
private class ActiveKey(val secret: SecretKey, val gated: Boolean)
|
||||||
|
|
||||||
|
/** Existing key we would decrypt with, unlock-gated first. Never creates. */
|
||||||
|
private fun activeKey(): ActiveKey? {
|
||||||
cached?.let { return it }
|
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 } }
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The key [seal] uses. Prefers the unlock-gated alias (creating it if the
|
||||||
|
* platform allows), which is what turns a pre-gate install into a gated one
|
||||||
|
* the next time a passphrase is stored.
|
||||||
|
*/
|
||||||
|
private fun keyForSeal(): ActiveKey {
|
||||||
|
val active = activeKey()
|
||||||
|
if (active?.gated == true) return active
|
||||||
|
return gatedKeyOrCreate() ?: active ?: legacyKeyOrCreate()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun gatedKeyOrCreate(): ActiveKey? {
|
||||||
|
cached?.let { if (it.gated) return it }
|
||||||
|
existingKey(ALIAS_UNLOCK_GATED)?.let { return ActiveKey(it, gated = true).also { k -> cached = k } }
|
||||||
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return null
|
||||||
|
// One attempt per process: a Keystore that refused the flag will refuse
|
||||||
|
// it again, and unlock must not retry key generation on every call.
|
||||||
|
if (gateRefusal != null) return null
|
||||||
|
return try {
|
||||||
|
val key = generateWithFallback(ALIAS_UNLOCK_GATED, unlockGated = true)
|
||||||
|
logBranch("unlock-gated alias=$ALIAS_UNLOCK_GATED")
|
||||||
|
ActiveKey(key, gated = true).also { cached = it }
|
||||||
|
} catch (e: GeneralSecurityException) {
|
||||||
|
recordGateRefusal(e)
|
||||||
|
null
|
||||||
|
} catch (e: ProviderException) {
|
||||||
|
recordGateRefusal(e)
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun legacyKeyOrCreate(): ActiveKey {
|
||||||
|
cached?.let { if (!it.gated) return it }
|
||||||
|
existingKey(ALIAS)?.let { return ActiveKey(it, gated = false).also { k -> cached = k } }
|
||||||
|
val key = generateWithFallback(ALIAS, unlockGated = false)
|
||||||
|
logBranch(
|
||||||
|
"ungated alias=$ALIAS" +
|
||||||
|
(gateRefusal?.let { " (unlock gate refused: $it)" } ?: ""),
|
||||||
|
)
|
||||||
|
return ActiveKey(key, gated = false).also { cached = it }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun recordGateRefusal(e: Exception) {
|
||||||
|
gateRefusal = "${e.javaClass.simpleName}: ${e.message}"
|
||||||
|
Log.w(
|
||||||
|
TAG,
|
||||||
|
"Keystore refused setUnlockedDeviceRequired(true) under $ALIAS_UNLOCK_GATED; " +
|
||||||
|
"falling back to the pre-gate alias $ALIAS (=$gateRefusal) " +
|
||||||
|
"sdk=${Build.VERSION.SDK_INT} manufacturer=${Build.MANUFACTURER} model=${Build.MODEL}",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun existingKey(alias: String): SecretKey? = try {
|
||||||
|
keyStore().getKey(alias, null) as? SecretKey
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
cached = key
|
|
||||||
return key
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun loadOrCreateKey(): SecretKey = cached ?: existingKey() ?: createKey()
|
private fun strongBoxAdvertised(): Boolean =
|
||||||
|
|
||||||
private fun createKey(): SecretKey {
|
|
||||||
val strongBoxAdvertised =
|
|
||||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
|
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
|
||||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
||||||
if (strongBoxAdvertised) {
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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(
|
||||||
|
text = if (copied) "Copied" else "Copy invite",
|
||||||
|
onClick = {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
clipboard.setClipEntry(
|
val clip = ClipData.newPlainText("onionwire invite", payload)
|
||||||
ClipEntry(ClipData.newPlainText("onionwire invite", invite!!)),
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
)
|
clip.description.extras = PersistableBundle().apply {
|
||||||
|
putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
clipboard.setClipEntry(ClipEntry(clip))
|
||||||
copied = true
|
copied = true
|
||||||
}
|
}
|
||||||
}) { Text(if (copied) "Copied" else "Copy") }
|
},
|
||||||
}
|
leadingIconRes = R.drawable.ic_ow_copy,
|
||||||
Spacer(Modifier.height(20.dp))
|
|
||||||
Text("What is in it", style = MaterialTheme.typography.titleSmall)
|
|
||||||
Spacer(Modifier.height(6.dp))
|
|
||||||
Mono("k ed25519 identity pubkey — who you are")
|
|
||||||
Mono("o current onion locator — where you are now")
|
|
||||||
Mono("spk x25519 signed prekey — session start material")
|
|
||||||
Mono("sig signature over k‖o‖spk — reject if it fails")
|
|
||||||
Spacer(Modifier.height(12.dp))
|
|
||||||
Text(
|
|
||||||
"The onion in here goes stale when you rotate. The key does not. " +
|
|
||||||
"If you re-share later, the same k updates their entry — it never " +
|
|
||||||
"creates a second friend.",
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
)
|
||||||
|
OwButton(
|
||||||
|
text = "Done",
|
||||||
|
variant = OwButtonVariant.Outline,
|
||||||
|
onClick = onBack,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(24.dp))
|
||||||
|
OwCard(Modifier.fillMaxWidth()) {
|
||||||
|
Text(
|
||||||
|
"What is in it",
|
||||||
|
style = MaterialTheme.typography.titleSmall,
|
||||||
|
color = OwColors.TextPrimary,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
InviteField("k", "ed25519 identity pubkey — who you are")
|
||||||
|
InviteField("o", "current onion locator — where you are now")
|
||||||
|
InviteField("spk", "x25519 signed prekey — session start material")
|
||||||
|
InviteField("sig", "signature over k‖o‖spk — reject if it fails")
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
OwDivider()
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
Text(
|
||||||
|
"The onion in here goes stale when you rotate. The key does " +
|
||||||
|
"not. If you re-share later, the same k updates their entry — " +
|
||||||
|
"it never creates a second friend.",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = OwColors.TextSecondary,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(24.dp))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@Composable
|
||||||
|
private fun InviteField(key: String, meaning: String) {
|
||||||
|
Row(Modifier.padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text(
|
||||||
|
key,
|
||||||
|
style = MonoStyle.copy(color = OwColors.Accent),
|
||||||
|
modifier = Modifier.padding(end = 10.dp),
|
||||||
|
)
|
||||||
|
Label(meaning)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paste someone else's invite.
|
||||||
|
*
|
||||||
|
* Verification is a separate, explicit step from adding: the preview shows who
|
||||||
|
* they are and where they are reachable *before* anything is written to the
|
||||||
|
* roster, because a mistyped or swapped invite is the one thing a human can
|
||||||
|
* still catch.
|
||||||
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun PasteInviteScreen(
|
fun PasteInviteScreen(
|
||||||
onDecode: suspend (String) -> InviteInfo,
|
onDecode: suspend (String) -> InviteInfo,
|
||||||
|
|
@ -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(
|
|
||||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
|
||||||
),
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
) {
|
|
||||||
Column(Modifier.padding(12.dp)) {
|
|
||||||
Label("THEY ARE")
|
Label("THEY ARE")
|
||||||
Mono(p.pubkeyHex)
|
Spacer(Modifier.height(2.dp))
|
||||||
Spacer(Modifier.height(8.dp))
|
Mono(shortId(p.pubkeyHex, head = 12, tail = 8))
|
||||||
|
Spacer(Modifier.height(6.dp))
|
||||||
Text(
|
Text(
|
||||||
"fingerprint ${p.pubkeyHex.take(16)}… — compare this with them " +
|
"Compare this fingerprint with them over a second channel " +
|
||||||
"over a second channel before you trust it.",
|
"before you trust it.",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = OwColors.TextSecondary,
|
||||||
)
|
)
|
||||||
Spacer(Modifier.height(8.dp))
|
Spacer(Modifier.height(10.dp))
|
||||||
|
OwDivider()
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
Label("REACHABLE AT")
|
Label("REACHABLE AT")
|
||||||
Mono(p.onion)
|
Spacer(Modifier.height(2.dp))
|
||||||
}
|
Mono(shortOnion(p.onion))
|
||||||
}
|
}
|
||||||
Spacer(Modifier.height(12.dp))
|
Spacer(Modifier.height(12.dp))
|
||||||
Button(
|
OwButton(
|
||||||
|
text = "Approve & add",
|
||||||
enabled = !adding && added == null,
|
enabled = !adding && added == null,
|
||||||
onClick = { scope.launch { flow.add(raw) } },
|
onClick = { scope.launch { flow.add(raw) } },
|
||||||
) { Text("Approve & add") }
|
leadingIconRes = R.drawable.ic_ow_add,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
added?.let { f ->
|
added?.let { f ->
|
||||||
Spacer(Modifier.height(16.dp))
|
Spacer(Modifier.height(16.dp))
|
||||||
Text(
|
OwAlertBanner(
|
||||||
"Added ${f.petname ?: f.fingerprint}",
|
variant = OwAlertVariant.Info,
|
||||||
style = MaterialTheme.typography.titleSmall,
|
title = "Added ${f.petname ?: shortId(f.fingerprint)}",
|
||||||
color = MaterialTheme.colorScheme.primary,
|
description = "If that key was already in your roster, only the " +
|
||||||
)
|
"locator was updated. One key is always one friend.",
|
||||||
Spacer(Modifier.height(4.dp))
|
|
||||||
Text(
|
|
||||||
"If that key was already in your roster, only the locator was updated. " +
|
|
||||||
"One key is always one friend.",
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
Spacer(Modifier.height(24.dp))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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.Card
|
import androidx.compose.material3.Card
|
||||||
import androidx.compose.material3.CardDefaults
|
import androidx.compose.material3.CardDefaults
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
|
@ -33,6 +32,9 @@ import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.testTag
|
import androidx.compose.ui.platform.testTag
|
||||||
import androidx.compose.ui.text.font.FontFamily
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import 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 kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
@ -54,7 +56,7 @@ import uniffi.onionwire_sdk.checkAddress
|
||||||
* store error after it.
|
* store error after it.
|
||||||
* - An **empty** address is a real, allowed value: it clears the profile
|
* - An **empty** address is a real, allowed value: it clears the profile
|
||||||
* address. It is labelled with its consequence, because with no profile
|
* address. It is labelled with its consequence, because with no profile
|
||||||
* address and no running wallet child the core has nothing to hand a payer
|
* address and no running wallet the core has nothing to hand a payer
|
||||||
* (`Node::wallet_receive_address`) and the invoice path fails.
|
* (`Node::wallet_receive_address`) and the invoice path fails.
|
||||||
* - The bio is carried, not owned: a save that did not touch the bio field
|
* - 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
|
* writes back the value read from the store immediately before the write, so
|
||||||
|
|
@ -100,7 +102,11 @@ fun ProfileScreen(
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
title = { Text("Profile") },
|
title = { Text("Profile") },
|
||||||
navigationIcon = {
|
navigationIcon = {
|
||||||
TextButton(onClick = onBack) { Text("Back") }
|
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,
|
||||||
|
|
@ -205,7 +211,7 @@ fun ProfileScreen(
|
||||||
supportingText = {
|
supportingText = {
|
||||||
Text(
|
Text(
|
||||||
// The consequence, on the screen, before a payment fails:
|
// The consequence, on the screen, before a payment fails:
|
||||||
// `Node::wallet_receive_address` uses the wallet child's
|
// `Node::wallet_receive_address` uses the wallet process's
|
||||||
// subaddress while it is up and this address otherwise,
|
// subaddress while it is up and this address otherwise,
|
||||||
// and with neither there is nothing to be paid to.
|
// and with neither there is nothing to be paid to.
|
||||||
profileAddressNotice(form.address),
|
profileAddressNotice(form.address),
|
||||||
|
|
@ -234,7 +240,8 @@ fun ProfileScreen(
|
||||||
.padding(12.dp),
|
.padding(12.dp),
|
||||||
horizontalArrangement = Arrangement.End,
|
horizontalArrangement = Arrangement.End,
|
||||||
) {
|
) {
|
||||||
Button(
|
OwButton(
|
||||||
|
text = if (busy) "Saving…" else "Save",
|
||||||
onClick = {
|
onClick = {
|
||||||
addressError = null
|
addressError = null
|
||||||
saveError = null
|
saveError = null
|
||||||
|
|
@ -247,7 +254,7 @@ fun ProfileScreen(
|
||||||
}
|
}
|
||||||
if (problem != null) {
|
if (problem != null) {
|
||||||
addressError = problem
|
addressError = problem
|
||||||
return@Button
|
return@OwButton
|
||||||
}
|
}
|
||||||
scope.launch {
|
scope.launch {
|
||||||
busy = true
|
busy = true
|
||||||
|
|
@ -294,9 +301,7 @@ fun ProfileScreen(
|
||||||
},
|
},
|
||||||
enabled = !busy && profileSaveEnabled(loaded, form),
|
enabled = !busy && profileSaveEnabled(loaded, form),
|
||||||
modifier = Modifier.testTag("profile-save"),
|
modifier = Modifier.testTag("profile-save"),
|
||||||
) {
|
)
|
||||||
Text(if (busy) "Saving…" else "Save")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
status?.let {
|
status?.let {
|
||||||
|
|
@ -432,7 +437,7 @@ internal const val PROFILE_SAVED: String = "profile saved"
|
||||||
/**
|
/**
|
||||||
* What an empty address means, stated where the address is typed.
|
* What an empty address means, stated where the address is typed.
|
||||||
*
|
*
|
||||||
* `Node::wallet_receive_address` answers with the wallet child's own subaddress
|
* `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
|
* 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
|
* fails outright. The user should read that here, not after a friend's payment
|
||||||
* bounces.
|
* bounces.
|
||||||
|
|
@ -440,7 +445,7 @@ internal const val PROFILE_SAVED: String = "profile saved"
|
||||||
internal fun profileAddressNotice(address: String): String =
|
internal fun profileAddressNotice(address: String): String =
|
||||||
if (address.trim().isEmpty()) {
|
if (address.trim().isEmpty()) {
|
||||||
"Empty is allowed, and it clears the profile address. Your receive address " +
|
"Empty is allowed, and it clears the profile address. Your receive address " +
|
||||||
"then comes from the wallet child while it is running — with no address " +
|
"then comes from the running wallet — with no address " +
|
||||||
"here and no wallet running, nobody can send you an invoice."
|
"here and no wallet running, nobody can send you an invoice."
|
||||||
} else {
|
} else {
|
||||||
"What friends pay to. Validated before it is saved; an invalid address is " +
|
"What friends pay to. Validated before it is saved; an invalid address is " +
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
|
@ -12,38 +18,71 @@ 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.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.saveable.rememberSaveable
|
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,
|
||||||
|
|
@ -51,245 +90,290 @@ fun RosterScreen(
|
||||||
onWipe: () -> Unit,
|
onWipe: () -> Unit,
|
||||||
onOpenProfile: () -> Unit,
|
onOpenProfile: () -> Unit,
|
||||||
onLock: () -> Unit,
|
onLock: () -> Unit,
|
||||||
onOpenWallet: () -> Unit,
|
onOpenWallets: () -> Unit,
|
||||||
) {
|
) {
|
||||||
var confirmWipe by remember { mutableStateOf(false) }
|
val context = LocalContext.current
|
||||||
// Closed by default; `rememberSaveable` so a rotation keeps whatever the
|
val clipboard = LocalClipboard.current
|
||||||
// user chose instead of snapping back to (or away from) the summary.
|
val scope = rememberCoroutineScope()
|
||||||
// Nothing about this is worth persisting to the store.
|
var confirmDeleteAll by remember { mutableStateOf(false) }
|
||||||
var identityExpanded by rememberSaveable { 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 = onOpenProfile) { Text("Profile") }
|
OwIconButton(
|
||||||
TextButton(onClick = onLock) { Text("Lock") }
|
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()
|
||||||
// The disclosure header. Collapsed, this one line *is* the
|
|
||||||
// identity block: the label, the abbreviated fingerprint,
|
|
||||||
// and a chevron saying there is more behind it.
|
|
||||||
Row(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.clickable { identityExpanded = !identityExpanded },
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
Label("YOU (stable forever)")
|
|
||||||
if (!identityExpanded) {
|
|
||||||
Spacer(Modifier.width(8.dp))
|
|
||||||
Mono(shortId(fingerprint))
|
|
||||||
}
|
}
|
||||||
Spacer(Modifier.weight(1f))
|
.onFailure {
|
||||||
Text(
|
Toast.makeText(context, "Could not read the invite", Toast.LENGTH_SHORT).show()
|
||||||
if (identityExpanded) "▾" else "▸",
|
}
|
||||||
style = MaterialTheme.typography.labelSmall,
|
}
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
},
|
||||||
|
onShare = onShare,
|
||||||
)
|
)
|
||||||
}
|
|
||||||
if (identityExpanded) {
|
|
||||||
Mono(fingerprint)
|
|
||||||
Spacer(Modifier.height(10.dp))
|
|
||||||
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,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
||||||
) {
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
Text(
|
Text(
|
||||||
f.petname?.takeIf { it.isNotBlank() } ?: f.fingerprint,
|
f.petname?.takeIf { it.isNotBlank() } ?: f.fingerprint,
|
||||||
style = MaterialTheme.typography.titleSmall,
|
style = MaterialTheme.typography.titleSmall,
|
||||||
|
color = OwColors.TextPrimary,
|
||||||
)
|
)
|
||||||
if (!f.lastConnectOk) {
|
if (!f.lastConnectOk) {
|
||||||
Spacer(Modifier.height(0.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
|
OwStatusDot(OwColors.Warning)
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
Text(
|
Text(
|
||||||
"locator stale",
|
"locator stale",
|
||||||
style = MaterialTheme.typography.labelSmall,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
color = MaterialTheme.colorScheme.error,
|
color = OwColors.Warning,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Spacer(Modifier.height(2.dp))
|
Spacer(Modifier.height(3.dp))
|
||||||
Text(
|
Text(
|
||||||
f.fingerprint,
|
shortId(f.fingerprint),
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MonoStyle,
|
||||||
fontFamily = FontFamily.Monospace,
|
color = OwColors.TextSecondary,
|
||||||
color = MaterialTheme.colorScheme.primary,
|
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
f.onion,
|
shortOnion(f.onion),
|
||||||
style = MaterialTheme.typography.labelSmall,
|
style = MonoStyle.copy(color = OwColors.TextMuted),
|
||||||
fontFamily = FontFamily.Monospace,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
Text("›", style = MaterialTheme.typography.titleMedium, color = OwColors.TextMuted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
* The compact stand-in for a long identity string: `head` characters, an
|
||||||
* ellipsis, then `tail` characters. Pure, so the roster's collapsed line and
|
* ellipsis, then `tail` characters. Pure, so the roster's line and its unit test
|
||||||
* its unit test agree on what "short" means.
|
* agree on what "short" means.
|
||||||
*
|
*
|
||||||
* A string no longer than the abbreviation is returned unchanged — the
|
* 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
|
* 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`/
|
* mangled. Kotlin strings are UTF-16, but these IDs are hex, so `take`/`takeLast`
|
||||||
* `takeLast` cannot split a surrogate pair here.
|
* cannot split a surrogate pair here.
|
||||||
*/
|
*/
|
||||||
fun shortId(id: String, head: Int = 6, tail: Int = 4): String {
|
fun shortId(id: String, head: Int = 6, tail: Int = 4): String {
|
||||||
if (id.length < head + tail + 1) return id
|
if (id.length < head + tail + 1) return id
|
||||||
return id.take(head) + "…" + id.takeLast(tail)
|
return id.take(head) + "…" + id.takeLast(tail)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
/**
|
||||||
fun Label(text: String) {
|
* A v3 onion locator shortened for a roster row, with the `.onion` suffix kept
|
||||||
Text(
|
* visible: `abcdefghij…uvwxyz.onion`.
|
||||||
text,
|
*
|
||||||
style = MaterialTheme.typography.labelSmall,
|
* The suffix is the part that tells a reader this is an onion address at all, so
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
* 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.
|
||||||
|
*/
|
||||||
@Composable
|
fun shortOnion(onion: String, head: Int = 10, tail: Int = 6): String {
|
||||||
fun Mono(text: String) {
|
val suffix = ".onion"
|
||||||
Text(
|
if (onion.isEmpty()) return onion
|
||||||
text,
|
if (!onion.endsWith(suffix)) return onion
|
||||||
style = MaterialTheme.typography.bodySmall,
|
val body = onion.removeSuffix(suffix)
|
||||||
fontFamily = FontFamily.Monospace,
|
if (body.length <= head + tail + 1) return onion
|
||||||
color = MaterialTheme.colorScheme.onSurface,
|
return body.take(head) + "…" + body.takeLast(tail) + suffix
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@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") }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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,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,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,11 @@ package com.siriusdevops.onionwire.ui
|
||||||
|
|
||||||
import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE
|
import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE
|
||||||
import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths
|
import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths
|
||||||
|
import java.io.File
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One snapshot of the app-owned wallet child, as the wallet screen sees it.
|
* One snapshot of the app-owned wallet process, as the wallet screen sees it.
|
||||||
*
|
*
|
||||||
* A plain mirror of the fields `WalletChildStatus` carries over UniFFI
|
* A plain mirror of the fields `WalletChildStatus` carries over UniFFI
|
||||||
* (`state`, `running`, `configured`, `chain_source`, `last_error`) — the same
|
* (`state`, `running`, `configured`, `chain_source`, `last_error`) — the same
|
||||||
|
|
@ -97,7 +98,7 @@ sealed interface WalletChildPhase {
|
||||||
data object Unread : WalletChildPhase {
|
data object Unread : WalletChildPhase {
|
||||||
override val testTag: String = "child-unread"
|
override val testTag: String = "child-unread"
|
||||||
override val label: String = "reading…"
|
override val label: String = "reading…"
|
||||||
override val contentDescription: String = "Reading the wallet child status"
|
override val contentDescription: String = "Reading the wallet status"
|
||||||
override val live: Boolean = false
|
override val live: Boolean = false
|
||||||
override val dead: Boolean = false
|
override val dead: Boolean = false
|
||||||
}
|
}
|
||||||
|
|
@ -106,7 +107,7 @@ sealed interface WalletChildPhase {
|
||||||
data object Off : WalletChildPhase {
|
data object Off : WalletChildPhase {
|
||||||
override val testTag: String = "child-off"
|
override val testTag: String = "child-off"
|
||||||
override val label: String = "off"
|
override val label: String = "off"
|
||||||
override val contentDescription: String = "The wallet child is off"
|
override val contentDescription: String = "The wallet is off"
|
||||||
override val live: Boolean = false
|
override val live: Boolean = false
|
||||||
override val dead: Boolean = false
|
override val dead: Boolean = false
|
||||||
}
|
}
|
||||||
|
|
@ -116,7 +117,7 @@ sealed interface WalletChildPhase {
|
||||||
override val testTag: String = "child-connecting"
|
override val testTag: String = "child-connecting"
|
||||||
override val label: String = "connecting"
|
override val label: String = "connecting"
|
||||||
override val contentDescription: String =
|
override val contentDescription: String =
|
||||||
"The wallet child is up; its wallet RPC has not answered yet"
|
"The wallet is starting; its RPC has not answered yet"
|
||||||
override val live: Boolean = true
|
override val live: Boolean = true
|
||||||
override val dead: Boolean = false
|
override val dead: Boolean = false
|
||||||
}
|
}
|
||||||
|
|
@ -135,7 +136,7 @@ sealed interface WalletChildPhase {
|
||||||
data object Ready : WalletChildPhase {
|
data object Ready : WalletChildPhase {
|
||||||
override val testTag: String = "child-ready"
|
override val testTag: String = "child-ready"
|
||||||
override val label: String = "ready"
|
override val label: String = "ready"
|
||||||
override val contentDescription: String = "The wallet child is ready"
|
override val contentDescription: String = "The wallet is ready"
|
||||||
override val live: Boolean = true
|
override val live: Boolean = true
|
||||||
override val dead: Boolean = false
|
override val dead: Boolean = false
|
||||||
}
|
}
|
||||||
|
|
@ -144,7 +145,7 @@ sealed interface WalletChildPhase {
|
||||||
data class Exited(val reason: String?) : WalletChildPhase {
|
data class Exited(val reason: String?) : WalletChildPhase {
|
||||||
override val testTag: String = "child-exited"
|
override val testTag: String = "child-exited"
|
||||||
override val label: String = "exited"
|
override val label: String = "exited"
|
||||||
override val contentDescription: String = "The wallet child exited"
|
override val contentDescription: String = "The wallet process exited"
|
||||||
override val live: Boolean = false
|
override val live: Boolean = false
|
||||||
override val dead: Boolean = true
|
override val dead: Boolean = true
|
||||||
}
|
}
|
||||||
|
|
@ -158,7 +159,7 @@ sealed interface WalletChildPhase {
|
||||||
override val testTag: String = "child-unrecognised"
|
override val testTag: String = "child-unrecognised"
|
||||||
override val label: String = "unknown (${shortSendReason(raw, UNRECOGNISED_BUDGET)})"
|
override val label: String = "unknown (${shortSendReason(raw, UNRECOGNISED_BUDGET)})"
|
||||||
override val contentDescription: String =
|
override val contentDescription: String =
|
||||||
"The wallet child reported a state this build does not know"
|
"The wallet reported a state this build does not know"
|
||||||
override val live: Boolean = false
|
override val live: Boolean = false
|
||||||
override val dead: Boolean = false
|
override val dead: Boolean = false
|
||||||
}
|
}
|
||||||
|
|
@ -336,25 +337,26 @@ const val ONION_NEEDS_ARTI_NOTICE: String =
|
||||||
"A .onion daemon needs the arti SOCKS child, which this build does not bundle."
|
"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. */
|
/** Shown while the first `wallet_status()` read is still in flight. */
|
||||||
const val READING_CHILD_NOTICE: String = "Reading the wallet child status…"
|
const val READING_CHILD_NOTICE: String = "Reading the wallet status…"
|
||||||
|
|
||||||
const val STARTING_CHILD_NOTICE: String =
|
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."
|
"Start is running. Status stays off until the on-device node answers — that can take a minute, and is not a dead button."
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The caveat the on-device node is offered with, **before** Start.
|
* 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"*,
|
* 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
|
* 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 the daemon
|
* measured in this repo are in `docs/cuprate-launch-spike.md`), and mainnet is
|
||||||
* this app launches is pinned to **testnet** (`src/cuprate.rs`). One sentence, not
|
* unvalidated. The title is the banner's; the two sentences are the body — one
|
||||||
* a glyph: the choice is opt-in and never a default, and a user who reads only
|
* copy of the caveat, never a second one elsewhere on the screen, so the two
|
||||||
* this line still knows what they picked.
|
* can never drift apart.
|
||||||
*/
|
*/
|
||||||
const val CUPRATE_PREPRODUCTION_WARNING: String =
|
const val CUPRATE_ON_DEVICE_TITLE: String = "Experimental On-Device Node (Cuprate)"
|
||||||
"On-device node is Cuprate, which is pre-production: its own user book says do NOT use " +
|
const val CUPRATE_ON_DEVICE_BODY: String =
|
||||||
"cuprated for any serious purposes, mainnet is unvalidated, and its monerod RPC parity " +
|
"Pre-production software with incomplete RPC parity (#278). Do not use for significant " +
|
||||||
"is incomplete (Cuprate issue #278). Try the in-process path; do not hold funds on it."
|
"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
|
* This build was compiled without the `cuprate-daemon` feature, so the stored
|
||||||
|
|
@ -445,13 +447,21 @@ fun selectedCuprateMode(inProcess: Boolean, mainnet: Boolean, prune: Boolean): C
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tapping a mode used to only persist `ChainConfig`, which looked like a no-op
|
* 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 and
|
* besides the storage line. Start when the storage floor would allow Start,
|
||||||
* a launch is not already in flight.
|
* **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(
|
fun shouldStartAfterSelectingChain(
|
||||||
storageBlocked: String?,
|
storageBlocked: String?,
|
||||||
starting: Boolean,
|
starting: Boolean,
|
||||||
): Boolean = storageBlocked == null && !starting
|
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
|
* Bytes as a screen-sized string. Binary units (a "GB" that is really a GiB is how
|
||||||
|
|
@ -463,6 +473,131 @@ fun formatBytes(bytes: Long): String = when {
|
||||||
else -> "$bytes B"
|
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.
|
* Why **Start** is not actionable, or `null` when it is.
|
||||||
*
|
*
|
||||||
|
|
@ -479,8 +614,11 @@ fun startBlockedReason(
|
||||||
bins.walletRpc == null -> NO_WALLET_RPC_MESSAGE
|
bins.walletRpc == null -> NO_WALLET_RPC_MESSAGE
|
||||||
starting -> STARTING_CHILD_NOTICE
|
starting -> STARTING_CHILD_NOTICE
|
||||||
input == null -> READING_CHILD_NOTICE
|
input == null -> READING_CHILD_NOTICE
|
||||||
input.running -> "The wallet child is already running."
|
// Unreachable from the wallet screen: while the wallet runs the lifecycle
|
||||||
!input.configured -> "No chain source yet: a wallet child needs a daemon to dial."
|
// 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
|
// 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.
|
// option is readable and unstoppable, so say it before the user presses Start.
|
||||||
input.chainInProcess && !input.nodeAvailable -> CUPRATE_NOT_IN_BUILD_NOTICE
|
input.chainInProcess && !input.nodeAvailable -> CUPRATE_NOT_IN_BUILD_NOTICE
|
||||||
|
|
@ -488,13 +626,179 @@ fun startBlockedReason(
|
||||||
else -> null
|
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
|
* 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.
|
* idempotent in the core, so this is only about not offering a no-op button.
|
||||||
*/
|
*/
|
||||||
fun stopBlockedReason(input: WalletChildInput?): String? = when {
|
fun stopBlockedReason(input: WalletChildInput?): String? = when {
|
||||||
input == null -> READING_CHILD_NOTICE
|
input == null -> READING_CHILD_NOTICE
|
||||||
!input.running -> "No wallet child is running."
|
!input.running -> "No wallet is running."
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -14,20 +14,13 @@ 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.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.Card
|
|
||||||
import androidx.compose.material3.CardDefaults
|
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedButton
|
|
||||||
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.DisposableEffect
|
import androidx.compose.runtime.DisposableEffect
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
|
@ -40,11 +33,21 @@ import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalView
|
import androidx.compose.ui.platform.LocalView
|
||||||
import androidx.compose.ui.platform.testTag
|
import androidx.compose.ui.platform.testTag
|
||||||
import androidx.compose.ui.text.font.FontFamily
|
|
||||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import com.siriusdevops.onionwire.WireViewModel
|
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 kotlinx.coroutines.launch
|
||||||
import uniffi.onionwire_sdk.WalletKeys
|
import uniffi.onionwire_sdk.WalletKeys
|
||||||
import uniffi.onionwire_sdk.WalletRow
|
import uniffi.onionwire_sdk.WalletRow
|
||||||
|
|
@ -83,7 +86,7 @@ internal fun walletRowDate(createdAt: Long): String {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whether the wallet child has a wallet open that the RPC answers for.
|
* 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`
|
* 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
|
* means its wallet RPC has not answered, `off`/`exited` mean there is no child
|
||||||
|
|
@ -126,8 +129,8 @@ internal fun walletSecretsBlockedReason(
|
||||||
isActive: Boolean,
|
isActive: Boolean,
|
||||||
walletReadable: Boolean,
|
walletReadable: Boolean,
|
||||||
): String? = when {
|
): String? = when {
|
||||||
!isActive -> "open this wallet to view its backup"
|
!isActive -> "Open this wallet to view its backup."
|
||||||
!walletReadable -> "the wallet child is not running — start it on the wallet screen to read the backup"
|
!walletReadable -> "The wallet is not running — start it on the wallet screen to read the backup."
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -159,16 +162,45 @@ private val RAW_RPC_CODE = Regex("""(?<![\d-])-13(?!\d)""")
|
||||||
*/
|
*/
|
||||||
private val RAW_JSON = Regex("""[{}]|\[\s*\{|"(error|code|message|result|jsonrpc)"\s*:""")
|
private val RAW_JSON = Regex("""[{}]|\[\s*\{|"(error|code|message|result|jsonrpc)"\s*:""")
|
||||||
|
|
||||||
/** Shown instead of the daemon's `-13` / `No wallet file` / JSON answer. */
|
/**
|
||||||
|
* 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 =
|
const val WALLET_NOT_OPEN_TEXT: String =
|
||||||
"No wallet is open in the wallet child yet. Open one from the list below — a wallet that " +
|
"Open or create a wallet to enable balance, address, and backup controls."
|
||||||
"needs a passphrase asks for it here — and the balance, address and backups work again."
|
|
||||||
|
|
||||||
/** Shown instead of a raw JSON refusal that names no condition the user can act on. */
|
/** Shown instead of a raw JSON refusal that names no condition the user can act on. */
|
||||||
const val WALLET_DAEMON_REFUSED_TEXT: String =
|
const val WALLET_DAEMON_REFUSED_TEXT: String =
|
||||||
"The wallet daemon refused that request and gave no readable reason. Check the wallet child " +
|
"The wallet daemon refused that request and gave no readable reason. Check the wallet " +
|
||||||
"on the wallet screen, then try again."
|
"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
|
* A failure string safe to put on screen, or `null` when there is nothing to
|
||||||
* show.
|
* show.
|
||||||
|
|
@ -194,6 +226,9 @@ internal fun walletFailureText(raw: String?): String? {
|
||||||
val text = raw?.trim().orEmpty()
|
val text = raw?.trim().orEmpty()
|
||||||
return when {
|
return when {
|
||||||
text.isEmpty() -> null
|
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) ->
|
NO_WALLET_FILE.containsMatchIn(text) || RAW_RPC_CODE.containsMatchIn(text) ->
|
||||||
WALLET_NOT_OPEN_TEXT
|
WALLET_NOT_OPEN_TEXT
|
||||||
RAW_JSON.containsMatchIn(text) -> WALLET_DAEMON_REFUSED_TEXT
|
RAW_JSON.containsMatchIn(text) -> WALLET_DAEMON_REFUSED_TEXT
|
||||||
|
|
@ -251,7 +286,7 @@ internal fun walletPassphrasePromptVisible(needsPassphrase: Boolean, walletOpen:
|
||||||
* A file name is required because the open is per-file (`open_wallet` on the
|
* 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
|
* 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
|
* 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 child.
|
* failure. An in-flight open is not re-submitted: it restarts the wallet process.
|
||||||
*/
|
*/
|
||||||
internal fun walletPassphraseSubmitEnabled(
|
internal fun walletPassphraseSubmitEnabled(
|
||||||
activeFilename: String?,
|
activeFilename: String?,
|
||||||
|
|
@ -270,14 +305,14 @@ internal fun walletPassphraseBlockedReason(
|
||||||
typed: String,
|
typed: String,
|
||||||
): String? = when {
|
): String? = when {
|
||||||
activeFilename == null ->
|
activeFilename == null ->
|
||||||
"the wallet child is not pointed at a wallet file yet — open one from the list below"
|
"No wallet file is open yet — open one from the list below."
|
||||||
typed.isEmpty() -> "type the passphrase for this wallet file"
|
typed.isEmpty() -> "Type the passphrase for this wallet file."
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Why the wallet child has nothing open, in this app's words — or `null` when
|
* Why the wallet process has nothing open, in this app's words — or `null` when
|
||||||
* it has a wallet open, or no child is running to hold one.
|
* 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
|
* 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
|
* file open, and every read then answers `-13 No wallet file`. The status line
|
||||||
|
|
@ -294,11 +329,10 @@ internal fun walletChildOpenHint(
|
||||||
): String? = when {
|
): String? = when {
|
||||||
!childRunning || walletOpen -> null
|
!childRunning || walletOpen -> null
|
||||||
needsPassphrase ->
|
needsPassphrase ->
|
||||||
"No wallet is open in the wallet child: it needs the passphrase for the file it is " +
|
"The wallet needs its passphrase: open it on the Saved wallets screen, where the " +
|
||||||
"pointed at. Open it on the Saved wallets screen, where the prompt is."
|
"prompt is."
|
||||||
else ->
|
else ->
|
||||||
"No wallet is open in the wallet child yet. Open a saved wallet on the Saved wallets " +
|
"Select a saved wallet or create a new one to view your balance and transact."
|
||||||
"screen, or create or import one here."
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -319,7 +353,6 @@ internal fun walletChildOpenHint(
|
||||||
* in saved state (`remember`, not `rememberSaveable`, and cleared on
|
* in saved state (`remember`, not `rememberSaveable`, and cleared on
|
||||||
* dispose).
|
* dispose).
|
||||||
*/
|
*/
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
|
||||||
@Composable
|
@Composable
|
||||||
fun WalletManagerScreen(
|
fun WalletManagerScreen(
|
||||||
vm: WireViewModel,
|
vm: WireViewModel,
|
||||||
|
|
@ -503,25 +536,24 @@ fun WalletManagerScreen(
|
||||||
// Root owns systemBars ∪ ime, exactly as the wallet screen does (see
|
// Root owns systemBars ∪ ime, exactly as the wallet screen does (see
|
||||||
// `screenContentInsets`).
|
// `screenContentInsets`).
|
||||||
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
||||||
|
containerColor = OwColors.Canvas,
|
||||||
topBar = {
|
topBar = {
|
||||||
TopAppBar(
|
OwTopBar(
|
||||||
title = { Text("Saved wallets") },
|
title = "Saved wallets",
|
||||||
navigationIcon = {
|
// A pushed sub-screen, so the chevron — never the word "Back".
|
||||||
TextButton(onClick = onBack) { Text("Back") }
|
onBack = onBack,
|
||||||
},
|
|
||||||
actions = {
|
actions = {
|
||||||
TextButton(
|
OwButton(
|
||||||
|
text = "Refresh",
|
||||||
|
variant = OwButtonVariant.Outline,
|
||||||
onClick = {
|
onClick = {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
vm.refreshWalletChild()
|
vm.refreshWalletChild()
|
||||||
reload()
|
reload()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
) { Text("Refresh") }
|
)
|
||||||
},
|
},
|
||||||
colors = TopAppBarDefaults.topAppBarColors(
|
|
||||||
containerColor = MaterialTheme.colorScheme.background,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
) { pad ->
|
) { pad ->
|
||||||
|
|
@ -559,22 +591,21 @@ fun WalletManagerScreen(
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
keysError?.let { message ->
|
keysError?.let { message ->
|
||||||
Card(
|
OwAlertBanner(
|
||||||
|
variant = OwAlertVariant.Error,
|
||||||
|
title = "Could not read the open wallet's private keys",
|
||||||
|
description = message,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.padding(horizontal = 16.dp, vertical = 8.dp)
|
||||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
.testTag("wallet-keys-error"),
|
||||||
colors = CardDefaults.cardColors(
|
action = {
|
||||||
containerColor = MaterialTheme.colorScheme.errorContainer,
|
OwButton(
|
||||||
),
|
text = "Dismiss",
|
||||||
) {
|
variant = OwButtonVariant.Outline,
|
||||||
Column(Modifier.padding(12.dp)) {
|
onClick = { keysError = null },
|
||||||
Text("could not read the open wallet's private keys")
|
)
|
||||||
Spacer(Modifier.height(4.dp))
|
},
|
||||||
Text(message, style = MaterialTheme.typography.bodySmall)
|
)
|
||||||
Spacer(Modifier.height(8.dp))
|
|
||||||
TextButton(onClick = { keysError = null }) { Text("Dismiss") }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
actionError?.let { ErrorText(it) }
|
actionError?.let { ErrorText(it) }
|
||||||
|
|
@ -608,46 +639,55 @@ fun WalletManagerScreen(
|
||||||
// A read failure is not an empty catalogue, and the two must
|
// A read failure is not an empty catalogue, and the two must
|
||||||
// not read alike: one is "the store did not answer", the other
|
// not read alike: one is "the store did not answer", the other
|
||||||
// is "you have no wallets yet".
|
// is "you have no wallets yet".
|
||||||
listError != null -> Column(Modifier.padding(12.dp)) {
|
listError != null -> OwAlertBanner(
|
||||||
Text(
|
variant = OwAlertVariant.Error,
|
||||||
"could not read the wallet catalogue",
|
title = "Could not read the wallet catalogue",
|
||||||
style = MaterialTheme.typography.titleSmall,
|
description = listError ?: "",
|
||||||
color = MaterialTheme.colorScheme.error,
|
modifier = Modifier
|
||||||
|
.padding(horizontal = 16.dp, vertical = 8.dp)
|
||||||
|
.testTag("wallet-list-error"),
|
||||||
|
action = {
|
||||||
|
OwButton(
|
||||||
|
text = "Retry",
|
||||||
|
variant = OwButtonVariant.Outline,
|
||||||
|
onClick = { scope.launch { reload() } },
|
||||||
)
|
)
|
||||||
Spacer(Modifier.height(4.dp))
|
},
|
||||||
Text(
|
|
||||||
listError ?: "",
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.error,
|
|
||||||
)
|
)
|
||||||
Spacer(Modifier.height(8.dp))
|
|
||||||
TextButton(onClick = { scope.launch { reload() } }) { Text("Retry") }
|
|
||||||
}
|
|
||||||
|
|
||||||
listed == null -> Text(
|
listed == null -> Text(
|
||||||
"loading…",
|
"Loading…",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
modifier = Modifier.padding(12.dp),
|
color = OwColors.TextSecondary,
|
||||||
|
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
)
|
)
|
||||||
|
|
||||||
listed.isEmpty() -> Column(Modifier.padding(12.dp)) {
|
listed.isEmpty() -> OwCard(
|
||||||
Text("No saved wallets yet", style = MaterialTheme.typography.titleSmall)
|
modifier = Modifier
|
||||||
Spacer(Modifier.height(4.dp))
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
|
) {
|
||||||
|
OwSectionTitle("No saved wallets yet")
|
||||||
|
Spacer(Modifier.height(6.dp))
|
||||||
Text(
|
Text(
|
||||||
"Wallets this install remembers show up here. Create or import one " +
|
"Wallets this install remembers show up here. Create or import one " +
|
||||||
"on the wallet screen and it appears on the next look.",
|
"on the wallet screen and it appears on the next look.",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
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(),
|
||||||
)
|
)
|
||||||
Spacer(Modifier.height(8.dp))
|
|
||||||
Button(onClick = onBack) { Text("Create or import a wallet") }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
Text(
|
Label(
|
||||||
"${listed.size} saved ${if (listed.size == 1) "wallet" else "wallets"}",
|
"${listed.size} SAVED ${if (listed.size == 1) "WALLET" else "WALLETS"}",
|
||||||
style = MaterialTheme.typography.labelSmall,
|
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
|
|
||||||
)
|
)
|
||||||
listed.forEach { row ->
|
listed.forEach { row ->
|
||||||
val isActive = active != null && active == row.walletFilename
|
val isActive = active != null && active == row.walletFilename
|
||||||
|
|
@ -680,7 +720,7 @@ fun WalletManagerScreen(
|
||||||
* and whether it is the open one.
|
* and whether it is the open one.
|
||||||
*
|
*
|
||||||
* The open row is not tappable. Re-opening it would stop and restart a running
|
* The open row is not tappable. Re-opening it would stop and restart a running
|
||||||
* wallet child onto the file it already has open — a slow no-op whose only
|
* 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.
|
* effect is to make the screen look like it did something.
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
|
|
@ -694,16 +734,12 @@ private fun WalletRowCard(
|
||||||
onShowPhrase: () -> Unit,
|
onShowPhrase: () -> Unit,
|
||||||
onShowKeys: () -> Unit,
|
onShowKeys: () -> Unit,
|
||||||
) {
|
) {
|
||||||
Card(
|
OwCard(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
.padding(horizontal = 16.dp, vertical = 6.dp)
|
||||||
.then(if (isActive) Modifier else Modifier.clickable(enabled = !opening, onClick = onOpen)),
|
.then(if (isActive) Modifier else Modifier.clickable(enabled = !opening, onClick = onOpen)),
|
||||||
colors = CardDefaults.cardColors(
|
|
||||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
|
||||||
),
|
|
||||||
) {
|
) {
|
||||||
Column(Modifier.padding(12.dp)) {
|
|
||||||
Row(
|
Row(
|
||||||
Modifier.fillMaxWidth(),
|
Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
|
@ -711,58 +747,60 @@ private fun WalletRowCard(
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
walletRowLabel(row.name, row.walletFilename),
|
walletRowLabel(row.name, row.walletFilename),
|
||||||
style = MaterialTheme.typography.titleSmall,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
color = OwColors.TextPrimary,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
when {
|
when {
|
||||||
isActive -> Text(
|
isActive -> OwPill(
|
||||||
"in use",
|
text = "In use",
|
||||||
style = MaterialTheme.typography.labelSmall,
|
textColor = OwColors.Accent,
|
||||||
color = MaterialTheme.colorScheme.primary,
|
container = OwColors.InfoTint,
|
||||||
)
|
borderColor = OwColors.InfoBorder,
|
||||||
opening -> Text(
|
dotColor = OwColors.Accent,
|
||||||
"opening…",
|
|
||||||
style = MaterialTheme.typography.labelSmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
else -> Text(
|
|
||||||
"tap to open",
|
|
||||||
style = MaterialTheme.typography.labelSmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
)
|
||||||
|
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))
|
Spacer(Modifier.height(4.dp))
|
||||||
Text(
|
Text(
|
||||||
"file ${row.walletFilename}",
|
"Created ${walletRowDate(row.createdAt)}",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
fontFamily = FontFamily.Monospace,
|
color = OwColors.TextSecondary,
|
||||||
)
|
|
||||||
Text(
|
|
||||||
"created ${walletRowDate(row.createdAt)}",
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(Modifier.height(8.dp))
|
Spacer(Modifier.height(10.dp))
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
OwButtonRow {
|
||||||
OutlinedButton(onClick = onShowPhrase, enabled = secretsEnabled) {
|
OwButton(
|
||||||
Text("Recovery phrase")
|
text = "Recovery phrase",
|
||||||
}
|
variant = OwButtonVariant.Outline,
|
||||||
OutlinedButton(onClick = onShowKeys, enabled = secretsEnabled) {
|
enabled = secretsEnabled,
|
||||||
Text("Private keys")
|
onClick = onShowPhrase,
|
||||||
}
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
OwButton(
|
||||||
|
text = "Private keys",
|
||||||
|
variant = OwButtonVariant.Outline,
|
||||||
|
enabled = secretsEnabled,
|
||||||
|
onClick = onShowKeys,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
blockedReason?.let {
|
blockedReason?.let {
|
||||||
Spacer(Modifier.height(4.dp))
|
Spacer(Modifier.height(6.dp))
|
||||||
Text(
|
Text(
|
||||||
it,
|
it,
|
||||||
style = MaterialTheme.typography.labelSmall,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = OwColors.TextMuted,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The one-time passphrase for a wallet file this install holds no passphrase
|
* The one-time passphrase for a wallet file this install holds no passphrase
|
||||||
|
|
@ -774,10 +812,10 @@ private fun WalletRowCard(
|
||||||
* wallet file. It is never logged, never persisted, and the caller drops it when
|
* wallet file. It is never logged, never persisted, and the caller drops it when
|
||||||
* the screen goes.
|
* the screen goes.
|
||||||
*
|
*
|
||||||
* Submit is dead while the wallet child is not running: the core verifies a
|
* 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
|
* passphrase against a live daemon and refuses to seal an unverified one, so a
|
||||||
* tap there could only fail. When the child *is* up — including `connecting`,
|
* tap there could only fail. When it *is* up — including `connecting`, whose RPC
|
||||||
* whose RPC has not answered yet — the core restarts it onto the file with this
|
* has not answered yet — the core restarts it onto the file with this
|
||||||
* passphrase, which is exactly the fix.
|
* passphrase, which is exactly the fix.
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
|
|
@ -791,26 +829,23 @@ private fun WalletPassphraseCard(
|
||||||
error: String?,
|
error: String?,
|
||||||
onSubmit: () -> Unit,
|
onSubmit: () -> Unit,
|
||||||
) {
|
) {
|
||||||
Card(
|
OwCard(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(horizontal = 12.dp, vertical = 8.dp)
|
.padding(horizontal = 16.dp, vertical = 8.dp)
|
||||||
.testTag("wallet-passphrase-card"),
|
.testTag("wallet-passphrase-card"),
|
||||||
colors = CardDefaults.cardColors(
|
|
||||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
|
||||||
),
|
|
||||||
) {
|
) {
|
||||||
Column(Modifier.padding(12.dp)) {
|
OwSectionTitle("This wallet needs its passphrase")
|
||||||
Text("This wallet needs its passphrase", style = MaterialTheme.typography.titleSmall)
|
Spacer(Modifier.height(6.dp))
|
||||||
Spacer(Modifier.height(4.dp))
|
|
||||||
Text(
|
Text(
|
||||||
"The wallet child is pointed at ${filename ?: "a wallet file"} but this install " +
|
"The wallet is pointed at ${filename ?: "a wallet file"} but this install " +
|
||||||
"holds no passphrase that opens it — the wallet was created before the " +
|
"holds no passphrase that opens it — the wallet was created before the " +
|
||||||
"passphrase was stored, or on another device. Type it once: the wallet " +
|
"passphrase was stored, or on another device. Type it once: the wallet " +
|
||||||
"opens, and later starts reopen it on their own.",
|
"opens, and later starts reopen it on their own.",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = OwColors.TextSecondary,
|
||||||
)
|
)
|
||||||
Spacer(Modifier.height(8.dp))
|
Spacer(Modifier.height(12.dp))
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = typed,
|
value = typed,
|
||||||
onValueChange = onTyped,
|
onValueChange = onTyped,
|
||||||
|
|
@ -822,46 +857,46 @@ private fun WalletPassphraseCard(
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.testTag("wallet-passphrase-input"),
|
.testTag("wallet-passphrase-input"),
|
||||||
)
|
)
|
||||||
Spacer(Modifier.height(4.dp))
|
Spacer(Modifier.height(6.dp))
|
||||||
Text(
|
Text(
|
||||||
"Never copied to the clipboard, never logged, and dropped when you leave this screen.",
|
"Never copied to the clipboard, never logged, and dropped when you leave this screen.",
|
||||||
style = MaterialTheme.typography.labelSmall,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = OwColors.TextSecondary,
|
||||||
)
|
)
|
||||||
if (!childRunning) {
|
if (!childRunning) {
|
||||||
Spacer(Modifier.height(4.dp))
|
Spacer(Modifier.height(8.dp))
|
||||||
Text(
|
OwAlertBanner(
|
||||||
"the wallet child is not running — start it on the wallet screen, then come back",
|
variant = OwAlertVariant.Info,
|
||||||
style = MaterialTheme.typography.labelSmall,
|
title = "The wallet is not running",
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
description = "Start it on the wallet screen, then come back.",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
error?.let {
|
error?.let {
|
||||||
Spacer(Modifier.height(6.dp))
|
Spacer(Modifier.height(8.dp))
|
||||||
Text(
|
OwAlertBanner(
|
||||||
it,
|
variant = OwAlertVariant.Error,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
title = "Could not open this wallet",
|
||||||
color = MaterialTheme.colorScheme.error,
|
description = it,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
blockedReason?.let {
|
blockedReason?.let {
|
||||||
Spacer(Modifier.height(4.dp))
|
Spacer(Modifier.height(8.dp))
|
||||||
Text(
|
OwAlertBanner(
|
||||||
it,
|
variant = OwAlertVariant.Info,
|
||||||
style = MaterialTheme.typography.labelSmall,
|
title = "Not ready to open",
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
description = it,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Spacer(Modifier.height(8.dp))
|
Spacer(Modifier.height(12.dp))
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
OwButton(
|
||||||
Button(
|
text = if (inFlight) "Opening…" else "Open this wallet",
|
||||||
|
variant = OwButtonVariant.Primary,
|
||||||
|
enabled = childRunning && walletPassphraseSubmitEnabled(filename, typed, inFlight),
|
||||||
onClick = onSubmit,
|
onClick = onSubmit,
|
||||||
enabled = childRunning &&
|
modifier = Modifier
|
||||||
walletPassphraseSubmitEnabled(filename, typed, inFlight),
|
.fillMaxWidth()
|
||||||
modifier = Modifier.testTag("wallet-passphrase-submit"),
|
.testTag("wallet-passphrase-submit"),
|
||||||
) { Text(if (inFlight) "Opening…" else "Open this wallet") }
|
)
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -880,64 +915,57 @@ private fun PrivateKeysCard(
|
||||||
warning: String,
|
warning: String,
|
||||||
onDone: () -> Unit,
|
onDone: () -> Unit,
|
||||||
) {
|
) {
|
||||||
Card(
|
OwCard(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
.padding(horizontal = 16.dp, vertical = 8.dp)
|
||||||
colors = CardDefaults.cardColors(
|
.testTag("wallet-private-keys-card"),
|
||||||
containerColor = MaterialTheme.colorScheme.errorContainer,
|
|
||||||
),
|
|
||||||
) {
|
) {
|
||||||
Column(Modifier.padding(12.dp)) {
|
OwSectionTitle("Private keys of the open wallet")
|
||||||
Text("Private keys of the open wallet", style = MaterialTheme.typography.titleSmall)
|
Spacer(Modifier.height(6.dp))
|
||||||
Spacer(Modifier.height(4.dp))
|
Text(warning, style = MaterialTheme.typography.bodySmall, color = OwColors.Danger)
|
||||||
Text(warning, style = MaterialTheme.typography.bodySmall)
|
Spacer(Modifier.height(12.dp))
|
||||||
Spacer(Modifier.height(8.dp))
|
Label("VIEW KEY")
|
||||||
Text(
|
// Mono, and deliberately no testTag: a handle on a spend secret is a
|
||||||
"view key",
|
// handle an automation can read back.
|
||||||
style = MaterialTheme.typography.labelSmall,
|
Mono(keys.viewKey, modifier = Modifier.fillMaxWidth())
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
Spacer(Modifier.height(10.dp))
|
||||||
)
|
|
||||||
Text(
|
|
||||||
keys.viewKey,
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
fontFamily = FontFamily.Monospace,
|
|
||||||
)
|
|
||||||
Spacer(Modifier.height(8.dp))
|
|
||||||
val spend = keys.spendKey
|
val spend = keys.spendKey
|
||||||
if (spend != null) {
|
if (spend != null) {
|
||||||
Text(
|
Label("SPEND KEY")
|
||||||
"spend key",
|
Mono(spend, modifier = Modifier.fillMaxWidth())
|
||||||
style = MaterialTheme.typography.labelSmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
spend,
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
fontFamily = FontFamily.Monospace,
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
Text(
|
Text(
|
||||||
"view-only wallet — no spend key",
|
"View-only wallet — no spend key.",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = OwColors.TextSecondary,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Spacer(Modifier.height(8.dp))
|
Spacer(Modifier.height(12.dp))
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
OwButton(
|
||||||
Button(onClick = onDone) { Text("Done") }
|
text = "Done",
|
||||||
}
|
variant = OwButtonVariant.Outline,
|
||||||
}
|
onClick = onDone,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A display-ready failure line. Never carries a secret; callers pass errors. */
|
/**
|
||||||
|
* 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
|
@Composable
|
||||||
private fun ErrorText(text: String) {
|
private fun ErrorText(text: String) {
|
||||||
Text(
|
val notOpen = text == WALLET_NOT_OPEN_TEXT
|
||||||
text,
|
OwAlertBanner(
|
||||||
style = MaterialTheme.typography.bodySmall,
|
variant = if (notOpen) OwAlertVariant.Info else OwAlertVariant.Error,
|
||||||
color = MaterialTheme.colorScheme.error,
|
title = if (notOpen) "No wallet open" else "Something went wrong",
|
||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
|
description = text,
|
||||||
|
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
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),
|
||||||
|
)
|
||||||
|
}
|
||||||
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>
|
||||||
|
|
@ -239,7 +239,9 @@ class ProfileDraftTest {
|
||||||
fun an_empty_address_says_nobody_can_pay() {
|
fun an_empty_address_says_nobody_can_pay() {
|
||||||
val text = profileAddressNotice("")
|
val text = profileAddressNotice("")
|
||||||
assertTrue(text.contains("clears the profile address"))
|
assertTrue(text.contains("clears the profile address"))
|
||||||
assertTrue(text.contains("wallet child"))
|
// 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"))
|
assertTrue(text.contains("nobody can send you an invoice"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -207,8 +207,8 @@ class WalletChildStatusTextTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun stop_is_blocked_when_nothing_is_running() {
|
fun stop_is_blocked_when_nothing_is_running() {
|
||||||
assertTrue(stopBlockedReason(input("off"))!!.contains("No wallet child"))
|
assertTrue(stopBlockedReason(input("off"))!!.contains("No wallet is running"))
|
||||||
assertTrue(stopBlockedReason(input("exited"))!!.contains("No wallet child"))
|
assertTrue(stopBlockedReason(input("exited"))!!.contains("No wallet is running"))
|
||||||
assertEquals(READING_CHILD_NOTICE, stopBlockedReason(null))
|
assertEquals(READING_CHILD_NOTICE, stopBlockedReason(null))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -397,7 +397,7 @@ class WalletChildStatusTextTest {
|
||||||
"a screen reader is told the same as the eye",
|
"a screen reader is told the same as the eye",
|
||||||
spoken.endsWith(walletChildLine(input)),
|
spoken.endsWith(walletChildLine(input)),
|
||||||
)
|
)
|
||||||
assertTrue("it is still a sentence", spoken.startsWith("The wallet child is up"))
|
assertTrue("it is still a sentence", spoken.startsWith("The wallet is starting"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
@ -417,14 +417,17 @@ class WalletChildStatusTextTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun the_preproduction_warning_is_a_sentence_a_user_can_act_on() {
|
fun the_on_device_banner_is_titled_and_says_what_it_costs() {
|
||||||
val warning = CUPRATE_PREPRODUCTION_WARNING
|
// The banner's title is the plan's exact string; the body keeps every
|
||||||
assertTrue("it names the software", warning.contains("Cuprate"))
|
// honesty bound the old single-sentence warning carried.
|
||||||
assertTrue("it quotes the user book", warning.contains("do NOT use cuprated"))
|
assertEquals("Experimental On-Device Node (Cuprate)", CUPRATE_ON_DEVICE_TITLE)
|
||||||
assertTrue("it names the parity gap", warning.contains("Cuprate issue #278"))
|
val body = CUPRATE_ON_DEVICE_BODY
|
||||||
assertTrue("it says mainnet is unvalidated", warning.contains("mainnet is unvalidated"))
|
assertTrue("it names the software", body.contains("Cuprate"))
|
||||||
assertTrue("it is a sentence, not a glyph", warning.trim().endsWith("."))
|
assertTrue("it names the parity gap", body.contains("#278"))
|
||||||
assertTrue("it is long enough to be a sentence", warning.length > 80)
|
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 ----------------------------------------------------
|
// --- storage honesty ----------------------------------------------------
|
||||||
|
|
@ -519,4 +522,239 @@ class WalletChildStatusTextTest {
|
||||||
assertEquals("1.5 GiB", formatBytes(3L * 1024 * 1024 * 1024 / 2))
|
assertEquals("1.5 GiB", formatBytes(3L * 1024 * 1024 * 1024 / 2))
|
||||||
assertEquals("3.0 GiB", formatBytes(CHAIN_FREE_SPACE_FLOOR_BYTES))
|
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))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -117,7 +117,7 @@ class WalletManagerTest {
|
||||||
@Test
|
@Test
|
||||||
fun a_row_that_is_not_open_says_to_open_it() {
|
fun a_row_that_is_not_open_says_to_open_it() {
|
||||||
val why = walletSecretsBlockedReason(isActive = false, walletReadable = readable)
|
val why = walletSecretsBlockedReason(isActive = false, walletReadable = readable)
|
||||||
assertEquals("open this wallet to view its backup", why)
|
assertEquals("Open this wallet to view its backup.", why)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
@ -212,7 +212,7 @@ class WalletManagerTest {
|
||||||
walletPassphraseSubmitEnabled(activeFilename = null, typed = "pw", inFlight = false),
|
walletPassphraseSubmitEnabled(activeFilename = null, typed = "pw", inFlight = false),
|
||||||
)
|
)
|
||||||
val why = walletPassphraseBlockedReason(activeFilename = null, typed = "pw")
|
val why = walletPassphraseBlockedReason(activeFilename = null, typed = "pw")
|
||||||
assertTrue("got '$why'", why != null && why.contains("not pointed at"))
|
assertTrue("got '$why'", why != null && why.contains("No wallet file is open yet"))
|
||||||
// The two reasons are different fixes and must not read alike.
|
// The two reasons are different fixes and must not read alike.
|
||||||
assertFalse(why == walletPassphraseBlockedReason(activeFilename = openFile, typed = ""))
|
assertFalse(why == walletPassphraseBlockedReason(activeFilename = openFile, typed = ""))
|
||||||
}
|
}
|
||||||
|
|
@ -225,7 +225,7 @@ class WalletManagerTest {
|
||||||
@Test
|
@Test
|
||||||
fun nothing_typed_is_the_other_reason() {
|
fun nothing_typed_is_the_other_reason() {
|
||||||
val why = walletPassphraseBlockedReason(activeFilename = openFile, typed = "")
|
val why = walletPassphraseBlockedReason(activeFilename = openFile, typed = "")
|
||||||
assertTrue("got '$why'", why != null && why.contains("type the passphrase"))
|
assertTrue("got '$why'", why != null && why.contains("Type the passphrase"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- the daemon's own words never reach the screen -----------------------
|
// --- the daemon's own words never reach the screen -----------------------
|
||||||
|
|
@ -348,7 +348,12 @@ class WalletManagerTest {
|
||||||
walletOpen = false,
|
walletOpen = false,
|
||||||
needsPassphrase = false,
|
needsPassphrase = false,
|
||||||
)
|
)
|
||||||
assertTrue("got '$hint'", hint != null && hint.contains("No wallet is open"))
|
// 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!!)
|
assertNoRawRpc(hint!!)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -463,7 +468,7 @@ class WalletManagerTest {
|
||||||
fun wallet_reads_reload_only_once_the_child_is_answering() {
|
fun wallet_reads_reload_only_once_the_child_is_answering() {
|
||||||
// `walletBalance()` answers `"err"` — it does not throw — while the
|
// `walletBalance()` answers `"err"` — it does not throw — while the
|
||||||
// child is still dialling, so reloading in that window is what pins the
|
// child is still dialling, so reloading in that window is what pins the
|
||||||
// headline on `balance —`. Reload only when the child has answered.
|
// headline on `Balance unavailable`. Reload only when the child has answered.
|
||||||
assertFalse(shouldReloadWalletReads(null))
|
assertFalse(shouldReloadWalletReads(null))
|
||||||
assertFalse(shouldReloadWalletReads("off"))
|
assertFalse(shouldReloadWalletReads("off"))
|
||||||
assertFalse(shouldReloadWalletReads("connecting"))
|
assertFalse(shouldReloadWalletReads("connecting"))
|
||||||
|
|
@ -472,4 +477,27 @@ class WalletManagerTest {
|
||||||
assertTrue(shouldReloadWalletReads("ready"))
|
assertTrue(shouldReloadWalletReads("ready"))
|
||||||
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(""))
|
||||||
|
}
|
||||||
|
}
|
||||||
807
crates/onionwire-sdk/Cargo.lock
generated
807
crates/onionwire-sdk/Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -33,7 +33,7 @@ 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.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -12,13 +12,19 @@ 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:
|
||||||
|
|
@ -29,16 +35,16 @@ Two crate features re-expose Arti's TLS backends, which Arti marks
|
||||||
features (without it the rustls backend compiles with no provider).
|
features (without it the rustls backend compiles with no provider).
|
||||||
* `native-tls` → opt-in only, via OpenSSL.
|
* `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.98+.** `Cargo.toml` sets `edition = "2024"` and `rust-version = "1.98"`.
|
**rustc 1.98+.** `Cargo.toml` sets `edition = "2024"` and `rust-version = "1.98"`.
|
||||||
Arti 0.46 itself requires only 1.91; the higher floor is the default
|
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
|
`cuprate-daemon` feature (`tapes` calls `VecDeque::pop_front_if`, stable since
|
||||||
1.93). CI builds inside `rust:1.98-bookworm`
|
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`).
|
||||||
|
|
@ -79,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
|
||||||
|
|
|
||||||
|
|
@ -312,20 +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.
|
||||||
|
|
||||||
`tip` is signed over the LF-joined fields only (no domain tag on encode today).
|
The invite string is separate and uses `onionwire-invite-v2` (see Invite).
|
||||||
The `tip ` prefix is not signed.
|
|
||||||
|
|
||||||
The invite string is separate and keeps `onionwire-invite-v1` (see Invite).
|
Legacy acceptance is one switch, `LEGACY_SIGS`, default **on**. Every fallback
|
||||||
|
listed below reads it; with it off, verification accepts only the emitted
|
||||||
|
(tagged) form. It is a local capability constant, not a wire field: it is never
|
||||||
|
sent, and a peer cannot negotiate it.
|
||||||
|
|
||||||
Older builds verify only the untagged bytes, so they reject tagged signatures
|
| frame | emitted | accepted inbound |
|
||||||
(fail closed, no downgrade). Mixed-version fleets break outbound application
|
| --- | --- | --- |
|
||||||
frames from a new sender to an old receiver until both sides are updated.
|
| 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
|
||||||
|
|
||||||
|
|
@ -348,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:
|
||||||
|
|
||||||
|
|
@ -380,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.
|
||||||
|
|
@ -403,8 +425,8 @@ 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. It is one-shot: if the peer onion
|
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.
|
is down, the send fails. There is no queued invoice.
|
||||||
|
|
@ -425,8 +447,8 @@ 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
|
||||||
|
|
@ -442,13 +464,20 @@ Sent after a chain transfer, together with `rcp `. One-shot.
|
||||||
tip <txid>\n<amount_atomic>\n<address>\n<memo>\n<ts>\n<sig_hex>
|
tip <txid>\n<amount_atomic>\n<address>\n<memo>\n<ts>\n<sig_hex>
|
||||||
```
|
```
|
||||||
|
|
||||||
The `tip ` prefix is **not** signed. Encode signs the LF-joined fields:
|
The `tip ` prefix is **not** signed.
|
||||||
|
|
||||||
|
**Current signature (encode this):**
|
||||||
|
|
||||||
```
|
```
|
||||||
ed25519_sign(identity_sk,
|
ed25519_sign(identity_sk,
|
||||||
txid || LF || amount_atomic || LF || address || LF || memo || LF || ascii(ts))
|
"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.
|
`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,
|
A peer that does not implement `tip ` MUST drop it as an unknown typed prefix,
|
||||||
not render it as chat.
|
not render it as chat.
|
||||||
|
|
@ -880,7 +909,8 @@ signature covers `kem_ascii`, removing the field or substituting a different
|
||||||
key fails verification — that is the anti-strip/anti-substitution property.
|
key fails verification — that is the anti-strip/anti-substitution property.
|
||||||
|
|
||||||
**Legacy accept (`onionwire:v1`):** a v1 invite has no `kem` field. Decode
|
**Legacy accept (`onionwire:v1`):** a v1 invite has no `kem` field. Decode
|
||||||
accepts it and yields a friend with no `kem_pk`, i.e. a classical peer. A v1
|
accepts it while `LEGACY_SIGS` is on and yields a friend with no `kem_pk`, i.e.
|
||||||
|
a classical peer; with the switch off a v1 invite fails closed. A v1
|
||||||
signature is accepted in either historical form: the tagged
|
signature is accepted in either historical form: the tagged
|
||||||
`"onionwire-invite-v1" || 0x00 || k || 0x00 || o || 0x00 || spk` or the raw
|
`"onionwire-invite-v1" || 0x00 || k || 0x00 || o || 0x00 || spk` or the raw
|
||||||
concatenation `k || o || spk` (no tag, no separators), so old invites keep
|
concatenation `k || o || spk` (no tag, no separators), so old invites keep
|
||||||
|
|
|
||||||
|
|
@ -110,11 +110,19 @@ The `SOURCE_DATE_EPOCH` step reads the committer time of
|
||||||
`needs.version.outputs.sha`. It is deliberately not "now": a rebuild of this tag
|
`needs.version.outputs.sha`. It is deliberately not "now": a rebuild of this tag
|
||||||
in six months has to hand the compiler the same epoch CI handed it.
|
in six months has to hand the compiler the same epoch CI handed it.
|
||||||
|
|
||||||
`publish` job (Pi runner) downloads both artifacts, refuses any empty file,
|
`publish` job (Pi runner) downloads both artifacts, stages them into `dist/`,
|
||||||
and calls `scripts/publish-release.sh` to create-or-update the release with all
|
signs every asset with `scripts/sign-release.sh` inside the same digest-pinned
|
||||||
four Linux assets. If this job fails and the tag was created by *this* run, the
|
builder image, and only then calls `scripts/publish-release.sh` to create-or-update
|
||||||
final step deletes the incomplete release and the tag. A failed `aarch64` or
|
the release with all four Linux assets plus the committed public key. Signing runs
|
||||||
`x86_64` job always fails `publish`, so nothing is published half-built.
|
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
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -59,9 +59,18 @@ What this does **not** buy:
|
||||||
## 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
|
||||||
|
|
@ -312,7 +321,7 @@ the app does not pick a public remote node for them.
|
||||||
every in-process surface still says `testnet only — mainnet is unvalidated`.
|
every in-process surface still says `testnet only — mainnet is unvalidated`.
|
||||||
Cross-compiled is not device-proven.
|
Cross-compiled is not device-proven.
|
||||||
- Cuprate's own `arti` feature is off (its Tor stack is `arti-client` 0.44,
|
- Cuprate's own `arti` feature is off (its Tor stack is `arti-client` 0.44,
|
||||||
which cannot unify with this crate's 0.46), so the in-process daemon's P2P
|
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
|
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,
|
peers. No Tor is on the chain path — Tor is the messenger's transport here,
|
||||||
not the chain's.
|
not the chain's.
|
||||||
|
|
@ -331,8 +340,8 @@ the app does not pick a public remote node for them.
|
||||||
`connect()`, and not a C-tor fallback for chat). That listener is the
|
`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
|
bundled `arti` **binary** run as a child (`arti proxy -p <port>`) — a
|
||||||
second, separate Tor client with its own state and cache dirs, because
|
second, separate Tor client with its own state and cache dirs, because
|
||||||
`arti-client` 0.46 exposes no SOCKS listener API. It is TCP loopback only
|
`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.46
|
(`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
|
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,
|
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
|
not an access-controlled one. The app gates the spawn on the unlocked store
|
||||||
|
|
|
||||||
|
|
@ -67,7 +67,7 @@ missing:
|
||||||
|
|
||||||
- **`/releases/latest/download/…` is not served by this Forgejo — it is a 404.**
|
- **`/releases/latest/download/…` is not served by this Forgejo — it is a 404.**
|
||||||
The GitHub habit fails here. Always pin the tag:
|
The GitHub habit fails here. Always pin the tag:
|
||||||
`…/releases/download/v0.5.0/onionwire-x86_64-unknown-linux-gnu`.
|
`…/releases/download/v0.7.0/onionwire-x86_64-unknown-linux-gnu`.
|
||||||
- **Cloudflare in front of the Forgejo rejects non-browser User-Agents.** A
|
- **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
|
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
|
`error code: 1010` — even with a correct tag and URL. Measured against a real
|
||||||
|
|
@ -157,10 +157,10 @@ is public": *the binary I downloaded might not be that source.*
|
||||||
git clone https://forgejo.siriusdevops.com/sirius/onionwire
|
git clone https://forgejo.siriusdevops.com/sirius/onionwire
|
||||||
cd onionwire
|
cd onionwire
|
||||||
git fetch --tags
|
git fetch --tags
|
||||||
scripts/verify-reproducible.sh v0.5.0
|
scripts/verify-reproducible.sh v0.7.0
|
||||||
```
|
```
|
||||||
|
|
||||||
Replace `v0.5.0` with the tag you are checking. You need docker; you do not
|
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
|
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
|
the same builder image, pinned **by digest**, that CI uses, with the source
|
||||||
paths, the target path, and `SOURCE_DATE_EPOCH` all fixed by
|
paths, the target path, and `SOURCE_DATE_EPOCH` all fixed by
|
||||||
|
|
|
||||||
|
|
@ -181,7 +181,7 @@ for the TUI. A build with `--no-default-features` does not include the daemon.
|
||||||
Cross-compiled is not device-proven. Pointing a mainnet wallet at it is not
|
Cross-compiled is not device-proven. Pointing a mainnet wallet at it is not
|
||||||
something this build claims to do.
|
something this build claims to do.
|
||||||
- **No Tor on the chain path.** Cuprate's `arti` feature is off (arti-client
|
- **No Tor on the chain path.** Cuprate's `arti` feature is off (arti-client
|
||||||
0.44 vs this crate's 0.46). P2P is **clearnet**. OnionWire's Arti is the
|
0.44 vs this crate's 0.49). P2P is **clearnet**. OnionWire's Arti is the
|
||||||
messenger only.
|
messenger only.
|
||||||
- **Inbound P2P off**, restricted RPC listener disabled. Unrestricted RPC is
|
- **Inbound P2P off**, restricted RPC listener disabled. Unrestricted RPC is
|
||||||
loopback 18081. `--trusted-daemon` still never passed.
|
loopback 18081. `--trusted-daemon` still never passed.
|
||||||
|
|
@ -208,18 +208,42 @@ C++ binary, so it reaches Tor through a SOCKS proxy the app provides:
|
||||||
**Tor hides the transport, not the host.** The daemon operator still sees the
|
**Tor hides the transport, not the host.** The daemon operator still sees the
|
||||||
wallet's addresses during sync.
|
wallet's addresses during sync.
|
||||||
|
|
||||||
### Readiness — receipt verification needs a synced daemon
|
### Readiness — receipt verification needs a synced wallet
|
||||||
|
|
||||||
`chain_ready()` asks the wallet RPC `get_info` and requires
|
`chain_ready()` compares the wallet's **own scanned height** with the **chain
|
||||||
**`synchronized == true`** with `height > 0` and `height >= target_height`. A
|
tip**. Both halves must answer:
|
||||||
missing field is *not ready* — fail closed.
|
|
||||||
|
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
|
Until then, **receipt verification stays `verified=0`**. An unsynced wallet
|
||||||
cannot see the chain. That is an honest limit, not a UI bug.
|
cannot see the chain. That is an honest limit, not a UI bug.
|
||||||
|
|
||||||
Loopback management calls (`get_address`, `query_key`, create/import) get 5s.
|
Loopback management calls (`get_address`, `query_key`, create/import) get 5s.
|
||||||
Calls that wait on the chain (`get_info`, `get_transfers`, `transfer`) get 60s
|
Calls that wait on the chain (`get_transfers`, `transfer`) get 60s
|
||||||
(`CHAIN_RPC_TIMEOUT`).
|
(`CHAIN_RPC_TIMEOUT`). Readiness is not a chain wait: it is one local
|
||||||
|
`get_height` plus one bounded daemon probe.
|
||||||
|
|
||||||
## Env vars (migration path)
|
## Env vars (migration path)
|
||||||
|
|
||||||
|
|
@ -256,8 +280,9 @@ re-points the wallet without a restart; a rejected form writes nothing.
|
||||||
UniFFI: `set_chain_source(ChainConfig)` / `chain_source()`,
|
UniFFI: `set_chain_source(ChainConfig)` / `chain_source()`,
|
||||||
`start_wallet_child()`, `stop_wallet_child()`, `wallet_status()` (cached read:
|
`start_wallet_child()`, `stop_wallet_child()`, `wallet_status()` (cached read:
|
||||||
no dial, for first paint) and `wallet_child_refresh()` (a live probe of the
|
no dial, for first paint) and `wallet_child_refresh()` (a live probe of the
|
||||||
same record — it dials the loopback wallet RPC, and the local daemon's
|
same record — it dials the loopback wallet RPC and asks the configured daemon
|
||||||
`get_info` when that RPC does not answer, so poll it on the order of seconds).
|
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
|
Pass absolute paths for `wallet_rpc_bin` / `arti_bin` (`nativeLibraryDir`); the
|
||||||
core never resolves a binary the caller named explicitly.
|
core never resolves a binary the caller named explicitly.
|
||||||
|
|
||||||
|
|
|
||||||
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.
|
||||||
|
|
@ -10,26 +10,45 @@
|
||||||
//! Neither call may panic, and neither may leave the state mutated on a frame
|
//! Neither call may panic, and neither may leave the state mutated on a frame
|
||||||
//! it rejects (asserted in `tests/ratchet.rs`, re-checked cheaply here by
|
//! it rejects (asserted in `tests/ratchet.rs`, re-checked cheaply here by
|
||||||
//! re-serializing after every decrypt).
|
//! re-serializing after every decrypt).
|
||||||
|
//!
|
||||||
|
//! Both bootstrap shapes are exercised: a classical friend (`remote_kem_pub =
|
||||||
|
//! None`) and a hybrid friend, whose peer ML-KEM ratchet key is a real
|
||||||
|
//! encapsulation key of `kem::PK_LEN` bytes derived from a fixed seed. A
|
||||||
|
//! garbage key would only ever hit the "invalid encapsulation key" error path.
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
use onionwire::kem::{self, PK_LEN, SEED_LEN};
|
||||||
use onionwire::ratchet::{RatchetKeyPair, RatchetState};
|
use onionwire::ratchet::{RatchetKeyPair, RatchetState};
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
/// A canonical ML-KEM-768 encapsulation key, built once: key generation is
|
||||||
// Restore path: arbitrary bytes as a persisted ratchet state.
|
/// deterministic for a fixed seed, so this only pays for itself on iteration 1.
|
||||||
if let Ok(state) = RatchetState::from_bytes(data) {
|
fn peer_kem_pub() -> &'static [u8] {
|
||||||
// A state that parsed must re-serialize without panicking.
|
static PK: OnceLock<Vec<u8>> = OnceLock::new();
|
||||||
let _ = state.to_bytes();
|
PK.get_or_init(|| {
|
||||||
|
let pk = kem::pk_from_seed(&[0x44u8; SEED_LEN]).expect("64 bytes is a valid ML-KEM seed");
|
||||||
|
assert_eq!(pk.len(), PK_LEN, "crate ML-KEM public key length changed");
|
||||||
|
pk
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wire path: a fresh bootstrap epoch for every input, so one iteration can
|
fn bootstrap(remote_kem_pub: Option<&[u8]>) -> RatchetState {
|
||||||
// never influence the next. The keys are fixed (not fuzzed) on purpose:
|
// The keys are fixed (not fuzzed) on purpose: the interesting surface is
|
||||||
// the interesting surface is `data` as the frame.
|
// `data` as the frame.
|
||||||
let mut state = RatchetState::bootstrap(
|
RatchetState::bootstrap(
|
||||||
[0x42u8; 32],
|
[0x42u8; 32],
|
||||||
RatchetKeyPair::from_secret([0x11u8; 32]),
|
RatchetKeyPair::from_secret([0x11u8; 32]),
|
||||||
[0x33u8; 32],
|
[0x33u8; 32],
|
||||||
);
|
remote_kem_pub,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Feed `data` to a fresh state and hold the existing invariants: a reject must
|
||||||
|
/// roll back, an accept must have advanced the receiving chain, and re-sending
|
||||||
|
/// from the resulting state must not panic.
|
||||||
|
fn exercise(remote_kem_pub: Option<&[u8]>, data: &[u8]) {
|
||||||
|
let mut state = bootstrap(remote_kem_pub);
|
||||||
let before = state.to_bytes();
|
let before = state.to_bytes();
|
||||||
|
|
||||||
match state.decrypt(data) {
|
match state.decrypt(data) {
|
||||||
|
|
@ -45,4 +64,17 @@ fuzz_target!(|data: &[u8]| {
|
||||||
|
|
||||||
// Re-encrypting a byte-identical state must stay a pure function.
|
// Re-encrypting a byte-identical state must stay a pure function.
|
||||||
let _ = state.encrypt(b"fuzz");
|
let _ = state.encrypt(b"fuzz");
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
// Restore path: arbitrary bytes as a persisted ratchet state.
|
||||||
|
if let Ok(state) = RatchetState::from_bytes(data) {
|
||||||
|
// A state that parsed must re-serialize without panicking.
|
||||||
|
let _ = state.to_bytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wire path: a fresh bootstrap epoch for every input, so one iteration can
|
||||||
|
// never influence the next. Classical and hybrid, both.
|
||||||
|
exercise(None, data);
|
||||||
|
exercise(Some(peer_kem_pub()), data);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
2
scripts/onionwire-signing.pub
Normal file
2
scripts/onionwire-signing.pub
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
untrusted comment: minisign public key 806195CBAD1B1E56
|
||||||
|
RWRWHhuty5VhgHpdAsbzMVNLmu1mztJblfxv06HjtVcrKHKS75792Jb+
|
||||||
165
src/backup.rs
165
src/backup.rs
|
|
@ -1,4 +1,9 @@
|
||||||
//! Encrypted identity backup. Onion (locator) is not included.
|
//! Encrypted identity backup. Onion (locator) is not included.
|
||||||
|
//!
|
||||||
|
//! `seal()` writes `owbak1 || profile(1) || salt(16) || nonce(12) || ct`.
|
||||||
|
//! The pre-profile `owbak1 || salt(16) || nonce(12) || ct` layout is still
|
||||||
|
//! accepted as [`KdfProfile::Legacy`]; the two are unambiguous because the
|
||||||
|
//! plaintext is a fixed [`PLAIN_LEN`], so only two total lengths are legal.
|
||||||
|
|
||||||
use argon2::{Algorithm, Argon2, Params, Version};
|
use argon2::{Algorithm, Argon2, Params, Version};
|
||||||
use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng, Payload};
|
use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng, Payload};
|
||||||
|
|
@ -11,6 +16,52 @@ const SALT_LEN: usize = 16;
|
||||||
const NONCE_LEN: usize = 12;
|
const NONCE_LEN: usize = 12;
|
||||||
const KEY_LEN: usize = 32;
|
const KEY_LEN: usize = 32;
|
||||||
const PLAIN_LEN: usize = KEY_LEN * 4;
|
const PLAIN_LEN: usize = KEY_LEN * 4;
|
||||||
|
/// Salt + nonce + ciphertext + Poly1305 tag, i.e. everything after `MAGIC`.
|
||||||
|
const SEALED_BODY_LEN: usize = SALT_LEN + NONCE_LEN + PLAIN_LEN + 16;
|
||||||
|
|
||||||
|
/// Which Argon2id parameters a stored blob was written with.
|
||||||
|
///
|
||||||
|
/// The id is recorded with the data (a byte in the backup header, a
|
||||||
|
/// `store_meta.kdf_profile` column in the store). `Legacy` is id `0` and also
|
||||||
|
/// covers every blob written before profiles existed — those have no recorded
|
||||||
|
/// id at all. Never change an existing profile's parameters: a new cost means
|
||||||
|
/// a new id.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum KdfProfile {
|
||||||
|
/// m = 19_456 KiB, t = 2, p = 1.
|
||||||
|
Legacy,
|
||||||
|
/// m = 65_536 KiB (64 MiB), t = 3, p = 1.
|
||||||
|
Current,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KdfProfile {
|
||||||
|
pub(crate) const LEGACY_ID: u8 = 0;
|
||||||
|
pub(crate) const CURRENT_ID: u8 = 1;
|
||||||
|
|
||||||
|
pub(crate) fn id(self) -> u8 {
|
||||||
|
match self {
|
||||||
|
Self::Legacy => Self::LEGACY_ID,
|
||||||
|
Self::Current => Self::CURRENT_ID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strict: an id this build does not know is an error, never a fallback.
|
||||||
|
pub(crate) fn from_id(id: u8) -> Result<Self, String> {
|
||||||
|
match id {
|
||||||
|
Self::LEGACY_ID => Ok(Self::Legacy),
|
||||||
|
Self::CURRENT_ID => Ok(Self::Current),
|
||||||
|
other => Err(format!("unknown kdf profile {other}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn params(self) -> Result<Params, String> {
|
||||||
|
let (m_cost, t_cost, p_cost) = match self {
|
||||||
|
Self::Legacy => (19_456, 2, 1),
|
||||||
|
Self::Current => (65_536, 3, 1),
|
||||||
|
};
|
||||||
|
Params::new(m_cost, t_cost, p_cost, Some(KEY_LEN)).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The identity bundle. Secret halves wipe on drop; `Debug` never prints them.
|
/// The identity bundle. Secret halves wipe on drop; `Debug` never prints them.
|
||||||
#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
|
#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
|
||||||
|
|
@ -58,14 +109,21 @@ impl BackupKeys {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result<Zeroizing<[u8; 32]>, String> {
|
pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result<Zeroizing<[u8; 32]>, String> {
|
||||||
|
kdf_with(KdfProfile::Current, passphrase, salt)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn kdf_with(
|
||||||
|
profile: KdfProfile,
|
||||||
|
passphrase: &str,
|
||||||
|
salt: &[u8],
|
||||||
|
) -> Result<Zeroizing<[u8; 32]>, String> {
|
||||||
if passphrase.is_empty() {
|
if passphrase.is_empty() {
|
||||||
return Err("empty passphrase".into());
|
return Err("empty passphrase".into());
|
||||||
}
|
}
|
||||||
if salt.len() != SALT_LEN {
|
if salt.len() != SALT_LEN {
|
||||||
return Err("salt length".into());
|
return Err("salt length".into());
|
||||||
}
|
}
|
||||||
let params = Params::new(19_456, 2, 1, Some(32)).map_err(|e| e.to_string())?;
|
let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, profile.params()?);
|
||||||
let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
|
|
||||||
let mut key = Zeroizing::new([0u8; 32]);
|
let mut key = Zeroizing::new([0u8; 32]);
|
||||||
argon
|
argon
|
||||||
.hash_password_into(passphrase.as_bytes(), salt, &mut key[..])
|
.hash_password_into(passphrase.as_bytes(), salt, &mut key[..])
|
||||||
|
|
@ -85,8 +143,9 @@ pub fn seal(passphrase: &str, keys: &BackupKeys) -> Result<Vec<u8>, String> {
|
||||||
let ct = cipher
|
let ct = cipher
|
||||||
.encrypt(&nonce, &keys.to_bytes()[..])
|
.encrypt(&nonce, &keys.to_bytes()[..])
|
||||||
.map_err(|_| "encrypt failed".to_string())?;
|
.map_err(|_| "encrypt failed".to_string())?;
|
||||||
let mut out = Vec::with_capacity(MAGIC.len() + SALT_LEN + NONCE_LEN + ct.len());
|
let mut out = Vec::with_capacity(MAGIC.len() + 1 + SEALED_BODY_LEN);
|
||||||
out.extend_from_slice(MAGIC);
|
out.extend_from_slice(MAGIC);
|
||||||
|
out.push(KdfProfile::Current.id());
|
||||||
out.extend_from_slice(&salt);
|
out.extend_from_slice(&salt);
|
||||||
out.extend_from_slice(&nonce);
|
out.extend_from_slice(&nonce);
|
||||||
out.extend_from_slice(&ct);
|
out.extend_from_slice(&ct);
|
||||||
|
|
@ -94,15 +153,25 @@ pub fn seal(passphrase: &str, keys: &BackupKeys) -> Result<Vec<u8>, String> {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn open(passphrase: &str, blob: &[u8]) -> Result<BackupKeys, String> {
|
pub fn open(passphrase: &str, blob: &[u8]) -> Result<BackupKeys, String> {
|
||||||
let min = MAGIC.len() + SALT_LEN + NONCE_LEN + 16;
|
if !blob.starts_with(MAGIC) {
|
||||||
if blob.len() < min || !blob.starts_with(MAGIC) {
|
|
||||||
return Err("not an onionwire backup".into());
|
return Err("not an onionwire backup".into());
|
||||||
}
|
}
|
||||||
let salt = &blob[MAGIC.len()..MAGIC.len() + SALT_LEN];
|
let rest = &blob[MAGIC.len()..];
|
||||||
let nonce_off = MAGIC.len() + SALT_LEN;
|
// The sealed plaintext is a fixed size, so a legacy blob is exactly
|
||||||
let nonce = Nonce::from_slice(&blob[nonce_off..nonce_off + NONCE_LEN]);
|
// SEALED_BODY_LEN bytes after MAGIC and a versioned one is one byte longer.
|
||||||
let ct = &blob[nonce_off + NONCE_LEN..];
|
let (profile, body) = match rest.len() {
|
||||||
let key = kdf(passphrase, salt)?;
|
SEALED_BODY_LEN => (KdfProfile::Legacy, rest),
|
||||||
|
n if n == SEALED_BODY_LEN + 1 => {
|
||||||
|
let profile = KdfProfile::from_id(rest[0])?;
|
||||||
|
(profile, &rest[1..])
|
||||||
|
}
|
||||||
|
_ => return Err("not an onionwire backup".into()),
|
||||||
|
};
|
||||||
|
let salt = &body[..SALT_LEN];
|
||||||
|
let nonce_off = SALT_LEN;
|
||||||
|
let nonce = Nonce::from_slice(&body[nonce_off..nonce_off + NONCE_LEN]);
|
||||||
|
let ct = &body[nonce_off + NONCE_LEN..];
|
||||||
|
let key = kdf_with(profile, passphrase, salt)?;
|
||||||
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..]));
|
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..]));
|
||||||
let pt = Zeroizing::new(
|
let pt = Zeroizing::new(
|
||||||
cipher
|
cipher
|
||||||
|
|
@ -191,4 +260,80 @@ mod tests {
|
||||||
assert!(dbg.contains("<redacted>"), "{dbg}");
|
assert!(dbg.contains("<redacted>"), "{dbg}");
|
||||||
assert!(dbg.contains("174"), "public half should stay: {dbg}");
|
assert!(dbg.contains("174"), "public half should stay: {dbg}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The pre-profile layout: `MAGIC || salt || nonce || ct`, no id byte.
|
||||||
|
fn legacy_blob(passphrase: &str, keys: &BackupKeys) -> Vec<u8> {
|
||||||
|
let salt = [0x5Au8; SALT_LEN];
|
||||||
|
let key = kdf_with(KdfProfile::Legacy, passphrase, &salt).expect("legacy kdf");
|
||||||
|
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..]));
|
||||||
|
let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
|
||||||
|
let ct = cipher.encrypt(&nonce, &keys.to_bytes()[..]).expect("seal");
|
||||||
|
let mut out = Vec::new();
|
||||||
|
out.extend_from_slice(MAGIC);
|
||||||
|
out.extend_from_slice(&salt);
|
||||||
|
out.extend_from_slice(&nonce);
|
||||||
|
out.extend_from_slice(&ct);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sealed_blob_records_the_current_profile_and_roundtrips() {
|
||||||
|
let k = keys(9);
|
||||||
|
let blob = seal("correct horse", &k).expect("seal");
|
||||||
|
assert_eq!(blob.len(), MAGIC.len() + 1 + SEALED_BODY_LEN);
|
||||||
|
assert_eq!(
|
||||||
|
blob[MAGIC.len()],
|
||||||
|
KdfProfile::Current.id(),
|
||||||
|
"new blobs must name their KDF profile"
|
||||||
|
);
|
||||||
|
assert_eq!(open("correct horse", &blob).expect("open"), k);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_profile_blob_still_opens() {
|
||||||
|
let k = keys(4);
|
||||||
|
let blob = legacy_blob("correct horse", &k);
|
||||||
|
assert_eq!(blob.len(), MAGIC.len() + SEALED_BODY_LEN);
|
||||||
|
assert_eq!(open("correct horse", &blob).expect("legacy open"), k);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_passphrase_on_a_current_profile_blob_is_the_existing_error() {
|
||||||
|
let blob = seal("right", &keys(1)).expect("seal");
|
||||||
|
let err = open("wrong", &blob).expect_err("wrong passphrase must fail");
|
||||||
|
assert_eq!(err, "wrong passphrase or corrupt backup");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_profile_id_is_a_clear_error_not_a_fallback() {
|
||||||
|
let mut blob = seal("pw", &keys(2)).expect("seal");
|
||||||
|
blob[MAGIC.len()] = 9;
|
||||||
|
let err = open("pw", &blob).expect_err("unknown profile must fail");
|
||||||
|
assert_eq!(err, "unknown kdf profile 9");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn trailing_garbage_is_not_an_onionwire_backup() {
|
||||||
|
let mut blob = seal("pw", &keys(3)).expect("seal");
|
||||||
|
blob.push(0xff);
|
||||||
|
assert_eq!(
|
||||||
|
open("pw", &blob).expect_err("must reject"),
|
||||||
|
"not an onionwire backup"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore = "manual KDF timing measurement; run with --release --ignored"]
|
||||||
|
fn kdf_profile_timings() {
|
||||||
|
use std::time::Instant;
|
||||||
|
let salt = [0x11u8; SALT_LEN];
|
||||||
|
for (label, profile) in [
|
||||||
|
("legacy m=19456 t=2 p=1", KdfProfile::Legacy),
|
||||||
|
("current m=65536 t=3 p=1", KdfProfile::Current),
|
||||||
|
] {
|
||||||
|
let started = Instant::now();
|
||||||
|
let _ = kdf_with(profile, "correct horse battery staple", &salt).expect("kdf");
|
||||||
|
eprintln!("{label}: {:.3}s", started.elapsed().as_secs_f64());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@
|
||||||
//! name reservation), so a pinned revision is the only honest way to depend on
|
//! name reservation), so a pinned revision is the only honest way to depend on
|
||||||
//! it.
|
//! it.
|
||||||
//! * Cuprate's own `arti` feature stays **off**. Its Tor stack is arti 0.44,
|
//! * Cuprate's own `arti` feature stays **off**. Its Tor stack is arti 0.44,
|
||||||
//! which cannot unify with this crate's arti 0.46, and this daemon is
|
//! which cannot unify with this crate's arti 0.49, and this daemon is
|
||||||
//! clearnet-only: OnionWire's Arti is the only Tor in the process.
|
//! clearnet-only: OnionWire's Arti is the only Tor in the process.
|
||||||
//! * The **unrestricted** RPC listener binds `127.0.0.1:<port>` — the address
|
//! * The **unrestricted** RPC listener binds `127.0.0.1:<port>` — the address
|
||||||
//! `WalletChild::daemon_address` returns for a local source. The restricted
|
//! `WalletChild::daemon_address` returns for a local source. The restricted
|
||||||
|
|
|
||||||
|
|
@ -54,9 +54,10 @@ pub fn verify(identity_pk: &[u8], loc: &Loc) -> bool {
|
||||||
let signature = Signature::from_bytes(&sig);
|
let signature = Signature::from_bytes(&sig);
|
||||||
vk.verify(&sign_msg_v2(&loc.onion, loc.ts), &signature)
|
vk.verify(&sign_msg_v2(&loc.onion, loc.ts), &signature)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
|| vk
|
|| (crate::pay::legacy_sigs()
|
||||||
|
&& vk
|
||||||
.verify(&sign_msg_v1(&loc.onion, loc.ts), &signature)
|
.verify(&sign_msg_v1(&loc.onion, loc.ts), &signature)
|
||||||
.is_ok()
|
.is_ok())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn encode(loc: &Loc) -> Vec<u8> {
|
pub fn encode(loc: &Loc) -> Vec<u8> {
|
||||||
|
|
|
||||||
187
src/node.rs
187
src/node.rs
|
|
@ -1065,7 +1065,12 @@ impl Node {
|
||||||
return self.wallet_child_status();
|
return self.wallet_child_status();
|
||||||
}
|
}
|
||||||
let cfg = self.wallet_child_config();
|
let cfg = self.wallet_child_config();
|
||||||
let w = self.wallet_snapshot();
|
// Readiness needs both halves: the wallet's own `get_height` and the
|
||||||
|
// chain tip. The tip comes from the configured daemon (loopback for a
|
||||||
|
// local source, the clearnet host the user typed, never a `.onion`).
|
||||||
|
let w = self
|
||||||
|
.wallet_snapshot()
|
||||||
|
.with_daemon_probe(cfg.daemon_probe_addr());
|
||||||
if !w.configured() {
|
if !w.configured() {
|
||||||
return self.wallet_child_status();
|
return self.wallet_child_status();
|
||||||
}
|
}
|
||||||
|
|
@ -1090,7 +1095,7 @@ impl Node {
|
||||||
}
|
}
|
||||||
let synced = progress.as_ref().is_some_and(wallet::ChainInfo::ready);
|
let synced = progress.as_ref().is_some_and(wallet::ChainInfo::ready);
|
||||||
let (height, target_height) = match progress {
|
let (height, target_height) = match progress {
|
||||||
Some(info) => (info.height, info.target_height),
|
Some(info) => (info.height, info.tip.unwrap_or(0)),
|
||||||
// The wallet RPC is the honest source when it answers. When it does
|
// The wallet RPC is the honest source when it answers. When it does
|
||||||
// not (a refused connection is the common one), the daemon this box
|
// not (a refused connection is the common one), the daemon this box
|
||||||
// owns can still say — and a daemon that does not answer leaves
|
// owns can still say — and a daemon that does not answer leaves
|
||||||
|
|
@ -1334,7 +1339,9 @@ impl Node {
|
||||||
|
|
||||||
/// Pay selected friend via wallet RPC, then signed receipt.
|
/// Pay selected friend via wallet RPC, then signed receipt.
|
||||||
pub async fn tip(&self, friend_pk: &[u8], atomic: &str, memo: &str) -> Result<(), String> {
|
pub async fn tip(&self, friend_pk: &[u8], atomic: &str, memo: &str) -> Result<(), String> {
|
||||||
let w = self.wallet_snapshot();
|
let w = self
|
||||||
|
.wallet_snapshot()
|
||||||
|
.with_daemon_probe(self.wallet_child_config().daemon_probe_addr());
|
||||||
if !w.configured() {
|
if !w.configured() {
|
||||||
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||||||
}
|
}
|
||||||
|
|
@ -2153,7 +2160,9 @@ impl Node {
|
||||||
// Honest prerequisite: an unsynced wallet cannot see the tx, so a
|
// Honest prerequisite: an unsynced wallet cannot see the tx, so a
|
||||||
// get_transfers "miss" would be a lie. Until the chain is ready the
|
// get_transfers "miss" would be a lie. Until the chain is ready the
|
||||||
// receipt stays verified=0 — that is the correct state, not an error.
|
// receipt stays verified=0 — that is the correct state, not an error.
|
||||||
let w = self.wallet_snapshot();
|
let w = self
|
||||||
|
.wallet_snapshot()
|
||||||
|
.with_daemon_probe(self.wallet_child_config().daemon_probe_addr());
|
||||||
let ready = w.configured() && w.can_verify_receipts().await;
|
let ready = w.configured() && w.can_verify_receipts().await;
|
||||||
if ready {
|
if ready {
|
||||||
match w.get_transfers().await {
|
match w.get_transfers().await {
|
||||||
|
|
@ -3417,25 +3426,43 @@ pub(crate) mod tests {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A loopback wallet RPC that answers what the tip path actually asks for:
|
/// A loopback wallet RPC that answers what the tip path actually asks for:
|
||||||
/// a digest challenge, then a synced `get_info` for the readiness gate and
|
/// a digest challenge, then the wallet's own scanned `get_height` for the
|
||||||
/// `tx_hash` for the transfer. The old single-answer mock stopped covering
|
/// readiness gate and `tx_hash` for the transfer. `get_info` is a daemon
|
||||||
/// the path when `Wallet::transfer` started probing the chain tip first —
|
/// method, not a wallet one, so it is never asked. Returns the wallet and
|
||||||
/// it answered `tx_hash` to `get_info` and every tip was refused as unsynced.
|
/// the daemon stub's address (the tip the gate compares against).
|
||||||
async fn mock_wallet() -> Wallet {
|
async fn mock_wallet() -> (Wallet, String) {
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||||
.await
|
.await
|
||||||
.expect("bind mock wallet");
|
.expect("bind mock wallet");
|
||||||
let port = listener.local_addr().expect("mock wallet addr").port();
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||||||
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(|req: &str| {
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(|req: &str| {
|
||||||
if req.contains("get_info") {
|
if req.contains("get_height") {
|
||||||
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
|
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100}}"#.to_string()
|
||||||
.to_string()
|
|
||||||
} else {
|
} else {
|
||||||
r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#.to_string()
|
r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#.to_string()
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
tokio::spawn(serve_mock_rpc(listener, reply));
|
tokio::spawn(serve_mock_rpc(listener, reply));
|
||||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
let wallet = Wallet::from_url(&format!("http://ow:[email protected]:{port}"))
|
||||||
|
.expect("wallet url");
|
||||||
|
let daemon = mock_daemon(100, 100).await;
|
||||||
|
(wallet, daemon)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Point a test node's chain source at a daemon stub, so readiness has a
|
||||||
|
/// tip to compare the wallet's scanned height against.
|
||||||
|
fn chain_source_at(node: &Node, addr: &str) {
|
||||||
|
let (host, port) = addr.rsplit_once(':').expect("host:port");
|
||||||
|
node.set_wallet_child_config(&ChildConfig {
|
||||||
|
source: ChainSource::Remote {
|
||||||
|
host: host.to_string(),
|
||||||
|
port: port.parse().expect("port"),
|
||||||
|
},
|
||||||
|
wallet_rpc_bin: PathBuf::from("monero-wallet-rpc"),
|
||||||
|
arti_bin: PathBuf::from("arti"),
|
||||||
|
wallet_filename: wallet::DEFAULT_WALLET_FILENAME.to_string(),
|
||||||
|
})
|
||||||
|
.expect("set chain source");
|
||||||
}
|
}
|
||||||
/// The payer of a tip must see it in their own chat: `receipt_chat_line` is
|
/// The payer of a tip must see it in their own chat: `receipt_chat_line` is
|
||||||
/// the recipient's view of the frame that arrived, `tip_chat_line` is what
|
/// the recipient's view of the frame that arrived, `tip_chat_line` is what
|
||||||
|
|
@ -3443,11 +3470,9 @@ pub(crate) mod tests {
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn outbound_tip_appends_the_senders_own_tip_chat_line() {
|
async fn outbound_tip_appends_the_senders_own_tip_chat_line() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let node = offline_node_with_wallet(
|
let (wallet, daemon) = mock_wallet().await;
|
||||||
&dir.path().join("bob"),
|
let node = offline_node_with_wallet(&dir.path().join("bob"), Arc::new(DialOk), wallet);
|
||||||
Arc::new(DialOk),
|
chain_source_at(&node, &daemon);
|
||||||
mock_wallet().await,
|
|
||||||
);
|
|
||||||
let peer = Keys::generate();
|
let peer = Keys::generate();
|
||||||
let addr = xmr_addr();
|
let addr = xmr_addr();
|
||||||
{
|
{
|
||||||
|
|
@ -3548,11 +3573,9 @@ pub(crate) mod tests {
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn outbound_tip_records_a_tip_payment_row() {
|
async fn outbound_tip_records_a_tip_payment_row() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let node = offline_node_with_wallet(
|
let (wallet, daemon) = mock_wallet().await;
|
||||||
&dir.path().join("bob"),
|
let node = offline_node_with_wallet(&dir.path().join("bob"), Arc::new(DialOk), wallet);
|
||||||
Arc::new(DialOk),
|
chain_source_at(&node, &daemon);
|
||||||
mock_wallet().await,
|
|
||||||
);
|
|
||||||
let peer = Keys::generate();
|
let peer = Keys::generate();
|
||||||
let addr = xmr_addr();
|
let addr = xmr_addr();
|
||||||
{
|
{
|
||||||
|
|
@ -3767,23 +3790,62 @@ pub(crate) mod tests {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A chain-daemon stub on an ephemeral loopback port: `GET /get_height`
|
||||||
|
/// answers the tip, `/json_rpc get_info` answers height/target. Returns
|
||||||
|
/// `host:port`.
|
||||||
|
async fn mock_daemon(height: u64, target: u64) -> String {
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||||
|
.await
|
||||||
|
.expect("bind mock daemon");
|
||||||
|
let addr = listener.local_addr().expect("mock daemon addr").to_string();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Ok((mut sock, _)) = listener.accept().await {
|
||||||
|
let mut buf = vec![0u8; 4096];
|
||||||
|
let Ok(n) = sock.read(&mut buf).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if n == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let req = String::from_utf8_lossy(&buf[..n]).to_string();
|
||||||
|
let body = if req.starts_with("GET /get_height") {
|
||||||
|
format!(r#"{{"height":{height}}}"#)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target}}}}}"#
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let _ = sock
|
||||||
|
.write_all(
|
||||||
|
format!(
|
||||||
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
)
|
||||||
|
.as_bytes(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
addr
|
||||||
|
}
|
||||||
|
|
||||||
/// A loopback wallet RPC that answers the *status* probe: a digest
|
/// A loopback wallet RPC that answers the *status* probe: a digest
|
||||||
/// challenge, then `get_address` / `get_balance` / `get_info`, with the
|
/// challenge, then `get_address` / `get_balance` / `get_height`, with the
|
||||||
/// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the
|
/// wallet's own scanned height. Returns the wallet and the daemon stub's
|
||||||
/// *transfer* path; this one answers a refresh, which never transfers.
|
/// address — the tip comes from the daemon, never from the wallet RPC.
|
||||||
/// A loopback wallet RPC that answers the *status* probe: a digest
|
/// [`mock_wallet`] above answers the *transfer* path; this one answers a
|
||||||
/// challenge, then `get_address` / `get_balance` / `get_info`, with the
|
/// refresh, which never transfers.
|
||||||
/// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the
|
async fn mock_syncing_wallet(height: u64, target: u64) -> (Wallet, String) {
|
||||||
/// *transfer* path; this one answers a refresh, which never transfers.
|
|
||||||
async fn mock_syncing_wallet(height: u64, target: u64) -> Wallet {
|
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||||
.await
|
.await
|
||||||
.expect("bind mock wallet");
|
.expect("bind mock wallet");
|
||||||
let port = listener.local_addr().expect("mock wallet addr").port();
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||||||
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
|
||||||
if req.contains("get_info") {
|
if req.contains("get_height") {
|
||||||
format!(
|
format!(
|
||||||
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"#
|
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height}}}}}"#
|
||||||
)
|
)
|
||||||
} else if req.contains("get_address") {
|
} else if req.contains("get_address") {
|
||||||
format!(
|
format!(
|
||||||
|
|
@ -3795,7 +3857,10 @@ pub(crate) mod tests {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
tokio::spawn(serve_mock_rpc(listener, reply));
|
tokio::spawn(serve_mock_rpc(listener, reply));
|
||||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
let wallet =
|
||||||
|
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url");
|
||||||
|
let daemon = mock_daemon(height, target).await;
|
||||||
|
(wallet, daemon)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Point `node`'s wallet client at a mock. The child process stays whatever
|
/// Point `node`'s wallet client at a mock. The child process stays whatever
|
||||||
|
|
@ -3804,13 +3869,14 @@ pub(crate) mod tests {
|
||||||
*node.wallet.lock().expect("wallet") = wallet;
|
*node.wallet.lock().expect("wallet") = wallet;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Like [`mock_syncing_wallet`], but `height` is read on every `get_info`,
|
/// Like [`mock_syncing_wallet`], but the wallet's scanned `height` is read on
|
||||||
/// so a later store is a later answer. `synchronized` stays false: the
|
/// every `get_height`, so a later store is a later answer. The daemon stub
|
||||||
/// status line is a syncing chain, not a caught-up one.
|
/// reports `target` as its tip. Returns the wallet and the daemon address so
|
||||||
|
/// a caller can point a chain source at it.
|
||||||
pub(crate) async fn mock_wallet_at(
|
pub(crate) async fn mock_wallet_at(
|
||||||
height: std::sync::Arc<std::sync::atomic::AtomicU64>,
|
height: std::sync::Arc<std::sync::atomic::AtomicU64>,
|
||||||
target: u64,
|
target: u64,
|
||||||
) -> Wallet {
|
) -> (Wallet, String) {
|
||||||
use std::sync::atomic::Ordering;
|
use std::sync::atomic::Ordering;
|
||||||
|
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||||
|
|
@ -3818,11 +3884,9 @@ pub(crate) mod tests {
|
||||||
.expect("bind mock wallet");
|
.expect("bind mock wallet");
|
||||||
let port = listener.local_addr().expect("mock wallet addr").port();
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||||||
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
|
||||||
if req.contains("get_info") {
|
if req.contains("get_height") {
|
||||||
let h = height.load(Ordering::Relaxed);
|
let h = height.load(Ordering::Relaxed);
|
||||||
format!(
|
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{h}}}}}"#)
|
||||||
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{h},"target_height":{target},"synchronized":false}}}}"#
|
|
||||||
)
|
|
||||||
} else if req.contains("get_address") {
|
} else if req.contains("get_address") {
|
||||||
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4test"}}"#.to_string()
|
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4test"}}"#.to_string()
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -3830,7 +3894,10 @@ pub(crate) mod tests {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
tokio::spawn(serve_mock_rpc(listener, reply));
|
tokio::spawn(serve_mock_rpc(listener, reply));
|
||||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
let wallet =
|
||||||
|
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url");
|
||||||
|
let daemon = mock_daemon(target, target).await;
|
||||||
|
(wallet, daemon)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A loopback daemon that answers `get_info` on the port the child probes
|
/// A loopback daemon that answers `get_info` on the port the child probes
|
||||||
|
|
@ -3868,12 +3935,12 @@ pub(crate) mod tests {
|
||||||
Some(())
|
Some(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The status row carries the real chain numbers: a wallet RPC that answers
|
/// The status row carries the real chain numbers: the wallet RPC's own
|
||||||
/// `get_info` fills height and target, and the one-liner shows them. A
|
/// `get_height` is the wallet's scanned height, and the daemon's tip is the
|
||||||
/// daemon that reports no target is not a caught-up chain — `h/0` with no
|
/// target. A daemon that reports no separate target still gives a tip, so
|
||||||
/// invented percentage.
|
/// `h/h` is the honest line — never an invented percentage.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn a_wallet_that_answers_get_info_fills_the_chain_progress() {
|
async fn the_wallet_height_and_the_daemon_tip_fill_the_chain_progress() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
||||||
let log = dir.path().join("argv.log");
|
let log = dir.path().join("argv.log");
|
||||||
|
|
@ -3890,14 +3957,16 @@ pub(crate) mod tests {
|
||||||
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||||||
node.start_wallet_child().expect("start");
|
node.start_wallet_child().expect("start");
|
||||||
// The child is a fake process; the wallet the node actually talks to is
|
// The child is a fake process; the wallet the node actually talks to is
|
||||||
// the mock RPC, which is where the numbers come from.
|
// the mock RPC, and the tip comes from the daemon stub.
|
||||||
*node.wallet.lock().unwrap() = mock_syncing_wallet(4549, 0).await;
|
let (wallet, daemon) = mock_syncing_wallet(4549, 0).await;
|
||||||
|
*node.wallet.lock().unwrap() = wallet;
|
||||||
|
chain_source_at(&node, &daemon);
|
||||||
|
|
||||||
let status = node.wallet_child_refresh().await;
|
let status = node.wallet_child_refresh().await;
|
||||||
assert_eq!(status.state, WalletChildState::Ready, "{status:?}");
|
assert_eq!(status.state, WalletChildState::Ready, "{status:?}");
|
||||||
assert_eq!(status.height, 4549, "{status:?}");
|
assert_eq!(status.height, 4549, "{status:?}");
|
||||||
assert_eq!(status.target_height, 0, "{status:?}");
|
assert_eq!(status.target_height, 4549, "{status:?}");
|
||||||
assert!(status.line().contains("sync 4549/0"), "{}", status.line());
|
assert!(status.line().contains("sync 4549/4549"), "{}", status.line());
|
||||||
assert!(!status.line().contains('%'), "{}", status.line());
|
assert!(!status.line().contains('%'), "{}", status.line());
|
||||||
|
|
||||||
node.stop_wallet_child().expect("stop");
|
node.stop_wallet_child().expect("stop");
|
||||||
|
|
@ -4347,7 +4416,10 @@ pub(crate) mod tests {
|
||||||
let err = node
|
let err = node
|
||||||
.start_wallet_child()
|
.start_wallet_child()
|
||||||
.expect_err("a missing binary fails");
|
.expect_err("a missing binary fails");
|
||||||
assert!(err.contains("spawn"), "{err}");
|
// The refusal names the configured path: the old `spawn <label>` copy
|
||||||
|
// could not say which program was missing.
|
||||||
|
assert!(err.contains("/nonexistent/onionwire-wallet-rpc"), "{err}");
|
||||||
|
assert!(err.contains("not found"), "{err}");
|
||||||
let status = node.wallet_child_status();
|
let status = node.wallet_child_status();
|
||||||
assert_eq!(status.state, WalletChildState::Off);
|
assert_eq!(status.state, WalletChildState::Off);
|
||||||
assert!(!status.running);
|
assert!(!status.running);
|
||||||
|
|
@ -5014,9 +5086,8 @@ pub(crate) mod tests {
|
||||||
r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#,
|
r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#,
|
||||||
addr = xmr_addr()
|
addr = xmr_addr()
|
||||||
)
|
)
|
||||||
} else if req.contains("get_info") {
|
} else if req.contains("get_height") {
|
||||||
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
|
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100}}"#.to_string()
|
||||||
.to_string()
|
|
||||||
} else {
|
} else {
|
||||||
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0","unlocked_balance":"0"}}"#
|
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0","unlocked_balance":"0"}}"#
|
||||||
.to_string()
|
.to_string()
|
||||||
|
|
@ -5275,7 +5346,9 @@ pub(crate) mod tests {
|
||||||
);
|
);
|
||||||
|
|
||||||
// The read after the restart takes the success path: the same mock
|
// The read after the restart takes the success path: the same mock
|
||||||
// answers `get_address`/`get_balance`/`get_info`.
|
// answers `get_address` / `get_balance` / `get_height`.
|
||||||
|
let daemon = mock_daemon(100, 100).await;
|
||||||
|
chain_source_at(&node, &daemon);
|
||||||
let status = node.wallet_child_refresh().await;
|
let status = node.wallet_child_refresh().await;
|
||||||
assert!(status.wallet_open, "{status:?}");
|
assert!(status.wallet_open, "{status:?}");
|
||||||
assert!(!status.needs_passphrase, "{status:?}");
|
assert!(!status.needs_passphrase, "{status:?}");
|
||||||
|
|
|
||||||
88
src/pay.rs
88
src/pay.rs
|
|
@ -1,9 +1,47 @@
|
||||||
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
|
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
|
||||||
use sha3::{Digest, Keccak256};
|
use sha3::{Digest, Keccak256};
|
||||||
|
use std::cell::Cell;
|
||||||
use zeroize::Zeroizing;
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
pub type Result<T> = std::result::Result<T, Error>;
|
pub type Result<T> = std::result::Result<T, Error>;
|
||||||
|
|
||||||
|
/// Legacy signature acceptance.
|
||||||
|
///
|
||||||
|
/// Every signed frame is **emitted** in its domain-tagged form. Inbound, the
|
||||||
|
/// historical untagged / LF-joined layout (and the `onionwire:v1` invite
|
||||||
|
/// string) is still accepted so a mixed-version fleet keeps working; that
|
||||||
|
/// fallback is gated on this one switch. Set it to `false` to fail closed on
|
||||||
|
/// legacy signatures for every frame that reads it — `loc`, the invite string,
|
||||||
|
/// `inv`, `rcp`, and `tip`. (`prf` is not yet gated; see `docs/PROTOCOL.md`.)
|
||||||
|
pub const LEGACY_SIGS: bool = true;
|
||||||
|
|
||||||
|
thread_local! {
|
||||||
|
/// Per-thread override for tests. `None` follows [`LEGACY_SIGS`].
|
||||||
|
static LEGACY_SIGS_OVERRIDE: Cell<Option<bool>> = const { Cell::new(None) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether legacy (pre-domain-tag) signatures are accepted inbound.
|
||||||
|
pub fn legacy_sigs() -> bool {
|
||||||
|
LEGACY_SIGS_OVERRIDE
|
||||||
|
.with(|o| o.get())
|
||||||
|
.unwrap_or(LEGACY_SIGS)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `f` with legacy acceptance forced to `on`, then restore the previous
|
||||||
|
/// thread state. A test hook, not a runtime setting: production code reads the
|
||||||
|
/// switch through [`legacy_sigs`] only.
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn with_legacy_sigs<R>(on: bool, f: impl FnOnce() -> R) -> R {
|
||||||
|
struct Restore(Option<bool>);
|
||||||
|
impl Drop for Restore {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
LEGACY_SIGS_OVERRIDE.with(|o| o.set(self.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _restore = Restore(LEGACY_SIGS_OVERRIDE.with(|o| o.replace(Some(on))));
|
||||||
|
f()
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Error(String);
|
pub struct Error(String);
|
||||||
|
|
||||||
|
|
@ -202,11 +240,12 @@ pub fn verify_invoice(identity_pk: &[u8], inv: &Invoice) -> bool {
|
||||||
identity_pk,
|
identity_pk,
|
||||||
&inv_sign_msg_v2(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
|
&inv_sign_msg_v2(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
|
||||||
&inv.sig,
|
&inv.sig,
|
||||||
) || verify_bytes(
|
) || (legacy_sigs()
|
||||||
|
&& verify_bytes(
|
||||||
identity_pk,
|
identity_pk,
|
||||||
&inv_sign_msg_v1(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
|
&inv_sign_msg_v1(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
|
||||||
&inv.sig,
|
&inv.sig,
|
||||||
)
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn encode_invoice(inv: &Invoice) -> Vec<u8> {
|
pub fn encode_invoice(inv: &Invoice) -> Vec<u8> {
|
||||||
|
|
@ -273,11 +312,12 @@ pub fn verify_receipt(identity_pk: &[u8], rcp: &Receipt) -> bool {
|
||||||
identity_pk,
|
identity_pk,
|
||||||
&rcp_sign_msg_v2(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
|
&rcp_sign_msg_v2(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
|
||||||
&rcp.sig,
|
&rcp.sig,
|
||||||
) || verify_bytes(
|
) || (legacy_sigs()
|
||||||
|
&& verify_bytes(
|
||||||
identity_pk,
|
identity_pk,
|
||||||
&rcp_sign_msg_v1(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
|
&rcp_sign_msg_v1(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
|
||||||
&rcp.sig,
|
&rcp.sig,
|
||||||
)
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn encode_receipt(rcp: &Receipt) -> Vec<u8> {
|
pub fn encode_receipt(rcp: &Receipt) -> Vec<u8> {
|
||||||
|
|
@ -339,6 +379,20 @@ fn check_tip_fields(txid: &str, amount_atomic: &str, address: &str, memo: &str)
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn tip_sign_msg_v2(txid: &str, amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
|
||||||
|
tagged(
|
||||||
|
b"onionwire-tip-v1",
|
||||||
|
&[
|
||||||
|
txid.as_bytes(),
|
||||||
|
amount_atomic.as_bytes(),
|
||||||
|
address.as_bytes(),
|
||||||
|
memo.as_bytes(),
|
||||||
|
ts.to_string().as_bytes(),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Historical untagged form. Accept-only, and only while [`LEGACY_SIGS`] is on.
|
||||||
fn tip_sign_msg_v1(txid: &str, amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
|
fn tip_sign_msg_v1(txid: &str, amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
|
||||||
let mut msg = Vec::from(txid.as_bytes());
|
let mut msg = Vec::from(txid.as_bytes());
|
||||||
msg.push(b'\n');
|
msg.push(b'\n');
|
||||||
|
|
@ -361,7 +415,10 @@ pub fn sign_tip(
|
||||||
ts: i64,
|
ts: i64,
|
||||||
) -> Result<Tip> {
|
) -> Result<Tip> {
|
||||||
check_tip_fields(txid, amount_atomic, address, memo)?;
|
check_tip_fields(txid, amount_atomic, address, memo)?;
|
||||||
let sig = sign_bytes(identity_sk, &tip_sign_msg_v1(txid, amount_atomic, address, memo, ts))?;
|
let sig = sign_bytes(
|
||||||
|
identity_sk,
|
||||||
|
&tip_sign_msg_v2(txid, amount_atomic, address, memo, ts),
|
||||||
|
)?;
|
||||||
Ok(Tip {
|
Ok(Tip {
|
||||||
txid: txid.to_string(),
|
txid: txid.to_string(),
|
||||||
amount_atomic: amount_atomic.to_string(),
|
amount_atomic: amount_atomic.to_string(),
|
||||||
|
|
@ -378,9 +435,26 @@ pub fn verify_tip(identity_pk: &[u8], tip: &Tip) -> bool {
|
||||||
}
|
}
|
||||||
verify_bytes(
|
verify_bytes(
|
||||||
identity_pk,
|
identity_pk,
|
||||||
&tip_sign_msg_v1(&tip.txid, &tip.amount_atomic, &tip.address, &tip.memo, tip.ts),
|
&tip_sign_msg_v2(
|
||||||
|
&tip.txid,
|
||||||
|
&tip.amount_atomic,
|
||||||
|
&tip.address,
|
||||||
|
&tip.memo,
|
||||||
|
tip.ts,
|
||||||
|
),
|
||||||
&tip.sig,
|
&tip.sig,
|
||||||
)
|
) || (legacy_sigs()
|
||||||
|
&& verify_bytes(
|
||||||
|
identity_pk,
|
||||||
|
&tip_sign_msg_v1(
|
||||||
|
&tip.txid,
|
||||||
|
&tip.amount_atomic,
|
||||||
|
&tip.address,
|
||||||
|
&tip.memo,
|
||||||
|
tip.ts,
|
||||||
|
),
|
||||||
|
&tip.sig,
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn encode_tip(tip: &Tip) -> Vec<u8> {
|
pub fn encode_tip(tip: &Tip) -> Vec<u8> {
|
||||||
|
|
|
||||||
|
|
@ -101,6 +101,11 @@ pub fn decode(raw: &str) -> Result<QrPayload> {
|
||||||
if kem_ascii.is_some() {
|
if kem_ascii.is_some() {
|
||||||
return Err(Error("unknown field".into()));
|
return Err(Error("unknown field".into()));
|
||||||
}
|
}
|
||||||
|
// A v1 invite only ever carries a legacy signature: with legacy
|
||||||
|
// acceptance off it fails closed here, before any verify.
|
||||||
|
if !crate::pay::legacy_sigs() {
|
||||||
|
return Err(Error("legacy invite signatures disabled".into()));
|
||||||
|
}
|
||||||
let ok_tagged = vk
|
let ok_tagged = vk
|
||||||
.verify(&sign_msg_v1_tagged(&k, &onion, &spk), &signature)
|
.verify(&sign_msg_v1_tagged(&k, &onion, &spk), &signature)
|
||||||
.is_ok();
|
.is_ok();
|
||||||
|
|
|
||||||
312
src/store.rs
312
src/store.rs
|
|
@ -293,7 +293,8 @@ impl Store {
|
||||||
CREATE TABLE IF NOT EXISTS store_meta (
|
CREATE TABLE IF NOT EXISTS store_meta (
|
||||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
kdf_salt BLOB NOT NULL,
|
kdf_salt BLOB NOT NULL,
|
||||||
wrapped_key BLOB NOT NULL
|
wrapped_key BLOB NOT NULL,
|
||||||
|
kdf_profile INTEGER NOT NULL DEFAULT 0
|
||||||
);
|
);
|
||||||
-- The wallet child's RPC creds + chain-source snapshot. One row,
|
-- The wallet child's RPC creds + chain-source snapshot. One row,
|
||||||
-- sealed with the store data key (see `save_wallet_child`): the
|
-- sealed with the store data key (see `save_wallet_child`): the
|
||||||
|
|
@ -692,6 +693,13 @@ impl Store {
|
||||||
"payload",
|
"payload",
|
||||||
"ALTER TABLE outbox ADD COLUMN payload BLOB",
|
"ALTER TABLE outbox ADD COLUMN payload BLOB",
|
||||||
)?;
|
)?;
|
||||||
|
// Which Argon2id profile wraps `store_meta.wrapped_key`. Rows written
|
||||||
|
// before the column existed are the legacy profile (id 0).
|
||||||
|
self.add_column_if_missing(
|
||||||
|
"store_meta",
|
||||||
|
"kdf_profile",
|
||||||
|
"ALTER TABLE store_meta ADD COLUMN kdf_profile INTEGER NOT NULL DEFAULT 0",
|
||||||
|
)?;
|
||||||
// `insert_payment` has accepted `kind = "tip"` since the tip path
|
// `insert_payment` has accepted `kind = "tip"` since the tip path
|
||||||
// landed, but the table's CHECK only allowed invoice/receipt, so every
|
// landed, but the table's CHECK only allowed invoice/receipt, so every
|
||||||
// tip insert (inbound *and* outbound) failed the constraint and the
|
// tip insert (inbound *and* outbound) failed the constraint and the
|
||||||
|
|
@ -741,17 +749,18 @@ impl Store {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unlock_messages(&mut self, passphrase: &str) -> Result<()> {
|
fn unlock_messages(&mut self, passphrase: &str) -> Result<()> {
|
||||||
let row: Option<(Vec<u8>, Vec<u8>)> = self
|
let row: Option<(Vec<u8>, Vec<u8>, i64)> = self
|
||||||
.conn
|
.conn
|
||||||
.query_row(
|
.query_row(
|
||||||
"SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1",
|
"SELECT kdf_salt, wrapped_key, kdf_profile FROM store_meta WHERE id = 1",
|
||||||
[],
|
[],
|
||||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||||
)
|
)
|
||||||
.optional()?;
|
.optional()?;
|
||||||
match row {
|
match row {
|
||||||
Some((salt, wrapped)) => {
|
Some((salt, wrapped, profile_id)) => {
|
||||||
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
let profile = kdf_profile_from_id(profile_id)?;
|
||||||
|
let wrap_key = crate::backup::kdf_with(profile, passphrase, &salt)?;
|
||||||
// The unwrapped data key lands in a Zeroizing buffer immediately.
|
// The unwrapped data key lands in a Zeroizing buffer immediately.
|
||||||
let raw = Zeroizing::new(
|
let raw = Zeroizing::new(
|
||||||
crate::backup::aead_decrypt(&wrap_key, &wrapped, b"")
|
crate::backup::aead_decrypt(&wrap_key, &wrapped, b"")
|
||||||
|
|
@ -761,6 +770,11 @@ impl Store {
|
||||||
return Err(Error("wrapped message key length".into()));
|
return Err(Error("wrapped message key length".into()));
|
||||||
}
|
}
|
||||||
self.msg_key.copy_from_slice(&raw);
|
self.msg_key.copy_from_slice(&raw);
|
||||||
|
// The passphrase proved itself: a legacy wrap is re-wrapped
|
||||||
|
// with the current profile once, in one transaction.
|
||||||
|
if profile != crate::backup::KdfProfile::Current {
|
||||||
|
self.rewrap_store_meta(passphrase)?;
|
||||||
|
}
|
||||||
self.rewrap_empty_aad_messages()?;
|
self.rewrap_empty_aad_messages()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
@ -772,8 +786,13 @@ impl Store {
|
||||||
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
||||||
let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key[..], b"")?;
|
let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key[..], b"")?;
|
||||||
self.conn.execute(
|
self.conn.execute(
|
||||||
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
|
"INSERT INTO store_meta (id, kdf_salt, wrapped_key, kdf_profile)
|
||||||
params![salt.as_slice(), wrapped],
|
VALUES (1, ?1, ?2, ?3)",
|
||||||
|
params![
|
||||||
|
salt.as_slice(),
|
||||||
|
wrapped,
|
||||||
|
i64::from(crate::backup::KdfProfile::CURRENT_ID)
|
||||||
|
],
|
||||||
)?;
|
)?;
|
||||||
self.msg_key = data_key;
|
self.msg_key = data_key;
|
||||||
self.reencrypt_legacy_messages()?;
|
self.reencrypt_legacy_messages()?;
|
||||||
|
|
@ -782,6 +801,27 @@ impl Store {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One-shot upgrade of a legacy-profile wrap to the current KDF profile.
|
||||||
|
/// Salt, ciphertext and profile id move together in a single transaction.
|
||||||
|
fn rewrap_store_meta(&mut self, passphrase: &str) -> Result<()> {
|
||||||
|
let mut salt = [0u8; 16];
|
||||||
|
OsRng.fill_bytes(&mut salt);
|
||||||
|
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
||||||
|
let wrapped = crate::backup::aead_encrypt(&wrap_key, &self.msg_key[..], b"")?;
|
||||||
|
let tx = self.conn.unchecked_transaction()?;
|
||||||
|
tx.execute(
|
||||||
|
"UPDATE store_meta SET kdf_salt = ?1, wrapped_key = ?2, kdf_profile = ?3
|
||||||
|
WHERE id = 1",
|
||||||
|
params![
|
||||||
|
salt.as_slice(),
|
||||||
|
wrapped,
|
||||||
|
i64::from(crate::backup::KdfProfile::CURRENT_ID)
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
tx.commit()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn reencrypt_legacy_messages(&self) -> Result<()> {
|
fn reencrypt_legacy_messages(&self) -> Result<()> {
|
||||||
let mut stmt = self
|
let mut stmt = self
|
||||||
.conn
|
.conn
|
||||||
|
|
@ -1748,8 +1788,41 @@ fn open_store_db(home: &Path, db_path: &Path, passphrase: &str) -> Result<Connec
|
||||||
your backup, or restore the db from backup and re-import"
|
your backup, or restore the db from backup and re-import"
|
||||||
)));
|
)));
|
||||||
};
|
};
|
||||||
|
// The SQLCipher file key is KDF(passphrase, store_salt) with no recorded
|
||||||
|
// profile: the file itself says which one opened it. A legacy store is
|
||||||
|
// opened with the legacy profile and immediately rekeyed to the current
|
||||||
|
// one, so the next start takes the fast path.
|
||||||
let key = crate::backup::kdf(passphrase, &salt)?;
|
let key = crate::backup::kdf(passphrase, &salt)?;
|
||||||
open_keyed(db_path, &key)
|
match open_keyed(db_path, &key) {
|
||||||
|
Ok(conn) => Ok(conn),
|
||||||
|
Err(_) => {
|
||||||
|
let legacy_key =
|
||||||
|
crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, passphrase, &salt)?;
|
||||||
|
let conn = open_keyed(db_path, &legacy_key)
|
||||||
|
.map_err(|_| Error("wrong passphrase or corrupt store".into()))?;
|
||||||
|
rekey_store(&conn, &key)?;
|
||||||
|
Ok(conn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rewrite every page of an open store under `new_key` in one transaction.
|
||||||
|
/// SQLCipher rolls the rekey back if any page write fails.
|
||||||
|
fn rekey_store(conn: &Connection, new_key: &[u8; 32]) -> Result<()> {
|
||||||
|
// Old-keyed WAL frames must be folded in before the rewrite, or they would
|
||||||
|
// replay under a key that no longer opens them.
|
||||||
|
conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;
|
||||||
|
let pragma = Zeroizing::new(format!(
|
||||||
|
"PRAGMA rekey = \"x'{hex}'\"",
|
||||||
|
hex = fingerprint(new_key)
|
||||||
|
));
|
||||||
|
conn.execute_batch(pragma.as_str())
|
||||||
|
.map_err(|e| Error(format!("store rekey: {e}")))?;
|
||||||
|
conn.query_row("SELECT count(*) FROM sqlite_master", [], |r| {
|
||||||
|
r.get::<_, i64>(0)
|
||||||
|
})
|
||||||
|
.map_err(|_| Error("store rekey failed".into()))?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// SQLCipher `PRAGMA key` with the raw-key form: the 32-byte Argon2id output is
|
/// SQLCipher `PRAGMA key` with the raw-key form: the 32-byte Argon2id output is
|
||||||
|
|
@ -1777,20 +1850,50 @@ fn pragma_key(key: &[u8; 32]) -> Zeroizing<String> {
|
||||||
/// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh
|
/// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh
|
||||||
/// store) accepts any passphrase, matching the v0.2.1 behaviour.
|
/// store) accepts any passphrase, matching the v0.2.1 behaviour.
|
||||||
fn wrapped_key_opens(conn: &Connection, passphrase: &str) -> Result<bool> {
|
fn wrapped_key_opens(conn: &Connection, passphrase: &str) -> Result<bool> {
|
||||||
let row: Option<(Vec<u8>, Vec<u8>)> = conn
|
let Some((salt, wrapped, profile_id)) = read_store_meta(conn)? else {
|
||||||
.query_row(
|
|
||||||
"SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1",
|
|
||||||
[],
|
|
||||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
||||||
)
|
|
||||||
.optional()?;
|
|
||||||
let Some((salt, wrapped)) = row else {
|
|
||||||
return Ok(true);
|
return Ok(true);
|
||||||
};
|
};
|
||||||
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
let profile = kdf_profile_from_id(profile_id)?;
|
||||||
|
let wrap_key = crate::backup::kdf_with(profile, passphrase, &salt)?;
|
||||||
Ok(crate::backup::aead_decrypt(&wrap_key, &wrapped, b"").is_ok())
|
Ok(crate::backup::aead_decrypt(&wrap_key, &wrapped, b"").is_ok())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `(kdf_salt, wrapped_key, kdf_profile)`.
|
||||||
|
type StoreMetaRow = (Vec<u8>, Vec<u8>, i64);
|
||||||
|
|
||||||
|
/// Read the `store_meta` row, tolerating a table that predates `kdf_profile`
|
||||||
|
/// (a v0.2.1 plaintext store), where the profile is the legacy one.
|
||||||
|
fn read_store_meta(conn: &Connection) -> Result<Option<StoreMetaRow>> {
|
||||||
|
let has_profile: i64 = conn.query_row(
|
||||||
|
"SELECT COUNT(*) FROM pragma_table_info('store_meta') WHERE name = 'kdf_profile'",
|
||||||
|
[],
|
||||||
|
|r| r.get(0),
|
||||||
|
)?;
|
||||||
|
let Some((salt, wrapped, profile)) = (if has_profile > 0 {
|
||||||
|
conn.query_row(
|
||||||
|
"SELECT kdf_salt, wrapped_key, kdf_profile FROM store_meta WHERE id = 1",
|
||||||
|
[],
|
||||||
|
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||||
|
)
|
||||||
|
.optional()?
|
||||||
|
} else {
|
||||||
|
conn.query_row(
|
||||||
|
"SELECT kdf_salt, wrapped_key, 0 FROM store_meta WHERE id = 1",
|
||||||
|
[],
|
||||||
|
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||||
|
)
|
||||||
|
.optional()?
|
||||||
|
}) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
Ok(Some((salt, wrapped, profile)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn kdf_profile_from_id(id: i64) -> Result<crate::backup::KdfProfile> {
|
||||||
|
let id = u8::try_from(id).map_err(|_| Error(format!("unknown kdf profile {id}")))?;
|
||||||
|
crate::backup::KdfProfile::from_id(id).map_err(Error)
|
||||||
|
}
|
||||||
|
|
||||||
/// Rewrites a plaintext sqlite store as an encrypted one and swaps it in.
|
/// Rewrites a plaintext sqlite store as an encrypted one and swaps it in.
|
||||||
/// The source file is only replaced after the new file opens, passes
|
/// The source file is only replaced after the new file opens, passes
|
||||||
/// `integrity_check` and unlocks with this passphrase.
|
/// `integrity_check` and unlocks with this passphrase.
|
||||||
|
|
@ -2271,7 +2374,8 @@ mod at_rest {
|
||||||
OsRng.fill_bytes(&mut salt);
|
OsRng.fill_bytes(&mut salt);
|
||||||
let mut data_key = Zeroizing::new([0u8; 32]);
|
let mut data_key = Zeroizing::new([0u8; 32]);
|
||||||
OsRng.fill_bytes(&mut data_key[..]);
|
OsRng.fill_bytes(&mut data_key[..]);
|
||||||
let wrap = crate::backup::kdf(passphrase, &salt).unwrap();
|
let wrap =
|
||||||
|
crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, passphrase, &salt).unwrap();
|
||||||
let wrapped = crate::backup::aead_encrypt(&wrap, &data_key[..], b"").unwrap();
|
let wrapped = crate::backup::aead_encrypt(&wrap, &data_key[..], b"").unwrap();
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
|
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
|
||||||
|
|
@ -2661,4 +2765,174 @@ mod at_rest {
|
||||||
assert_eq!(store.list_wallets().unwrap().len(), 1);
|
assert_eq!(store.list_wallets().unwrap().len(), 1);
|
||||||
assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row);
|
assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Turn a freshly created store into the exact pre-profile shape: the
|
||||||
|
/// SQLCipher file keyed with the legacy Argon2id params, and the message
|
||||||
|
/// key wrapped under the legacy profile with no meaningful profile id.
|
||||||
|
/// Returns the (salt, wrapped) pair that must be replaced by the upgrade.
|
||||||
|
fn downgrade_to_legacy_profile(dir: &Path, pass: &str) -> (Vec<u8>, Vec<u8>) {
|
||||||
|
let store = Store::open_at_with_passphrase(dir, pass).unwrap();
|
||||||
|
let data_key = *store.msg_key;
|
||||||
|
let salt: [u8; 16] = fs::read(dir.join(SALT_FILE)).unwrap().try_into().unwrap();
|
||||||
|
let legacy_db_key =
|
||||||
|
crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, pass, &salt).unwrap();
|
||||||
|
let wrap_salt = [0x33u8; 16];
|
||||||
|
let legacy_wrap =
|
||||||
|
crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, pass, &wrap_salt).unwrap();
|
||||||
|
let wrapped = crate::backup::aead_encrypt(&legacy_wrap, &data_key[..], b"").unwrap();
|
||||||
|
store
|
||||||
|
.conn
|
||||||
|
.execute(
|
||||||
|
"UPDATE store_meta SET kdf_salt = ?1, wrapped_key = ?2, kdf_profile = 0
|
||||||
|
WHERE id = 1",
|
||||||
|
params![wrap_salt.as_slice(), wrapped.clone()],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
store
|
||||||
|
.conn
|
||||||
|
.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")
|
||||||
|
.unwrap();
|
||||||
|
store
|
||||||
|
.conn
|
||||||
|
.execute_batch(&format!(
|
||||||
|
"PRAGMA rekey = \"x'{hex}'\"",
|
||||||
|
hex = fingerprint(&legacy_db_key[..])
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
drop(store);
|
||||||
|
(wrap_salt.to_vec(), wrapped)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn store_meta_parts(dir: &Path, pass: &str) -> (Vec<u8>, Vec<u8>, i64) {
|
||||||
|
let salt: [u8; 16] = fs::read(dir.join(SALT_FILE)).unwrap().try_into().unwrap();
|
||||||
|
let key = crate::backup::kdf(pass, &salt).unwrap();
|
||||||
|
let db = dir.join("onionwire.db");
|
||||||
|
let conn = open_keyed(&db, &key)
|
||||||
|
.or_else(|_| {
|
||||||
|
let legacy =
|
||||||
|
crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, pass, &salt)?;
|
||||||
|
open_keyed(&db, &legacy)
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
conn.query_row(
|
||||||
|
"SELECT kdf_salt, wrapped_key, kdf_profile FROM store_meta WHERE id = 1",
|
||||||
|
[],
|
||||||
|
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_legacy_store_opens_and_upgrades_its_kdf_profile_exactly_once() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let pass = "legacy-upgrade-pass";
|
||||||
|
let pk = [7u8; 32];
|
||||||
|
{
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
|
||||||
|
store.upsert_friend(&pk, "b.onion", None).unwrap();
|
||||||
|
store.append_message(&pk, "in", b"survives rekey").unwrap();
|
||||||
|
}
|
||||||
|
let (old_salt, old_wrapped) = downgrade_to_legacy_profile(dir.path(), pass);
|
||||||
|
assert_eq!(
|
||||||
|
store_meta_parts(dir.path(), pass).2,
|
||||||
|
0,
|
||||||
|
"fixture must start on the legacy profile"
|
||||||
|
);
|
||||||
|
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), pass).expect("legacy upgrade");
|
||||||
|
assert_eq!(
|
||||||
|
store.list_messages(&pk).unwrap()[0].plaintext,
|
||||||
|
b"survives rekey",
|
||||||
|
"the rekey must not lose data"
|
||||||
|
);
|
||||||
|
let (salt, wrapped, profile) = store_meta_parts(dir.path(), pass);
|
||||||
|
assert_eq!(profile, i64::from(crate::backup::KdfProfile::CURRENT_ID));
|
||||||
|
assert_ne!(salt, old_salt, "upgrade must mint a fresh wrap salt");
|
||||||
|
assert_ne!(wrapped, old_wrapped, "upgrade must re-wrap the message key");
|
||||||
|
drop(store);
|
||||||
|
|
||||||
|
// The SQLCipher file itself moved to the current profile.
|
||||||
|
let file_salt: [u8; 16] = fs::read(dir.path().join(SALT_FILE))
|
||||||
|
.unwrap()
|
||||||
|
.try_into()
|
||||||
|
.unwrap();
|
||||||
|
let current = crate::backup::kdf(pass, &file_salt).unwrap();
|
||||||
|
assert!(
|
||||||
|
open_keyed(&dir.path().join("onionwire.db"), ¤t).is_ok(),
|
||||||
|
"store must be rekeyed to the current profile"
|
||||||
|
);
|
||||||
|
let legacy =
|
||||||
|
crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, pass, &file_salt).unwrap();
|
||||||
|
assert!(
|
||||||
|
open_keyed(&dir.path().join("onionwire.db"), &legacy).is_err(),
|
||||||
|
"the legacy file key must no longer open the store"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Second unlock is a no-op: the profile flip is one-shot.
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
|
||||||
|
let (salt2, wrapped2, profile2) = store_meta_parts(dir.path(), pass);
|
||||||
|
assert_eq!(profile2, i64::from(crate::backup::KdfProfile::CURRENT_ID));
|
||||||
|
assert_eq!((salt2, wrapped2), (salt, wrapped), "re-wrapped twice");
|
||||||
|
assert_eq!(store.list_messages(&pk).unwrap().len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore = "manual unlock timing measurement; run with --release --ignored"]
|
||||||
|
fn store_unlock_timing() {
|
||||||
|
use std::time::Instant;
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let pass = "unlock-timing-pass";
|
||||||
|
let started = Instant::now();
|
||||||
|
drop(Store::open_at_with_passphrase(dir.path(), pass).unwrap());
|
||||||
|
eprintln!(
|
||||||
|
"first open (create): {:.3}s",
|
||||||
|
started.elapsed().as_secs_f64()
|
||||||
|
);
|
||||||
|
|
||||||
|
let started = Instant::now();
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
|
||||||
|
eprintln!(
|
||||||
|
"reopen, current profile: {:.3}s",
|
||||||
|
started.elapsed().as_secs_f64()
|
||||||
|
);
|
||||||
|
drop(store);
|
||||||
|
|
||||||
|
downgrade_to_legacy_profile(dir.path(), pass);
|
||||||
|
let started = Instant::now();
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
|
||||||
|
eprintln!(
|
||||||
|
"reopen, legacy store (open + rekey + rewrap): {:.3}s",
|
||||||
|
started.elapsed().as_secs_f64()
|
||||||
|
);
|
||||||
|
drop(store);
|
||||||
|
|
||||||
|
let started = Instant::now();
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
|
||||||
|
eprintln!(
|
||||||
|
"reopen after upgrade: {:.3}s",
|
||||||
|
started.elapsed().as_secs_f64()
|
||||||
|
);
|
||||||
|
drop(store);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unknown_store_kdf_profile_is_a_clean_error() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let pass = "unknown-profile-pass";
|
||||||
|
{
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
|
||||||
|
store
|
||||||
|
.conn
|
||||||
|
.execute("UPDATE store_meta SET kdf_profile = 9 WHERE id = 1", [])
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let err = match Store::open_at_with_passphrase(dir.path(), pass) {
|
||||||
|
Ok(_) => panic!("an unknown kdf profile must not fall back to legacy params"),
|
||||||
|
Err(e) => e,
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
err.to_string().contains("unknown kdf profile 9"),
|
||||||
|
"got {err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
16
src/tui.rs
16
src/tui.rs
|
|
@ -7694,8 +7694,22 @@ mod wallet_setup_config_tests {
|
||||||
app.node.start_wallet_child().expect("start");
|
app.node.start_wallet_child().expect("start");
|
||||||
|
|
||||||
let height = Arc::new(AtomicU64::new(1111));
|
let height = Arc::new(AtomicU64::new(1111));
|
||||||
let wallet = rt.block_on(mock_wallet_at(Arc::clone(&height), 9000));
|
let (wallet, daemon) = rt.block_on(mock_wallet_at(Arc::clone(&height), 9000));
|
||||||
test_install_wallet(&app.node, wallet);
|
test_install_wallet(&app.node, wallet);
|
||||||
|
// Readiness compares the wallet's scanned height with a daemon tip, so
|
||||||
|
// point the chain source at the stub the wallet mock returned.
|
||||||
|
let (host, port) = daemon.rsplit_once(':').expect("host:port");
|
||||||
|
app.node
|
||||||
|
.set_wallet_child_config(&ChildConfig {
|
||||||
|
source: ChainSource::Remote {
|
||||||
|
host: host.to_string(),
|
||||||
|
port: port.parse().expect("daemon port"),
|
||||||
|
},
|
||||||
|
wallet_rpc_bin: std::path::PathBuf::from("monero-wallet-rpc"),
|
||||||
|
arti_bin: std::path::PathBuf::from("arti"),
|
||||||
|
wallet_filename: "onionwire".into(),
|
||||||
|
})
|
||||||
|
.expect("point the chain source at the daemon stub");
|
||||||
app.handle_key(key(KeyCode::F(7))).expect("F7");
|
app.handle_key(key(KeyCode::F(7))).expect("F7");
|
||||||
|
|
||||||
wait_for_sync_line(&mut app, &rt, "sync 1111/9000");
|
wait_for_sync_line(&mut app, &rt, "sync 1111/9000");
|
||||||
|
|
|
||||||
265
src/wallet.rs
265
src/wallet.rs
|
|
@ -1,4 +1,5 @@
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use rand::RngCore;
|
use rand::RngCore;
|
||||||
|
|
@ -363,12 +364,16 @@ pub fn readiness(configured: bool, connected: bool, no_spend: bool, is_tip: bool
|
||||||
Readiness::Ready
|
Readiness::Ready
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What a redacted credential renders as. One spelling everywhere: the
|
||||||
|
/// existing `Debug` pins and the URL accessor must agree.
|
||||||
|
pub(crate) const REDACTED: &str = "<redacted>";
|
||||||
|
|
||||||
/// Display copy, not a log line: drop the secret if some lower layer put it in
|
/// Display copy, not a log line: drop the secret if some lower layer put it in
|
||||||
/// the message, and keep it short enough for a status line.
|
/// the message, and keep it short enough for a status line.
|
||||||
pub(crate) fn redact(msg: &str, secret: &str) -> String {
|
pub(crate) fn redact(msg: &str, secret: &str) -> String {
|
||||||
let mut out = msg.trim().to_string();
|
let mut out = msg.trim().to_string();
|
||||||
if !secret.is_empty() {
|
if !secret.is_empty() {
|
||||||
out = out.replace(secret, "<redacted>");
|
out = out.replace(secret, REDACTED);
|
||||||
}
|
}
|
||||||
const MAX: usize = 120;
|
const MAX: usize = 120;
|
||||||
if out.chars().count() > MAX {
|
if out.chars().count() > MAX {
|
||||||
|
|
@ -378,6 +383,51 @@ pub(crate) fn redact(msg: &str, secret: &str) -> String {
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// [`redact`] for a whole `user:pass` login: drop the pair first (so no
|
||||||
|
/// `user:<redacted>` survives), then the password half on its own, in case a
|
||||||
|
/// lower layer printed only that. Every error/status string built from a
|
||||||
|
/// [`WalletConfig`] goes through here.
|
||||||
|
pub(crate) fn redact_login(msg: &str, login: &str) -> String {
|
||||||
|
let login = login.trim();
|
||||||
|
if login.is_empty() {
|
||||||
|
return redact(msg, "");
|
||||||
|
}
|
||||||
|
let pass = login.split_once(':').map(|(_, p)| p).unwrap_or(login);
|
||||||
|
redact(&redact(msg, login), pass)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The URL with its userinfo replaced, for anything that prints a wallet
|
||||||
|
/// endpoint: `http://<redacted>:<redacted>@127.0.0.1:<port>/json_rpc`. A URL
|
||||||
|
/// with no userinfo is returned unchanged.
|
||||||
|
pub(crate) fn redact_url(url: &str) -> String {
|
||||||
|
match (url.find("://"), url.find('@')) {
|
||||||
|
(Some(scheme), Some(at)) if at > scheme + 3 => {
|
||||||
|
format!(
|
||||||
|
"{}://{REDACTED}:{REDACTED}@{}",
|
||||||
|
&url[..scheme],
|
||||||
|
&url[at + 1..]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
_ => url.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one-shot notice for a login taken from the environment. Environment is
|
||||||
|
/// readable through `/proc`, inherited by children, and lands in shell history,
|
||||||
|
/// so the store is the preferred channel (`Wallet::for_boot` already tries it
|
||||||
|
/// first). `true` only on the call that actually printed.
|
||||||
|
static ENV_LOGIN_WARNED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
fn warn_env_login_once() -> bool {
|
||||||
|
if ENV_LOGIN_WARNED.swap(true, Ordering::SeqCst) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
eprintln!(
|
||||||
|
"ONIONWIRE_WALLET_RPC_LOGIN: environment is readable by other processes and lands in shell history; put it in the wallet setup screen instead"
|
||||||
|
);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct Endpoint {
|
struct Endpoint {
|
||||||
host: String,
|
host: String,
|
||||||
|
|
@ -387,14 +437,25 @@ struct Endpoint {
|
||||||
pass: Zeroizing<String>,
|
pass: Zeroizing<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Endpoint {
|
||||||
|
/// The URL with both halves of the login replaced, for any log line, error
|
||||||
|
/// string or status row:
|
||||||
|
/// `http://<redacted>:<redacted>@127.0.0.1:<port>/json_rpc`.
|
||||||
|
pub(crate) fn redacted(&self) -> String {
|
||||||
|
format!(
|
||||||
|
"http://{REDACTED}:{REDACTED}@{}{}",
|
||||||
|
host_header(&self.host, self.port),
|
||||||
|
self.path
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Debug` goes through [`Endpoint::redacted`]: a `{:?}` must never be the one
|
||||||
|
/// place the login survives.
|
||||||
impl std::fmt::Debug for Endpoint {
|
impl std::fmt::Debug for Endpoint {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
f.debug_struct("Endpoint")
|
f.debug_struct("Endpoint")
|
||||||
.field("host", &self.host)
|
.field("url", &self.redacted())
|
||||||
.field("port", &self.port)
|
|
||||||
.field("path", &self.path)
|
|
||||||
.field("user", &self.user)
|
|
||||||
.field("pass", &"<redacted>")
|
|
||||||
.finish()
|
.finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -427,34 +488,53 @@ pub struct Wallet {
|
||||||
/// Budget for loopback management calls (`get_address`, `query_key`,
|
/// Budget for loopback management calls (`get_address`, `query_key`,
|
||||||
/// create/import). The wallet child is on the same box, so this stays short.
|
/// create/import). The wallet child is on the same box, so this stays short.
|
||||||
timeout_local: Duration,
|
timeout_local: Duration,
|
||||||
/// Budget for calls that wait on the daemon (`get_info`, `get_transfers`,
|
/// Budget for calls that wait on the daemon (`get_transfers`, `transfer`).
|
||||||
/// `transfer`). A first sync or a remote daemon legitimately outlasts the
|
/// A first sync or a remote daemon legitimately outlasts the local budget,
|
||||||
/// local budget, and treating that as "down" is what left receipts
|
/// and treating that as "down" is what left receipts
|
||||||
/// permanently unverified.
|
/// permanently unverified.
|
||||||
timeout_chain: Duration,
|
timeout_chain: Duration,
|
||||||
|
/// Chain daemon to compare the wallet's scanned height against. `None`
|
||||||
|
/// means no comparable tip (receive-only, a `.onion` daemon that needs the
|
||||||
|
/// SOCKS child, an externally run wallet RPC): readiness stays false. Set
|
||||||
|
/// from [`crate::wallet_child::ChildConfig::daemon_probe_addr`] by the node.
|
||||||
|
daemon_probe: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The `get_info` fields one wallet-RPC probe carries: the readiness verdict and
|
/// What the readiness pair is: the wallet's own scanned height and the chain
|
||||||
/// the numbers a status line shows. `0` height/target means the wallet RPC
|
/// tip the daemon reports. Neither number comes from the wallet RPC's
|
||||||
/// answered without a number — unknown, never "caught up", and never a percent.
|
/// `get_info` — `monero-wallet-rpc` does not implement it (`-32601 Method not
|
||||||
|
/// found`); `get_info` exists on the daemon only.
|
||||||
|
///
|
||||||
|
/// `0` height means the wallet RPC answered without a number. `tip == None`
|
||||||
|
/// means the daemon did not answer. Both are unknown — never "caught up".
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub struct ChainInfo {
|
pub struct ChainInfo {
|
||||||
/// The wallet RPC said `synchronized: true`. A missing field is `false`.
|
/// Blocks the wallet has scanned, from the wallet RPC's `get_height`.
|
||||||
pub synchronized: bool,
|
|
||||||
/// Blocks the wallet's daemon has, as the wallet RPC reports them.
|
|
||||||
pub height: u64,
|
pub height: u64,
|
||||||
/// Blocks that daemon is syncing towards; `0` when it reported none.
|
/// The daemon's chain tip, or `None` when it could not be asked.
|
||||||
pub target_height: u64,
|
pub tip: Option<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How far behind the daemon tip a wallet may be and still count as caught up.
|
||||||
|
///
|
||||||
|
/// The tip moves every ~2 minutes and the daemon answer and the wallet scan are
|
||||||
|
/// two reads, not one snapshot, so a strict `>=` gate flaps on a wallet that is
|
||||||
|
/// one block behind for a few seconds. Two blocks is a deliberate slack, small
|
||||||
|
/// enough that a real lag (a first sync, a stalled scan) still reads not-ready.
|
||||||
|
const READY_SLACK_BLOCKS: u64 = 2;
|
||||||
|
|
||||||
impl ChainInfo {
|
impl ChainInfo {
|
||||||
/// The readiness predicate: the daemon reached the tip and the wallet
|
/// The readiness predicate, stated once:
|
||||||
/// scanned up to it. `synchronized` must be explicitly true, and a chain
|
///
|
||||||
/// with no height is not ready.
|
/// `height > 0 && (tip == 0 || height + READY_SLACK_BLOCKS >= tip)`
|
||||||
|
///
|
||||||
|
/// A daemon that did not answer is not ready. A wallet with no scanned
|
||||||
|
/// height is not ready. Fail closed on every branch.
|
||||||
pub fn ready(&self) -> bool {
|
pub fn ready(&self) -> bool {
|
||||||
self.synchronized
|
self.height > 0
|
||||||
&& self.height > 0
|
&& self.tip.is_some_and(|tip| {
|
||||||
&& (self.target_height == 0 || self.height >= self.target_height)
|
tip == 0 || self.height.saturating_add(READY_SLACK_BLOCKS) >= tip
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -502,6 +582,7 @@ impl Wallet {
|
||||||
no_spend,
|
no_spend,
|
||||||
timeout_local: RPC_TIMEOUT,
|
timeout_local: RPC_TIMEOUT,
|
||||||
timeout_chain: CHAIN_RPC_TIMEOUT,
|
timeout_chain: CHAIN_RPC_TIMEOUT,
|
||||||
|
daemon_probe: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -524,7 +605,13 @@ impl Wallet {
|
||||||
.map(|v| Zeroizing::new(v.trim().to_string()))
|
.map(|v| Zeroizing::new(v.trim().to_string()))
|
||||||
.filter(|v| !v.is_empty());
|
.filter(|v| !v.is_empty());
|
||||||
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
|
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
|
||||||
Ok(endpoint) => Self::new(Some(endpoint), no_spend),
|
Ok(endpoint) => {
|
||||||
|
// Store wins (see `for_boot`); this path only runs when
|
||||||
|
// no usable stored config exists, so the login really is
|
||||||
|
// coming from the environment.
|
||||||
|
warn_env_login_once();
|
||||||
|
Self::new(Some(endpoint), no_spend)
|
||||||
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
|
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
|
||||||
Self::new(None, no_spend)
|
Self::new(None, no_spend)
|
||||||
|
|
@ -546,7 +633,7 @@ impl Wallet {
|
||||||
return Err(Error("wallet RPC endpoint required".into()));
|
return Err(Error("wallet RPC endpoint required".into()));
|
||||||
}
|
}
|
||||||
let ep = parse_http_url(cfg.rpc_url.trim(), Some(cfg.rpc_login.as_str()))
|
let ep = parse_http_url(cfg.rpc_url.trim(), Some(cfg.rpc_login.as_str()))
|
||||||
.map_err(|e| Error(redact(&e.to_string(), cfg.secret())))?;
|
.map_err(|e| Error(redact_login(&e.to_string(), cfg.rpc_login.as_str())))?;
|
||||||
Ok(Self::new(Some(ep), cfg.no_spend))
|
Ok(Self::new(Some(ep), cfg.no_spend))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -632,7 +719,7 @@ impl Wallet {
|
||||||
return PingResult {
|
return PingResult {
|
||||||
ok: false,
|
ok: false,
|
||||||
status: "not connected".into(),
|
status: "not connected".into(),
|
||||||
error: Some(redact(&e.to_string(), cfg.secret())),
|
error: Some(redact_login(&e.to_string(), cfg.rpc_login.as_str())),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
@ -654,12 +741,13 @@ impl Wallet {
|
||||||
|
|
||||||
/// Display-safe copy of an error: no RPC password, short enough for a line.
|
/// Display-safe copy of an error: no RPC password, short enough for a line.
|
||||||
fn sanitize(&self, msg: &str) -> String {
|
fn sanitize(&self, msg: &str) -> String {
|
||||||
let pass = self
|
// Both halves of `user:pass`, not just the password: an error that
|
||||||
.endpoint
|
// names the URL's userinfo must not survive as `user:<redacted>`.
|
||||||
.as_ref()
|
let login = match self.endpoint.as_ref() {
|
||||||
.map(|e| e.pass.as_str())
|
Some(ep) => Zeroizing::new(format!("{}:{}", ep.user, ep.pass.as_str())),
|
||||||
.unwrap_or("");
|
None => Zeroizing::new(String::new()),
|
||||||
redact(msg, pass)
|
};
|
||||||
|
redact_login(msg, login.as_str())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set both RPC budgets. The timeout is a property of the backend, not a
|
/// Set both RPC budgets. The timeout is a property of the backend, not a
|
||||||
|
|
@ -677,6 +765,13 @@ impl Wallet {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Where to read the chain tip for the readiness comparison. `None` keeps
|
||||||
|
/// readiness fail-closed: a wallet with no comparable daemon is never ready.
|
||||||
|
pub fn with_daemon_probe(mut self, addr: Option<String>) -> Self {
|
||||||
|
self.daemon_probe = addr;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
pub fn no_spend(&self) -> bool {
|
pub fn no_spend(&self) -> bool {
|
||||||
self.no_spend
|
self.no_spend
|
||||||
}
|
}
|
||||||
|
|
@ -790,27 +885,34 @@ impl Wallet {
|
||||||
.map_err(|_| Error("wallet RPC returned a non-numeric unlocked_balance".into()))
|
.map_err(|_| Error("wallet RPC returned a non-numeric unlocked_balance".into()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The real readiness predicate: the daemon has reached the chain tip and
|
/// The real readiness predicate: the wallet's own scanned height is at the
|
||||||
/// the wallet has scanned up to it. `synchronized` must be explicitly true —
|
/// chain tip (within the deliberate [`READY_SLACK_BLOCKS`]). The wallet RPC
|
||||||
/// a missing field is not-ready, never a silent pass.
|
/// is asked `get_height` — never `get_info`, which it does not implement —
|
||||||
|
/// and the tip comes from the daemon client.
|
||||||
pub async fn chain_ready(&self) -> Result<bool> {
|
pub async fn chain_ready(&self) -> Result<bool> {
|
||||||
Ok(self.chain_info().await?.ready())
|
Ok(self.chain_info().await?.ready())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One `get_info` round trip, carrying both the readiness fields and the
|
/// One readiness pair: the wallet's scanned height from the wallet RPC's
|
||||||
/// numbers a status line shows — the status line and the spend gate ask the
|
/// `get_height`, and the daemon's tip from the daemon client. The status
|
||||||
/// same question, so they ask it once. `0` height/target means the wallet
|
/// line and the spend gate ask the same question, so they ask it once.
|
||||||
/// RPC answered without a number: unknown, never "caught up".
|
///
|
||||||
|
/// A wallet RPC that cannot answer (no wallet file open, restarting,
|
||||||
|
/// transport) is `height: 0` + no tip: unknown is not ready, and "no wallet
|
||||||
|
/// open" is a state, not an error to paint on a status row. A missing
|
||||||
|
/// daemon answer leaves `tip: None`, which is also not ready.
|
||||||
pub async fn chain_info(&self) -> Result<ChainInfo> {
|
pub async fn chain_info(&self) -> Result<ChainInfo> {
|
||||||
let v = self.chain_rpc("get_info", serde_json::json!({})).await?;
|
let height = match self.chain_rpc("get_height", serde_json::json!({})).await {
|
||||||
Ok(ChainInfo {
|
Ok(v) => v.get("height").and_then(|h| h.as_u64()).unwrap_or(0),
|
||||||
synchronized: v
|
Err(_) => 0,
|
||||||
.get("synchronized")
|
};
|
||||||
.and_then(|b| b.as_bool())
|
let tip = match self.daemon_probe.as_deref() {
|
||||||
.unwrap_or(false),
|
// One small probe: a slow or dead daemon is "unknown", not a hung
|
||||||
height: v.get("height").and_then(|h| h.as_u64()).unwrap_or(0),
|
// status poll. The management budget is the short one.
|
||||||
target_height: v.get("target_height").and_then(|h| h.as_u64()).unwrap_or(0),
|
Some(addr) => daemon_get_height(addr, self.timeout_local).await.ok(),
|
||||||
})
|
None => None,
|
||||||
|
};
|
||||||
|
Ok(ChainInfo { height, tip })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// May this wallet attempt a spend? Fail closed: any readiness doubt is a
|
/// May this wallet attempt a spend? Fail closed: any readiness doubt is a
|
||||||
|
|
@ -1798,3 +1900,70 @@ fn hex_val(c: u8) -> Option<u8> {
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
/// The env is process-wide; these are the only lib tests that touch it.
|
||||||
|
static ENV_LOCK: Mutex<()> = Mutex::new(());
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn redacting_an_error_drops_the_whole_login_not_just_the_password() {
|
||||||
|
let msg = "dial http://ow:[email protected]:18083 failed for ow:hunter2";
|
||||||
|
let out = redact_login(msg, "ow:hunter2");
|
||||||
|
assert!(!out.contains("hunter2"), "{out}");
|
||||||
|
assert!(!out.contains("ow:hunter2"), "{out}");
|
||||||
|
assert!(out.contains("127.0.0.1:18083"), "{out}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn redacted_url_keeps_the_endpoint_and_drops_the_userinfo() {
|
||||||
|
assert_eq!(
|
||||||
|
redact_url("http://ow:[email protected]:18083/json_rpc"),
|
||||||
|
"http://<redacted>:<redacted>@127.0.0.1:18083/json_rpc"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
redact_url("http://127.0.0.1:18083/json_rpc"),
|
||||||
|
"http://127.0.0.1:18083/json_rpc"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wallet_debug_prints_no_login() {
|
||||||
|
let w = Wallet::from_url("http://ow:[email protected]:18083").unwrap();
|
||||||
|
let dbg = format!("{w:?}");
|
||||||
|
assert!(!dbg.contains("hunter2"), "{dbg}");
|
||||||
|
assert!(!dbg.contains("ow:hunter2"), "{dbg}");
|
||||||
|
assert!(dbg.contains("127.0.0.1"), "{dbg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn env_login_warns_once_per_process_and_not_for_a_stored_config() {
|
||||||
|
let _guard = ENV_LOCK.lock().unwrap();
|
||||||
|
ENV_LOGIN_WARNED.store(false, Ordering::SeqCst);
|
||||||
|
// The one-shot gate itself: the first call prints, later ones do not.
|
||||||
|
assert!(warn_env_login_once(), "first env login must warn");
|
||||||
|
assert!(!warn_env_login_once(), "warning is once per process");
|
||||||
|
ENV_LOGIN_WARNED.store(false, Ordering::SeqCst);
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://127.0.0.1:18083");
|
||||||
|
std::env::set_var("ONIONWIRE_WALLET_RPC_LOGIN", "ow:hunter2");
|
||||||
|
}
|
||||||
|
let _ = Wallet::from_env();
|
||||||
|
let warned_from_env = ENV_LOGIN_WARNED.load(Ordering::SeqCst);
|
||||||
|
unsafe { std::env::remove_var("ONIONWIRE_WALLET_RPC_LOGIN") };
|
||||||
|
assert!(warned_from_env, "an env login must warn");
|
||||||
|
|
||||||
|
// The store is the preferred channel; `for_boot` takes it and never
|
||||||
|
// reaches the env path, so no warning.
|
||||||
|
ENV_LOGIN_WARNED.store(false, Ordering::SeqCst);
|
||||||
|
let cfg = WalletConfig::new("http://127.0.0.1:18083", "ow:hunter2", false);
|
||||||
|
let _ = Wallet::for_boot(Some(&cfg));
|
||||||
|
let warned_from_store = ENV_LOGIN_WARNED.load(Ordering::SeqCst);
|
||||||
|
unsafe { std::env::remove_var("ONIONWIRE_WALLET_RPC") };
|
||||||
|
assert!(!warned_from_store, "a stored login must not warn");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@
|
||||||
//! compiled-in public node.
|
//! compiled-in public node.
|
||||||
//! * A `.onion` daemon is reached through a SOCKS child: the bundled `arti`
|
//! * A `.onion` daemon is reached through a SOCKS child: the bundled `arti`
|
||||||
//! binary run as `arti proxy -p <port>`, with **TCP loopback only** (arti
|
//! binary run as `arti proxy -p <port>`, with **TCP loopback only** (arti
|
||||||
//! 2.6.0 / tor-config 0.46 have no AF_UNIX listener — `Listen` is IP-only and
|
//! 2.6.0 / tor-config 0.49 have no AF_UNIX listener — `Listen` is IP-only and
|
||||||
//! arti's `port_info` says AF_UNIX is future work, arti#1965). The wallet
|
//! arti's `port_info` says AF_UNIX is future work, arti#1965). The wallet
|
||||||
//! child is then pointed at it with `--proxy socks5://127.0.0.1:<port>`
|
//! child is then pointed at it with `--proxy socks5://127.0.0.1:<port>`
|
||||||
//! *and* `--daemon-address <onion>:<port>`. The messenger's in-process
|
//! *and* `--daemon-address <onion>:<port>`. The messenger's in-process
|
||||||
|
|
@ -22,6 +22,13 @@
|
||||||
//! * The two Tor clients do not share state: the SOCKS child gets its own
|
//! * The two Tor clients do not share state: the SOCKS child gets its own
|
||||||
//! `state_dir`/`cache_dir` under the wallet dir.
|
//! `state_dir`/`cache_dir` under the wallet dir.
|
||||||
//! * `--trusted-daemon` is never passed: a remote daemon is untrusted.
|
//! * `--trusted-daemon` is never passed: a remote daemon is untrusted.
|
||||||
|
//! * Residual, and not fixable while the child is a spawned `monero-wallet-rpc`:
|
||||||
|
//! `--rpc-login` is visible in `/proc/<pid>/cmdline` to same-uid processes
|
||||||
|
//! because `monero-wallet-rpc` offers no other credential channel. The
|
||||||
|
//! mitigation is a loopback-only bind, a strong generated login, and never
|
||||||
|
//! handing the child a remote daemon. The login is also never rendered: the
|
||||||
|
//! client's `url()` carries it for `Wallet::from_url`, while `Debug` and
|
||||||
|
//! [`WalletClient::redacted_url`] show `http://<redacted>:<redacted>@127.0.0.1:<port>`.
|
||||||
//! * The in-process daemon is *not* a child: it is a value owned by this struct,
|
//! * The in-process daemon is *not* a child: it is a value owned by this struct,
|
||||||
//! and dropping it shuts the node down. It still binds the same loopback RPC
|
//! and dropping it shuts the node down. It still binds the same loopback RPC
|
||||||
//! port, so everything downstream of `--daemon-address` is unchanged.
|
//! port, so everything downstream of `--daemon-address` is unchanged.
|
||||||
|
|
@ -283,7 +290,7 @@ impl WalletChild {
|
||||||
/// one app never share state silently.
|
/// one app never share state silently.
|
||||||
///
|
///
|
||||||
/// `-p` is the arti CLI's `socks-port` argument (arti 2.6.0 `src/lib.rs`);
|
/// `-p` is the arti CLI's `socks-port` argument (arti 2.6.0 `src/lib.rs`);
|
||||||
/// it binds localhost only (`Listen::new_localhost`, tor-config 0.46
|
/// it binds localhost only (`Listen::new_localhost`, tor-config 0.49
|
||||||
/// `listen.rs`: "We interpret standalone ports to be localhost
|
/// `listen.rs`: "We interpret standalone ports to be localhost
|
||||||
/// addresses" — `[::1, 127.0.0.1]`). There is no Unix-socket listen target
|
/// addresses" — `[::1, 127.0.0.1]`). There is no Unix-socket listen target
|
||||||
/// to prefer: `Listen` is IP-only and arti's `port_info` says AF_UNIX is
|
/// to prefer: `Listen` is IP-only and arti's `port_info` says AF_UNIX is
|
||||||
|
|
@ -544,6 +551,15 @@ impl WalletChild {
|
||||||
&self,
|
&self,
|
||||||
creds: impl FnOnce() -> Result<(String, Zeroizing<String>)>,
|
creds: impl FnOnce() -> Result<(String, Zeroizing<String>)>,
|
||||||
) -> Result<Option<WalletClient>> {
|
) -> Result<Option<WalletClient>> {
|
||||||
|
// Pre-flight the wallet RPC binary before anything is spawned: a bin
|
||||||
|
// that cannot be exec'd must not cost a daemon launch (and its
|
||||||
|
// readiness wait) first, and `exec`'s errno alone cannot say *which*
|
||||||
|
// path was missing.
|
||||||
|
// A bare name is the copy next to this binary, when one is there.
|
||||||
|
// An absolute path is the caller's (Android jniLibs, a test fake).
|
||||||
|
let bin = resolve_wallet_rpc_bin(&self.wallet_rpc_bin, bundled_wallet_rpc_dir().as_deref());
|
||||||
|
check_wallet_rpc_bin(&self.wallet_rpc_bin, &bin, bare_bin_resolvable())?;
|
||||||
|
|
||||||
// Local chain source: own the daemon first, so the wallet child has
|
// Local chain source: own the daemon first, so the wallet child has
|
||||||
// something to dial. Either a spawned `monerod` or the in-process
|
// something to dial. Either a spawned `monerod` or the in-process
|
||||||
// Cuprate node — both bind `DEFAULT_MONEROD_RPC_PORT` on loopback, so
|
// Cuprate node — both bind `DEFAULT_MONEROD_RPC_PORT` on loopback, so
|
||||||
|
|
@ -603,9 +619,6 @@ impl WalletChild {
|
||||||
let port = Self::pick_port()?;
|
let port = Self::pick_port()?;
|
||||||
let login = format!("{user}:{}", pass.as_str());
|
let login = format!("{user}:{}", pass.as_str());
|
||||||
let daemon = Self::daemon_address(&self.source);
|
let daemon = Self::daemon_address(&self.source);
|
||||||
// A bare name is the copy next to this binary, when one is there.
|
|
||||||
// An absolute path is the caller's (Android jniLibs, a test fake).
|
|
||||||
let bin = resolve_wallet_rpc_bin(&self.wallet_rpc_bin, bundled_wallet_rpc_dir().as_deref());
|
|
||||||
let argv = Self::wallet_rpc_argv(
|
let argv = Self::wallet_rpc_argv(
|
||||||
&bin,
|
&bin,
|
||||||
port,
|
port,
|
||||||
|
|
@ -774,7 +787,9 @@ pub struct ChildConfig {
|
||||||
/// The user's chain-source choice. `None` is receive-only: nothing spawns.
|
/// The user's chain-source choice. `None` is receive-only: nothing spawns.
|
||||||
pub source: ChainSource,
|
pub source: ChainSource,
|
||||||
/// `monero-wallet-rpc`. A bare name is resolved on `PATH`; Android passes an
|
/// `monero-wallet-rpc`. A bare name is resolved on `PATH`; Android passes an
|
||||||
/// absolute path out of the app's native library directory.
|
/// absolute path out of the app's native library directory. On a target
|
||||||
|
/// with no `PATH` to resolve it (Android), a bare name is refused rather
|
||||||
|
/// than persisted — it could only fail at `exec`.
|
||||||
pub wallet_rpc_bin: PathBuf,
|
pub wallet_rpc_bin: PathBuf,
|
||||||
/// `arti`, run as the SOCKS child for a `.onion` daemon only.
|
/// `arti`, run as the SOCKS child for a `.onion` daemon only.
|
||||||
pub arti_bin: PathBuf,
|
pub arti_bin: PathBuf,
|
||||||
|
|
@ -809,17 +824,25 @@ impl ChildConfig {
|
||||||
self.source.label()
|
self.source.label()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Where a status refresh may ask the chain daemon itself for
|
/// Where the readiness comparison may ask the chain daemon itself for its
|
||||||
/// height/target, when the wallet RPC is not answering. Only a daemon this
|
/// tip. `monero-wallet-rpc` has no `get_info`, so the wallet's own
|
||||||
/// box owns: a `monerod`/Cuprate the child spawned binds loopback, and
|
/// `get_height` is only half the answer.
|
||||||
/// asking it is a plain local socket. A remote daemon is the wallet child's
|
///
|
||||||
/// to dial (over SOCKS, if it is an onion) — a status refresh does not open
|
/// - A daemon this box owns (`monerod`/Cuprate it spawned) binds loopback:
|
||||||
/// a second path to it.
|
/// asking it is a plain local socket.
|
||||||
|
/// - A clearnet remote daemon the user typed is already the wallet child's
|
||||||
|
/// dial target, so one `get_height` is the same exposure — not a new path.
|
||||||
|
/// - A `.onion` daemon must **not** be dialled directly: without the SOCKS
|
||||||
|
/// child that would resolve the name on clearnet DNS and leak. It stays
|
||||||
|
/// fail-closed (height-only, not ready) until the SOCKS path exists.
|
||||||
pub fn daemon_probe_addr(&self) -> Option<String> {
|
pub fn daemon_probe_addr(&self) -> Option<String> {
|
||||||
match self.source {
|
match &self.source {
|
||||||
ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. } => {
|
ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. } => {
|
||||||
Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"))
|
Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"))
|
||||||
}
|
}
|
||||||
|
ChainSource::Remote { host, port } if !crate::wallet::is_onion_host(host) => {
|
||||||
|
Some(format!("{}:{port}", host.trim()))
|
||||||
|
}
|
||||||
ChainSource::None | ChainSource::Remote { .. } => None,
|
ChainSource::None | ChainSource::Remote { .. } => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -837,6 +860,14 @@ impl ChildConfig {
|
||||||
if self.wallet_rpc_bin.as_os_str().is_empty() {
|
if self.wallet_rpc_bin.as_os_str().is_empty() {
|
||||||
return Err(ChildError("monero-wallet-rpc path required".into()));
|
return Err(ChildError("monero-wallet-rpc path required".into()));
|
||||||
}
|
}
|
||||||
|
// A bare name is only resolvable through `PATH`. Where this target has
|
||||||
|
// no `PATH` to search (an app sandbox), accepting it here would persist
|
||||||
|
// a setting that can only fail at `exec`, so refuse it with the path in
|
||||||
|
// the message. The resolved-bin existence check is the start path's job
|
||||||
|
// (`check_wallet_rpc_bin`): at save time the file may not be created yet.
|
||||||
|
if !bare_bin_resolvable() && self.wallet_rpc_bin.components().nth(1).is_none() {
|
||||||
|
return Err(bare_bin_refused(&self.wallet_rpc_bin));
|
||||||
|
}
|
||||||
if self.arti_bin.as_os_str().is_empty() {
|
if self.arti_bin.as_os_str().is_empty() {
|
||||||
return Err(ChildError("arti path required".into()));
|
return Err(ChildError("arti path required".into()));
|
||||||
}
|
}
|
||||||
|
|
@ -1060,12 +1091,23 @@ impl WalletChildStatus {
|
||||||
/// The loopback client built from the generated URL — the production path when
|
/// The loopback client built from the generated URL — the production path when
|
||||||
/// the app owns the child. Never `ONIONWIRE_WALLET_RPC`, never anything but
|
/// the app owns the child. Never `ONIONWIRE_WALLET_RPC`, never anything but
|
||||||
/// numeric loopback.
|
/// numeric loopback.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Clone)]
|
||||||
pub struct WalletClient {
|
pub struct WalletClient {
|
||||||
url: String,
|
url: String,
|
||||||
no_spend: bool,
|
no_spend: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Hand-written: `url` carries the generated login, so a derived `Debug` would
|
||||||
|
/// turn any `{:?}` — a log line, a panic message, an assert — into a leak.
|
||||||
|
impl std::fmt::Debug for WalletClient {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("WalletClient")
|
||||||
|
.field("url", &self.redacted_url())
|
||||||
|
.field("no_spend", &self.no_spend)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl WalletClient {
|
impl WalletClient {
|
||||||
/// Build the [`Wallet`] this child serves. The chain-side RPC budget is the
|
/// Build the [`Wallet`] this child serves. The chain-side RPC budget is the
|
||||||
/// wallet backend's default (see `CHAIN_RPC_TIMEOUT`), because a first sync
|
/// wallet backend's default (see `CHAIN_RPC_TIMEOUT`), because a first sync
|
||||||
|
|
@ -1076,11 +1118,18 @@ impl WalletClient {
|
||||||
.with_no_spend(self.no_spend)
|
.with_no_spend(self.no_spend)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The loopback URL. Carries the generated creds — do not log it.
|
/// The loopback URL. Carries the generated creds — do not log it; use
|
||||||
|
/// [`WalletClient::redacted_url`] for anything a human or a log can see.
|
||||||
pub fn url(&self) -> &str {
|
pub fn url(&self) -> &str {
|
||||||
&self.url
|
&self.url
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The same endpoint with both halves of the login replaced:
|
||||||
|
/// `http://<redacted>:<redacted>@127.0.0.1:<port>/json_rpc`.
|
||||||
|
pub fn redacted_url(&self) -> String {
|
||||||
|
wallet::redact_url(&self.url)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn no_spend(&self) -> bool {
|
pub fn no_spend(&self) -> bool {
|
||||||
self.no_spend
|
self.no_spend
|
||||||
}
|
}
|
||||||
|
|
@ -1229,6 +1278,60 @@ fn resolve_wallet_rpc_bin(configured: &Path, beside: Option<&Path>) -> PathBuf {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Can a spawned child resolve a bare `argv[0]` through `PATH` on this target?
|
||||||
|
/// An app sandbox (Android) has no `PATH` for a child to search, so a bare name
|
||||||
|
/// there can only fail at `exec`; a desktop can resolve one. Compile-time, so
|
||||||
|
/// the core needs no runtime platform probe.
|
||||||
|
const fn bare_bin_resolvable() -> bool {
|
||||||
|
!cfg!(target_os = "android")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bare_bin_refused(configured: &Path) -> ChildError {
|
||||||
|
ChildError(format!(
|
||||||
|
"monero-wallet-rpc: {} is a bare name and this platform has no PATH to resolve it; \
|
||||||
|
configure an absolute path",
|
||||||
|
configured.display()
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pre-flight the wallet RPC binary *before* `exec`, so the failure names the
|
||||||
|
/// path and the reason instead of a bare `os error 2`.
|
||||||
|
///
|
||||||
|
/// `resolved` is what `spawn` would use; `configured` is what the caller set.
|
||||||
|
/// A bare name is `PATH`'s job where a `PATH` exists — this does not search
|
||||||
|
/// one, and does not fall back anywhere. On a target with no `PATH`
|
||||||
|
/// (`bare_resolvable == false`) a bare name is refused outright.
|
||||||
|
fn check_wallet_rpc_bin(configured: &Path, resolved: &Path, bare_resolvable: bool) -> Result<()> {
|
||||||
|
if resolved.components().nth(1).is_none() {
|
||||||
|
return if bare_resolvable {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(bare_bin_refused(configured))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let named = if resolved == configured {
|
||||||
|
configured.display().to_string()
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"{} (configured {})",
|
||||||
|
resolved.display(),
|
||||||
|
configured.display()
|
||||||
|
)
|
||||||
|
};
|
||||||
|
match fs::metadata(resolved) {
|
||||||
|
Ok(meta) if !meta.is_file() => Err(ChildError(format!(
|
||||||
|
"monero-wallet-rpc: {named} is not a file"
|
||||||
|
))),
|
||||||
|
Ok(meta) if meta.permissions().mode() & 0o111 == 0 => Err(ChildError(format!(
|
||||||
|
"monero-wallet-rpc: {named} is not executable"
|
||||||
|
))),
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(e) => Err(ChildError(format!(
|
||||||
|
"monero-wallet-rpc: {named} not found ({e})"
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn executable_file(path: &Path) -> bool {
|
fn executable_file(path: &Path) -> bool {
|
||||||
std::fs::metadata(path)
|
std::fs::metadata(path)
|
||||||
.is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
|
.is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
|
||||||
|
|
@ -1246,10 +1349,12 @@ fn spawn(argv: &[String], what: &str) -> Result<Child> {
|
||||||
let (bin, args) = argv
|
let (bin, args) = argv
|
||||||
.split_first()
|
.split_first()
|
||||||
.ok_or_else(|| ChildError(format!("empty argv for {what}")))?;
|
.ok_or_else(|| ChildError(format!("empty argv for {what}")))?;
|
||||||
Command::new(bin)
|
Command::new(bin).args(args).spawn().map_err(|e| {
|
||||||
.args(args)
|
// Both halves matter: the label keeps the copy readable, `argv[0]`
|
||||||
.spawn()
|
// says which program actually failed (a bare name vs. an absolute
|
||||||
.map_err(|e| ChildError(format!("spawn {what}: {e}")))
|
// path — the difference the Android report could not show).
|
||||||
|
ChildError(format!("spawn {what} ({bin}): {e}"))
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn kill_slot(slot: &Mutex<Option<Child>>, what: &str) -> Result<()> {
|
fn kill_slot(slot: &Mutex<Option<Child>>, what: &str) -> Result<()> {
|
||||||
|
|
@ -1506,7 +1611,7 @@ mod tests {
|
||||||
"{argv:?}"
|
"{argv:?}"
|
||||||
);
|
);
|
||||||
// `-p` binds localhost only (arti's `socks-port` arg); there is no
|
// `-p` binds localhost only (arti's `socks-port` arg); there is no
|
||||||
// Unix-socket listen target in arti 2.6.0 / tor-config 0.46.
|
// Unix-socket listen target in arti 2.6.0 / tor-config 0.49.
|
||||||
assert!(!argv.iter().any(|a| a == "--port"), "{argv:?}");
|
assert!(!argv.iter().any(|a| a == "--port"), "{argv:?}");
|
||||||
assert!(
|
assert!(
|
||||||
argv.iter()
|
argv.iter()
|
||||||
|
|
@ -1912,6 +2017,123 @@ mod tests {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The spawn error must name the *program that failed* (`argv[0]`), not
|
||||||
|
/// just the human label: on Android the two differ, and which one it was is
|
||||||
|
/// the whole diagnosis.
|
||||||
|
#[test]
|
||||||
|
fn a_spawn_error_names_argv0_and_the_label() {
|
||||||
|
let dir = tmp_dir("spawn-missing");
|
||||||
|
fs::create_dir_all(&dir).unwrap();
|
||||||
|
let missing = dir.join("libmonerowalletrpc.so");
|
||||||
|
let argv = vec![missing.display().to_string(), "--version".into()];
|
||||||
|
|
||||||
|
let err = spawn(&argv, "monero-wallet-rpc").expect_err("a missing program cannot spawn");
|
||||||
|
let msg = err.to_string();
|
||||||
|
assert!(msg.starts_with("spawn monero-wallet-rpc ("), "{msg}");
|
||||||
|
assert!(msg.contains(&missing.display().to_string()), "{msg}");
|
||||||
|
// The errno is carried through verbatim: no invented cause.
|
||||||
|
assert!(msg.contains("No such file or directory"), "{msg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pre-flight: a bin that is not an existing regular executable is refused
|
||||||
|
/// with the configured path in the message, before `exec` gets a say.
|
||||||
|
#[test]
|
||||||
|
fn a_missing_wallet_rpc_bin_is_refused_with_the_configured_path() {
|
||||||
|
let dir = tmp_dir("preflight-missing");
|
||||||
|
fs::create_dir_all(&dir).unwrap();
|
||||||
|
let configured = dir.join("libmonerowalletrpc.so");
|
||||||
|
|
||||||
|
let err = check_wallet_rpc_bin(&configured, &configured, true)
|
||||||
|
.expect_err("a bin that does not exist cannot be spawned");
|
||||||
|
let msg = err.to_string();
|
||||||
|
assert!(msg.contains(&configured.display().to_string()), "{msg}");
|
||||||
|
assert!(msg.contains("not found"), "{msg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wallet_rpc_bin_that_is_not_a_file_is_refused() {
|
||||||
|
let dir = tmp_dir("preflight-dir");
|
||||||
|
let configured = dir.join("libmonerowalletrpc.so");
|
||||||
|
fs::create_dir_all(&configured).unwrap();
|
||||||
|
|
||||||
|
let err = check_wallet_rpc_bin(&configured, &configured, true)
|
||||||
|
.expect_err("a directory cannot be executed");
|
||||||
|
let msg = err.to_string();
|
||||||
|
assert!(msg.contains(&configured.display().to_string()), "{msg}");
|
||||||
|
assert!(msg.contains("not a file"), "{msg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wallet_rpc_bin_without_any_execute_bit_is_refused() {
|
||||||
|
let dir = tmp_dir("preflight-noexec");
|
||||||
|
fs::create_dir_all(&dir).unwrap();
|
||||||
|
let configured = dir.join("libmonerowalletrpc.so");
|
||||||
|
fs::write(&configured, b"not a program\n").unwrap();
|
||||||
|
let mut perms = fs::metadata(&configured).unwrap().permissions();
|
||||||
|
perms.set_mode(0o644);
|
||||||
|
fs::set_permissions(&configured, perms).unwrap();
|
||||||
|
|
||||||
|
let err = check_wallet_rpc_bin(&configured, &configured, true)
|
||||||
|
.expect_err("a file with no execute bit cannot be spawned");
|
||||||
|
let msg = err.to_string();
|
||||||
|
assert!(msg.contains(&configured.display().to_string()), "{msg}");
|
||||||
|
assert!(msg.contains("not executable"), "{msg}");
|
||||||
|
|
||||||
|
let mut perms = fs::metadata(&configured).unwrap().permissions();
|
||||||
|
perms.set_mode(0o755);
|
||||||
|
fs::set_permissions(&configured, perms).unwrap();
|
||||||
|
assert!(
|
||||||
|
check_wallet_rpc_bin(&configured, &configured, true).is_ok(),
|
||||||
|
"an executable file passes the pre-flight"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A bare name is only resolvable through `PATH`. Where the target has no
|
||||||
|
/// `PATH` to search (an app sandbox), it is refused with the path in the
|
||||||
|
/// message; on a desktop the pre-flight leaves it to `exec`.
|
||||||
|
#[test]
|
||||||
|
fn a_bare_wallet_rpc_bin_is_refused_where_path_cannot_resolve_it() {
|
||||||
|
let bare = Path::new("monero-wallet-rpc");
|
||||||
|
|
||||||
|
let err = check_wallet_rpc_bin(bare, bare, false)
|
||||||
|
.expect_err("a bare name cannot resolve in an app sandbox");
|
||||||
|
let msg = err.to_string();
|
||||||
|
assert!(msg.contains("monero-wallet-rpc"), "{msg}");
|
||||||
|
assert!(msg.contains("bare name"), "{msg}");
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
check_wallet_rpc_bin(bare, bare, true).is_ok(),
|
||||||
|
"a desktop leaves a bare name to PATH"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The start path refuses a missing bin before spawning anything, and says
|
||||||
|
/// which configured path was missing.
|
||||||
|
#[test]
|
||||||
|
fn start_refuses_a_wallet_rpc_bin_that_is_not_there() {
|
||||||
|
let dir = tmp_dir("start-missing-bin");
|
||||||
|
let store = open_store(&dir);
|
||||||
|
let missing = dir.join("wallet").join("libmonerowalletrpc.so");
|
||||||
|
let child = WalletChild::new(
|
||||||
|
ChainSource::Remote {
|
||||||
|
host: "127.0.0.1".into(),
|
||||||
|
port: 18089,
|
||||||
|
},
|
||||||
|
dir.join("wallet"),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
.with_wallet_rpc_bin(missing.clone());
|
||||||
|
|
||||||
|
let err = child
|
||||||
|
.start(&store)
|
||||||
|
.expect_err("a missing wallet rpc bin cannot spawn");
|
||||||
|
let msg = err.to_string();
|
||||||
|
assert!(msg.contains(&missing.display().to_string()), "{msg}");
|
||||||
|
assert!(msg.contains("not found"), "{msg}");
|
||||||
|
assert!(!child.running(), "nothing may be left running: {msg}");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn monerod_argv_binds_loopback_and_uses_the_datadir() {
|
fn monerod_argv_binds_loopback_and_uses_the_datadir() {
|
||||||
let dir = tmp_dir("monerod-argv");
|
let dir = tmp_dir("monerod-argv");
|
||||||
|
|
@ -2055,6 +2277,26 @@ mod tests {
|
||||||
rest.split('@').next().expect("userinfo").to_string()
|
rest.split('@').next().expect("userinfo").to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The client dials with creds in the URL, but nothing that renders it may
|
||||||
|
/// repeat them: `Debug` and `redacted_url` are the display surfaces.
|
||||||
|
#[test]
|
||||||
|
fn wallet_client_debug_and_redacted_url_hide_the_login() {
|
||||||
|
let client = WalletClient {
|
||||||
|
url: "http://alice:[email protected]:18083/json_rpc".into(),
|
||||||
|
no_spend: false,
|
||||||
|
};
|
||||||
|
let dbg = format!("{client:?}");
|
||||||
|
assert!(!dbg.contains("s3cret"), "{dbg}");
|
||||||
|
assert!(!dbg.contains("alice:s3cret"), "{dbg}");
|
||||||
|
assert!(dbg.contains("127.0.0.1"), "{dbg}");
|
||||||
|
assert_eq!(
|
||||||
|
client.redacted_url(),
|
||||||
|
"http://<redacted>:<redacted>@127.0.0.1:18083/json_rpc"
|
||||||
|
);
|
||||||
|
// The dial still needs the real userinfo — redaction is for display.
|
||||||
|
assert!(client.url().contains("alice:s3cret"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn pick_port_is_free_loopback_and_bindable() {
|
fn pick_port_is_free_loopback_and_bindable() {
|
||||||
let port = WalletChild::pick_port().unwrap();
|
let port = WalletChild::pick_port().unwrap();
|
||||||
|
|
@ -2375,11 +2617,12 @@ mod tests {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Only a daemon this box owns is asked directly. A remote daemon is the
|
/// A daemon this box owns, or a clearnet daemon the user typed, may be asked
|
||||||
/// wallet child's to dial — a status refresh must not open a second path to
|
/// for its tip: both are already dialled by the wallet child. A `.onion`
|
||||||
/// it, and receive-only has nothing to ask at all.
|
/// daemon must not be dialled without the SOCKS child, and receive-only has
|
||||||
|
/// nothing to ask at all.
|
||||||
#[test]
|
#[test]
|
||||||
fn only_a_loopback_source_gets_a_daemon_probe_address() {
|
fn only_a_reachable_daemon_gets_a_probe_address() {
|
||||||
let loopback = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}");
|
let loopback = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}");
|
||||||
for source in [
|
for source in [
|
||||||
ChainSource::Local {
|
ChainSource::Local {
|
||||||
|
|
@ -2399,16 +2642,25 @@ mod tests {
|
||||||
};
|
};
|
||||||
assert_eq!(cfg.daemon_probe_addr().as_deref(), Some(loopback.as_str()));
|
assert_eq!(cfg.daemon_probe_addr().as_deref(), Some(loopback.as_str()));
|
||||||
}
|
}
|
||||||
|
// A clearnet remote daemon is the user's explicit choice and the wallet
|
||||||
|
// child already dials it: one `get_height` is the same exposure.
|
||||||
|
let cfg = ChildConfig {
|
||||||
|
source: ChainSource::Remote {
|
||||||
|
host: "203.0.113.7".to_string(),
|
||||||
|
port: 18081,
|
||||||
|
},
|
||||||
|
..ChildConfig::default()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
cfg.daemon_probe_addr().as_deref(),
|
||||||
|
Some("203.0.113.7:18081")
|
||||||
|
);
|
||||||
for source in [
|
for source in [
|
||||||
ChainSource::None,
|
ChainSource::None,
|
||||||
ChainSource::Remote {
|
ChainSource::Remote {
|
||||||
host: "peer.onion".to_string(),
|
host: "peer.onion".to_string(),
|
||||||
port: 18081,
|
port: 18081,
|
||||||
},
|
},
|
||||||
ChainSource::Remote {
|
|
||||||
host: "203.0.113.7".to_string(),
|
|
||||||
port: 18081,
|
|
||||||
},
|
|
||||||
] {
|
] {
|
||||||
let cfg = ChildConfig {
|
let cfg = ChildConfig {
|
||||||
source,
|
source,
|
||||||
|
|
|
||||||
185
tests/app_sig.rs
185
tests/app_sig.rs
|
|
@ -198,3 +198,188 @@ fn inv_signature_does_not_verify_as_rcp() {
|
||||||
"inv-shaped payload must not verify as rcp"
|
"inv-shaped payload must not verify as rcp"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- legacy acceptance is one switch (`pay::LEGACY_SIGS`) ----
|
||||||
|
|
||||||
|
fn untagged_loc(sk: &SigningKey, onion: &str, ts: i64) -> Loc {
|
||||||
|
let mut msg = Vec::from(onion.as_bytes());
|
||||||
|
msg.push(b'\n');
|
||||||
|
msg.extend_from_slice(ts.to_string().as_bytes());
|
||||||
|
Loc {
|
||||||
|
onion: onion.into(),
|
||||||
|
ts,
|
||||||
|
sig: sk.sign(&msg).to_bytes().to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn untagged_inv(sk: &SigningKey, amount: &str, address: &str, memo: &str, ts: i64) -> Invoice {
|
||||||
|
let mut msg = Vec::from(amount.as_bytes());
|
||||||
|
msg.push(b'\n');
|
||||||
|
msg.extend_from_slice(address.as_bytes());
|
||||||
|
msg.push(b'\n');
|
||||||
|
msg.extend_from_slice(memo.as_bytes());
|
||||||
|
msg.push(b'\n');
|
||||||
|
msg.extend_from_slice(ts.to_string().as_bytes());
|
||||||
|
Invoice {
|
||||||
|
amount_atomic: amount.into(),
|
||||||
|
address: address.into(),
|
||||||
|
memo: memo.into(),
|
||||||
|
ts,
|
||||||
|
sig: sk.sign(&msg).to_bytes().to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn untagged_rcp(sk: &SigningKey, txid: &str, amount: &str, address: &str, ts: i64) -> Receipt {
|
||||||
|
let mut msg = Vec::from(txid.as_bytes());
|
||||||
|
msg.push(b'\n');
|
||||||
|
msg.extend_from_slice(amount.as_bytes());
|
||||||
|
msg.push(b'\n');
|
||||||
|
msg.extend_from_slice(address.as_bytes());
|
||||||
|
msg.push(b'\n');
|
||||||
|
msg.extend_from_slice(ts.to_string().as_bytes());
|
||||||
|
Receipt {
|
||||||
|
txid: txid.into(),
|
||||||
|
amount_atomic: amount.into(),
|
||||||
|
address: address.into(),
|
||||||
|
ts,
|
||||||
|
sig: sk.sign(&msg).to_bytes().to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn untagged_tip(
|
||||||
|
sk: &SigningKey,
|
||||||
|
txid: &str,
|
||||||
|
amount: &str,
|
||||||
|
address: &str,
|
||||||
|
memo: &str,
|
||||||
|
ts: i64,
|
||||||
|
) -> onionwire::pay::Tip {
|
||||||
|
let mut msg = Vec::from(txid.as_bytes());
|
||||||
|
for f in [amount, address, memo] {
|
||||||
|
msg.push(b'\n');
|
||||||
|
msg.extend_from_slice(f.as_bytes());
|
||||||
|
}
|
||||||
|
msg.push(b'\n');
|
||||||
|
msg.extend_from_slice(ts.to_string().as_bytes());
|
||||||
|
onionwire::pay::Tip {
|
||||||
|
txid: txid.into(),
|
||||||
|
amount_atomic: amount.into(),
|
||||||
|
address: address.into(),
|
||||||
|
memo: memo.into(),
|
||||||
|
ts,
|
||||||
|
sig: sk.sign(&msg).to_bytes().to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_untagged_tip_still_verifies() {
|
||||||
|
let (sk, pk) = keypair();
|
||||||
|
let tip = untagged_tip(&sk, "abc123", "1", MAINNET_STD, "coffee", 42);
|
||||||
|
assert!(
|
||||||
|
pay::verify_tip(&pk, &tip),
|
||||||
|
"legacy tip LF layout must still verify while LEGACY_SIGS is on"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_off_rejects_untagged_loc() {
|
||||||
|
let (sk, pk) = keypair();
|
||||||
|
let legacy = untagged_loc(&sk, "abc.onion", 42);
|
||||||
|
let tagged = loc::sign(&sk.to_bytes(), "abc.onion", 42).unwrap();
|
||||||
|
pay::with_legacy_sigs(false, || {
|
||||||
|
assert!(
|
||||||
|
!loc::verify(&pk, &legacy),
|
||||||
|
"untagged loc must be rejected with legacy off"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
loc::verify(&pk, &tagged),
|
||||||
|
"tagged loc must still verify with legacy off"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
loc::verify(&pk, &legacy),
|
||||||
|
"the switch restores acceptance after the scoped override"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_off_rejects_untagged_inv() {
|
||||||
|
let (sk, pk) = keypair();
|
||||||
|
let legacy = untagged_inv(&sk, "1", MAINNET_STD, "coffee", 42);
|
||||||
|
let tagged = pay::sign_invoice(&sk.to_bytes(), "1", MAINNET_STD, "coffee", 42).unwrap();
|
||||||
|
pay::with_legacy_sigs(false, || {
|
||||||
|
assert!(
|
||||||
|
!pay::verify_invoice(&pk, &legacy),
|
||||||
|
"untagged inv must be rejected with legacy off"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
pay::verify_invoice(&pk, &tagged),
|
||||||
|
"tagged inv must still verify with legacy off"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
assert!(pay::verify_invoice(&pk, &legacy));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_off_rejects_untagged_rcp() {
|
||||||
|
let (sk, pk) = keypair();
|
||||||
|
let legacy = untagged_rcp(&sk, "deadbeef", "1", MAINNET_STD, 99);
|
||||||
|
let tagged = pay::sign_receipt(&sk.to_bytes(), "deadbeef", "1", MAINNET_STD, 99).unwrap();
|
||||||
|
pay::with_legacy_sigs(false, || {
|
||||||
|
assert!(
|
||||||
|
!pay::verify_receipt(&pk, &legacy),
|
||||||
|
"untagged rcp must be rejected with legacy off"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
pay::verify_receipt(&pk, &tagged),
|
||||||
|
"tagged rcp must still verify with legacy off"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
assert!(pay::verify_receipt(&pk, &legacy));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_off_rejects_untagged_tip() {
|
||||||
|
let (sk, pk) = keypair();
|
||||||
|
let legacy = untagged_tip(&sk, "abc123", "1", MAINNET_STD, "coffee", 42);
|
||||||
|
let tagged = pay::sign_tip(&sk.to_bytes(), "abc123", "1", MAINNET_STD, "coffee", 42).unwrap();
|
||||||
|
pay::with_legacy_sigs(false, || {
|
||||||
|
assert!(
|
||||||
|
!pay::verify_tip(&pk, &legacy),
|
||||||
|
"untagged tip must be rejected with legacy off"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
pay::verify_tip(&pk, &tagged),
|
||||||
|
"tagged tip must still verify with legacy off"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
assert!(pay::verify_tip(&pk, &legacy));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `sign_tip` emits the tagged form only: its signature must not verify over
|
||||||
|
/// the untagged LF layout.
|
||||||
|
#[test]
|
||||||
|
fn tip_emits_tagged_form_only() {
|
||||||
|
use ed25519_dalek::{Signature, Verifier};
|
||||||
|
let (sk, pk) = keypair();
|
||||||
|
let tip = pay::sign_tip(&sk.to_bytes(), "abc123", "1", MAINNET_STD, "coffee", 42).unwrap();
|
||||||
|
assert!(pay::verify_tip(&pk, &tip));
|
||||||
|
let sig: [u8; 64] = tip.sig.as_slice().try_into().expect("64-byte sig");
|
||||||
|
let mut msg = Vec::from(b"abc123".as_slice());
|
||||||
|
for f in ["1", MAINNET_STD, "coffee"] {
|
||||||
|
msg.push(b'\n');
|
||||||
|
msg.extend_from_slice(f.as_bytes());
|
||||||
|
}
|
||||||
|
msg.push(b'\n');
|
||||||
|
msg.extend_from_slice(b"42");
|
||||||
|
assert!(
|
||||||
|
sk.verifying_key()
|
||||||
|
.verify(&msg, &Signature::from_bytes(&sig))
|
||||||
|
.is_err(),
|
||||||
|
"sign_tip must not sign the untagged layout"
|
||||||
|
);
|
||||||
|
// And the tagged signature covers the memo: changing it fails.
|
||||||
|
let mut tampered = tip.clone();
|
||||||
|
tampered.memo = String::new();
|
||||||
|
assert!(!pay::verify_tip(&pk, &tampered));
|
||||||
|
}
|
||||||
|
|
|
||||||
22
tests/qr.rs
22
tests/qr.rs
|
|
@ -312,3 +312,25 @@ fn huge_hex_is_err_quickly() {
|
||||||
"decode must fail closed before a multi-MB alloc"
|
"decode must fail closed before a multi-MB alloc"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_off_rejects_v1_invite_but_v2_still_decodes() {
|
||||||
|
let _home = TempHome::new();
|
||||||
|
let store = Store::open().expect("open");
|
||||||
|
let me = store.self_identity().expect("self");
|
||||||
|
let sk: [u8; 32] = me.identity_sk.as_slice().try_into().expect("32-byte sk");
|
||||||
|
let onion = v3onion("switch");
|
||||||
|
let raw_v1 = legacy_v1(&sk, &onion, &[8u8; 32]);
|
||||||
|
let raw_v2 = qr::encode(&me.identity_sk, &onion, &[8u8; 32], &me.kem_pk).expect("encode v2");
|
||||||
|
|
||||||
|
onionwire::pay::with_legacy_sigs(false, || {
|
||||||
|
assert!(
|
||||||
|
qr::decode(&raw_v1).is_err(),
|
||||||
|
"a v1 invite must be rejected with legacy off"
|
||||||
|
);
|
||||||
|
let p = qr::decode(&raw_v2).expect("v2 invite still decodes with legacy off");
|
||||||
|
assert!(p.kem_pk.is_some(), "v2 invite keeps its PQ key");
|
||||||
|
});
|
||||||
|
// Legacy acceptance returns with the default switch state.
|
||||||
|
assert!(qr::decode(&raw_v1).is_ok());
|
||||||
|
}
|
||||||
|
|
|
||||||
271
tests/wallet.rs
271
tests/wallet.rs
|
|
@ -101,6 +101,33 @@ fn password_absent_from_url_errors() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A 401 on the authenticated retry means the login is wrong. That copy is
|
||||||
|
/// rendered in the TUI/Android status line, so it must not echo either half of
|
||||||
|
/// the credential — not the password, not `user:pass`, not a URL with userinfo.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn ping_401_error_carries_no_credential() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
// Answer the authenticated retry with another 401: the digest was built
|
||||||
|
// from this connection's own challenge, so this is a wrong login.
|
||||||
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> =
|
||||||
|
Arc::new(|_| digest_401("refused-again"));
|
||||||
|
tokio::spawn(serve_rpc_conns_with(listener, reply, None, None, true));
|
||||||
|
|
||||||
|
let pass = "s3cretPASS";
|
||||||
|
let login = format!("ow:{pass}");
|
||||||
|
let res = Wallet::ping(&format!("http://127.0.0.1:{}", addr.port()), login.as_str()).await;
|
||||||
|
assert!(!res.ok, "a refused digest must not report connected");
|
||||||
|
let err = res.error.expect("failure carries a reason");
|
||||||
|
println!("401 ping error: {err}");
|
||||||
|
assert!(!err.contains(pass), "password leaked in error: {err}");
|
||||||
|
assert!(!err.contains(&login), "login leaked in error: {err}");
|
||||||
|
assert!(
|
||||||
|
!err.contains(&format!("://{login}@")),
|
||||||
|
"URL userinfo leaked in error: {err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn mock_get_address_parses_string() {
|
async fn mock_get_address_parses_string() {
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
|
@ -123,12 +150,14 @@ async fn mock_create_address_and_transfer() {
|
||||||
listener,
|
listener,
|
||||||
Arc::new(Mutex::new(Vec::new())),
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
Arc::new(move |method| match method {
|
Arc::new(move |method| match method {
|
||||||
// A spend is only attempted on a synced wallet.
|
// A spend is only attempted on a synced wallet: the wallet's own
|
||||||
"get_info" => synced_info(),
|
// scanned height plus the daemon tip.
|
||||||
|
"get_height" => wallet_height(3210000),
|
||||||
_ => rpc_result(&format!(r#"{{"address":"{addr_hex}","tx_hash":"abc123"}}"#)),
|
_ => rpc_result(&format!(r#"{{"address":"{addr_hex}","tx_hash":"abc123"}}"#)),
|
||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
let w = recording_wallet(port);
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||||||
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||||
let created = w.create_address().await.expect("create_address");
|
let created = w.create_address().await.expect("create_address");
|
||||||
assert!(created.starts_with('8'));
|
assert!(created.starts_with('8'));
|
||||||
|
|
||||||
|
|
@ -414,10 +443,59 @@ fn rpc_result(result: &str) -> String {
|
||||||
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
|
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a fully synced wallet answers to `get_info`: the daemon has reached the
|
/// What the wallet RPC answers to `get_height`: the wallet's own scanned height.
|
||||||
/// tip and the wallet has scanned it. This is the honest readiness signal.
|
/// This is the honest wallet-side signal — `get_info` does not exist there.
|
||||||
fn synced_info() -> String {
|
fn wallet_height(height: u64) -> String {
|
||||||
rpc_result(r#"{"height":3210000,"target_height":3210000,"synchronized":true}"#)
|
rpc_result(&format!(r#"{{"height":{height}}}"#))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A chain-daemon stub. `GET /get_height` answers the tip; `/json_rpc get_info`
|
||||||
|
/// answers height and target. A daemon is unauthenticated, so no Digest flow.
|
||||||
|
async fn serve_daemon(
|
||||||
|
listener: TcpListener,
|
||||||
|
height: u64,
|
||||||
|
target: u64,
|
||||||
|
log: Option<Arc<Mutex<Vec<String>>>>,
|
||||||
|
) {
|
||||||
|
while let Ok((mut sock, _)) = listener.accept().await {
|
||||||
|
let mut buf = vec![0u8; 8192];
|
||||||
|
let Ok(n) = sock.read(&mut buf).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if n == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let req = String::from_utf8_lossy(&buf[..n]).to_string();
|
||||||
|
if let Some(log) = &log {
|
||||||
|
log.lock().expect("daemon log").push(req.clone());
|
||||||
|
}
|
||||||
|
let body = if req.starts_with("GET /get_height") {
|
||||||
|
format!(r#"{{"height":{height}}}"#)
|
||||||
|
} else if req.contains("get_info") {
|
||||||
|
format!(
|
||||||
|
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target}}}}}"#
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
"{}".to_string()
|
||||||
|
};
|
||||||
|
let _ = sock
|
||||||
|
.write_all(
|
||||||
|
format!(
|
||||||
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
)
|
||||||
|
.as_bytes(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start a daemon stub on an ephemeral loopback port; returns `host:port`.
|
||||||
|
async fn mock_daemon(height: u64, target: u64) -> String {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap().to_string();
|
||||||
|
tokio::spawn(serve_daemon(listener, height, target, None));
|
||||||
|
addr
|
||||||
}
|
}
|
||||||
|
|
||||||
fn recording_wallet(port: u16) -> Wallet {
|
fn recording_wallet(port: u16) -> Wallet {
|
||||||
|
|
@ -505,11 +583,12 @@ async fn view_only_wallet_maps_transfer_failure_to_clear_message() {
|
||||||
Arc::clone(&log),
|
Arc::clone(&log),
|
||||||
Arc::new(|method| match method {
|
Arc::new(|method| match method {
|
||||||
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
|
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
|
||||||
"get_info" => synced_info(),
|
"get_height" => wallet_height(3210000),
|
||||||
_ => rpc_error(-18, "No transaction created"),
|
_ => rpc_error(-18, "No transaction created"),
|
||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
let w = recording_wallet(port);
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||||||
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||||
assert!(!w.no_spend());
|
assert!(!w.no_spend());
|
||||||
let err = w
|
let err = w
|
||||||
.transfer(
|
.transfer(
|
||||||
|
|
@ -537,11 +616,13 @@ async fn spend_capable_wallet_keeps_the_original_transfer_error() {
|
||||||
Arc::new(Mutex::new(Vec::new())),
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
Arc::new(|method| match method {
|
Arc::new(|method| match method {
|
||||||
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
|
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
|
||||||
"get_info" => synced_info(),
|
"get_height" => wallet_height(3210000),
|
||||||
_ => rpc_error(-18, "No transaction created"),
|
_ => rpc_error(-18, "No transaction created"),
|
||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||||||
let err = recording_wallet(port)
|
let err = recording_wallet(port)
|
||||||
|
.with_daemon_probe(Some(daemon))
|
||||||
.transfer(
|
.transfer(
|
||||||
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||||
1,
|
1,
|
||||||
|
|
@ -1190,7 +1271,8 @@ async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) {
|
||||||
serve_rpc_conns(
|
serve_rpc_conns(
|
||||||
listener,
|
listener,
|
||||||
Arc::new(|method: &str| match method {
|
Arc::new(|method: &str| match method {
|
||||||
"get_info" => synced_info(),
|
"get_height" => wallet_height(3210000),
|
||||||
|
"get_transfers" => rpc_result(r#"{"in":[],"pending":[]}"#),
|
||||||
_ => rpc_result(
|
_ => rpc_result(
|
||||||
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
|
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
|
||||||
),
|
),
|
||||||
|
|
@ -1215,15 +1297,14 @@ async fn unsynced_wallet_is_not_ready_and_refuses_to_spend() {
|
||||||
listener,
|
listener,
|
||||||
Arc::clone(&log),
|
Arc::clone(&log),
|
||||||
Arc::new(|method| match method {
|
Arc::new(|method| match method {
|
||||||
"get_info" => {
|
"get_height" => wallet_height(1200000),
|
||||||
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
|
|
||||||
}
|
|
||||||
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
let w = recording_wallet(port);
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||||||
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||||
assert!(
|
assert!(
|
||||||
!w.chain_ready().await.expect("get_info"),
|
!w.chain_ready().await.expect("get_height"),
|
||||||
"must not be ready"
|
"must not be ready"
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
|
|
@ -1240,16 +1321,115 @@ async fn unsynced_wallet_is_not_ready_and_refuses_to_spend() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A missing/absent `synchronized` (or a wallet behind the daemon) is not-ready,
|
/// `monero-wallet-rpc` has no `get_info` (it answers `-32601 Method not found`).
|
||||||
/// never a silent pass. Fail closed.
|
/// Readiness must never depend on that call: the wallet's own `get_height` is
|
||||||
|
/// compared with the daemon's tip.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn missing_or_behind_synchronized_is_not_ready() {
|
async fn readiness_never_asks_the_wallet_rpc_for_get_info() {
|
||||||
for info in [
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
r#"{"height":10}"#,
|
let port = listener.local_addr().unwrap().port();
|
||||||
r#"{"height":100,"target_height":200,"synchronized":true}"#,
|
let log = Arc::new(Mutex::new(Vec::new()));
|
||||||
r#"{"height":0,"target_height":0,"synchronized":true}"#,
|
tokio::spawn(serve_recording(
|
||||||
r#"{"synchronized":"true"}"#,
|
listener,
|
||||||
|
Arc::clone(&log),
|
||||||
|
Arc::new(|method| match method {
|
||||||
|
"get_height" => wallet_height(3210000),
|
||||||
|
"get_info" => rpc_error(-32601, "Method not found"),
|
||||||
|
_ => rpc_result("{}"),
|
||||||
|
}),
|
||||||
|
));
|
||||||
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||||||
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||||
|
assert!(
|
||||||
|
w.chain_ready().await.expect("get_height"),
|
||||||
|
"a wallet at the daemon tip is ready without get_info"
|
||||||
|
);
|
||||||
|
let seen = log.lock().expect("log").clone();
|
||||||
|
assert!(
|
||||||
|
seen.iter().any(|r| r.contains("\"method\":\"get_height\"")),
|
||||||
|
"the wallet's own scanned height must be asked: {seen:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!seen.iter().any(|r| r.contains("\"method\":\"get_info\"")),
|
||||||
|
"get_info is not a wallet-RPC method and must not be probed: {seen:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Readiness against a daemon tip: equal is ready, the tip moves every ~2 min so
|
||||||
|
/// a two-block gap is ready, a real lag is not.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_wallet_within_the_slack_of_the_daemon_tip_is_ready() {
|
||||||
|
for (wallet, tip, ready) in [
|
||||||
|
(3210000u64, 3210000u64, true),
|
||||||
|
(3209998, 3210000, true),
|
||||||
|
(3209997, 3210000, false),
|
||||||
] {
|
] {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
tokio::spawn(serve_recording(
|
||||||
|
listener,
|
||||||
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
|
Arc::new(move |_| wallet_height(wallet)),
|
||||||
|
));
|
||||||
|
let daemon = mock_daemon(tip, tip).await;
|
||||||
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||||
|
assert_eq!(
|
||||||
|
w.chain_ready().await.expect("get_height"),
|
||||||
|
ready,
|
||||||
|
"wallet {wallet} / tip {tip}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A daemon that does not answer leaves the tip unknown. Unknown is *not*
|
||||||
|
/// caught up — fail closed, never a silent pass.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_unreachable_daemon_is_not_ready() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
tokio::spawn(serve_recording(
|
||||||
|
listener,
|
||||||
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
|
Arc::new(|_| wallet_height(3210000)),
|
||||||
|
));
|
||||||
|
// Bind, read the port, drop: nothing is listening there.
|
||||||
|
let dead = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let dead_addr = dead.local_addr().unwrap().to_string();
|
||||||
|
drop(dead);
|
||||||
|
let w = recording_wallet(port).with_daemon_probe(Some(dead_addr));
|
||||||
|
assert!(
|
||||||
|
!w.chain_ready().await.expect("get_height"),
|
||||||
|
"an unanswered daemon must not read as ready"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A wallet RPC with no wallet file open answers `-13 No wallet file` to
|
||||||
|
/// `get_height`. That is a state, not an error banner: not ready, no Err.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_rpc_with_no_wallet_open_is_not_ready_and_not_an_error() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
tokio::spawn(serve_recording(
|
||||||
|
listener,
|
||||||
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
|
Arc::new(|_| rpc_error(-13, "No wallet file")),
|
||||||
|
));
|
||||||
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||||||
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||||
|
assert!(
|
||||||
|
!w.chain_ready()
|
||||||
|
.await
|
||||||
|
.expect("no wallet file is a state, not an error"),
|
||||||
|
"a wallet with no file open is not ready"
|
||||||
|
);
|
||||||
|
assert!(!w.can_verify_receipts().await);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An answered `get_height` with no height (or height 0) is unknown, and a
|
||||||
|
/// daemon tip of 0 is a daemon that has not indexed anything: not ready.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_missing_or_zero_wallet_height_is_not_ready() {
|
||||||
|
for info in [r#"{}"#, r#"{"height":0}"#, r#"{"height":"10"}"#] {
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
let port = listener.local_addr().unwrap().port();
|
let port = listener.local_addr().unwrap().port();
|
||||||
let canned = rpc_result(info);
|
let canned = rpc_result(info);
|
||||||
|
|
@ -1258,9 +1438,10 @@ async fn missing_or_behind_synchronized_is_not_ready() {
|
||||||
Arc::new(Mutex::new(Vec::new())),
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
Arc::new(move |_| canned.clone()),
|
Arc::new(move |_| canned.clone()),
|
||||||
));
|
));
|
||||||
let w = recording_wallet(port);
|
let daemon = mock_daemon(0, 0).await;
|
||||||
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||||
assert!(
|
assert!(
|
||||||
!w.chain_ready().await.expect("get_info"),
|
!w.chain_ready().await.expect("get_height"),
|
||||||
"{info} must not read as ready"
|
"{info} must not read as ready"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -1274,12 +1455,13 @@ async fn synced_wallet_is_ready_and_spends() {
|
||||||
listener,
|
listener,
|
||||||
Arc::new(Mutex::new(Vec::new())),
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
Arc::new(|method| match method {
|
Arc::new(|method| match method {
|
||||||
"get_info" => synced_info(),
|
"get_height" => wallet_height(3210000),
|
||||||
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
let w = recording_wallet(port);
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||||||
assert!(w.chain_ready().await.expect("get_info"));
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||||
|
assert!(w.chain_ready().await.expect("get_height"));
|
||||||
assert!(w.can_verify_receipts().await);
|
assert!(w.can_verify_receipts().await);
|
||||||
assert_eq!(w.transfer(SPEND_ADDR, 1).await.expect("transfer"), "abc123");
|
assert_eq!(w.transfer(SPEND_ADDR, 1).await.expect("transfer"), "abc123");
|
||||||
}
|
}
|
||||||
|
|
@ -1298,12 +1480,13 @@ async fn spend_ready_needs_an_unlocked_balance() {
|
||||||
listener,
|
listener,
|
||||||
Arc::new(Mutex::new(Vec::new())),
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
Arc::new(move |method| match method {
|
Arc::new(move |method| match method {
|
||||||
"get_info" => synced_info(),
|
"get_height" => wallet_height(3210000),
|
||||||
"get_balance" => balance.clone(),
|
"get_balance" => balance.clone(),
|
||||||
_ => rpc_result(r#"{}"#),
|
_ => rpc_result("{}"),
|
||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
let w = recording_wallet(port);
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||||||
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||||
assert_eq!(w.spend_ready().await.expect("spend_ready"), ready);
|
assert_eq!(w.spend_ready().await.expect("spend_ready"), ready);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1342,16 +1525,15 @@ async fn unsynced_wallet_leaves_a_matching_receipt_unverified() {
|
||||||
listener,
|
listener,
|
||||||
Arc::new(Mutex::new(Vec::new())),
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
Arc::new(move |method| match method {
|
Arc::new(move |method| match method {
|
||||||
"get_info" => {
|
"get_height" => wallet_height(1200000),
|
||||||
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
|
|
||||||
}
|
|
||||||
"get_transfers" => rpc_result(&format!(
|
"get_transfers" => rpc_result(&format!(
|
||||||
r#"{{"in":[{{"txid":"deadbeef","amount":5,"address":"{addr_owned}"}}],"pending":[]}}"#
|
r#"{{"in":[{{"txid":"deadbeef","amount":5,"address":"{addr_owned}"}}],"pending":[]}}"#
|
||||||
)),
|
)),
|
||||||
_ => rpc_result(r#"{}"#),
|
_ => rpc_result("{}"),
|
||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
let w = recording_wallet(port);
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||||||
|
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||||
|
|
||||||
// The same shape node.rs::ingest_receipt runs.
|
// The same shape node.rs::ingest_receipt runs.
|
||||||
if w.can_verify_receipts().await
|
if w.can_verify_receipts().await
|
||||||
|
|
@ -1366,8 +1548,10 @@ async fn unsynced_wallet_leaves_a_matching_receipt_unverified() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Chain-dependent calls get a longer budget than local wallet-management calls,
|
/// Chain-dependent calls (`get_transfers`, `transfer`) get a longer budget than
|
||||||
/// and the budget is the backend's to set — not a hard-coded 5s.
|
/// local wallet-management calls, and the budget is the backend's to set — not a
|
||||||
|
/// hard-coded 5s. Readiness is no longer a chain wait: it is one local
|
||||||
|
/// `get_height` plus one bounded daemon probe.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn chain_calls_get_a_longer_budget_than_local_calls() {
|
async fn chain_calls_get_a_longer_budget_than_local_calls() {
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
|
@ -1385,12 +1569,11 @@ async fn chain_calls_get_a_longer_budget_than_local_calls() {
|
||||||
err.to_ascii_lowercase().contains("timed out"),
|
err.to_ascii_lowercase().contains("timed out"),
|
||||||
"the local call must hit the short budget: {err}"
|
"the local call must hit the short budget: {err}"
|
||||||
);
|
);
|
||||||
assert!(
|
let rows = w
|
||||||
w.chain_ready()
|
.get_transfers()
|
||||||
.await
|
.await
|
||||||
.expect("get_info within the chain budget"),
|
.expect("get_transfers within the chain budget");
|
||||||
"chain calls must outlast daemon latency"
|
assert!(rows.is_empty(), "{rows:?}");
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue