Compare commits
28 changed files with 1895 additions and 3634 deletions
|
|
@ -57,7 +57,7 @@ env:
|
|||
# feature 'vec_deque_pop_if'`, after the job has already built the rest of
|
||||
# the graph. 1.98 is the release this graph is built with on the dev machine
|
||||
# and in the Android workflows. `--no-default-features` still builds on 1.91
|
||||
# (Arti 0.49's floor); the default build does not, so the image follows the
|
||||
# (Arti 0.46's floor); the default build does not, so the image follows the
|
||||
# default build.
|
||||
RUST_IMAGE: rust:1.98-bookworm
|
||||
CARGO_REGISTRY_VOLUME: onionwire-cargo-registry
|
||||
|
|
|
|||
794
Cargo.lock
generated
794
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
14
Cargo.toml
14
Cargo.toml
|
|
@ -2,7 +2,7 @@
|
|||
name = "onionwire"
|
||||
version = "0.2.1"
|
||||
edition = "2024"
|
||||
# 1.98, not 1.92. Arti 0.49 builds on 1.92, but the default feature set includes
|
||||
# 1.98, not 1.91. Arti 0.46 builds on 1.91, but the default feature set includes
|
||||
# `cuprate-daemon`, and `tapes` (a Cuprate dep this repo cannot patch) calls
|
||||
# `VecDeque::pop_front_if`, stable only from 1.93. 1.98 is the release CI and
|
||||
# the Android workflows actually build that graph with. `--no-default-features`
|
||||
|
|
@ -36,26 +36,26 @@ rustls = ["arti-client/rustls"]
|
|||
# Cuprate's own `arti` feature stays OFF (and is off in its default feature set,
|
||||
# which is why `default-features = false` is load-bearing): it would link a
|
||||
# second, older Tor stack (arti-client 0.44, which cannot unify with this
|
||||
# crate's 0.49) next to OnionWire's. The in-process daemon runs clearnet-only;
|
||||
# crate's 0.46) next to OnionWire's. The in-process daemon runs clearnet-only;
|
||||
# OnionWire's Arti is the only Tor in the process.
|
||||
cuprate-daemon = ["dep:cuprated", "dep:toml"]
|
||||
|
||||
[dependencies]
|
||||
arti-client = { version = "0.49", default-features = false, features = [
|
||||
arti-client = { version = "0.46", default-features = false, features = [
|
||||
"tokio",
|
||||
"onion-service-client",
|
||||
"onion-service-service",
|
||||
"compression",
|
||||
] }
|
||||
futures = "0.3"
|
||||
safelog = "0.10"
|
||||
safelog = "0.9"
|
||||
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
||||
rand = "0.8"
|
||||
rusqlite = { version = "0.36", features = ["bundled-sqlcipher-vendored-openssl"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "time", "net"] }
|
||||
tor-cell = "0.49"
|
||||
tor-hsservice = "0.49"
|
||||
tor-rtcompat = { version = "0.49", features = ["tokio"] }
|
||||
tor-cell = "0.46"
|
||||
tor-hsservice = "0.46"
|
||||
tor-rtcompat = { version = "0.46", features = ["tokio"] }
|
||||
# Direct dependency only to select rustls's crypto provider: Arti pulls rustls in
|
||||
# through `tor-rtcompat` with `default-features = false`, and rustls 0.23
|
||||
# resolves its provider from its OWN `ring`/`aws-lc-rs` features, so without this
|
||||
|
|
|
|||
22
README.md
22
README.md
|
|
@ -3,7 +3,7 @@
|
|||
Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti).
|
||||
No hosted server. Identity is an ed25519 public key; the onion is only a locator.
|
||||
|
||||
Current tagged release: **v0.7.0**. Linux TUI + Android SDK/APK. Two people add
|
||||
Current tagged release: **v0.5.0**. Linux TUI + Android SDK/APK. Two people add
|
||||
each other with an `onionwire:v2:…` invite string (`F2` share / `F3` paste;
|
||||
~1.9 KB because it carries an ML-KEM-768 key). There is no invite QR graphic.
|
||||
Chat is Noise IK over your own v3 onion; when the friend was added from a v2
|
||||
|
|
@ -61,8 +61,8 @@ resulting hash) next to its `.sha256`.
|
|||
**x86_64:**
|
||||
|
||||
```bash
|
||||
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.7.0/onionwire-x86_64-unknown-linux-gnu
|
||||
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.7.0/onionwire-x86_64-unknown-linux-gnu.sha256
|
||||
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.5.0/onionwire-x86_64-unknown-linux-gnu
|
||||
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.5.0/onionwire-x86_64-unknown-linux-gnu.sha256
|
||||
sha256sum -c onionwire-x86_64-unknown-linux-gnu.sha256
|
||||
chmod +x onionwire-x86_64-unknown-linux-gnu
|
||||
./onionwire-x86_64-unknown-linux-gnu --version
|
||||
|
|
@ -71,8 +71,8 @@ chmod +x onionwire-x86_64-unknown-linux-gnu
|
|||
**aarch64:**
|
||||
|
||||
```bash
|
||||
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.7.0/onionwire-aarch64-unknown-linux-gnu
|
||||
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.7.0/onionwire-aarch64-unknown-linux-gnu.sha256
|
||||
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.5.0/onionwire-aarch64-unknown-linux-gnu
|
||||
curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.5.0/onionwire-aarch64-unknown-linux-gnu.sha256
|
||||
sha256sum -c onionwire-aarch64-unknown-linux-gnu.sha256
|
||||
chmod +x onionwire-aarch64-unknown-linux-gnu
|
||||
./onionwire-aarch64-unknown-linux-gnu --version
|
||||
|
|
@ -103,7 +103,7 @@ format (`<hash> onionwire-<target>`).
|
|||
### Option B — build from source
|
||||
|
||||
Needs [Rust](https://rustup.rs/) **1.98+** (`edition = "2024"`; `Cargo.toml`
|
||||
`rust-version = "1.98"`). Arti 0.49 itself builds on 1.92, but the default
|
||||
`rust-version = "1.98"`). Arti 0.46 itself builds on 1.91, but the default
|
||||
feature set includes the in-process chain daemon, and that graph does not
|
||||
(`tapes` calls `VecDeque::pop_front_if`, stable since 1.93). Do not install `tor`.
|
||||
|
||||
|
|
@ -134,7 +134,7 @@ system OpenSSL headers or `pkg-config` are required — Arti's TLS backend is
|
|||
`rustls`.
|
||||
|
||||
The crate version in `Cargo.toml` is **not** bumped by the release workflow. The
|
||||
tag (`v0.7.0`) is the version users download; `onionwire --version` prints
|
||||
tag (`v0.5.0`) is the version users download; `onionwire --version` prints
|
||||
`CARGO_PKG_VERSION` from the tree that was built.
|
||||
|
||||
### Two instances on one machine
|
||||
|
|
@ -433,9 +433,7 @@ invites interoperate.
|
|||
- **SDK** — `onionwire-sdk-<version>.aar`. UniFFI Kotlin over the same Rust crate
|
||||
the TUI runs. See [crates/onionwire-sdk/README.md](crates/onionwire-sdk/README.md).
|
||||
- **APK** — `onionwire-<version>-android-arm64-v8a.apk`. Kotlin + Jetpack Compose.
|
||||
Build notes: [android/README.md](android/README.md). The UI is a design-token
|
||||
system (one accent, 16px cards, three-tab shell: Chats / Wallet / Node &
|
||||
Settings) rather than per-screen styling; see *App shell* in that README.
|
||||
Build notes: [android/README.md](android/README.md).
|
||||
|
||||
The APK build is amd64-only. After the Linux `release` workflow finishes,
|
||||
dispatch `android-release` with that tag so the APK/AAR attach to the same
|
||||
|
|
@ -443,7 +441,7 @@ Forgejo release.
|
|||
|
||||
```bash
|
||||
scripts/build-android-local.sh # -> dist/, with .sha256
|
||||
PUBLISH_TAG=v0.7.0 scripts/build-android-local.sh # + upload to that release
|
||||
PUBLISH_TAG=v0.5.0 scripts/build-android-local.sh # + upload to that release
|
||||
```
|
||||
|
||||
## Releases (maintainers)
|
||||
|
|
@ -463,7 +461,7 @@ Actions → **release** → Run workflow:
|
|||
Then dispatch **android-release** with `tag=<that tag>` to attach the APK + AAR.
|
||||
|
||||
```bash
|
||||
FORGEJO_TOKEN=<pat> scripts/build-release-local.sh v0.7.0
|
||||
FORGEJO_TOKEN=<pat> scripts/build-release-local.sh v0.5.0
|
||||
```
|
||||
|
||||
Do not run `cargo publish`; `publish = false`.
|
||||
|
|
|
|||
|
|
@ -192,11 +192,9 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str
|
|||
}
|
||||
|
||||
composable(Routes.Wallet) {
|
||||
// A top-level tab, so no back chevron — same shape as the
|
||||
// Chats and Node & Settings destinations. The catalogue
|
||||
// sub-screen still gets one from its own top bar.
|
||||
WalletScreen(
|
||||
vm = vm,
|
||||
onBack = { nav.popBackStack() },
|
||||
onOpenWallets = { nav.navigate(Routes.Wallets) },
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,9 +15,6 @@ import com.siriusdevops.onionwire.keepalive.KeepAliveStatus
|
|||
import com.siriusdevops.onionwire.keepalive.NodeHost
|
||||
import com.siriusdevops.onionwire.ui.SeedBackupGate
|
||||
import com.siriusdevops.onionwire.ui.WalletKeyOrigin
|
||||
import com.siriusdevops.onionwire.ui.NO_CHAIN_SOURCE_NOTICE
|
||||
import com.siriusdevops.onionwire.ui.storedWalletBinBlockedReason
|
||||
import com.siriusdevops.onionwire.ui.walletBinHealPath
|
||||
import com.siriusdevops.onionwire.ui.walletFailureText
|
||||
import com.siriusdevops.onionwire.wallet.ChainStorage
|
||||
import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE
|
||||
|
|
@ -1018,72 +1015,10 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
|||
*/
|
||||
fun chainFreeBytes(): Long? = ChainStorage.freeBytes(home)
|
||||
|
||||
/**
|
||||
* Repairs a stored `walletRpcBin` this device cannot execute, and reports
|
||||
* whether it wrote anything back.
|
||||
*
|
||||
* A wallet-child record written by an older install can carry the bare name
|
||||
* `monero-wallet-rpc` (or an empty string). Nothing in an APK sandbox
|
||||
* resolves a bare name on `PATH`, so `start_wallet_child` spawns it and dies
|
||||
* with `No such file or directory` — while the Start gate, which only ever
|
||||
* looked at the *resolved* bundle, stayed green. This re-points the stored
|
||||
* record at the absolute `nativeLibraryDir` path this install actually
|
||||
* carries, before anything is spawned.
|
||||
*
|
||||
* What it deliberately does not do:
|
||||
* - it never changes `kind`, host, port, mode, datadir or wallet filename —
|
||||
* a repair of the binary is not a change of chain source;
|
||||
* - it does nothing for receive-only (`ChainChoice.NONE`), which stores a
|
||||
* bin it never spawns;
|
||||
* - it never overwrites a stored path that exists and is executable, even
|
||||
* when that path is not the bundled binary — a user who pointed at a real
|
||||
* file keeps it;
|
||||
* - it never fails loudly: a repair that cannot be made leaves the stored
|
||||
* record alone, and the gate then names the path it will try to spawn.
|
||||
*/
|
||||
suspend fun healStoredWalletBin(bins: WalletChildBinaryPaths): Result<Boolean> =
|
||||
withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val wire = requireWire()
|
||||
val stored = runCatching { wire.chainSource() }.getOrNull()
|
||||
?: return@runCatching false
|
||||
if (stored.kind == ChainChoice.NONE) return@runCatching false
|
||||
val healed = walletBinHealPath(stored.walletRpcBin, bins.walletRpc)
|
||||
?: return@runCatching false
|
||||
wire.setChainSource(
|
||||
ChainConfig(
|
||||
kind = stored.kind,
|
||||
monerodBin = stored.monerodBin,
|
||||
monerodDatadir = stored.monerodDatadir,
|
||||
host = stored.host,
|
||||
port = stored.port,
|
||||
walletRpcBin = healed,
|
||||
artiBin = stored.artiBin,
|
||||
walletFilename = stored.walletFilename,
|
||||
mainnet = stored.mainnet,
|
||||
prune = stored.prune,
|
||||
),
|
||||
)
|
||||
true
|
||||
}
|
||||
}.onSuccess { healed ->
|
||||
if (healed) {
|
||||
refreshChainSource()
|
||||
refreshWalletChild()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Kick off start on [viewModelScope] so leaving the composition does not
|
||||
* cancel Cuprate launch. Returns immediately; watch [walletChildStarting]
|
||||
* and [walletChildError]. Core status stays `off` until the node answers.
|
||||
*
|
||||
* Self-heals the stored binary first, then re-reads that stored record and
|
||||
* refuses to spawn when it still names a path this device cannot run. The
|
||||
* screen's gate is the primary door, but an auto-start from a mode tap is
|
||||
* not the only caller: this is the last place that can stop a doomed spawn,
|
||||
* and the reason it writes is the named path rather than the core's opaque
|
||||
* `spawn monero-wallet-rpc: …`.
|
||||
*/
|
||||
fun startWalletChild() {
|
||||
if (!startInFlight.compareAndSet(false, true)) return
|
||||
|
|
@ -1091,20 +1026,6 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
|||
_walletChildError.value = null
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val bins = bundledBinaries()
|
||||
healStoredWalletBin(bins)
|
||||
val stored = withContext(Dispatchers.IO) {
|
||||
runCatching { requireWire().chainSource() }.getOrNull()
|
||||
}
|
||||
if (stored == null || stored.kind == ChainChoice.NONE) {
|
||||
_walletChildError.value = NO_CHAIN_SOURCE_NOTICE
|
||||
return@launch
|
||||
}
|
||||
val blocked = storedWalletBinBlockedReason(stored.walletRpcBin, bins.walletRpc)
|
||||
if (blocked != null) {
|
||||
_walletChildError.value = blocked
|
||||
return@launch
|
||||
}
|
||||
val started = withContext(Dispatchers.IO) {
|
||||
runCatching { requireWire().startWalletChild() }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ import uniffi.onionwire_sdk.checkAddress
|
|||
* store error after it.
|
||||
* - An **empty** address is a real, allowed value: it clears the profile
|
||||
* address. It is labelled with its consequence, because with no profile
|
||||
* address and no running wallet the core has nothing to hand a payer
|
||||
* address and no running wallet child the core has nothing to hand a payer
|
||||
* (`Node::wallet_receive_address`) and the invoice path fails.
|
||||
* - The bio is carried, not owned: a save that did not touch the bio field
|
||||
* writes back the value read from the store immediately before the write, so
|
||||
|
|
@ -211,7 +211,7 @@ fun ProfileScreen(
|
|||
supportingText = {
|
||||
Text(
|
||||
// The consequence, on the screen, before a payment fails:
|
||||
// `Node::wallet_receive_address` uses the wallet process's
|
||||
// `Node::wallet_receive_address` uses the wallet child's
|
||||
// subaddress while it is up and this address otherwise,
|
||||
// and with neither there is nothing to be paid to.
|
||||
profileAddressNotice(form.address),
|
||||
|
|
@ -437,7 +437,7 @@ internal const val PROFILE_SAVED: String = "profile saved"
|
|||
/**
|
||||
* What an empty address means, stated where the address is typed.
|
||||
*
|
||||
* `Node::wallet_receive_address` answers with the wallet process's own subaddress
|
||||
* `Node::wallet_receive_address` answers with the wallet child's own subaddress
|
||||
* while it is up, and this address otherwise; with neither, the invoice path
|
||||
* fails outright. The user should read that here, not after a friend's payment
|
||||
* bounces.
|
||||
|
|
@ -445,7 +445,7 @@ internal const val PROFILE_SAVED: String = "profile saved"
|
|||
internal fun profileAddressNotice(address: String): String =
|
||||
if (address.trim().isEmpty()) {
|
||||
"Empty is allowed, and it clears the profile address. Your receive address " +
|
||||
"then comes from the running wallet — with no address " +
|
||||
"then comes from the wallet child while it is running — with no address " +
|
||||
"here and no wallet running, nobody can send you an invoice."
|
||||
} else {
|
||||
"What friends pay to. Validated before it is saved; an invalid address is " +
|
||||
|
|
|
|||
|
|
@ -2,11 +2,10 @@ package com.siriusdevops.onionwire.ui
|
|||
|
||||
import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE
|
||||
import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* One snapshot of the app-owned wallet process, as the wallet screen sees it.
|
||||
* 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
|
||||
|
|
@ -98,7 +97,7 @@ sealed interface WalletChildPhase {
|
|||
data object Unread : WalletChildPhase {
|
||||
override val testTag: String = "child-unread"
|
||||
override val label: String = "reading…"
|
||||
override val contentDescription: String = "Reading the wallet status"
|
||||
override val contentDescription: String = "Reading the wallet child status"
|
||||
override val live: Boolean = false
|
||||
override val dead: Boolean = false
|
||||
}
|
||||
|
|
@ -107,7 +106,7 @@ sealed interface WalletChildPhase {
|
|||
data object Off : WalletChildPhase {
|
||||
override val testTag: String = "child-off"
|
||||
override val label: String = "off"
|
||||
override val contentDescription: String = "The wallet is off"
|
||||
override val contentDescription: String = "The wallet child is off"
|
||||
override val live: Boolean = false
|
||||
override val dead: Boolean = false
|
||||
}
|
||||
|
|
@ -117,7 +116,7 @@ sealed interface WalletChildPhase {
|
|||
override val testTag: String = "child-connecting"
|
||||
override val label: String = "connecting"
|
||||
override val contentDescription: String =
|
||||
"The wallet is starting; its RPC has not answered yet"
|
||||
"The wallet child is up; its wallet RPC has not answered yet"
|
||||
override val live: Boolean = true
|
||||
override val dead: Boolean = false
|
||||
}
|
||||
|
|
@ -136,7 +135,7 @@ sealed interface WalletChildPhase {
|
|||
data object Ready : WalletChildPhase {
|
||||
override val testTag: String = "child-ready"
|
||||
override val label: String = "ready"
|
||||
override val contentDescription: String = "The wallet is ready"
|
||||
override val contentDescription: String = "The wallet child is ready"
|
||||
override val live: Boolean = true
|
||||
override val dead: Boolean = false
|
||||
}
|
||||
|
|
@ -145,7 +144,7 @@ sealed interface WalletChildPhase {
|
|||
data class Exited(val reason: String?) : WalletChildPhase {
|
||||
override val testTag: String = "child-exited"
|
||||
override val label: String = "exited"
|
||||
override val contentDescription: String = "The wallet process exited"
|
||||
override val contentDescription: String = "The wallet child exited"
|
||||
override val live: Boolean = false
|
||||
override val dead: Boolean = true
|
||||
}
|
||||
|
|
@ -159,7 +158,7 @@ sealed interface WalletChildPhase {
|
|||
override val testTag: String = "child-unrecognised"
|
||||
override val label: String = "unknown (${shortSendReason(raw, UNRECOGNISED_BUDGET)})"
|
||||
override val contentDescription: String =
|
||||
"The wallet reported a state this build does not know"
|
||||
"The wallet child reported a state this build does not know"
|
||||
override val live: Boolean = false
|
||||
override val dead: Boolean = false
|
||||
}
|
||||
|
|
@ -337,26 +336,25 @@ 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 status…"
|
||||
const val READING_CHILD_NOTICE: String = "Reading the wallet child status…"
|
||||
|
||||
const val STARTING_CHILD_NOTICE: String =
|
||||
"Start is running. Status stays off until the on-device node answers — that can take a minute, and is not a dead button."
|
||||
|
||||
/**
|
||||
* The alert banner the on-device node is offered with, **before** Start.
|
||||
* 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 mainnet is
|
||||
* unvalidated. The title is the banner's; the two sentences are the body — one
|
||||
* copy of the caveat, never a second one elsewhere on the screen, so the two
|
||||
* can never drift apart.
|
||||
* 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_ON_DEVICE_TITLE: String = "Experimental On-Device Node (Cuprate)"
|
||||
const val CUPRATE_ON_DEVICE_BODY: String =
|
||||
"Pre-production software with incomplete RPC parity (#278). Do not use for significant " +
|
||||
"funds. Mainnet is unvalidated, and Cuprate's own user book says do NOT use cuprated " +
|
||||
"for any serious purposes."
|
||||
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, 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
|
||||
|
|
@ -447,21 +445,13 @@ fun selectedCuprateMode(inProcess: Boolean, mainnet: Boolean, prune: Boolean): C
|
|||
|
||||
/**
|
||||
* Tapping a mode used to only persist `ChainConfig`, which looked like a no-op
|
||||
* besides the storage line. Start when the storage floor would allow Start,
|
||||
* **the Start gate itself would allow it**, and a launch is not already in
|
||||
* flight.
|
||||
*
|
||||
* [startBlocked] is the same reason the Start button is disabled by
|
||||
* (`startGateReason`). A mode tap stores the source either way, but persisting
|
||||
* a choice must never launch a child the gate would refuse — the old
|
||||
* storage-only predicate is exactly how an auto-start slipped past a stored
|
||||
* binary that could not run.
|
||||
* besides the storage line. Start when the storage floor would allow Start and
|
||||
* a launch is not already in flight.
|
||||
*/
|
||||
fun shouldStartAfterSelectingChain(
|
||||
storageBlocked: String?,
|
||||
starting: Boolean,
|
||||
startBlocked: String? = null,
|
||||
): Boolean = storageBlocked == null && startBlocked == null && !starting
|
||||
): Boolean = storageBlocked == null && !starting
|
||||
|
||||
/**
|
||||
* Bytes as a screen-sized string. Binary units (a "GB" that is really a GiB is how
|
||||
|
|
@ -473,131 +463,6 @@ fun formatBytes(bytes: Long): String = when {
|
|||
else -> "$bytes B"
|
||||
}
|
||||
|
||||
/**
|
||||
* A block height with thousands separators: `3794383` → `3,794,383`.
|
||||
*
|
||||
* Hand-grouped rather than `String.format("%,d")` on purpose: the grouped
|
||||
* format is locale-dependent (some locales use a period or a non-breaking
|
||||
* space), and a block height is a number in a monospace column, not prose. The
|
||||
* screen and its test must print the same string everywhere.
|
||||
*/
|
||||
fun formatBlockCount(blocks: ULong): String {
|
||||
val digits = blocks.toString()
|
||||
val out = StringBuilder(digits.length + digits.length / 3)
|
||||
digits.forEachIndexed { i, c ->
|
||||
if (i > 0 && (digits.length - i) % 3 == 0) out.append(',')
|
||||
out.append(c)
|
||||
}
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* What the node card's progress header renders for one height / target pair.
|
||||
*
|
||||
* [percentText] and [blockText] are null when there is nothing honest to say —
|
||||
* and `target == 0` is exactly that: the daemon reporting **no target** is not
|
||||
* evidence of being caught up (`src/wallet.rs` returns `0` for a height it does
|
||||
* not have, and Cuprate omits the target even at the tip). A percentage invented
|
||||
* from a zero target would read as progress; an unknown target is said in words.
|
||||
*/
|
||||
data class SyncProgress(
|
||||
/** 0f..1f of the track to fill. `0f` whenever the target is unknown. */
|
||||
val fraction: Float,
|
||||
/** `12.8%`, or null when the daemon reported no target. */
|
||||
val percentText: String?,
|
||||
/** `Block 485,253 of 3,794,383`, or null when neither number is known. */
|
||||
val blockText: String?,
|
||||
)
|
||||
|
||||
fun syncProgress(height: ULong, target: ULong): SyncProgress {
|
||||
if (height == 0uL && target == 0uL) return SyncProgress(0f, null, null)
|
||||
if (target == 0uL) {
|
||||
return SyncProgress(
|
||||
fraction = 0f,
|
||||
percentText = null,
|
||||
blockText = "Block ${formatBlockCount(height)} of an unknown target",
|
||||
)
|
||||
}
|
||||
val fraction = (height.toDouble() / target.toDouble()).coerceIn(0.0, 1.0)
|
||||
return SyncProgress(
|
||||
fraction = fraction.toFloat(),
|
||||
percentText = String.format(Locale.US, "%.1f%%", fraction * 100.0),
|
||||
blockText = "Block ${formatBlockCount(height)} of ${formatBlockCount(target)}",
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The balance line, with the core's two sentinels translated into words.
|
||||
*
|
||||
* `walletBalance()` does not throw: it answers `off` (no chain source is
|
||||
* configured at all) or `err` (configured, but the read failed — no wallet file
|
||||
* open, or the process is down) and a formatted amount otherwise. Printing
|
||||
* either sentinel raw is what put the string `wallet off` on the wallet screen;
|
||||
* printing the same word for both is worse, because they are fixed in different
|
||||
* places. The sentinels themselves are the core's contract and are not touched
|
||||
* here — this is the display only.
|
||||
*/
|
||||
fun noWalletBalanceHeadline(balance: String?): String = when (balance) {
|
||||
null -> "…"
|
||||
"off" -> "No Wallet Loaded"
|
||||
"err" -> "Balance unavailable"
|
||||
else -> balance
|
||||
}
|
||||
|
||||
/** `Mainnet Pruned` / `Mainnet Full` / `Testnet` — the three stored modes, as words. */
|
||||
fun chainModeLabel(mainnet: Boolean, prune: Boolean): String = when {
|
||||
!mainnet -> "Testnet"
|
||||
prune -> "Mainnet Pruned"
|
||||
else -> "Mainnet Full"
|
||||
}
|
||||
|
||||
/**
|
||||
* How the node card's header reads. [tone] is the status dot's colour class, not
|
||||
* a decoration: it is the caller's statement about the core's own word.
|
||||
*/
|
||||
enum class NodeStatusTone {
|
||||
/** Nothing is running, and nothing is wrong. */
|
||||
Idle,
|
||||
|
||||
/** Up, or on its way up. */
|
||||
Busy,
|
||||
|
||||
/** Answered and at the tip. */
|
||||
Good,
|
||||
|
||||
/** A state the app cannot read, or a process that is gone. */
|
||||
Bad,
|
||||
}
|
||||
|
||||
data class NodeStatusHead(val title: String, val tone: NodeStatusTone)
|
||||
|
||||
/**
|
||||
* The header sentence for the node card, from the core's `state` alone.
|
||||
*
|
||||
* Fail-closed exactly as [walletChildPhase] is: an unrecognised state gets
|
||||
* [NodeStatusTone.Bad] and never reads as ready. A running child that has not
|
||||
* answered is `Connecting…`, not `Ready` — the RPC has not spoken yet.
|
||||
*/
|
||||
fun nodeStatusHead(
|
||||
input: WalletChildInput?,
|
||||
inProcess: Boolean = false,
|
||||
mainnet: Boolean = false,
|
||||
prune: Boolean = false,
|
||||
): NodeStatusHead {
|
||||
val mode = if (inProcess) " (${chainModeLabel(mainnet, prune)})" else ""
|
||||
return when (walletChildPhase(input)) {
|
||||
WalletChildPhase.Unread -> NodeStatusHead("Reading wallet status", NodeStatusTone.Idle)
|
||||
WalletChildPhase.Off ->
|
||||
NodeStatusHead(if (inProcess) "Node Idle$mode" else "Wallet Offline", NodeStatusTone.Idle)
|
||||
WalletChildPhase.Connecting -> NodeStatusHead("Connecting…", NodeStatusTone.Busy)
|
||||
WalletChildPhase.Syncing ->
|
||||
NodeStatusHead(if (inProcess) "Syncing Node$mode" else "Syncing Wallet", NodeStatusTone.Busy)
|
||||
WalletChildPhase.Ready -> NodeStatusHead("Wallet Ready", NodeStatusTone.Good)
|
||||
is WalletChildPhase.Exited -> NodeStatusHead("Wallet Stopped", NodeStatusTone.Bad)
|
||||
is WalletChildPhase.Unrecognised -> NodeStatusHead("Unknown wallet state", NodeStatusTone.Bad)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Why **Start** is not actionable, or `null` when it is.
|
||||
*
|
||||
|
|
@ -614,11 +479,8 @@ fun startBlockedReason(
|
|||
bins.walletRpc == null -> NO_WALLET_RPC_MESSAGE
|
||||
starting -> STARTING_CHILD_NOTICE
|
||||
input == null -> READING_CHILD_NOTICE
|
||||
// Unreachable from the wallet screen: while the wallet runs the lifecycle
|
||||
// control *is* Stop, so Start is never offered. Kept as a pure predicate so
|
||||
// a stale status read cannot turn the one control into a no-op tap.
|
||||
input.running -> "The wallet is already running."
|
||||
!input.configured -> NO_CHAIN_SOURCE_NOTICE
|
||||
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
|
||||
|
|
@ -626,179 +488,13 @@ fun startBlockedReason(
|
|||
else -> null
|
||||
}
|
||||
|
||||
/** The stored config names no chain source, so there is no daemon to dial. */
|
||||
const val NO_CHAIN_SOURCE_NOTICE: String =
|
||||
"No chain source yet: the wallet needs a daemon to dial."
|
||||
|
||||
/**
|
||||
* Whether [path] is a file this process may `exec`, measured the way the kernel
|
||||
* will measure it at spawn time. A missing file and an existing file without
|
||||
* the execute bit are both "cannot run here" — they differ only in errno.
|
||||
*
|
||||
* Never throws: a path the filesystem refuses to answer for is not executable.
|
||||
*/
|
||||
fun isExecutableWalletBin(path: String): Boolean =
|
||||
runCatching { File(path).let { it.isFile && it.canExecute() } }.getOrDefault(false)
|
||||
|
||||
/**
|
||||
* The absolute path the stored config should keep instead of [storedBin], or
|
||||
* `null` when the stored path is already runnable here (or there is nothing
|
||||
* better to offer).
|
||||
*
|
||||
* This is the repair rule behind the self-heal. A record written by an older
|
||||
* install can carry the bare name `monero-wallet-rpc` (or nothing at all),
|
||||
* which nothing in an APK sandbox resolves on `PATH`; the spawn then dies with
|
||||
* `ENOENT` and the screen had no way to say why. When this build *does* carry
|
||||
* the binary at a resolved absolute path, that path replaces the unusable one.
|
||||
*
|
||||
* It never overwrites a path the user pointed at that actually runs: an
|
||||
* existing, executable file is left alone even when it is not the bundled one.
|
||||
*/
|
||||
fun walletBinHealPath(
|
||||
storedBin: String?,
|
||||
resolvedBin: String?,
|
||||
executable: (String) -> Boolean = ::isExecutableWalletBin,
|
||||
): String? {
|
||||
val resolved = resolvedBin?.takeIf { it.isNotBlank() } ?: return null
|
||||
val stored = storedBin?.trim().orEmpty()
|
||||
if (stored.isNotEmpty() && executable(stored)) return null
|
||||
return resolved
|
||||
}
|
||||
|
||||
/**
|
||||
* Why the **stored** `ChainConfig.walletRpcBin` will not produce a child, or
|
||||
* `null` when it will. [startBlockedReason] only ever sees the *resolved*
|
||||
* binaries, so a stale path saved by an older install passed that gate and
|
||||
* then failed inside `spawn`.
|
||||
*
|
||||
* The reason always names the path it is about, so the next failure report
|
||||
* carries its own cause instead of the opaque `spawn monero-wallet-rpc: No such
|
||||
* file or directory`. A store that holds no path at all is named as such —
|
||||
* "stored bin missing" is a distinct condition from "this build ships none".
|
||||
*/
|
||||
fun storedWalletBinBlockedReason(
|
||||
storedBin: String?,
|
||||
resolvedBin: String?,
|
||||
executable: (String) -> Boolean = ::isExecutableWalletBin,
|
||||
): String? {
|
||||
if (resolvedBin.isNullOrBlank()) return NO_WALLET_RPC_MESSAGE
|
||||
val stored = storedBin?.trim().orEmpty()
|
||||
if (stored.isEmpty()) {
|
||||
return "No wallet binary path is stored for this chain source, so there is nothing to " +
|
||||
"spawn. This build ships $resolvedBin — pick a chain source to store it."
|
||||
}
|
||||
if (executable(stored)) return null
|
||||
return "The stored wallet binary cannot be run on this device: $stored. " +
|
||||
"This build ships $resolvedBin."
|
||||
}
|
||||
|
||||
/**
|
||||
* The full **Start** gate: the eligibility rules above plus the stored binary.
|
||||
*
|
||||
* [startBlockedReason] runs first so its established copy and ordering (no
|
||||
* binary in this build, start in flight, no chain source) is unchanged; the
|
||||
* stored-path check is the new second half. Together they make a populated
|
||||
* `bins` insufficient on its own — which was the hole that let a bare stored
|
||||
* name through.
|
||||
*/
|
||||
fun startGateReason(
|
||||
bins: WalletChildBinaryPaths,
|
||||
input: WalletChildInput?,
|
||||
storedWalletBin: String?,
|
||||
onionDaemon: Boolean = false,
|
||||
starting: Boolean = false,
|
||||
executable: (String) -> Boolean = ::isExecutableWalletBin,
|
||||
): String? =
|
||||
startBlockedReason(bins, input, onionDaemon, starting)
|
||||
?: storedWalletBinBlockedReason(storedWalletBin, bins.walletRpc, executable)
|
||||
|
||||
/**
|
||||
* Why **Create wallet** / **Import wallet** cannot be offered yet, or `null`
|
||||
* when they can.
|
||||
*
|
||||
* Both are RPC calls (`create_wallet` / `restore_deterministic_wallet`) against
|
||||
* the running child. With no child the call cannot succeed, and the core's
|
||||
* refusal is the desktop TUI's `wallet not configured — open F7 …` — a key that
|
||||
* does not exist on a phone. Collecting a passphrase only to print that is the
|
||||
* second dead end this screen must not offer.
|
||||
*/
|
||||
fun walletSetupBlockedReason(input: WalletChildInput?): String? =
|
||||
when (walletChildPhase(input)) {
|
||||
WalletChildPhase.Unread -> READING_CHILD_NOTICE
|
||||
WalletChildPhase.Off -> WALLET_SETUP_NEEDS_CHILD
|
||||
WalletChildPhase.Connecting -> WALLET_SETUP_STARTING
|
||||
is WalletChildPhase.Exited, is WalletChildPhase.Unrecognised -> WALLET_SETUP_NEEDS_CHILD
|
||||
WalletChildPhase.Syncing, WalletChildPhase.Ready -> null
|
||||
}
|
||||
|
||||
/** Shown on the disabled Create / Import controls when no wallet process is up. */
|
||||
const val WALLET_SETUP_NEEDS_CHILD: String =
|
||||
"Create and Import need the wallet process running. Start it on the node card first."
|
||||
|
||||
/** Shown while the child is up but its RPC has not answered yet. */
|
||||
const val WALLET_SETUP_STARTING: String =
|
||||
"The wallet is still starting. Wait until it answers, then create or import."
|
||||
|
||||
/** Tone of the one failure banner a card may paint. */
|
||||
enum class WalletFailureTone {
|
||||
/** Information about a state the app is in, not a failed call. */
|
||||
Info,
|
||||
|
||||
/** A call actually failed. */
|
||||
Error,
|
||||
}
|
||||
|
||||
/**
|
||||
* The banner a card should paint for a display-ready failure string, or `null`
|
||||
* when it should paint none.
|
||||
*
|
||||
* [WALLET_NOT_OPEN_TEXT] is documented as a *state*, not a failure — a running
|
||||
* child with no wallet file open answers every read with the daemon's `-13`,
|
||||
* and that is exactly what first-run looks like. It nevertheless reached the
|
||||
* node card's red `Wallet error` banner, duplicating the `No wallet open` info
|
||||
* banner directly above it. This decision is keyed on the *mapped* text only:
|
||||
* the mapping in [walletFailureText] is untouched, so nothing raw becomes
|
||||
* visible, and only the paint changes.
|
||||
*
|
||||
* - [walletOpen] true: the state has ended, so a stale no-wallet sentence is
|
||||
* dropped entirely.
|
||||
* - [openHintVisible] true: the info banner above already says it — one
|
||||
* sentence, once.
|
||||
* - otherwise the sentence is still information, so it is painted as
|
||||
* [WalletFailureTone.Info] rather than red.
|
||||
*/
|
||||
fun walletFailureBanner(
|
||||
text: String?,
|
||||
openHintVisible: Boolean,
|
||||
walletOpen: Boolean,
|
||||
): WalletFailureBanner? {
|
||||
val shown = text?.takeIf { it.isNotBlank() } ?: return null
|
||||
return if (shown == WALLET_NOT_OPEN_TEXT) {
|
||||
when {
|
||||
walletOpen -> null
|
||||
openHintVisible -> null
|
||||
else -> WalletFailureBanner(shown, WalletFailureTone.Info, "No wallet open")
|
||||
}
|
||||
} else {
|
||||
WalletFailureBanner(shown, WalletFailureTone.Error, "Wallet error")
|
||||
}
|
||||
}
|
||||
|
||||
/** One banner: its sentence, its tone, and its title. */
|
||||
data class WalletFailureBanner(
|
||||
val text: String,
|
||||
val tone: WalletFailureTone,
|
||||
val title: String,
|
||||
)
|
||||
|
||||
|
||||
/**
|
||||
* Why **Stop** is not actionable, or `null` when it is. `stop_wallet_child` is
|
||||
* 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 is running."
|
||||
!input.running -> "No wallet child is running."
|
||||
else -> null
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,13 +14,20 @@ import androidx.compose.foundation.layout.fillMaxSize
|
|||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
|
|
@ -33,21 +40,11 @@ import androidx.compose.ui.Alignment
|
|||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.siriusdevops.onionwire.WireViewModel
|
||||
import com.siriusdevops.onionwire.ui.components.Label
|
||||
import com.siriusdevops.onionwire.ui.components.Mono
|
||||
import com.siriusdevops.onionwire.ui.components.OwAlertBanner
|
||||
import com.siriusdevops.onionwire.ui.components.OwAlertVariant
|
||||
import com.siriusdevops.onionwire.ui.components.OwButton
|
||||
import com.siriusdevops.onionwire.ui.components.OwButtonRow
|
||||
import com.siriusdevops.onionwire.ui.components.OwButtonVariant
|
||||
import com.siriusdevops.onionwire.ui.components.OwCard
|
||||
import com.siriusdevops.onionwire.ui.components.OwPill
|
||||
import com.siriusdevops.onionwire.ui.components.OwSectionTitle
|
||||
import com.siriusdevops.onionwire.ui.components.OwTopBar
|
||||
import kotlinx.coroutines.launch
|
||||
import uniffi.onionwire_sdk.WalletKeys
|
||||
import uniffi.onionwire_sdk.WalletRow
|
||||
|
|
@ -86,7 +83,7 @@ internal fun walletRowDate(createdAt: Long): String {
|
|||
}
|
||||
|
||||
/**
|
||||
* Whether the wallet process has a wallet open that the RPC answers for.
|
||||
* Whether the wallet child has a wallet open that the RPC answers for.
|
||||
*
|
||||
* The core's `state` is the only honest signal available here: `connecting`
|
||||
* means its wallet RPC has not answered, `off`/`exited` mean there is no child
|
||||
|
|
@ -129,8 +126,8 @@ internal fun walletSecretsBlockedReason(
|
|||
isActive: Boolean,
|
||||
walletReadable: Boolean,
|
||||
): String? = when {
|
||||
!isActive -> "Open this wallet to view its backup."
|
||||
!walletReadable -> "The wallet is not running — start it on the wallet screen to read the backup."
|
||||
!isActive -> "open this wallet to view its backup"
|
||||
!walletReadable -> "the wallet child is not running — start it on the wallet screen to read the backup"
|
||||
else -> null
|
||||
}
|
||||
|
||||
|
|
@ -162,45 +159,16 @@ private val RAW_RPC_CODE = Regex("""(?<![\d-])-13(?!\d)""")
|
|||
*/
|
||||
private val RAW_JSON = Regex("""[{}]|\[\s*\{|"(error|code|message|result|jsonrpc)"\s*:""")
|
||||
|
||||
/**
|
||||
* Shown instead of the daemon's `-13` / `No wallet file` / JSON answer.
|
||||
*
|
||||
* A state the app is *in*, not a failure of the last call — the wallet screen
|
||||
* renders it as an info banner, never as a red error line.
|
||||
*/
|
||||
/** Shown instead of the daemon's `-13` / `No wallet file` / JSON answer. */
|
||||
const val WALLET_NOT_OPEN_TEXT: String =
|
||||
"Open or create a wallet to enable balance, address, and backup controls."
|
||||
"No wallet is open in the wallet child yet. Open one from the list below — a wallet that " +
|
||||
"needs a passphrase asks for it here — and the balance, address and backups work again."
|
||||
|
||||
/** Shown instead of a raw JSON refusal that names no condition the user can act on. */
|
||||
const val WALLET_DAEMON_REFUSED_TEXT: String =
|
||||
"The wallet daemon refused that request and gave no readable reason. Check the wallet " +
|
||||
"The wallet daemon refused that request and gave no readable reason. Check the wallet child " +
|
||||
"on the wallet screen, then try again."
|
||||
|
||||
/**
|
||||
* The desktop TUI's refusal, in the phone's words.
|
||||
*
|
||||
* `src/wallet.rs::NOT_CONFIGURED_MSG` is written for the Linux TUI: "wallet not
|
||||
* configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC". Neither `F7`
|
||||
* nor an environment variable exists on the phone, and the actual condition is
|
||||
* simply that no wallet child is running. Printing that string was the second
|
||||
* dead end on the device: a user who typed a passphrase into Create got told to
|
||||
* press a key that is not on the device.
|
||||
*/
|
||||
const val WALLET_RPC_NOT_RUNNING_TEXT: String =
|
||||
"The wallet process is not running, so there is nothing to open a wallet on. " +
|
||||
"Start it on the node card, then create or import."
|
||||
|
||||
/**
|
||||
* The TUI's unconfigured copy, and nothing else: the F7 hint, the phrase
|
||||
* "wallet not configured", or an instruction to set `ONIONWIRE_WALLET_RPC`.
|
||||
* All three describe the same fact — no wallet RPC to dial — and none of them
|
||||
* is actionable on a phone.
|
||||
*/
|
||||
private val TUI_WALLET_NOT_CONFIGURED = Regex(
|
||||
"""open\s*f7|wallet not configured|ONIONWIRE_WALLET_RPC""",
|
||||
RegexOption.IGNORE_CASE,
|
||||
)
|
||||
|
||||
/**
|
||||
* A failure string safe to put on screen, or `null` when there is nothing to
|
||||
* show.
|
||||
|
|
@ -226,9 +194,6 @@ internal fun walletFailureText(raw: String?): String? {
|
|||
val text = raw?.trim().orEmpty()
|
||||
return when {
|
||||
text.isEmpty() -> null
|
||||
// Before the JSON / -13 filters: the TUI's refusal is a plain sentence
|
||||
// the raw pass-through would otherwise let reach the phone verbatim.
|
||||
TUI_WALLET_NOT_CONFIGURED.containsMatchIn(text) -> WALLET_RPC_NOT_RUNNING_TEXT
|
||||
NO_WALLET_FILE.containsMatchIn(text) || RAW_RPC_CODE.containsMatchIn(text) ->
|
||||
WALLET_NOT_OPEN_TEXT
|
||||
RAW_JSON.containsMatchIn(text) -> WALLET_DAEMON_REFUSED_TEXT
|
||||
|
|
@ -286,7 +251,7 @@ internal fun walletPassphrasePromptVisible(needsPassphrase: Boolean, walletOpen:
|
|||
* A file name is required because the open is per-file (`open_wallet` on the
|
||||
* file the child is pointed at); a blank passphrase is refused by the core
|
||||
* anyway, so the button stays dead rather than round-tripping a guaranteed
|
||||
* failure. An in-flight open is not re-submitted: it restarts the wallet process.
|
||||
* failure. An in-flight open is not re-submitted: it restarts the wallet child.
|
||||
*/
|
||||
internal fun walletPassphraseSubmitEnabled(
|
||||
activeFilename: String?,
|
||||
|
|
@ -305,14 +270,14 @@ internal fun walletPassphraseBlockedReason(
|
|||
typed: String,
|
||||
): String? = when {
|
||||
activeFilename == null ->
|
||||
"No wallet file is open yet — open one from the list below."
|
||||
typed.isEmpty() -> "Type the passphrase for this wallet file."
|
||||
"the wallet child is not pointed at a wallet file yet — open one from the list below"
|
||||
typed.isEmpty() -> "type the passphrase for this wallet file"
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* Why the wallet process has nothing open, in this app's words — or `null` when
|
||||
* it has a wallet open, or nothing is running to hold one.
|
||||
* Why the wallet child has nothing open, in this app's words — or `null` when
|
||||
* it has a wallet open, or no child is running to hold one.
|
||||
*
|
||||
* A live `monero-wallet-rpc` is not a usable wallet: it starts with no wallet
|
||||
* file open, and every read then answers `-13 No wallet file`. The status line
|
||||
|
|
@ -329,10 +294,11 @@ internal fun walletChildOpenHint(
|
|||
): String? = when {
|
||||
!childRunning || walletOpen -> null
|
||||
needsPassphrase ->
|
||||
"The wallet needs its passphrase: open it on the Saved wallets screen, where the " +
|
||||
"prompt is."
|
||||
"No wallet is open in the wallet child: it needs the passphrase for the file it is " +
|
||||
"pointed at. Open it on the Saved wallets screen, where the prompt is."
|
||||
else ->
|
||||
"Select a saved wallet or create a new one to view your balance and transact."
|
||||
"No wallet is open in the wallet child yet. Open a saved wallet on the Saved wallets " +
|
||||
"screen, or create or import one here."
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -353,6 +319,7 @@ internal fun walletChildOpenHint(
|
|||
* in saved state (`remember`, not `rememberSaveable`, and cleared on
|
||||
* dispose).
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun WalletManagerScreen(
|
||||
vm: WireViewModel,
|
||||
|
|
@ -536,24 +503,25 @@ fun WalletManagerScreen(
|
|||
// Root owns systemBars ∪ ime, exactly as the wallet screen does (see
|
||||
// `screenContentInsets`).
|
||||
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
||||
containerColor = OwColors.Canvas,
|
||||
topBar = {
|
||||
OwTopBar(
|
||||
title = "Saved wallets",
|
||||
// A pushed sub-screen, so the chevron — never the word "Back".
|
||||
onBack = onBack,
|
||||
TopAppBar(
|
||||
title = { Text("Saved wallets") },
|
||||
navigationIcon = {
|
||||
TextButton(onClick = onBack) { Text("Back") }
|
||||
},
|
||||
actions = {
|
||||
OwButton(
|
||||
text = "Refresh",
|
||||
variant = OwButtonVariant.Outline,
|
||||
TextButton(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
vm.refreshWalletChild()
|
||||
reload()
|
||||
}
|
||||
},
|
||||
)
|
||||
) { Text("Refresh") }
|
||||
},
|
||||
colors = TopAppBarDefaults.topAppBarColors(
|
||||
containerColor = MaterialTheme.colorScheme.background,
|
||||
),
|
||||
)
|
||||
},
|
||||
) { pad ->
|
||||
|
|
@ -591,21 +559,22 @@ fun WalletManagerScreen(
|
|||
)
|
||||
}
|
||||
keysError?.let { message ->
|
||||
OwAlertBanner(
|
||||
variant = OwAlertVariant.Error,
|
||||
title = "Could not read the open wallet's private keys",
|
||||
description = message,
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp)
|
||||
.testTag("wallet-keys-error"),
|
||||
action = {
|
||||
OwButton(
|
||||
text = "Dismiss",
|
||||
variant = OwButtonVariant.Outline,
|
||||
onClick = { keysError = null },
|
||||
)
|
||||
},
|
||||
)
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer,
|
||||
),
|
||||
) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text("could not read the open wallet's private keys")
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(message, style = MaterialTheme.typography.bodySmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TextButton(onClick = { keysError = null }) { Text("Dismiss") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
actionError?.let { ErrorText(it) }
|
||||
|
|
@ -639,55 +608,46 @@ fun WalletManagerScreen(
|
|||
// A read failure is not an empty catalogue, and the two must
|
||||
// not read alike: one is "the store did not answer", the other
|
||||
// is "you have no wallets yet".
|
||||
listError != null -> OwAlertBanner(
|
||||
variant = OwAlertVariant.Error,
|
||||
title = "Could not read the wallet catalogue",
|
||||
description = listError ?: "",
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp)
|
||||
.testTag("wallet-list-error"),
|
||||
action = {
|
||||
OwButton(
|
||||
text = "Retry",
|
||||
variant = OwButtonVariant.Outline,
|
||||
onClick = { scope.launch { reload() } },
|
||||
listError != null -> Column(Modifier.padding(12.dp)) {
|
||||
Text(
|
||||
"could not read the wallet catalogue",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
},
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
listError ?: "",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TextButton(onClick = { scope.launch { reload() } }) { Text("Retry") }
|
||||
}
|
||||
|
||||
listed == null -> Text(
|
||||
"Loading…",
|
||||
"loading…",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = OwColors.TextSecondary,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
modifier = Modifier.padding(12.dp),
|
||||
)
|
||||
|
||||
listed.isEmpty() -> OwCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
) {
|
||||
OwSectionTitle("No saved wallets yet")
|
||||
Spacer(Modifier.height(6.dp))
|
||||
listed.isEmpty() -> Column(Modifier.padding(12.dp)) {
|
||||
Text("No saved wallets yet", style = MaterialTheme.typography.titleSmall)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"Wallets this install remembers show up here. Create or import one " +
|
||||
"on the wallet screen and it appears on the next look.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = OwColors.TextSecondary,
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
OwButton(
|
||||
text = "Create or import a wallet",
|
||||
variant = OwButtonVariant.Primary,
|
||||
onClick = onBack,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Button(onClick = onBack) { Text("Create or import a wallet") }
|
||||
}
|
||||
|
||||
else -> {
|
||||
Label(
|
||||
"${listed.size} SAVED ${if (listed.size == 1) "WALLET" else "WALLETS"}",
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
Text(
|
||||
"${listed.size} saved ${if (listed.size == 1) "wallet" else "wallets"}",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
)
|
||||
listed.forEach { row ->
|
||||
val isActive = active != null && active == row.walletFilename
|
||||
|
|
@ -720,7 +680,7 @@ fun WalletManagerScreen(
|
|||
* and whether it is the open one.
|
||||
*
|
||||
* The open row is not tappable. Re-opening it would stop and restart a running
|
||||
* wallet process onto the file it already has open — a slow no-op whose only
|
||||
* wallet child onto the file it already has open — a slow no-op whose only
|
||||
* effect is to make the screen look like it did something.
|
||||
*/
|
||||
@Composable
|
||||
|
|
@ -734,12 +694,16 @@ private fun WalletRowCard(
|
|||
onShowPhrase: () -> Unit,
|
||||
onShowKeys: () -> Unit,
|
||||
) {
|
||||
OwCard(
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 6.dp)
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.then(if (isActive) Modifier else Modifier.clickable(enabled = !opening, onClick = onOpen)),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
),
|
||||
) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
|
|
@ -747,59 +711,57 @@ private fun WalletRowCard(
|
|||
) {
|
||||
Text(
|
||||
walletRowLabel(row.name, row.walletFilename),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = OwColors.TextPrimary,
|
||||
modifier = Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
when {
|
||||
isActive -> OwPill(
|
||||
text = "In use",
|
||||
textColor = OwColors.Accent,
|
||||
container = OwColors.InfoTint,
|
||||
borderColor = OwColors.InfoBorder,
|
||||
dotColor = OwColors.Accent,
|
||||
isActive -> Text(
|
||||
"in use",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
opening -> Text(
|
||||
"opening…",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
else -> Text(
|
||||
"tap to open",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
opening -> OwPill(text = "Opening…", textColor = OwColors.TextSecondary)
|
||||
else -> OwPill(text = "Tap to open", textColor = OwColors.TextSecondary)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Label("FILE")
|
||||
Mono(row.walletFilename)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"Created ${walletRowDate(row.createdAt)}",
|
||||
"file ${row.walletFilename}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = OwColors.TextSecondary,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
)
|
||||
Text(
|
||||
"created ${walletRowDate(row.createdAt)}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OwButtonRow {
|
||||
OwButton(
|
||||
text = "Recovery phrase",
|
||||
variant = OwButtonVariant.Outline,
|
||||
enabled = secretsEnabled,
|
||||
onClick = onShowPhrase,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
OwButton(
|
||||
text = "Private keys",
|
||||
variant = OwButtonVariant.Outline,
|
||||
enabled = secretsEnabled,
|
||||
onClick = onShowKeys,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = onShowPhrase, enabled = secretsEnabled) {
|
||||
Text("Recovery phrase")
|
||||
}
|
||||
OutlinedButton(onClick = onShowKeys, enabled = secretsEnabled) {
|
||||
Text("Private keys")
|
||||
}
|
||||
}
|
||||
blockedReason?.let {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = OwColors.TextMuted,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -812,10 +774,10 @@ private fun WalletRowCard(
|
|||
* wallet file. It is never logged, never persisted, and the caller drops it when
|
||||
* the screen goes.
|
||||
*
|
||||
* Submit is dead while the wallet is not running: the core verifies a
|
||||
* Submit is dead while the wallet child is not running: the core verifies a
|
||||
* passphrase against a live daemon and refuses to seal an unverified one, so a
|
||||
* tap there could only fail. When it *is* up — including `connecting`, whose RPC
|
||||
* has not answered yet — the core restarts it onto the file with this
|
||||
* tap there could only fail. When the child *is* up — including `connecting`,
|
||||
* whose RPC has not answered yet — the core restarts it onto the file with this
|
||||
* passphrase, which is exactly the fix.
|
||||
*/
|
||||
@Composable
|
||||
|
|
@ -829,23 +791,26 @@ private fun WalletPassphraseCard(
|
|||
error: String?,
|
||||
onSubmit: () -> Unit,
|
||||
) {
|
||||
OwCard(
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp)
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp)
|
||||
.testTag("wallet-passphrase-card"),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
),
|
||||
) {
|
||||
OwSectionTitle("This wallet needs its passphrase")
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text("This wallet needs its passphrase", style = MaterialTheme.typography.titleSmall)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"The wallet is pointed at ${filename ?: "a wallet file"} but this install " +
|
||||
"The wallet child is pointed at ${filename ?: "a wallet file"} but this install " +
|
||||
"holds no passphrase that opens it — the wallet was created before the " +
|
||||
"passphrase was stored, or on another device. Type it once: the wallet " +
|
||||
"opens, and later starts reopen it on their own.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = OwColors.TextSecondary,
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = typed,
|
||||
onValueChange = onTyped,
|
||||
|
|
@ -857,46 +822,46 @@ private fun WalletPassphraseCard(
|
|||
.fillMaxWidth()
|
||||
.testTag("wallet-passphrase-input"),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"Never copied to the clipboard, never logged, and dropped when you leave this screen.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = OwColors.TextSecondary,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
if (!childRunning) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OwAlertBanner(
|
||||
variant = OwAlertVariant.Info,
|
||||
title = "The wallet is not running",
|
||||
description = "Start it on the wallet screen, then come back.",
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"the wallet child is not running — start it on the wallet screen, then come back",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
error?.let {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OwAlertBanner(
|
||||
variant = OwAlertVariant.Error,
|
||||
title = "Could not open this wallet",
|
||||
description = it,
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
blockedReason?.let {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OwAlertBanner(
|
||||
variant = OwAlertVariant.Info,
|
||||
title = "Not ready to open",
|
||||
description = it,
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
OwButton(
|
||||
text = if (inFlight) "Opening…" else "Open this wallet",
|
||||
variant = OwButtonVariant.Primary,
|
||||
enabled = childRunning && walletPassphraseSubmitEnabled(filename, typed, inFlight),
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
Button(
|
||||
onClick = onSubmit,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("wallet-passphrase-submit"),
|
||||
)
|
||||
enabled = childRunning &&
|
||||
walletPassphraseSubmitEnabled(filename, typed, inFlight),
|
||||
modifier = Modifier.testTag("wallet-passphrase-submit"),
|
||||
) { Text(if (inFlight) "Opening…" else "Open this wallet") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -915,57 +880,64 @@ private fun PrivateKeysCard(
|
|||
warning: String,
|
||||
onDone: () -> Unit,
|
||||
) {
|
||||
OwCard(
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp)
|
||||
.testTag("wallet-private-keys-card"),
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer,
|
||||
),
|
||||
) {
|
||||
OwSectionTitle("Private keys of the open wallet")
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(warning, style = MaterialTheme.typography.bodySmall, color = OwColors.Danger)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Label("VIEW KEY")
|
||||
// Mono, and deliberately no testTag: a handle on a spend secret is a
|
||||
// handle an automation can read back.
|
||||
Mono(keys.viewKey, modifier = Modifier.fillMaxWidth())
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text("Private keys of the open wallet", style = MaterialTheme.typography.titleSmall)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(warning, style = MaterialTheme.typography.bodySmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"view key",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
keys.viewKey,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
val spend = keys.spendKey
|
||||
if (spend != null) {
|
||||
Label("SPEND KEY")
|
||||
Mono(spend, modifier = Modifier.fillMaxWidth())
|
||||
Text(
|
||||
"spend key",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
spend,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
"View-only wallet — no spend key.",
|
||||
"view-only wallet — no spend key",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = OwColors.TextSecondary,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
OwButton(
|
||||
text = "Done",
|
||||
variant = OwButtonVariant.Outline,
|
||||
onClick = onDone,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
Button(onClick = onDone) { Text("Done") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A display-ready failure line, as a banner. Never carries a secret; callers
|
||||
* pass errors.
|
||||
*
|
||||
* "No wallet is open" is not a failure — it is a state the app is in, and it
|
||||
* gets the info banner and its own title. Only a real refusal is red.
|
||||
*/
|
||||
/** A display-ready failure line. Never carries a secret; callers pass errors. */
|
||||
@Composable
|
||||
private fun ErrorText(text: String) {
|
||||
val notOpen = text == WALLET_NOT_OPEN_TEXT
|
||||
OwAlertBanner(
|
||||
variant = if (notOpen) OwAlertVariant.Info else OwAlertVariant.Error,
|
||||
title = if (notOpen) "No wallet open" else "Something went wrong",
|
||||
description = text,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -17,7 +17,6 @@ import androidx.compose.runtime.getValue
|
|||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.role
|
||||
import androidx.compose.ui.semantics.selected
|
||||
|
|
@ -43,14 +42,6 @@ fun OwSegmentedControl(
|
|||
onSelect: (Int) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true,
|
||||
/**
|
||||
* Optional per-segment `testTag`s, one per option. Additive: omitted (the
|
||||
* default) leaves every existing call site byte-identical. It exists because
|
||||
* a merged "Pruned / Full / Testnet" track has no per-value handle otherwise,
|
||||
* and the wallet screen's tests address each segment by the tag it had when
|
||||
* the three options were three stacked buttons.
|
||||
*/
|
||||
testTags: List<String?> = emptyList(),
|
||||
) {
|
||||
Row(
|
||||
modifier = modifier
|
||||
|
|
@ -76,14 +67,12 @@ fun OwSegmentedControl(
|
|||
animationSpec = tween(durationMillis = 160),
|
||||
label = "segment-text",
|
||||
)
|
||||
val tag = testTags.getOrNull(index)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.height(36.dp)
|
||||
.clip(RoundedCornerShape(9.dp))
|
||||
.background(container)
|
||||
.then(if (tag != null) Modifier.testTag(tag) else Modifier)
|
||||
.clickable(enabled = enabled && !selected) { onSelect(index) }
|
||||
.semantics {
|
||||
role = Role.Tab
|
||||
|
|
|
|||
|
|
@ -239,9 +239,7 @@ class ProfileDraftTest {
|
|||
fun an_empty_address_says_nobody_can_pay() {
|
||||
val text = profileAddressNotice("")
|
||||
assertTrue(text.contains("clears the profile address"))
|
||||
// The consequence, not the process name: the copy no longer says
|
||||
// "wallet child" anywhere a user can read it.
|
||||
assertTrue(text.contains("running wallet"))
|
||||
assertTrue(text.contains("wallet child"))
|
||||
assertTrue(text.contains("nobody can send you an invoice"))
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -207,8 +207,8 @@ class WalletChildStatusTextTest {
|
|||
|
||||
@Test
|
||||
fun stop_is_blocked_when_nothing_is_running() {
|
||||
assertTrue(stopBlockedReason(input("off"))!!.contains("No wallet is running"))
|
||||
assertTrue(stopBlockedReason(input("exited"))!!.contains("No wallet is running"))
|
||||
assertTrue(stopBlockedReason(input("off"))!!.contains("No wallet child"))
|
||||
assertTrue(stopBlockedReason(input("exited"))!!.contains("No wallet child"))
|
||||
assertEquals(READING_CHILD_NOTICE, stopBlockedReason(null))
|
||||
}
|
||||
|
||||
|
|
@ -397,7 +397,7 @@ class WalletChildStatusTextTest {
|
|||
"a screen reader is told the same as the eye",
|
||||
spoken.endsWith(walletChildLine(input)),
|
||||
)
|
||||
assertTrue("it is still a sentence", spoken.startsWith("The wallet is starting"))
|
||||
assertTrue("it is still a sentence", spoken.startsWith("The wallet child is up"))
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
@ -417,17 +417,14 @@ class WalletChildStatusTextTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun the_on_device_banner_is_titled_and_says_what_it_costs() {
|
||||
// The banner's title is the plan's exact string; the body keeps every
|
||||
// honesty bound the old single-sentence warning carried.
|
||||
assertEquals("Experimental On-Device Node (Cuprate)", CUPRATE_ON_DEVICE_TITLE)
|
||||
val body = CUPRATE_ON_DEVICE_BODY
|
||||
assertTrue("it names the software", body.contains("Cuprate"))
|
||||
assertTrue("it names the parity gap", body.contains("#278"))
|
||||
assertTrue("it quotes the user book", body.contains("do NOT use cuprated"))
|
||||
assertTrue("it says mainnet is unvalidated", body.contains("Mainnet is unvalidated"))
|
||||
assertTrue("it says not to hold funds", body.contains("Do not use for significant funds"))
|
||||
assertTrue("it is a sentence, not a glyph", body.trim().endsWith("."))
|
||||
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 mainnet is unvalidated", warning.contains("mainnet is unvalidated"))
|
||||
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 ----------------------------------------------------
|
||||
|
|
@ -522,239 +519,4 @@ class WalletChildStatusTextTest {
|
|||
assertEquals("1.5 GiB", formatBytes(3L * 1024 * 1024 * 1024 / 2))
|
||||
assertEquals("3.0 GiB", formatBytes(CHAIN_FREE_SPACE_FLOOR_BYTES))
|
||||
}
|
||||
|
||||
// --- the node card's progress header (plan P4.3) -------------------------
|
||||
|
||||
@Test
|
||||
fun block_counts_group_by_three_regardless_of_locale() {
|
||||
assertEquals("0", formatBlockCount(0uL))
|
||||
assertEquals("999", formatBlockCount(999uL))
|
||||
assertEquals("1,000", formatBlockCount(1_000uL))
|
||||
assertEquals("485,253", formatBlockCount(485_253uL))
|
||||
assertEquals("3,794,383", formatBlockCount(3_794_383uL))
|
||||
assertEquals("12,345,678", formatBlockCount(12_345_678uL))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun the_progress_header_says_percent_and_formatted_blocks() {
|
||||
val p = syncProgress(485_253uL, 3_794_383uL)
|
||||
assertEquals("12.8%", p.percentText)
|
||||
assertEquals("Block 485,253 of 3,794,383", p.blockText)
|
||||
assertTrue("a fraction of the track", p.fraction > 0.12f && p.fraction < 0.13f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun a_caught_up_node_fills_the_track_and_does_not_overflow() {
|
||||
val atTip = syncProgress(3_794_383uL, 3_794_383uL)
|
||||
assertEquals("100.0%", atTip.percentText)
|
||||
assertEquals(1f, atTip.fraction)
|
||||
// A daemon one block ahead of the target it reported must not render
|
||||
// 108% — the bar clamps and the text is the clamped number.
|
||||
val ahead = syncProgress(4_100_000uL, 3_794_383uL)
|
||||
assertEquals("100.0%", ahead.percentText)
|
||||
assertEquals(1f, ahead.fraction)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun an_unknown_target_is_never_a_percentage() {
|
||||
// `target_height == 0` is "the daemon reported no target" — Cuprate
|
||||
// omits it even at the tip. Printing 100% there would claim synced.
|
||||
val p = syncProgress(4_549uL, 0uL)
|
||||
assertNull("no percent from a zero target", p.percentText)
|
||||
assertEquals(0f, p.fraction)
|
||||
assertEquals("Block 4,549 of an unknown target", p.blockText)
|
||||
assertFalse("no percent string leaks", p.blockText!!.contains("%"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun no_numbers_means_no_progress_row() {
|
||||
val p = syncProgress(0uL, 0uL)
|
||||
assertNull(p.percentText)
|
||||
assertNull(p.blockText)
|
||||
assertEquals(0f, p.fraction)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun the_three_modes_are_named_the_way_the_stored_choice_reads() {
|
||||
assertEquals("Mainnet Pruned", chainModeLabel(mainnet = true, prune = true))
|
||||
assertEquals("Mainnet Full", chainModeLabel(mainnet = true, prune = false))
|
||||
assertEquals("Testnet", chainModeLabel(mainnet = false, prune = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun the_node_header_never_reads_ready_without_the_cores_word() {
|
||||
assertEquals("Wallet Offline", nodeStatusHead(input("off", configured = false)).title)
|
||||
assertEquals("Connecting…", nodeStatusHead(input("connecting", running = true)).title)
|
||||
assertEquals(NodeStatusTone.Busy, nodeStatusHead(input("connecting", running = true)).tone)
|
||||
assertTrue(
|
||||
"a running child that has not answered is not ready",
|
||||
nodeStatusHead(input("connecting", running = true)).tone != NodeStatusTone.Good,
|
||||
)
|
||||
assertEquals(NodeStatusTone.Good, nodeStatusHead(input("ready", running = true)).tone)
|
||||
assertEquals(NodeStatusTone.Bad, nodeStatusHead(input("mining", running = true)).tone)
|
||||
assertEquals(
|
||||
"an unknown state is never green",
|
||||
NodeStatusTone.Bad,
|
||||
nodeStatusHead(input("mining", running = true)).tone,
|
||||
)
|
||||
assertEquals("Wallet Stopped", nodeStatusHead(input("exited")).title)
|
||||
assertEquals("Reading wallet status", nodeStatusHead(null).title)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun the_node_header_names_the_mode_only_for_the_on_device_node() {
|
||||
assertEquals(
|
||||
"Syncing Node (Mainnet Pruned)",
|
||||
nodeStatusHead(
|
||||
node(state = "syncing", chainSource = "in-process mainnet pruned", nodeState = "syncing"),
|
||||
inProcess = true,
|
||||
mainnet = true,
|
||||
prune = true,
|
||||
).title,
|
||||
)
|
||||
assertEquals(
|
||||
"Node Idle (Testnet)",
|
||||
nodeStatusHead(input("off", configured = false), inProcess = true, mainnet = false).title,
|
||||
)
|
||||
assertEquals(
|
||||
"Syncing Wallet",
|
||||
nodeStatusHead(input("syncing", running = true, chainSource = "remote daemon")).title,
|
||||
)
|
||||
}
|
||||
|
||||
// --- the stored wallet binary: heal before spawn, then gate on it -------
|
||||
|
||||
private val hostsBundled = "/data/app/~~abc/onionwire-1/lib/arm64/libmonerowalletrpc.so"
|
||||
|
||||
@Test
|
||||
fun a_stored_bare_name_is_repaired_to_the_bundled_absolute_path() {
|
||||
// A record written by an older install: a bare name nothing in an APK
|
||||
// sandbox resolves on PATH. The repair is the absolute path this
|
||||
// install actually carries.
|
||||
assertEquals(hostsBundled, walletBinHealPath("monero-wallet-rpc", hostsBundled) { false })
|
||||
assertEquals("an empty stored bin is healed too", hostsBundled, walletBinHealPath("", hostsBundled) { false })
|
||||
assertEquals("and a missing field", hostsBundled, walletBinHealPath(null, hostsBundled) { false })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun a_stored_path_that_actually_runs_is_never_overwritten() {
|
||||
val userBin = "/data/user/0/com.siriusdevops.onionwire/files/monero-wallet-rpc"
|
||||
assertNull(
|
||||
"a real executable file the user pointed at is left alone",
|
||||
walletBinHealPath(userBin, hostsBundled) { it == userBin },
|
||||
)
|
||||
assertNull(
|
||||
"a bundled path already stored needs no write",
|
||||
walletBinHealPath(hostsBundled, hostsBundled) { it == hostsBundled },
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun no_bundled_binary_means_there_is_nothing_to_repair_with() {
|
||||
assertNull(walletBinHealPath("monero-wallet-rpc", null) { false })
|
||||
assertNull(walletBinHealPath("monero-wallet-rpc", " ") { false })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun a_stored_bin_missing_on_the_device_blocks_start_and_names_the_path() {
|
||||
val why = startGateReason(bundled, input("off"), "monero-wallet-rpc") { false }
|
||||
assertNotNull("a stored path that cannot run must block Start", why)
|
||||
assertTrue("the reason names the stored path it is about", why!!.contains("monero-wallet-rpc"))
|
||||
assertTrue("and the path this build does carry", why.contains(bundled.walletRpc!!))
|
||||
assertTrue("and says it cannot run", why.contains("cannot be run"))
|
||||
assertFalse(
|
||||
"a gate that refuses never lets a mode tap auto-start",
|
||||
shouldStartAfterSelectingChain(storageBlocked = null, starting = false, startBlocked = why),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun an_absent_resolved_bin_blocks_with_the_resolved_absence_message() {
|
||||
// Nothing in this build to spawn: the established string, unchanged.
|
||||
val why = startGateReason(noBinary, input("off"), "/stale/libmonerowalletrpc.so") { false }
|
||||
assertEquals(NO_WALLET_RPC_MESSAGE, why)
|
||||
assertFalse(shouldStartAfterSelectingChain(null, false, why))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun a_runnable_stored_bin_passes_the_gate() {
|
||||
assertNull(startGateReason(bundled, input("off"), bundled.walletRpc) { it == bundled.walletRpc })
|
||||
assertNull(storedWalletBinBlockedReason(bundled.walletRpc, bundled.walletRpc) { true })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun the_gate_keeps_the_established_start_ordering() {
|
||||
// Reading the status still wins over a stored-path complaint: the
|
||||
// existing copy and its order were not rewritten to make room.
|
||||
assertEquals(READING_CHILD_NOTICE, startGateReason(bundled, null, null) { false })
|
||||
assertEquals(
|
||||
NO_CHAIN_SOURCE_NOTICE,
|
||||
startGateReason(bundled, input("off", configured = false, chainSource = "receive-only"), null) { false },
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun a_mode_tap_stores_the_source_but_cannot_auto_start_what_the_gate_refuses() {
|
||||
assertTrue(shouldStartAfterSelectingChain(storageBlocked = null, starting = false))
|
||||
assertTrue(
|
||||
shouldStartAfterSelectingChain(storageBlocked = null, starting = false, startBlocked = null),
|
||||
)
|
||||
assertFalse(
|
||||
shouldStartAfterSelectingChain(
|
||||
storageBlocked = null,
|
||||
starting = false,
|
||||
startBlocked = "The stored wallet binary cannot be run on this device: …",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun create_and_import_are_blocked_without_a_running_child() {
|
||||
assertEquals(WALLET_SETUP_NEEDS_CHILD, walletSetupBlockedReason(input("off")))
|
||||
assertEquals(WALLET_SETUP_NEEDS_CHILD, walletSetupBlockedReason(input("exited", lastError = "spawn …")))
|
||||
assertEquals(WALLET_SETUP_NEEDS_CHILD, walletSetupBlockedReason(input("mining")))
|
||||
assertEquals(WALLET_SETUP_STARTING, walletSetupBlockedReason(input("connecting", running = true)))
|
||||
assertEquals(READING_CHILD_NOTICE, walletSetupBlockedReason(null))
|
||||
assertNull(
|
||||
"a syncing wallet answers RPC, so a create is fine",
|
||||
walletSetupBlockedReason(input("syncing", running = true)),
|
||||
)
|
||||
assertNull(walletSetupBlockedReason(input("ready", running = true)))
|
||||
}
|
||||
|
||||
// --- the no-wallet-open state is information, not a failure ------------
|
||||
|
||||
@Test
|
||||
fun the_no_wallet_open_state_is_information_never_the_red_failure() {
|
||||
// The `No wallet open` info banner owns this sentence; printing it a
|
||||
// second time in red is the duplicate the device report caught.
|
||||
assertNull(
|
||||
"already said once by the info banner above",
|
||||
walletFailureBanner(WALLET_NOT_OPEN_TEXT, openHintVisible = true, walletOpen = false),
|
||||
)
|
||||
val alone = walletFailureBanner(WALLET_NOT_OPEN_TEXT, openHintVisible = false, walletOpen = false)
|
||||
assertNotNull(alone)
|
||||
assertEquals(WalletFailureTone.Info, alone!!.tone)
|
||||
assertEquals("No wallet open", alone.title)
|
||||
assertEquals(WALLET_NOT_OPEN_TEXT, alone.text)
|
||||
assertNull(
|
||||
"the state ended when a wallet was opened",
|
||||
walletFailureBanner(WALLET_NOT_OPEN_TEXT, openHintVisible = false, walletOpen = true),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun a_real_failure_still_paints_red() {
|
||||
val refused = walletFailureText("wallet connect: Connection refused (os error 111)")!!
|
||||
val banner = walletFailureBanner(refused, openHintVisible = true, walletOpen = false)!!
|
||||
assertEquals("a refusal is still a failure", WalletFailureTone.Error, banner.tone)
|
||||
assertEquals("Wallet error", banner.title)
|
||||
assertEquals(refused, banner.text)
|
||||
|
||||
val exited = walletFailureText("spawn monero-wallet-rpc: No such file or directory (os error 2)")!!
|
||||
assertEquals(WalletFailureTone.Error, walletFailureBanner(exited, false, false)!!.tone)
|
||||
|
||||
assertNull(walletFailureBanner(null, true, false))
|
||||
assertNull(walletFailureBanner(" ", true, false))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -117,7 +117,7 @@ class WalletManagerTest {
|
|||
@Test
|
||||
fun a_row_that_is_not_open_says_to_open_it() {
|
||||
val why = walletSecretsBlockedReason(isActive = false, walletReadable = readable)
|
||||
assertEquals("Open this wallet to view its backup.", why)
|
||||
assertEquals("open this wallet to view its backup", why)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
@ -212,7 +212,7 @@ class WalletManagerTest {
|
|||
walletPassphraseSubmitEnabled(activeFilename = null, typed = "pw", inFlight = false),
|
||||
)
|
||||
val why = walletPassphraseBlockedReason(activeFilename = null, typed = "pw")
|
||||
assertTrue("got '$why'", why != null && why.contains("No wallet file is open yet"))
|
||||
assertTrue("got '$why'", why != null && why.contains("not pointed at"))
|
||||
// The two reasons are different fixes and must not read alike.
|
||||
assertFalse(why == walletPassphraseBlockedReason(activeFilename = openFile, typed = ""))
|
||||
}
|
||||
|
|
@ -225,7 +225,7 @@ class WalletManagerTest {
|
|||
@Test
|
||||
fun nothing_typed_is_the_other_reason() {
|
||||
val why = walletPassphraseBlockedReason(activeFilename = openFile, typed = "")
|
||||
assertTrue("got '$why'", why != null && why.contains("Type the passphrase"))
|
||||
assertTrue("got '$why'", why != null && why.contains("type the passphrase"))
|
||||
}
|
||||
|
||||
// --- the daemon's own words never reach the screen -----------------------
|
||||
|
|
@ -348,12 +348,7 @@ class WalletManagerTest {
|
|||
walletOpen = false,
|
||||
needsPassphrase = false,
|
||||
)
|
||||
// The §4.1 replacement copy, verbatim: a live wallet with no file open
|
||||
// is a state, not an error.
|
||||
assertEquals(
|
||||
"Select a saved wallet or create a new one to view your balance and transact.",
|
||||
hint,
|
||||
)
|
||||
assertTrue("got '$hint'", hint != null && hint.contains("No wallet is open"))
|
||||
assertNoRawRpc(hint!!)
|
||||
}
|
||||
|
||||
|
|
@ -468,7 +463,7 @@ class WalletManagerTest {
|
|||
fun wallet_reads_reload_only_once_the_child_is_answering() {
|
||||
// `walletBalance()` answers `"err"` — it does not throw — while the
|
||||
// child is still dialling, so reloading in that window is what pins the
|
||||
// headline on `Balance unavailable`. Reload only when the child has answered.
|
||||
// headline on `balance —`. Reload only when the child has answered.
|
||||
assertFalse(shouldReloadWalletReads(null))
|
||||
assertFalse(shouldReloadWalletReads("off"))
|
||||
assertFalse(shouldReloadWalletReads("connecting"))
|
||||
|
|
@ -477,27 +472,4 @@ class WalletManagerTest {
|
|||
assertTrue(shouldReloadWalletReads("ready"))
|
||||
assertTrue(shouldReloadWalletReads(" Ready "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun the_tui_not_configured_copy_is_mapped_and_never_rendered_verbatim() {
|
||||
// `src/wallet.rs::NOT_CONFIGURED_MSG` is the desktop TUI's refusal. A
|
||||
// phone has no F7 key and no ONIONWIRE_WALLET_RPC, so that sentence is
|
||||
// the second dead end the device report caught: a passphrase was typed
|
||||
// into Create, and the screen answered with a keyboard shortcut.
|
||||
val tui = "wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC"
|
||||
val shown = walletFailureText(tui)
|
||||
assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, shown)
|
||||
assertFalse("no F7 reaches the screen", shown!!.contains("F7"))
|
||||
assertFalse("no env var name either", shown.contains("ONIONWIRE_WALLET_RPC"))
|
||||
assertTrue("the phone sentence says what to do", shown.contains("Start it on the node card"))
|
||||
|
||||
// Each fragment alone is the same fact and is mapped too; case and
|
||||
// spacing are not load-bearing.
|
||||
assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, walletFailureText("Open F7"))
|
||||
assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, walletFailureText("Wallet Not Configured"))
|
||||
assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, walletFailureText("set ONIONWIRE_WALLET_RPC"))
|
||||
|
||||
// And it is idempotent: the sticky error card re-filters its own text.
|
||||
assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, walletFailureText(shown))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
809
crates/onionwire-sdk/Cargo.lock
generated
809
crates/onionwire-sdk/Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -33,7 +33,7 @@ cuprate-daemon = ["onionwire/cuprate-daemon"]
|
|||
[dependencies]
|
||||
onionwire = { path = "../..", default-features = false, features = ["rustls"] }
|
||||
# `static-sqlite`: Android has no system libsqlite3 to link against.
|
||||
arti-client = { version = "0.49", default-features = false, features = [
|
||||
arti-client = { version = "0.46", default-features = false, features = [
|
||||
"tokio",
|
||||
"onion-service-client",
|
||||
"onion-service-service",
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ runs on. An Android peer and a Linux peer that exchange invites interoperate —
|
|||
there is one protocol, not two.
|
||||
|
||||
This is **not** a WebView wrapper and **not** a client for a hosted service.
|
||||
Each install runs Arti in-process (`arti-client` 0.49, `onion-service-client` +
|
||||
Each install runs Arti in-process (`arti-client` 0.46, `onion-service-client` +
|
||||
`onion-service-service`), hosts its own v3 onion service, and dials friends'
|
||||
onions directly. There is no `tor` binary, no torrc, no Orbot as the pipe.
|
||||
|
||||
|
|
|
|||
|
|
@ -12,19 +12,13 @@ Direct dependencies that come from the Arti repository, exactly as
|
|||
|
||||
| crate | requirement | features in `Cargo.toml` |
|
||||
|---|---|---|
|
||||
| `arti-client` | `0.49` | `default-features = false`; `tokio`, `onion-service-client`, `onion-service-service`, `compression` |
|
||||
| `tor-cell` | `0.49` | — |
|
||||
| `tor-hsservice` | `0.49` | — |
|
||||
| `tor-rtcompat` | `0.49` | `tokio` |
|
||||
| `safelog` | `0.10` | — |
|
||||
| `arti-client` | `0.46` | `default-features = false`; `tokio`, `onion-service-client`, `onion-service-service`, `compression` |
|
||||
| `tor-cell` | `0.46` | — |
|
||||
| `tor-hsservice` | `0.46` | — |
|
||||
| `tor-rtcompat` | `0.46` | `tokio` |
|
||||
|
||||
`snow`, `rusqlite`, `ratatui`, and the rest are unrelated to Arti and are not
|
||||
part of a Tor upgrade. `safelog` lives in the Arti repository and moves in
|
||||
lockstep with the `tor-*` set: a stale direct `safelog` pin puts two copies in
|
||||
the graph, and `HsId::display_redacted` then resolves against the wrong trait
|
||||
(`error[E0599]: no method named display_redacted`). The SDK workspace
|
||||
(`crates/onionwire-sdk`) has its own `arti-client` pin and lockfile; bump it
|
||||
too.
|
||||
part of a Tor upgrade.
|
||||
|
||||
Two crate features re-expose Arti's TLS backends, which Arti marks
|
||||
**non-additive** — exactly one may be selected per build graph:
|
||||
|
|
@ -35,16 +29,16 @@ Two crate features re-expose Arti's TLS backends, which Arti marks
|
|||
features (without it the rustls backend compiles with no provider).
|
||||
* `native-tls` → opt-in only, via OpenSSL.
|
||||
|
||||
Published Arti releases move all of the crates above together in lockstep.
|
||||
Bump them as **one set**. A mixed set (e.g. `arti-client` 0.47 with
|
||||
`tor-hsservice` 0.49) is not a configuration anyone tests upstream, and cargo
|
||||
will usually refuse or silently pick one `tor-*` version and mismatched
|
||||
`tor-*` internals fail at runtime.
|
||||
Published Arti releases move all four crates together in lockstep. Bump them as
|
||||
**one set**. A mixed set (e.g. `arti-client` 0.47 with `tor-hsservice` 0.46) is
|
||||
not a configuration anyone tests upstream, and cargo will usually refuse or
|
||||
silently pick one `tor-*` version and mismatched `tor-*` internals fail at
|
||||
runtime.
|
||||
|
||||
## Toolchain floor
|
||||
|
||||
**rustc 1.98+.** `Cargo.toml` sets `edition = "2024"` and `rust-version = "1.98"`.
|
||||
Arti 0.49 itself requires only 1.92; the higher floor is the default
|
||||
Arti 0.46 itself requires only 1.91; the higher floor is the default
|
||||
`cuprate-daemon` feature (`tapes` calls `VecDeque::pop_front_if`, stable since
|
||||
1.93). CI builds inside `rust:1.98-bookworm`
|
||||
(`RUST_IMAGE` in `.forgejo/workflows/ci.yml` and `release.yml`).
|
||||
|
|
@ -85,22 +79,16 @@ issue the watcher files.
|
|||
|
||||
1. Read the upstream release notes (Arti tags: <https://gitlab.torproject.org/tpo/core/arti/-/releases>)
|
||||
and the CHANGELOG for breaking API changes. Check the new MSRV.
|
||||
2. Branch from `main`; bump every Arti-repository pin in `[dependencies]` of
|
||||
`Cargo.toml` together (`arti-client`, `tor-cell`, `tor-hsservice`,
|
||||
`tor-rtcompat`, and `safelog`), the matching `arti-client` pin in
|
||||
`crates/onionwire-sdk/Cargo.toml`, and `rust-version` if the floor moved.
|
||||
2. Branch from `main`; bump all four requirements in `[dependencies]` of
|
||||
`Cargo.toml` together, and `rust-version` if the floor moved.
|
||||
3. Refresh the lockfile (CI builds with `--locked` and `Cargo.lock` is
|
||||
committed):
|
||||
```
|
||||
cargo update -p arti-client -p tor-cell -p tor-hsservice -p tor-rtcompat -p safelog
|
||||
cargo update -p arti-client -p tor-cell -p tor-hsservice -p tor-rtcompat
|
||||
git diff --stat Cargo.lock
|
||||
```
|
||||
Expect the whole `tor-*` family to move in the diff. A single `tor-*` crate
|
||||
moving alone is a sign the set is not actually lockstep — stop and look.
|
||||
Then refresh the SDK workspace's separate lockfile:
|
||||
```
|
||||
( cd crates/onionwire-sdk && cargo update -p arti-client )
|
||||
```
|
||||
4. Build and run the offline suite:
|
||||
```
|
||||
cargo test --locked
|
||||
|
|
|
|||
|
|
@ -321,7 +321,7 @@ the app does not pick a public remote node for them.
|
|||
every in-process surface still says `testnet only — mainnet is unvalidated`.
|
||||
Cross-compiled is not device-proven.
|
||||
- Cuprate's own `arti` feature is off (its Tor stack is `arti-client` 0.44,
|
||||
which cannot unify with this crate's 0.49), so the in-process daemon's P2P
|
||||
which cannot unify with this crate's 0.46), so the in-process daemon's P2P
|
||||
traffic is **clearnet**: your ISP sees that this device talks to Monero
|
||||
peers. No Tor is on the chain path — Tor is the messenger's transport here,
|
||||
not the chain's.
|
||||
|
|
@ -340,8 +340,8 @@ the app does not pick a public remote node for them.
|
|||
`connect()`, and not a C-tor fallback for chat). That listener is the
|
||||
bundled `arti` **binary** run as a child (`arti proxy -p <port>`) — a
|
||||
second, separate Tor client with its own state and cache dirs, because
|
||||
`arti-client` 0.49 exposes no SOCKS listener API. It is TCP loopback only
|
||||
(`arti proxy -p` binds `127.0.0.1`/`::1`; arti 2.6.0 / `tor-config` 0.49
|
||||
`arti-client` 0.46 exposes no SOCKS listener API. It is TCP loopback only
|
||||
(`arti proxy -p` binds `127.0.0.1`/`::1`; arti 2.6.0 / `tor-config` 0.46
|
||||
have no Unix-socket listen target — arti#1965), and the port is usable by
|
||||
any local process at the user's privilege level: it is an app-private port,
|
||||
not an access-controlled one. The app gates the spawn on the unlocked store
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ missing:
|
|||
|
||||
- **`/releases/latest/download/…` is not served by this Forgejo — it is a 404.**
|
||||
The GitHub habit fails here. Always pin the tag:
|
||||
`…/releases/download/v0.7.0/onionwire-x86_64-unknown-linux-gnu`.
|
||||
`…/releases/download/v0.5.0/onionwire-x86_64-unknown-linux-gnu`.
|
||||
- **Cloudflare in front of the Forgejo rejects non-browser User-Agents.** A
|
||||
script that sends a default library UA gets `HTTP 403` with the body
|
||||
`error code: 1010` — even with a correct tag and URL. Measured against a real
|
||||
|
|
@ -157,10 +157,10 @@ is public": *the binary I downloaded might not be that source.*
|
|||
git clone https://forgejo.siriusdevops.com/sirius/onionwire
|
||||
cd onionwire
|
||||
git fetch --tags
|
||||
scripts/verify-reproducible.sh v0.7.0
|
||||
scripts/verify-reproducible.sh v0.5.0
|
||||
```
|
||||
|
||||
Replace `v0.7.0` with the tag you are checking. You need docker; you do not
|
||||
Replace `v0.5.0` with the tag you are checking. You need docker; you do not
|
||||
need Rust, or the right glibc, or the right distro. The rebuild happens inside
|
||||
the same builder image, pinned **by digest**, that CI uses, with the source
|
||||
paths, the target path, and `SOURCE_DATE_EPOCH` all fixed by
|
||||
|
|
|
|||
|
|
@ -181,7 +181,7 @@ for the TUI. A build with `--no-default-features` does not include the daemon.
|
|||
Cross-compiled is not device-proven. Pointing a mainnet wallet at it is not
|
||||
something this build claims to do.
|
||||
- **No Tor on the chain path.** Cuprate's `arti` feature is off (arti-client
|
||||
0.44 vs this crate's 0.49). P2P is **clearnet**. OnionWire's Arti is the
|
||||
0.44 vs this crate's 0.46). P2P is **clearnet**. OnionWire's Arti is the
|
||||
messenger only.
|
||||
- **Inbound P2P off**, restricted RPC listener disabled. Unrestricted RPC is
|
||||
loopback 18081. `--trusted-daemon` still never passed.
|
||||
|
|
@ -208,42 +208,18 @@ C++ binary, so it reaches Tor through a SOCKS proxy the app provides:
|
|||
**Tor hides the transport, not the host.** The daemon operator still sees the
|
||||
wallet's addresses during sync.
|
||||
|
||||
### Readiness — receipt verification needs a synced wallet
|
||||
### Readiness — receipt verification needs a synced daemon
|
||||
|
||||
`chain_ready()` compares the wallet's **own scanned height** with the **chain
|
||||
tip**. Both halves must answer:
|
||||
|
||||
1. the wallet RPC's `get_height` reports `height > 0`. That is
|
||||
`monero-wallet-rpc`'s own method; `get_info` does **not** exist there — it
|
||||
answers `-32601 Method not found`, so readiness never asks for it.
|
||||
2. the chain daemon reports a tip, and the wallet is at it or within **2
|
||||
blocks**. The tip moves every ~2 minutes and the two numbers are two reads,
|
||||
not one snapshot, so a strict equality flaps; two blocks of slack does not
|
||||
hide a real lag.
|
||||
|
||||
The tip comes from `daemon_get_height` (`GET /get_height` — one spelling that
|
||||
works on monerod and Cuprate) against `ChildConfig::daemon_probe_addr()`:
|
||||
|
||||
- local `monerod` / in-process Cuprate → `127.0.0.1:18081`;
|
||||
- a **clearnet** remote daemon the user typed → that host. The wallet child
|
||||
already dials it, so one `get_height` is the same exposure, not a new path;
|
||||
- a **`.onion`** daemon → **not dialled** without the SOCKS child: a direct dial
|
||||
would resolve the name on clearnet DNS and leak. Readiness stays false
|
||||
(height-only); the status row reads syncing. A documented limit, not a bug;
|
||||
- receive-only, or an externally run wallet RPC with no chain source → nothing
|
||||
to ask, so not ready.
|
||||
|
||||
Unknown is **not caught up**. A daemon that does not answer, a wallet with no
|
||||
file open (`-13 No wallet file`), and a missing height all read *not ready*,
|
||||
never a silent pass. "No wallet open" is a state, not an error banner.
|
||||
`chain_ready()` asks the wallet RPC `get_info` and requires
|
||||
**`synchronized == true`** with `height > 0` and `height >= target_height`. A
|
||||
missing field is *not ready* — fail closed.
|
||||
|
||||
Until then, **receipt verification stays `verified=0`**. An unsynced wallet
|
||||
cannot see the chain. That is an honest limit, not a UI bug.
|
||||
|
||||
Loopback management calls (`get_address`, `query_key`, create/import) get 5s.
|
||||
Calls that wait on the chain (`get_transfers`, `transfer`) get 60s
|
||||
(`CHAIN_RPC_TIMEOUT`). Readiness is not a chain wait: it is one local
|
||||
`get_height` plus one bounded daemon probe.
|
||||
Calls that wait on the chain (`get_info`, `get_transfers`, `transfer`) get 60s
|
||||
(`CHAIN_RPC_TIMEOUT`).
|
||||
|
||||
## Env vars (migration path)
|
||||
|
||||
|
|
@ -280,9 +256,8 @@ re-points the wallet without a restart; a rejected form writes nothing.
|
|||
UniFFI: `set_chain_source(ChainConfig)` / `chain_source()`,
|
||||
`start_wallet_child()`, `stop_wallet_child()`, `wallet_status()` (cached read:
|
||||
no dial, for first paint) and `wallet_child_refresh()` (a live probe of the
|
||||
same record — it dials the loopback wallet RPC and asks the configured daemon
|
||||
for its tip (the wallet's `get_height` is the other half), so poll it on the
|
||||
order of seconds).
|
||||
same record — it dials the loopback wallet RPC, and the local daemon's
|
||||
`get_info` when that RPC does not answer, so poll it on the order of seconds).
|
||||
Pass absolute paths for `wallet_rpc_bin` / `arti_bin` (`nativeLibraryDir`); the
|
||||
core never resolves a binary the caller named explicitly.
|
||||
|
||||
|
|
|
|||
|
|
@ -10,45 +10,26 @@
|
|||
//! Neither call may panic, and neither may leave the state mutated on a frame
|
||||
//! it rejects (asserted in `tests/ratchet.rs`, re-checked cheaply here by
|
||||
//! re-serializing after every decrypt).
|
||||
//!
|
||||
//! Both bootstrap shapes are exercised: a classical friend (`remote_kem_pub =
|
||||
//! None`) and a hybrid friend, whose peer ML-KEM ratchet key is a real
|
||||
//! encapsulation key of `kem::PK_LEN` bytes derived from a fixed seed. A
|
||||
//! garbage key would only ever hit the "invalid encapsulation key" error path.
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
use onionwire::kem::{self, PK_LEN, SEED_LEN};
|
||||
use onionwire::ratchet::{RatchetKeyPair, RatchetState};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// A canonical ML-KEM-768 encapsulation key, built once: key generation is
|
||||
/// deterministic for a fixed seed, so this only pays for itself on iteration 1.
|
||||
fn peer_kem_pub() -> &'static [u8] {
|
||||
static PK: OnceLock<Vec<u8>> = OnceLock::new();
|
||||
PK.get_or_init(|| {
|
||||
let pk = kem::pk_from_seed(&[0x44u8; SEED_LEN]).expect("64 bytes is a valid ML-KEM seed");
|
||||
assert_eq!(pk.len(), PK_LEN, "crate ML-KEM public key length changed");
|
||||
pk
|
||||
})
|
||||
}
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
// Restore path: arbitrary bytes as a persisted ratchet state.
|
||||
if let Ok(state) = RatchetState::from_bytes(data) {
|
||||
// A state that parsed must re-serialize without panicking.
|
||||
let _ = state.to_bytes();
|
||||
}
|
||||
|
||||
fn bootstrap(remote_kem_pub: Option<&[u8]>) -> RatchetState {
|
||||
// The keys are fixed (not fuzzed) on purpose: the interesting surface is
|
||||
// `data` as the frame.
|
||||
RatchetState::bootstrap(
|
||||
// Wire path: a fresh bootstrap epoch for every input, so one iteration can
|
||||
// never influence the next. The keys are fixed (not fuzzed) on purpose:
|
||||
// the interesting surface is `data` as the frame.
|
||||
let mut state = RatchetState::bootstrap(
|
||||
[0x42u8; 32],
|
||||
RatchetKeyPair::from_secret([0x11u8; 32]),
|
||||
[0x33u8; 32],
|
||||
remote_kem_pub,
|
||||
)
|
||||
}
|
||||
|
||||
/// Feed `data` to a fresh state and hold the existing invariants: a reject must
|
||||
/// roll back, an accept must have advanced the receiving chain, and re-sending
|
||||
/// from the resulting state must not panic.
|
||||
fn exercise(remote_kem_pub: Option<&[u8]>, data: &[u8]) {
|
||||
let mut state = bootstrap(remote_kem_pub);
|
||||
);
|
||||
let before = state.to_bytes();
|
||||
|
||||
match state.decrypt(data) {
|
||||
|
|
@ -64,17 +45,4 @@ fn exercise(remote_kem_pub: Option<&[u8]>, data: &[u8]) {
|
|||
|
||||
// Re-encrypting a byte-identical state must stay a pure function.
|
||||
let _ = state.encrypt(b"fuzz");
|
||||
}
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
// Restore path: arbitrary bytes as a persisted ratchet state.
|
||||
if let Ok(state) = RatchetState::from_bytes(data) {
|
||||
// A state that parsed must re-serialize without panicking.
|
||||
let _ = state.to_bytes();
|
||||
}
|
||||
|
||||
// Wire path: a fresh bootstrap epoch for every input, so one iteration can
|
||||
// never influence the next. Classical and hybrid, both.
|
||||
exercise(None, data);
|
||||
exercise(Some(peer_kem_pub()), data);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@
|
|||
//! name reservation), so a pinned revision is the only honest way to depend on
|
||||
//! it.
|
||||
//! * Cuprate's own `arti` feature stays **off**. Its Tor stack is arti 0.44,
|
||||
//! which cannot unify with this crate's arti 0.49, and this daemon is
|
||||
//! which cannot unify with this crate's arti 0.46, and this daemon is
|
||||
//! clearnet-only: OnionWire's Arti is the only Tor in the process.
|
||||
//! * The **unrestricted** RPC listener binds `127.0.0.1:<port>` — the address
|
||||
//! `WalletChild::daemon_address` returns for a local source. The restricted
|
||||
|
|
|
|||
187
src/node.rs
187
src/node.rs
|
|
@ -1065,12 +1065,7 @@ impl Node {
|
|||
return self.wallet_child_status();
|
||||
}
|
||||
let cfg = self.wallet_child_config();
|
||||
// Readiness needs both halves: the wallet's own `get_height` and the
|
||||
// chain tip. The tip comes from the configured daemon (loopback for a
|
||||
// local source, the clearnet host the user typed, never a `.onion`).
|
||||
let w = self
|
||||
.wallet_snapshot()
|
||||
.with_daemon_probe(cfg.daemon_probe_addr());
|
||||
let w = self.wallet_snapshot();
|
||||
if !w.configured() {
|
||||
return self.wallet_child_status();
|
||||
}
|
||||
|
|
@ -1095,7 +1090,7 @@ impl Node {
|
|||
}
|
||||
let synced = progress.as_ref().is_some_and(wallet::ChainInfo::ready);
|
||||
let (height, target_height) = match progress {
|
||||
Some(info) => (info.height, info.tip.unwrap_or(0)),
|
||||
Some(info) => (info.height, info.target_height),
|
||||
// The wallet RPC is the honest source when it answers. When it does
|
||||
// not (a refused connection is the common one), the daemon this box
|
||||
// owns can still say — and a daemon that does not answer leaves
|
||||
|
|
@ -1339,9 +1334,7 @@ impl Node {
|
|||
|
||||
/// Pay selected friend via wallet RPC, then signed receipt.
|
||||
pub async fn tip(&self, friend_pk: &[u8], atomic: &str, memo: &str) -> Result<(), String> {
|
||||
let w = self
|
||||
.wallet_snapshot()
|
||||
.with_daemon_probe(self.wallet_child_config().daemon_probe_addr());
|
||||
let w = self.wallet_snapshot();
|
||||
if !w.configured() {
|
||||
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||||
}
|
||||
|
|
@ -2160,9 +2153,7 @@ impl Node {
|
|||
// Honest prerequisite: an unsynced wallet cannot see the tx, so a
|
||||
// get_transfers "miss" would be a lie. Until the chain is ready the
|
||||
// receipt stays verified=0 — that is the correct state, not an error.
|
||||
let w = self
|
||||
.wallet_snapshot()
|
||||
.with_daemon_probe(self.wallet_child_config().daemon_probe_addr());
|
||||
let w = self.wallet_snapshot();
|
||||
let ready = w.configured() && w.can_verify_receipts().await;
|
||||
if ready {
|
||||
match w.get_transfers().await {
|
||||
|
|
@ -3426,43 +3417,25 @@ pub(crate) mod tests {
|
|||
}
|
||||
|
||||
/// A loopback wallet RPC that answers what the tip path actually asks for:
|
||||
/// a digest challenge, then the wallet's own scanned `get_height` for the
|
||||
/// readiness gate and `tx_hash` for the transfer. `get_info` is a daemon
|
||||
/// method, not a wallet one, so it is never asked. Returns the wallet and
|
||||
/// the daemon stub's address (the tip the gate compares against).
|
||||
async fn mock_wallet() -> (Wallet, String) {
|
||||
/// a digest challenge, then a synced `get_info` for the readiness gate and
|
||||
/// `tx_hash` for the transfer. The old single-answer mock stopped covering
|
||||
/// the path when `Wallet::transfer` started probing the chain tip first —
|
||||
/// it answered `tx_hash` to `get_info` and every tip was refused as unsynced.
|
||||
async fn mock_wallet() -> Wallet {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind mock wallet");
|
||||
let port = listener.local_addr().expect("mock wallet addr").port();
|
||||
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(|req: &str| {
|
||||
if req.contains("get_height") {
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100}}"#.to_string()
|
||||
if req.contains("get_info") {
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
|
||||
.to_string()
|
||||
} else {
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#.to_string()
|
||||
}
|
||||
});
|
||||
tokio::spawn(serve_mock_rpc(listener, reply));
|
||||
let wallet = Wallet::from_url(&format!("http://ow:[email protected]:{port}"))
|
||||
.expect("wallet url");
|
||||
let daemon = mock_daemon(100, 100).await;
|
||||
(wallet, daemon)
|
||||
}
|
||||
|
||||
/// Point a test node's chain source at a daemon stub, so readiness has a
|
||||
/// tip to compare the wallet's scanned height against.
|
||||
fn chain_source_at(node: &Node, addr: &str) {
|
||||
let (host, port) = addr.rsplit_once(':').expect("host:port");
|
||||
node.set_wallet_child_config(&ChildConfig {
|
||||
source: ChainSource::Remote {
|
||||
host: host.to_string(),
|
||||
port: port.parse().expect("port"),
|
||||
},
|
||||
wallet_rpc_bin: PathBuf::from("monero-wallet-rpc"),
|
||||
arti_bin: PathBuf::from("arti"),
|
||||
wallet_filename: wallet::DEFAULT_WALLET_FILENAME.to_string(),
|
||||
})
|
||||
.expect("set chain source");
|
||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
||||
}
|
||||
/// The payer of a tip must see it in their own chat: `receipt_chat_line` is
|
||||
/// the recipient's view of the frame that arrived, `tip_chat_line` is what
|
||||
|
|
@ -3470,9 +3443,11 @@ pub(crate) mod tests {
|
|||
#[tokio::test]
|
||||
async fn outbound_tip_appends_the_senders_own_tip_chat_line() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (wallet, daemon) = mock_wallet().await;
|
||||
let node = offline_node_with_wallet(&dir.path().join("bob"), Arc::new(DialOk), wallet);
|
||||
chain_source_at(&node, &daemon);
|
||||
let node = offline_node_with_wallet(
|
||||
&dir.path().join("bob"),
|
||||
Arc::new(DialOk),
|
||||
mock_wallet().await,
|
||||
);
|
||||
let peer = Keys::generate();
|
||||
let addr = xmr_addr();
|
||||
{
|
||||
|
|
@ -3573,9 +3548,11 @@ pub(crate) mod tests {
|
|||
#[tokio::test]
|
||||
async fn outbound_tip_records_a_tip_payment_row() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (wallet, daemon) = mock_wallet().await;
|
||||
let node = offline_node_with_wallet(&dir.path().join("bob"), Arc::new(DialOk), wallet);
|
||||
chain_source_at(&node, &daemon);
|
||||
let node = offline_node_with_wallet(
|
||||
&dir.path().join("bob"),
|
||||
Arc::new(DialOk),
|
||||
mock_wallet().await,
|
||||
);
|
||||
let peer = Keys::generate();
|
||||
let addr = xmr_addr();
|
||||
{
|
||||
|
|
@ -3790,62 +3767,23 @@ pub(crate) mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
/// A chain-daemon stub on an ephemeral loopback port: `GET /get_height`
|
||||
/// answers the tip, `/json_rpc get_info` answers height/target. Returns
|
||||
/// `host:port`.
|
||||
async fn mock_daemon(height: u64, target: u64) -> String {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind mock daemon");
|
||||
let addr = listener.local_addr().expect("mock daemon addr").to_string();
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut sock, _)) = listener.accept().await {
|
||||
let mut buf = vec![0u8; 4096];
|
||||
let Ok(n) = sock.read(&mut buf).await else {
|
||||
return;
|
||||
};
|
||||
if n == 0 {
|
||||
continue;
|
||||
}
|
||||
let req = String::from_utf8_lossy(&buf[..n]).to_string();
|
||||
let body = if req.starts_with("GET /get_height") {
|
||||
format!(r#"{{"height":{height}}}"#)
|
||||
} else {
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target}}}}}"#
|
||||
)
|
||||
};
|
||||
let _ = sock
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
addr
|
||||
}
|
||||
|
||||
/// A loopback wallet RPC that answers the *status* probe: a digest
|
||||
/// challenge, then `get_address` / `get_balance` / `get_height`, with the
|
||||
/// wallet's own scanned height. Returns the wallet and the daemon stub's
|
||||
/// address — the tip comes from the daemon, never from the wallet RPC.
|
||||
/// [`mock_wallet`] above answers the *transfer* path; this one answers a
|
||||
/// refresh, which never transfers.
|
||||
async fn mock_syncing_wallet(height: u64, target: u64) -> (Wallet, String) {
|
||||
/// challenge, then `get_address` / `get_balance` / `get_info`, with the
|
||||
/// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the
|
||||
/// *transfer* path; this one answers a refresh, which never transfers.
|
||||
/// A loopback wallet RPC that answers the *status* probe: a digest
|
||||
/// challenge, then `get_address` / `get_balance` / `get_info`, with the
|
||||
/// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the
|
||||
/// *transfer* path; this one answers a refresh, which never transfers.
|
||||
async fn mock_syncing_wallet(height: u64, target: u64) -> Wallet {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind mock wallet");
|
||||
let port = listener.local_addr().expect("mock wallet addr").port();
|
||||
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
|
||||
if req.contains("get_height") {
|
||||
if req.contains("get_info") {
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height}}}}}"#
|
||||
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"#
|
||||
)
|
||||
} else if req.contains("get_address") {
|
||||
format!(
|
||||
|
|
@ -3857,10 +3795,7 @@ pub(crate) mod tests {
|
|||
}
|
||||
});
|
||||
tokio::spawn(serve_mock_rpc(listener, reply));
|
||||
let wallet =
|
||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url");
|
||||
let daemon = mock_daemon(height, target).await;
|
||||
(wallet, daemon)
|
||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
||||
}
|
||||
|
||||
/// Point `node`'s wallet client at a mock. The child process stays whatever
|
||||
|
|
@ -3869,14 +3804,13 @@ pub(crate) mod tests {
|
|||
*node.wallet.lock().expect("wallet") = wallet;
|
||||
}
|
||||
|
||||
/// Like [`mock_syncing_wallet`], but the wallet's scanned `height` is read on
|
||||
/// every `get_height`, so a later store is a later answer. The daemon stub
|
||||
/// reports `target` as its tip. Returns the wallet and the daemon address so
|
||||
/// a caller can point a chain source at it.
|
||||
/// Like [`mock_syncing_wallet`], but `height` is read on every `get_info`,
|
||||
/// so a later store is a later answer. `synchronized` stays false: the
|
||||
/// status line is a syncing chain, not a caught-up one.
|
||||
pub(crate) async fn mock_wallet_at(
|
||||
height: std::sync::Arc<std::sync::atomic::AtomicU64>,
|
||||
target: u64,
|
||||
) -> (Wallet, String) {
|
||||
) -> Wallet {
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
|
|
@ -3884,9 +3818,11 @@ pub(crate) mod tests {
|
|||
.expect("bind mock wallet");
|
||||
let port = listener.local_addr().expect("mock wallet addr").port();
|
||||
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
|
||||
if req.contains("get_height") {
|
||||
if req.contains("get_info") {
|
||||
let h = height.load(Ordering::Relaxed);
|
||||
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{h}}}}}"#)
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{h},"target_height":{target},"synchronized":false}}}}"#
|
||||
)
|
||||
} else if req.contains("get_address") {
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4test"}}"#.to_string()
|
||||
} else {
|
||||
|
|
@ -3894,10 +3830,7 @@ pub(crate) mod tests {
|
|||
}
|
||||
});
|
||||
tokio::spawn(serve_mock_rpc(listener, reply));
|
||||
let wallet =
|
||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url");
|
||||
let daemon = mock_daemon(target, target).await;
|
||||
(wallet, daemon)
|
||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
||||
}
|
||||
|
||||
/// A loopback daemon that answers `get_info` on the port the child probes
|
||||
|
|
@ -3935,12 +3868,12 @@ pub(crate) mod tests {
|
|||
Some(())
|
||||
}
|
||||
|
||||
/// The status row carries the real chain numbers: the wallet RPC's own
|
||||
/// `get_height` is the wallet's scanned height, and the daemon's tip is the
|
||||
/// target. A daemon that reports no separate target still gives a tip, so
|
||||
/// `h/h` is the honest line — never an invented percentage.
|
||||
/// The status row carries the real chain numbers: a wallet RPC that answers
|
||||
/// `get_info` fills height and target, and the one-liner shows them. A
|
||||
/// daemon that reports no target is not a caught-up chain — `h/0` with no
|
||||
/// invented percentage.
|
||||
#[tokio::test]
|
||||
async fn the_wallet_height_and_the_daemon_tip_fill_the_chain_progress() {
|
||||
async fn a_wallet_that_answers_get_info_fills_the_chain_progress() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
||||
let log = dir.path().join("argv.log");
|
||||
|
|
@ -3957,16 +3890,14 @@ pub(crate) mod tests {
|
|||
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||||
node.start_wallet_child().expect("start");
|
||||
// The child is a fake process; the wallet the node actually talks to is
|
||||
// the mock RPC, and the tip comes from the daemon stub.
|
||||
let (wallet, daemon) = mock_syncing_wallet(4549, 0).await;
|
||||
*node.wallet.lock().unwrap() = wallet;
|
||||
chain_source_at(&node, &daemon);
|
||||
// the mock RPC, which is where the numbers come from.
|
||||
*node.wallet.lock().unwrap() = mock_syncing_wallet(4549, 0).await;
|
||||
|
||||
let status = node.wallet_child_refresh().await;
|
||||
assert_eq!(status.state, WalletChildState::Ready, "{status:?}");
|
||||
assert_eq!(status.height, 4549, "{status:?}");
|
||||
assert_eq!(status.target_height, 4549, "{status:?}");
|
||||
assert!(status.line().contains("sync 4549/4549"), "{}", status.line());
|
||||
assert_eq!(status.target_height, 0, "{status:?}");
|
||||
assert!(status.line().contains("sync 4549/0"), "{}", status.line());
|
||||
assert!(!status.line().contains('%'), "{}", status.line());
|
||||
|
||||
node.stop_wallet_child().expect("stop");
|
||||
|
|
@ -4416,10 +4347,7 @@ pub(crate) mod tests {
|
|||
let err = node
|
||||
.start_wallet_child()
|
||||
.expect_err("a missing binary fails");
|
||||
// The refusal names the configured path: the old `spawn <label>` copy
|
||||
// could not say which program was missing.
|
||||
assert!(err.contains("/nonexistent/onionwire-wallet-rpc"), "{err}");
|
||||
assert!(err.contains("not found"), "{err}");
|
||||
assert!(err.contains("spawn"), "{err}");
|
||||
let status = node.wallet_child_status();
|
||||
assert_eq!(status.state, WalletChildState::Off);
|
||||
assert!(!status.running);
|
||||
|
|
@ -5086,8 +5014,9 @@ pub(crate) mod tests {
|
|||
r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#,
|
||||
addr = xmr_addr()
|
||||
)
|
||||
} else if req.contains("get_height") {
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100}}"#.to_string()
|
||||
} else if req.contains("get_info") {
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
|
||||
.to_string()
|
||||
} else {
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0","unlocked_balance":"0"}}"#
|
||||
.to_string()
|
||||
|
|
@ -5346,9 +5275,7 @@ pub(crate) mod tests {
|
|||
);
|
||||
|
||||
// The read after the restart takes the success path: the same mock
|
||||
// answers `get_address` / `get_balance` / `get_height`.
|
||||
let daemon = mock_daemon(100, 100).await;
|
||||
chain_source_at(&node, &daemon);
|
||||
// answers `get_address`/`get_balance`/`get_info`.
|
||||
let status = node.wallet_child_refresh().await;
|
||||
assert!(status.wallet_open, "{status:?}");
|
||||
assert!(!status.needs_passphrase, "{status:?}");
|
||||
|
|
|
|||
16
src/tui.rs
16
src/tui.rs
|
|
@ -7694,22 +7694,8 @@ mod wallet_setup_config_tests {
|
|||
app.node.start_wallet_child().expect("start");
|
||||
|
||||
let height = Arc::new(AtomicU64::new(1111));
|
||||
let (wallet, daemon) = rt.block_on(mock_wallet_at(Arc::clone(&height), 9000));
|
||||
let wallet = rt.block_on(mock_wallet_at(Arc::clone(&height), 9000));
|
||||
test_install_wallet(&app.node, wallet);
|
||||
// Readiness compares the wallet's scanned height with a daemon tip, so
|
||||
// point the chain source at the stub the wallet mock returned.
|
||||
let (host, port) = daemon.rsplit_once(':').expect("host:port");
|
||||
app.node
|
||||
.set_wallet_child_config(&ChildConfig {
|
||||
source: ChainSource::Remote {
|
||||
host: host.to_string(),
|
||||
port: port.parse().expect("daemon port"),
|
||||
},
|
||||
wallet_rpc_bin: std::path::PathBuf::from("monero-wallet-rpc"),
|
||||
arti_bin: std::path::PathBuf::from("arti"),
|
||||
wallet_filename: "onionwire".into(),
|
||||
})
|
||||
.expect("point the chain source at the daemon stub");
|
||||
app.handle_key(key(KeyCode::F(7))).expect("F7");
|
||||
|
||||
wait_for_sync_line(&mut app, &rt, "sync 1111/9000");
|
||||
|
|
|
|||
100
src/wallet.rs
100
src/wallet.rs
|
|
@ -488,53 +488,34 @@ pub struct Wallet {
|
|||
/// Budget for loopback management calls (`get_address`, `query_key`,
|
||||
/// create/import). The wallet child is on the same box, so this stays short.
|
||||
timeout_local: Duration,
|
||||
/// Budget for calls that wait on the daemon (`get_transfers`, `transfer`).
|
||||
/// A first sync or a remote daemon legitimately outlasts the local budget,
|
||||
/// and treating that as "down" is what left receipts
|
||||
/// Budget for calls that wait on the daemon (`get_info`, `get_transfers`,
|
||||
/// `transfer`). A first sync or a remote daemon legitimately outlasts the
|
||||
/// local budget, and treating that as "down" is what left receipts
|
||||
/// permanently unverified.
|
||||
timeout_chain: Duration,
|
||||
/// Chain daemon to compare the wallet's scanned height against. `None`
|
||||
/// means no comparable tip (receive-only, a `.onion` daemon that needs the
|
||||
/// SOCKS child, an externally run wallet RPC): readiness stays false. Set
|
||||
/// from [`crate::wallet_child::ChildConfig::daemon_probe_addr`] by the node.
|
||||
daemon_probe: Option<String>,
|
||||
}
|
||||
|
||||
/// What the readiness pair is: the wallet's own scanned height and the chain
|
||||
/// tip the daemon reports. Neither number comes from the wallet RPC's
|
||||
/// `get_info` — `monero-wallet-rpc` does not implement it (`-32601 Method not
|
||||
/// found`); `get_info` exists on the daemon only.
|
||||
///
|
||||
/// `0` height means the wallet RPC answered without a number. `tip == None`
|
||||
/// means the daemon did not answer. Both are unknown — never "caught up".
|
||||
/// The `get_info` fields one wallet-RPC probe carries: the readiness verdict and
|
||||
/// the numbers a status line shows. `0` height/target means the wallet RPC
|
||||
/// answered without a number — unknown, never "caught up", and never a percent.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ChainInfo {
|
||||
/// Blocks the wallet has scanned, from the wallet RPC's `get_height`.
|
||||
/// The wallet RPC said `synchronized: true`. A missing field is `false`.
|
||||
pub synchronized: bool,
|
||||
/// Blocks the wallet's daemon has, as the wallet RPC reports them.
|
||||
pub height: u64,
|
||||
/// The daemon's chain tip, or `None` when it could not be asked.
|
||||
pub tip: Option<u64>,
|
||||
/// Blocks that daemon is syncing towards; `0` when it reported none.
|
||||
pub target_height: u64,
|
||||
}
|
||||
|
||||
/// How far behind the daemon tip a wallet may be and still count as caught up.
|
||||
///
|
||||
/// The tip moves every ~2 minutes and the daemon answer and the wallet scan are
|
||||
/// two reads, not one snapshot, so a strict `>=` gate flaps on a wallet that is
|
||||
/// one block behind for a few seconds. Two blocks is a deliberate slack, small
|
||||
/// enough that a real lag (a first sync, a stalled scan) still reads not-ready.
|
||||
const READY_SLACK_BLOCKS: u64 = 2;
|
||||
|
||||
impl ChainInfo {
|
||||
/// The readiness predicate, stated once:
|
||||
///
|
||||
/// `height > 0 && (tip == 0 || height + READY_SLACK_BLOCKS >= tip)`
|
||||
///
|
||||
/// A daemon that did not answer is not ready. A wallet with no scanned
|
||||
/// height is not ready. Fail closed on every branch.
|
||||
/// The readiness predicate: the daemon reached the tip and the wallet
|
||||
/// scanned up to it. `synchronized` must be explicitly true, and a chain
|
||||
/// with no height is not ready.
|
||||
pub fn ready(&self) -> bool {
|
||||
self.height > 0
|
||||
&& self.tip.is_some_and(|tip| {
|
||||
tip == 0 || self.height.saturating_add(READY_SLACK_BLOCKS) >= tip
|
||||
})
|
||||
self.synchronized
|
||||
&& self.height > 0
|
||||
&& (self.target_height == 0 || self.height >= self.target_height)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -582,7 +563,6 @@ impl Wallet {
|
|||
no_spend,
|
||||
timeout_local: RPC_TIMEOUT,
|
||||
timeout_chain: CHAIN_RPC_TIMEOUT,
|
||||
daemon_probe: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -765,13 +745,6 @@ impl Wallet {
|
|||
self
|
||||
}
|
||||
|
||||
/// Where to read the chain tip for the readiness comparison. `None` keeps
|
||||
/// readiness fail-closed: a wallet with no comparable daemon is never ready.
|
||||
pub fn with_daemon_probe(mut self, addr: Option<String>) -> Self {
|
||||
self.daemon_probe = addr;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn no_spend(&self) -> bool {
|
||||
self.no_spend
|
||||
}
|
||||
|
|
@ -885,34 +858,27 @@ impl Wallet {
|
|||
.map_err(|_| Error("wallet RPC returned a non-numeric unlocked_balance".into()))
|
||||
}
|
||||
|
||||
/// The real readiness predicate: the wallet's own scanned height is at the
|
||||
/// chain tip (within the deliberate [`READY_SLACK_BLOCKS`]). The wallet RPC
|
||||
/// is asked `get_height` — never `get_info`, which it does not implement —
|
||||
/// and the tip comes from the daemon client.
|
||||
/// The real readiness predicate: the daemon has reached the chain tip and
|
||||
/// the wallet has scanned up to it. `synchronized` must be explicitly true —
|
||||
/// a missing field is not-ready, never a silent pass.
|
||||
pub async fn chain_ready(&self) -> Result<bool> {
|
||||
Ok(self.chain_info().await?.ready())
|
||||
}
|
||||
|
||||
/// One readiness pair: the wallet's scanned height from the wallet RPC's
|
||||
/// `get_height`, and the daemon's tip from the daemon client. The status
|
||||
/// line and the spend gate ask the same question, so they ask it once.
|
||||
///
|
||||
/// A wallet RPC that cannot answer (no wallet file open, restarting,
|
||||
/// transport) is `height: 0` + no tip: unknown is not ready, and "no wallet
|
||||
/// open" is a state, not an error to paint on a status row. A missing
|
||||
/// daemon answer leaves `tip: None`, which is also not ready.
|
||||
/// One `get_info` round trip, carrying both the readiness fields and the
|
||||
/// numbers a status line shows — the status line and the spend gate ask the
|
||||
/// same question, so they ask it once. `0` height/target means the wallet
|
||||
/// RPC answered without a number: unknown, never "caught up".
|
||||
pub async fn chain_info(&self) -> Result<ChainInfo> {
|
||||
let height = match self.chain_rpc("get_height", serde_json::json!({})).await {
|
||||
Ok(v) => v.get("height").and_then(|h| h.as_u64()).unwrap_or(0),
|
||||
Err(_) => 0,
|
||||
};
|
||||
let tip = match self.daemon_probe.as_deref() {
|
||||
// One small probe: a slow or dead daemon is "unknown", not a hung
|
||||
// status poll. The management budget is the short one.
|
||||
Some(addr) => daemon_get_height(addr, self.timeout_local).await.ok(),
|
||||
None => None,
|
||||
};
|
||||
Ok(ChainInfo { height, tip })
|
||||
let v = self.chain_rpc("get_info", serde_json::json!({})).await?;
|
||||
Ok(ChainInfo {
|
||||
synchronized: v
|
||||
.get("synchronized")
|
||||
.and_then(|b| b.as_bool())
|
||||
.unwrap_or(false),
|
||||
height: v.get("height").and_then(|h| h.as_u64()).unwrap_or(0),
|
||||
target_height: v.get("target_height").and_then(|h| h.as_u64()).unwrap_or(0),
|
||||
})
|
||||
}
|
||||
|
||||
/// May this wallet attempt a spend? Fail closed: any readiness doubt is a
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@
|
|||
//! compiled-in public node.
|
||||
//! * A `.onion` daemon is reached through a SOCKS child: the bundled `arti`
|
||||
//! binary run as `arti proxy -p <port>`, with **TCP loopback only** (arti
|
||||
//! 2.6.0 / tor-config 0.49 have no AF_UNIX listener — `Listen` is IP-only and
|
||||
//! 2.6.0 / tor-config 0.46 have no AF_UNIX listener — `Listen` is IP-only and
|
||||
//! arti's `port_info` says AF_UNIX is future work, arti#1965). The wallet
|
||||
//! child is then pointed at it with `--proxy socks5://127.0.0.1:<port>`
|
||||
//! *and* `--daemon-address <onion>:<port>`. The messenger's in-process
|
||||
|
|
@ -290,7 +290,7 @@ impl WalletChild {
|
|||
/// one app never share state silently.
|
||||
///
|
||||
/// `-p` is the arti CLI's `socks-port` argument (arti 2.6.0 `src/lib.rs`);
|
||||
/// it binds localhost only (`Listen::new_localhost`, tor-config 0.49
|
||||
/// it binds localhost only (`Listen::new_localhost`, tor-config 0.46
|
||||
/// `listen.rs`: "We interpret standalone ports to be localhost
|
||||
/// addresses" — `[::1, 127.0.0.1]`). There is no Unix-socket listen target
|
||||
/// to prefer: `Listen` is IP-only and arti's `port_info` says AF_UNIX is
|
||||
|
|
@ -551,15 +551,6 @@ impl WalletChild {
|
|||
&self,
|
||||
creds: impl FnOnce() -> Result<(String, Zeroizing<String>)>,
|
||||
) -> Result<Option<WalletClient>> {
|
||||
// Pre-flight the wallet RPC binary before anything is spawned: a bin
|
||||
// that cannot be exec'd must not cost a daemon launch (and its
|
||||
// readiness wait) first, and `exec`'s errno alone cannot say *which*
|
||||
// path was missing.
|
||||
// A bare name is the copy next to this binary, when one is there.
|
||||
// An absolute path is the caller's (Android jniLibs, a test fake).
|
||||
let bin = resolve_wallet_rpc_bin(&self.wallet_rpc_bin, bundled_wallet_rpc_dir().as_deref());
|
||||
check_wallet_rpc_bin(&self.wallet_rpc_bin, &bin, bare_bin_resolvable())?;
|
||||
|
||||
// Local chain source: own the daemon first, so the wallet child has
|
||||
// something to dial. Either a spawned `monerod` or the in-process
|
||||
// Cuprate node — both bind `DEFAULT_MONEROD_RPC_PORT` on loopback, so
|
||||
|
|
@ -619,6 +610,9 @@ impl WalletChild {
|
|||
let port = Self::pick_port()?;
|
||||
let login = format!("{user}:{}", pass.as_str());
|
||||
let daemon = Self::daemon_address(&self.source);
|
||||
// A bare name is the copy next to this binary, when one is there.
|
||||
// An absolute path is the caller's (Android jniLibs, a test fake).
|
||||
let bin = resolve_wallet_rpc_bin(&self.wallet_rpc_bin, bundled_wallet_rpc_dir().as_deref());
|
||||
let argv = Self::wallet_rpc_argv(
|
||||
&bin,
|
||||
port,
|
||||
|
|
@ -787,9 +781,7 @@ pub struct ChildConfig {
|
|||
/// The user's chain-source choice. `None` is receive-only: nothing spawns.
|
||||
pub source: ChainSource,
|
||||
/// `monero-wallet-rpc`. A bare name is resolved on `PATH`; Android passes an
|
||||
/// absolute path out of the app's native library directory. On a target
|
||||
/// with no `PATH` to resolve it (Android), a bare name is refused rather
|
||||
/// than persisted — it could only fail at `exec`.
|
||||
/// absolute path out of the app's native library directory.
|
||||
pub wallet_rpc_bin: PathBuf,
|
||||
/// `arti`, run as the SOCKS child for a `.onion` daemon only.
|
||||
pub arti_bin: PathBuf,
|
||||
|
|
@ -824,25 +816,17 @@ impl ChildConfig {
|
|||
self.source.label()
|
||||
}
|
||||
|
||||
/// Where the readiness comparison may ask the chain daemon itself for its
|
||||
/// tip. `monero-wallet-rpc` has no `get_info`, so the wallet's own
|
||||
/// `get_height` is only half the answer.
|
||||
///
|
||||
/// - A daemon this box owns (`monerod`/Cuprate it spawned) binds loopback:
|
||||
/// asking it is a plain local socket.
|
||||
/// - A clearnet remote daemon the user typed is already the wallet child's
|
||||
/// dial target, so one `get_height` is the same exposure — not a new path.
|
||||
/// - A `.onion` daemon must **not** be dialled directly: without the SOCKS
|
||||
/// child that would resolve the name on clearnet DNS and leak. It stays
|
||||
/// fail-closed (height-only, not ready) until the SOCKS path exists.
|
||||
/// Where a status refresh may ask the chain daemon itself for
|
||||
/// height/target, when the wallet RPC is not answering. Only a daemon this
|
||||
/// box owns: a `monerod`/Cuprate the child spawned binds loopback, and
|
||||
/// asking it is a plain local socket. A remote daemon is the wallet child's
|
||||
/// to dial (over SOCKS, if it is an onion) — a status refresh does not open
|
||||
/// a second path to it.
|
||||
pub fn daemon_probe_addr(&self) -> Option<String> {
|
||||
match &self.source {
|
||||
match self.source {
|
||||
ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. } => {
|
||||
Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"))
|
||||
}
|
||||
ChainSource::Remote { host, port } if !crate::wallet::is_onion_host(host) => {
|
||||
Some(format!("{}:{port}", host.trim()))
|
||||
}
|
||||
ChainSource::None | ChainSource::Remote { .. } => None,
|
||||
}
|
||||
}
|
||||
|
|
@ -860,14 +844,6 @@ impl ChildConfig {
|
|||
if self.wallet_rpc_bin.as_os_str().is_empty() {
|
||||
return Err(ChildError("monero-wallet-rpc path required".into()));
|
||||
}
|
||||
// A bare name is only resolvable through `PATH`. Where this target has
|
||||
// no `PATH` to search (an app sandbox), accepting it here would persist
|
||||
// a setting that can only fail at `exec`, so refuse it with the path in
|
||||
// the message. The resolved-bin existence check is the start path's job
|
||||
// (`check_wallet_rpc_bin`): at save time the file may not be created yet.
|
||||
if !bare_bin_resolvable() && self.wallet_rpc_bin.components().nth(1).is_none() {
|
||||
return Err(bare_bin_refused(&self.wallet_rpc_bin));
|
||||
}
|
||||
if self.arti_bin.as_os_str().is_empty() {
|
||||
return Err(ChildError("arti path required".into()));
|
||||
}
|
||||
|
|
@ -1278,60 +1254,6 @@ fn resolve_wallet_rpc_bin(configured: &Path, beside: Option<&Path>) -> PathBuf {
|
|||
}
|
||||
}
|
||||
|
||||
/// Can a spawned child resolve a bare `argv[0]` through `PATH` on this target?
|
||||
/// An app sandbox (Android) has no `PATH` for a child to search, so a bare name
|
||||
/// there can only fail at `exec`; a desktop can resolve one. Compile-time, so
|
||||
/// the core needs no runtime platform probe.
|
||||
const fn bare_bin_resolvable() -> bool {
|
||||
!cfg!(target_os = "android")
|
||||
}
|
||||
|
||||
fn bare_bin_refused(configured: &Path) -> ChildError {
|
||||
ChildError(format!(
|
||||
"monero-wallet-rpc: {} is a bare name and this platform has no PATH to resolve it; \
|
||||
configure an absolute path",
|
||||
configured.display()
|
||||
))
|
||||
}
|
||||
|
||||
/// Pre-flight the wallet RPC binary *before* `exec`, so the failure names the
|
||||
/// path and the reason instead of a bare `os error 2`.
|
||||
///
|
||||
/// `resolved` is what `spawn` would use; `configured` is what the caller set.
|
||||
/// A bare name is `PATH`'s job where a `PATH` exists — this does not search
|
||||
/// one, and does not fall back anywhere. On a target with no `PATH`
|
||||
/// (`bare_resolvable == false`) a bare name is refused outright.
|
||||
fn check_wallet_rpc_bin(configured: &Path, resolved: &Path, bare_resolvable: bool) -> Result<()> {
|
||||
if resolved.components().nth(1).is_none() {
|
||||
return if bare_resolvable {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(bare_bin_refused(configured))
|
||||
};
|
||||
}
|
||||
let named = if resolved == configured {
|
||||
configured.display().to_string()
|
||||
} else {
|
||||
format!(
|
||||
"{} (configured {})",
|
||||
resolved.display(),
|
||||
configured.display()
|
||||
)
|
||||
};
|
||||
match fs::metadata(resolved) {
|
||||
Ok(meta) if !meta.is_file() => Err(ChildError(format!(
|
||||
"monero-wallet-rpc: {named} is not a file"
|
||||
))),
|
||||
Ok(meta) if meta.permissions().mode() & 0o111 == 0 => Err(ChildError(format!(
|
||||
"monero-wallet-rpc: {named} is not executable"
|
||||
))),
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => Err(ChildError(format!(
|
||||
"monero-wallet-rpc: {named} not found ({e})"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn executable_file(path: &Path) -> bool {
|
||||
std::fs::metadata(path)
|
||||
.is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
|
||||
|
|
@ -1349,12 +1271,10 @@ fn spawn(argv: &[String], what: &str) -> Result<Child> {
|
|||
let (bin, args) = argv
|
||||
.split_first()
|
||||
.ok_or_else(|| ChildError(format!("empty argv for {what}")))?;
|
||||
Command::new(bin).args(args).spawn().map_err(|e| {
|
||||
// Both halves matter: the label keeps the copy readable, `argv[0]`
|
||||
// says which program actually failed (a bare name vs. an absolute
|
||||
// path — the difference the Android report could not show).
|
||||
ChildError(format!("spawn {what} ({bin}): {e}"))
|
||||
})
|
||||
Command::new(bin)
|
||||
.args(args)
|
||||
.spawn()
|
||||
.map_err(|e| ChildError(format!("spawn {what}: {e}")))
|
||||
}
|
||||
|
||||
fn kill_slot(slot: &Mutex<Option<Child>>, what: &str) -> Result<()> {
|
||||
|
|
@ -1611,7 +1531,7 @@ mod tests {
|
|||
"{argv:?}"
|
||||
);
|
||||
// `-p` binds localhost only (arti's `socks-port` arg); there is no
|
||||
// Unix-socket listen target in arti 2.6.0 / tor-config 0.49.
|
||||
// Unix-socket listen target in arti 2.6.0 / tor-config 0.46.
|
||||
assert!(!argv.iter().any(|a| a == "--port"), "{argv:?}");
|
||||
assert!(
|
||||
argv.iter()
|
||||
|
|
@ -2017,123 +1937,6 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
/// The spawn error must name the *program that failed* (`argv[0]`), not
|
||||
/// just the human label: on Android the two differ, and which one it was is
|
||||
/// the whole diagnosis.
|
||||
#[test]
|
||||
fn a_spawn_error_names_argv0_and_the_label() {
|
||||
let dir = tmp_dir("spawn-missing");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let missing = dir.join("libmonerowalletrpc.so");
|
||||
let argv = vec![missing.display().to_string(), "--version".into()];
|
||||
|
||||
let err = spawn(&argv, "monero-wallet-rpc").expect_err("a missing program cannot spawn");
|
||||
let msg = err.to_string();
|
||||
assert!(msg.starts_with("spawn monero-wallet-rpc ("), "{msg}");
|
||||
assert!(msg.contains(&missing.display().to_string()), "{msg}");
|
||||
// The errno is carried through verbatim: no invented cause.
|
||||
assert!(msg.contains("No such file or directory"), "{msg}");
|
||||
}
|
||||
|
||||
/// Pre-flight: a bin that is not an existing regular executable is refused
|
||||
/// with the configured path in the message, before `exec` gets a say.
|
||||
#[test]
|
||||
fn a_missing_wallet_rpc_bin_is_refused_with_the_configured_path() {
|
||||
let dir = tmp_dir("preflight-missing");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let configured = dir.join("libmonerowalletrpc.so");
|
||||
|
||||
let err = check_wallet_rpc_bin(&configured, &configured, true)
|
||||
.expect_err("a bin that does not exist cannot be spawned");
|
||||
let msg = err.to_string();
|
||||
assert!(msg.contains(&configured.display().to_string()), "{msg}");
|
||||
assert!(msg.contains("not found"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wallet_rpc_bin_that_is_not_a_file_is_refused() {
|
||||
let dir = tmp_dir("preflight-dir");
|
||||
let configured = dir.join("libmonerowalletrpc.so");
|
||||
fs::create_dir_all(&configured).unwrap();
|
||||
|
||||
let err = check_wallet_rpc_bin(&configured, &configured, true)
|
||||
.expect_err("a directory cannot be executed");
|
||||
let msg = err.to_string();
|
||||
assert!(msg.contains(&configured.display().to_string()), "{msg}");
|
||||
assert!(msg.contains("not a file"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wallet_rpc_bin_without_any_execute_bit_is_refused() {
|
||||
let dir = tmp_dir("preflight-noexec");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let configured = dir.join("libmonerowalletrpc.so");
|
||||
fs::write(&configured, b"not a program\n").unwrap();
|
||||
let mut perms = fs::metadata(&configured).unwrap().permissions();
|
||||
perms.set_mode(0o644);
|
||||
fs::set_permissions(&configured, perms).unwrap();
|
||||
|
||||
let err = check_wallet_rpc_bin(&configured, &configured, true)
|
||||
.expect_err("a file with no execute bit cannot be spawned");
|
||||
let msg = err.to_string();
|
||||
assert!(msg.contains(&configured.display().to_string()), "{msg}");
|
||||
assert!(msg.contains("not executable"), "{msg}");
|
||||
|
||||
let mut perms = fs::metadata(&configured).unwrap().permissions();
|
||||
perms.set_mode(0o755);
|
||||
fs::set_permissions(&configured, perms).unwrap();
|
||||
assert!(
|
||||
check_wallet_rpc_bin(&configured, &configured, true).is_ok(),
|
||||
"an executable file passes the pre-flight"
|
||||
);
|
||||
}
|
||||
|
||||
/// A bare name is only resolvable through `PATH`. Where the target has no
|
||||
/// `PATH` to search (an app sandbox), it is refused with the path in the
|
||||
/// message; on a desktop the pre-flight leaves it to `exec`.
|
||||
#[test]
|
||||
fn a_bare_wallet_rpc_bin_is_refused_where_path_cannot_resolve_it() {
|
||||
let bare = Path::new("monero-wallet-rpc");
|
||||
|
||||
let err = check_wallet_rpc_bin(bare, bare, false)
|
||||
.expect_err("a bare name cannot resolve in an app sandbox");
|
||||
let msg = err.to_string();
|
||||
assert!(msg.contains("monero-wallet-rpc"), "{msg}");
|
||||
assert!(msg.contains("bare name"), "{msg}");
|
||||
|
||||
assert!(
|
||||
check_wallet_rpc_bin(bare, bare, true).is_ok(),
|
||||
"a desktop leaves a bare name to PATH"
|
||||
);
|
||||
}
|
||||
|
||||
/// The start path refuses a missing bin before spawning anything, and says
|
||||
/// which configured path was missing.
|
||||
#[test]
|
||||
fn start_refuses_a_wallet_rpc_bin_that_is_not_there() {
|
||||
let dir = tmp_dir("start-missing-bin");
|
||||
let store = open_store(&dir);
|
||||
let missing = dir.join("wallet").join("libmonerowalletrpc.so");
|
||||
let child = WalletChild::new(
|
||||
ChainSource::Remote {
|
||||
host: "127.0.0.1".into(),
|
||||
port: 18089,
|
||||
},
|
||||
dir.join("wallet"),
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
.with_wallet_rpc_bin(missing.clone());
|
||||
|
||||
let err = child
|
||||
.start(&store)
|
||||
.expect_err("a missing wallet rpc bin cannot spawn");
|
||||
let msg = err.to_string();
|
||||
assert!(msg.contains(&missing.display().to_string()), "{msg}");
|
||||
assert!(msg.contains("not found"), "{msg}");
|
||||
assert!(!child.running(), "nothing may be left running: {msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monerod_argv_binds_loopback_and_uses_the_datadir() {
|
||||
let dir = tmp_dir("monerod-argv");
|
||||
|
|
@ -2617,12 +2420,11 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
/// A daemon this box owns, or a clearnet daemon the user typed, may be asked
|
||||
/// for its tip: both are already dialled by the wallet child. A `.onion`
|
||||
/// daemon must not be dialled without the SOCKS child, and receive-only has
|
||||
/// nothing to ask at all.
|
||||
/// Only a daemon this box owns is asked directly. A remote daemon is the
|
||||
/// wallet child's to dial — a status refresh must not open a second path to
|
||||
/// it, and receive-only has nothing to ask at all.
|
||||
#[test]
|
||||
fn only_a_reachable_daemon_gets_a_probe_address() {
|
||||
fn only_a_loopback_source_gets_a_daemon_probe_address() {
|
||||
let loopback = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}");
|
||||
for source in [
|
||||
ChainSource::Local {
|
||||
|
|
@ -2642,25 +2444,16 @@ mod tests {
|
|||
};
|
||||
assert_eq!(cfg.daemon_probe_addr().as_deref(), Some(loopback.as_str()));
|
||||
}
|
||||
// A clearnet remote daemon is the user's explicit choice and the wallet
|
||||
// child already dials it: one `get_height` is the same exposure.
|
||||
let cfg = ChildConfig {
|
||||
source: ChainSource::Remote {
|
||||
host: "203.0.113.7".to_string(),
|
||||
port: 18081,
|
||||
},
|
||||
..ChildConfig::default()
|
||||
};
|
||||
assert_eq!(
|
||||
cfg.daemon_probe_addr().as_deref(),
|
||||
Some("203.0.113.7:18081")
|
||||
);
|
||||
for source in [
|
||||
ChainSource::None,
|
||||
ChainSource::Remote {
|
||||
host: "peer.onion".to_string(),
|
||||
port: 18081,
|
||||
},
|
||||
ChainSource::Remote {
|
||||
host: "203.0.113.7".to_string(),
|
||||
port: 18081,
|
||||
},
|
||||
] {
|
||||
let cfg = ChildConfig {
|
||||
source,
|
||||
|
|
|
|||
244
tests/wallet.rs
244
tests/wallet.rs
|
|
@ -150,14 +150,12 @@ async fn mock_create_address_and_transfer() {
|
|||
listener,
|
||||
Arc::new(Mutex::new(Vec::new())),
|
||||
Arc::new(move |method| match method {
|
||||
// A spend is only attempted on a synced wallet: the wallet's own
|
||||
// scanned height plus the daemon tip.
|
||||
"get_height" => wallet_height(3210000),
|
||||
// A spend is only attempted on a synced wallet.
|
||||
"get_info" => synced_info(),
|
||||
_ => rpc_result(&format!(r#"{{"address":"{addr_hex}","tx_hash":"abc123"}}"#)),
|
||||
}),
|
||||
));
|
||||
let daemon = mock_daemon(3210000, 3210000).await;
|
||||
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||
let w = recording_wallet(port);
|
||||
let created = w.create_address().await.expect("create_address");
|
||||
assert!(created.starts_with('8'));
|
||||
|
||||
|
|
@ -443,59 +441,10 @@ fn rpc_result(result: &str) -> String {
|
|||
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
|
||||
}
|
||||
|
||||
/// What the wallet RPC answers to `get_height`: the wallet's own scanned height.
|
||||
/// This is the honest wallet-side signal — `get_info` does not exist there.
|
||||
fn wallet_height(height: u64) -> String {
|
||||
rpc_result(&format!(r#"{{"height":{height}}}"#))
|
||||
}
|
||||
|
||||
/// A chain-daemon stub. `GET /get_height` answers the tip; `/json_rpc get_info`
|
||||
/// answers height and target. A daemon is unauthenticated, so no Digest flow.
|
||||
async fn serve_daemon(
|
||||
listener: TcpListener,
|
||||
height: u64,
|
||||
target: u64,
|
||||
log: Option<Arc<Mutex<Vec<String>>>>,
|
||||
) {
|
||||
while let Ok((mut sock, _)) = listener.accept().await {
|
||||
let mut buf = vec![0u8; 8192];
|
||||
let Ok(n) = sock.read(&mut buf).await else {
|
||||
return;
|
||||
};
|
||||
if n == 0 {
|
||||
continue;
|
||||
}
|
||||
let req = String::from_utf8_lossy(&buf[..n]).to_string();
|
||||
if let Some(log) = &log {
|
||||
log.lock().expect("daemon log").push(req.clone());
|
||||
}
|
||||
let body = if req.starts_with("GET /get_height") {
|
||||
format!(r#"{{"height":{height}}}"#)
|
||||
} else if req.contains("get_info") {
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target}}}}}"#
|
||||
)
|
||||
} else {
|
||||
"{}".to_string()
|
||||
};
|
||||
let _ = sock
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a daemon stub on an ephemeral loopback port; returns `host:port`.
|
||||
async fn mock_daemon(height: u64, target: u64) -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
tokio::spawn(serve_daemon(listener, height, target, None));
|
||||
addr
|
||||
/// What a fully synced wallet answers to `get_info`: the daemon has reached the
|
||||
/// tip and the wallet has scanned it. This is the honest readiness signal.
|
||||
fn synced_info() -> String {
|
||||
rpc_result(r#"{"height":3210000,"target_height":3210000,"synchronized":true}"#)
|
||||
}
|
||||
|
||||
fn recording_wallet(port: u16) -> Wallet {
|
||||
|
|
@ -583,12 +532,11 @@ async fn view_only_wallet_maps_transfer_failure_to_clear_message() {
|
|||
Arc::clone(&log),
|
||||
Arc::new(|method| match method {
|
||||
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
|
||||
"get_height" => wallet_height(3210000),
|
||||
"get_info" => synced_info(),
|
||||
_ => rpc_error(-18, "No transaction created"),
|
||||
}),
|
||||
));
|
||||
let daemon = mock_daemon(3210000, 3210000).await;
|
||||
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||
let w = recording_wallet(port);
|
||||
assert!(!w.no_spend());
|
||||
let err = w
|
||||
.transfer(
|
||||
|
|
@ -616,13 +564,11 @@ async fn spend_capable_wallet_keeps_the_original_transfer_error() {
|
|||
Arc::new(Mutex::new(Vec::new())),
|
||||
Arc::new(|method| match method {
|
||||
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
|
||||
"get_height" => wallet_height(3210000),
|
||||
"get_info" => synced_info(),
|
||||
_ => rpc_error(-18, "No transaction created"),
|
||||
}),
|
||||
));
|
||||
let daemon = mock_daemon(3210000, 3210000).await;
|
||||
let err = recording_wallet(port)
|
||||
.with_daemon_probe(Some(daemon))
|
||||
.transfer(
|
||||
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||
1,
|
||||
|
|
@ -1271,8 +1217,7 @@ async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) {
|
|||
serve_rpc_conns(
|
||||
listener,
|
||||
Arc::new(|method: &str| match method {
|
||||
"get_height" => wallet_height(3210000),
|
||||
"get_transfers" => rpc_result(r#"{"in":[],"pending":[]}"#),
|
||||
"get_info" => synced_info(),
|
||||
_ => rpc_result(
|
||||
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
|
||||
),
|
||||
|
|
@ -1297,14 +1242,15 @@ async fn unsynced_wallet_is_not_ready_and_refuses_to_spend() {
|
|||
listener,
|
||||
Arc::clone(&log),
|
||||
Arc::new(|method| match method {
|
||||
"get_height" => wallet_height(1200000),
|
||||
"get_info" => {
|
||||
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
|
||||
}
|
||||
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
||||
}),
|
||||
));
|
||||
let daemon = mock_daemon(3210000, 3210000).await;
|
||||
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||
let w = recording_wallet(port);
|
||||
assert!(
|
||||
!w.chain_ready().await.expect("get_height"),
|
||||
!w.chain_ready().await.expect("get_info"),
|
||||
"must not be ready"
|
||||
);
|
||||
assert!(
|
||||
|
|
@ -1321,115 +1267,16 @@ async fn unsynced_wallet_is_not_ready_and_refuses_to_spend() {
|
|||
);
|
||||
}
|
||||
|
||||
/// `monero-wallet-rpc` has no `get_info` (it answers `-32601 Method not found`).
|
||||
/// Readiness must never depend on that call: the wallet's own `get_height` is
|
||||
/// compared with the daemon's tip.
|
||||
/// A missing/absent `synchronized` (or a wallet behind the daemon) is not-ready,
|
||||
/// never a silent pass. Fail closed.
|
||||
#[tokio::test]
|
||||
async fn readiness_never_asks_the_wallet_rpc_for_get_info() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let log = Arc::new(Mutex::new(Vec::new()));
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::clone(&log),
|
||||
Arc::new(|method| match method {
|
||||
"get_height" => wallet_height(3210000),
|
||||
"get_info" => rpc_error(-32601, "Method not found"),
|
||||
_ => rpc_result("{}"),
|
||||
}),
|
||||
));
|
||||
let daemon = mock_daemon(3210000, 3210000).await;
|
||||
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||
assert!(
|
||||
w.chain_ready().await.expect("get_height"),
|
||||
"a wallet at the daemon tip is ready without get_info"
|
||||
);
|
||||
let seen = log.lock().expect("log").clone();
|
||||
assert!(
|
||||
seen.iter().any(|r| r.contains("\"method\":\"get_height\"")),
|
||||
"the wallet's own scanned height must be asked: {seen:?}"
|
||||
);
|
||||
assert!(
|
||||
!seen.iter().any(|r| r.contains("\"method\":\"get_info\"")),
|
||||
"get_info is not a wallet-RPC method and must not be probed: {seen:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Readiness against a daemon tip: equal is ready, the tip moves every ~2 min so
|
||||
/// a two-block gap is ready, a real lag is not.
|
||||
#[tokio::test]
|
||||
async fn a_wallet_within_the_slack_of_the_daemon_tip_is_ready() {
|
||||
for (wallet, tip, ready) in [
|
||||
(3210000u64, 3210000u64, true),
|
||||
(3209998, 3210000, true),
|
||||
(3209997, 3210000, false),
|
||||
async fn missing_or_behind_synchronized_is_not_ready() {
|
||||
for info in [
|
||||
r#"{"height":10}"#,
|
||||
r#"{"height":100,"target_height":200,"synchronized":true}"#,
|
||||
r#"{"height":0,"target_height":0,"synchronized":true}"#,
|
||||
r#"{"synchronized":"true"}"#,
|
||||
] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::new(Mutex::new(Vec::new())),
|
||||
Arc::new(move |_| wallet_height(wallet)),
|
||||
));
|
||||
let daemon = mock_daemon(tip, tip).await;
|
||||
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||
assert_eq!(
|
||||
w.chain_ready().await.expect("get_height"),
|
||||
ready,
|
||||
"wallet {wallet} / tip {tip}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A daemon that does not answer leaves the tip unknown. Unknown is *not*
|
||||
/// caught up — fail closed, never a silent pass.
|
||||
#[tokio::test]
|
||||
async fn an_unreachable_daemon_is_not_ready() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::new(Mutex::new(Vec::new())),
|
||||
Arc::new(|_| wallet_height(3210000)),
|
||||
));
|
||||
// Bind, read the port, drop: nothing is listening there.
|
||||
let dead = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let dead_addr = dead.local_addr().unwrap().to_string();
|
||||
drop(dead);
|
||||
let w = recording_wallet(port).with_daemon_probe(Some(dead_addr));
|
||||
assert!(
|
||||
!w.chain_ready().await.expect("get_height"),
|
||||
"an unanswered daemon must not read as ready"
|
||||
);
|
||||
}
|
||||
|
||||
/// A wallet RPC with no wallet file open answers `-13 No wallet file` to
|
||||
/// `get_height`. That is a state, not an error banner: not ready, no Err.
|
||||
#[tokio::test]
|
||||
async fn an_rpc_with_no_wallet_open_is_not_ready_and_not_an_error() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::new(Mutex::new(Vec::new())),
|
||||
Arc::new(|_| rpc_error(-13, "No wallet file")),
|
||||
));
|
||||
let daemon = mock_daemon(3210000, 3210000).await;
|
||||
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||
assert!(
|
||||
!w.chain_ready()
|
||||
.await
|
||||
.expect("no wallet file is a state, not an error"),
|
||||
"a wallet with no file open is not ready"
|
||||
);
|
||||
assert!(!w.can_verify_receipts().await);
|
||||
}
|
||||
|
||||
/// An answered `get_height` with no height (or height 0) is unknown, and a
|
||||
/// daemon tip of 0 is a daemon that has not indexed anything: not ready.
|
||||
#[tokio::test]
|
||||
async fn a_missing_or_zero_wallet_height_is_not_ready() {
|
||||
for info in [r#"{}"#, r#"{"height":0}"#, r#"{"height":"10"}"#] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let canned = rpc_result(info);
|
||||
|
|
@ -1438,10 +1285,9 @@ async fn a_missing_or_zero_wallet_height_is_not_ready() {
|
|||
Arc::new(Mutex::new(Vec::new())),
|
||||
Arc::new(move |_| canned.clone()),
|
||||
));
|
||||
let daemon = mock_daemon(0, 0).await;
|
||||
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||
let w = recording_wallet(port);
|
||||
assert!(
|
||||
!w.chain_ready().await.expect("get_height"),
|
||||
!w.chain_ready().await.expect("get_info"),
|
||||
"{info} must not read as ready"
|
||||
);
|
||||
}
|
||||
|
|
@ -1455,13 +1301,12 @@ async fn synced_wallet_is_ready_and_spends() {
|
|||
listener,
|
||||
Arc::new(Mutex::new(Vec::new())),
|
||||
Arc::new(|method| match method {
|
||||
"get_height" => wallet_height(3210000),
|
||||
"get_info" => synced_info(),
|
||||
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
||||
}),
|
||||
));
|
||||
let daemon = mock_daemon(3210000, 3210000).await;
|
||||
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||
assert!(w.chain_ready().await.expect("get_height"));
|
||||
let w = recording_wallet(port);
|
||||
assert!(w.chain_ready().await.expect("get_info"));
|
||||
assert!(w.can_verify_receipts().await);
|
||||
assert_eq!(w.transfer(SPEND_ADDR, 1).await.expect("transfer"), "abc123");
|
||||
}
|
||||
|
|
@ -1480,13 +1325,12 @@ async fn spend_ready_needs_an_unlocked_balance() {
|
|||
listener,
|
||||
Arc::new(Mutex::new(Vec::new())),
|
||||
Arc::new(move |method| match method {
|
||||
"get_height" => wallet_height(3210000),
|
||||
"get_info" => synced_info(),
|
||||
"get_balance" => balance.clone(),
|
||||
_ => rpc_result("{}"),
|
||||
_ => rpc_result(r#"{}"#),
|
||||
}),
|
||||
));
|
||||
let daemon = mock_daemon(3210000, 3210000).await;
|
||||
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||
let w = recording_wallet(port);
|
||||
assert_eq!(w.spend_ready().await.expect("spend_ready"), ready);
|
||||
}
|
||||
}
|
||||
|
|
@ -1525,15 +1369,16 @@ async fn unsynced_wallet_leaves_a_matching_receipt_unverified() {
|
|||
listener,
|
||||
Arc::new(Mutex::new(Vec::new())),
|
||||
Arc::new(move |method| match method {
|
||||
"get_height" => wallet_height(1200000),
|
||||
"get_info" => {
|
||||
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
|
||||
}
|
||||
"get_transfers" => rpc_result(&format!(
|
||||
r#"{{"in":[{{"txid":"deadbeef","amount":5,"address":"{addr_owned}"}}],"pending":[]}}"#
|
||||
)),
|
||||
_ => rpc_result("{}"),
|
||||
_ => rpc_result(r#"{}"#),
|
||||
}),
|
||||
));
|
||||
let daemon = mock_daemon(3210000, 3210000).await;
|
||||
let w = recording_wallet(port).with_daemon_probe(Some(daemon));
|
||||
let w = recording_wallet(port);
|
||||
|
||||
// The same shape node.rs::ingest_receipt runs.
|
||||
if w.can_verify_receipts().await
|
||||
|
|
@ -1548,10 +1393,8 @@ async fn unsynced_wallet_leaves_a_matching_receipt_unverified() {
|
|||
);
|
||||
}
|
||||
|
||||
/// Chain-dependent calls (`get_transfers`, `transfer`) get a longer budget than
|
||||
/// local wallet-management calls, and the budget is the backend's to set — not a
|
||||
/// hard-coded 5s. Readiness is no longer a chain wait: it is one local
|
||||
/// `get_height` plus one bounded daemon probe.
|
||||
/// Chain-dependent calls get a longer budget than local wallet-management calls,
|
||||
/// and the budget is the backend's to set — not a hard-coded 5s.
|
||||
#[tokio::test]
|
||||
async fn chain_calls_get_a_longer_budget_than_local_calls() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
|
|
@ -1569,11 +1412,12 @@ async fn chain_calls_get_a_longer_budget_than_local_calls() {
|
|||
err.to_ascii_lowercase().contains("timed out"),
|
||||
"the local call must hit the short budget: {err}"
|
||||
);
|
||||
let rows = w
|
||||
.get_transfers()
|
||||
assert!(
|
||||
w.chain_ready()
|
||||
.await
|
||||
.expect("get_transfers within the chain budget");
|
||||
assert!(rows.is_empty(), "{rows:?}");
|
||||
.expect("get_info within the chain budget"),
|
||||
"chain calls must outlast daemon latency"
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
|
|||
Loading…
Reference in a new issue