Merge branch 'main' into wt/t_14ac0a3f
Some checks failed
ci / test (pull_request) Successful in 5m56s
android-ci / android (pull_request) Has been cancelled
ci / sdk (pull_request) Successful in 1m30s
ci / fuzz (pull_request) Has been cancelled

This commit is contained in:
sirius 2026-09-21 15:10:10 +00:00
commit 49756d2a2d
11 changed files with 1013 additions and 19 deletions

View file

@ -1,6 +1,8 @@
package com.siriusdevops.onionwire
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import androidx.core.app.NotificationManagerCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
@ -11,6 +13,8 @@ import com.siriusdevops.onionwire.crypto.StoredPassphraseStore
import com.siriusdevops.onionwire.keepalive.KeepAliveService
import com.siriusdevops.onionwire.keepalive.KeepAliveStatus
import com.siriusdevops.onionwire.keepalive.NodeHost
import com.siriusdevops.onionwire.ui.SeedBackupGate
import com.siriusdevops.onionwire.ui.WalletKeyOrigin
import com.siriusdevops.onionwire.wallet.ChainStorage
import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE
import com.siriusdevops.onionwire.wallet.WalletChildBinaries
@ -588,11 +592,32 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
suspend fun sendTip(pubkeyHex: String, amountXmr: String, memo: String = ""): Result<Unit> =
runCatching { requireWire().sendTip(pubkeyHex, amountXmr, memo) }
/**
* Create a wallet and read its seed once. The seed-backup flag is reset
* here, not by the screen: every successful create is a new seed nobody has
* read, and a caller that forgot to reset it would leave a spend key
* unrecoverable. See [SeedBackupGate.afterWallet].
*/
suspend fun createWallet(password: String): Result<String> =
runCatching { requireWire().createWallet(password) }
.onSuccess { setWalletSeedConfirmed(SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) }
/**
* Import a wallet from a user-supplied seed. That seed is already on paper —
* the user just pasted it — so the wallet counts as backed up without the
* confirm step.
*/
suspend fun importWallet(password: String, seed: String): Result<Unit> =
runCatching { requireWire().importWallet(password, seed) }
.onSuccess { setWalletSeedConfirmed(SeedBackupGate.afterWallet(WalletKeyOrigin.Imported)) }
/**
* Re-read the open wallet's 25-word seed, for the "Back up seed" recovery
* path. A spend key: only ever called from that explicit user action, shown
* on the blocking card, and dropped. Never logged and never persisted.
*/
suspend fun walletSeed(): Result<String> =
runCatching { requireWire().walletSeed() }
fun spendAuthorityWarning(): String = runCatching {
requireWire().spendAuthorityWarning()
@ -600,6 +625,47 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
"this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed."
}
// --- Seed backup gate --------------------------------------------------
// Whether the open wallet's seed has been confirmed written down. This is
// NOT a secret — it is a boolean in app-local prefs, deliberately kept out
// of the Keystore-wrapped store under `filesDir/secrets`, which holds the
// passphrase and nothing else.
//
// The flow is nullable, and the null is load-bearing: nothing stored means
// "this install has never created or imported a wallet through this build",
// which is not the same as "the user created one and has not confirmed it".
// See [SeedBackupGate.warningVisible] for why the screen needs both.
private val seedBackupPrefs: SharedPreferences =
app.getSharedPreferences(SEED_BACKUP_PREFS, Context.MODE_PRIVATE)
private val _walletSeedConfirmed = MutableStateFlow(
if (seedBackupPrefs.contains(SEED_BACKED_UP_KEY)) {
seedBackupPrefs.getBoolean(SEED_BACKED_UP_KEY, false)
} else {
null
},
)
/**
* The stored seed-backup flag: `false` unconfirmed, `true` confirmed or
* imported, `null` nothing stored (an install that predates the flag).
*/
val walletSeedConfirmed: StateFlow<Boolean?> = _walletSeedConfirmed.asStateFlow()
/**
* One confirm step from the blocking seed card. The gate decides: a wrong
* word leaves the flag where it was, so this can never un-confirm a wallet.
*/
fun confirmWalletSeed(typed: String) {
setWalletSeedConfirmed(SeedBackupGate.afterConfirm(typed, _walletSeedConfirmed.value == true))
}
private fun setWalletSeedConfirmed(confirmed: Boolean) {
seedBackupPrefs.edit().putBoolean(SEED_BACKED_UP_KEY, confirmed).apply()
_walletSeedConfirmed.value = confirmed
}
// --- App-owned wallet child (issue #107) -------------------------------
// The app owns `monero-wallet-rpc` instead of asking the user to start one
// and export `ONIONWIRE_WALLET_RPC`. The core's own states are surfaced
@ -920,3 +986,13 @@ suspend fun walletChildRefreshLoop(
/** Cadence of the wallet-child refresh loop, in milliseconds. */
private const val WALLET_CHILD_TICK_MS: Long = 2_000
/**
* App-local prefs file for the seed-backup flag. Not a secret, so it is a plain
* prefs file rather than anything under `filesDir/secrets`.
*/
private const val SEED_BACKUP_PREFS: String = "wallet_seed_backup"
/** Key inside [SEED_BACKUP_PREFS]: has the open wallet's seed been written down? */
private const val SEED_BACKED_UP_KEY: String = "backed_up"

View file

@ -0,0 +1,113 @@
package com.siriusdevops.onionwire.ui
/**
* Where the open wallet's key material came from.
*
* The distinction is the whole gate. A seed the user *supplied* (import) is a
* seed the user already has on paper, so that wallet is backed up from the
* start. A seed the app *generated* (create) has been read by nobody until it
* is put on screen, so that wallet starts unbacked and stays unbacked until the
* user proves it is written down.
*/
enum class WalletKeyOrigin {
Created,
Imported,
}
/**
* The seed-backup gate: every decision the wallet screen makes about an
* unconfirmed seed, as pure Kotlin — no Compose, no Android, no prefs — so the
* rules are covered by `SeedBackupGateTest` on the JVM without a device.
*
* The gate exists because a seed shown once and then lost is an unrecoverable
* wallet: XMR received into a wallet whose 25 words were never written down
* cannot be spent or recovered by anyone, including this app. So the answer is
* not advisory — while it says the seed is unbacked, the wallet screen keeps a
* warning up and hides the receive address and its QR.
*
* The confirm word and its case-insensitivity mirror the TUI's own seed screen
* (`src/tui.rs`, `WalletSetup::CreateSeed`, which compares with
* `eq_ignore_ascii_case("SEEN")`) instead of inventing a second convention for
* the same wallet.
*/
object SeedBackupGate {
/** The word that releases the block. The TUI's word, not a new one. */
const val CONFIRM_WORD: String = "SEEN"
/**
* True when [typed] releases the block.
*
* Trimmed and case-insensitive, so a soft keyboard's auto-capitalised `Seen`
* and a trailing space from a paste both count. Everything else — including
* the empty string — stays blocked.
*/
fun accepts(typed: String): Boolean =
typed.trim().equals(CONFIRM_WORD, ignoreCase = true)
/**
* The flag right after a wallet is created or imported.
*
* A create always resets it: the wallet file is new, and the seed it was
* built from has never been read by anyone.
*/
fun afterWallet(origin: WalletKeyOrigin): Boolean = when (origin) {
WalletKeyOrigin.Created -> false
WalletKeyOrigin.Imported -> true
}
/**
* The flag after one confirm step.
*
* Only a correct [typed] can flip it to `true`; a wrong word can never
* un-confirm a wallet that is already backed up.
*/
fun afterConfirm(typed: String, backedUp: Boolean): Boolean =
backedUp || accepts(typed)
/** Done is dead until the word is right. */
fun confirmEnabled(typed: String): Boolean = accepts(typed)
/**
* The persistent strip is up while this install has an unconfirmed seed.
*
* [confirmed] is the stored flag, and it is nullable on purpose:
*
* - `false` — this install created a wallet and nobody has confirmed the
* seed. The wallet exists whether or not its balance reads, so the strip
* is up regardless.
* - `true` — confirmed, or imported. Nothing to say.
* - `null` — nothing stored: an install that predates this flag, or one
* that has never created or imported a wallet here. "We never asked" is
* not "the user wrote it down", but it is also not evidence that a wallet
* exists — so the strip waits for [walletReadable], the core's own proof
* that the child has a wallet open.
*
* Without that last distinction the strip would fire on every install that
* has configured a chain source but not yet created a wallet, which is
* exactly the state a first-run user is in.
*/
fun warningVisible(confirmed: Boolean?, walletReadable: Boolean): Boolean = when (confirmed) {
true -> false
false -> true
null -> walletReadable
}
/**
* The receive address and its QR are shown only while there is no unbacked
* seed to worry about. Receiving into an unbacked wallet is the one mistake
* this gate exists to prevent, so the address is hidden rather than merely
* warned about.
*/
fun receiveAddressVisible(confirmed: Boolean?, walletReadable: Boolean): Boolean =
!warningVisible(confirmed, walletReadable)
/**
* The strip's words. One source: the screen renders this verbatim, so the
* reason the address disappeared travels with the hiding.
*/
const val WARNING: String =
"seed not backed up. write down the 25 words before you receive anything — " +
"a wallet whose seed was never written down cannot be recovered. " +
"the receive address stays hidden until you do."
}

View file

@ -76,6 +76,7 @@ fun WalletScreen(
val childError by vm.walletChildError.collectAsStateWithLifecycle()
val starting by vm.walletChildStarting.collectAsStateWithLifecycle()
val chain by vm.chainSource.collectAsStateWithLifecycle()
val seedConfirmed by vm.walletSeedConfirmed.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
// Resolved once per composition: the native library directory is fixed for
// the life of the process.
@ -92,7 +93,11 @@ fun WalletScreen(
var error by remember { mutableStateOf<String?>(null) }
var composer by remember { mutableStateOf<PayKind?>(null) }
var setup by remember { mutableStateOf<SetupKind?>(null) }
var backupSeed by remember { mutableStateOf<String?>(null) }
// The seed currently on the blocking card: set by a successful create, or by
// "Back up seed" re-reading it from the wallet child. Null means no card.
// Never persisted and never logged — it is a spend key.
var pendingSeed by remember { mutableStateOf<String?>(null) }
var seedConfirm by remember { mutableStateOf("") }
var daemonText by remember { mutableStateOf("") }
var daemonError by remember { mutableStateOf<String?>(null) }
@ -103,6 +108,26 @@ fun WalletScreen(
runCatching { transfers = vm.walletRecentTransfers(25) }
}
/**
* "Back up seed": re-read the open wallet's seed from the wallet child and
* put it on the blocking card. This is the only path to a seed that was
* created before this screen existed, so the failure is shown rather than
* swallowed — it is the difference between "the child is not running" and
* "there is nothing to recover".
*/
fun openSeedBackup() {
scope.launch {
error = null
vm.walletSeed().fold(
onSuccess = { seed ->
pendingSeed = seed
seedConfirm = ""
},
onFailure = { error = it.message ?: it.toString() },
)
}
}
LaunchedEffect(Unit) {
reload()
vm.refreshChainSource()
@ -151,6 +176,46 @@ fun WalletScreen(
.screenContentInsets()
.verticalScroll(rememberScrollState()),
) {
// The blocking seed step. While a seed is on screen this card is the
// whole body: no Cancel, and Done stays dead until the confirm word
// is typed, so the one-shot seed cannot be dismissed unread. The
// app-bar Back still leaves the screen — that is the TUI's `Esc` —
// and it costs nothing now, because leaving no longer loses the
// seed: the wallet stays unbacked (strip up, receive address hidden)
// until "Back up seed" puts this card back on screen.
val seed = pendingSeed
if (seed != null) {
SeedBackupCard(
seed = seed,
typed = seedConfirm,
onTyped = { seedConfirm = it },
onDone = {
// The gate owns the transition: a wrong word (which the
// disabled Done button already blocks) cannot confirm.
vm.confirmWalletSeed(seedConfirm)
pendingSeed = null
seedConfirm = ""
},
)
error?.let { ErrorLine(it) }
return@Column
}
// The persistent unbacked strip, above everything else on the page.
// `walletReadable` is the core's own evidence that the child has a
// wallet open: `wallet_balance` returns exactly "off" for a chain
// source that was never configured, "err" for a configured one whose
// read failed (no wallet file open yet, or the child is down), and a
// real amount otherwise. The gate uses it only for an install that
// has never created a wallet here, so a first-run user who has
// configured a daemon but not yet created anything is not nagged
// about a seed they do not have.
val walletReadable = balance != null && balance != "off" && balance != "err"
val unbacked = SeedBackupGate.warningVisible(seedConfirmed, walletReadable)
if (unbacked) {
UnbackedSeedCard(error = error, onBackUpSeed = { openSeedBackup() })
}
Card(
modifier = Modifier
.fillMaxWidth()
@ -173,7 +238,12 @@ fun WalletScreen(
style = MaterialTheme.typography.headlineSmall,
fontFamily = FontFamily.Monospace,
)
val addr = address
// Hidden until the seed is confirmed written down: XMR into a
// wallet whose 25 words were never recorded is unrecoverable,
// so the address and its QR are gated, not just warned about.
val addr = address?.takeIf {
SeedBackupGate.receiveAddressVisible(seedConfirmed, walletReadable)
}
if (addr != null) {
Spacer(Modifier.height(8.dp))
Text(
@ -333,7 +403,9 @@ fun WalletScreen(
onCancel = { setup = null },
onCreated = { seed ->
setup = null
backupSeed = seed
// The card is the whole body from here until SEEN.
pendingSeed = seed
seedConfirm = ""
scope.launch { reload() }
},
onImported = {
@ -374,36 +446,170 @@ fun WalletScreen(
modifier = Modifier.weight(1f),
) { Text("Import") }
}
// The recovery path for a wallet whose seed was missed. The
// strip above carries its own copy of this button while the
// seed is unconfirmed, so exactly one is ever on screen —
// and this copy is only offered once the child can actually
// read a wallet, which is the only state in which the seed
// read can succeed.
if (walletReadable && !SeedBackupGate.warningVisible(seedConfirmed, walletReadable)) {
Spacer(Modifier.height(8.dp))
OutlinedButton(
onClick = { openSeedBackup() },
modifier = Modifier
.fillMaxWidth()
.testTag("wallet-seed-backup-action"),
) { Text("Back up seed") }
}
}
}
backupSeed?.let { seed ->
Text(
"write this seed down once. anyone with it can spend.",
style = MaterialTheme.typography.labelSmall,
modifier = Modifier.padding(horizontal = 12.dp),
)
Text(
seed,
style = MaterialTheme.typography.bodySmall,
fontFamily = FontFamily.Monospace,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
)
TextButton(onClick = { backupSeed = null }) { Text("I wrote it down") }
// While the strip is up the error belongs next to the button that
// caused it: this page is one long scroll and the daemon card sits
// between the strip and the bottom, so a failed `wallet_seed` read
// would otherwise land off-screen.
if (!unbacked) {
error?.let { ErrorLine(it) }
}
}
}
}
/** The one error line every wallet action shares. */
@Composable
private fun ErrorLine(text: String) {
Text(
text,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
)
}
/**
* The persistent unbacked strip: up at the top of the wallet screen from the
* moment a create succeeds until the seed is confirmed written down, and again
* on any install whose wallet predates the flag.
*
* It is not a toast and not a dialog — leaving the screen does not dismiss it,
* because the state it reports is the wallet's, not the screen's. Its button is
* the recovery path for a seed that was created before the user knew to look.
*/
@Composable
private fun UnbackedSeedCard(
error: String?,
onBackUpSeed: () -> Unit,
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 8.dp)
.testTag("wallet-seed-warning"),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer,
),
) {
Column(Modifier.padding(12.dp)) {
Text(
SeedBackupGate.WARNING,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer,
)
Spacer(Modifier.height(8.dp))
OutlinedButton(
onClick = onBackUpSeed,
modifier = Modifier
.fillMaxWidth()
.testTag("wallet-seed-backup-action"),
) { Text("Back up seed") }
error?.let {
Spacer(Modifier.height(6.dp))
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
)
}
}
}
}
/**
* The blocking seed step: the 25 words, and a Done that is dead until the
* confirm word is typed.
*
* There is no Cancel and no copy button. No Cancel, because a seed this card is
* showing for the first time has never been written down anywhere else, so
* dismissing it unread is how a wallet becomes unrecoverable. No copy button,
* because the Android clipboard is readable by every other app on the device
* (and by the clipboard history on Android 13+), which would hand the spend key
* to whoever asks for it next.
*
* The seed is a Kotlin `String`, so it cannot be wiped in place the way the
* TUI's `Zeroizing<String>` is; dropping the reference is the strongest thing
* available here. That is another reason it is never written to disk.
*/
@Composable
private fun SeedBackupCard(
seed: String,
typed: String,
onTyped: (String) -> Unit,
onDone: () -> Unit,
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp)
.testTag("wallet-seed-card"),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
),
) {
Column(Modifier.padding(12.dp)) {
Text("Back up this seed", style = MaterialTheme.typography.titleSmall)
Spacer(Modifier.height(8.dp))
Text(
"These 25 words are the only way to recover this wallet, and anyone who " +
"reads them can spend it. Write them down now — this is the only copy.",
style = MaterialTheme.typography.bodySmall,
)
Spacer(Modifier.height(8.dp))
Text(
seed,
style = MaterialTheme.typography.bodyMedium,
fontFamily = FontFamily.Monospace,
modifier = Modifier
.fillMaxWidth()
.testTag("wallet-seed-words"),
)
Spacer(Modifier.height(12.dp))
Text(
"Type ${SeedBackupGate.CONFIRM_WORD} to confirm you have written it down.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(4.dp))
OutlinedTextField(
value = typed,
onValueChange = onTyped,
singleLine = true,
label = { Text("type ${SeedBackupGate.CONFIRM_WORD}") },
modifier = Modifier
.fillMaxWidth()
.testTag("wallet-seed-confirm-input"),
)
Spacer(Modifier.height(8.dp))
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
Button(
onClick = onDone,
enabled = SeedBackupGate.confirmEnabled(typed),
modifier = Modifier.testTag("wallet-seed-confirm-done"),
) { Text("Done") }
}
}
}
}
@Composable
private fun TransferCard(t: TransferRow) {
Card(

View file

@ -0,0 +1,176 @@
package com.siriusdevops.onionwire.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The seed-backup gate's rules, on the JVM.
*
* These are the decisions the wallet screen renders from: whether the created
* seed card is still blocking, whether the persistent warning is up, and
* whether the receive address is on screen at all. Pure logic, so no
* Robolectric and no Compose test dependency — same shape as
* `WalletChildStatusTextTest` and `OutboxDetailTest`.
*/
class SeedBackupGateTest {
/** A wallet the child can actually read: `wallet_balance` returned a value. */
private val readable = true
/** `wallet_balance` said "off" (no chain source) or "err" (nothing open). */
private val notReadable = false
// --- the confirm word is the TUI's word ---------------------------------
@Test
fun the_confirm_word_is_the_tui_word() {
// `src/tui.rs` `WalletSetup::CreateSeed` compares against "SEEN". A
// second convention here would be a different gate than the TUI's.
assertEquals("SEEN", SeedBackupGate.CONFIRM_WORD)
}
@Test
fun a_correct_word_releases_the_block_whatever_its_case_or_padding() {
assertTrue(SeedBackupGate.accepts("SEEN"))
// The TUI compares with `eq_ignore_ascii_case`.
assertTrue(SeedBackupGate.accepts("seen"))
assertTrue(SeedBackupGate.accepts("SeEn"))
// A soft keyboard auto-capitalises and a paste can carry whitespace.
assertTrue(SeedBackupGate.accepts(" seen "))
}
@Test
fun a_blank_or_wrong_word_stays_blocked() {
assertFalse(SeedBackupGate.accepts(""))
assertFalse(SeedBackupGate.accepts(" "))
assertFalse(SeedBackupGate.accepts("SEE"))
// A prefix is not the word: the TUI only fires on the whole match.
assertFalse(SeedBackupGate.accepts("SEENN"))
assertFalse(SeedBackupGate.accepts("seen."))
// The other word in this flow is the spend-authority one.
assertFalse(SeedBackupGate.accepts("SPEND"))
}
@Test
fun done_is_dead_until_the_word_is_right() {
assertFalse(SeedBackupGate.confirmEnabled(""))
assertFalse(SeedBackupGate.confirmEnabled("SEENN"))
assertTrue(SeedBackupGate.confirmEnabled("SEEN"))
assertTrue(SeedBackupGate.confirmEnabled("seen"))
}
// --- the state transitions ----------------------------------------------
@Test
fun a_create_starts_unbacked() {
assertFalse(SeedBackupGate.afterWallet(WalletKeyOrigin.Created))
}
@Test
fun an_import_is_backed_up_without_the_gate() {
// The user pasted the seed to get here, so there is nothing to confirm.
assertTrue(SeedBackupGate.afterWallet(WalletKeyOrigin.Imported))
}
@Test
fun a_successful_confirm_marks_the_wallet_backed_up() {
val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created)
assertTrue(SeedBackupGate.afterConfirm("SEEN", created))
}
@Test
fun a_wrong_word_leaves_an_unbacked_wallet_unbacked() {
assertFalse(SeedBackupGate.afterConfirm("", false))
assertFalse(SeedBackupGate.afterConfirm("nope", false))
}
@Test
fun a_wrong_word_cannot_un_confirm_a_backed_up_wallet() {
// Done is disabled for a wrong word, but the flag must not be a way to
// walk a confirmed wallet back into the hidden-address state.
assertTrue(SeedBackupGate.afterConfirm("", true))
assertTrue(SeedBackupGate.afterConfirm("SPEND", true))
}
@Test
fun a_new_create_resets_a_confirmed_wallet_to_unbacked() {
// Create -> confirm -> create again: the second wallet file has its own
// seed, and nobody has read it yet.
val first =
SeedBackupGate.afterConfirm("SEEN", SeedBackupGate.afterWallet(WalletKeyOrigin.Created))
assertTrue(first)
assertFalse(SeedBackupGate.afterWallet(WalletKeyOrigin.Created))
}
// --- what the screen does with the flag ---------------------------------
@Test
fun a_created_wallet_keeps_the_strip_up_until_the_word_is_typed() {
val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created)
assertTrue(SeedBackupGate.warningVisible(created, readable))
val confirmed = SeedBackupGate.afterConfirm("seen", created)
assertFalse(SeedBackupGate.warningVisible(confirmed, readable))
}
@Test
fun an_imported_wallet_never_shows_the_strip() {
val backedUp = SeedBackupGate.afterWallet(WalletKeyOrigin.Imported)
assertFalse(SeedBackupGate.warningVisible(backedUp, readable))
assertFalse(SeedBackupGate.warningVisible(backedUp, notReadable))
}
@Test
fun a_created_wallet_keeps_the_strip_up_even_before_its_balance_reads() {
// A create is proof a wallet exists, so a child that has not answered
// yet must not be read as "no wallet to warn about".
assertTrue(SeedBackupGate.warningVisible(false, notReadable))
}
@Test
fun the_receive_address_is_hidden_while_the_seed_is_unconfirmed() {
assertFalse(SeedBackupGate.receiveAddressVisible(false, readable))
assertTrue(SeedBackupGate.receiveAddressVisible(true, readable))
}
@Test
fun a_created_wallet_hides_its_receive_address_until_the_word_is_typed() {
val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created)
assertFalse(SeedBackupGate.receiveAddressVisible(created, readable))
val confirmed = SeedBackupGate.afterConfirm("seen", created)
assertTrue(SeedBackupGate.receiveAddressVisible(confirmed, readable))
}
@Test
fun an_install_that_never_created_a_wallet_here_waits_for_a_readable_wallet() {
// `null` is "nothing stored": an install that predates the flag, or one
// that has only configured a chain source. `wallet_balance` returns
// "err" for a configured chain whose child has no wallet open, and a
// first-run user is in exactly that state — nagging them about a seed
// they do not have is the false positive this rule exists to prevent.
assertFalse(SeedBackupGate.warningVisible(null, notReadable))
assertTrue(SeedBackupGate.receiveAddressVisible(null, notReadable))
}
@Test
fun an_unconfirmed_wallet_that_predates_the_flag_is_warned_about_once_it_reads() {
// The user this gate is for: they created a wallet on an older build,
// so nothing is stored, but the child can read the wallet. That is a
// real wallet whose seed nobody has confirmed.
assertTrue(SeedBackupGate.warningVisible(null, readable))
assertFalse(SeedBackupGate.receiveAddressVisible(null, readable))
}
@Test
fun the_strip_says_why_the_address_is_gone() {
// The hiding is only fair if the strip names it; assert the strip is
// not empty and actually mentions the seed and the receive address.
val text = SeedBackupGate.WARNING
assertTrue(text.contains("seed"))
assertTrue(text.contains("receive address"))
assertTrue(text.contains("recovered"))
}
}

