diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index fe6fe69..3961d03 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -56,7 +56,7 @@ env: # On `rust:1.91-bookworm` that is `error[E0658]: use of unstable library # 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 + # and in the Android workflows. `--no-default-features` still builds on 1.92 # (Arti 0.49's floor); the default build does not, so the image follows the # default build. RUST_IMAGE: rust:1.98-bookworm diff --git a/Cargo.lock b/Cargo.lock index 443af58..6a58e34 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4458,7 +4458,7 @@ dependencies = [ "derive-deftly", "libc", "paste", - "thiserror 2.0.20", + "thiserror 1.0.69", ] [[package]] diff --git a/README.md b/README.md index 21bc666..bbb3568 100644 --- a/README.md +++ b/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 @@ -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-.aar`. UniFFI Kotlin over the same Rust crate the TUI runs. See [crates/onionwire-sdk/README.md](crates/onionwire-sdk/README.md). - **APK** — `onionwire--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=` to attach the APK + AAR. ```bash -FORGEJO_TOKEN= scripts/build-release-local.sh v0.7.0 +FORGEJO_TOKEN= scripts/build-release-local.sh v0.5.0 ``` Do not run `cargo publish`; `publish = false`. diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 5da0390..cc16ef2 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -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 = - 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() } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt index 2f15281..5bae4d1 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt @@ -2,7 +2,6 @@ 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 /** @@ -447,21 +446,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 @@ -618,7 +609,7 @@ fun startBlockedReason( // 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.configured -> "No chain source yet: the wallet 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,172 +617,6 @@ 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. diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt index 214394d..68884be 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt @@ -176,31 +176,6 @@ const val WALLET_DAEMON_REFUSED_TEXT: String = "The wallet daemon refused that request and gave no readable reason. Check the wallet " + "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 +201,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 diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index 4299cc2..67c2f29 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -169,11 +169,6 @@ fun WalletScreen( LaunchedEffect(Unit) { reload() vm.refreshChainSource() - // Self-heal before the gate is asked: a stored `wallet_rpc_bin` left by - // an older install can point at a path this device cannot execute, and - // the bundled binary is the right answer for it. The gate below then - // names the path only when no repair was possible. - vm.healStoredWalletBin(bins) } // The same reads again, once the wallet has actually answered. They are @@ -267,33 +262,22 @@ fun WalletScreen( // about a seed they do not have. val walletReadable = balance != null && balance != "off" && balance != "err" val walletOpen = child?.walletOpen == true - // A sticky failure captured while no wallet was open is not a - // failure once one is: drop it, so the red line does not outlive - // the state that produced it. - LaunchedEffect(walletOpen) { - if (walletOpen) vm.clearWalletChildError() - } val unbacked = SeedBackupGate.warningVisible(seedConfirmed, walletReadable) if (unbacked) { UnbackedSeedCard(error = error, onBackUpSeed = { openSeedBackup() }) } val phase = walletChildPhase(childInput) - // Create and Import are RPC calls against the running child. With no - // child up they can only fail, and the failure is the TUI's `open F7` - // copy — so the controls stay dead and say why instead. - val setupBlocked = walletSetupBlockedReason(childInput) WalletHeroCard( balance = balance, address = address, walletOpen = walletOpen, phase = phase, showQr = showQr, - setupBlocked = setupBlocked, onToggleQr = { showQr = !showQr }, onOpenWallets = onOpenWallets, - onCreate = { if (setupBlocked == null) setup = SetupKind.Create }, - onImport = { if (setupBlocked == null) setup = SetupKind.Import }, + onCreate = { setup = SetupKind.Create }, + onImport = { setup = SetupKind.Import }, onInvoice = { composer = PayKind.Invoice }, onTip = { composer = PayKind.Tip }, onBackUpSeed = if ( @@ -352,12 +336,9 @@ fun WalletScreen( .onFailure { daemonError = walletFailureText(it.message ?: it.toString()) } .onSuccess { // Selecting a mode stores it and, when the - // storage floor *and* the Start gate would allow - // a launch, starts the node. The stored binary is - // what the just-saved config holds; the gate - // asks it the same question Start does, so a - // mode tap can never launch a child Start would - // have refused. + // storage floor would allow Start, starts the + // node: a mode button that only rewrites a + // storage line reads as a no-op. if (shouldStartAfterSelectingChain( chainStorageBlockedReason( vm.chainFreeBytes(), @@ -365,10 +346,6 @@ fun WalletScreen( prune = prune, ), starting = starting, - startBlocked = storedWalletBinBlockedReason( - bins.walletRpc, - bins.walletRpc, - ), ) ) { vm.startWalletChild() @@ -465,12 +442,6 @@ private fun WalletHeroCard( walletOpen: Boolean, phase: WalletChildPhase, showQr: Boolean, - /** - * Why Create / Import cannot be offered yet, or `null` when they can. From - * [walletSetupBlockedReason]: both flows are RPC calls against a running - * wallet child, so a stopped child is a dead end the screen may not offer. - */ - setupBlocked: String?, onToggleQr: () -> Unit, onOpenWallets: () -> Unit, onCreate: () -> Unit, @@ -531,30 +502,16 @@ private fun WalletHeroCard( OwButton( text = "Create Wallet", variant = OwButtonVariant.Primary, - enabled = setupBlocked == null, onClick = onCreate, modifier = Modifier.weight(1f).testTag("wallet-create"), ) OwButton( text = "Import Wallet", variant = OwButtonVariant.Secondary, - enabled = setupBlocked == null, onClick = onImport, modifier = Modifier.weight(1f).testTag("wallet-import"), ) } - // Why the two flows are dead, in a sentence rather than a grey pair - // of buttons. The only fix is on the node card below, so the copy - // points there. - setupBlocked?.let { - Spacer(Modifier.height(8.dp)) - OwAlertBanner( - variant = OwAlertVariant.Info, - title = "Wallet not running", - description = it, - modifier = Modifier.testTag("wallet-setup-blocked"), - ) - } // Invoicing does not need a wallet file: the core resolves the payee // address from the profile (`no receive address — set profile xmr or // ONIONWIRE_WALLET_RPC` is the both-missing case). Hiding the action @@ -657,27 +614,16 @@ private fun WalletHeroCard( OwButton( text = "New wallet", variant = OwButtonVariant.Outline, - enabled = setupBlocked == null, onClick = onCreate, modifier = Modifier.weight(1f).testTag("wallet-create"), ) OwButton( text = "Import wallet", variant = OwButtonVariant.Outline, - enabled = setupBlocked == null, onClick = onImport, modifier = Modifier.weight(1f).testTag("wallet-import"), ) } - setupBlocked?.let { - Spacer(Modifier.height(8.dp)) - OwAlertBanner( - variant = OwAlertVariant.Info, - title = "Wallet not running", - description = it, - modifier = Modifier.testTag("wallet-setup-blocked"), - ) - } // The recovery path for a wallet whose seed was missed: a quiet action, // because a healthy wallet needs it rarely and a seed is a spend key. // While the seed is unconfirmed the strip above carries the button @@ -744,10 +690,7 @@ private fun NodeCard( val progress = syncProgress(input?.height ?: 0uL, input?.targetHeight ?: 0uL) val node = nodePhase(input) val onionDaemon = chain?.kind == ChainChoice.REMOTE && isOnionHost(chain.host) - // The full gate: eligibility *and* the stored binary this build will - // actually spawn. A populated `bins` alone used to pass, which is how a - // stored bare name got as far as `spawn` and failed with ENOENT. - val startWhy = startGateReason(bins, input, chain?.walletRpcBin, onionDaemon, starting) + val startWhy = startBlockedReason(bins, input, onionDaemon, starting) ?: if (inProcess) { chainStorageBlockedReason( nodeFreeBytes, @@ -1033,28 +976,15 @@ private fun NodeCard( // acts, like the chat screen's load error. Filtered through // `walletFailureText`: the daemon's own `-13 No wallet file` / JSON // answer is not a sentence about this app and never reaches the screen. - // - // "No wallet open" is a state, not a failure: the info banner above - // already owns it, so it is not painted red and not printed twice. val failure = walletFailureText(input?.lastError) ?: actionError ?: daemonError failure?.let { - walletFailureBanner( - text = it, - openHintVisible = openHint != null, - walletOpen = walletOpen, - )?.let { banner -> - Spacer(Modifier.height(8.dp)) - OwAlertBanner( - variant = if (banner.tone == WalletFailureTone.Info) { - OwAlertVariant.Info - } else { - OwAlertVariant.Error - }, - title = banner.title, - description = banner.text, - modifier = Modifier.testTag("wallet-child-error"), - ) - } + Spacer(Modifier.height(8.dp)) + OwAlertBanner( + variant = OwAlertVariant.Error, + title = "Wallet error", + description = it, + modifier = Modifier.testTag("wallet-child-error"), + ) } } } diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt index 255c217..def027a 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt @@ -621,140 +621,4 @@ class WalletChildStatusTextTest { 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)) - } } diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt index aab4313..fac959d 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt @@ -477,27 +477,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)) - } } diff --git a/crates/onionwire-sdk/Cargo.lock b/crates/onionwire-sdk/Cargo.lock index c327104..896c6f6 100644 --- a/crates/onionwire-sdk/Cargo.lock +++ b/crates/onionwire-sdk/Cargo.lock @@ -4514,7 +4514,7 @@ dependencies = [ "derive-deftly", "libc", "paste", - "thiserror 2.0.20", + "thiserror 1.0.69", ] [[package]] diff --git a/crates/onionwire-sdk/Cargo.toml b/crates/onionwire-sdk/Cargo.toml index ff24a3a..dc03fc3 100644 --- a/crates/onionwire-sdk/Cargo.toml +++ b/crates/onionwire-sdk/Cargo.toml @@ -3,7 +3,7 @@ name = "onionwire-sdk" version = "0.1.0" edition = "2024" # Follows the root crate. The SDK builds onionwire with `default-features = -# false` (no `cuprate-daemon`), which would still compile on 1.91, but cargo +# false` (no `cuprate-daemon`), which would still compile on 1.92, but cargo # checks the path dependency's `rust-version` anyway, and that floor is 1.98. rust-version = "1.98" description = "OnionWire Android/Kotlin SDK: in-process Arti onion transport, Noise IK, identity = ed25519 pubkey." diff --git a/docs/ARTI_UPGRADE.md b/docs/ARTI_UPGRADE.md index 7045e62..8072903 100644 --- a/docs/ARTI_UPGRADE.md +++ b/docs/ARTI_UPGRADE.md @@ -16,15 +16,15 @@ Direct dependencies that come from the Arti repository, exactly as | `tor-cell` | `0.49` | — | | `tor-hsservice` | `0.49` | — | | `tor-rtcompat` | `0.49` | `tokio` | -| `safelog` | `0.10` | — | `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. + +`safelog` is the one non-`tor-*` crate that moves with Arti. `HsId`'s +`DisplayRedacted` impl comes from the `safelog` version Arti itself depends on, +so a direct `safelog` pin older than that version makes +`id.display_redacted()` a "multiple different versions of crate `safelog`" +error in `src/hs.rs`. Bump `safelog` in the same commit as the four crates above. Two crate features re-expose Arti's TLS backends, which Arti marks **non-additive** — exactly one may be selected per build graph: @@ -35,11 +35,11 @@ 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.48 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. ## Toolchain floor @@ -85,22 +85,16 @@ issue the watcher files. 1. Read the upstream release notes (Arti tags: ) 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 diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 14ac1e1..a4821b4 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -341,7 +341,7 @@ the app does not pick a public remote node for them. bundled `arti` **binary** run as a child (`arti proxy -p `) — 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 proxy -p` binds `127.0.0.1`/`::1`; arti 2.9.0 / `tor-config` 0.49 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 diff --git a/docs/VERIFY.md b/docs/VERIFY.md index d2f2c4e..ea1e57e 100644 --- a/docs/VERIFY.md +++ b/docs/VERIFY.md @@ -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 diff --git a/docs/WALLET.md b/docs/WALLET.md index 3f6fdb4..1c8163b 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -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. diff --git a/fuzz/fuzz_targets/ratchet_frame.rs b/fuzz/fuzz_targets/ratchet_frame.rs index 9d7f50f..9361768 100644 --- a/fuzz/fuzz_targets/ratchet_frame.rs +++ b/fuzz/fuzz_targets/ratchet_frame.rs @@ -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> = 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); }); diff --git a/src/node.rs b/src/node.rs index 340ab7a..86b6412 100644 --- a/src/node.rs +++ b/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 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:secret@127.0.0.1:{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:secret@127.0.0.1:{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 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:secret@127.0.0.1:{port}")).expect("wallet url"); - let daemon = mock_daemon(height, target).await; - (wallet, daemon) + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{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, 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 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:secret@127.0.0.1:{port}")).expect("wallet url"); - let daemon = mock_daemon(target, target).await; - (wallet, daemon) + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{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