diff --git a/.forgejo/workflows/android-ci.yml b/.forgejo/workflows/android-ci.yml new file mode 100644 index 0000000..9417544 --- /dev/null +++ b/.forgejo/workflows/android-ci.yml @@ -0,0 +1,236 @@ +name: android-ci + +# Android changes had no CI at all: ci.yml's path allowlist (src/**, crates/**, +# tests/**, Cargo.toml, Cargo.lock, ci.yml) never matches android/**, and +# android-release.yml is dispatch/tag-driven — so an android-only PR ran zero +# jobs and merged on an empty check list. This is the android side of CI. +# +# It builds the same gradle targets the release builds through the same script +# android-release.yml calls (scripts/build-android-local.sh): `:sdk:assembleRelease` +# + `:app:assembleRelease`, Rust for aarch64-linux-android via cargo-ndk, UniFFI +# bindings, APK packaging with the .so. The only difference from a release is +# signing: ONIONWIRE_REQUIRE_RELEASE_KEY=false and no release keystore, so +# Gradle falls back to the debug key. Nothing here is signed for release, +# nothing is published, no tag is touched. +# +# Why a separate workflow instead of android/** added to ci.yml: the only way +# to keep the Rust jobs from running on android-only diffs is job-level change +# detection, and a gate that mis-detects hands out a green check for a suite +# that never ran. Here the runner's own paths filter decides — same mechanism +# ci.yml already uses. +on: + push: + branches: [main] + paths: + - "android/**" + - "crates/**" + - "src/**" + - "Cargo.toml" + - "Cargo.lock" + - "scripts/build-android-local.sh" + - ".forgejo/workflows/android-ci.yml" + pull_request: + paths: + - "android/**" + - "crates/**" + - "src/**" + - "Cargo.toml" + - "Cargo.lock" + - "scripts/build-android-local.sh" + - ".forgejo/workflows/android-ci.yml" + workflow_dispatch: + +# Deliberately the SAME group and the SAME volumes as android-release.yml: the +# APK build is ~9 min with warm volumes (SDK/NDK, cargo registry, cargo target, +# Gradle cache) and a cold copy of those is over a gigabyte of downloads per +# runner. Serializing the two workflows by group name is what keeps them off +# each other's volumes. +concurrency: + group: onionwire-android-release-v2 + cancel-in-progress: false + +env: + CARGO_TERM_COLOR: never + CARGO_BUILD_JOBS: "1" + ONIONWIRE_ANDROID_ABI: arm64-v8a + ANDROID_IMAGE: debian:bookworm + ANDROID_CMDLINE_TOOLS_URL: https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip + RUST_TOOLCHAIN: "1.91" + DOCKER_STATIC_URL: https://download.docker.com/linux/static/stable/x86_64/docker-27.5.1.tgz + # Distinct container prefix: run ids are per-workflow, so this workflow and + # android-release.yml can both be holding a container named "-". + BUILD_CONTAINER: onionwire-android-ci-${{ github.run_id }} + SDK_VOLUME: onionwire-android-sdk + CARGO_VOLUME: onionwire-android-cargo-registry + TARGET_VOLUME: onionwire-android-target + GRADLE_VOLUME: onionwire-android-gradle + +jobs: + android: + runs-on: docker-amd64 + timeout-minutes: 120 + steps: + - name: Checkout + uses: https://code.forgejo.org/actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Record runner resources + run: | + set -euo pipefail + cd "${GITHUB_WORKSPACE}" + echo "workspace=$GITHUB_WORKSPACE hostname=$(hostname) arch=$(uname -m)" + nproc || true + free -h || true + df -h || true + ls -l /var/run/docker.sock || true + + - name: Ensure docker CLI + run: | + set -euo pipefail + if ! command -v docker >/dev/null 2>&1; then + echo "docker CLI missing in job image; fetching static client" + curl -fsSL "$DOCKER_STATIC_URL" -o /tmp/docker.tgz + tar -xzf /tmp/docker.tgz -C /tmp + install -m 755 /tmp/docker/docker /usr/local/bin/docker + fi + export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}" + docker version + docker info >/tmp/docker-info.txt + grep -E 'Server Version|Operating System|Total Memory|Name' /tmp/docker-info.txt || true + + - name: Build APK + AAR (debug-signed) in bookworm container + id: build + run: | + set -euo pipefail + cd "${GITHUB_WORKSPACE}" + export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}" + start=$(date +%s) + cat > .ci-android-verify.sh <<'INNER' + #!/usr/bin/env bash + set -euo pipefail + export DEBIAN_FRONTEND=noninteractive + apt-get update + apt-get install -y --no-install-recommends \ + openjdk-17-jdk-headless python3 unzip curl ca-certificates file build-essential pkg-config git + if [ ! -x /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager ]; then + mkdir -p /opt/android-sdk/cmdline-tools + curl -fsSL "$ANDROID_CMDLINE_TOOLS_URL" -o /tmp/cmdline-tools.zip + rm -rf /tmp/cmdline-tools + unzip -q /tmp/cmdline-tools.zip -d /tmp/cmdline-tools + mkdir -p /opt/android-sdk/cmdline-tools/latest + cp -a /tmp/cmdline-tools/cmdline-tools/. /opt/android-sdk/cmdline-tools/latest/ + fi + yes | /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root=/opt/android-sdk --licenses >/tmp/sdk-licenses.log || true + /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root=/opt/android-sdk \ + "platform-tools" "platforms;android-36" "build-tools;36.0.0" "ndk;28.2.13676358" + test -d /opt/android-sdk/ndk/28.2.13676358 + export ANDROID_HOME=/opt/android-sdk ANDROID_SDK_ROOT=/opt/android-sdk + export ANDROID_NDK_HOME=/opt/android-sdk/ndk/28.2.13676358 + export PATH="$ANDROID_HOME/build-tools/36.0.0:$ANDROID_HOME/platform-tools:$PATH" + if [ ! -x /cargo/bin/rustup ]; then + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain "$RUST_TOOLCHAIN" --no-modify-path --profile minimal + fi + export PATH="/cargo/bin:$PATH" + rustup toolchain install "$RUST_TOOLCHAIN" + rustup default "$RUST_TOOLCHAIN" + rustup target add aarch64-linux-android + command -v cargo-ndk >/dev/null || cargo install cargo-ndk --locked + echo "=== toolchain ===" + java -version + rustc --version + cargo ndk --version + du -sh /opt/android-sdk /cargo /cargo-target /gradle || true + # No keystore here on purpose: this is a verification build, not a + # release build. The script warns that Gradle fell back to the debug + # key; that warning is expected in this job. + scripts/build-android-local.sh + version="$(python3 - <<'PY' + import re, pathlib + t = pathlib.Path('android/app/build.gradle.kts').read_text() + m = re.search(r'versionName\s*=.*?:\s*"([^"]+)"', t) + print(m.group(1) if m else '') + PY + )" + abi="${ONIONWIRE_ANDROID_ABI:-arm64-v8a}" + apk="dist/onionwire-$version-android-$abi.apk" + aar="dist/onionwire-sdk-$version.aar" + { + echo "=== file ===" + file "$apk" "$aar" + echo "=== unzip lib ===" + unzip -l "$apk" | grep -E 'lib/.+\.so' || true + unzip -l "$apk" | grep "lib/$abi/libonionwire_sdk.so" + echo "=== classes.dex + Compose entrypoints ===" + unzip -l "$apk" | grep -E 'classes[0-9]*\.dex' | head -n3 + echo "=== sha256 ===" + ( cd dist && sha256sum -c "onionwire-$version-android-$abi.apk.sha256" "onionwire-sdk-$version.aar.sha256" ) + echo "=== apksigner (expect debug cert: this is a verification build) ===" + apksigner verify --print-certs "$apk" | sed -n '1,6p' + echo "=== aapt ===" + aapt dump badging "$apk" | sed -n '1,20p' || true + echo "=== sizes ===" + wc -c "$apk" "$aar" + } | tee dist/android-ci-verify.log + INNER + chmod +x .ci-android-verify.sh + docker volume create "$SDK_VOLUME" >/dev/null + docker volume create "$CARGO_VOLUME" >/dev/null + docker volume create "$TARGET_VOLUME" >/dev/null + docker volume create "$GRADLE_VOLUME" >/dev/null + docker rm -f "$BUILD_CONTAINER" >/dev/null 2>&1 || true + docker pull "$ANDROID_IMAGE" + docker create --name "$BUILD_CONTAINER" -i \ + -e CARGO_TERM_COLOR=never \ + -e CARGO_BUILD_JOBS="$CARGO_BUILD_JOBS" \ + -e CARGO_HOME=/cargo \ + -e CARGO_TARGET_DIR=/cargo-target \ + -e GRADLE_USER_HOME=/gradle \ + -e ANDROID_HOME=/opt/android-sdk \ + -e ANDROID_SDK_ROOT=/opt/android-sdk \ + -e ANDROID_NDK_HOME=/opt/android-sdk/ndk/28.2.13676358 \ + -e ONIONWIRE_ANDROID_ABI="$ONIONWIRE_ANDROID_ABI" \ + -e ONIONWIRE_REQUIRE_RELEASE_KEY=false \ + -e RUST_TOOLCHAIN="$RUST_TOOLCHAIN" \ + -e ANDROID_CMDLINE_TOOLS_URL="$ANDROID_CMDLINE_TOOLS_URL" \ + -e GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.jvmargs=-Xmx1024m -XX:MaxMetaspaceSize=384m -Dfile.encoding=UTF-8" \ + -v "$SDK_VOLUME":/opt/android-sdk \ + -v "$CARGO_VOLUME":/cargo \ + -v "$TARGET_VOLUME":/cargo-target \ + -v "$GRADLE_VOLUME":/gradle \ + -w /src \ + "$ANDROID_IMAGE" \ + bash -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src && bash /src/.ci-android-verify.sh' + tar czf - \ + --exclude=./target --exclude=./.git --exclude=./.worktrees \ + --exclude=./android/.gradle --exclude=./android/app/build \ + --exclude=./android/sdk/build --exclude=./dist \ + --exclude=./crates/onionwire-sdk/target \ + . \ + | docker start -a -i "$BUILD_CONTAINER" + mkdir -p dist + docker cp "$BUILD_CONTAINER:/src/dist/." dist/ + end=$(date +%s) + echo "build_wall_clock_seconds=$((end - start))" + echo "wall_clock_seconds=$((end - start))" >> "$GITHUB_OUTPUT" + docker rm -f "$BUILD_CONTAINER" >/dev/null || true + ls -l dist/ + + - name: Verify artifacts + run: | + set -euo pipefail + cd "${GITHUB_WORKSPACE}" + abi="$ONIONWIRE_ANDROID_ABI" + ls -l dist/ + apk="$(ls dist/onionwire-*-android-$abi.apk)" + aar="$(ls dist/onionwire-sdk-*.aar)" + [ -s "$apk" ] || { echo "missing or empty $apk" >&2; exit 1; } + [ -s "$aar" ] || { echo "missing or empty $aar" >&2; exit 1; } + echo "apk=$apk bytes=$(wc -c < "$apk")" + echo "aar=$aar bytes=$(wc -c < "$aar")" + ( cd dist && sha256sum -c ./*.sha256 ) + echo "=== android-ci-verify.log (from build container) ===" + cat dist/android-ci-verify.log + echo "=== resources after build ===" + free -h || true + df -h || true diff --git a/README.md b/README.md index 7b53161..098569c 100644 --- a/README.md +++ b/README.md @@ -370,6 +370,7 @@ FORGEJO_TOKEN= scripts/build-release-local.sh v0.2.1 Workflows (Forgejo Actions, `.forgejo/workflows/`): - [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — two jobs on the Pi runner (`docker` label), serialized by `onionwire-ci-pi`. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk` (separate cargo workspace — own `Cargo.lock`, root crate by path, `rustls` instead of `native-tls` — so a root signature change cannot silently break the Android SDK). Both run on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. +- [`.forgejo/workflows/android-ci.yml`](.forgejo/workflows/android-ci.yml) — the android side of CI, on the `docker-amd64` runner: builds `:sdk:assembleRelease` + `:app:assembleRelease` with the same script the release uses (`scripts/build-android-local.sh`, Rust for `aarch64-linux-android` via cargo-ndk + UniFFI bindings) and verifies the packaged `libonionwire_sdk.so`, checksums and APK badging. Debug keystore, no publish, no tag. Runs on `main` and PRs when `android/`, `src/`, `crates/`, `Cargo.toml`, `Cargo.lock` or `scripts/build-android-local.sh` change. Same concurrency group **and** the same runner volumes as `android-release.yml`, so a PR build never fights a release build over the SDK/NDK, cargo and Gradle caches. - [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — manual, batched release (`workflow_dispatch` only: `dry_run`, `bump`, `version`, `tag`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release, fail-closed tag delete on failure. Dispatch [`android-release.yml`](.forgejo/workflows/android-release.yml) with that tag to add the APK + AAR (no automatic trigger fires on this Forgejo; it is `workflow_dispatch` only). Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. - [`.forgejo/workflows/android-release.yml`](.forgejo/workflows/android-release.yml) — amd64-only Android build (dispatch-only on this Forgejo; wakes from an explicit `tag=` input, not a tag push). diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt index 6038c5c..1d14fa6 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt @@ -143,15 +143,13 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str val pk = entry.arguments?.getString("pk").orEmpty() val friend = friends.firstOrNull { it.pubkeyHex == pk } ChatScreen( + vm = vm, + peer = pk, title = friend?.petname?.takeIf { it.isNotBlank() } ?: friend?.fingerprint ?: pk.take(16), fingerprint = friend?.fingerprint ?: pk.take(16), onion = friend?.onion.orEmpty(), - loadMessages = { vm.messages(pk) }, - loadOutbox = { vm.outbox(pk) }, - loadMaxAttempts = { vm.outboxMaxAttempts() }, - onSend = { body -> vm.send(pk, body) }, onBack = { nav.popBackStack() }, ) } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index b25a0c0..f22fb12 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -12,9 +12,14 @@ import com.siriusdevops.onionwire.keepalive.KeepAliveService import com.siriusdevops.onionwire.keepalive.KeepAliveStatus import com.siriusdevops.onionwire.keepalive.NodeHost import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import uniffi.onionwire_sdk.ChatMessage @@ -61,6 +66,22 @@ sealed interface Unlock { data class OneTap(val backing: KeyBacking) : Unlock } +/** + * Everything one open chat screen renders, refreshed on a single cadence. + * + * [messages] is null until the first read lands — the screen shows its spinner + * on that, exactly as it did reading the SDK itself. [error] is the last load + * failure and is sticky on purpose: it survives the ticks that succeed, so a + * transient store error is still on screen after the next 2s tick rather than + * blinking away. A send clears it (the user has acted on it). + */ +data class ChatState( + val messages: List? = null, + val outbox: List = emptyList(), + val maxAttempts: UInt? = null, + val error: String? = null, +) + /** * Owns the UI side of the process's single node. * @@ -101,6 +122,22 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { private val _keepAliveNote = MutableStateFlow(null) val keepAliveNote: StateFlow = _keepAliveNote.asStateFlow() + /** + * The currently open chat, or null when no chat screen is composed. + * + * There is exactly one node and one chat on screen at a time, so this is + * one state object rather than a map keyed by peer: a second poller for a + * second peer would double the SDK traffic for a screen nobody is looking + * at, and the node's store reads are not free. + */ + private val _chat = MutableStateFlow(null) + val chat: StateFlow = _chat.asStateFlow() + + /** The peer [chat] belongs to; guards a stale tick from a previous peer. */ + private var chatPeer: String? = null + + private var chatPoller: Job? = null + init { // A node the foreground service kept alive is still open. Adopt it and // go straight to the roster: showing an unlock screen for a store that @@ -177,6 +214,10 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { */ fun lock() { if (NodeHost.current() == null) return + // Stop the chat tick before the node goes: the next read of a closed + // store would surface as a chat load error on a screen the user has + // already left, and every tick would keep re-reporting it. + stopChatPoller() KeepAliveService.stop(getApplication()) NodeHost.lock() _friends.value = emptyList() @@ -381,6 +422,87 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { */ suspend fun outboxMaxAttempts(): UInt = uniffi.onionwire_sdk.outboxMaxAttempts() + /** + * Starts the one 2s refresh loop for [pubkeyHex] and resets the chat state. + * + * Called from the chat screen entering the composition. Re-entering the + * same peer while its poller is alive is a no-op — navigating to the chat + * and back must never stack a second loop on top of the first. + */ + fun openChat(pubkeyHex: String) { + if (chatPeer == pubkeyHex && chatPoller?.isActive == true) return + chatPoller?.cancel() + chatPeer = pubkeyHex + _chat.value = ChatState() + chatPoller = viewModelScope.launch { pollChat(pubkeyHex) } + } + + /** + * Stops the loop when the chat screen leaves. Ignored when another peer has + * taken over in the meantime (navigating chat A → chat B disposes A after B + * has already opened). + */ + fun closeChat(pubkeyHex: String) { + if (chatPeer != pubkeyHex) return + stopChatPoller() + } + + private fun stopChatPoller() { + chatPoller?.cancel() + chatPoller = null + chatPeer = null + _chat.value = null + } + + /** + * Drops the last load error. The send path calls this: the user has acted, + * so a stale "could not read" line must not sit under the composer while + * the send is in flight. + */ + fun clearChatError() { + _chat.update { it?.copy(error = null) } + } + + /** + * The cadence, in the ViewModel: inbound messages are appended by the node + * in the background and the retry worker moves queued rows along, and in v1 + * there is no push channel into the UI, so messages and outbox are read + * together on one 2s tick. The outbox rows are read on that tick too — + * their `next_attempt_at` is a fixed instant, so a row saying "retry 45s" + * turns into "retry now" here without the store having to change. + * + * The retry budget is read once per open chat (it is a constant of the + * outbox, not per-peer state); a failure leaves it null and the rows fall + * back to the flat marker. + */ + private suspend fun pollChat(pk: String) { + runCatching { outboxMaxAttempts() }.onSuccess { budget -> + if (chatPeer == pk) _chat.update { it?.copy(maxAttempts = budget) } + } + while (currentCoroutineContext().isActive) { + val loaded = runCatching { messages(pk) } + val out = runCatching { outbox(pk) } + // A cancelled loop can still be sitting in a completed SDK read: + // writing that peer's rows into a state that now belongs to another + // peer would show the wrong conversation. + if (chatPeer != pk) return + _chat.update { state -> + val base = state ?: ChatState() + base.copy( + messages = loaded.getOrNull() ?: base.messages, + outbox = out.getOrNull() ?: base.outbox, + // Same order the screen's own loop reported them in, and + // sticky on success — a new failure replaces the last one, + // a successful tick does not clear the last one. + error = out.exceptionOrNull()?.let { it.message ?: it.toString() } + ?: loaded.exceptionOrNull()?.let { it.message ?: it.toString() } + ?: base.error, + ) + } + delay(2_000) + } + } + /** * Sends one chat message and reports what the core did with it. * @@ -428,4 +550,16 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun sendTip(pubkeyHex: String, amountXmr: String, memo: String = ""): Result = runCatching { requireWire().sendTip(pubkeyHex, amountXmr, memo) } + + suspend fun createWallet(password: String): Result = + runCatching { requireWire().createWallet(password) } + + suspend fun importWallet(password: String, seed: String): Result = + runCatching { requireWire().importWallet(password, seed) } + + fun spendAuthorityWarning(): String = runCatching { + requireWire().spendAuthorityWarning() + }.getOrElse { + "this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed." + } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt index b45038c..499b6f8 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt @@ -2,10 +2,12 @@ package com.siriusdevops.onionwire.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues 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 @@ -15,11 +17,16 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold @@ -27,6 +34,7 @@ import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -34,26 +42,28 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.unit.dp -import kotlinx.coroutines.delay -import uniffi.onionwire_sdk.ChatMessage -import uniffi.onionwire_sdk.OutboxRow +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.siriusdevops.onionwire.WireViewModel import uniffi.onionwire_sdk.SendState @OptIn(ExperimentalMaterial3Api::class) @Composable fun ChatScreen( + vm: WireViewModel, + /** The peer's ed25519 pubkey hex — the key the open chat's poller runs for. */ + peer: String, title: String, fingerprint: String, onion: String, - loadMessages: suspend () -> List, - loadOutbox: suspend () -> List, - loadMaxAttempts: suspend () -> UInt, - onSend: suspend (String) -> SendState, onBack: () -> Unit, /** * Wall clock in unix seconds. `next_attempt_at` is absolute, so the @@ -62,36 +72,55 @@ fun ChatScreen( */ nowSeconds: () -> Long = { System.currentTimeMillis() / 1_000L }, ) { - var messages by remember { mutableStateOf?>(null) } - var outbox by remember { mutableStateOf>(emptyList()) } - // The core's retry budget, fetched once: `try 3/8` renders against this and - // never against a constant in the app. - var maxAttempts by remember { mutableStateOf(null) } + // The refresh cadence lives in the ViewModel: one poller per open chat, not + // one per composition. Collecting here means a re-composition (or a + // configuration change) does not start a second loop against the SDK. + val chat by vm.chat.collectAsStateWithLifecycle() + val messages = chat?.messages + val outbox = chat?.outbox.orEmpty() + // The core's retry budget, fetched once per open chat: `try 3/8` renders + // against this and never against a constant in the app. + val maxAttempts = chat?.maxAttempts + var draft by remember { mutableStateOf("") } var pending by remember { mutableStateOf(null) } - var error by remember { mutableStateOf(null) } + // Send-path failures are the screen's own state; load failures come back on + // [ChatState.error]. Both render in the same place under the list. + var sendError by remember { mutableStateOf(null) } var notice by remember { mutableStateOf(null) } + val error = sendError ?: chat?.error val listState = rememberLazyListState() - // Poll: the node appends inbound messages in the background and the retry - // worker moves queued rows along; there is no push channel into the UI in - // v1, so the delivery markers refresh on the same cadence as the bodies. - // The outbox rows are read on that cadence too — their `next_attempt_at` is - // a fixed instant, so a row saying "retry 45s" turns into "retry now" here - // without the store having to change. - LaunchedEffect(Unit) { - runCatching { loadMaxAttempts() }.onSuccess { maxAttempts = it } - while (true) { - runCatching { loadMessages() } - .onSuccess { messages = it } - .onFailure { error = it.message ?: it.toString() } - runCatching { loadOutbox() } - .onSuccess { outbox = it } - .onFailure { error = it.message ?: it.toString() } - delay(2_000) + // Auto-scroll bookkeeping. `firstFillDone` keeps the one-jump-to-the-bottom + // on the first load (and again after leaving and re-entering the chat); + // `ownSendPending` is the user's own message asking for the list to follow + // even though they may have scrolled up in history. + var firstFillDone by remember { mutableStateOf(false) } + var ownSendPending by remember { mutableStateOf(false) } + + // The composer is the only place a message can be sent from, so after a + // send the keyboard is left up and the caret goes back into the field — + // the next message is one keystroke away instead of a re-tap. + val inputFocus = remember { FocusRequester() } + val send: () -> Unit = { + if (draft.isNotBlank() && pending == null) { + pending = draft + draft = "" + // The user's own message is the one case where the list is allowed + // to move while they are scrolled up in history. + ownSendPending = true + inputFocus.requestFocus() } } + // The poller's lifetime is the chat screen's: entering starts it, leaving + // stops it, and re-entering the same peer is a no-op in the ViewModel, so + // there is exactly one loop no matter how the nav stack is walked. + DisposableEffect(peer) { + vm.openChat(peer) + onDispose { vm.closeChat(peer) } + } + // Send. An unreachable peer's onion is not an error any more: the core // stores the message in its local outbox and the retry worker dials again // with backoff (30s doubling, capped at 30 min, 8 attempts, then terminal @@ -99,22 +128,45 @@ fun ChatScreen( // queued for those. LaunchedEffect(pending) { val body = pending ?: return@LaunchedEffect - error = null + sendError = null notice = null - runCatching { onSend(body) } + // The user has acted on whatever the poller last reported. + vm.clearChatError() + runCatching { vm.send(peer, body) } .onSuccess { if (it == SendState.QUEUED) { notice = "Queued: their onion is unreachable. The message stays on " + "this device and is retried until it lands." } } - .onFailure { error = it.message ?: it.toString() } + .onFailure { sendError = it.message ?: it.toString() } pending = null } + // Known and accepted: this is keyed on the message count, so a delivery-only + // change (a row flipping `queued` → `sent`, same size, different marker) + // does not re-run it. That has always been the behaviour here and it is the + // safe one — the list never moves for a marker. LaunchedEffect(messages?.size) { val n = messages?.size ?: 0 - if (n > 0) listState.animateScrollToItem(n - 1) + if (n == 0) return@LaunchedEffect + if (!firstFillDone) { + // First load: one jump to the bottom so the newest message is the + // one on screen, without an animation nobody asked for. + listState.scrollToItem(n - 1) + firstFillDone = true + return@LaunchedEffect + } + // Follow the tail only when the reader is already there. `n - 2` + // rather than `!canScrollForward`: the append has already made the list + // scrollable by the time this runs, so "can I scroll further" is true + // even for someone who was glued to the bottom a frame ago — and + // `lastVisible >= n - 2` tolerates the last row being partly on screen. + val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1 + if (ownSendPending || lastVisible >= n - 2) { + listState.animateScrollToItem(n - 1) + } + ownSendPending = false } Scaffold( @@ -139,8 +191,17 @@ fun ChatScreen( ), ) }, + // The top bar carries its own status-bar inset; the content root applies + // systemBars + IME once (see `screenContentInsets`) so the navigation + // bar is not counted twice while the keyboard is up. + contentWindowInsets = WindowInsets(0, 0, 0, 0), ) { pad -> - Column(Modifier.padding(pad).fillMaxSize()) { + Column( + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets(), + ) { Text( "onion: $onion", style = MaterialTheme.typography.labelSmall, @@ -152,14 +213,21 @@ fun ChatScreen( val list = messages when { list == null -> { - Spacer(Modifier.height(16.dp)) - CircularProgressIndicator(Modifier.padding(16.dp)) + // The body region always claims the leftover height, so the + // composer below it can never be pushed off the bottom — + // least of all by the keyboard. + Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { + CircularProgressIndicator(Modifier.padding(16.dp)) + } } list.isEmpty() -> { Column( - Modifier.fillMaxWidth().padding(24.dp), - verticalArrangement = Arrangement.Center, + Modifier + .weight(1f) + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(24.dp), ) { Text("No messages", style = MaterialTheme.typography.titleSmall) Spacer(Modifier.height(6.dp)) @@ -274,28 +342,60 @@ fun ChatScreen( ) } + // The composer sticks to the bottom of the window: `screenContentInsets` + // already lifted it above the keyboard, and its row is never allowed + // to be squeezed out by the messages above it (they hold the weight). Row( - Modifier.fillMaxWidth().padding(8.dp), - verticalAlignment = Alignment.CenterVertically, + Modifier + .fillMaxWidth() + .padding(8.dp) + .testTag("chat-composer"), + verticalAlignment = Alignment.Bottom, ) { OutlinedTextField( value = draft, onValueChange = { draft = it }, - modifier = Modifier.weight(1f), + modifier = Modifier + .weight(1f) + .focusRequester(inputFocus) + .testTag("chat-input"), maxLines = 4, label = { Text("message") }, + // DECISION (item 3 of the follow-up card): the IME's action + // key sends; the soft keyboard cannot insert a manual + // newline. `ImeAction.Send` and `maxLines = 4` are not in + // conflict — `maxLines` is a wrap limit (a long message + // grows to four lines, then scrolls inside the field), not + // a newline affordance. Chat convention wins: Enter-to-send + // is what a messenger's users reach for, and the Send button + // is on the same row. Nothing is unreachable either — a + // hardware keyboard's Enter never goes through the IME + // action, so Shift+Enter still inserts a real newline in + // the field. + keyboardOptions = KeyboardOptions( + capitalization = KeyboardCapitalization.Sentences, + imeAction = ImeAction.Send, + ), + keyboardActions = KeyboardActions(onSend = { send() }), ) Spacer(Modifier.width(8.dp)) - if (pending != null) { - CircularProgressIndicator() - } else { - Button( - enabled = draft.isNotBlank(), - onClick = { - pending = draft - draft = "" - }, - ) { Text("Send") } + // Always drawn, never swapped out for a spinner: a button that + // changes size under the thumb — or disappears — is how "I hit + // send and nothing happened" gets reported. + Button( + enabled = draft.isNotBlank() && pending == null, + onClick = send, + modifier = Modifier.testTag("chat-send"), + ) { + if (pending != null) { + CircularProgressIndicator( + modifier = Modifier.size(14.dp), + strokeWidth = 2.dp, + color = LocalContentColor.current, + ) + Spacer(Modifier.width(6.dp)) + } + Text("Send") } } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt new file mode 100644 index 0000000..fd7802d --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt @@ -0,0 +1,45 @@ +package com.siriusdevops.onionwire.ui + +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.ime +import androidx.compose.foundation.layout.only +import androidx.compose.foundation.layout.systemBars +import androidx.compose.foundation.layout.union +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier + +/** + * The bottom + horizontal window insets one screen's content root must apply + * itself. + * + * `MainActivity` calls `enableEdgeToEdge()`, which means + * `setDecorFitsSystemWindows(window, false)`. On API 30+ that stops the + * framework from resizing the window for the soft keyboard: the manifest's + * `android:windowSoftInputMode="adjustResize"` has nothing left to resize, and + * the IME arrives as a *window inset* instead. `Scaffold`'s + * `contentWindowInsets` only covers `systemBars`, so anything anchored to the + * bottom of the window — the chat composer, a submit button under a text field + * — ends up drawn behind the keyboard, reachable only by dismissing it. + * + * The IME's bottom inset already covers the navigation bar, so the two are + * unioned (per-side `max`), never summed: keyboard height while typing, + * navigation-bar height otherwise, and no double padding in between. + * + * The `Top` side is deliberately excluded — a `Scaffold`'s `pad.top` is the app + * bar's own measured height, and the app bar carries its own status-bar inset + * (`TopAppBarDefaults.windowInsets`). + * + * Pair every use with `Scaffold(contentWindowInsets = WindowInsets(0, 0, 0, 0))` + * so the same inset is not applied twice. + * + * `@Composable` because `WindowInsets.systemBars` / `WindowInsets.ime` are + * composable reads — call it from a composable (every call site is one). + */ +@Composable +fun Modifier.screenContentInsets(): Modifier = + windowInsetsPadding( + WindowInsets.systemBars.union(WindowInsets.ime) + .only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom), + ) \ No newline at end of file diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt index 31da473..4d67f52 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt @@ -1,9 +1,11 @@ package com.siriusdevops.onionwire.ui +import android.content.ClipData 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 @@ -31,8 +33,8 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalClipboardManager -import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.platform.ClipEntry +import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch import uniffi.onionwire_sdk.FriendInfo @@ -44,7 +46,8 @@ fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) { var invite by remember { mutableStateOf(null) } var error by remember { mutableStateOf(null) } var copied by remember { mutableStateOf(false) } - val clip = LocalClipboardManager.current + val clipboard = LocalClipboard.current + val scope = rememberCoroutineScope() LaunchedEffect(Unit) { runCatching { ownerInvite() } @@ -62,9 +65,17 @@ fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) { ), ) }, + // The root applies systemBars + IME itself (see `screenContentInsets`), + // so Scaffold must not also pad for the navigation bar. + contentWindowInsets = WindowInsets(0, 0, 0, 0), ) { pad -> Column( - Modifier.padding(pad).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets() + .verticalScroll(rememberScrollState()) + .padding(16.dp), ) { Text( "Hand this to one person, over a channel you already trust. " + @@ -98,8 +109,12 @@ fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) { Spacer(Modifier.height(12.dp)) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { Button(onClick = { - clip.setText(AnnotatedString(invite!!)) - copied = true + scope.launch { + clipboard.setClipEntry( + ClipEntry(ClipData.newPlainText("onionwire invite", invite!!)), + ) + copied = true + } }) { Text(if (copied) "Copied" else "Copy") } } Spacer(Modifier.height(20.dp)) @@ -149,9 +164,18 @@ fun PasteInviteScreen( ), ) }, + // Same inset handoff as the chat composer: with the keyboard up, the + // Verify / Approve buttons under the invite field must still be + // reachable by scrolling, not by dismissing the keyboard. + contentWindowInsets = WindowInsets(0, 0, 0, 0), ) { pad -> Column( - Modifier.padding(pad).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets() + .verticalScroll(rememberScrollState()) + .padding(16.dp), ) { OutlinedTextField( value = raw, diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt index 18b8750..ed641dc 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt @@ -6,6 +6,7 @@ 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 @@ -52,6 +53,11 @@ fun RosterScreen( var confirmWipe by remember { mutableStateOf(false) } Scaffold( + // The content root below consumes systemBars ∪ ime itself (see + // `screenContentInsets`); zeroing the Scaffold's own insets keeps the + // navigation bar from being applied twice and lets the wipe-confirm + // strip sit above the keyboard instead of under it. + contentWindowInsets = WindowInsets(0, 0, 0, 0), topBar = { TopAppBar( title = { Text("OnionWire") }, @@ -64,7 +70,7 @@ fun RosterScreen( ) }, ) { pad -> - Column(Modifier.padding(pad).fillMaxSize()) { + Column(Modifier.padding(pad).fillMaxSize().screenContentInsets()) { Card( modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp), @@ -134,7 +140,11 @@ fun RosterScreen( ) } } else { - LazyColumn(Modifier.fillMaxSize()) { + // 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()) { items(friends, key = { it.pubkeyHex }) { f -> FriendRow(f) { onOpenChat(f) } HorizontalDivider() diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt index e8b4cc1..b1f99b5 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt @@ -4,6 +4,7 @@ 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 @@ -59,9 +60,17 @@ fun RotateScreen( ), ) }, + // Root owns systemBars + IME (see `screenContentInsets`) so the confirm + // button under the passphrase field stays reachable with the keyboard up. + contentWindowInsets = WindowInsets(0, 0, 0, 0), ) { pad -> Column( - Modifier.padding(pad).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets() + .verticalScroll(rememberScrollState()) + .padding(16.dp), ) { Text("Rotate onion address?", style = MaterialTheme.typography.titleLarge) Spacer(Modifier.height(12.dp)) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt index 7adb6f8..4e57d5e 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt @@ -8,6 +8,7 @@ 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.safeDrawingPadding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll @@ -68,6 +69,10 @@ fun UnlockScreen( Column( modifier = Modifier .fillMaxSize() + // This screen has no Scaffold, so its root owns every window inset: + // without this the keyboard covers the passphrase field's Open + // button and the status bar overlaps the title. + .safeDrawingPadding() .verticalScroll(rememberScrollState()) .padding(24.dp), verticalArrangement = Arrangement.Center, diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index a4d3776..bc09ec7 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -9,14 +9,15 @@ 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.WindowInsets import androidx.compose.foundation.layout.aspectRatio 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.lazy.LazyColumn -import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults @@ -47,11 +48,13 @@ import com.google.zxing.BarcodeFormat import com.google.zxing.EncodeHintType import com.google.zxing.qrcode.QRCodeWriter import com.siriusdevops.onionwire.WireViewModel +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.TransferRow private enum class PayKind { Invoice, Tip } +private enum class SetupKind { Create, Import } @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -67,6 +70,8 @@ fun WalletScreen( var transfers by remember { mutableStateOf>(emptyList()) } var error by remember { mutableStateOf(null) } var composer by remember { mutableStateOf(null) } + var setup by remember { mutableStateOf(null) } + var backupSeed by remember { mutableStateOf(null) } suspend fun reload() { runCatching { balance = vm.walletBalance() } @@ -78,6 +83,11 @@ fun WalletScreen( LaunchedEffect(Unit) { reload() } Scaffold( + // The content root below consumes systemBars ∪ ime itself (see + // `screenContentInsets`); zeroing the Scaffold's own insets keeps the + // navigation bar from being applied twice, and keeps the IME inset out + // of the Scaffold's inner padding. + contentWindowInsets = WindowInsets(0, 0, 0, 0), topBar = { TopAppBar( title = { Text("Wallet") }, @@ -91,7 +101,13 @@ fun WalletScreen( }, ) { pad -> Column( - Modifier.padding(pad).fillMaxSize(), + Modifier + .padding(pad) + .fillMaxSize() + // systemBars ∪ ime, applied outside the scrolling viewport so + // the inset does not scroll away with the content. + .screenContentInsets() + .verticalScroll(rememberScrollState()), ) { Card( modifier = Modifier @@ -167,22 +183,22 @@ fun WalletScreen( style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), ) - LazyColumn( + // Plain Column, not a LazyColumn: the root is a scrolling + // container now, so a nested lazy list would either throw on the + // unbounded height or need an arbitrary cap. `walletRecentTransfers` + // is bounded (25 rows), and the page scrolls as one gesture. + Column( modifier = Modifier .fillMaxWidth() - .weight(1f, fill = false) .padding(horizontal = 12.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { - items(transfers, key = { it.txid }) { t -> - TransferCard(t) - } + transfers.forEach { t -> TransferCard(t) } } - } else { - Spacer(Modifier.weight(1f)) } val kind = composer + val setupKind = setup if (kind != null) { PayComposer( kind = kind, @@ -205,24 +221,72 @@ fun WalletScreen( } }, ) + } else if (setupKind != null) { + WalletSetupCard( + kind = setupKind, + warning = vm.spendAuthorityWarning(), + onCancel = { setup = null }, + onCreated = { seed -> + setup = null + backupSeed = seed + scope.launch { reload() } + }, + onImported = { + setup = null + scope.launch { reload() } + }, + onError = { error = it }, + create = { pw -> vm.createWallet(pw) }, + importWallet = { pw, seed -> vm.importWallet(pw, seed) }, + scope = scope, + ) } else { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(12.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - OutlinedButton( - onClick = { composer = PayKind.Invoice }, - modifier = Modifier.weight(1f), - ) { Text("Invoice") } - OutlinedButton( - onClick = { composer = PayKind.Tip }, - modifier = Modifier.weight(1f), - ) { Text("Tip") } + Column(Modifier.fillMaxWidth().padding(12.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedButton( + onClick = { composer = PayKind.Invoice }, + modifier = Modifier.weight(1f), + ) { Text("Invoice") } + OutlinedButton( + onClick = { composer = PayKind.Tip }, + modifier = Modifier.weight(1f), + ) { Text("Tip") } + } + Spacer(Modifier.height(8.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedButton( + onClick = { setup = SetupKind.Create }, + modifier = Modifier.weight(1f), + ) { Text("Create") } + OutlinedButton( + onClick = { setup = SetupKind.Import }, + modifier = Modifier.weight(1f), + ) { Text("Import") } + } } } + backupSeed?.let { seed -> + Text( + "write this seed down once. anyone with it can spend.", + style = MaterialTheme.typography.labelSmall, + modifier = Modifier.padding(horizontal = 12.dp), + ) + Text( + seed, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + TextButton(onClick = { backupSeed = null }) { Text("I wrote it down") } + } + error?.let { Text( it, @@ -347,6 +411,92 @@ private fun PayComposer( } } +@Composable +private fun WalletSetupCard( + kind: SetupKind, + warning: String, + onCancel: () -> Unit, + onCreated: (String) -> Unit, + onImported: () -> Unit, + onError: (String) -> Unit, + create: suspend (String) -> Result, + importWallet: suspend (String, String) -> Result, + scope: CoroutineScope, +) { + var accepted by remember { mutableStateOf(kind != SetupKind.Create) } + var password by remember { mutableStateOf("") } + var seed by remember { mutableStateOf("") } + val ready = password.isNotEmpty() && (kind == SetupKind.Create || seed.isNotBlank()) + + Card( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text( + if (kind == SetupKind.Create) "Create wallet" else "Import wallet", + style = MaterialTheme.typography.titleSmall, + ) + Spacer(Modifier.height(8.dp)) + if (kind == SetupKind.Create && !accepted) { + Text(warning, style = MaterialTheme.typography.bodySmall) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = onCancel) { Text("Cancel") } + Button(onClick = { accepted = true }) { Text("I accept spend authority") } + } + return@Column + } + if (kind == SetupKind.Import) { + Text( + "Paste the 25-word seed. Create does not need a key.", + style = MaterialTheme.typography.bodySmall, + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = seed, + onValueChange = { seed = it }, + label = { Text("seed") }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + } + OutlinedTextField( + value = password, + onValueChange = { password = it }, + singleLine = true, + label = { Text("wallet passphrase") }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = onCancel) { Text("Cancel") } + Button( + onClick = { + scope.launch { + when (kind) { + SetupKind.Create -> create(password).fold( + onSuccess = onCreated, + onFailure = { onError(it.message ?: it.toString()) }, + ) + SetupKind.Import -> importWallet(password, seed.trim()).fold( + onSuccess = { onImported() }, + onFailure = { onError(it.message ?: it.toString()) }, + ) + } + } + }, + enabled = ready, + ) { Text(if (kind == SetupKind.Create) "Create" else "Import") } + } + } + } +} + /** Generate a QR bitmap for the given URI string. Returns null on encode failure. */ internal fun generateQrBitmap(uri: String): Bitmap? { return try { diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index df25c28..136b815 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -575,6 +575,30 @@ impl Wire { .await .map_err(WireError::new) } + + /// Create a new spend-capable wallet. Returns the 25-word seed once so the + /// UI can show a backup screen. The user does not paste a key on this path. + /// Requires `ONIONWIRE_WALLET_RPC` pointed at a `--wallet-dir` RPC. + pub async fn create_wallet(&self, password: String) -> WResult { + self.node()? + .wallet_create(&password) + .await + .map_err(WireError::new) + } + + /// Import a wallet from an existing 25-word seed. This is the only path + /// that takes a user-supplied secret. + pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> { + self.node()? + .wallet_restore(&password, &seed) + .await + .map_err(WireError::new) + } + + /// Spend-authority warning shown before create. Not a tooltip. + pub fn spend_authority_warning(&self) -> String { + onionwire::wallet::SPEND_AUTHORITY_WARNING.to_string() + } } fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome { diff --git a/docs/RELEASING.md b/docs/RELEASING.md index a4ccc3b..fe6b3b6 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -114,6 +114,18 @@ The Android build runs on the **amd64** runner (the Pi is aarch64 and cannot produce an APK), then a second job on the Pi attaches the assets. It is the long pole of a release — the Linux binaries land first. +### Android CI (not a release) + +`android-ci.yml` runs the same gradle targets on the same amd64 runner for every +PR and `main` push that touches `android/`, `src/`, `crates/`, `Cargo.toml`, +`Cargo.lock` or `scripts/build-android-local.sh`, so an android-only PR is no +longer merged on an empty check list. It signs with the **debug** key +(`ONIONWIRE_REQUIRE_RELEASE_KEY=false`, no keystore) and publishes nothing — +`apksigner` in that job reports the debug cert, which is expected there and +never in `android-release`. It shares `android-release.yml`'s concurrency group +and volumes, so the PR build is warm (~9 min) instead of re-downloading a +gigabyte of SDK/NDK. + ## Rebuilding an existing tag - **Both** Linux binaries: dispatch `release` with `tag=vX.Y.Z`. The tag's own diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 48daf63..006ee1f 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -69,21 +69,61 @@ The queue is bounded in scope: chat only. File transfer and `rcp` frames are one A signed `prf` frame is shown to people who already have a session with you. Apply only for existing friends. There is still no name lookup, DHT, or public profile server. Anyone who already has a Noise session can see the profile you send them; that is not confidentiality against that friend. -## Monero sidecar is not a wallet +## Payments are opt-in; spend is a local authority -OnionWire never holds spend keys. Optional `ONIONWIRE_WALLET_RPC` talks HTTP Digest to a user-hosted `monero-wallet-rpc` on loopback (`--rpc-login` required; open RPC is refused). A Noise friend can sign any `rcp`; the signature proves who sent the claim, not that a payment happened. `verified=1` only after a conjunctive RPC match: one `get_transfers` row with the same non-empty `txid`, `amount`, and `address`. Incoming `rcp` stays `verified=0` if RPC is down, errors, or no exact row. Subaddress reuse is the user’s wallet policy. +Chat does not need a wallet. Payment frames (`inv`, `rcp`, `tip`) are signed +claims over Noise: a signature proves which friend sent the claim, not that +money moved. `verified=1` only after a conjunctive match — one `get_transfers` +row with the same non-empty `txid`, `amount`, and `address`. RPC down, error, or +no exact row → stay `verified=0`. Subaddress reuse is the user’s wallet policy. -Run it **view-only** (recommended). `/pay` and receipt verification need only -`create_address`/`get_transfers`, which a wallet without a spend key serves -fine; `ONIONWIRE_WALLET_NO_SPEND=1` disables `/tip` locally, before any RPC -dial, and a view-only wallet is detected over RPC (`query_key` -`key_type=spend_key` → `-29`, `WALLET_RPC_ERROR_CODE_WATCH_ONLY`) so `/tip` says -so plainly instead of failing with a raw wallet error. The trade-off is -explicit: an OnionWire instance pointed at a **spend-capable** wallet is a local -spend authority — any process that can read the RPC credentials can move the -balance, and `/tip` gives a chat peer a supported way to ask for a transfer. -Loopback binding is not an authorization boundary. Full setup, view-only wallet -creation, and the credential/loopback reasoning: [WALLET.md](WALLET.md). +**Default: no spend.** No seed and no spend key on the device. Receive can use +the profile `xmr_addr`, or a view-only wallet (`create_address` / +`get_transfers` only). `/tip` is off (`ONIONWIRE_WALLET_NO_SPEND`, or a +watch-only wallet detected over RPC via `query_key spend_key` → `-29`). + +**Spend is opt-in**, at wallet create or restore, not a hidden default. A +seed-backed spend-capable wallet makes OnionWire a **local spend authority** +for that file: anyone with the wallet passphrase or the wallet-RPC credentials +can move the balance, and `/tip` is a supported way for a chat peer to get paid. +The spend-authority warning is unavoidable at that create/restore step. Loopback +binding is not an authorization boundary. Back up the seed; do not leave a +spend-capable wallet on a device you do not trust; a separate hot wallet with a +small balance is the sane spend shape, not savings. + +The app talks to `monero-wallet-rpc` over **loopback HTTP Digest** only +(`--rpc-login` required; open RPC refused). That process may be one the user +already runs, or one the app spawns. Wallet RPC is never dialed over clearnet or +over `.onion` — a remote wallet RPC would move spend authority off the box +through a channel the messenger’s `--password` gate does not cover. + +### Chain source is the user’s choice + +Scan, receipt verification, and spend need a Monero daemon. The user picks one; +the app does not pick a public remote node for them. + +1. **Spawn a local `monerod`** (pruned is the on-device target). Chain traffic + stays on the device. The user accepts disk (tens of GB for a pruned mainnet + node), first-sync time, and — on Android — process kills: the daemon is not + always running. A pruned node is not an archive. Seed restore of deep history + can degrade; once the wallet has scanned, its own cache is the history. + Unsynced or not running is an honest “not ready” / unverified state, not a + fake success. + +2. **A daemon address they supply.** The wallet child points `--daemon-address` + at that host. Trust follows the address: + - **Loopback** — same privacy as (1); the user owns `monerod`. + - **`.onion`** — chain traffic over Tor through a localhost SOCKS5 listener + the app provides for the wallet child (not the messenger’s Arti + `connect()`, and not a C-tor fallback for chat). Tor hides the transport. + The daemon operator still sees the wallet’s addresses during sync. The + host is the trust boundary. + - **Clearnet** — only if the user typed it. Not a default, not implied. + The ISP sees Monero-node traffic; the daemon operator sees addresses. Show + that trust shift before using the address. + +Remote daemons are untrusted (`--trusted-daemon` off). Setup, view-only vs +spend, and RPC credentials: [WALLET.md](WALLET.md). ## Backup file is the identity @@ -96,12 +136,23 @@ Incoming rendezvous accepts are token-bucket limited (30/60s, burst 10). Excess ## Network (UDP / clearnet) The application does not open UDP sockets and does not resolve friends via -system DNS. Peer dials are Arti `connect((onion, 80))` only. The one -intentional clearnet socket is optional `monero-wallet-rpc` on **loopback TCP** -(numeric loopback preferred; `localhost` still does `getaddrinfo`). +system DNS. Peer dials are Arti `connect((onion, 80))` only. -Do not add STUN/ICE/WebRTC, a DHT, SOCKS/C-tor fallback, or “direct TCP when -the onion is slow.” Those are the Tox-over-Tor leak class. +Wallet **RPC** (HTTP Digest to `monero-wallet-rpc`) is loopback TCP only +(numeric `127.0.0.1` / `::1` preferred; `localhost` still does `getaddrinfo`). +That socket is the app talking to the wallet process, not to the chain. + +**Chain** traffic is the wallet child’s connection to a Monero daemon. It is +off unless the user opted into a wallet and chose a chain source: spawned local +`monerod` (loopback), or a daemon address they entered. A `.onion` daemon is +reached through a localhost SOCKS5 proxy used only by that wallet child. A +clearnet daemon address is an explicit user choice — a clearnet socket they +asked for — not the messenger path and not a hidden default. + +Do not add STUN/ICE/WebRTC, a DHT, SOCKS/C-tor fallback for **peer dials**, or +“direct TCP when the onion is slow.” Those are the Tox-over-Tor leak class. A +SOCKS listener used only by the wallet child to reach a user-chosen `.onion` +daemon is not that class. ## Peer text is untrusted display data diff --git a/docs/WALLET.md b/docs/WALLET.md index 7da17bc..9975bc7 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -1,14 +1,23 @@ # OnionWire + monero-wallet-rpc -OnionWire is not a wallet. It never holds a seed, a spend key, or a view key. -It talks optional JSON-RPC to a `monero-wallet-rpc` that **you** run, on -loopback, only to: +Chat does not require a wallet. A wallet is opt-in. + +**Default: no spend.** No seed and no spend key on the device. Receive uses the +profile `xmr_addr`, or a view-only wallet for invoices (`create_address`) and +receipt checks (`get_transfers`). `/tip` is off. + +**Spend is opt-in** at wallet create or restore (seed-backed). That makes +OnionWire a local spend authority for that wallet file — see the spend-authority +warning below. The threat-model write-up is [THREAT_MODEL.md](THREAT_MODEL.md). + +The app talks to `monero-wallet-rpc` over loopback HTTP Digest only, whether +that process is one you already run or one the app spawns: - hand out a receive subaddress for `/pay` invoices (`create_address`), - read incoming transfers to verify a peer's receipt (`get_transfers`), -- and — only if you let it — spend for `/tip` (`transfer`). +- and — only if you opted into spend — `/tip` (`transfer`). -**Run it view-only, and switch `/tip` off explicitly.** Everything else in this +**Prefer view-only until you actually want `/tip`.** Everything else in this document explains why, and what breaks when you do. ## Env vars @@ -21,6 +30,20 @@ document explains why, and what breaks when you do. `README.md` carries the operator summary; this file is the long form. +## Create vs import + +Create does **not** take a private key. `/wallet create` (TUI: F6 then `c`) asks +the RPC to generate a new spend-capable wallet (`create_wallet`), then shows the +seed **once** for backup (`query_key mnemonic`). Type `SPEND` to accept the +spend-authority warning, set a passphrase, write the seed down, type `SEEN`. + +Import is the only path that takes an existing secret: `/wallet import` (F6 then +`i`) pastes the 25-word seed into `restore_deterministic_wallet`. Do not put the +seed on the composer line — it would sit in chat history. + +The RPC must be started with `--wallet-dir` (not only `--wallet-file`) or create +and import fail. The in-app filename is `onionwire`. + ## Recommended topology ``` @@ -34,9 +57,26 @@ document explains why, and what breaks when you do. └──────────────────────────────────────────────────────────────┘ ``` -Loopback is the only address OnionWire will dial. `.onion` RPC URLs are -rejected: there is no Arti dial for the wallet, and a remote wallet would move -your key material off the box. +Loopback is the only address OnionWire will dial for **wallet RPC**. `.onion` +wallet-RPC URLs are rejected: there is no Arti dial for the wallet process, and +a remote wallet RPC would move spend authority off the box. + +## Chain source + +The wallet needs a daemon for scan, verify, and spend. You pick one; OnionWire +does not pick a public remote node for you. + +1. **Spawn a local `monerod`** (pruned on-device). Chain traffic stays on the + box. You accept disk, first sync, and (on Android) the daemon not always + running. +2. **A daemon address you supply** — `--daemon-address` on the wallet child. + Loopback if you already run `monerod`. `.onion` if you want chain traffic + over Tor (wallet child `--proxy` to a localhost SOCKS listener; the daemon + operator still sees addresses). Clearnet only if you type it — ISP sees + Monero-node traffic; not a default. + +Remote daemons are untrusted (`--trusted-daemon` off). Unsynced or unreachable +→ receipts stay unverified and spend is refused. That is the honest state. ## Create a view-only wallet @@ -88,7 +128,7 @@ Restore the wallet from a height *at or before* its first incoming transaction | Receipt verification (`get_transfers`) | works | works | | Profile `xmr_addr` fallback when RPC is down | works | works | | `/tip ` (`transfer`) | **cannot work** | works | -| OnionWire learns your spend key | never | never (it stays in the wallet) | +| OnionWire copies your spend key into its own process | never | never (it stays in the wallet file / RPC) | With `ONIONWIRE_WALLET_NO_SPEND=1` a `/tip` is refused before the RPC is contacted, with: diff --git a/scripts/publish-release.sh b/scripts/publish-release.sh index bfbbfa1..b5d075e 100755 --- a/scripts/publish-release.sh +++ b/scripts/publish-release.sh @@ -21,11 +21,7 @@ api_curl() { } auth_json() { -<<<<<<< Updated upstream - api_curl -u "sirius:${FORGEJO_TOKEN}" -H "Content-Type: application/json" "$@" -======= api_curl -u "sirius:${FORGEJO_TOKEN}" -H "Content-Type: application/json" "$@" | sed 's/\r$//' ->>>>>>> Stashed changes } tag="${1:?usage: publish-release.sh ...}" @@ -130,12 +126,7 @@ for a in json.load(sys.stdin): fi done up=$(api_curl -o /tmp/release-asset.json -w '%{http_code}' \ -<<<<<<< Updated upstream - -X POST "$api/releases/$rid/assets?name=$asset" \ - -u "sirius:${FORGEJO_TOKEN}" \ -======= -X POST -u "sirius:${FORGEJO_TOKEN}" "$api/releases/$rid/assets?name=$asset" \ ->>>>>>> Stashed changes -F "attachment=@$f") if [ "$up" != "201" ]; then die_http "upload $asset" "$up" /tmp/release-asset.json diff --git a/src/node.rs b/src/node.rs index ee21275..5ca5bbe 100644 --- a/src/node.rs +++ b/src/node.rs @@ -684,6 +684,29 @@ impl Node { Ok(rows.into_iter().take(cap).collect()) } + /// Create a new spend-capable wallet. Returns the seed once for backup. + /// The user never pastes a key on this path. + pub async fn wallet_create(&self, password: &str) -> Result { + if !self.wallet.configured() { + return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into()); + } + self.wallet + .create_wallet(wallet::DEFAULT_WALLET_FILENAME, password) + .await + .map_err(|e| e.to_string()) + } + + /// Import a wallet from an existing 25-word seed. This is the only path + /// that takes a user-supplied secret. + pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> { + if !self.wallet.configured() { + return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into()); + } + self.wallet + .restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed) + .await + .map_err(|e| e.to_string()) + } async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> { self.ensure_running()?; diff --git a/src/tui.rs b/src/tui.rs index e149d9a..8622ca5 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -454,9 +454,12 @@ OnionWire keys\n\ F3 paste invite\n\ F4 rotate onion locator\n\ F5 selected friend's profile (/who)\n\ + F6 wallet (receive QR, create/import)\n\ /profile edit name, bio, Monero address\n\ /pay [memo] invoice to receive\n\ /tip [memo] pay selected friend\n\ + /wallet create new spend wallet (seed shown once)\n\ + /wallet import restore from existing seed\n\ /file /path send file to selected friend (1 MiB)\n\ /backup /path encrypted identity export\n\ /restore /path overwrite self keys\n\ @@ -562,6 +565,8 @@ pub enum SlashCmd { Backup { path: String }, Restore { path: String }, File { path: String }, + WalletCreate, + WalletImport, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -710,6 +715,11 @@ pub fn parse_cmd(raw: &str) -> Option { { return parse_path_cmd(rest).map(|path| SlashCmd::File { path }); } + match s { + "/wallet create" => return Some(SlashCmd::WalletCreate), + "/wallet import" => return Some(SlashCmd::WalletImport), + _ => {} + } None } @@ -1118,11 +1128,20 @@ enum Screen { transfers: Vec, qr_modal: Option, }, + WalletSetup(WalletSetup), Quit { prompt: QuitPrompt, }, } +enum WalletSetup { + CreateWarn { typed: String }, + CreatePass { entry: PassphraseEntry }, + CreateSeed { seed: Zeroizing, typed: String }, + ImportSeed { buf: Zeroizing }, + ImportPass { seed: Zeroizing, entry: PassphraseEntry }, +} + impl App { fn new(node: Arc, rt: tokio::runtime::Handle) -> Result { let friends = node.list_friends()?; @@ -1276,6 +1295,18 @@ impl App { self.composer.clear(); file_cmd = Some(path); } + Some(ComposerAction::Cmd(SlashCmd::WalletCreate)) => { + self.composer.clear(); + self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }); + } + Some(ComposerAction::Cmd(SlashCmd::WalletImport)) => { + self.composer.clear(); + self.screen = Screen::WalletSetup(WalletSetup::ImportSeed { + buf: Zeroizing::new(String::new()), + }); + } Some(ComposerAction::Send(text)) => { self.composer.clear(); chat_send = Some(text); @@ -1394,8 +1425,19 @@ impl App { Screen::Wallet { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(), + KeyCode::Char('c') => { + self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }); + } + KeyCode::Char('i') => { + self.screen = Screen::WalletSetup(WalletSetup::ImportSeed { + buf: Zeroizing::new(String::new()), + }); + } _ => {} }, + Screen::WalletSetup(_) => self.handle_wallet_setup(key)?, Screen::Quit { prompt } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => match prompt.on_char('\n') { @@ -1663,6 +1705,151 @@ impl App { }); } + fn handle_wallet_setup(&mut self, key: KeyEvent) -> Result<(), String> { + let Screen::WalletSetup(setup) = &mut self.screen else { + return Ok(()); + }; + if key.code == KeyCode::Esc { + match setup { + WalletSetup::CreatePass { entry } | WalletSetup::ImportPass { entry, .. } => { + entry.close(); + } + WalletSetup::CreateSeed { seed, .. } => seed.zeroize(), + WalletSetup::ImportSeed { buf } => buf.zeroize(), + WalletSetup::CreateWarn { .. } => {} + } + self.screen = Screen::Main; + return Ok(()); + } + match setup { + WalletSetup::CreateWarn { typed } => match key.code { + KeyCode::Char(c) if c.is_ascii_alphabetic() => { + typed.push(c); + if typed.eq_ignore_ascii_case("SPEND") { + self.screen = Screen::WalletSetup(WalletSetup::CreatePass { + entry: PassphraseEntry::new(), + }); + } + } + KeyCode::Backspace => { + typed.pop(); + } + _ => {} + }, + WalletSetup::CreatePass { entry } => match key.code { + KeyCode::Backspace => entry.backspace(), + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { + entry.push(c); + } + KeyCode::Enter => { + let first = entry.take_first(); + let pass = entry.take_buf(); + if let Some(first) = first { + if first.as_str() != pass.as_str() { + entry.close(); + self.alert = Some("passphrases do not match".into()); + self.screen = Screen::Main; + return Ok(()); + } + match self.rt.block_on(self.node.wallet_create(pass.as_str())) { + Ok(seed) => { + self.screen = Screen::WalletSetup(WalletSetup::CreateSeed { + seed: Zeroizing::new(seed), + typed: String::new(), + }); + } + Err(e) => { + self.alert = Some(e); + self.screen = Screen::Main; + } + } + } else { + self.screen = Screen::WalletSetup(WalletSetup::CreatePass { + entry: PassphraseEntry::with_first(pass.as_str()), + }); + } + } + _ => {} + }, + WalletSetup::CreateSeed { typed, seed } => match key.code { + KeyCode::Char(c) if c.is_ascii_alphabetic() => { + typed.push(c); + if typed.eq_ignore_ascii_case("SEEN") { + seed.zeroize(); + self.status_note = Some("wallet created — seed shown once".into()); + return self.open_wallet(); + } + } + KeyCode::Backspace => { + typed.pop(); + } + _ => {} + }, + WalletSetup::ImportSeed { buf } => match key.code { + KeyCode::Backspace => { + buf.pop(); + } + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { + buf.push(c); + } + KeyCode::Enter => { + let seed = std::mem::replace(buf, Zeroizing::new(String::new())); + if seed.trim().is_empty() { + self.alert = Some("seed required to import a wallet".into()); + self.screen = Screen::Main; + return Ok(()); + } + self.screen = Screen::WalletSetup(WalletSetup::ImportPass { + seed, + entry: PassphraseEntry::new(), + }); + } + _ => {} + }, + WalletSetup::ImportPass { entry, seed } => match key.code { + KeyCode::Backspace => entry.backspace(), + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { + entry.push(c); + } + KeyCode::Enter => { + let first = entry.take_first(); + let pass = entry.take_buf(); + if let Some(first) = first { + if first.as_str() != pass.as_str() { + entry.close(); + seed.zeroize(); + self.alert = Some("passphrases do not match".into()); + self.screen = Screen::Main; + return Ok(()); + } + let result = self + .rt + .block_on(self.node.wallet_restore(pass.as_str(), seed.as_str())); + seed.zeroize(); + match result { + Ok(()) => { + self.status_note = Some("wallet imported".into()); + return self.open_wallet(); + } + Err(e) => { + self.alert = Some(e); + self.screen = Screen::Main; + } + } + } else { + let seed = std::mem::replace(seed, Zeroizing::new(String::new())); + self.screen = Screen::WalletSetup(WalletSetup::ImportPass { + seed, + entry: PassphraseEntry::with_first(pass.as_str()), + }); + } + } + _ => {} + }, + } + Ok(()) + } + fn submit_paste(&mut self, raw: &str) -> Result<(), String> { match qr::decode(raw.trim()) { Err(e) => { @@ -1835,6 +2022,7 @@ impl App { Screen::Wallet { receive_addr, balance, transfers, qr_modal } => { draw_wallet(f, receive_addr, balance, transfers, qr_modal.as_ref()) } + Screen::WalletSetup(setup) => draw_wallet_setup(f, setup), } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -2152,7 +2340,13 @@ match screen { BackupKind::Restore => "type RESTORE Esc cancel ? help", }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", - Screen::Wallet { .. } => "r toggle qr Esc back ? help", + Screen::Wallet { .. } => "c create i import r qr Esc back ? help", + Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", + Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { + "Enter submit Esc cancel ? help" + } + Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help", + Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } @@ -2489,7 +2683,7 @@ recent transfers lines.push(format!(" {} {} XMR", t.txid.chars().take(16).collect::(), xmr)); } } - let help = "r toggle qr Esc back"; + let help = "c create i import r toggle qr Esc back"; lines.push("".into()); f.render_widget( Paragraph::new(lines.join("\n")) @@ -2502,6 +2696,49 @@ recent transfers f.render_widget(Paragraph::new(help).style(style_dim()), cols[3]); } +fn draw_wallet_setup(f: &mut Frame, setup: &WalletSetup) { + let (title, body) = match setup { + WalletSetup::CreateWarn { typed } => ( + "create spend wallet", + format!( + "{}\n\nType SPEND to confirm Esc to cancel\n{typed}", + wallet::SPEND_AUTHORITY_WARNING + ), + ), + WalletSetup::CreatePass { entry } => ( + "wallet passphrase", + if entry.first().is_some() { + "re-type passphrase\n\nEnter submits Esc cancels".into() + } else { + "set a passphrase for the wallet file\n\nEnter continues Esc cancels".into() + }, + ), + WalletSetup::CreateSeed { seed, typed } => ( + "write down this seed", + format!( + "{}\n\nthis is shown once. anyone with it can spend.\nType SEEN when you have written it down\n{typed}", + seed.as_str() + ), + ), + WalletSetup::ImportSeed { buf } => ( + "import wallet", + format!( + "paste the 25-word seed. this is the only path that takes an existing key.\n\n{}\n\nEnter continues Esc cancels", + buf.as_str() + ), + ), + WalletSetup::ImportPass { entry, .. } => ( + "wallet passphrase", + if entry.first().is_some() { + "re-type passphrase\n\nEnter submits Esc cancels".into() + } else { + "passphrase for the imported wallet file\n\nEnter continues Esc cancels".into() + }, + ), + }; + draw_text_overlay(f, title, &body); +} + fn io_err(e: io::Error) -> String { e.to_string() } diff --git a/src/wallet.rs b/src/wallet.rs index cf255a0..61234cc 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -61,6 +61,12 @@ pub struct TransferRow { pub address: String, } +/// Wallet file name used for in-app create/import (`--wallet-dir` on the RPC). +pub const DEFAULT_WALLET_FILENAME: &str = "onionwire"; + +/// Shown before a spend-capable create. Not a tooltip — the user must confirm. +pub const SPEND_AUTHORITY_WARNING: &str = "this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed. do not leave it on a box you do not trust."; + const RPC_TIMEOUT: Duration = Duration::from_secs(5); impl Wallet { @@ -215,6 +221,65 @@ impl Wallet { json_str(&v, "balance") } + /// Create a new spend-capable wallet on the RPC (`create_wallet`). The + /// user does not paste a key — the daemon generates the seed. Returns that + /// seed once (from `query_key mnemonic`) so the UI can show a backup + /// screen. Needs `--wallet-dir` on the RPC. + pub async fn create_wallet(&self, filename: &str, password: &str) -> Result { + let filename = filename.trim(); + if filename.is_empty() { + return Err(Error("wallet filename required".into())); + } + if password.is_empty() { + return Err(Error("wallet passphrase required".into())); + } + self.rpc( + "create_wallet", + serde_json::json!({ + "filename": filename, + "password": password, + "language": "English" + }), + ) + .await?; + let v = self + .rpc("query_key", serde_json::json!({"key_type": "mnemonic"})) + .await + .map_err(|e| { + Error(format!( + "wallet created but seed backup unavailable: {e}" + )) + })?; + json_str(&v, "key") + } + + /// Import an existing wallet from its 25-word seed. This is the only path + /// that takes a user-supplied secret. + pub async fn restore_wallet(&self, filename: &str, password: &str, seed: &str) -> Result<()> { + let filename = filename.trim(); + if filename.is_empty() { + return Err(Error("wallet filename required".into())); + } + if password.is_empty() { + return Err(Error("wallet passphrase required".into())); + } + let seed = seed.trim(); + if seed.is_empty() { + return Err(Error("seed required to import a wallet".into())); + } + self.rpc( + "restore_deterministic_wallet", + serde_json::json!({ + "filename": filename, + "password": password, + "seed": seed, + "language": "English" + }), + ) + .await?; + Ok(()) + } + async fn rpc(&self, method: &str, params: serde_json::Value) -> Result { let ep = self .endpoint diff --git a/tests/pay.rs b/tests/pay.rs index c2ab11c..1dc600b 100644 --- a/tests/pay.rs +++ b/tests/pay.rs @@ -206,6 +206,9 @@ fn slash_pay_tip_and_wipe_still_parse() { assert_eq!(parse_cmd("/wipe"), Some(SlashCmd::Wipe(WipeKind::Messages))); assert_eq!(parse_slash("/wipe-all"), Some(WipeKind::All)); assert_eq!(parse_slash("/pay 0.12"), None); + assert_eq!(parse_cmd("/wallet create"), Some(SlashCmd::WalletCreate)); + assert_eq!(parse_cmd("/wallet import"), Some(SlashCmd::WalletImport)); + assert_eq!(parse_cmd("/wallet"), None); } #[test] diff --git a/tests/tui_chrome.rs b/tests/tui_chrome.rs index a0ada29..1eacccf 100644 --- a/tests/tui_chrome.rs +++ b/tests/tui_chrome.rs @@ -45,10 +45,13 @@ fn help_overlay_lists_core_bindings() { "F3", "F4", "F5", + "F6", "send chat", "/profile", "/pay", "/tip", + "/wallet create", + "/wallet import", "/file", "/backup", "/restore", diff --git a/tests/wallet.rs b/tests/wallet.rs index 1d4a451..10fb7a1 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -429,6 +429,112 @@ async fn spend_capable_wallet_keeps_the_original_transfer_error() { assert!(!err.to_ascii_lowercase().contains("view-only"), "got {err}"); } +/// Create generates a spend-capable wallet on the RPC; the user never pastes a key. +/// Seed is read back once via `query_key mnemonic` for the backup screen. +#[tokio::test] +async fn create_wallet_does_not_send_a_seed_and_returns_mnemonic() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|method| match method { + "create_wallet" => rpc_result(r#"{}"#), + "query_key" => rpc_result(r#"{"key":"lumber tacit lemon ivory risk"}"#), + _ => rpc_error(-1, "unexpected method"), + }), + )); + let seed = recording_wallet(port) + .create_wallet("onionwire", "hunter2") + .await + .expect("create_wallet"); + assert_eq!(seed, "lumber tacit lemon ivory risk"); + let seen = log.lock().expect("log").clone(); + let create = seen + .iter() + .find(|r| r.contains(r#""method":"create_wallet""#)) + .expect("create_wallet RPC"); + assert!( + !create.contains("lumber") && !create.contains("seed"), + "create must not take a seed: {create}" + ); + assert!( + create.contains(r#""filename":"onionwire""#), + "filename missing: {create}" + ); + assert!( + seen.iter().any(|r| r.contains(r#""method":"query_key""#) + && r.contains("mnemonic")), + "must read mnemonic after create: {seen:?}" + ); +} + +#[test] +fn create_wallet_empty_filename_or_password_is_local_error() { + let w = Wallet::from_url("http://ow:secret@127.0.0.1:18083").unwrap(); + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let err = rt + .block_on(w.create_wallet("", "pw")) + .unwrap_err() + .to_string(); + assert!(err.contains("filename"), "got {err}"); + let err = rt + .block_on(w.create_wallet("onionwire", "")) + .unwrap_err() + .to_string(); + assert!( + err.to_ascii_lowercase().contains("password") + || err.to_ascii_lowercase().contains("passphrase"), + "got {err}" + ); +} + +/// Import is the only path that takes an existing secret (the 25-word seed). +#[tokio::test] +async fn restore_wallet_sends_seed_to_restore_deterministic_wallet() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|method| match method { + "restore_deterministic_wallet" => rpc_result(r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","seed":"lumber tacit lemon ivory risk"}"#), + _ => rpc_error(-1, "unexpected method"), + }), + )); + recording_wallet(port) + .restore_wallet("onionwire", "hunter2", "lumber tacit lemon ivory risk") + .await + .expect("restore_wallet"); + let seen = log.lock().expect("log").clone(); + let restore = seen + .iter() + .find(|r| r.contains(r#""method":"restore_deterministic_wallet""#)) + .expect("restore RPC"); + assert!( + restore.contains("lumber tacit lemon ivory risk"), + "seed missing: {restore}" + ); +} + +#[test] +fn restore_wallet_empty_seed_is_local_error() { + let w = Wallet::from_url("http://ow:secret@127.0.0.1:18083").unwrap(); + let err = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(w.restore_wallet("onionwire", "pw", " ")) + .unwrap_err() + .to_string(); + assert!(err.to_ascii_lowercase().contains("seed"), "got {err}"); +} + /// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused. #[tokio::test] async fn open_rpc_without_digest_challenge_is_still_refused() {