View file

@ -594,6 +594,17 @@ impl Wire {
.map_err(WireError::new)
}
/// Re-read this wallet's 25-word seed so the UI can offer a "back up seed"
/// action after creation. Dials the wallet child's RPC (`query_key
/// mnemonic`), so it is cheap but not free, and it needs a wallet the child
/// has open. The result is a spend key: call this only from an explicit
/// user action, show it, and do not persist or log it.
///
/// The Kotlin binding is `Wire.walletSeed()`.
pub async fn wallet_seed(&self) -> WResult<String> {
self.node()?.wallet_seed().await.map_err(WireError::new)
}
/// Import a wallet from an existing 25-word seed. This is the only path
/// that takes a user-supplied secret.
pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> {

View file

@ -20,6 +20,6 @@ pub mod wallet;
pub mod wallet_child;
pub use store::{
Friend, FriendProfile, Message, Payment, PaymentWrite, SelfIdentity, Store,
resolve_store_passphrase,
Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, SelfIdentity, Store,
WalletRecord, resolve_store_passphrase,
};

View file

@ -1179,6 +1179,18 @@ impl Node {
.map_err(|e| e.to_string())
}
/// Re-read the seed of the wallet file the child has open. `create_wallet`
/// returns it once; after that this is the only path to it. The seed is a
/// spend key, so the caller must only show it on an explicit user action
/// and must not log or store it.
pub async fn wallet_seed(&self) -> Result<String, String> {
let w = self.wallet_snapshot();
if !w.configured() {
return Err(wallet::NOT_CONFIGURED_MSG.into());
}
w.mnemonic().await.map_err(|e| e.to_string())
}
/// Import a wallet from an existing 25-word seed. This is the only path
/// that takes a user-supplied secret.
pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> {

View file

@ -177,6 +177,34 @@ pub struct PaymentWrite<'a> {
pub verified: bool,
}
/// Fields the caller supplies to add a wallet to the catalogue. `id` and
/// `created_at` are assigned by the store, never by the caller.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewWallet {
/// Optional user label. Blank (or whitespace) is stored as SQL NULL.
pub name: Option<String>,
/// The identity this wallet belongs to. Identity is the pubkey, so several
/// wallets may share one — this column is deliberately not unique.
pub identity_pubkey: [u8; 32],
/// The onion locator current at creation. A locator, not an identity: it
/// rotates (F4) and is allowed to be empty before the HS publishes.
pub onion_locator: String,
/// The wallet file name under the wallet dir. Unique: a second wallet must
/// get its own file rather than overwrite the first one's.
pub wallet_filename: String,
}
/// One wallet in the catalogue: the row that makes a wallet survive a restart.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalletRecord {
pub id: i64,
pub name: Option<String>,
pub identity_pubkey: [u8; 32],
pub onion_locator: String,
pub wallet_filename: String,
pub created_at: i64,
}
impl Store {
pub fn open() -> Result<Self> {
Self::open_at(&home_dir()?)
@ -275,6 +303,21 @@ impl Store {
no_spend INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
-- The wallet catalogue: one row per wallet file this install knows
-- about, so a created wallet is remembered across restarts (the
-- wallet child's own config only describes the one it is pointed at
-- right now). `identity_pubkey` is the owning identity and is NOT
-- unique — identity is the roster key, while a wallet is one file;
-- `onion_locator` is a locator and may be stale or empty.
CREATE TABLE IF NOT EXISTS wallets (
id INTEGER PRIMARY KEY,
name TEXT,
identity_pubkey BLOB NOT NULL,
onion_locator TEXT NOT NULL DEFAULT '',
wallet_filename TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS wallets_by_created ON wallets (created_at, id);
CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY,
friend_id INTEGER NOT NULL REFERENCES friends(id),
@ -418,6 +461,93 @@ impl Store {
}))
}
/// Add a wallet to the catalogue and return the stored row (id and
/// `created_at` assigned here). This is the only way a wallet becomes
/// remembered: the wallet file on disk is not a directory listing the app
/// scans.
///
/// `wallet_filename` is unique. Creating a second wallet is not a rewrite of
/// the first — it must be handed its own file name, otherwise both wallets
/// would open the same file and the second would look like a failed create.
pub fn create_wallet(&self, w: &NewWallet) -> Result<WalletRecord> {
let filename = w.wallet_filename.trim();
if filename.is_empty() {
return Err(Error("wallet filename required".into()));
}
let name = w.name.as_deref().map(str::trim).filter(|n| !n.is_empty());
let taken: Option<i64> = self
.conn
.query_row(
"SELECT id FROM wallets WHERE wallet_filename = ?1",
params![filename],
|row| row.get(0),
)
.optional()?;
if let Some(id) = taken {
return Err(Error(format!(
"wallet filename already in use: {filename} (wallet {id})"
)));
}
let created_at = unix_now();
self.conn.execute(
"INSERT INTO wallets (name, identity_pubkey, onion_locator, wallet_filename, created_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![
name,
w.identity_pubkey.as_slice(),
w.onion_locator,
filename,
created_at
],
)?;
Ok(WalletRecord {
id: self.conn.last_insert_rowid(),
name: name.map(str::to_string),
identity_pubkey: w.identity_pubkey,
onion_locator: w.onion_locator.clone(),
wallet_filename: filename.to_string(),
created_at,
})
}
/// One wallet by row id, or `None` when there is no such wallet.
pub fn get_wallet_by_id(&self, id: i64) -> Result<Option<WalletRecord>> {
Ok(self
.conn
.query_row(
"SELECT id, name, identity_pubkey, onion_locator, wallet_filename, created_at
FROM wallets WHERE id = ?1",
params![id],
wallet_row,
)
.optional()?)
}
/// Every known wallet, oldest first (row id breaks a `created_at` tie, so
/// the order a wallet-selection screen shows is stable across runs).
pub fn list_wallets(&self) -> Result<Vec<WalletRecord>> {
let mut stmt = self.conn.prepare(
"SELECT id, name, identity_pubkey, onion_locator, wallet_filename, created_at
FROM wallets ORDER BY created_at, id",
)?;
let rows = stmt
.query_map([], wallet_row)?
.collect::<std::result::Result<Vec<_>, _>>()?;
Ok(rows)
}
/// Forget a wallet. `true` when a row was removed, `false` when there was
/// nothing to remove (an unknown id is not an error).
///
/// This drops the catalogue row only; the wallet file on disk and the
/// payments already recorded stay where they are.
pub fn delete_wallet(&self, id: i64) -> Result<bool> {
let removed = self
.conn
.execute("DELETE FROM wallets WHERE id = ?1", params![id])?;
Ok(removed > 0)
}
pub fn replace_identity_keys(
&self,
identity_sk: &[u8],
@ -1651,6 +1781,31 @@ fn unix_now() -> i64 {
.unwrap_or(0)
}
/// Read one `wallets` row. A pubkey column that is not exactly 32 bytes is a
/// corrupt row, not a value to guess at.
fn wallet_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<WalletRecord> {
let pubkey: Vec<u8> = row.get(2)?;
let len = pubkey.len();
let identity_pubkey: [u8; 32] = pubkey.try_into().map_err(|_| {
rusqlite::Error::FromSqlConversionFailure(
2,
rusqlite::types::Type::Blob,
Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("identity_pubkey is {len} bytes, expected 32"),
)),
)
})?;
Ok(WalletRecord {
id: row.get(0)?,
name: row.get(1)?,
identity_pubkey,
onion_locator: row.get(3)?,
wallet_filename: row.get(4)?,
created_at: row.get(5)?,
})
}
/// AAD for the sealed wallet-child row. Domain-separates it from message and
/// outbox blobs that share the same store data key.
const WALLET_CHILD_AAD: &[u8] = b"onionwire/wallet-child/v1";
@ -2308,4 +2463,33 @@ mod at_rest {
}
}
}
/// An install that predates the `wallets` table (the Android upgrade path)
/// gains it on the next open, and keeps everything else it had: the schema
/// is additive (`CREATE TABLE IF NOT EXISTS` on every open).
#[test]
fn a_store_without_the_wallets_table_gains_it_on_reopen() {
let dir = tempfile::tempdir().unwrap();
let wallet = crate::store::NewWallet {
name: Some("First".into()),
identity_pubkey: [9u8; 32],
onion_locator: "w.onion".into(),
wallet_filename: "onionwire".into(),
};
{
let store = Store::open_at_with_passphrase(dir.path(), "upgrade-pass").unwrap();
let row = store.create_wallet(&wallet).unwrap();
assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row);
// Simulate a pre-`wallets` install.
store.conn.execute_batch("DROP TABLE wallets").unwrap();
}
let store = Store::open_at_with_passphrase(dir.path(), "upgrade-pass").unwrap();
assert!(
store.list_wallets().unwrap().is_empty(),
"the dropped table comes back empty, not missing"
);
let row = store.create_wallet(&wallet).unwrap();
assert_eq!(store.list_wallets().unwrap().len(), 1);
assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row);
}
}

