From e6b6bc8dd6abd4700df55ac8468396c7601e7043 Mon Sep 17 00:00:00 2001 From: sirius Date: Fri, 18 Sep 2026 15:34:30 -0400 Subject: [PATCH] android: build the SDK with cuprate-daemon and offer the on-device node MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part 3 of "cuprated built in": the chain daemon now ships inside the APK and the wallet screen can pick it. Build (android/sdk/build.gradle.kts) - `cargoBuildAndroid` runs `cargo ndk … build --release --lib --features cuprate-daemon`. The Android target only: `cargoHostLib` / `uniffiBindgen` stay feature-free, because the host cdylib exists only so `uniffi-bindgen --library` can dlopen it and the UniFFI surface does not fork on a cargo feature. - The link needs the NDK's libc++ and compiler-rt builtins explicitly (RandomX is C++ and its aarch64 JIT calls `__clear_cache`; `randomx-rs` links the NDK's stub `libstdc++.a`). `cargo ndk --link-builtins` covers the builtins only, so the whole set is spelled out as per-ABI `CARGO_TARGET__RUSTFLAGS` — a global `RUSTFLAGS` would break the host build scripts. The linker is the NDK clang driver at the app's API level, named explicitly, because the dev machines pin the API 21 wrapper for `aarch64-linux-android` and API 21 fails this link. - `ANDROID_NDK` is exported alongside `ANDROID_NDK_HOME`/`NDK_HOME`: without it `cmake-rs` aborts and `randomx-rs`'s build script panics. - The task logs the feature it builds with, so CI carries the request, not just the task name. Wallet screen - Third chain source, **On-device node (Cuprate)**, beside the daemon field and Receive-only. Stored as `ChainChoice.InProcessCuprate` with an empty `monerod_datadir`, which the SDK resolves to `$ONIONWIRE_HOME/chain`. Existing Save daemon / Receive-only / Start / Stop behaviour is unchanged. - The status line grows `· node ` from `WalletChildStatus.node_state` for this source only, fail-closed on an unrecognised word. No sync height: the SDK exposes none, so the screen does not show a number it cannot get. - Storage honesty: free space on the chain store's filesystem, and Start is refused below a 3 GiB floor or when that filesystem cannot be read. The floor is a floor, not a sync estimate — nothing here exposes one. - The pre-production warning (quoted user book, testnet only, Cuprate issue #278) is a sentence above Start, assertable in a test. Opt-in, never a default. - The daemon field's hint no longer suggests a loopback daemon on the phone. CI - `android-ci.yml` extracts `lib//libonionwire_sdk.so` from the built APK and fails the job unless it contains `target_max_memory`, a rodata literal compiled only under `cuprate-daemon`. v0.7.0's shipped `.so` has zero of them, so this separates "in the artifact" from "requested". Docs - `android/CUPRATE_DAEMON.md`: the build wiring, the link line, the CI gate, and an explicit "not verified on a device" section. `MONERO_BINARIES.md` points at it for the chain source that is not a binary. --- .forgejo/workflows/android-ci.yml | 15 ++ android/CUPRATE_DAEMON.md | 157 ++++++++++++++ android/MONERO_BINARIES.md | 10 + .../siriusdevops/onionwire/WireViewModel.kt | 43 ++++ .../onionwire/ui/WalletChildStatusText.kt | 196 ++++++++++++++++++ .../siriusdevops/onionwire/ui/WalletScreen.kt | 101 ++++++++- .../onionwire/wallet/ChainStorage.kt | 30 +++ .../onionwire/ui/WalletChildStatusTextTest.kt | 134 ++++++++++++ android/sdk/build.gradle.kts | 132 +++++++++++- 9 files changed, 807 insertions(+), 11 deletions(-) create mode 100644 android/CUPRATE_DAEMON.md create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/wallet/ChainStorage.kt diff --git a/.forgejo/workflows/android-ci.yml b/.forgejo/workflows/android-ci.yml index 9417544..94aeaeb 100644 --- a/.forgejo/workflows/android-ci.yml +++ b/.forgejo/workflows/android-ci.yml @@ -161,6 +161,21 @@ jobs: echo "=== unzip lib ===" unzip -l "$apk" | grep -E 'lib/.+\.so' || true unzip -l "$apk" | grep "lib/$abi/libonionwire_sdk.so" + echo "=== in-process chain daemon (cuprate-daemon) is IN this APK ===" + # The build log's "features=cuprate-daemon" line says the feature was + # *requested*; this says it is *in the artifact*. `target_max_memory` is + # a rodata literal from src/cuprate.rs's config TOML, compiled only under + # `#[cfg(feature = "cuprate-daemon")]` — v0.7.0's libonionwire_sdk.so + # contains zero occurrences of it (checked), so its presence is the + # difference between a build that carries the daemon and one that only + # claims to. A missing marker fails the job: an APK whose on-device node + # can only fail is the regression this gate exists to catch. + unzip -p "$apk" "lib/$abi/libonionwire_sdk.so" > /tmp/libonionwire_sdk.so + strings -a /tmp/libonionwire_sdk.so | grep -c 'target_max_memory' || true + if ! strings -a /tmp/libonionwire_sdk.so | grep -q 'target_max_memory'; then + echo "lib/$abi/libonionwire_sdk.so carries no cuprated config string: the cuprate-daemon feature is NOT in this APK" >&2 + exit 1 + fi echo "=== classes.dex + Compose entrypoints ===" unzip -l "$apk" | grep -E 'classes[0-9]*\.dex' | head -n3 echo "=== sha256 ===" diff --git a/android/CUPRATE_DAEMON.md b/android/CUPRATE_DAEMON.md new file mode 100644 index 0000000..6b426d0 --- /dev/null +++ b/android/CUPRATE_DAEMON.md @@ -0,0 +1,157 @@ +# The in-process chain daemon (`cuprate-daemon`) in the APK + +The wallet's third chain source — Cuprate's chain daemon running **inside the +OnionWire process** — is compiled into the Android build. This document is the +provenance record for that: how the feature is enabled, why the link line looks +the way it does, what CI checks, and what has *not* been proven. + +Companion reading: `docs/WALLET.md` ("The in-process chain daemon") for what the +daemon is, `docs/cuprate-android-spike.md` for the cross-compile spike this +plumbing comes from, and `MONERO_BINARIES.md` for the `monero-wallet-rpc` +executable, which is still a child process — Cuprate has no wallet layer. + +## What changed in the build + +`android/sdk/build.gradle.kts`: + +| | | +|---|---| +| Feature | `--features cuprate-daemon` on the **Android** build only | +| Where | `cargoBuildAndroid` (the `cargo ndk` cross-compile) | +| Not where | `cargoHostLib` / `uniffiBindgen` stay feature-free | + +The host cdylib exists only so `uniffi-bindgen --library` can dlopen it. Building +the Cuprate graph there would add ~152 crates and a C++ RandomX build to every +build for a library that never runs the daemon, and the UniFFI surface does not +fork on a cargo feature (`ChainChoice.InProcessCuprate` is present either way, and +`WalletChildStatus` carries the same fields) — so the generated Kotlin bindings are +the same bytes. + +`cargoBuildAndroid` prints the feature it is building with, so the CI log carries +the request rather than only the task name: + +``` +cargo ndk build for arm64-v8a features=cuprate-daemon api=26 ndk=28.2.13676358 +``` + +## The link line + +RandomX is C++ and its aarch64 JIT calls `__clear_cache`, and `randomx-rs`'s build +script emits `rustc-link-lib=static=stdc++` against the NDK's *stub* +`libstdc++.a`. Without libc++ and the compiler-rt builtins the link fails on +`__cxa_allocate_exception` / `std::runtime_error` / `typeinfo` / `__clear_cache`. +`cargo ndk --link-builtins` covers the builtins but not libc++, and +`-static-libstdc++` is ignored by NDK clang, so the full set is spelled out: + +``` +-L$NDK/toolchains/llvm/prebuilt//sysroot/usr/lib/ +-L$NDK/toolchains/llvm/prebuilt//lib/clang//lib/linux +-lclang_rt.builtins--android +-lc++_static +-lc++abi +-Wl,--exclude-libs,libc++_static.a +-Wl,--exclude-libs,libc++abi.a +``` + +Three more things the build has to get right, each of which fails as something +else: + +1. **`ANDROID_NDK` must be exported**, not only `ANDROID_NDK_HOME` / `NDK_HOME`. + `cmake-rs` (RandomX's C++ half) aborts with *"Android: Neither the NDK or a + standalone toolchain was found"*, and `randomx-rs`'s build script then panics + inside `cmake`. The task exports all three. +2. **The linker is the NDK clang driver, named explicitly.** The dev machines' + `~/.cargo/config.toml` pins `[target.aarch64-linux-android] linker` to the + **API 21** wrapper, and API 21 fails this link (`pthread_atfork` is API 23+). + `cargo-ndk`'s own linker wrapper is bypassed so the `-Wl,…` args reach clang as + link args. +3. **The flags are `CARGO_TARGET__RUSTFLAGS`, not `RUSTFLAGS`.** A global + rustflags would also apply to build scripts and proc macros, which are + **host**-targeted, where `-lc++_static` breaks the link. Setting the + per-target variable also *replaces* the `target..rustflags` in + `~/.cargo/config.toml`, so the sysroot `-L` it carried is repeated in the list. + +## What ends up in the APK + +``` +lib/arm64-v8a/libandroidx.graphics.path.so +lib/arm64-v8a/libjnidispatch.so +lib/arm64-v8a/libmonerowalletrpc.so +lib/arm64-v8a/libonionwire_sdk.so +lib/arm64-v8a/librandomx_rs-.so <- new, see below +``` + +`librandomx_rs-.so` is new and is **not a load-time dependency** of the SDK: +`readelf -d libonionwire_sdk.so` lists `liblog.so` and nothing else, and the +RandomX code is statically inside the SDK's own `.so` (its symbols and strings are +there). `cargo-ndk` copies every cdylib the target directory produced into +`jniLibs`, and `randomx-rs` also builds one. It is left in place rather than +filtered out: it is 1,122,296 bytes uncompressed / 387,996 deflated, and dropping +it would be a packaging rule that silently breaks the day something *does* link it. + +## The CI gate + +`.forgejo/workflows/android-ci.yml` extracts `lib//libonionwire_sdk.so` from +the built APK and greps it for `target_max_memory` — a rodata literal from +`src/cuprate.rs`'s config TOML, compiled only under +`#[cfg(feature = "cuprate-daemon")]`. The job **fails** if it is absent. + +The negative control is v0.7.0's shipped APK: its `libonionwire_sdk.so` contains +**zero** occurrences of that string (and of `randomx` / `cuprated`), so a match +means the daemon is in the artifact, not merely requested. The build log line +above is the other half of the proof — request and artifact, separately checkable. + +## What the wallet screen does with it + +`ui/WalletScreen.kt` grew a third chain source beside the daemon field and +**Receive-only** (`ui/WalletChildStatusText.kt` holds the pure model): + +* Selecting **On-device node (Cuprate)** stores `ChainChoice.InProcessCuprate` with + an **empty** `monerod_datadir`, which the SDK resolves to + `$ONIONWIRE_HOME/chain` — the same directory a spawned `monerod` would use. Kotlin + never invents an absolute path. +* `monero-wallet-rpc` is still required and still a subprocess: Start is gated on + the bundled binary exactly as before, and an in-process node does not bundle + `arti`, so a `.onion` daemon is still refused. +* The status line renders the core's words verbatim and grows a `node ` + segment from `WalletChildStatus.node_state` for this source only. An unrecognised + word is never rendered as ready. +* **No sync height.** `WalletChildStatus` has no height field — the core keeps a + `chain_height()` internally (`src/cuprate.rs`) but does not expose it over + UniFFI, so the screen does not show a number it cannot get. A height on the + status line is a follow-up on the SDK surface, not something the UI can invent. +* **Storage honesty.** The card shows the free space on the filesystem the fjall + store grows into (`StatFs` on the app's data dir) and refuses Start below a + 3 GiB floor, or when that filesystem cannot be read at all. The floor is a + *floor*, not a sync estimate, and the doc comment says why: nothing in this stack + exposes one — `WalletChildStatus` has no size field, and Cuprate's restricted RPC + reports a hardcoded 5 GiB `database_size` placeholder. +* **Pre-production warning**, above the Start button, in a sentence: + `CUPRATE_PREPRODUCTION_WARNING` — quoted user book, testnet-only, and Cuprate + issue #278, assertable in `WalletChildStatusTextTest`. Opt-in, never a default. + +## Not verified + +The daemon was **not executed on a device or an emulator**. There is no +`arm64-v8a` AVD on the build host (the same gap `MONERO_BINARIES.md` records), and +no aarch64 Android sysroot to run it under `qemu-user`. What is proven: it +cross-compiles and links against the NDK's C++ runtime, the feature is in the +shipped `.so`, the artifact packages, and the Kotlin that drives it compiles and +passes its unit tests. What is not: that `cuprated` starts, opens its fjall store +and answers on loopback under Android's runtime — and, on top of that, Cuprate +itself is pre-production and testnet-only. + +To close the gap, on an arm64 device or a software-emulated arm64 AVD: + +```bash +sdkmanager "system-images;android-35;google_apis;arm64-v8a" +avdmanager create avd -n ow-arm64 -k "system-images;android-35;google_apis;arm64-v8a" +emulator -avd ow-arm64 # software-emulated on an x86_64 host: slow +adb install -r dist/onionwire--android-arm64-v8a.apk +``` + +then unlock the node, open Wallet, tap **On-device node (Cuprate)**, read the +warning, press **Start wallet**, and watch the status line for +`connecting → syncing · in-process node · node starting → node syncing`. A wallet +balance needs the chain synced, which on a phone is a long wait — the status line +is the thing to watch, not the balance. diff --git a/android/MONERO_BINARIES.md b/android/MONERO_BINARIES.md index a191105..c9f4185 100644 --- a/android/MONERO_BINARIES.md +++ b/android/MONERO_BINARIES.md @@ -166,3 +166,13 @@ 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. + +## The other chain source: an in-process daemon, not a binary + +The third chain source — Cuprate's chain daemon running inside the OnionWire +process — is a **linked feature of the SDK's `.so`**, not a `jniLibs` executable, +so it has its own record: `android/CUPRATE_DAEMON.md` (feature wiring, the NDK C++ +/ compiler-rt link line, the CI check that greps the shipped `.so` for a +cuprated-only string, and what has not been verified). `monero-wallet-rpc` above +stays a child process for it — Cuprate has no wallet layer. + 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 6d9bae3..3e5d7d5 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,7 @@ 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.ChainStorage import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE import com.siriusdevops.onionwire.wallet.WalletChildBinaries import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths @@ -722,6 +723,48 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { refreshWalletChild() } + /** + * The third chain source: the chain daemon **inside this app** (Cuprate), no + * `monerod` binary and no remote operator. Stores the setting; [startWalletChild] + * is what launches the node *and* the wallet child (one call in the core). + * + * `monerodDatadir` is left empty on purpose: the SDK resolves that to + * `$ONIONWIRE_HOME/chain`, the same per-identity directory a spawned `monerod` + * would use, so Kotlin never invents an absolute path. `monero-wallet-rpc` is + * still required — Cuprate has no wallet layer, so the subprocess stays, and the + * core rejects a config without it. + */ + suspend fun setInProcessCuprate(bins: WalletChildBinaryPaths): Result = + withContext(Dispatchers.IO) { + runCatching { + requireWire().setChainSource( + ChainConfig( + kind = ChainChoice.IN_PROCESS_CUPRATE, + monerodBin = "", + monerodDatadir = "", + host = "", + port = 0u, + walletRpcBin = bins.walletRpc.orEmpty(), + // Inert for this source: an in-process node is loopback + // clearnet, so the core never spawns the SOCKS child. + artiBin = expectedArtiPath(), + walletFilename = WalletChildBinaries.WALLET_FILENAME, + ), + ) + } + }.onSuccess { + _walletChildError.value = null + refreshChainSource() + refreshWalletChild() + } + + /** + * Free bytes on the filesystem the in-process chain store grows into, or + * `null` when it cannot be read. The screen shows this before the user commits + * to a store on the device; it is a measurement, not an estimate. + */ + fun chainFreeBytes(): Long? = ChainStorage.freeBytes(home) + /** * Spawns the child (and its daemon/SOCKS siblings) and returns what the core * reached. 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 index 8ed5faf..247d91b 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt @@ -2,6 +2,7 @@ package com.siriusdevops.onionwire.ui import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths +import java.util.Locale /** * One snapshot of the app-owned wallet child, as the wallet screen sees it. @@ -25,6 +26,25 @@ data class WalletChildInput( val configured: Boolean, /** The core's label: `receive-only` / `local node` / `remote onion daemon` / `remote daemon`. */ val chainSource: String, + /** + * The configured source runs the chain daemon **inside this app** (Cuprate) + * rather than spawning `monerod` or dialling a remote one — the core's + * `chain_in_process`. When true the line grows a node segment, because there + * is no separate daemon process for the state word to describe. + */ + val chainInProcess: Boolean = false, + /** + * This build carries `cuprate-daemon`, so the in-process node can actually + * start — the core's `node_available`. `false` means the option is stored but + * a start can only fail: say so before the user commits, never after. + */ + val nodeAvailable: Boolean = true, + /** + * The node's own word — the core's `node_state`: `off` / `starting` / + * `syncing` / `ready` / `exited`. **Empty** for every other chain source, and + * empty for an in-process source that has not been read yet. + */ + val nodeState: String = "", val lastError: String? = null, ) @@ -133,6 +153,98 @@ sealed interface WalletChildPhase { /** Cells of an unrecognised state word kept on the status line. */ const val UNRECOGNISED_BUDGET: Int = 16 +/** + * The in-process node's own word, for the chain sources that have one. + * + * Same fail-closed rule as [WalletChildPhase]: an unrecognised word is never + * [Ready]. [Absent] is not a node state at all — it is "this chain source has no + * node segment on the line", which is true of receive-only, a spawned `monerod` + * and a remote daemon, and also of an in-process source the core has not reported + * a node word for yet. Nothing is inferred to fill it in. + */ +sealed interface NodePhase { + + /** Stable handle for Compose semantics and tests. */ + val testTag: String + + /** Word drawn after `node`, or empty for [Absent]. */ + val label: String + + /** What a screen reader announces. Always a sentence. */ + val contentDescription: String + + /** No node segment: not an in-process chain source. */ + data object Absent : NodePhase { + override val testTag: String = "node-absent" + override val label: String = "" + override val contentDescription: String = "No on-device node" + } + + /** The app's own node is not running. */ + data object Off : NodePhase { + override val testTag: String = "node-off" + override val label: String = "off" + override val contentDescription: String = "The on-device node is off" + } + + /** The node is up; its loopback RPC has not answered yet. */ + data object Starting : NodePhase { + override val testTag: String = "node-starting" + override val label: String = "starting" + override val contentDescription: String = + "The on-device node is starting; its RPC has not answered yet" + } + + /** The node answers; its chain is not at the tip. */ + data object Syncing : NodePhase { + override val testTag: String = "node-syncing" + override val label: String = "syncing" + override val contentDescription: String = + "The on-device node is syncing; the chain is not at the tip yet" + } + + /** The node answers and its chain is at the tip. */ + data object Ready : NodePhase { + override val testTag: String = "node-ready" + override val label: String = "ready" + override val contentDescription: String = "The on-device node is ready" + } + + /** A started node is gone. */ + data object Exited : NodePhase { + override val testTag: String = "node-exited" + override val label: String = "exited" + override val contentDescription: String = "The on-device node exited" + } + + /** A node word this build does not know. Fail-closed: never [Ready]. */ + data class Unrecognised(val raw: String) : NodePhase { + override val testTag: String = "node-unrecognised" + override val label: String = "unknown (${shortSendReason(raw, UNRECOGNISED_BUDGET)})" + override val contentDescription: String = + "The on-device node reported a state this build does not know" + } +} + +/** + * Maps the core's `node_state` onto a [NodePhase]. + * + * [NodePhase.Absent] for a source that has no node (or no word yet); anything the + * five words do not cover is [NodePhase.Unrecognised] — never [NodePhase.Ready]. + */ +fun nodePhase(input: WalletChildInput?): NodePhase { + if (input == null || !input.chainInProcess) return NodePhase.Absent + return when (val state = input.nodeState.trim().lowercase()) { + "" -> NodePhase.Absent + "off" -> NodePhase.Off + "starting" -> NodePhase.Starting + "syncing" -> NodePhase.Syncing + "ready" -> NodePhase.Ready + "exited" -> NodePhase.Exited + else -> NodePhase.Unrecognised(state) + } +} + /** * Maps the core's `state` word onto a [WalletChildPhase]. Case- and * whitespace-tolerant; anything else is [WalletChildPhase.Unrecognised]. @@ -161,11 +273,18 @@ fun walletChildPhase(input: WalletChildInput?): WalletChildPhase { fun walletChildLine(input: WalletChildInput?): String { val phase = walletChildPhase(input) val source = input?.chainSource?.takeIf { it.isNotBlank() } ?: "no chain source" + val node = nodePhase(input) val why = input?.lastError?.takeIf { it.isNotBlank() } return buildString { append(phase.label) append(" · ") append(source) + // Only an in-process source has a node of its own to name. The node word + // is the core's, rendered as-is — there is no second state machine here. + if (node !is NodePhase.Absent) { + append(" · node ") + append(node.label) + } when { why != null -> append(" — ").append(shortSendReason(why)) phase is WalletChildPhase.Exited -> append(" — the child process is gone") @@ -184,6 +303,80 @@ const val ONION_NEEDS_ARTI_NOTICE: String = /** Shown while the first `wallet_status()` read is still in flight. */ const val READING_CHILD_NOTICE: String = "Reading the wallet child status…" +/** + * The caveat the on-device node is offered with, **before** Start. + * + * Cuprate's own user book says *"do NOT use cuprated for any serious purposes"*, + * its `monerod` RPC parity is incomplete (Cuprate issue #278, and the four gaps + * measured in this repo are in `docs/cuprate-launch-spike.md`), and the daemon + * this app launches is pinned to **testnet** (`src/cuprate.rs`). One sentence, not + * a glyph: the choice is opt-in and never a default, and a user who reads only + * this line still knows what they picked. + */ +const val CUPRATE_PREPRODUCTION_WARNING: String = + "On-device node is Cuprate, which is pre-production: its own user book says do NOT use " + + "cuprated for any serious purposes, it runs testnet only here (mainnet is unvalidated), " + + "and its monerod RPC parity is incomplete (Cuprate issue #278). Try the in-process " + + "path; do not hold funds on it." + +/** + * This build was compiled without the `cuprate-daemon` feature, so the stored + * on-device chain source can be read back but can never start. Mirrors the core's + * own refusal (`onionwire::cuprate::NO_FEATURE_MSG`) rather than inventing a + * second wording for the same fact. + */ +const val CUPRATE_NOT_IN_BUILD_NOTICE: String = + "This build has no in-process chain daemon, so the on-device node cannot start." + +/** + * Free space the chain store's filesystem must have before the on-device node is + * started. + * + * A **floor**, not a sync estimate, and deliberately so: nothing in this stack + * exposes one. `WalletChildStatus` carries no size field, and Cuprate's own + * restricted RPC reports a hardcoded 5 GiB `database_size` placeholder (see + * `src/cuprate.rs`), so a number taken from the node would be fiction. What can be + * measured honestly is the free space on the filesystem the fjall store grows + * into, and the device can be told when that is not enough. + */ +const val CHAIN_FREE_SPACE_FLOOR_BYTES: Long = 3L * 1024 * 1024 * 1024 + +/** + * What the chain store costs, in the user's terms: the free space this device + * actually has, and what the node does *not* tell us. + */ +fun chainStorageLine(freeBytes: Long?): String = when { + freeBytes == null -> + "chain store: free space on this device could not be read." + else -> + "chain store: ${formatBytes(freeBytes)} free on this device — a synced testnet store " + + "grows into it. The node reports no size estimate of its own." +} + +/** + * Why the on-device node must not be started on this device, or `null` when it + * may. Fail-closed on an unreadable filesystem: an unknown free space is not + * reported as enough. + */ +fun chainStorageBlockedReason(freeBytes: Long?): String? = when { + freeBytes == null -> + "Free space on the chain store's filesystem could not be read, so it is not known to fit." + freeBytes < CHAIN_FREE_SPACE_FLOOR_BYTES -> + "Not enough space for the chain store: ${formatBytes(freeBytes)} free, and the " + + "on-device node needs at least ${formatBytes(CHAIN_FREE_SPACE_FLOOR_BYTES)}." + else -> null +} + +/** + * Bytes as a screen-sized string. Binary units (a "GB" that is really a GiB is how + * a store that needs 3 GiB ends up on a device with 2.8). + */ +fun formatBytes(bytes: Long): String = when { + bytes >= 1L shl 30 -> String.format(Locale.US, "%.1f GiB", bytes.toDouble() / (1L shl 30)) + bytes >= 1L shl 20 -> String.format(Locale.US, "%.0f MiB", bytes.toDouble() / (1L shl 20)) + else -> "$bytes B" +} + /** * Why **Start** is not actionable, or `null` when it is. * @@ -200,6 +393,9 @@ fun startBlockedReason( 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." + // The stored source is the app's own node but this build has no daemon: the + // option is readable and unstoppable, so say it before the user presses Start. + input.chainInProcess && !input.nodeAvailable -> CUPRATE_NOT_IN_BUILD_NOTICE onionDaemon && bins.arti == null -> ONION_NEEDS_ARTI_NOTICE else -> null } 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 4ea8286..3f54179 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 @@ -80,6 +80,10 @@ fun WalletScreen( // the life of the process. val bins = remember { vm.bundledBinaries() } val childInput = child?.toInput() + // Free space on the filesystem the in-process chain store grows into. Read + // once per composition of the screen: it is the same filesystem for the life + // of the process, and the number is only a commit-time gate. + val nodeFreeBytes = remember { vm.chainFreeBytes() } var showQr by remember { mutableStateOf(false) } var balance by remember { mutableStateOf(null) } var address by remember { mutableStateOf(null) } @@ -221,6 +225,7 @@ fun WalletScreen( bins = bins, input = childInput, chain = chain, + nodeFreeBytes = nodeFreeBytes, actionError = childError, daemonText = daemonText, daemonError = daemonError, @@ -247,6 +252,13 @@ fun WalletScreen( .onFailure { daemonError = it.message ?: it.toString() } } }, + onInProcessNode = { + daemonError = null + scope.launch { + vm.setInProcessCuprate(bins) + .onFailure { daemonError = it.message ?: it.toString() } + } + }, onStart = { scope.launch { vm.startWalletChild() } }, onStop = { scope.launch { vm.stopWalletChild() } }, ) @@ -572,35 +584,50 @@ private fun WalletSetupCard( } /** - * The app-owned `monero-wallet-rpc` control (issue #107). + * The app-owned `monero-wallet-rpc` control (issue #107), now with the third chain + * source: the chain daemon **inside this app** (Cuprate). * * **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`. + * verbatim, so a child that died reads `exited` and never `off`, and an in-process + * source grows a `node ` segment that is the core's own `node_state`. * * 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. + * binary, no chain source, a `.onion` daemon with no bundled `arti` SOCKS child, + * or a build without `cuprate-daemon` 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. + * + * The on-device node is opt-in and carries its pre-production warning **above the + * Start button**, plus the free space on the filesystem its fjall store grows + * into. A device that cannot hold the chain is told before it commits, not left to + * fail at sync time. */ @Composable private fun WalletChildCard( bins: WalletChildBinaryPaths, input: WalletChildInput?, chain: ChainConfig?, + nodeFreeBytes: Long?, actionError: String?, daemonText: String, daemonError: String?, onDaemonText: (String) -> Unit, onSaveDaemon: () -> Unit, onReceiveOnly: () -> Unit, + onInProcessNode: () -> Unit, onStart: () -> Unit, onStop: () -> Unit, ) { val phase = walletChildPhase(input) + val node = nodePhase(input) val onionDaemon = chain?.kind == ChainChoice.REMOTE && isOnionHost(chain.host) + // The selection is in-process as soon as it is stored, before the first status + // read comes back: the warning and the storage line must not wait for the + // poller, or the user would press Start having seen neither. + val inProcess = input?.chainInProcess == true || chain?.kind == ChainChoice.IN_PROCESS_CUPRATE val startWhy = startBlockedReason(bins, input, onionDaemon) + ?: if (inProcess) chainStorageBlockedReason(nodeFreeBytes) else null val stopWhy = stopBlockedReason(input) Card( @@ -615,8 +642,9 @@ private fun WalletChildCard( 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`. + // The core's own words: `ready · remote onion daemon`, plus + // `· node syncing` for the in-process source. Tagged with the phase so + // a UI test can assert `exited` is never `off`. Text( walletChildLine(input), style = MaterialTheme.typography.bodySmall, @@ -629,6 +657,23 @@ private fun WalletChildCard( }, ) + // The node's own word, when there is one, as its own assertable line: + // an unrecognised node state can never be read as ready. + if (node !is NodePhase.Absent) { + Text( + "node: ${node.label}", + style = MaterialTheme.typography.labelSmall, + fontFamily = FontFamily.Monospace, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .fillMaxWidth() + .testTag(node.testTag) + .semantics(mergeDescendants = true) { + contentDescription = node.contentDescription + }, + ) + } + if (!bins.walletRpcBundled) { Spacer(Modifier.height(6.dp)) Text( @@ -648,8 +693,9 @@ private fun WalletChildCard( 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.", + "A daemon on your LAN (e.g. 192.168.1.20:18089) or a public node's " + + "clearnet address. A phone cannot run monerod — for a chain with no " + + "daemon at all, use the on-device node below.", style = MaterialTheme.typography.labelSmall, ) }, @@ -677,6 +723,38 @@ private fun WalletChildCard( ) { Text("Receive-only") } } + // The third chain source. Never a default: selecting it is what stores + // `ChainChoice.InProcessCuprate`, and the warning below is what the user + // reads before Start. + Spacer(Modifier.height(8.dp)) + OutlinedButton( + onClick = onInProcessNode, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-chain-in-process"), + ) { Text("On-device node (Cuprate)") } + + if (inProcess) { + Spacer(Modifier.height(8.dp)) + Text( + CUPRATE_PREPRODUCTION_WARNING, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-cuprate-warning"), + ) + Spacer(Modifier.height(4.dp)) + Text( + chainStorageLine(nodeFreeBytes), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-chain-storage"), + ) + } + Spacer(Modifier.height(8.dp)) Row( modifier = Modifier.fillMaxWidth(), @@ -738,6 +816,9 @@ internal fun WalletChildStatus.toInput(): WalletChildInput = WalletChildInput( running = running, configured = configured, chainSource = chainSource, + chainInProcess = chainInProcess, + nodeAvailable = nodeAvailable, + nodeState = nodeState, lastError = lastError, ) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/wallet/ChainStorage.kt b/android/app/src/main/java/com/siriusdevops/onionwire/wallet/ChainStorage.kt new file mode 100644 index 0000000..cd06bab --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/wallet/ChainStorage.kt @@ -0,0 +1,30 @@ +package com.siriusdevops.onionwire.wallet + +import android.os.StatFs +import java.io.File + +/** + * Free space on the filesystem the in-process chain store grows into. + * + * The chain source this is for is Cuprate's fjall store under + * `$ONIONWIRE_HOME/chain` (`WireViewModel.home` is `filesDir/onionwire`), which is + * the same filesystem as `filesDir` — so `StatFs` on the app's own data directory + * answers the question the user is actually being asked: *will this fit here?* + * + * It is a **measurement, not an estimate**: nothing in the SDK exposes a chain + * size (`WalletChildStatus` has no size field, and Cuprate's restricted RPC + * reports a hardcoded 5 GiB placeholder — `src/cuprate.rs`). The floor the screen + * applies to this number is [com.siriusdevops.onionwire.ui.CHAIN_FREE_SPACE_FLOOR_BYTES], + * and it is documented there as a floor rather than a sync estimate. + * + * `null` means "could not be read", and the screen treats that as fail-closed: an + * unknown free space is not reported as enough. Kept out of the JVM unit tests on + * purpose — `StatFs` is an Android class, so the pure formatting and the gate live + * in `ui/WalletChildStatusText.kt` where they are covered without a device. + */ +object ChainStorage { + + /** Free bytes on [path]'s filesystem, or `null` when it cannot be read. */ + fun freeBytes(path: File): Long? = runCatching { StatFs(path.absolutePath).availableBytes } + .getOrNull() +} 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 index 8603173..0ad32b9 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt @@ -26,12 +26,18 @@ class WalletChildStatusTextTest { running: Boolean = false, configured: Boolean = true, chainSource: String = "remote daemon", + chainInProcess: Boolean = false, + nodeAvailable: Boolean = true, + nodeState: String = "", lastError: String? = null, ) = WalletChildInput( state = state, running = running, configured = configured, chainSource = chainSource, + chainInProcess = chainInProcess, + nodeAvailable = nodeAvailable, + nodeState = nodeState, lastError = lastError, ) @@ -240,4 +246,132 @@ class WalletChildStatusTextTest { val parsed = parseDaemonAddress("127.0.0.1:18089")!! assertEquals("127.0.0.1:18089", parsed.text) } + + // --- the on-device node (Cuprate) --------------------------------------- + + private fun node( + state: String = "syncing", + chainSource: String = "in-process node", + nodeState: String, + nodeAvailable: Boolean = true, + running: Boolean = true, + ) = input( + state = state, + running = running, + chainSource = chainSource, + chainInProcess = true, + nodeAvailable = nodeAvailable, + nodeState = nodeState, + ) + + @Test + fun each_core_node_state_maps_to_its_own_phase() { + assertTrue(nodePhase(node(nodeState = "off")) is NodePhase.Off) + assertTrue(nodePhase(node(nodeState = "starting")) is NodePhase.Starting) + assertTrue(nodePhase(node(nodeState = "syncing")) is NodePhase.Syncing) + assertTrue(nodePhase(node(nodeState = "ready")) is NodePhase.Ready) + assertTrue(nodePhase(node(nodeState = "exited")) is NodePhase.Exited) + } + + @Test + fun only_an_in_process_source_has_a_node_segment() { + assertTrue(nodePhase(input("ready", running = true)) is NodePhase.Absent) + assertTrue(nodePhase(null) is NodePhase.Absent) + // In-process, but the core has not reported a node word yet: no segment, + // rather than an invented one. + assertTrue(nodePhase(node(nodeState = "")) is NodePhase.Absent) + } + + @Test + fun an_unknown_node_state_is_never_ready() { + val phase = nodePhase(node(nodeState = "mining")) + assertTrue(phase is NodePhase.Unrecognised) + assertFalse("an unknown node word must not read as ready", phase is NodePhase.Ready) + assertTrue(phase.label.startsWith("unknown")) + } + + @Test + fun the_line_grows_a_node_segment_for_the_in_process_source() { + assertEquals( + "syncing · in-process node · node syncing", + walletChildLine(node(state = "syncing", nodeState = "syncing")), + ) + assertEquals( + "ready · in-process node · node ready", + walletChildLine(node(state = "ready", nodeState = "ready")), + ) + } + + @Test + fun the_line_has_no_node_segment_for_the_other_sources() { + assertFalse(walletChildLine(input("ready", running = true)).contains("node ")) + assertFalse(walletChildLine(input("off", chainSource = "receive-only")).contains("node ")) + } + + @Test + fun start_is_blocked_when_the_build_has_no_in_process_daemon() { + val why = startBlockedReason( + bundled, + node(state = "off", nodeState = "off", nodeAvailable = false, running = false), + ) + assertEquals(CUPRATE_NOT_IN_BUILD_NOTICE, why) + assertNull( + "a build that carries the daemon is not blocked", + startBlockedReason( + bundled, + node(state = "off", nodeState = "off", nodeAvailable = true, running = false), + ), + ) + } + + @Test + fun the_preproduction_warning_is_a_sentence_a_user_can_act_on() { + val warning = CUPRATE_PREPRODUCTION_WARNING + assertTrue("it names the software", warning.contains("Cuprate")) + assertTrue("it quotes the user book", warning.contains("do NOT use cuprated")) + assertTrue("it names the parity gap", warning.contains("Cuprate issue #278")) + assertTrue("it says testnet", warning.contains("testnet")) + assertTrue("it is a sentence, not a glyph", warning.trim().endsWith(".")) + assertTrue("it is long enough to be a sentence", warning.length > 80) + } + + // --- storage honesty ---------------------------------------------------- + + @Test + fun storage_is_blocked_when_free_space_is_unreadable() { + assertTrue(chainStorageBlockedReason(null)!!.contains("could not be read")) + } + + @Test + fun storage_is_blocked_below_the_floor() { + val why = chainStorageBlockedReason(CHAIN_FREE_SPACE_FLOOR_BYTES - 1) + assertNotNull(why) + assertTrue(why!!, why.contains("Not enough space")) + assertTrue("the number is on screen", why.contains("3.0 GiB")) + } + + @Test + fun storage_is_allowed_at_and_above_the_floor() { + assertNull(chainStorageBlockedReason(CHAIN_FREE_SPACE_FLOOR_BYTES)) + assertNull(chainStorageBlockedReason(64L * 1024 * 1024 * 1024)) + } + + @Test + fun the_storage_line_reports_the_measured_number() { + val line = chainStorageLine(41L * 1024 * 1024 * 1024) + assertTrue(line, line.contains("41.0 GiB")) + assertTrue("it says what the number is not", line.contains("no size estimate")) + assertTrue( + "an unreadable filesystem says so", + chainStorageLine(null).contains("could not be read"), + ) + } + + @Test + fun bytes_are_formatted_in_binary_units() { + assertEquals("512 B", formatBytes(512)) + assertEquals("2 MiB", formatBytes(2L * 1024 * 1024)) + assertEquals("1.5 GiB", formatBytes(3L * 1024 * 1024 * 1024 / 2)) + assertEquals("3.0 GiB", formatBytes(CHAIN_FREE_SPACE_FLOOR_BYTES)) + } } diff --git a/android/sdk/build.gradle.kts b/android/sdk/build.gradle.kts index 546f587..ccc4989 100644 --- a/android/sdk/build.gradle.kts +++ b/android/sdk/build.gradle.kts @@ -52,6 +52,87 @@ val onionwireAbis: List = (findProperty("onionwire.abis") as String?) ?.split(',')?.map(String::trim)?.filter(String::isNotEmpty) ?: listOf("arm64-v8a") +/** + * Rust features for the **Android** target build. + * + * `cuprate-daemon` is what puts the in-process Monero chain daemon (Cuprate) in + * the APK — the SDK crate's passthrough to the core + * (`cuprate-daemon = ["onionwire/cuprate-daemon"]`), so `WalletChildStatus.node_available` + * is `true` on the device and `ChainChoice.InProcessCuprate` can actually start. + * + * Deliberately **not** applied to `cargoHostLib` / `uniffiBindgen`: those build a + * host cdylib only so `uniffi-bindgen --library` can dlopen it, the cuprated graph + * (152 crates plus a C++ RandomX build) buys nothing there, and the UniFFI surface + * does not fork on a cargo feature. The Kotlin bindings are byte-identical either + * way, which is what `crates/onionwire-sdk`'s own tests cover. + */ +val onionwireRustFeatures: List = listOf("cuprate-daemon") + +/** `arm64-v8a` -> the Rust triple, the sysroot dir name and the builtins archive. */ +data class AndroidTarget( + val abi: String, + val triple: String, + /** Sysroot library dir under `.../sysroot/usr/lib/`. */ + val sysrootLib: String, + /** `libclang_rt.builtins-.a`, from the NDK clang resource dir. */ + val builtins: String, + /** NDK clang driver prefix: `-clang`. */ + val clangPrefix: String, +) + +val androidTargets: Map = listOf( + AndroidTarget("arm64-v8a", "aarch64-linux-android", "aarch64-linux-android", "aarch64-android", "aarch64-linux-android"), + AndroidTarget("x86_64", "x86_64-linux-android", "x86_64-linux-android", "x86_64-android", "x86_64-linux-android"), + AndroidTarget("armeabi-v7a", "armv7-linux-androideabi", "arm-linux-androideabi", "arm-android", "armv7a-linux-androideabi"), + AndroidTarget("x86", "i686-linux-android", "i686-linux-android", "i386-android", "i686-linux-android"), +).associateBy(AndroidTarget::abi) + +/** The NDK's host tag (`linux-x86_64`, `darwin-x86_64`, …) — exactly one prebuilt tree. */ +val ndkHostTag: String = ndkDir.resolve("toolchains/llvm/prebuilt").listFiles() + ?.filter(File::isDirectory)?.singleOrNull()?.name + ?: error("expected exactly one NDK prebuilt toolchain under $ndkDir/toolchains/llvm/prebuilt") + +/** The NDK clang resource dir (`lib/clang//lib/linux`) — exactly one version. */ +val ndkClangLibDir: File = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/lib/clang") + .listFiles()?.filter(File::isDirectory)?.singleOrNull() + ?.resolve("lib/linux") + ?: error("expected exactly one clang resource dir under $ndkDir/toolchains/llvm/prebuilt/$ndkHostTag/lib/clang") + +/** + * Per-ABI link flags for the Android build. + * + * RandomX is C++ and its aarch64 JIT calls `__clear_cache`, and `randomx-rs`'s + * build script emits `rustc-link-lib=static=stdc++` against the NDK's *stub* + * `libstdc++.a`. Without libc++ and the compiler-rt builtins on the link line the + * build dies on `__cxa_allocate_exception` / `std::runtime_error` / `typeinfo` + * (and `__clear_cache`) undefined. `cargo ndk --link-builtins` covers only the + * builtins, not libc++ — and `-static-libstdc++` is ignored by NDK clang — so the + * whole set is spelled out. Recipe and evidence: `docs/cuprate-android-spike.md`. + * + * Exported as `CARGO_TARGET__RUSTFLAGS` rather than `RUSTFLAGS`: a global + * rustflags would also apply to build scripts and proc macros, which are + * **host**-targeted, and `-lc++_static` there breaks the host link. + * + * The same variables also *replace* any `target..rustflags` in + * `~/.cargo/config.toml`, so the sysroot `-L` it carried is repeated here. + */ +fun linkFlags(target: AndroidTarget): String { + val sysrootLib = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/sysroot/usr/lib/${target.sysrootLib}") + return listOf( + "-C", "link-arg=-L$sysrootLib", + "-C", "link-arg=-L$ndkClangLibDir", + "-C", "link-arg=-lclang_rt.builtins-${target.builtins}", + "-C", "link-arg=-lc++_static", + "-C", "link-arg=-lc++abi", + "-C", "link-arg=-Wl,--exclude-libs,libc++_static.a", + "-C", "link-arg=-Wl,--exclude-libs,libc++abi.a", + ).joinToString(" ") +} + +/** The NDK clang driver for one ABI at [onionwireApiLevel]. */ +private fun clangDriver(target: AndroidTarget): File = + ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/bin/${target.clangPrefix}$onionwireApiLevel-clang") + val jniLibsDir = layout.buildDirectory.dir("rustJniLibs") val uniffiKotlinDir = layout.buildDirectory.dir("generated/uniffi") @@ -61,7 +142,16 @@ val cargoTargetDir: File = System.getenv("CARGO_TARGET_DIR")?.let(::File) ?: sdkCrateDir.resolve("target") val hostCdylib: File = cargoTargetDir.resolve("release/libonionwire_sdk.so") -/** Host cdylib. UniFFI's `--library` mode dlopens it, so it must be host-arch. */ +/** + * Host cdylib. UniFFI's `--library` mode dlopens it, so it must be host-arch. + * + * Feature-free **on purpose**: this exists only to emit the Kotlin bindings, and + * `cuprate-daemon` would drag the whole Cuprate graph (152 crates + a C++ RandomX + * build) through a host compile that never runs the daemon. The UniFFI surface + * does not fork on a cargo feature — `ChainChoice.InProcessCuprate` is present in + * both — so the generated Kotlin is the same. `onionwireRustFeatures` is for + * [cargoBuildAndroid] only. + */ val cargoHostLib by tasks.registering(Exec::class) { group = "onionwire" description = "Builds libonionwire_sdk.so for the host (used only to emit bindings)." @@ -99,10 +189,38 @@ val cargoBuildAndroid by tasks.registering(Exec::class) { inputs.file(sdkCrateDir.resolve("Cargo.lock")) inputs.dir(repoRoot.resolve("src")) inputs.file(repoRoot.resolve("Cargo.toml")) + // The feature set is an input: `-Ponionwire.features=` … there is no knob + // (a build that silently dropped `cuprate-daemon` would ship an APK whose + // on-device node can only fail), but the task must not stay "up to date" + // across a change to this list. + inputs.property("rustFeatures", onionwireRustFeatures) outputs.dir(jniLibsDir) environment("ANDROID_HOME", androidSdkDir.absolutePath) environment("ANDROID_NDK_HOME", ndkDir.absolutePath) environment("NDK_HOME", ndkDir.absolutePath) + // `cmake-rs` (RandomX's C++ half) aborts with "Neither the NDK or a standalone + // toolchain was found" unless ANDROID_NDK itself is exported — NDK_HOME and + // ANDROID_NDK_HOME are not enough, and `randomx-rs`'s build script then panics + // inside `cmake`. + environment("ANDROID_NDK", ndkDir.absolutePath) + environment("ANDROID_NDK_ROOT", ndkDir.absolutePath) + // Per-ABI link env. The clang driver is named explicitly because + // `~/.cargo/config.toml` on the dev machines pins the *API 21* wrapper for + // `aarch64-linux-android`, and API 21 fails this link (`pthread_atfork` is + // API 23+); `cargo-ndk`'s own linker wrapper is bypassed on purpose so the + // `-Wl,…` args below reach clang as link args. + onionwireAbis.forEach { abi -> + val target = androidTargets[abi] + ?: error("no Android target mapping for ABI '$abi' — add it to androidTargets in sdk/build.gradle.kts") + val rustFlagsVar = "CARGO_TARGET_${target.triple.uppercase().replace('-', '_')}_RUSTFLAGS" + val linkerVar = "CARGO_TARGET_${target.triple.uppercase().replace('-', '_')}_LINKER" + val linker = clangDriver(target) + require(linker.canExecute()) { + "NDK clang driver for $abi not found at $linker — NDK $onionwireNdkVersion incomplete?" + } + environment(rustFlagsVar, linkFlags(target)) + environment(linkerVar, linker.absolutePath) + } commandLine( buildList { add(cargoExe); add("ndk") @@ -110,8 +228,20 @@ val cargoBuildAndroid by tasks.registering(Exec::class) { add("--platform"); add(onionwireApiLevel.toString()) add("-o"); add(jniLibsDir.get().asFile.absolutePath) add("build"); add("--release"); add("--lib") + if (onionwireRustFeatures.isNotEmpty()) { + add("--features"); add(onionwireRustFeatures.joinToString(",")) + } } ) + // The CI log has to show the feature actually requested, not merely the task + // name: "the feature is in the artifact" is checked against this line. + doFirst { + logger.lifecycle( + "cargo ndk build for ${onionwireAbis.joinToString()} " + + "features=${onionwireRustFeatures.joinToString(",").ifEmpty { "(none)" }} " + + "api=$onionwireApiLevel ndk=$onionwireNdkVersion", + ) + } } // ---------------------------------------------------------------------------