diff --git a/android/MONERO_BINARIES.md b/android/MONERO_BINARIES.md new file mode 100644 index 0000000..a191105 --- /dev/null +++ b/android/MONERO_BINARIES.md @@ -0,0 +1,168 @@ +# Bundled native executables (`jniLibs`) + +The wallet screen starts an **app-owned `monero-wallet-rpc` child** (issue #107, +`src/wallet_child.rs`). Monero ships no Android binaries, so this repository +carries one, built here. + +| | | +|---|---| +| File in the tree | `android/app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so` | +| Bytes | 19 954 224 (stripped) | +| sha256 | `d9126788030ecd1ccdb40c7764e66e9a14d158a147ad335b256f0577681b5ad4` | +| Format | `ELF 64-bit LSB shared object, ARM aarch64, dynamically linked, interpreter /system/bin/linker64, for Android 21, built by NDK r17b` | +| Needed libs | `libc.so`, `libm.so`, `libdl.so` — everything else is static | +| Source | `https://github.com/monero-project/monero` | +| Tag | `v0.18.4.4` | +| Commit | `516e5355a103a2bf0b7e10328ebcaa2945019445` | +| Reproduce with | `scripts/build-monero-wallet-rpc-android.sh` | +| Verified by | `android/monero-binaries.sha256`, checked by `scripts/build-android-local.sh` on every build (local and CI) | + +Only `arm64-v8a` is built. `-Ponionwire.abis=x86_64` produces an APK with no +wallet binary in it — the screen says so (`NO_WALLET_RPC_MESSAGE`) instead of +offering a Start that cannot work. + +## How it is built + +`scripts/build-monero-wallet-rpc-android.sh` runs upstream's own Android +cross-compile path — `contrib/depends` (boost, openssl, libunbound, libzmq, +libsodium, ncurses, readline, libiconv, expat for `aarch64-linux-android`) plus +the `toolchain.cmake` it emits — and then builds the single CMake target +`wallet_rpc_server`. It takes ~40 min on 12 cores and needs ~15 GB of scratch +space. It is **not** part of the CI path: CI here runs on a Raspberry Pi and the +Gradle build is already ~9 minutes. CI verifies the committed bytes instead. + +Four things about the build are worth writing down, because each one is a +failure that looks like something else: + +1. **CMake must be 3.x.** `contrib/depends` emits a *standalone-NDK-toolchain* + `toolchain.cmake` (`CMAKE_ANDROID_STANDALONE_TOOLCHAIN`). CMake 4.x no longer + honours that, silently falls back to the host `clang`, and the configure step + dies with `ld.lld: cannot open /usr/lib/clang/.../libclang_rt.builtins.a`. + The script installs 3.22.6 into a venv when the host CMake is 4.x. + +2. **The NDK r17b prebuilt `clang60` needs `libtinfo.so.5`.** `android_ndk.mk` + pins NDK r17b and drives the long-removed `make_standalone_toolchain.py` + (r17b still has it). Its `clang60` binary is linked against ncurses 5; + current distros ship ncurses 6 only, so every compile fails with + `error while loading shared libraries: libtinfo.so.5`. A shim directory with + `libtinfo.so.5 -> libtinfo.so.6` on `LD_LIBRARY_PATH` fixes it. The script + creates it. + +3. **`/usr` is in `CMAKE_FIND_ROOT_PATH`, and `/usr` is the host.** This is the + one that costs the most time. `CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY` does + not help: `/usr` is listed as a root, so `find_library()` returns host + libraries. Two consequences in this tree: + * `find_package(HIDAPI)` finds the **host** hidapi, defines `HAVE_HIDAPI`, + and `src/device` then fails to compile `hidapi/hidapi.h` — the include dir + it found is `/usr/include/hidapi`, so `` resolves to + `/usr/include/hidapi/hidapi/hidapi.h`. + * Monero's optional zmq extras (`pgm`, `norm`, `gssapi_krb5`, `protolib`, + `bsd`, `md`, `protokit`) are probed with `find_library` and appended to + `ZMQ_LIB`, so the final link gets `/usr/lib/libpgm.so` — an x86-64 shared + object in an aarch64 link line: `error adding symbols: File in wrong + format`. `libzmq.a` does not actually reference openpgm. + + The script rewrites the generated `toolchain.cmake` to + `SET(CMAKE_FIND_ROOT_PATH )`. This is also why upstream's + `make depends target=aarch64-linux-android` is not reproducible: it happens + to work only on a build host with none of those libraries installed. + + A stale `CMakeCache.txt` keeps the host paths after the toolchain is fixed, + and nothing complains until the link, so the script also passes + `-U PGM_LIBRARY -U GSSAPI_LIBRARY …` and configures in a fresh build dir. + +4. **The CMake target is `wallet_rpc_server`, not `monero-wallet-rpc`.** The + latter is the *output* name. `make monero-wallet-rpc` fails with + `No rule to make target`. + +### Not bit-reproducible + +Build paths and timestamps land in the binary, so a fresh run of the script +will not reproduce the sha256 above. That hash is a **provenance record of the +shipped blob** and the thing CI re-verifies — not a reproducible-build +assertion. If you rebuild, update both `android/monero-binaries.sha256` and this +table in the same commit, and say what changed in the tag or the toolchain. + +## Why it is a `jniLibs` `.so` and not an asset + +Since Android 10 (API 29) an app may not `exec()` a file in its own data +directory: the SELinux policy carries no `execute` on `app_data_file`, so the +familiar "ship it in `assets/`, copy it to `filesDir`, `chmod 700`" recipe is +refused by the kernel regardless of the mode bits. The one directory Android +hands out executable is `ApplicationInfo.nativeLibraryDir`, which the package +manager populates from the APK's `lib//` entries at install time. + +So the executable is named `libmonerowalletrpc.so` and shipped through +`jniLibs`, and the path the core is handed is + +``` +/libmonerowalletrpc.so +``` + +resolved at runtime by `wallet/WalletChildBinaries.kt`. This only works with +`android:extractNativeLibs="true"`; with the AGP 8 default +(`extractNativeLibs="false"`) the file stays inside the APK and there is nothing +on disk to run. `app/build.gradle.kts` sets `packaging.jniLibs.useLegacyPackaging += true` for exactly that reason, and `keepDebugSymbols` for this one entry so +AGP's strip pass cannot rewrite the bytes that CI verifies. + +Cost: the release APK grows from ~9 MB to ~28 MB (the binary is deflate-stored +at 6.9 MB) and installs ~20 MB into the app's native library directory. + +## `arti` is NOT bundled + +`WalletChild` runs `arti proxy -p ` as the SOCKS child for a **`.onion`** +daemon, and `ChildConfig::validate` requires a non-empty `arti_bin` for any +chain source that is not receive-only. There is no `arti` executable in this +build, and producing one (a standalone `arti` binary for +`aarch64-linux-android`, from a crate the Rust side does not currently build as +a bin) is a follow-up, not something this card could do without editing +`Cargo.toml`/`crates/**`. + +What the app does about it, honestly: + +* `arti_bin` is set to `/libarti.so` — the path the binary + *would* occupy. For a loopback or clearnet daemon the core never spawns it, so + the value is inert. It is deliberately **not** set to a real binary: + `monero-wallet-rpc` named as the SOCKS child would be spawned as the proxy the + moment the user typed an `.onion` host. +* The wallet screen refuses an `.onion` daemon while `libarti.so` is absent, and + says why (`ONION_NEEDS_ARTI_NOTICE`) instead of letting the spawn fail. + +So today: **loopback and clearnet daemons work; `.onion` daemons do not.** + +## Verification in CI + +`.forgejo/workflows/android-ci.yml` builds the APK on every `android/**` PR and +`scripts/build-android-local.sh` does the checking, so both CI jobs and local +builds get it: + +1. before Gradle, `sha256sum -c android/monero-binaries.sha256` against the + committed blob; +2. after packaging, `unzip -p` the `lib//libmonerowalletrpc.so` entry out + of the produced APK and compare its sha256 with the committed file. A + mismatch fails the build — the bytes that ship are the bytes that were + verified, not the bytes that were hoped for. + +## Not verified + +The binary was **not executed on a device or emulator**. There is no +`arm64-v8a` AVD on the build host (all three existing AVDs are `x86_64`), and no +aarch64 sysroot to run it under `qemu-user`. What is proven: it cross-compiles, +it is a valid `aarch64` Android PIE executable, it packages into the APK with +the expected bytes, and the Kotlin that drives it compiles. What is not: +that `monero-wallet-rpc` starts, opens its wallet file and answers JSON-RPC +under Android's runtime. + +To close that gap: + +```bash +sdkmanager "system-images;android-35;google_apis;arm64-v8a" +avdmanager create avd -n ow-arm64 -k "system-images;android-35;google_apis;arm64-v8a" +emulator -avd ow-arm64 # software-emulated on an x86_64 host: slow +adb install -r dist/onionwire--android-arm64-v8a.apk +``` + +then unlock the node, open Wallet, type a daemon as `host:port`, Save, and watch +the status line for `connecting → syncing → ready`. A `.onion` daemon will stop +at the arti notice above. diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index f72f3ac..0f83997 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -102,6 +102,23 @@ android { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } + jniLibs { + // `android:extractNativeLibs="true"`. This is what puts + // `libmonerowalletrpc.so` on disk in `ApplicationInfo.nativeLibraryDir` + // at install time, which is the ONLY directory Android lets an app + // `exec()` from (since API 29 a file in `filesDir` is not executable + // whatever its mode bits say). With the AGP 8 default + // (`extractNativeLibs="false"`) the wallet binary would stay inside + // the APK and `start_wallet_child` would fail with ENOENT on a path + // that looks correct. See android/MONERO_BINARIES.md. + useLegacyPackaging = true + // The wallet child is an executable, not a linked library, and + // scripts/build-monero-wallet-rpc-android.sh already stripped it with + // the target's own strip. Excluding it from AGP's strip pass keeps the + // bytes in the APK identical to the committed blob, which is what + // scripts/build-android-local.sh verifies in CI. + keepDebugSymbols += "**/libmonerowalletrpc.so" + } } } 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 f22fb12..6d9bae3 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -11,6 +11,9 @@ import com.siriusdevops.onionwire.crypto.StoredPassphraseStore import com.siriusdevops.onionwire.keepalive.KeepAliveService import com.siriusdevops.onionwire.keepalive.KeepAliveStatus import com.siriusdevops.onionwire.keepalive.NodeHost +import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE +import com.siriusdevops.onionwire.wallet.WalletChildBinaries +import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.currentCoroutineContext @@ -22,6 +25,8 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import uniffi.onionwire_sdk.ChainChoice +import uniffi.onionwire_sdk.ChainConfig import uniffi.onionwire_sdk.ChatMessage import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.InviteInfo @@ -29,6 +34,7 @@ import uniffi.onionwire_sdk.OutboxRow import uniffi.onionwire_sdk.RotateOutcome import uniffi.onionwire_sdk.SendState import uniffi.onionwire_sdk.TransferRow +import uniffi.onionwire_sdk.WalletChildStatus import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.decodeInvite import java.io.File @@ -562,4 +568,201 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { }.getOrElse { "this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed." } + + // --- App-owned wallet child (issue #107) ------------------------------- + // The app owns `monero-wallet-rpc` instead of asking the user to start one + // and export `ONIONWIRE_WALLET_RPC`. The core's own states are surfaced + // verbatim: off / connecting / syncing / ready / exited. Nothing here + // invents a "starting…" state, and a child that died is never folded into + // "off" — see `ui/WalletChildStatusText.kt`. + + /** The last `wallet_status()` snapshot, or null before the first read. */ + private val _walletChild = MutableStateFlow(null) + val walletChild: StateFlow = _walletChild.asStateFlow() + + /** + * The last failed start/stop/read, display-ready. Sticky on purpose, like + * [ChatState.error]: a transient store read that fails once must not blink + * off the screen on the next successful tick. + */ + private val _walletChildError = MutableStateFlow(null) + val walletChildError: StateFlow = _walletChildError.asStateFlow() + + /** The stored chain source + binary settings, for prefilling the editor. */ + private val _chainSource = MutableStateFlow(null) + val chainSource: StateFlow = _chainSource.asStateFlow() + + private var walletChildPoller: Job? = null + + /** + * What this install can actually spawn. Read from + * `applicationInfo.nativeLibraryDir` — the only directory Android hands out + * executable — so the screen can say "not bundled" instead of offering a + * Start that can only fail. + */ + fun bundledBinaries(): WalletChildBinaryPaths = + WalletChildBinaries.resolve( + getApplication().applicationInfo.nativeLibraryDir, + ) + + /** + * Starts the one wallet-child refresh loop for the wallet screen. Re-entering + * the screen while the loop is alive is a no-op: navigating to the wallet + * and back must never stack a second poller. + */ + fun openWalletChild() { + if (walletChildPoller?.isActive == true) return + walletChildPoller = viewModelScope.launch { + while (currentCoroutineContext().isActive) { + refreshWalletChild() + delay(WALLET_CHILD_TICK_MS) + } + } + } + + /** Stops the loop when the wallet screen leaves. */ + fun closeWalletChild() { + walletChildPoller?.cancel() + walletChildPoller = null + } + + /** Drops the last failure. The user has acted on it. */ + fun clearWalletChildError() { + _walletChildError.value = null + } + + /** + * One `wallet_status()` read. + * + * `Wire::wallet_status` is synchronous in Rust and re-reads the sealed + * wallet-child record out of the SQLCipher store, so it goes to + * [Dispatchers.IO] — a store decrypt on the main thread is an ANR waiting + * for a slow device. It never dials and never spawns, so a 2s cadence is + * cheap. + */ + suspend fun refreshWalletChild() { + val read = withContext(Dispatchers.IO) { runCatching { requireWire().walletStatus() } } + read.fold( + onSuccess = { _walletChild.value = it }, + onFailure = { _walletChildError.value = it.message ?: it.toString() }, + ) + } + + /** Re-reads the stored chain source so the editor can prefill from it. */ + suspend fun refreshChainSource() { + val read = withContext(Dispatchers.IO) { runCatching { requireWire().chainSource() } } + read.onSuccess { _chainSource.value = it } + } + + /** + * Saves a daemon the user typed, then leaves it to [startWalletChild] to + * spawn against it. `set_chain_source` only stores: the core validates the + * config before anything is written and a rejected config leaves the stored + * one — and any running child — untouched. + * + * [bins] is what this install resolved; the paths handed to the core are + * absolute, because nothing in an APK sandbox resolves a bare + * `monero-wallet-rpc` on `PATH`. + */ + suspend fun saveRemoteDaemon( + host: String, + port: Int, + bins: WalletChildBinaryPaths, + ): Result { + val rpc = bins.walletRpc + ?: return Result.failure(IllegalStateException(NO_WALLET_RPC_MESSAGE)) + return withContext(Dispatchers.IO) { + runCatching { + requireWire().setChainSource( + ChainConfig( + kind = ChainChoice.REMOTE, + monerodBin = "", + monerodDatadir = "", + host = host, + port = port.toUShort(), + walletRpcBin = rpc, + // Inert unless the host is a `.onion`; the screen refuses + // an onion daemon outright while no `arti` is bundled. + artiBin = expectedArtiPath(), + walletFilename = WalletChildBinaries.WALLET_FILENAME, + ), + ) + } + }.onSuccess { + _walletChildError.value = null + refreshChainSource() + refreshWalletChild() + } + } + + /** + * Back to receive-only: no child, no daemon, no chain traffic. The binary + * paths are still stored so switching back to a daemon does not need them + * re-derived. + */ + suspend fun setReceiveOnly(bins: WalletChildBinaryPaths): Result = + withContext(Dispatchers.IO) { + runCatching { + requireWire().setChainSource( + ChainConfig( + kind = ChainChoice.NONE, + monerodBin = "", + monerodDatadir = "", + host = "", + port = 0u, + walletRpcBin = bins.walletRpc.orEmpty(), + artiBin = expectedArtiPath(), + walletFilename = WalletChildBinaries.WALLET_FILENAME, + ), + ) + } + }.onSuccess { + _walletChildError.value = null + refreshChainSource() + refreshWalletChild() + } + + /** + * Spawns the child (and its daemon/SOCKS siblings) and returns what the core + * reached. + * + * The returned state is `connecting` at best on the first call — the wallet + * RPC does not answer the instant the process exists — and that is reported + * as-is. The spawn is synchronous inside the node and a `.onion` source + * waits up to 20s for its SOCKS listener, so this never runs on the main + * thread. + */ + suspend fun startWalletChild(): Result { + _walletChildError.value = null + val started = withContext(Dispatchers.IO) { + runCatching { requireWire().startWalletChild() } + } + started.fold( + onSuccess = { _walletChild.value = it }, + onFailure = { _walletChildError.value = it.message ?: it.toString() }, + ) + return started + } + + /** Stops the child and its siblings. Idempotent in the core. */ + suspend fun stopWalletChild(): Result { + _walletChildError.value = null + val stopped = withContext(Dispatchers.IO) { + runCatching { requireWire().stopWalletChild() } + } + stopped.fold( + onSuccess = { refreshWalletChild() }, + onFailure = { _walletChildError.value = it.message ?: it.toString() }, + ) + return stopped + } + + /** The absolute path the core would be handed for the `arti` SOCKS child. */ + private fun expectedArtiPath(): String = WalletChildBinaries.expectedPath( + getApplication().applicationInfo.nativeLibraryDir, + WalletChildBinaries.ARTI_LIB, + ) } + +/** Cadence of the wallet-child refresh loop, in milliseconds. */ +private const val WALLET_CHILD_TICK_MS: Long = 2_000 diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt new file mode 100644 index 0000000..8ed5faf --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt @@ -0,0 +1,262 @@ +package com.siriusdevops.onionwire.ui + +import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE +import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths + +/** + * One snapshot of the app-owned wallet child, as the wallet screen sees it. + * + * A plain mirror of the fields `WalletChildStatus` carries over UniFFI + * (`state`, `running`, `configured`, `chain_source`, `last_error`) — the same + * shape as `ChatRowInput` / `OutboxRowInput`, so this model and its tests stay + * on the JVM and never load the generated UniFFI types or JNA. + * + * `state` is the core's own word (`src/wallet_child.rs::WalletChildState`): + * `off` / `connecting` / `syncing` / `ready` / `exited`. Nothing here is + * inferred from a timeout, and nothing is invented: a state this build does not + * recognise is reported as unrecognised rather than folded into one that would + * read better. + */ +data class WalletChildInput( + val state: String, + /** A `monero-wallet-rpc` process is alive right now. */ + val running: Boolean, + /** A chain source is configured (anything but receive-only). */ + val configured: Boolean, + /** The core's label: `receive-only` / `local node` / `remote onion daemon` / `remote daemon`. */ + val chainSource: String, + val lastError: String? = null, +) + +/** + * What the wallet screen renders for one snapshot. + * + * The five states are the core's; there is no sixth "starting…". A child that + * was started and is gone is [Exited] — never [Off], and never [Ready]: the + * whole point of the control is that the user can see and drive the child. + * [Unread] is not a state of the child at all, it is the first + * `wallet_status()` read still in flight, and it is a word rather than a + * spinner so a stuck read is readable instead of merely animated. + * + * [testTag] and [contentDescription] are the assertable handles, matching + * `Delivery`: a screen reader gets a sentence, never a bare glyph or a bare + * word. + */ +sealed interface WalletChildPhase { + + /** Stable handle for Compose semantics and tests. */ + val testTag: String + + /** Word drawn on the status line. */ + val label: String + + /** What a screen reader announces. Always a sentence. */ + val contentDescription: String + + /** A child process is up. */ + val live: Boolean + + /** A started child is gone. Never `off`, never `ready`. */ + val dead: Boolean + + /** Nothing read yet. */ + data object Unread : WalletChildPhase { + override val testTag: String = "child-unread" + override val label: String = "reading…" + override val contentDescription: String = "Reading the wallet child status" + override val live: Boolean = false + override val dead: Boolean = false + } + + /** No child has been started, or it was stopped. */ + data object Off : WalletChildPhase { + override val testTag: String = "child-off" + override val label: String = "off" + override val contentDescription: String = "The wallet child is off" + override val live: Boolean = false + override val dead: Boolean = false + } + + /** The process exists; its wallet RPC has not answered yet. */ + data object Connecting : WalletChildPhase { + override val testTag: String = "child-connecting" + override val label: String = "connecting" + override val contentDescription: String = + "The wallet child is up; its wallet RPC has not answered yet" + override val live: Boolean = true + override val dead: Boolean = false + } + + /** The wallet answered; the chain is behind the tip. */ + data object Syncing : WalletChildPhase { + override val testTag: String = "child-syncing" + override val label: String = "syncing" + override val contentDescription: String = + "The wallet is answering; the chain is not at the tip yet" + override val live: Boolean = true + override val dead: Boolean = false + } + + /** Wallet RPC answered and the chain is at the tip. */ + data object Ready : WalletChildPhase { + override val testTag: String = "child-ready" + override val label: String = "ready" + override val contentDescription: String = "The wallet child is ready" + override val live: Boolean = true + override val dead: Boolean = false + } + + /** A started child has died. [reason] is the core's `last_error`, if any. */ + data class Exited(val reason: String?) : WalletChildPhase { + override val testTag: String = "child-exited" + override val label: String = "exited" + override val contentDescription: String = "The wallet child exited" + override val live: Boolean = false + override val dead: Boolean = true + } + + /** + * A state string this build does not know. Fail-closed: it is never + * reported as [Ready], so an unrecognised word cannot read as "wallet + * working". + */ + data class Unrecognised(val raw: String) : WalletChildPhase { + override val testTag: String = "child-unrecognised" + override val label: String = "unknown (${shortSendReason(raw, UNRECOGNISED_BUDGET)})" + override val contentDescription: String = + "The wallet child reported a state this build does not know" + override val live: Boolean = false + override val dead: Boolean = false + } +} + +/** Cells of an unrecognised state word kept on the status line. */ +const val UNRECOGNISED_BUDGET: Int = 16 + +/** + * Maps the core's `state` word onto a [WalletChildPhase]. Case- and + * whitespace-tolerant; anything else is [WalletChildPhase.Unrecognised]. + */ +fun walletChildPhase(input: WalletChildInput?): WalletChildPhase { + if (input == null) return WalletChildPhase.Unread + return when (val state = input.state.trim().lowercase()) { + "off" -> WalletChildPhase.Off + "connecting" -> WalletChildPhase.Connecting + "syncing" -> WalletChildPhase.Syncing + "ready" -> WalletChildPhase.Ready + "exited" -> WalletChildPhase.Exited(input.lastError?.takeIf { it.isNotBlank() }) + else -> WalletChildPhase.Unrecognised(state) + } +} + +/** + * `off · receive-only`, `exited · remote daemon — spawn monero-wallet-rpc: No + * such file or directory`. + * + * The chain-source label is the core's own (`WalletChildStatus.chain_source`), + * rendered verbatim: `receive-only`, `local node`, `remote onion daemon`, + * `remote daemon`. The trailing failure text is the core's `last_error`, cut + * and sanitized by the same rule chat rows use. + */ +fun walletChildLine(input: WalletChildInput?): String { + val phase = walletChildPhase(input) + val source = input?.chainSource?.takeIf { it.isNotBlank() } ?: "no chain source" + val why = input?.lastError?.takeIf { it.isNotBlank() } + return buildString { + append(phase.label) + append(" · ") + append(source) + when { + why != null -> append(" — ").append(shortSendReason(why)) + phase is WalletChildPhase.Exited -> append(" — the child process is gone") + } + } +} + +/** + * A `.onion` daemon is only reachable through the `arti` SOCKS child, and this + * build does not ship one — say that before the user presses Start rather than + * after the spawn fails. + */ +const val ONION_NEEDS_ARTI_NOTICE: String = + "A .onion daemon needs the arti SOCKS child, which this build does not bundle." + +/** Shown while the first `wallet_status()` read is still in flight. */ +const val READING_CHILD_NOTICE: String = "Reading the wallet child status…" + +/** + * Why **Start** is not actionable, or `null` when it is. + * + * Ordered by what the user can act on: a binary this build does not carry is + * not fixable from this screen, a missing chain source is. Every branch names + * the actual condition — there is no generic "starting…" state to hide behind. + */ +fun startBlockedReason( + bins: WalletChildBinaryPaths, + input: WalletChildInput?, + onionDaemon: Boolean = false, +): String? = when { + bins.walletRpc == null -> NO_WALLET_RPC_MESSAGE + input == null -> READING_CHILD_NOTICE + input.running -> "The wallet child is already running." + !input.configured -> "No chain source yet: a wallet child needs a daemon to dial." + onionDaemon && bins.arti == null -> ONION_NEEDS_ARTI_NOTICE + else -> null +} + +/** + * Why **Stop** is not actionable, or `null` when it is. `stop_wallet_child` is + * idempotent in the core, so this is only about not offering a no-op button. + */ +fun stopBlockedReason(input: WalletChildInput?): String? = when { + input == null -> READING_CHILD_NOTICE + !input.running -> "No wallet child is running." + else -> null +} + +/** + * Does this daemon host name a Tor onion service? Mirrors + * `wallet::is_onion_host` — the core's own rule, so the screen and the spawn + * path agree on which daemons need the SOCKS child. + */ +fun isOnionHost(host: String): Boolean = host.trim().lowercase().endsWith(".onion") + +/** + * Parse the one text field the chain-source editor offers (`host:port`) into a + * daemon address, or `null` when it is not one. + * + * Deliberately strict: the core rejects an empty host or port 0 anyway, and a + * silently-guessed port is how a wallet ends up dialing the wrong daemon. An + * IPv6 literal in brackets is accepted; a bare IPv6 address is not, because + * `::1:18089` has no unambiguous split. + */ +fun parseDaemonAddress(raw: String): DaemonAddress? { + val text = raw.trim() + if (text.isEmpty()) return null + val host: String + val portText: String + if (text.startsWith("[")) { + val end = text.indexOf(']') + if (end <= 1) return null + host = text.substring(1, end) + val rest = text.substring(end + 1) + if (!rest.startsWith(":")) return null + portText = rest.substring(1) + } else { + // A bare IPv6 literal has no unambiguous split: `::1:18089` is either + // the host `::1` on 18089 or the host `::1:18089`. Bracket it. + if (text.count { it == ':' } != 1) return null + val cut = text.lastIndexOf(':') + host = text.substring(0, cut) + portText = text.substring(cut + 1) + } + val port = portText.toIntOrNull() ?: return null + if (host.isBlank() || port !in 1..65535) return null + return DaemonAddress(host, port) +} + +/** A daemon address the user typed. */ +data class DaemonAddress(val host: String, val port: Int) { + /** The single-line form the field holds. */ + val text: String get() = "$host:$port" +} 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 bc09ec7..4ea8286 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 @@ -31,6 +31,7 @@ import androidx.compose.material3.TextButton 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 @@ -41,6 +42,9 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale +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.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle @@ -48,10 +52,15 @@ import com.google.zxing.BarcodeFormat import com.google.zxing.EncodeHintType import com.google.zxing.qrcode.QRCodeWriter import com.siriusdevops.onionwire.WireViewModel +import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE +import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch +import uniffi.onionwire_sdk.ChainChoice +import uniffi.onionwire_sdk.ChainConfig import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.TransferRow +import uniffi.onionwire_sdk.WalletChildStatus private enum class PayKind { Invoice, Tip } private enum class SetupKind { Create, Import } @@ -63,7 +72,14 @@ fun WalletScreen( onBack: () -> Unit, ) { val friends by vm.friends.collectAsStateWithLifecycle() + val child by vm.walletChild.collectAsStateWithLifecycle() + val childError by vm.walletChildError.collectAsStateWithLifecycle() + val chain by vm.chainSource.collectAsStateWithLifecycle() val scope = rememberCoroutineScope() + // Resolved once per composition: the native library directory is fixed for + // the life of the process. + val bins = remember { vm.bundledBinaries() } + val childInput = child?.toInput() var showQr by remember { mutableStateOf(false) } var balance by remember { mutableStateOf(null) } var address by remember { mutableStateOf(null) } @@ -72,6 +88,8 @@ fun WalletScreen( var composer by remember { mutableStateOf(null) } var setup by remember { mutableStateOf(null) } var backupSeed by remember { mutableStateOf(null) } + var daemonText by remember { mutableStateOf("") } + var daemonError by remember { mutableStateOf(null) } suspend fun reload() { runCatching { balance = vm.walletBalance() } @@ -80,7 +98,26 @@ fun WalletScreen( runCatching { transfers = vm.walletRecentTransfers(25) } } - LaunchedEffect(Unit) { reload() } + LaunchedEffect(Unit) { + reload() + vm.refreshChainSource() + } + + // The wallet child's 2s refresh loop lives in the ViewModel (like the chat + // poller); this screen only owns its lifetime, so leaving the wallet and + // coming back cannot stack a second loop on the first. + DisposableEffect(Unit) { + vm.openWalletChild() + onDispose { vm.closeWalletChild() } + } + + // Prefill the daemon field from the stored config, never over typing. + LaunchedEffect(chain) { + val stored = chain + if (stored != null && stored.kind == ChainChoice.REMOTE && daemonText.isBlank()) { + daemonText = "${stored.host}:${stored.port}" + } + } Scaffold( // The content root below consumes systemBars ∪ ime itself (see @@ -177,6 +214,43 @@ fun WalletScreen( } } + // The app-owned `monero-wallet-rpc` control. Above the existing + // Create / Import / Invoice / Tip actions, which are untouched: the + // daemon is what makes the balance and the sends mean anything. + WalletChildCard( + bins = bins, + input = childInput, + chain = chain, + actionError = childError, + daemonText = daemonText, + daemonError = daemonError, + onDaemonText = { + daemonText = it + daemonError = null + }, + onSaveDaemon = { + val parsed = parseDaemonAddress(daemonText) + if (parsed == null) { + daemonError = "Type the daemon as host:port, e.g. 127.0.0.1:18089." + } else { + daemonError = null + scope.launch { + vm.saveRemoteDaemon(parsed.host, parsed.port, bins) + .onFailure { daemonError = it.message ?: it.toString() } + } + } + }, + onReceiveOnly = { + daemonError = null + scope.launch { + vm.setReceiveOnly(bins) + .onFailure { daemonError = it.message ?: it.toString() } + } + }, + onStart = { scope.launch { vm.startWalletChild() } }, + onStop = { scope.launch { vm.stopWalletChild() } }, + ) + if (transfers.isNotEmpty()) { Text( "recent transfers", @@ -497,6 +571,176 @@ private fun WalletSetupCard( } } +/** + * The app-owned `monero-wallet-rpc` control (issue #107). + * + * **Start** / **Stop** drive `Wire::start_wallet_child` / `stop_wallet_child` + * through [WireViewModel]; the status line is `Wire::wallet_status()` rendered + * verbatim, so a child that died reads `exited` and never `off`. + * + * The card is deliberately talkative about what it *cannot* do: no bundled + * binary, no chain source, or a `.onion` daemon with no bundled `arti` SOCKS + * child each get their own sentence, because a Start button that can only fail + * is worse than no button. There is no "starting…" state to hide behind — the + * only spinner-free words on screen are the core's own. + */ +@Composable +private fun WalletChildCard( + bins: WalletChildBinaryPaths, + input: WalletChildInput?, + chain: ChainConfig?, + actionError: String?, + daemonText: String, + daemonError: String?, + onDaemonText: (String) -> Unit, + onSaveDaemon: () -> Unit, + onReceiveOnly: () -> Unit, + onStart: () -> Unit, + onStop: () -> Unit, +) { + val phase = walletChildPhase(input) + val onionDaemon = chain?.kind == ChainChoice.REMOTE && isOnionHost(chain.host) + val startWhy = startBlockedReason(bins, input, onionDaemon) + val stopWhy = stopBlockedReason(input) + + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("wallet daemon", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(6.dp)) + + // The core's own words: `ready · remote onion daemon`. Tagged with + // the phase so a UI test can assert `exited` is never `off`. + Text( + walletChildLine(input), + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + modifier = Modifier + .fillMaxWidth() + .testTag(phase.testTag) + .semantics(mergeDescendants = true) { + contentDescription = "${phase.contentDescription}. ${walletChildLine(input)}" + }, + ) + + if (!bins.walletRpcBundled) { + Spacer(Modifier.height(6.dp)) + Text( + NO_WALLET_RPC_MESSAGE, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.fillMaxWidth(), + ) + } + + // What the user can fix from here: which daemon the child dials. + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = daemonText, + onValueChange = onDaemonText, + singleLine = true, + label = { Text("daemon host:port") }, + supportingText = { + Text( + "e.g. 127.0.0.1:18089 for a local daemon you run yourself, " + + "or a node's clearnet address.", + style = MaterialTheme.typography.labelSmall, + ) + }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-daemon-input"), + ) + Spacer(Modifier.height(4.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedButton( + onClick = onSaveDaemon, + enabled = bins.walletRpcBundled, + modifier = Modifier + .weight(1f) + .testTag("wallet-daemon-save"), + ) { Text("Save daemon") } + OutlinedButton( + onClick = onReceiveOnly, + modifier = Modifier + .weight(1f) + .testTag("wallet-daemon-receive-only"), + ) { Text("Receive-only") } + } + + Spacer(Modifier.height(8.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Button( + onClick = onStart, + enabled = startWhy == null, + modifier = Modifier + .weight(1f) + .testTag("wallet-child-start"), + ) { Text("Start wallet") } + OutlinedButton( + onClick = onStop, + enabled = stopWhy == null, + modifier = Modifier + .weight(1f) + .testTag("wallet-child-stop"), + ) { Text("Stop wallet") } + } + + // Why Start is dead, in the core's terms rather than a grey button. + startWhy?.let { + Spacer(Modifier.height(6.dp)) + Text( + it, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-child-start-blocked"), + ) + } + + // The last thing the core or the RPC call said. Sticky until the + // user acts, like the chat screen's load error. + val failure = input?.lastError ?: actionError ?: daemonError + failure?.let { + Spacer(Modifier.height(6.dp)) + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-child-error"), + ) + } + } + } +} + +/** + * The SDK record as the pure model `WalletChildStatusText.kt` renders. Field for + * field, nothing inferred. + */ +internal fun WalletChildStatus.toInput(): WalletChildInput = WalletChildInput( + state = state, + running = running, + configured = configured, + chainSource = chainSource, + lastError = lastError, +) + /** 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/android/app/src/main/java/com/siriusdevops/onionwire/wallet/WalletChildBinaries.kt b/android/app/src/main/java/com/siriusdevops/onionwire/wallet/WalletChildBinaries.kt new file mode 100644 index 0000000..b9292a6 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/wallet/WalletChildBinaries.kt @@ -0,0 +1,101 @@ +package com.siriusdevops.onionwire.wallet + +import java.io.File + +/** + * The app-owned wallet-child executables, as the APK actually carries them. + * + * **Why `jniLibs` and not an asset.** Since Android 10 (API 29) an app may not + * `exec()` a file it wrote into its own data directory: the SELinux policy has + * no `execute` on `app_data_file`, so `filesDir/libmonerowalletrpc.so` copied + * out of `assets/` with the exec bit set is still refused by the kernel — the + * classic "copy it to app-private storage" recipe died with `targetSdk 29`. + * The one directory Android does hand out executable is + * `ApplicationInfo.nativeLibraryDir`: the package manager unpacks the + * `lib//` entries from the APK there at install time with the exec bit + * intact. A plain + * executable therefore has to be named `lib*.so` and shipped through + * `jniLibs`, and that unpack only happens when the manifest says + * `android:extractNativeLibs="true"` (`packaging.jniLibs.useLegacyPackaging` + * in `app/build.gradle.kts`). With `extractNativeLibs="false"` — the AGP 8 + * default — the `.so` stays inside the APK and there is nothing on disk to run. + * + * The names here are the paths handed to the core as `ChainConfig.wallet_rpc_bin` + * and `ChainConfig.arti_bin`; the core spawns exactly the path it is given and + * never falls back to `PATH` (nothing in an APK sandbox resolves a bare + * `monero-wallet-rpc`). + */ +object WalletChildBinaries { + + /** `jniLibs//` entry name for `monero-wallet-rpc`. */ + const val WALLET_RPC_LIB: String = "libmonerowalletrpc.so" + + /** + * Wallet file name inside `$ONIONWIRE_HOME/wallet`. Mirrors the core's + * `wallet::DEFAULT_WALLET_FILENAME`, so a config saved from here and a + * config the core defaults to name the same file. + */ + const val WALLET_FILENAME: String = "onionwire" + + /** + * `jniLibs//` entry name for the `arti` SOCKS child. **Not bundled in + * this build** — a `.onion` daemon needs a separate Rust binary, which is a + * follow-up (see `android/MONERO_BINARIES.md`). The constant exists so the + * screen can name the path it would use, and so the absence is checkable + * rather than assumed. + */ + const val ARTI_LIB: String = "libarti.so" + + /** + * Resolve the bundled binaries under [nativeLibraryDir]. + * + * A null/blank directory (or a missing file) means this install does not + * carry the binary — the screen says so instead of offering a Start that + * can only fail. + */ + fun resolve(nativeLibraryDir: String?): WalletChildBinaryPaths = + WalletChildBinaryPaths( + walletRpc = existing(nativeLibraryDir, WALLET_RPC_LIB), + arti = existing(nativeLibraryDir, ARTI_LIB), + ) + + /** + * The absolute path the core is handed for an entry, whether or not the + * file is present. + * + * Used for `arti_bin` on a clearnet/loopback daemon: the core validates + * that `arti_bin` is non-empty for any non-receive-only source but only + * ever spawns it for a `.onion` host, so the value is inert there. Naming + * the path the binary *would* occupy is deliberate — passing a real binary + * that is not `arti` (say, `monero-wallet-rpc`) would be spawned as the + * SOCKS child the moment the user typed an `.onion` host, which is worse + * than an honest `ENOENT`. + */ + fun expectedPath(nativeLibraryDir: String?, entry: String): String { + val dir = nativeLibraryDir?.takeIf { it.isNotBlank() } ?: return "" + return File(dir, entry).absolutePath + } + + private fun existing(nativeLibraryDir: String?, entry: String): String? { + val dir = nativeLibraryDir?.takeIf { it.isNotBlank() } ?: return null + val file = File(dir, entry) + return if (file.isFile) file.absolutePath else null + } +} + +/** What this install can actually spawn. */ +data class WalletChildBinaryPaths( + val walletRpc: String?, + val arti: String?, +) { + val walletRpcBundled: Boolean get() = walletRpc != null + val artiBundled: Boolean get() = arti != null +} + +/** + * Shown when this install carries no `monero-wallet-rpc`. One string, used by + * both the status line and the Start gate, so the two can never disagree about + * why the button is dead. + */ +const val NO_WALLET_RPC_MESSAGE: String = + "monero-wallet-rpc is not bundled in this build, so there is nothing to start." diff --git a/android/app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so b/android/app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so new file mode 100755 index 0000000..1d1f151 Binary files /dev/null and b/android/app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so differ diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt new file mode 100644 index 0000000..8603173 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt @@ -0,0 +1,243 @@ +package com.siriusdevops.onionwire.ui + +import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE +import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The wallet-child status line the screen renders from + * `Wire::wallet_status()`. + * + * These assert the pure model — the same shape as `MessageDeliveryTest` and + * `OutboxDetailTest` — so the rules that matter are covered on the JVM without + * a device: every core state has its own word, a died child never reads as + * `off` and never as `ready`, an unknown state is never `ready`, and Start is + * only offered when there is something to spawn. + */ +class WalletChildStatusTextTest { + + private fun input( + state: String, + running: Boolean = false, + configured: Boolean = true, + chainSource: String = "remote daemon", + lastError: String? = null, + ) = WalletChildInput( + state = state, + running = running, + configured = configured, + chainSource = chainSource, + lastError = lastError, + ) + + private val bundled = WalletChildBinaryPaths(walletRpc = "/lib/libmonerowalletrpc.so", arti = null) + private val noBinary = WalletChildBinaryPaths(walletRpc = null, arti = null) + + // --- every core state has its own word --------------------------------- + + @Test + fun each_core_state_maps_to_its_own_phase() { + assertTrue(walletChildPhase(input("off")) is WalletChildPhase.Off) + assertTrue(walletChildPhase(input("connecting")) is WalletChildPhase.Connecting) + assertTrue(walletChildPhase(input("syncing")) is WalletChildPhase.Syncing) + assertTrue(walletChildPhase(input("ready")) is WalletChildPhase.Ready) + assertTrue(walletChildPhase(input("exited")) is WalletChildPhase.Exited) + } + + @Test + fun nothing_read_yet_is_not_off() { + val phase = walletChildPhase(null) + assertTrue(phase is WalletChildPhase.Unread) + assertEquals("reading…", phase.label) + } + + @Test + fun state_matching_tolerates_case_and_padding() { + assertTrue(walletChildPhase(input(" READY ")) is WalletChildPhase.Ready) + assertTrue(walletChildPhase(input("Exited")) is WalletChildPhase.Exited) + } + + // --- a died child is never "off" and never "ready" --------------------- + + @Test + fun exited_is_its_own_state_and_never_off_or_ready() { + val phase = walletChildPhase(input("exited", lastError = "spawn monero-wallet-rpc: No such file")) + assertTrue(phase is WalletChildPhase.Exited) + assertTrue("a died child is dead", phase.dead) + assertFalse("a died child is not off", phase is WalletChildPhase.Off) + assertFalse("a died child is not ready", phase is WalletChildPhase.Ready) + assertFalse("a died child is not live", phase.live) + } + + @Test + fun exited_keeps_the_cores_reason() { + val phase = walletChildPhase(input("exited", lastError = "child exited with status 1")) + assertEquals("child exited with status 1", (phase as WalletChildPhase.Exited).reason) + } + + // --- an unknown state is never ready ----------------------------------- + + @Test + fun an_unknown_state_is_never_ready() { + val phase = walletChildPhase(input("wobbling")) + assertTrue(phase is WalletChildPhase.Unrecognised) + assertFalse("an unknown state must not read as ready", phase is WalletChildPhase.Ready) + assertTrue(phase.label.startsWith("unknown")) + } + + @Test + fun an_unknown_state_word_is_cut_and_sanitized() { + val raw = "wobbling\u0000\u0007" + "x".repeat(80) + val phase = walletChildPhase(input(raw)) as WalletChildPhase.Unrecognised + assertFalse("controls must not reach the screen", phase.label.contains('\u0000')) + assertTrue("the word is capped", phase.label.length < raw.length) + } + + // --- the status line names the chain source ---------------------------- + + @Test + fun the_line_names_the_chain_source_the_core_reported() { + assertEquals("off · receive-only", walletChildLine(input("off", chainSource = "receive-only"))) + assertEquals( + "ready · remote onion daemon", + walletChildLine(input("ready", running = true, chainSource = "remote onion daemon")), + ) + assertEquals( + "connecting · local node", + walletChildLine(input("connecting", running = true, chainSource = "local node")), + ) + } + + @Test + fun the_line_says_when_there_is_no_chain_source() { + assertEquals("off · no chain source", walletChildLine(input("off", chainSource = " "))) + } + + @Test + fun the_line_carries_the_cores_failure_text() { + val line = walletChildLine( + input("off", lastError = "spawn monero-wallet-rpc: Permission denied"), + ) + assertTrue(line, line.contains("Permission denied")) + assertTrue("the state word survives", line.startsWith("off · ")) + } + + @Test + fun an_exited_child_with_no_reason_still_says_it_is_gone() { + val line = walletChildLine(input("exited", lastError = null)) + assertTrue(line, line.contains("gone")) + } + + @Test + fun a_long_failure_text_is_cut_like_a_chat_row() { + val line = walletChildLine(input("off", lastError = "a: b: " + "y".repeat(400))) + assertTrue(line, line.length < 120) + } + + // --- Start is only offered when there is something to spawn ------------ + + @Test + fun start_is_blocked_when_the_build_carries_no_binary() { + val why = startBlockedReason(noBinary, input("off")) + assertEquals(NO_WALLET_RPC_MESSAGE, why) + } + + @Test + fun start_is_blocked_before_the_first_read() { + assertEquals(READING_CHILD_NOTICE, startBlockedReason(bundled, null)) + } + + @Test + fun start_is_blocked_with_no_chain_source() { + val why = startBlockedReason(bundled, input("off", configured = false, chainSource = "receive-only")) + assertNotNull(why) + assertTrue(why!!, why.contains("chain source")) + } + + @Test + fun start_is_blocked_while_the_child_is_already_running() { + val why = startBlockedReason(bundled, input("ready", running = true)) + assertNotNull(why) + assertTrue(why!!, why.contains("already running")) + } + + @Test + fun start_is_blocked_for_an_onion_daemon_without_the_socks_child() { + val why = startBlockedReason(bundled, input("off"), onionDaemon = true) + assertEquals(ONION_NEEDS_ARTI_NOTICE, why) + } + + @Test + fun start_is_allowed_for_a_clearnet_daemon_with_the_binary_present() { + assertNull(startBlockedReason(bundled, input("off"))) + } + + @Test + fun start_is_allowed_again_after_the_child_exited() { + assertNull( + "a died child must be restartable", + startBlockedReason(bundled, input("exited", lastError = "child exited with status 1")), + ) + } + + // --- Stop --------------------------------------------------------------- + + @Test + fun stop_is_blocked_when_nothing_is_running() { + assertTrue(stopBlockedReason(input("off"))!!.contains("No wallet child")) + assertTrue(stopBlockedReason(input("exited"))!!.contains("No wallet child")) + assertEquals(READING_CHILD_NOTICE, stopBlockedReason(null)) + } + + @Test + fun stop_is_allowed_while_a_child_is_up() { + assertNull(stopBlockedReason(input("connecting", running = true))) + assertNull(stopBlockedReason(input("syncing", running = true))) + assertNull(stopBlockedReason(input("ready", running = true))) + } + + // --- onion detection mirrors the core ---------------------------------- + + @Test + fun onion_detection_matches_the_cores_rule() { + assertTrue(isOnionHost("abcdefghijklmnop.onion")) + assertTrue(isOnionHost("ABCDEFGH.ONION")) + assertTrue(isOnionHost(" abcdefgh.onion ")) + assertFalse(isOnionHost("onion.example.com")) + assertFalse(isOnionHost("127.0.0.1")) + assertFalse(isOnionHost("node.onion.example.com")) + } + + // --- the daemon address field ------------------------------------------ + + @Test + fun daemon_address_parses_host_and_port() { + assertEquals(DaemonAddress("127.0.0.1", 18089), parseDaemonAddress("127.0.0.1:18089")) + assertEquals(DaemonAddress("abc.onion", 18081), parseDaemonAddress(" abc.onion:18081 ")) + assertEquals(DaemonAddress("node.example.com", 18089), parseDaemonAddress("node.example.com:18089")) + assertEquals(DaemonAddress("::1", 18089), parseDaemonAddress("[::1]:18089")) + } + + @Test + fun daemon_address_rejects_what_it_cannot_split_honestly() { + assertNull(parseDaemonAddress("")) + assertNull(parseDaemonAddress("node.example.com")) + assertNull(parseDaemonAddress(":18089")) + assertNull(parseDaemonAddress("node.example.com:")) + assertNull(parseDaemonAddress("node.example.com:0")) + assertNull(parseDaemonAddress("node.example.com:70000")) + assertNull(parseDaemonAddress("node.example.com:eight")) + assertNull("a bare IPv6 has no unambiguous split", parseDaemonAddress("::1:18089")) + } + + @Test + fun daemon_address_round_trips_through_its_text_form() { + val parsed = parseDaemonAddress("127.0.0.1:18089")!! + assertEquals("127.0.0.1:18089", parsed.text) + } +} diff --git a/android/monero-binaries.sha256 b/android/monero-binaries.sha256 new file mode 100644 index 0000000..c3557f1 --- /dev/null +++ b/android/monero-binaries.sha256 @@ -0,0 +1 @@ +d9126788030ecd1ccdb40c7764e66e9a14d158a147ad335b256f0577681b5ad4 app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so diff --git a/scripts/build-android-local.sh b/scripts/build-android-local.sh index 006d2bf..5731afc 100755 --- a/scripts/build-android-local.sh +++ b/scripts/build-android-local.sh @@ -45,6 +45,19 @@ fi abi="${ONIONWIRE_ANDROID_ABI:-arm64-v8a}" +# --------------------------------------------------------------------------- +# Bundled native executables. CI must not take a committed blob on trust: the +# wallet screen runs `monero-wallet-rpc` straight out of the APK's `lib//`, +# so a corrupted or swapped blob is a wallet-level problem rather than a +# build-level one. `android/monero-binaries.sha256` is the provenance record +# (see android/MONERO_BINARIES.md); this re-verifies it before every build, and +# again against the bytes that ended up inside the APK, below. +# --------------------------------------------------------------------------- +BINARY_MANIFEST="android/monero-binaries.sha256" +[ -f "$BINARY_MANIFEST" ] || { echo "missing $BINARY_MANIFEST" >&2; exit 1; } +echo "==> verifying bundled native executables against $BINARY_MANIFEST" +( cd android && sha256sum -c "$(basename "$BINARY_MANIFEST")" ) + echo "==> android build: version $version (versionCode $ONIONWIRE_VERSION_CODE), abi $abi" ( cd android && "./gradlew" --no-daemon \ "-Ponionwire.abis=$abi" \ @@ -77,6 +90,20 @@ done echo "==> verify" ( cd dist && sha256sum -c ./*.sha256 ) file "$apk" "$aar" + +# The bytes inside the shipped APK, not the bytes we hoped we copied. An AGP +# strip pass would rewrite `lib//*.so` between jniLibs and the APK, which +# is why `app/build.gradle.kts` keeps debug symbols for this one entry. +echo "==> bundled wallet binary inside the APK" +bundled_sha="$(unzip -p "$apk" "lib/$abi/libmonerowalletrpc.so" | sha256sum | cut -d' ' -f1)" +committed_sha="$(sha256sum "android/app/src/main/jniLibs/$abi/libmonerowalletrpc.so" | cut -d' ' -f1)" +unzip -l "$apk" | grep "lib/$abi/" || true +echo "lib/$abi/libmonerowalletrpc.so sha256=$bundled_sha (committed $committed_sha)" +[ "$bundled_sha" = "$committed_sha" ] || { + echo "the APK's bundled binary does not match the committed blob" >&2 + exit 1 +} + ls -l "$apk" "$aar" "$apk.sha256" "$aar.sha256" if [ -n "${PUBLISH_TAG:-}" ]; then diff --git a/scripts/build-monero-wallet-rpc-android.sh b/scripts/build-monero-wallet-rpc-android.sh new file mode 100755 index 0000000..249a971 --- /dev/null +++ b/scripts/build-monero-wallet-rpc-android.sh @@ -0,0 +1,173 @@ +#!/usr/bin/env bash +# +# Reproduce the bundled `monero-wallet-rpc` for Android (arm64-v8a). +# +# This is the command behind `android/app/src/main/jniLibs/arm64-v8a/ +# libmonerowalletrpc.so` and `android/MONERO_BINARIES.md`. It is deliberately +# NOT part of the CI path: building Monero's C++ tree for Android is a +# ~30-45 min job on 12 cores and CI here runs on an arm64 Raspberry Pi. CI +# re-verifies the committed blob's checksum instead (see +# `scripts/build-android-local.sh`); this script is how that blob is produced +# and how a reviewer re-derives it. +# +# Monero ships no Android binaries and no Android CMake preset, so this uses +# upstream's own cross-compile path: `contrib/depends` (which builds boost, +# openssl, libunbound, libzmq, libsodium, ncurses and readline for the target) +# plus the toolchain.cmake it emits. +# +# Usage: +# scripts/build-monero-wallet-rpc-android.sh [workdir] +# +# Output: +# /monero-src/build/aarch64-linux-android/release/bin/monero-wallet-rpc +# +# Requirements (all host-side): git, make, cmake 3.2x (NOT 4.x — see below), +# unzip, curl, python3, a JDK-free C/C++ host toolchain (gcc/clang), ~15 GB free. +set -euo pipefail + +MONERO_TAG="${MONERO_TAG:-v0.18.4.4}" +WORKDIR="${1:-${HOME}/.hermes/tmp/monero-src}" +JOBS="${JOBS:-$(nproc)}" +# NDK r17b is what `contrib/depends/packages/android_ndk.mk` pins; it downloads +# and unpacks it itself. Nothing here uses the Gradle-side NDK. +NDK_ABI_DIR="aarch64-linux-android" + +root="$(cd "$(dirname "$0")/.." && pwd)" +cd "$root" + +echo "==> monero $MONERO_TAG -> $WORKDIR ($JOBS jobs)" + +# --------------------------------------------------------------------------- +# 0. cmake 3.x. CMake 4.x removed the standalone-NDK-toolchain handling that +# `contrib/depends`' generated toolchain.cmake relies on; with 4.x the +# configure step picks the HOST clang and dies on `--target=` link flags. +# --------------------------------------------------------------------------- +CMAKE_BIN="${CMAKE_BIN:-cmake}" +if ! "$CMAKE_BIN" --version | head -1 | grep -qE 'version 3\.'; then + echo "==> host cmake is not 3.x; installing 3.22.6 into $WORKDIR/../cmakevenv" + python3 -m venv "$WORKDIR/../cmakevenv" >/dev/null 2>&1 || true + "$WORKDIR/../cmakevenv/bin/pip" install -q "cmake==3.22.6" + CMAKE_BIN="$WORKDIR/../cmakevenv/bin/cmake" +fi +"$CMAKE_BIN" --version | head -1 + +# --------------------------------------------------------------------------- +# 1. Source, at the tag. Submodules are mandatory: the configure step refuses +# to run without external/miniupnp (and randomx/rapidjson/supercop build). +# --------------------------------------------------------------------------- +if [ ! -d "$WORKDIR/.git" ]; then + git clone --depth 1 --branch "$MONERO_TAG" \ + https://github.com/monero-project/monero.git "$WORKDIR" +fi +git -C "$WORKDIR" submodule update --init --force --depth 1 + +# --------------------------------------------------------------------------- +# 2. Host quirk: the NDK r17b standalone toolchain's prebuilt `clang60` is +# linked against ncurses 5 (`libtinfo.so.5`). Debian bookworm, Arch and +# everything else current ships ncurses 6 only, so the compiler refuses to +# start with "error while loading shared libraries: libtinfo.so.5". ncurses +# 6 is ABI-compatible for what clang uses terminfo for; a shim directory is +# enough, and it is scoped to this build via LD_LIBRARY_PATH. +# --------------------------------------------------------------------------- +compat="$WORKDIR/../ndk17-compat" +mkdir -p "$compat" +if [ ! -e "$compat/libtinfo.so.5" ]; then + for cand in /usr/lib/libtinfo.so.6 \ + /usr/lib/x86_64-linux-gnu/libtinfo.so.6 \ + /usr/lib64/libtinfo.so.6 \ + /lib/x86_64-linux-gnu/libtinfo.so.6; do + if [ -e "$cand" ]; then + ln -sf "$cand" "$compat/libtinfo.so.5" + break + fi + done +fi +if [ ! -e "$compat/libtinfo.so.5" ]; then + echo "!! no libtinfo.so.6 found to shim libtinfo.so.5; NDK r17b clang will not run" >&2 + exit 1 +fi +export LD_LIBRARY_PATH="$compat${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" + +# The card's rule for this host: never build C in /tmp (16 GB tmpfs with a +# per-user quota — "Disk quota exceeded" mid-build looks like a protocol bug). +export TMPDIR="${TMPDIR:-$WORKDIR/../monero-build-tmp}" +mkdir -p "$TMPDIR" + +# --------------------------------------------------------------------------- +# 3. The dependencies, cross-built for the target. ~20 min. +# --------------------------------------------------------------------------- +make -C "$WORKDIR/contrib/depends" HOST="$NDK_ABI_DIR" -j"$JOBS" + +# --------------------------------------------------------------------------- +# 3b. The toolchain.cmake depends emits sets +# SET(CMAKE_FIND_ROOT_PATH /usr) +# and /usr is the HOST. `CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY` does not +# save you: /usr is a root, so `find_library()` happily returns host +# libraries. That bites twice in this tree: +# * monero's optional zmq extras (pgm, norm, gssapi_krb5, protolib, bsd, +# md, protokit) get host paths appended to ZMQ_LIB, and the final link +# dies with `/usr/lib/libpgm.so: error adding symbols: File in wrong +# format` — a host x86-64 .so in an aarch64 link line; +# * `find_package(HIDAPI)` succeeds against the host hidapi, defines +# HAVE_HIDAPI, and src/device then fails to compile `hidapi/hidapi.h`. +# Nothing under /usr is a valid Android target library, so drop it. This is +# also what upstream's `make depends target=aarch64-linux-android` silently +# relies on: it only works on a build host that happens to have none of +# these installed. +# --------------------------------------------------------------------------- +prefix="$WORKDIR/contrib/depends/$NDK_ABI_DIR" +tc="$prefix/share/toolchain.cmake" +cp "$tc" "$tc.orig" +sed -i -E "s|^SET\(CMAKE_FIND_ROOT_PATH .*|SET(CMAKE_FIND_ROOT_PATH ${prefix})|" "$tc" +grep -qF "SET(CMAKE_FIND_ROOT_PATH ${prefix})" "$tc" \ + || { echo "could not pin CMAKE_FIND_ROOT_PATH in $tc" >&2; exit 1; } + +# --------------------------------------------------------------------------- +# 4. Configure with the toolchain depends just emitted, then build ONLY the +# wallet RPC. The CMake target is `wallet_rpc_server`; the binary it emits is +# `monero-wallet-rpc`. (`make monero-wallet-rpc` is not a target and fails +# with "No rule to make target".) +# --------------------------------------------------------------------------- +builddir="$WORKDIR/build/$NDK_ABI_DIR/release" +rm -rf "$builddir" +mkdir -p "$builddir" +( + cd "$builddir" + # `-U` on the optional-library cache entries is belt-and-braces for a reused + # build dir: a cache written before the toolchain patch still holds the host + # paths, and a stale cache is invisible until the link step. + "$CMAKE_BIN" \ + -DCMAKE_TOOLCHAIN_FILE="$tc" \ + -DBUILD_TESTS=OFF \ + -DBUILD_DOCUMENTATION=OFF \ + -DCMAKE_BUILD_TYPE=Release \ + -U PGM_LIBRARY -U NORM_LIBRARY -U GSSAPI_LIBRARY -U PROTOLIB_LIBRARY \ + -U SODIUM_LIBRARY -U BSD_LIBRARY -U MD_LIBRARY -U PROTOKIT_LIBRARY \ + -U ZMQ_LIB -U ZMQ_INCLUDE_PATH -U HIDAPI_LIBRARY -U HIDAPI_INCLUDE_DIR \ + "$WORKDIR" + make wallet_rpc_server -j"$JOBS" +) + +bin="$builddir/bin/monero-wallet-rpc" +[ -s "$bin" ] || { echo "missing $bin" >&2; exit 1; } + +# --------------------------------------------------------------------------- +# 5. Strip with the target's own strip, then verify the shape. +# --------------------------------------------------------------------------- +strip_bin="$WORKDIR/contrib/depends/$NDK_ABI_DIR/native/bin/${NDK_ABI_DIR}-strip" +[ -x "$strip_bin" ] && "$strip_bin" "$bin" || true + +echo "==> $bin" +file "$bin" +wc -c "$bin" +sha256sum "$bin" + +echo +echo "==> to package it into the APK:" +echo " cp '$bin' android/app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so" +echo " # then update android/monero-binaries.sha256 and android/MONERO_BINARIES.md" +echo +echo "NOTE: a Monero build is not bit-reproducible (build paths and timestamps" +echo " land in the binary), so a fresh run will NOT match the committed" +echo " sha256. That hash is a provenance record of the shipped blob and the" +echo " thing CI verifies — not a reproducible-build assertion."