View file

@ -788,6 +788,25 @@ impl Wallet {
json_str(&v, "key")
}
/// Re-read the seed of the wallet file the RPC has open (`query_key
/// mnemonic`). After `create_wallet` this is the **only** way to recover a
/// created wallet's seed, so the UI can offer a backup action instead of
/// showing it once. It needs an open, spend-capable wallet file; a
/// watch-only one answers the RPC's `-29` and surfaces as the view-only
/// refusal.
///
/// The returned words are a spend key: never log them, never store them,
/// and never put them in an error string.
pub async fn mnemonic(&self) -> Result<String> {
if !self.configured() {
return Err(Error(NOT_CONFIGURED_MSG.into()));
}
let v = self
.rpc("query_key", serde_json::json!({"key_type": "mnemonic"}))
.await?;
json_str(&v, "key")
}
/// Import an existing wallet from its 25-word seed. This is the only path
/// that takes a user-supplied secret.
pub async fn restore_wallet(&self, filename: &str, password: &str, seed: &str) -> Result<()> {

View file

@ -540,3 +540,126 @@ fn ratchet_state_survives_reopening_the_store() {
assert_eq!(store.load_ratchet(&pk(1)).expect("load"), Some(blob));
assert_eq!(store.list_messages(&pk(1)).unwrap()[0].plaintext, b"hello");
}
// ---- the wallet catalogue (`wallets`) --------------------------------------
//
// Several wallet *files* live under one identity: the row here is what makes a
// wallet survive a restart, because the wallet child's own config only ever
// describes the one it is pointed at right now.
fn new_wallet(filename: &str, name: Option<&str>) -> onionwire::NewWallet {
onionwire::NewWallet {
name: name.map(str::to_string),
identity_pubkey: pk(7),
onion_locator: "walletloc.onion".to_string(),
wallet_filename: filename.to_string(),
}
}
#[test]
fn create_wallet_stores_every_field_and_reads_it_back() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open");
let row = store
.create_wallet(&new_wallet("savings", Some("Savings")))
.expect("create");
assert!(row.id > 0, "id assigned: {row:?}");
assert!(row.created_at > 0, "created_at stamped: {row:?}");
assert_eq!(row.wallet_filename, "savings");
assert_eq!(row.name.as_deref(), Some("Savings"));
assert_eq!(row.identity_pubkey, pk(7));
assert_eq!(row.onion_locator, "walletloc.onion");
let got = store
.get_wallet_by_id(row.id)
.expect("get")
.expect("row exists");
assert_eq!(got, row, "the stored row is what came back");
}
#[test]
fn multiple_wallets_coexist_and_survive_a_reopen() {
let dir = tempfile::tempdir().expect("tempdir");
let (spending, savings) = {
let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open");
let spending = store
.create_wallet(&new_wallet("spending", Some("Spending")))
.expect("spending");
let savings = store
.create_wallet(&new_wallet("savings", None))
.expect("savings");
assert_ne!(spending.id, savings.id, "two wallets, two rows");
(spending.id, savings.id)
};
let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("reopen");
let rows = store.list_wallets().expect("list");
assert_eq!(rows.len(), 2, "both wallets remembered: {rows:?}");
assert_eq!(rows[0].id, spending, "creation order");
assert_eq!(rows[1].id, savings);
assert_eq!(
rows[1].name, None,
"an unlabelled wallet round-trips as None"
);
assert_eq!(rows[1].wallet_filename, "savings");
}
#[test]
fn a_second_wallet_cannot_reuse_a_wallet_filename() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open");
let first = store
.create_wallet(&new_wallet("onionwire", None))
.expect("first");
let err = store
.create_wallet(&new_wallet("onionwire", Some("Clash")))
.expect_err("a duplicate filename must not overwrite the first wallet");
assert!(
err.to_string().contains("onionwire"),
"names the file: {err}"
);
let rows = store.list_wallets().expect("list");
assert_eq!(rows.len(), 1, "the rejected insert left one row: {rows:?}");
assert_eq!(rows[0], first, "the first wallet is untouched");
}
#[test]
fn delete_wallet_removes_only_that_row() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open");
let a = store.create_wallet(&new_wallet("a", None)).expect("a");
let b = store.create_wallet(&new_wallet("b", None)).expect("b");
assert!(store.delete_wallet(a.id).expect("delete"), "row was there");
assert_eq!(store.get_wallet_by_id(a.id).expect("get"), None);
let rows = store.list_wallets().expect("list");
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].id, b.id);
assert!(
!store
.delete_wallet(9999)
.expect("unknown id is not an error"),
"nothing to delete reports false"
);
}
#[test]
fn a_wallet_without_a_label_or_locator_stores_nulls_and_rejects_a_blank_filename() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open");
let mut blank = new_wallet("blank", Some(" "));
blank.onion_locator = String::new();
let row = store.create_wallet(&blank).expect("blank label");
assert_eq!(row.name, None, "a whitespace label is no label");
assert_eq!(row.onion_locator, "", "a locator may be empty pre-publish");
let err = store
.create_wallet(&new_wallet(" ", None))
.expect_err("an empty filename cannot name a wallet file");
assert!(err.to_string().contains("filename"), "{err}");
}

