Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
6a19a54
fix: add durable store for retained hardware sends
Jasonvdb Nov 4, 2026
dcb9f9b
fix: keep signed hardware sends after uncertain broadcasts
Jasonvdb Nov 4, 2026
4d4f8bc
fix: retry retained hardware sends from the review screens
Jasonvdb Nov 4, 2026
8a7e7ca
fix: keep ordinary retained sends in the durable record only
Jasonvdb Nov 4, 2026
d60b85f
chore: add changelog fragment for retained hardware sends
Jasonvdb Nov 4, 2026
8a915ab
fix: consume retained send consent and allow near-max retry
Jasonvdb Nov 4, 2026
7f0e555
fix: keep observed hardware sends to prevent double payment
Jasonvdb Nov 4, 2026
0b5e550
fix: complete hardware send when its record is already observed
Jasonvdb Nov 4, 2026
69dea19
Merge branch 'master' into fix/hw-send-keep-signed-tx
Jasonvdb Nov 5, 2026
f4d69bd
fix: keep retained hardware send until replacement is signed
Jasonvdb Nov 5, 2026
c144c09
fix: warn when a retained hardware send blocks another payment
Jasonvdb Nov 5, 2026
5dc0639
fix: keep hardware send consent until the new payment is signed
Jasonvdb Nov 5, 2026
a459606
fix: give back hardware send consent when old record is restored
Jasonvdb Nov 5, 2026
36f7145
fix: keep hardware send consent when passphrase prompt is dismissed
Jasonvdb Nov 5, 2026
9082894
fix: regrant consent from the restore's own outcome
Jasonvdb Nov 6, 2026
7589be4
Merge branch 'master' into fix/hw-send-keep-signed-tx
Jasonvdb Nov 12, 2026
663bb55
fix: warn before a hardware transfer signs over a kept send
Jasonvdb Nov 12, 2026
3f7f211
fix: let auto funding pick the wallet holding a retained retry
Jasonvdb Nov 12, 2026
a3d4968
chore: merge master into fix/hw-send-keep-signed-tx
Jasonvdb Nov 12, 2026
037d639
docs: cover the retained send warning on hardware transfers
Jasonvdb Nov 12, 2026
aeb7611
Merge branch 'master' into fix/hw-send-keep-signed-tx
Jasonvdb Nov 12, 2026
03cc384
Merge branch 'master' into fix/hw-send-keep-signed-tx
Jasonvdb Nov 13, 2026
d58aa37
fix: keep near-max hardware transfer retries reachable after a fee rise
Jasonvdb Nov 13, 2026
caea116
chore: merge master into fix/hw-send-keep-signed-tx
Jasonvdb Nov 16, 2026
961dba4
chore: merge master into fix/hw-send-keep-signed-tx
Jasonvdb Nov 16, 2026
5eb68d7
Merge branch 'master' into fix/hw-send-keep-signed-tx
Jasonvdb Nov 17, 2026
f37672d
Merge branch 'master' into fix/hw-send-keep-signed-tx
Jasonvdb Nov 18, 2026
47cc70c
Merge branch 'master' into fix/hw-send-keep-signed-tx
Jasonvdb Nov 18, 2026
661757a
Merge branch 'master' into fix/hw-send-keep-signed-tx
Jasonvdb Nov 18, 2026
78bbee1
Merge branch 'master' into fix/hw-send-keep-signed-tx
Jasonvdb Nov 18, 2026
d01c8c3
Merge branch 'master' into fix/hw-send-keep-signed-tx
Jasonvdb Nov 18, 2026
2bf3461
Merge branch 'master' into fix/hw-send-keep-signed-tx
Jasonvdb Nov 19, 2026
e069934
Merge branch 'master' into fix/hw-send-keep-signed-tx
Jasonvdb Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions app/src/main/java/to/bitkit/data/keychain/Keychain.kt
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ class Keychain @Inject constructor(
fun loadString(key: String, walletIndex: Int): String? =
loadIndexed(key, stringPreferencesKey("${key}_$walletIndex"))?.decodeToString()

/** Reads an entry that belongs to [scope], such as one hardware wallet, whatever the current wallet index is. */
fun loadScopedString(key: String, scope: String): String? =
loadIndexed(key, scopedKey(key, scope))?.decodeToString()

fun load(key: String): ByteArray? = loadIndexed(key, key.indexed)

private fun loadIndexed(key: String, indexedKey: Preferences.Key<String>): ByteArray? {
Expand All @@ -65,7 +69,7 @@ class Keychain @Inject constructor(
} catch (c: CancellationException) {
throw c
} catch (t: Throwable) {
emitLoadDiagnosticsOnce(key, t)
emitLoadDiagnosticsOnce(key, t) { indexedKey }
throw KeychainError.FailedToLoad(key, cause = t)
}
}
Expand Down Expand Up @@ -136,6 +140,9 @@ class Keychain @Inject constructor(
suspend fun upsertString(key: String, value: String, walletIndex: Int) =
upsertIndexed(key, value, stringPreferencesKey("${key}_$walletIndex"))

suspend fun upsertScopedString(key: String, value: String, scope: String) =
upsertIndexed(key, value, scopedKey(key, scope))

private suspend fun upsertIndexed(key: String, value: String, indexedKey: Preferences.Key<String>) {
try {
val encryptedValue = keyStore.encrypt(value.toByteArray())
Expand All @@ -152,6 +159,10 @@ class Keychain @Inject constructor(

suspend fun delete(key: String, walletIndex: Int) = deleteIndexed(key, stringPreferencesKey("${key}_$walletIndex"))

suspend fun deleteScoped(key: String, scope: String) = deleteIndexed(key, scopedKey(key, scope))

private fun scopedKey(key: String, scope: String) = stringPreferencesKey("${key}_$scope")

private suspend fun deleteIndexed(key: String, indexedKey: Preferences.Key<String>) {
try {
keychain.edit { it.remove(indexedKey) }
Expand Down Expand Up @@ -205,11 +216,15 @@ class Keychain @Inject constructor(
.map { string -> string?.toIntOrNull() }
}

private fun emitLoadDiagnosticsOnce(key: String, cause: Throwable) {
private fun emitLoadDiagnosticsOnce(
key: String,
cause: Throwable,
preferenceKey: () -> Preferences.Key<String> = { key.indexed },
) {
if (!loadDiagnosticsEmitted.add(key)) return

val aliasPresent = probe { keyStore.containsAlias() }
val entryPresent = probe { snapshot.contains(key.indexed) }
val entryPresent = probe { snapshot.contains(preferenceKey()) }
val walletIndex = probe {
runBlocking { db.configDao().getAll().first() }.firstOrNull()?.walletIndex ?: 0L
}
Expand Down Expand Up @@ -252,6 +267,7 @@ class Keychain @Inject constructor(
PAYKIT_ALLOWANCE_RESTORE_PAUSE,
PUBKY_SECRET_KEY,
SHARED_PUBKY_SOURCE,
HW_RETAINED_SEND,
WAKE_CREDENTIALS,
WAKE_REGISTRATION,
}
Expand Down
10 changes: 10 additions & 0 deletions app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ fun Throwable.isDefiniteHardwarePreBroadcastFailure(): Boolean = generateSequenc
it is BroadcastException.InvalidHex || it is BroadcastException.InvalidTransaction
}

/** bitkit-core raises this text when it never reached a server, so no transaction bytes went out. */
private const val ELECTRUM_CONNECT_FAILURE_PREFIX = "Failed to connect to Electrum:"

private fun BroadcastException.ElectrumException.isConnectFailure(): Boolean =
errorDetails.startsWith(ELECTRUM_CONNECT_FAILURE_PREFIX, ignoreCase = true)

fun Throwable.isHardwareBroadcastNotSubmitted(): Boolean = generateSequence(this) { it.cause }.any {
it is BroadcastException.ElectrumException && it.isConnectFailure()
}

// A recognized node refusal permits leaving the sheet, but never proves non-delivery.
fun Throwable.isHardwareBroadcastRefusalForNavigation(): Boolean =
isDefiniteHardwarePreBroadcastFailure() || generateSequence(this) { it.cause }.any {
Expand Down
197 changes: 197 additions & 0 deletions app/src/main/java/to/bitkit/repositories/HwRetainedSendRepo.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
package to.bitkit.repositories

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import to.bitkit.data.keychain.Keychain
import to.bitkit.data.keychain.KeychainError
import to.bitkit.di.IoDispatcher
import to.bitkit.ext.runSuspendCatching
import to.bitkit.models.HwFundingSignedTx
import to.bitkit.utils.AppError
import to.bitkit.utils.SignedTransactionId
import javax.inject.Inject
import javax.inject.Singleton

/**
* A signed ordinary hardware-wallet send whose broadcast may have gone out. Rebroadcasting these same bytes cannot pay
* twice, because the txid stays the same, while a new signature can create a second payment.
* [serializedTx] and [address] reveal the payment, so [toString] leaves them out.
*/
@Serializable
data class HwRetainedSend(
val walletId: String,
val address: String,
val amountSats: ULong,
val serializedTx: String,
val miningFeeSats: ULong,
val feeRate: ULong,
val totalSpent: ULong,
val retryWasRefused: Boolean = false,
val observed: Boolean = false,
) {
val signedTx: HwFundingSignedTx
get() = HwFundingSignedTx(serializedTx, miningFeeSats, feeRate, totalSpent)

fun isSamePayment(address: String, amountSats: ULong) = this.address == address && this.amountSats == amountSats

/**
* Whether a payment to [address] may send these bytes again. A refused retry or a payment already on the network
* is not a retry, so it gets no exemption from today's maximum or fee.
*/
fun offersRetryTo(address: String) = !retryWasRefused && !observed && this.address == address

override fun toString() =
"HwRetainedSend(walletId='$walletId', retryWasRefused='$retryWasRefused', observed='$observed')"
}

/** Which existing record [HwRetainedSendRepo.retain] may overwrite with different bytes. */
enum class HwRetainedSendReplacement {
None,

/** Only a record the watcher has seen, because that payment is resolved. Checked again at write time. */
ObservedRecord,

/** The user accepted a second payment, so anything stored may go, including an entry that cannot be read. */
Consented,
}

/** What [HwRetainedSendRepo.retain] did to the wallet's entry, so a send that never goes out can undo exactly that. */
sealed interface HwRetainOutcome {
data object Stored : HwRetainOutcome
data object AlreadyHeld : HwRetainOutcome
data class Replaced(val previous: HwRetainedSend) : HwRetainOutcome
data object ReplacedUnreadableEntry : HwRetainOutcome
}

/** What [HwRetainedSendRepo.restore] did to the wallet's entry. A failed read or write fails the `Result` instead. */
enum class HwRestoreOutcome { WroteOldRecord, LeftCurrentRecord }

sealed class HwRetainedSendError(message: String) : AppError(message) {
class DifferentTransactionRetained : HwRetainedSendError("A different signed transaction is already retained")

/** Carries no cause, because a decoder's message can quote the entry, and those bytes reveal the payment. */
class Undecodable : HwRetainedSendError("The retained send entry cannot be decoded")
}

/**
* Holds at most one retained send per hardware wallet, in device-only storage that `Keychain.wipe` clears and backups
* never read. Every read fails on unreadable storage rather than reporting no record, because a missing record lets the
* next attempt sign again.
*/
@Singleton
class HwRetainedSendRepo @Inject constructor(
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
private val keychain: Keychain,
) {
companion object {
private val KEY = Keychain.Key.HW_RETAINED_SEND.name
private val storeJson = Json { ignoreUnknownKeys = true }
}

private val mutex = Mutex()

/**
* Retaining the bytes already held keeps the existing record, including its `retryWasRefused`. A replacement is one
* write, so a failed one leaves the old record as it was.
*/
suspend fun retain(
walletId: String,
address: String,
amountSats: ULong,
signedTx: HwFundingSignedTx,
replacement: HwRetainedSendReplacement = HwRetainedSendReplacement.None,
): Result<HwRetainOutcome> = locked {
val send = HwRetainedSend(
walletId = walletId,
address = address,
amountSats = amountSats,
serializedTx = signedTx.serializedTx,
miningFeeSats = signedTx.miningFeeSats,
feeRate = signedTx.feeRate,
totalSpent = signedTx.totalSpent,
)
val existing = runSuspendCatching { load(walletId) }.getOrElse {
// Keychain wraps decrypt failures as FailedToLoad, so an undecryptable entry looks like a read failure.
val isUnreadable = it is HwRetainedSendError.Undecodable || it is KeychainError.FailedToLoad
if (replacement != HwRetainedSendReplacement.Consented || !isUnreadable) throw it
save(send)
return@locked HwRetainOutcome.ReplacedUnreadableEntry
}
when {
existing == null -> {
save(send)
HwRetainOutcome.Stored
}
existing.serializedTx.equals(send.serializedTx, ignoreCase = true) -> HwRetainOutcome.AlreadyHeld
replacement == HwRetainedSendReplacement.Consented ||
replacement == HwRetainedSendReplacement.ObservedRecord && existing.observed -> {
save(send)
HwRetainOutcome.Replaced(existing)
}
else -> throw HwRetainedSendError.DifferentTransactionRetained()
}
}

/**
* Puts back the record that [serializedTx] replaced, when those bytes never reached dispatch or settled as not
* sent. Bytes the watcher has seen did go out, so they stay as the record.
*/
suspend fun restore(previous: HwRetainedSend, serializedTx: String): Result<HwRestoreOutcome> = locked {
val current = load(previous.walletId)
if (current?.serializedTx.equals(serializedTx, ignoreCase = true) && current?.observed == false) {
save(previous)
HwRestoreOutcome.WroteOldRecord
} else {
HwRestoreOutcome.LeftCurrentRecord
}
}

suspend fun record(walletId: String): Result<HwRetainedSend?> = locked { load(walletId) }

suspend fun markRetryRefused(walletId: String): Result<Unit> = locked {
load(walletId)?.takeUnless { it.retryWasRefused }?.let { save(it.copy(retryWasRefused = true)) }
}

/** Reads first so an undecodable entry fails and stays in place. Only [abandon] may delete one. */
suspend fun release(walletId: String): Result<Unit> = locked {
if (load(walletId) != null) keychain.deleteScoped(KEY, walletId)
}

/**
* Marks the wallet's record when one of [txIds] is its transaction. A record with invalid hex never matches.
* Never deletes: a delivered transaction is when the sign button still reads Retry, and with no record to restore
* that retry would sign a second payment.
*/
suspend fun markObserved(walletId: String, txIds: Collection<String>): Result<Unit> = locked {
val record = load(walletId)?.takeUnless { it.observed } ?: return@locked
val txId = runCatching { SignedTransactionId.fromHex(record.serializedTx) }.getOrNull() ?: return@locked
if (txIds.any { it.equals(txId, ignoreCase = true) }) save(record.copy(observed = true))
}

/**
* Only for a user who removed the wallet. This is the one path that deletes an entry it cannot read, otherwise
* re-pairing the wallet brings the warning back.
*/
suspend fun abandon(walletId: String): Result<Unit> = locked {
// Keychain wraps decrypt failures as FailedToLoad, so an undecryptable entry looks like a plain read failure.
keychain.deleteScoped(KEY, walletId)
}

private suspend fun <T> locked(block: suspend () -> T): Result<T> = withContext(ioDispatcher) {
runSuspendCatching { mutex.withLock { block() } }
}

private fun load(walletId: String): HwRetainedSend? {
val entry = keychain.loadScopedString(KEY, walletId) ?: return null
return runCatching { storeJson.decodeFromString<HwRetainedSend>(entry) }
.getOrElse { throw HwRetainedSendError.Undecodable() }
}

private suspend fun save(send: HwRetainedSend) =
keychain.upsertScopedString(KEY, storeJson.encodeToString(send), send.walletId)
}
41 changes: 33 additions & 8 deletions app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ class HwWalletRepo @Inject constructor(
private val preActivityMetadataRepo: PreActivityMetadataRepo,
private val hwWalletStore: HwWalletStore,
private val settingsStore: SettingsStore,
private val hwRetainedSendRepo: HwRetainedSendRepo,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) {
companion object {
Expand Down Expand Up @@ -1109,6 +1110,9 @@ class HwWalletRepo @Inject constructor(
"Hardware wallet '$walletId' still present after removal"
}
}
}.onSuccess {
hwRetainedSendRepo.abandon(walletId)
.onFailure { Logger.warn("Failed to release retained send of '$walletId'", it, context = TAG) }
}.onFailure {
watcherSyncRequests.tryEmit(Unit)
}
Expand Down Expand Up @@ -1186,19 +1190,29 @@ class HwWalletRepo @Inject constructor(
syncWatchers()
}

private suspend fun markObservedRetainedSend(walletId: String, txIds: List<String>) {
if (txIds.isEmpty()) return
hwRetainedSendRepo.markObserved(walletId, txIds)
.onFailure { Logger.warn("Failed to mark observed send of '$walletId'", it, context = TAG) }
}

private fun observeWatcherEvents() {
scope.launch {
trezorRepo.watcherEvents.collect { (watcherId, event) ->
if (event !is WatcherEvent.TransactionsChanged) return@collect
val receivedTxs = watcherMutex.withLock {
val walletId = activeWatcherWalletIds[watcherId] ?: return@withLock emptyList()
val outcome = watcherMutex.withLock {
val walletId = activeWatcherWalletIds[watcherId] ?: return@withLock null
val activities = event.activities
.filter { it.walletId() == walletId }
.toImmutableList()
val observedTxIds = activities.mapNotNull { activity ->
(activity as? Activity.Onchain)?.v1?.takeIf { it.doesExist }?.txId
}
val transactionDetails = event.transactionDetails
.filter { it.walletId == walletId }
.toImmutableList()
val addressType = watcherId.toFundingAddressType() ?: return@withLock emptyList()
val addressType = watcherId.toFundingAddressType()
?: return@withLock HwWatcherEventOutcome(walletId, observedTxIds)
val watcher = HwWatcherData(
walletId = walletId,
addressType = addressType,
Expand All @@ -1221,14 +1235,14 @@ class HwWalletRepo @Inject constructor(
_watcherData.update { data ->
data + (watcherId to watcher.copy(activities = it.activities))
}
return@withLock emptyList()
return@withLock HwWatcherEventOutcome(walletId, observedTxIds)
}

val persistedActivities = activityRepo.persistHwSnapshot(
walletId = walletId,
activities = activities,
transactionDetails = transactionDetails,
).getOrElse { return@withLock emptyList() }
).getOrElse { return@withLock HwWatcherEventOutcome(walletId, observedTxIds) }
val immutablePersistedActivities = persistedActivities.toImmutableList()
lastPersistedHwSnapshots[walletId] = PersistedHwSnapshot(
source = snapshotCacheKey,
Expand All @@ -1238,9 +1252,14 @@ class HwWalletRepo @Inject constructor(
val updatedWatcherData = _watcherData.value + (watcherId to persistedWatcher)
_watcherData.update { updatedWatcherData }
persistedActivityIds[watcherId] = persistedActivities.map { it.scopedId() }.toSet()
buildReceivedTxs(previousIds, persistedActivities, updatedWatcherData)
}
receivedTxs.forEach { _receivedTxs.emit(it) }
HwWatcherEventOutcome(
walletId = walletId,
observedTxIds = observedTxIds,
receivedTxs = buildReceivedTxs(previousIds, persistedActivities, updatedWatcherData),
)
} ?: return@collect
markObservedRetainedSend(outcome.walletId, outcome.observedTxIds)
outcome.receivedTxs.forEach { _receivedTxs.emit(it) }
}
}
}
Expand Down Expand Up @@ -1559,6 +1578,12 @@ private fun WatcherEvent.TransactionsChanged.toReceiveAddress(
addressType = addressType,
)

private data class HwWatcherEventOutcome(
val walletId: String,
val observedTxIds: List<String>,
val receivedTxs: List<HwWalletReceivedTx> = emptyList(),
)

private data class HwSnapshot(
val activities: ImmutableList<Activity>,
val transactionDetails: ImmutableList<TransactionDetails>,
Expand Down
Loading