onionwire/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt
Lance Walters cf0a517cd2
All checks were successful
ci / test (pull_request) Successful in 4m15s
ci / sdk (pull_request) Successful in 1m12s
wallet: create/import in-app (no key paste on create) + opt-in spend
/ wallet create generates a wallet on the RPC and shows the 25-word seed
once for backup; /wallet import is the only path that takes an existing
seed, and it is collected on a dedicated screen so it never reaches the
composer line or chat history.

Threat model now states the real policy: payments are opt-in, default is
no spend key, spend is a local authority at create/restore, and the chain
source is the user's choice (spawned local monerod or a daemon address
they supply). WALLET.md and README follow.

Tests: canned-RPC create/restore, slash parse, help overlay.
2026-09-13 23:25:25 -04:00

443 lines
17 KiB
Kotlin

package com.siriusdevops.onionwire
import android.app.Application
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 kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
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.Wire
import uniffi.onionwire_sdk.decodeInvite
import java.io.File
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
}
/**
* 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()
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()
if (existing != null) {
viewModelScope.launch { adopt(existing) }
} 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
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
viewModelScope.launch {
try {
// The SDK open is dispatched to Dispatchers.IO inside NodeHost:
// cold start is minutes of Tor bootstrap, which the main thread
// does not survive.
val w = NodeHost.open(home, secret.concatToString())
if (storeAfterwards) store(secret)
adopt(w)
startKeepAlive(w)
} catch (t: Throwable) {
_phase.value = Phase.Failed(t.message ?: t.toString())
} 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() }
}
/**
* 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) {
if (NodeHost.keepAlive.value is KeepAliveStatus.On) return
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()
/**
* 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) }
suspend fun createWallet(password: String): Result<String> =
runCatching { requireWire().createWallet(password) }
suspend fun importWallet(password: String, seed: String): Result<Unit> =
runCatching { requireWire().importWallet(password, seed) }
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."
}
}