View file

@ -819,6 +819,80 @@ async fn mock_digest_auth_accepted() {
assert!(got.starts_with('4'), "got {got}");
}
/// The seed is a spend key: `mnemonic` must be one `query_key mnemonic` call
/// and nothing else, so the caller sees exactly what the open wallet answers.
#[tokio::test]
async fn mnemonic_returns_the_words_the_rpc_answers() {
const WORDS: &str = "one two three four five six seven eight nine ten eleven twelve \
thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty twentyone \
twentytwo twentythree twentyfour twentyfive";
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_rpc_conns(
listener,
Arc::new(|method: &str| match method {
"query_key" => rpc_result(&format!(r#"{{"key":"{WORDS}"}}"#)),
other => panic!("mnemonic must make one query_key call, saw {other}"),
}),
None,
None,
));
let got = recording_wallet(port).mnemonic().await.expect("mnemonic");
assert_eq!(got, WORDS);
}
/// A wallet with no open file answers a JSON-RPC error. It must surface as the
/// wallet's error, and the RPC login from the URL must not ride along with it.
#[tokio::test]
async fn mnemonic_surfaces_an_rpc_error_without_leaking_the_login() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_rpc_conns(
listener,
Arc::new(|_: &str| rpc_error(-1, "wallet file is not open")),
None,
None,
));
let err = recording_wallet(port).mnemonic().await.unwrap_err();
let msg = err.to_string();
assert!(msg.contains("wallet file is not open"), "got {err}");
assert!(!msg.contains("secret"), "password leaked: {err}");
assert!(!msg.contains("http://"), "endpoint leaked: {err}");
}
/// The refused-digest refusal names the login in prose ("the login does not
/// match"), which is exactly the copy that must not carry the credential.
#[tokio::test]
async fn mnemonic_refuses_a_rejected_digest_without_leaking_the_login() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_rpc_conns_with(
listener,
Arc::new(|_: &str| "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n".to_string()),
None,
None,
true,
));
let err = recording_wallet(port).mnemonic().await.unwrap_err();
let msg = err.to_string();
assert!(msg.contains("digest rejected"), "got {err}");
assert!(!msg.contains("secret"), "password leaked: {err}");
}
/// No endpoint, no dial: the refusal is the configured-guard copy the rest of
/// the wallet uses, not a connection error.
#[test]
fn mnemonic_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() {
let w = Wallet::disabled();
let err = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(w.mnemonic())
.unwrap_err();
assert_eq!(err.to_string(), NOT_CONFIGURED_MSG);
}
/// Answers the Digest challenge, then holds the reply for `delay`. Lets a test
/// prove which call classes get which budget.
async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) {