All checks were successful
android-ci / android (pull_request) Successful in 10m35s
A created wallet's seed was two lines of small text at the bottom of the wallet page, dismissed by one tap, gone for good once the screen was left. A real user created a wallet, never saw the seed, and the app had no way to show it again. - `SeedBackupGate` (new, pure Kotlin): the confirm word `SEEN` and its case-insensitive match mirror the TUI's own `WalletSetup::CreateSeed` gate; create starts unbacked, import is backed up without the gate, and only a correct word can confirm. - The seed card is the whole body until the word is typed and Done is tapped: no Cancel, no copy button (the Android clipboard is readable by every other app), Done dead until `SEEN`. - "Back up seed" re-reads the seed through the new `Wire::wallet_seed()` (`WireViewModel.walletSeed()`), so a seed missed the first time is not lost. Its failure is shown next to the button, not at the bottom of a long scroll. - While unconfirmed: a warning strip stays at the top of the wallet screen and the receive address and Show QR are hidden — XMR received into a wallet whose 25 words were never written down is unrecoverable. - The flag lives in app-local prefs (`wallet_seed_backup`), not in the Keystore-wrapped store, and is reset by `createWallet` itself so no caller can forget it. The stored flag is nullable, and the null is load-bearing. `false` means this install created a wallet and nobody has confirmed the seed, so the strip is up whether or not the balance reads. `null` means nothing is stored — an install that predates the flag, or one that has never created a wallet here — and there the strip waits for `wallet_balance` to return a real amount, the core's own evidence that the child has a wallet open. Without that distinction a first-run user who had configured a chain source but not yet created a wallet (`wallet_balance` returns "err") would be warned about a seed they do not have. The app-bar Back still leaves the screen, deliberately — it is the TUI's `Esc`. It costs nothing now, because leaving no longer loses the seed. Verification: `./gradlew :app:testDebugUnitTest` green, 135 tests (`SeedBackupGateTest` 18 of them).
998 lines
40 KiB
Kotlin
998 lines
40 KiB
Kotlin
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
|
|
import com.siriusdevops.onionwire.crypto.KeyBacking
|
|
import com.siriusdevops.onionwire.crypto.KeystorePassphraseCipher
|
|
import com.siriusdevops.onionwire.crypto.StoreSecret
|
|
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
|
|
import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths
|
|
import kotlinx.coroutines.CancellationException
|
|
import kotlinx.coroutines.Dispatchers
|
|
import kotlinx.coroutines.Job
|
|
import kotlinx.coroutines.currentCoroutineContext
|
|
import kotlinx.coroutines.delay
|
|
import kotlinx.coroutines.flow.MutableStateFlow
|
|
import kotlinx.coroutines.flow.StateFlow
|
|
import kotlinx.coroutines.flow.asStateFlow
|
|
import kotlinx.coroutines.flow.update
|
|
import kotlinx.coroutines.isActive
|
|
import kotlinx.coroutines.launch
|
|
import kotlinx.coroutines.withContext
|
|
import uniffi.onionwire_sdk.ChainChoice
|
|
import uniffi.onionwire_sdk.ChainConfig
|
|
import uniffi.onionwire_sdk.ChatMessage
|
|
import uniffi.onionwire_sdk.FriendInfo
|
|
import uniffi.onionwire_sdk.InviteInfo
|
|
import uniffi.onionwire_sdk.OutboxRow
|
|
import uniffi.onionwire_sdk.RotateOutcome
|
|
import uniffi.onionwire_sdk.SendState
|
|
import uniffi.onionwire_sdk.TransferRow
|
|
import uniffi.onionwire_sdk.WalletChildStatus
|
|
import uniffi.onionwire_sdk.Wire
|
|
import uniffi.onionwire_sdk.decodeInvite
|
|
import java.io.File
|
|
import java.util.concurrent.atomic.AtomicBoolean
|
|
|
|
sealed interface Phase {
|
|
/** No identity unlocked. Nothing Tor-related is running. */
|
|
data object Locked : Phase
|
|
|
|
/** Bootstrap + onion publish. Cold start is minutes, not seconds. */
|
|
data object Opening : Phase
|
|
|
|
data class Ready(
|
|
val fingerprint: String,
|
|
val onion: String,
|
|
val sdkVersion: String,
|
|
) : Phase
|
|
|
|
data class Failed(val message: String) : Phase
|
|
}
|
|
|
|
/**
|
|
* How the lock screen expects the next unlock to happen.
|
|
*
|
|
* This is a probe of local state, not a promise: [OneTap] means a blob exists
|
|
* *and* decrypted successfully during this process's lifetime.
|
|
*/
|
|
sealed interface Unlock {
|
|
/**
|
|
* The passphrase must be typed. [notice] explains why a stored one is not
|
|
* being used (key invalidated, blob corrupt, nothing stored yet).
|
|
*/
|
|
data class TypeIt(val notice: String? = null) : Unlock
|
|
|
|
/** A stored, decryptable passphrase exists — one tap. */
|
|
data class OneTap(val backing: KeyBacking) : Unlock
|
|
}
|
|
|
|
/**
|
|
* Everything one open chat screen renders, refreshed on a single cadence.
|
|
*
|
|
* [messages] is null until the first read lands — the screen shows its spinner
|
|
* on that, exactly as it did reading the SDK itself. [error] is the last load
|
|
* failure and is sticky on purpose: it survives the ticks that succeed, so a
|
|
* transient store error is still on screen after the next 2s tick rather than
|
|
* blinking away. A send clears it (the user has acted on it).
|
|
*/
|
|
data class ChatState(
|
|
val messages: List<ChatMessage>? = null,
|
|
val outbox: List<OutboxRow> = emptyList(),
|
|
val maxAttempts: UInt? = null,
|
|
val error: String? = null,
|
|
)
|
|
|
|
/**
|
|
* Owns the UI side of the process's single node.
|
|
*
|
|
* The node itself lives in [NodeHost], not here, because it now has two
|
|
* possible owners: this ViewModel while the UI is up, and [KeepAliveService]
|
|
* while the screen is off. A configuration change still must not drop a
|
|
* published onion, and neither must the activity being destroyed — that part
|
|
* is unchanged.
|
|
*/
|
|
class WireViewModel(app: Application) : AndroidViewModel(app) {
|
|
|
|
/** `context.filesDir` — app-private, never external storage. */
|
|
private val home: File = File(app.filesDir, "onionwire")
|
|
|
|
/**
|
|
* The Keystore-wrapped passphrase. Two files at most: this blob and the
|
|
* KeyStore key under alias [KeystorePassphraseCipher.ALIAS]. Nothing else
|
|
* on disk ever sees the plaintext.
|
|
*/
|
|
private val secrets: StoredPassphraseStore = StoredPassphraseStore(
|
|
File(File(app.filesDir, "secrets"), "store-passphrase.bin"),
|
|
KeystorePassphraseCipher(app),
|
|
)
|
|
|
|
private val _phase = MutableStateFlow<Phase>(Phase.Locked)
|
|
val phase: StateFlow<Phase> = _phase.asStateFlow()
|
|
|
|
private val _unlock = MutableStateFlow<Unlock>(Unlock.TypeIt())
|
|
val unlock: StateFlow<Unlock> = _unlock.asStateFlow()
|
|
|
|
private val _friends = MutableStateFlow<List<FriendInfo>>(emptyList())
|
|
val friends: StateFlow<List<FriendInfo>> = _friends.asStateFlow()
|
|
|
|
/**
|
|
* One line of battery honesty for the roster: what is still running once
|
|
* the screen is off, or why it is not. Null while locked.
|
|
*/
|
|
private val _keepAliveNote = MutableStateFlow<String?>(null)
|
|
val keepAliveNote: StateFlow<String?> = _keepAliveNote.asStateFlow()
|
|
|
|
/**
|
|
* The currently open chat, or null when no chat screen is composed.
|
|
*
|
|
* There is exactly one node and one chat on screen at a time, so this is
|
|
* one state object rather than a map keyed by peer: a second poller for a
|
|
* second peer would double the SDK traffic for a screen nobody is looking
|
|
* at, and the node's store reads are not free.
|
|
*/
|
|
private val _chat = MutableStateFlow<ChatState?>(null)
|
|
val chat: StateFlow<ChatState?> = _chat.asStateFlow()
|
|
|
|
/** The peer [chat] belongs to; guards a stale tick from a previous peer. */
|
|
private var chatPeer: String? = null
|
|
|
|
private var chatPoller: Job? = null
|
|
|
|
init {
|
|
// A node the foreground service kept alive is still open. Adopt it and
|
|
// go straight to the roster: showing an unlock screen for a store that
|
|
// is already open would be theatre, and unlocking again would race the
|
|
// live node for the sqlite file.
|
|
val existing = NodeHost.current()
|
|
when {
|
|
existing != null -> viewModelScope.launch { adopt(existing) }
|
|
NodeHost.isOpening() -> {
|
|
_phase.value = Phase.Opening
|
|
viewModelScope.launch { resumeOpening() }
|
|
}
|
|
else -> refreshUnlockState()
|
|
}
|
|
|
|
viewModelScope.launch {
|
|
NodeHost.keepAlive.collect { renderKeepAliveNote(it) }
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Unlocks with a typed passphrase. Empty fails closed — the SDK maps it
|
|
* straight to an error, it is not a "skip" path.
|
|
*
|
|
* [remember] wraps the passphrase with the Keystore key so later launches
|
|
* are one tap. It is opt-in in the UI (and on by default there); it is
|
|
* never implied by this call.
|
|
*/
|
|
fun unlock(passphrase: String, remember: Boolean = false) {
|
|
if (passphrase.isEmpty()) return
|
|
openWith(passphrase.toCharArray(), storeAfterwards = remember)
|
|
}
|
|
|
|
/**
|
|
* One-tap unlock from the stored blob.
|
|
*
|
|
* Any failure — key deleted, blob corrupt, GCM tag mismatch — degrades to
|
|
* "type it" with the reason on screen. It never crashes and never silently
|
|
* unlocks with something else.
|
|
*/
|
|
fun unlockStored() {
|
|
if (_phase.value is Phase.Opening) return
|
|
viewModelScope.launch {
|
|
val loaded = withContext(Dispatchers.IO) { secrets.load() }
|
|
when (loaded) {
|
|
is StoredPassphraseStore.Load.Loaded ->
|
|
openWith(loaded.passphrase, storeAfterwards = false)
|
|
|
|
StoredPassphraseStore.Load.Absent -> {
|
|
_unlock.value = Unlock.TypeIt("No passphrase is stored on this device.")
|
|
}
|
|
|
|
is StoredPassphraseStore.Load.Unavailable -> {
|
|
_unlock.value = Unlock.TypeIt(unavailableNotice(loaded.reason))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Drops the stored passphrase and its Keystore key. Irreversible. */
|
|
fun forgetStoredPassphrase() {
|
|
viewModelScope.launch {
|
|
withContext(Dispatchers.IO) { secrets.forget() }
|
|
_unlock.value = Unlock.TypeIt(
|
|
"Stored passphrase deleted. Type it to open the store again.",
|
|
)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Explicit Lock: stops the node and the keep-alive with it.
|
|
*
|
|
* Order matters. The service goes first — a still-running keep-alive would
|
|
* re-anchor the node and leave a notification pointing at a dead onion —
|
|
* then the policy tears the node down, flush before `shutdown()` so the
|
|
* outbox survives.
|
|
*/
|
|
fun lock() {
|
|
if (NodeHost.current() == null) return
|
|
// Stop the chat tick before the node goes: the next read of a closed
|
|
// store would surface as a chat load error on a screen the user has
|
|
// already left, and every tick would keep re-reporting it.
|
|
stopChatPoller()
|
|
KeepAliveService.stop(getApplication())
|
|
NodeHost.lock()
|
|
_friends.value = emptyList()
|
|
_phase.value = Phase.Locked
|
|
refreshUnlockState()
|
|
}
|
|
|
|
/**
|
|
* The UI is going away: a normal finish, a task swipe, or the process being
|
|
* killed. This deliberately does **not** shut the node down — [NodeHost]
|
|
* decides between "flush and stay published" (a keep-alive is holding it)
|
|
* and "flush and stop" (nothing is). A ViewModel that shut down a node the
|
|
* foreground service owns is the bug this card exists to avoid.
|
|
*/
|
|
override fun onCleared() {
|
|
NodeHost.onUiDetached()
|
|
super.onCleared()
|
|
}
|
|
|
|
/** Re-reads the notification state after the runtime prompt resolves. */
|
|
fun onNotificationPermissionChanged() {
|
|
renderKeepAliveNote(NodeHost.keepAlive.value)
|
|
// Android does not retroactively post a foreground notification that was
|
|
// suppressed while POST_NOTIFICATIONS was denied — the service started,
|
|
// the user then granted, and the shade stayed empty. Re-announce, so the
|
|
// grant actually produces the one honest signal the user has.
|
|
if (NodeHost.keepAlive.value is KeepAliveStatus.On) {
|
|
viewModelScope.launch {
|
|
NodeHost.current()?.let { KeepAliveService.start(getApplication(), it.onion()) }
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Whether the keep-alive's notification can actually be posted. */
|
|
fun notificationsAllowed(): Boolean =
|
|
NotificationManagerCompat.from(getApplication()).areNotificationsEnabled()
|
|
|
|
private fun renderKeepAliveNote(status: KeepAliveStatus) {
|
|
val text = getApplication<Application>()
|
|
_keepAliveNote.value = when (status) {
|
|
// Not a null note: "off" is a real state the user should be able to
|
|
// read, right after the notification's Stop action.
|
|
KeepAliveStatus.Off -> text.getString(R.string.keep_alive_note_off)
|
|
|
|
KeepAliveStatus.On -> text.getString(
|
|
if (notificationsAllowed()) {
|
|
R.string.keep_alive_note_on
|
|
} else {
|
|
// Denial is not fatal: the service runs either way and
|
|
// Android lists it in the Task Manager. Say that instead of
|
|
// pretending the notification is there.
|
|
R.string.keep_alive_note_hidden
|
|
},
|
|
)
|
|
|
|
is KeepAliveStatus.Unavailable ->
|
|
text.getString(R.string.keep_alive_note_unavailable, status.reason)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The one path that opens the SDK.
|
|
*
|
|
* [secret] is wiped in `finally`, including when the Keystore write or the
|
|
* SDK call throws. The SDK's UniFFI signature takes a `String`, so one
|
|
* immutable copy is unavoidable here — see PR #49 for the follow-up SDK
|
|
* signature this card cannot make itself.
|
|
*/
|
|
private fun openWith(secret: CharArray, storeAfterwards: Boolean) {
|
|
if (secret.isEmpty() || _phase.value is Phase.Opening) {
|
|
StoreSecret.wipe(secret)
|
|
return
|
|
}
|
|
val existing = NodeHost.current()
|
|
if (existing != null) {
|
|
// Already open, kept alive while the UI was gone: adopt, never
|
|
// re-open. The live node holds the sqlite file and Arti's state
|
|
// lock, so a second open would fail — or worse, half-succeed.
|
|
StoreSecret.wipe(secret)
|
|
viewModelScope.launch { adopt(existing) }
|
|
return
|
|
}
|
|
_phase.value = Phase.Opening
|
|
NodeHost.noteOpening()
|
|
// Hold the process from this tap, not after Tor publishes: otherwise
|
|
// closing the activity cancels viewModelScope and kills bootstrap.
|
|
KeepAliveService.start(getApplication(), "")
|
|
viewModelScope.launch {
|
|
try {
|
|
val w = NodeHost.open(home, secret.concatToString())
|
|
if (storeAfterwards) store(secret)
|
|
adopt(w)
|
|
startKeepAlive(w)
|
|
} catch (t: CancellationException) {
|
|
throw t
|
|
} catch (t: Throwable) {
|
|
_phase.value = Phase.Failed(t.message ?: t.toString())
|
|
if (!NodeHost.hasWorkForKeepAlive()) {
|
|
KeepAliveService.stop(getApplication())
|
|
}
|
|
} finally {
|
|
StoreSecret.wipe(secret)
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Points the UI at a node that is already running. The SDK getters are
|
|
* `suspend`, hence the coroutine call sites.
|
|
*/
|
|
private suspend fun adopt(w: Wire) {
|
|
_phase.value = Phase.Ready(
|
|
fingerprint = w.fingerprint(),
|
|
onion = w.onion(),
|
|
sdkVersion = w.version(),
|
|
)
|
|
runCatching { refreshFriends() }
|
|
}
|
|
|
|
/** Re-attach after the activity died mid-bootstrap. */
|
|
private suspend fun resumeOpening() {
|
|
try {
|
|
val w = NodeHost.awaitOpen()
|
|
adopt(w)
|
|
startKeepAlive(w)
|
|
} catch (t: CancellationException) {
|
|
throw t
|
|
} catch (t: Throwable) {
|
|
_phase.value = Phase.Failed(t.message ?: t.toString())
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Starts the foreground keep-alive. Always reached from a user-visible
|
|
* unlock, so the API 31+ background-start restriction does not apply; if
|
|
* the system refuses anyway, [NodeHost] records why and the roster says so.
|
|
*/
|
|
private suspend fun startKeepAlive(w: Wire) {
|
|
// Announced even when the keep-alive is already `On`: it was anchored at
|
|
// the Open tap with an empty locator, so the notice says "OnionWire is
|
|
// starting". The POST_NOTIFICATIONS callback happens to re-announce on a
|
|
// fresh install, but on a device that already granted notifications
|
|
// there is no callback at all — the notice would then claim bootstrap
|
|
// forever. Same notification id, so this replaces it with the address
|
|
// the user can actually hand out.
|
|
KeepAliveService.start(getApplication(), w.onion())
|
|
}
|
|
|
|
private suspend fun store(secret: CharArray) {
|
|
val outcome: Result<KeyBacking> = withContext(Dispatchers.IO) {
|
|
try {
|
|
secrets.save(secret)
|
|
Result.success(secrets.backing())
|
|
} catch (t: Throwable) {
|
|
Result.failure(t)
|
|
}
|
|
}
|
|
_unlock.value = outcome.fold(
|
|
onSuccess = { Unlock.OneTap(it) },
|
|
onFailure = {
|
|
// Unlock succeeded, so this is not fatal — say so plainly
|
|
// instead of pretending the passphrase was stored.
|
|
Unlock.TypeIt("Could not store the passphrase: ${it.message ?: it}.")
|
|
},
|
|
)
|
|
}
|
|
|
|
private fun refreshUnlockState() {
|
|
viewModelScope.launch {
|
|
val state = withContext(Dispatchers.IO) {
|
|
when (val loaded = secrets.load()) {
|
|
is StoredPassphraseStore.Load.Loaded -> {
|
|
// We only needed to know it decrypts. Wipe immediately.
|
|
StoreSecret.wipe(loaded.passphrase)
|
|
Unlock.OneTap(secrets.backing())
|
|
}
|
|
|
|
StoredPassphraseStore.Load.Absent -> Unlock.TypeIt()
|
|
|
|
is StoredPassphraseStore.Load.Unavailable ->
|
|
Unlock.TypeIt(unavailableNotice(loaded.reason))
|
|
}
|
|
}
|
|
_unlock.value = state
|
|
}
|
|
}
|
|
|
|
private fun unavailableNotice(reason: String): String =
|
|
"The stored passphrase could not be read — $reason. Type it once to store it again."
|
|
|
|
private fun requireWire(): Wire = NodeHost.requireOpen()
|
|
|
|
suspend fun refreshFriends() {
|
|
_friends.value = requireWire().friends()
|
|
}
|
|
|
|
suspend fun invite(): String = requireWire().invite()
|
|
|
|
suspend fun addFriend(invite: String): FriendInfo {
|
|
val f = requireWire().addFriend(invite)
|
|
refreshFriends()
|
|
return f
|
|
}
|
|
|
|
suspend fun setPetname(pubkeyHex: String, petname: String?) {
|
|
requireWire().setPetname(pubkeyHex, petname?.takeIf { it.isNotBlank() })
|
|
refreshFriends()
|
|
}
|
|
|
|
suspend fun messages(pubkeyHex: String): List<ChatMessage> =
|
|
requireWire().messages(pubkeyHex)
|
|
|
|
/**
|
|
* The core's outbox rows for one friend: the `"queued"` / `"sending"` /
|
|
* `"failed"` rows behind [ChatMessage.delivery], each with the attempt count
|
|
* and absolute next-attempt time the store holds. Empty means nothing is
|
|
* outstanding for them. Read this instead of guessing a retry schedule in
|
|
* the app.
|
|
*/
|
|
suspend fun outbox(pubkeyHex: String): List<OutboxRow> =
|
|
requireWire().outbox(pubkeyHex)
|
|
|
|
/**
|
|
* The core's retry budget — the denominator in `try n/8`. A constant of the
|
|
* outbox, not per-node state, so it is fetched from the SDK rather than
|
|
* duplicated here; the app must not hardcode it.
|
|
*/
|
|
suspend fun outboxMaxAttempts(): UInt = uniffi.onionwire_sdk.outboxMaxAttempts()
|
|
|
|
/**
|
|
* Starts the one 2s refresh loop for [pubkeyHex] and resets the chat state.
|
|
*
|
|
* Called from the chat screen entering the composition. Re-entering the
|
|
* same peer while its poller is alive is a no-op — navigating to the chat
|
|
* and back must never stack a second loop on top of the first.
|
|
*/
|
|
fun openChat(pubkeyHex: String) {
|
|
if (chatPeer == pubkeyHex && chatPoller?.isActive == true) return
|
|
chatPoller?.cancel()
|
|
chatPeer = pubkeyHex
|
|
_chat.value = ChatState()
|
|
chatPoller = viewModelScope.launch { pollChat(pubkeyHex) }
|
|
}
|
|
|
|
/**
|
|
* Stops the loop when the chat screen leaves. Ignored when another peer has
|
|
* taken over in the meantime (navigating chat A → chat B disposes A after B
|
|
* has already opened).
|
|
*/
|
|
fun closeChat(pubkeyHex: String) {
|
|
if (chatPeer != pubkeyHex) return
|
|
stopChatPoller()
|
|
}
|
|
|
|
private fun stopChatPoller() {
|
|
chatPoller?.cancel()
|
|
chatPoller = null
|
|
chatPeer = null
|
|
_chat.value = null
|
|
}
|
|
|
|
/**
|
|
* Drops the last load error. The send path calls this: the user has acted,
|
|
* so a stale "could not read" line must not sit under the composer while
|
|
* the send is in flight.
|
|
*/
|
|
fun clearChatError() {
|
|
_chat.update { it?.copy(error = null) }
|
|
}
|
|
|
|
/**
|
|
* The cadence, in the ViewModel: inbound messages are appended by the node
|
|
* in the background and the retry worker moves queued rows along, and in v1
|
|
* there is no push channel into the UI, so messages and outbox are read
|
|
* together on one 2s tick. The outbox rows are read on that tick too —
|
|
* their `next_attempt_at` is a fixed instant, so a row saying "retry 45s"
|
|
* turns into "retry now" here without the store having to change.
|
|
*
|
|
* The retry budget is read once per open chat (it is a constant of the
|
|
* outbox, not per-peer state); a failure leaves it null and the rows fall
|
|
* back to the flat marker.
|
|
*/
|
|
private suspend fun pollChat(pk: String) {
|
|
runCatching { outboxMaxAttempts() }.onSuccess { budget ->
|
|
if (chatPeer == pk) _chat.update { it?.copy(maxAttempts = budget) }
|
|
}
|
|
while (currentCoroutineContext().isActive) {
|
|
val loaded = runCatching { messages(pk) }
|
|
val out = runCatching { outbox(pk) }
|
|
// A cancelled loop can still be sitting in a completed SDK read:
|
|
// writing that peer's rows into a state that now belongs to another
|
|
// peer would show the wrong conversation.
|
|
if (chatPeer != pk) return
|
|
_chat.update { state ->
|
|
val base = state ?: ChatState()
|
|
base.copy(
|
|
messages = loaded.getOrNull() ?: base.messages,
|
|
outbox = out.getOrNull() ?: base.outbox,
|
|
// Same order the screen's own loop reported them in, and
|
|
// sticky on success — a new failure replaces the last one,
|
|
// a successful tick does not clear the last one.
|
|
error = out.exceptionOrNull()?.let { it.message ?: it.toString() }
|
|
?: loaded.exceptionOrNull()?.let { it.message ?: it.toString() }
|
|
?: base.error,
|
|
)
|
|
}
|
|
delay(2_000)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Sends one chat message and reports what the core did with it.
|
|
*
|
|
* `SENT` — the peer's onion took the frame during this call. `QUEUED` — it
|
|
* was unreachable, so the message is in the local outbox and the retry
|
|
* worker will dial again with backoff until it lands or fails terminally.
|
|
* The state is returned rather than swallowed so the UI never shows a
|
|
* queued message as delivered.
|
|
*/
|
|
suspend fun send(pubkeyHex: String, body: String): SendState =
|
|
requireWire().send(pubkeyHex, body)
|
|
|
|
suspend fun wipeMessages() {
|
|
requireWire().wipeMessages()
|
|
}
|
|
|
|
suspend fun rotateOnion(): RotateOutcome {
|
|
val out = requireWire().rotateOnion()
|
|
_phase.value = (_phase.value as? Phase.Ready)?.copy(onion = requireWire().onion())
|
|
?: _phase.value
|
|
refreshFriends()
|
|
return out
|
|
}
|
|
|
|
suspend fun decode(invite: String): InviteInfo = decodeInvite(invite)
|
|
|
|
// --- Wallet & payments -------------------------------------------------
|
|
// These mirror the SDK surface added for the wallet screen. Payment sends
|
|
// are one-shot: if the peer's onion is unreachable, `send_*` fails now.
|
|
// They are NOT queued through the outbox like chat messages — that is a
|
|
// deliberate choice in the core, not a bug.
|
|
|
|
suspend fun walletBalance(): String = requireWire().walletBalance()
|
|
|
|
suspend fun walletReceiveAddress(): String? = runCatching {
|
|
requireWire().walletReceiveAddress()
|
|
}.getOrElse { null }
|
|
|
|
suspend fun walletRecentTransfers(cap: Int = 25): List<TransferRow> = runCatching {
|
|
requireWire().walletRecentTransfers(cap.toUInt())
|
|
}.getOrElse { emptyList() }
|
|
|
|
suspend fun sendInvoice(pubkeyHex: String, amountXmr: String, memo: String = ""): Result<Unit> =
|
|
runCatching { requireWire().sendInvoice(pubkeyHex, amountXmr, memo) }
|
|
|
|
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()
|
|
}.getOrElse {
|
|
"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
|
|
// verbatim: off / connecting / syncing / ready / exited. Nothing here
|
|
// invents a "starting…" state, and a child that died is never folded into
|
|
// "off" — see `ui/WalletChildStatusText.kt`.
|
|
|
|
/** The last `wallet_status()` snapshot, or null before the first read. */
|
|
private val _walletChild = MutableStateFlow<WalletChildStatus?>(null)
|
|
val walletChild: StateFlow<WalletChildStatus?> = _walletChild.asStateFlow()
|
|
|
|
/**
|
|
* The last failed start/stop/read, display-ready. Sticky on purpose, like
|
|
* [ChatState.error]: a transient store read that fails once must not blink
|
|
* off the screen on the next successful tick.
|
|
*/
|
|
private val _walletChildError = MutableStateFlow<String?>(null)
|
|
val walletChildError: StateFlow<String?> = _walletChildError.asStateFlow()
|
|
|
|
/**
|
|
* Start is in flight. Core status stays `off` until Cuprate/`monerod` answers,
|
|
* so the screen must not wait on that snapshot to show that the tap landed.
|
|
*/
|
|
private val startInFlight = AtomicBoolean(false)
|
|
private val _walletChildStarting = MutableStateFlow(false)
|
|
val walletChildStarting: StateFlow<Boolean> = _walletChildStarting.asStateFlow()
|
|
|
|
/** The stored chain source + binary settings, for prefilling the editor. */
|
|
private val _chainSource = MutableStateFlow<ChainConfig?>(null)
|
|
val chainSource: StateFlow<ChainConfig?> = _chainSource.asStateFlow()
|
|
|
|
private var walletChildPoller: Job? = null
|
|
|
|
/**
|
|
* What this install can actually spawn. Read from
|
|
* `applicationInfo.nativeLibraryDir` — the only directory Android hands out
|
|
* executable — so the screen can say "not bundled" instead of offering a
|
|
* Start that can only fail.
|
|
*/
|
|
fun bundledBinaries(): WalletChildBinaryPaths =
|
|
WalletChildBinaries.resolve(
|
|
getApplication<Application>().applicationInfo.nativeLibraryDir,
|
|
)
|
|
|
|
/**
|
|
* Starts the one wallet-child refresh loop for the wallet screen. Re-entering
|
|
* the screen while the loop is alive is a no-op: navigating to the wallet
|
|
* and back must never stack a second poller.
|
|
*/
|
|
fun openWalletChild() {
|
|
if (walletChildPoller?.isActive == true) return
|
|
walletChildPoller = viewModelScope.launch {
|
|
walletChildRefreshLoop(
|
|
tickMs = WALLET_CHILD_TICK_MS,
|
|
// The first paint is the cached read: it never dials, so the
|
|
// screen has a record to render while the first probe is still
|
|
// in flight.
|
|
cached = ::paintWalletChildCached,
|
|
// Every tick after that is a live probe, so `height` /
|
|
// `target_height` move on their own instead of only when a
|
|
// chain-mode button is tapped.
|
|
live = ::refreshWalletChild,
|
|
)
|
|
}
|
|
}
|
|
|
|
/** Stops the loop when the wallet screen leaves. */
|
|
fun closeWalletChild() {
|
|
walletChildPoller?.cancel()
|
|
walletChildPoller = null
|
|
}
|
|
|
|
/** Drops the last failure. The user has acted on it. */
|
|
fun clearWalletChildError() {
|
|
_walletChildError.value = null
|
|
}
|
|
|
|
/**
|
|
* The first paint: one `wallet_status()` read.
|
|
*
|
|
* `Wire::wallet_status` is synchronous in Rust and re-reads the sealed
|
|
* wallet-child record out of the SQLCipher store, so it goes to
|
|
* [Dispatchers.IO] — a store decrypt on the main thread is an ANR waiting
|
|
* for a slow device. It never dials and never spawns, so it is the right
|
|
* read to have a record on screen — and the wrong one to poll with.
|
|
*/
|
|
suspend fun paintWalletChildCached() = readWalletChild { requireWire().walletStatus() }
|
|
|
|
/**
|
|
* One tick: a live probe, `Wire::wallet_child_refresh()`.
|
|
*
|
|
* `Wire::wallet_status` above only re-reads what the last probe left behind,
|
|
* so polling it pins the `sync h/t` segment on whatever the last
|
|
* start/stop saw. This one dials — the child's loopback wallet RPC, and the
|
|
* configured local daemon's `get_info` when the wallet RPC does not answer
|
|
* — which is what makes the chain's height and target move between ticks.
|
|
*
|
|
* It never spawns a child, and the core short-circuits with the cached
|
|
* snapshot when there is no live child, so it cannot invent `ready` for a
|
|
* wallet that is not there. Not free, though: the tick stays on the order of
|
|
* seconds rather than frames.
|
|
*
|
|
* Failure is folded into the sticky [walletChildError], same as the cached
|
|
* read: a probe that fails once must not blink the previous error off the
|
|
* screen.
|
|
*/
|
|
suspend fun refreshWalletChild() = readWalletChild { requireWire().walletChildRefresh() }
|
|
|
|
/**
|
|
* Runs one of the two reads on [Dispatchers.IO] and lands it in the wallet
|
|
* state. `requireWire()` throws when the node is locked, so it is called
|
|
* *inside* the [runCatching] — a locked node has to surface as
|
|
* [walletChildError], not as a crash on the tick.
|
|
*/
|
|
private suspend fun readWalletChild(read: suspend () -> WalletChildStatus) {
|
|
val result = withContext(Dispatchers.IO) { runCatching { read() } }
|
|
result.fold(
|
|
onSuccess = { _walletChild.value = it },
|
|
onFailure = { _walletChildError.value = it.message ?: it.toString() },
|
|
)
|
|
}
|
|
|
|
/** Re-reads the stored chain source so the editor can prefill from it. */
|
|
suspend fun refreshChainSource() {
|
|
val read = withContext(Dispatchers.IO) { runCatching { requireWire().chainSource() } }
|
|
read.onSuccess { _chainSource.value = it }
|
|
}
|
|
|
|
/**
|
|
* Saves a daemon the user typed, then leaves it to [startWalletChild] to
|
|
* spawn against it. `set_chain_source` only stores: the core validates the
|
|
* config before anything is written and a rejected config leaves the stored
|
|
* one — and any running child — untouched.
|
|
*
|
|
* [bins] is what this install resolved; the paths handed to the core are
|
|
* absolute, because nothing in an APK sandbox resolves a bare
|
|
* `monero-wallet-rpc` on `PATH`.
|
|
*/
|
|
suspend fun saveRemoteDaemon(
|
|
host: String,
|
|
port: Int,
|
|
bins: WalletChildBinaryPaths,
|
|
): Result<Unit> {
|
|
val rpc = bins.walletRpc
|
|
?: return Result.failure(IllegalStateException(NO_WALLET_RPC_MESSAGE))
|
|
return withContext(Dispatchers.IO) {
|
|
runCatching {
|
|
requireWire().setChainSource(
|
|
ChainConfig(
|
|
kind = ChainChoice.REMOTE,
|
|
monerodBin = "",
|
|
monerodDatadir = "",
|
|
host = host,
|
|
port = port.toUShort(),
|
|
walletRpcBin = rpc,
|
|
// Inert unless the host is a `.onion`; the screen refuses
|
|
// an onion daemon outright while no `arti` is bundled.
|
|
artiBin = expectedArtiPath(),
|
|
walletFilename = WalletChildBinaries.WALLET_FILENAME,
|
|
mainnet = false,
|
|
prune = false,
|
|
),
|
|
)
|
|
}
|
|
}.onSuccess {
|
|
_walletChildError.value = null
|
|
refreshChainSource()
|
|
refreshWalletChild()
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Back to receive-only: no child, no daemon, no chain traffic. The binary
|
|
* paths are still stored so switching back to a daemon does not need them
|
|
* re-derived.
|
|
*/
|
|
suspend fun setReceiveOnly(bins: WalletChildBinaryPaths): Result<Unit> =
|
|
withContext(Dispatchers.IO) {
|
|
runCatching {
|
|
requireWire().setChainSource(
|
|
ChainConfig(
|
|
kind = ChainChoice.NONE,
|
|
monerodBin = "",
|
|
monerodDatadir = "",
|
|
host = "",
|
|
port = 0u,
|
|
walletRpcBin = bins.walletRpc.orEmpty(),
|
|
artiBin = expectedArtiPath(),
|
|
walletFilename = WalletChildBinaries.WALLET_FILENAME,
|
|
mainnet = false,
|
|
prune = false,
|
|
),
|
|
)
|
|
}
|
|
}.onSuccess {
|
|
_walletChildError.value = null
|
|
refreshChainSource()
|
|
refreshWalletChild()
|
|
}
|
|
|
|
/**
|
|
* The third chain source: the chain daemon **inside this app** (Cuprate), no
|
|
* `monerod` binary and no remote operator. Stores the setting; [startWalletChild]
|
|
* is what launches the node *and* the wallet child (one call in the core).
|
|
*
|
|
* `monerodDatadir` is left empty on purpose: the SDK resolves that to
|
|
* `$ONIONWIRE_HOME/chain/{testnet,mainnet-pruned,mainnet-full}` from
|
|
* [mainnet] and [prune], so Kotlin never invents an absolute path.
|
|
*/
|
|
suspend fun setInProcessCuprate(
|
|
bins: WalletChildBinaryPaths,
|
|
mainnet: Boolean,
|
|
prune: Boolean,
|
|
): Result<Unit> =
|
|
withContext(Dispatchers.IO) {
|
|
runCatching {
|
|
requireWire().setChainSource(
|
|
ChainConfig(
|
|
kind = ChainChoice.IN_PROCESS_CUPRATE,
|
|
monerodBin = "",
|
|
monerodDatadir = "",
|
|
host = "",
|
|
port = 0u,
|
|
walletRpcBin = bins.walletRpc.orEmpty(),
|
|
// Inert for this source: an in-process node is loopback
|
|
// clearnet, so the core never spawns the SOCKS child.
|
|
artiBin = expectedArtiPath(),
|
|
walletFilename = WalletChildBinaries.WALLET_FILENAME,
|
|
mainnet = mainnet,
|
|
prune = prune,
|
|
),
|
|
)
|
|
}
|
|
}.onSuccess {
|
|
_walletChildError.value = null
|
|
refreshChainSource()
|
|
refreshWalletChild()
|
|
}
|
|
|
|
/**
|
|
* Free bytes on the filesystem the in-process chain store grows into, or
|
|
* `null` when it cannot be read. The screen shows this before the user commits
|
|
* to a store on the device; it is a measurement, not an estimate.
|
|
*/
|
|
fun chainFreeBytes(): Long? = ChainStorage.freeBytes(home)
|
|
|
|
/**
|
|
* 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.
|
|
*/
|
|
fun startWalletChild() {
|
|
if (!startInFlight.compareAndSet(false, true)) return
|
|
_walletChildStarting.value = true
|
|
_walletChildError.value = null
|
|
viewModelScope.launch {
|
|
try {
|
|
val started = withContext(Dispatchers.IO) {
|
|
runCatching { requireWire().startWalletChild() }
|
|
}
|
|
started.fold(
|
|
onSuccess = { _walletChild.value = it },
|
|
onFailure = { _walletChildError.value = it.message ?: it.toString() },
|
|
)
|
|
} finally {
|
|
startInFlight.set(false)
|
|
_walletChildStarting.value = false
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Stops the child and its siblings. Idempotent in the core. */
|
|
suspend fun stopWalletChild(): Result<Unit> {
|
|
_walletChildError.value = null
|
|
val stopped = withContext(Dispatchers.IO) {
|
|
runCatching { requireWire().stopWalletChild() }
|
|
}
|
|
stopped.fold(
|
|
onSuccess = { refreshWalletChild() },
|
|
onFailure = { _walletChildError.value = it.message ?: it.toString() },
|
|
)
|
|
return stopped
|
|
}
|
|
|
|
/** The absolute path the core would be handed for the `arti` SOCKS child. */
|
|
private fun expectedArtiPath(): String = WalletChildBinaries.expectedPath(
|
|
getApplication<Application>().applicationInfo.nativeLibraryDir,
|
|
WalletChildBinaries.ARTI_LIB,
|
|
)
|
|
}
|
|
|
|
/**
|
|
* The wallet-child refresh loop: one [cached] paint so the screen has something
|
|
* to render, then a live [live] probe every [tickMs].
|
|
*
|
|
* The reads are parameters only so the JVM test tree can drive this loop
|
|
* without a `Wire` — `NodeHost.requireOpen()` is a process-global the unit test
|
|
* cannot prime. The two call sites in [WireViewModel.openWalletChild] bind them
|
|
* to the cached read and to the live probe.
|
|
*
|
|
* Serialized by construction, and that is the point: the loop suspends on each
|
|
* read before it sleeps, so a probe slower than [tickMs] delays the next tick
|
|
* instead of overlapping it. Do not turn this into a `Flow` with
|
|
* `collectLatest`, and do not `launch` the probe: two concurrent
|
|
* `wallet_child_refresh` calls against one wallet child is a racing probe.
|
|
*/
|
|
suspend fun walletChildRefreshLoop(
|
|
tickMs: Long,
|
|
cached: suspend () -> Unit,
|
|
live: suspend () -> Unit,
|
|
) {
|
|
cached()
|
|
while (currentCoroutineContext().isActive) {
|
|
delay(tickMs)
|
|
live()
|
|
}
|
|
}
|
|
|
|
/** 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"
|
|
|