android: start/stop the monero-wallet-rpc child from WalletScreen, bundle the binary
All checks were successful
android-ci / android (pull_request) Successful in 8m59s

Implements the Android half of issue #107. Stacked on `wt/t_8a8ff353`
(PR #108) because the UniFFI wallet-child surface is not on `main` yet.

Binary
------

`android/app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so` is a real
`monero-wallet-rpc` cross-compiled for `aarch64-linux-android` from
monero-project/monero v0.18.4.4 (516e5355) via upstream's own
`contrib/depends` + toolchain.cmake path, then stripped with the target's own
strip. 19 954 224 bytes, sha256
d9126788030ecd1ccdb40c7764e66e9a14d158a147ad335b256f0577681b5ad4.

It ships through `jniLibs` and not as an asset on purpose: since API 29 the
kernel refuses `exec()` on a file in the app's data directory, so the only
executable directory an app has is `applicationInfo.nativeLibraryDir`, which
the package manager fills from `lib/<abi>/` at install time. That requires
`android:extractNativeLibs="true"` (`packaging.jniLibs.useLegacyPackaging`),
which `app/build.gradle.kts` now sets, plus `keepDebugSymbols` for this one
entry so AGP's strip pass cannot rewrite the bytes CI verifies.

`scripts/build-monero-wallet-rpc-android.sh` reproduces the build and
`android/MONERO_BINARIES.md` records the four host quirks that cost the most
time (CMake must be 3.x; NDK r17b clang60 needs a libtinfo.so.5 shim; the
generated toolchain.cmake puts the HOST `/usr` in CMAKE_FIND_ROOT_PATH, which
breaks the link with a host libpgm.so and defines HAVE_HIDAPI against host
headers; the CMake target is `wallet_rpc_server`, not `monero-wallet-rpc`).

CI re-verifies the blob rather than taking it on trust:
`scripts/build-android-local.sh` checks `android/monero-binaries.sha256` before
Gradle, and after packaging pulls `lib/<abi>/libmonerowalletrpc.so` back out of
the APK and compares its sha256 with the committed file.

`arti` is NOT bundled, so a `.onion` daemon cannot be started yet. The app says
that instead of pretending: `arti_bin` is set to the path the binary would
occupy, and the screen refuses an `.onion` daemon while it is absent.
Loopback and clearnet daemons work.

UI
--

`WalletScreen` gains a "wallet daemon" card above the existing
Create / Import / Invoice / Tip actions, which are untouched:

* a status line from `Wire::wallet_status()` rendered verbatim —
  `off` / `connecting` / `syncing` / `ready` / `exited` plus the core's
  chain-source label (`receive-only` / `local node` / `remote onion daemon` /
  `remote daemon`). A died child reads `exited`; it is never folded into `off`
  and never into `ready`;
* Start / Stop calling `start_wallet_child` / `stop_wallet_child` through
  `WireViewModel`, on `Dispatchers.IO` (the spawn is synchronous inside the node
  and the status read re-decrypts the sealed record);
* a `host:port` field that saves a remote daemon via `set_chain_source`, plus a
  Receive-only button;
* honest failure states instead of a spinner: no bundled binary, no chain
  source, a `.onion` daemon with no arti, or a start that failed — each gets its
  own sentence, and Start is disabled with the reason on screen.

`WireViewModel` owns the 2s wallet-child poller, the same way it owns the chat
poller, so leaving the wallet screen and coming back cannot stack a second loop.
`ui/WalletChildStatusText.kt` is the pure model (mirrors the
`ChatRowInput`/`OutboxRowInput` convention) and carries the state mapping, the
status line and the Start/Stop gates; `WalletChildStatusTextTest` covers them on
the JVM.

Verified
--------

`./gradlew :app:testDebugUnitTest` passes, `scripts/build-android-local.sh`
produces `dist/onionwire-0.1.0-android-arm64-v8a.apk` (27 884 277 bytes,
versionName 0.1.0 / versionCode 100) with
`lib/arm64-v8a/libmonerowalletrpc.so` inside it at the committed sha256, and
`extractNativeLibs="true"` in the merged release manifest.

NOT verified: the binary was never executed. The build host has no arm64-v8a
AVD (all three existing AVDs are x86_64) and no aarch64 sysroot for qemu-user,
so nothing here proves `monero-wallet-rpc` starts, opens its wallet file and
answers JSON-RPC under Android's runtime. `android/MONERO_BINARIES.md` says so
plainly and lists the emulator steps to close the gap.
This commit is contained in:
apk-dev 2026-09-18 10:19:18 -04:00 • committed by agent
commit 0134396588
No known key found for this signature in database
11 changed files with 1440 additions and 1 deletions

View file

@ -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<WalletChildStatus?>(null)
val walletChild: StateFlow<WalletChildStatus?> = _walletChild.asStateFlow()
/**
* The last failed start/stop/read, display-ready. Sticky on purpose, like
* [ChatState.error]: a transient store read that fails once must not blink
* off the screen on the next successful tick.
*/
private val _walletChildError = MutableStateFlow<String?>(null)
val walletChildError: StateFlow<String?> = _walletChildError.asStateFlow()
/** The stored chain source + binary settings, for prefilling the editor. */
private val _chainSource = MutableStateFlow<ChainConfig?>(null)
val chainSource: StateFlow<ChainConfig?> = _chainSource.asStateFlow()
private var walletChildPoller: Job? = null
/**
* What this install can actually spawn. Read from
* `applicationInfo.nativeLibraryDir` — the only directory Android hands out
* executable — so the screen can say "not bundled" instead of offering a
* Start that can only fail.
*/
fun bundledBinaries(): WalletChildBinaryPaths =
WalletChildBinaries.resolve(
getApplication<Application>().applicationInfo.nativeLibraryDir,
)
/**
* Starts the one wallet-child refresh loop for the wallet screen. Re-entering
* the screen while the loop is alive is a no-op: navigating to the wallet
* and back must never stack a second poller.
*/
fun openWalletChild() {
if (walletChildPoller?.isActive == true) return
walletChildPoller = viewModelScope.launch {
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<Unit> {
val rpc = bins.walletRpc
?: return Result.failure(IllegalStateException(NO_WALLET_RPC_MESSAGE))
return withContext(Dispatchers.IO) {
runCatching {
requireWire().setChainSource(
ChainConfig(
kind = ChainChoice.REMOTE,
monerodBin = "",
monerodDatadir = "",
host = host,
port = port.toUShort(),
walletRpcBin = rpc,
// Inert unless the host is a `.onion`; the screen refuses
// an onion daemon outright while no `arti` is bundled.
artiBin = expectedArtiPath(),
walletFilename = WalletChildBinaries.WALLET_FILENAME,
),
)
}
}.onSuccess {
_walletChildError.value = null
refreshChainSource()
refreshWalletChild()
}
}
/**
* Back to receive-only: no child, no daemon, no chain traffic. The binary
* paths are still stored so switching back to a daemon does not need them
* re-derived.
*/
suspend fun setReceiveOnly(bins: WalletChildBinaryPaths): Result<Unit> =
withContext(Dispatchers.IO) {
runCatching {
requireWire().setChainSource(
ChainConfig(
kind = ChainChoice.NONE,
monerodBin = "",
monerodDatadir = "",
host = "",
port = 0u,
walletRpcBin = bins.walletRpc.orEmpty(),
artiBin = expectedArtiPath(),
walletFilename = WalletChildBinaries.WALLET_FILENAME,
),
)
}
}.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<WalletChildStatus> {
_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<Unit> {
_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<Application>().applicationInfo.nativeLibraryDir,
WalletChildBinaries.ARTI_LIB,
)
}
/** Cadence of the wallet-child refresh loop, in milliseconds. */
private const val WALLET_CHILD_TICK_MS: Long = 2_000

View file

@ -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"
}

View file

@ -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<String?>(null) }
var address by remember { mutableStateOf<String?>(null) }
@ -72,6 +88,8 @@ fun WalletScreen(
var composer by remember { mutableStateOf<PayKind?>(null) }
var setup by remember { mutableStateOf<SetupKind?>(null) }
var backupSeed by remember { mutableStateOf<String?>(null) }
var daemonText by remember { mutableStateOf("") }
var daemonError by remember { mutableStateOf<String?>(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 {

View file

@ -0,0 +1,101 @@
package com.siriusdevops.onionwire.wallet
import java.io.File
/**
* The app-owned wallet-child executables, as the APK actually carries them.
*
* **Why `jniLibs` and not an asset.** Since Android 10 (API 29) an app may not
* `exec()` a file it wrote into its own data directory: the SELinux policy has
* no `execute` on `app_data_file`, so `filesDir/libmonerowalletrpc.so` copied
* out of `assets/` with the exec bit set is still refused by the kernel — the
* classic "copy it to app-private storage" recipe died with `targetSdk 29`.
* The one directory Android does hand out executable is
* `ApplicationInfo.nativeLibraryDir`: the package manager unpacks the
* `lib/<abi>/` entries from the APK there at install time with the exec bit
* intact. A plain
* executable therefore has to be named `lib*.so` and shipped through
* `jniLibs`, and that unpack only happens when the manifest says
* `android:extractNativeLibs="true"` (`packaging.jniLibs.useLegacyPackaging`
* in `app/build.gradle.kts`). With `extractNativeLibs="false"` — the AGP 8
* default — the `.so` stays inside the APK and there is nothing on disk to run.
*
* The names here are the paths handed to the core as `ChainConfig.wallet_rpc_bin`
* and `ChainConfig.arti_bin`; the core spawns exactly the path it is given and
* never falls back to `PATH` (nothing in an APK sandbox resolves a bare
* `monero-wallet-rpc`).
*/
object WalletChildBinaries {
/** `jniLibs/<abi>/` entry name for `monero-wallet-rpc`. */
const val WALLET_RPC_LIB: String = "libmonerowalletrpc.so"
/**
* Wallet file name inside `$ONIONWIRE_HOME/wallet`. Mirrors the core's
* `wallet::DEFAULT_WALLET_FILENAME`, so a config saved from here and a
* config the core defaults to name the same file.
*/
const val WALLET_FILENAME: String = "onionwire"
/**
* `jniLibs/<abi>/` entry name for the `arti` SOCKS child. **Not bundled in
* this build** — a `.onion` daemon needs a separate Rust binary, which is a
* follow-up (see `android/MONERO_BINARIES.md`). The constant exists so the
* screen can name the path it would use, and so the absence is checkable
* rather than assumed.
*/
const val ARTI_LIB: String = "libarti.so"
/**
* Resolve the bundled binaries under [nativeLibraryDir].
*
* A null/blank directory (or a missing file) means this install does not
* carry the binary — the screen says so instead of offering a Start that
* can only fail.
*/
fun resolve(nativeLibraryDir: String?): WalletChildBinaryPaths =
WalletChildBinaryPaths(
walletRpc = existing(nativeLibraryDir, WALLET_RPC_LIB),
arti = existing(nativeLibraryDir, ARTI_LIB),
)
/**
* The absolute path the core is handed for an entry, whether or not the
* file is present.
*
* Used for `arti_bin` on a clearnet/loopback daemon: the core validates
* that `arti_bin` is non-empty for any non-receive-only source but only
* ever spawns it for a `.onion` host, so the value is inert there. Naming
* the path the binary *would* occupy is deliberate — passing a real binary
* that is not `arti` (say, `monero-wallet-rpc`) would be spawned as the
* SOCKS child the moment the user typed an `.onion` host, which is worse
* than an honest `ENOENT`.
*/
fun expectedPath(nativeLibraryDir: String?, entry: String): String {
val dir = nativeLibraryDir?.takeIf { it.isNotBlank() } ?: return ""
return File(dir, entry).absolutePath
}
private fun existing(nativeLibraryDir: String?, entry: String): String? {
val dir = nativeLibraryDir?.takeIf { it.isNotBlank() } ?: return null
val file = File(dir, entry)
return if (file.isFile) file.absolutePath else null
}
}
/** What this install can actually spawn. */
data class WalletChildBinaryPaths(
val walletRpc: String?,
val arti: String?,
) {
val walletRpcBundled: Boolean get() = walletRpc != null
val artiBundled: Boolean get() = arti != null
}
/**
* Shown when this install carries no `monero-wallet-rpc`. One string, used by
* both the status line and the Start gate, so the two can never disagree about
* why the button is dead.
*/
const val NO_WALLET_RPC_MESSAGE: String =
"monero-wallet-rpc is not bundled in this build, so there is nothing to start."

Binary file not shown.