From 75619973c12af7a5aa45fe1bd1faf6426856cc6e Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 08:51:23 -0500 Subject: [PATCH 01/14] fix: never drop a hardware broadcast after a timeout Co-Authored-By: Claude Opus 5.5 --- .../screens/wallets/send/HwSendViewModel.kt | 47 +++++++++---------- .../wallets/send/HwSendViewModelTest.kt | 38 +++++++++++++++ 2 files changed, 61 insertions(+), 24 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index 3cd0b4f7d3..7823e0892e 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -64,7 +64,6 @@ class HwSendViewModel @Inject constructor( const val TAG = "HwSendViewModel" val COMPOSE_TIMEOUT = 45.seconds val SIGN_TIMEOUT = 120.seconds - val BROADCAST_TIMEOUT = 120.seconds } val wallets: StateFlow> @@ -241,34 +240,34 @@ class HwSendViewModel @Inject constructor( } } _uiState.update { it.copy(isBroadcastUnresolved = true) } - return withTimeout(BROADCAST_TIMEOUT) { - val request = payment.request - val requestId = request.paymentRequestId - if (requestId == null) { + // No deadline: the broadcast runs to its end on the core queue, so one could only discard the outcome of a + // payment that went out. The sheet stays unresolved until it answers. + val request = payment.request + val requestId = request.paymentRequestId + val outcome = if (requestId == null) { + pendingBroadcast = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) + hwWalletRepo.broadcastFunding(payment.signedTx, request.paymentDeadlineAt) + } else { + hwWalletRepo.broadcastFundingAtBoundary(payment.signedTx, request.paymentDeadlineAt) { + check( + paykitPaymentProofRepo.markHardwareOnchainDispatch( + requestId, + request.walletId, + SignedTransactionId.fromHex(payment.signedTx.serializedTx), + request.paymentIdentity, + request.address, + request.amountSats, + ) + ) { "Original hardware payment is no longer eligible for dispatch" } pendingBroadcast = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) - hwWalletRepo.broadcastFunding(payment.signedTx, request.paymentDeadlineAt) - } else { - hwWalletRepo.broadcastFundingAtBoundary(payment.signedTx, request.paymentDeadlineAt) { - check( - paykitPaymentProofRepo.markHardwareOnchainDispatch( - requestId, - request.walletId, - SignedTransactionId.fromHex(payment.signedTx.serializedTx), - request.paymentIdentity, - request.address, - request.amountSats, - ) - ) { "Original hardware payment is no longer eligible for dispatch" } - pendingBroadcast = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) - } } - }.getOrElse { error -> + } + return outcome.getOrElse { error -> if (generateSequence(error) { it.cause }.any { it is ServiceError.PaymentDeadlineExpired }) { - val request = payment.request - val cleared = request.paymentRequestId?.let { requestId -> + val cleared = requestId?.let { !payment.hasAttemptedBroadcast && paykitPaymentProofRepo.clearHardwareOnchainCandidateBeforeDispatch( - requestId, request.walletId, SignedTransactionId.fromHex(payment.signedTx.serializedTx), + it, request.walletId, SignedTransactionId.fromHex(payment.signedTx.serializedTx), request.paymentIdentity, request.address, request.amountSats, payment.hasAttemptedBroadcast, ) } ?: !payment.hasAttemptedBroadcast diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt index 0fef39c0a1..849b52dc7d 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt @@ -10,6 +10,7 @@ import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch +import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.withContext @@ -499,6 +500,43 @@ class HwSendViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.isSigning) } + @Test + fun `a broadcast that succeeds after two minutes is recorded as sent without a retry prompt`() = test { + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + val broadcastResult = CompletableDeferred>() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { + withContext(NonCancellable) { broadcastResult.await() } + } + + sut.signAndBroadcast(request()) + advanceTimeBy(121.seconds) + runCurrent() + assertTrue(sut.uiState.value.isBroadcastUnresolved) + assertFalse(sut.uiState.value.canLeave) + + broadcastResult.complete(Result.success(fixture.broadcast)) + advanceUntilIdle() + toastJob.cancel() + + assertTrue(toasts.isEmpty()) + verify(activityService).createSentOnchainActivityFromSendResult( + txid = fixture.broadcast.txId, + address = ADDRESS, + amount = AMOUNT_SATS, + fee = fixture.broadcast.miningFeeSats, + feeRate = fixture.broadcast.feeRate, + isTransfer = false, + channelId = null, + walletId = WALLET_ID, + ) + assertEquals(fixture.broadcast.txId, sut.results.first().txId) + verify(hwWalletRepo, times(1)).signFunding(WALLET_ID, fixture.funding) + verify(hwWalletRepo, times(1)).broadcastFunding(fixture.signedTx) + } + @Test fun `broadcast failure warns the payment was not confirmed`() = test { val toasts = mutableListOf() From 83af398895db70894a7134f1aa0516d295f7f5d7 Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 08:56:24 -0500 Subject: [PATCH 02/14] fix: keep a hardware send unresolved after an unknown broadcast Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/ext/BroadcastExceptionExt.kt | 13 +- .../screens/wallets/send/HwSendSignScreen.kt | 4 + .../screens/wallets/send/HwSendViewModel.kt | 129 ++++++- .../screens/wallets/send/SendPendingScreen.kt | 27 +- .../java/to/bitkit/ui/sheets/SendSheet.kt | 29 +- app/src/main/res/values-ar/strings.xml | 2 + app/src/main/res/values-b+es+419/strings.xml | 2 + app/src/main/res/values-ca/strings.xml | 2 + app/src/main/res/values-cs/strings.xml | 2 + app/src/main/res/values-de/strings.xml | 2 + app/src/main/res/values-el/strings.xml | 2 + app/src/main/res/values-es-rES/strings.xml | 2 + app/src/main/res/values-es/strings.xml | 2 + app/src/main/res/values-fr/strings.xml | 2 + app/src/main/res/values-it/strings.xml | 2 + app/src/main/res/values-nl/strings.xml | 2 + app/src/main/res/values-pl/strings.xml | 2 + app/src/main/res/values-pt-rBR/strings.xml | 2 + app/src/main/res/values-pt/strings.xml | 2 + app/src/main/res/values-ru/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + .../bitkit/ext/BroadcastExceptionExtTest.kt | 26 ++ .../wallets/send/HwSendViewModelTest.kt | 361 ++++++++++++++++-- 23 files changed, 570 insertions(+), 51 deletions(-) diff --git a/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt b/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt index 076410ed36..4e361a4ba8 100644 --- a/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt +++ b/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt @@ -16,7 +16,18 @@ fun Throwable.isDefiniteHardwarePreBroadcastFailure(): Boolean = generateSequenc it is BroadcastException.InvalidHex || it is BroadcastException.InvalidTransaction } -// A recognized node refusal permits leaving the sheet, but never proves non-delivery. +/** + * Whether a hardware broadcast proves it sent nothing: core could not decode the transaction or connect to the + * server, or the node refused it. Any other failure may follow the write, so the payment may still confirm. A refusal + * is proof only when no earlier broadcast of the same bytes may have reached the network. + */ +fun Throwable.isHardwareBroadcastNotSent(): Boolean = isHardwareBroadcastRefusalForNavigation() || + generateSequence(this) { it.cause }.any { + it is BroadcastException.ElectrumException && it.errorDetails.startsWith("Failed to connect to Electrum: ") + } + +// A recognized node refusal permits leaving the sheet. It never proves that an earlier, uncertain dispatch of the +// same bytes was not delivered, so it never releases a Shop payment's guard. fun Throwable.isHardwareBroadcastRefusalForNavigation(): Boolean = isDefiniteHardwarePreBroadcastFailure() || generateSequence(this) { it.cause }.any { if (it !is BroadcastException.ElectrumException) return@any false diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt index 703136b785..a3f69b533e 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt @@ -56,6 +56,7 @@ fun HwSendSignScreen( beginPaymentSubmission: () -> (() -> Unit), paymentDeadlineAt: Instant?, onBack: () -> Unit, + onPaymentPending: (HwSendResult) -> Unit, ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() val wallets by viewModel.wallets.collectAsStateWithLifecycle() @@ -85,6 +86,9 @@ fun HwSendSignScreen( } // Without this the sheet's NavHost pops the route itself, ignoring the guard and skipping onBack BackHandler(onBack = onBackRequest) + uiState.unresolvedSend?.let { send -> + LaunchedEffect(send) { onPaymentPending(send) } + } val signAndBroadcast = { viewModel.signAndBroadcast( diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index 7823e0892e..1e25db9306 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -4,6 +4,7 @@ import android.content.Context import androidx.compose.runtime.Immutable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import com.synonym.bitkitcore.Activity import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.collections.immutable.ImmutableList @@ -14,11 +15,13 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeout import to.bitkit.R import to.bitkit.ext.isBroadcastConnectivityFailure +import to.bitkit.ext.isHardwareBroadcastNotSent import to.bitkit.ext.isHardwareBroadcastRefusalForNavigation import to.bitkit.ext.isHwDeviceBusy import to.bitkit.ext.isHwFirmwareError @@ -76,6 +79,7 @@ class HwSendViewModel @Inject constructor( val results = pendingResult.filterNotNull() private var pendingBroadcast: PendingHwSendBroadcast? = null + private var unresolvedSendWatch: Job? = null private var signingWalletId: String? = null private var signingJob: Job? = null private var signingAttempt = 0 @@ -100,6 +104,16 @@ class HwSendViewModel @Inject constructor( val finishSubmission = beginPaymentSubmission() try { runCatching { + // A send whose broadcast may have gone out is only ever broadcast again as the same bytes, and + // nothing is signed beside it + if (pendingBroadcast?.isOutcomeUnknown == true) { + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.common__error), + description = context.getString(R.string.wallet__send_pending__blocked_new_send), + ) + return@runCatching + } if (pendingBroadcast?.matches(request) == false) { ToastEventBus.send( type = Toast.ToastType.ERROR, @@ -244,14 +258,12 @@ class HwSendViewModel @Inject constructor( // payment that went out. The sheet stays unresolved until it answers. val request = payment.request val requestId = request.paymentRequestId - val outcome = if (requestId == null) { - pendingBroadcast = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) - hwWalletRepo.broadcastFunding(payment.signedTx, request.paymentDeadlineAt) - } else { - hwWalletRepo.broadcastFundingAtBoundary(payment.signedTx, request.paymentDeadlineAt) { + var isDispatched = false + val outcome = hwWalletRepo.broadcastFundingAtBoundary(payment.signedTx, request.paymentDeadlineAt) { + requestId?.let { check( paykitPaymentProofRepo.markHardwareOnchainDispatch( - requestId, + it, request.walletId, SignedTransactionId.fromHex(payment.signedTx.serializedTx), request.paymentIdentity, @@ -259,8 +271,9 @@ class HwSendViewModel @Inject constructor( request.amountSats, ) ) { "Original hardware payment is no longer eligible for dispatch" } - pendingBroadcast = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) } + isDispatched = true + pendingBroadcast = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) } return outcome.getOrElse { error -> if (generateSequence(error) { it.cause }.any { it is ServiceError.PaymentDeadlineExpired }) { @@ -277,10 +290,92 @@ class HwSendViewModel @Inject constructor( onPaymentDeadlineExpired(unresolved) return null } + // A failure before the dispatch sent nothing, while one after it may follow the write + if (requestId == null && isDispatched && !error.isHardwareBroadcastNotSent()) { + holdUnresolvedBroadcast(payment) + } throw error } } + private fun holdUnresolvedBroadcast(payment: PendingHwSendBroadcast) { + val held = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false, isOutcomeUnknown = true) + pendingBroadcast = held + val request = held.request + val txId = SignedTransactionId.fromHex(held.signedTx.serializedTx) + val send = HwSendResult(request.walletId, txId, request.amountSats, paymentIdentity = request.paymentIdentity) + _uiState.update { it.copy(unresolvedSend = send) } + unresolvedSendWatch = viewModelScope.launch { + hwWalletRepo.activities.first { activities -> + activities.filterIsInstance().any { + it.v1.walletId == send.walletId && it.v1.txId.equals(send.txId, ignoreCase = true) + } + } + completeUnresolvedSend(held, send) + } + } + + /** + * Broadcasts the signed bytes of a send whose broadcast may have gone out once more, for when that broadcast never + * reached the server. Any failure keeps the send held, since the first broadcast may still confirm. + */ + fun retryUnresolvedSend() { + val payment = pendingBroadcast?.takeIf { it.isOutcomeUnknown } ?: return + val send = _uiState.value.unresolvedSend ?: return + if (_uiState.value.isRetryingUnresolvedSend) return + _uiState.update { it.copy(isRetryingUnresolvedSend = true) } + viewModelScope.launch { + try { + hwWalletRepo.broadcastFunding(payment.signedTx) + .onSuccess { completeUnresolvedSend(payment, send) } + .onFailure { + if (pendingBroadcast !== payment) return@onFailure + // A refusal now does not prove the first broadcast was not delivered, so the send stays held + val description = if (it.isHardwareBroadcastRefusalForNavigation()) { + R.string.hardware__send_broadcast_refused_text + } else { + R.string.hardware__send_broadcast_failed_text + } + ToastEventBus.send( + type = Toast.ToastType.WARNING, + title = context.getString(R.string.hardware__send_broadcast_failed_title), + description = context.getString(description), + ) + } + } finally { + _uiState.update { it.copy(isRetryingUnresolvedSend = false) } + } + } + } + + /** + * Refuses a new hardware send while an earlier one may have gone out, saying so, and returns that earlier send to + * finish first; null when there is none. + */ + fun refuseNewSend(): HwSendResult? { + val send = _uiState.value.unresolvedSend ?: return null + viewModelScope.launch { + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.common__error), + description = context.getString(R.string.wallet__send_pending__blocked_new_send), + ) + } + return send + } + + private suspend fun completeUnresolvedSend(payment: PendingHwSendBroadcast, send: HwSendResult) { + if (pendingBroadcast !== payment) return + // Known to be sent now, so neither the wallet's observation nor a retry completes it a second time + pendingBroadcast = payment.copy(isOutcomeUnknown = false) + val signedTx = payment.signedTx + val result = HwFundingBroadcastResult(send.txId, signedTx.miningFeeSats, signedTx.feeRate, signedTx.totalSpent) + runSuspendCatching { persistResult(payment.request, result) } + .onFailure { Logger.error("Failed to persist hardware send result", it, context = TAG) } + _uiState.update { it.copy(unresolvedSend = null) } + pendingResult.update { send } + } + fun submitPassphrase( walletId: String, passphrase: String, @@ -334,8 +429,12 @@ class HwSendViewModel @Inject constructor( signingJob?.cancel() signingJob = null signingAttempt++ - // A refused Shop payment may leave the sheet, but its signed operation stays guarded. - if (pendingBroadcast?.let { it.request.paymentRequestId != null && it.hasAttemptedBroadcast } != true) { + // A refused Shop payment may leave the sheet, but its signed operation stays guarded, as does a send whose + // broadcast may have gone out. + if (pendingBroadcast?.let { + it.isOutcomeUnknown || it.request.paymentRequestId != null && it.hasAttemptedBroadcast + } != true + ) { pendingBroadcast = null } _uiState.update { @@ -374,6 +473,8 @@ class HwSendViewModel @Inject constructor( } fun completeBroadcast() { + unresolvedSendWatch?.cancel() + unresolvedSendWatch = null pendingBroadcast = null signingWalletId = null pendingResult.update { null } @@ -381,6 +482,7 @@ class HwSendViewModel @Inject constructor( it.copy( hasPendingBroadcast = false, isBroadcastUnresolved = false, + unresolvedSend = null, ) } } @@ -497,6 +599,11 @@ class HwSendViewModel @Inject constructor( _uiState.update { it.copy(isBroadcastUnresolved = retainedShopPayment && pendingBroadcast?.blocksNavigation == true) } + // The payment shows as pending until the wallet sees it, so it is not offered to be tried again + if (pendingBroadcast?.isOutcomeUnknown == true) { + Logger.warn("Held hardware send of '$walletId' after an unknown broadcast outcome", context = TAG) + return + } when { error.isHwUserCancellation() -> { Logger.info("Hardware send cancelled on device for '$walletId'", context = TAG) @@ -556,6 +663,9 @@ data class HwSendUiState( val isBroadcastUnresolved: Boolean = false, val isPassphraseRequired: Boolean = false, val isVerifyingPassphrase: Boolean = false, + /** A send whose broadcast may have gone out: it is pending until it is sent, and nothing is signed beside it. */ + val unresolvedSend: HwSendResult? = null, + val isRetryingUnresolvedSend: Boolean = false, ) { /** * Whether the sign sheet may be dismissed. Connecting or unlocking can be abandoned, and leaving @@ -591,6 +701,7 @@ private data class PendingHwSendBroadcast( val isPreparedForBroadcast: Boolean = false, val hasAttemptedBroadcast: Boolean = false, val isRefusedForNavigation: Boolean = false, + val isOutcomeUnknown: Boolean = false, ) { val blocksNavigation: Boolean get() = hasAttemptedBroadcast && !isRefusedForNavigation diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt index c32f08e225..4c29505dfa 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt @@ -97,6 +97,9 @@ fun SendPendingScreen( onNavigateToPin: () -> Unit, beginPaymentReview: () -> (() -> Unit), onRecoveredTransfer: (OnchainSendAttempt) -> Unit = {}, + canRetryHardwareSend: Boolean = false, + isRetryingHardwareSend: Boolean = false, + onRetryHardwareSend: () -> Unit = {}, ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() @@ -166,6 +169,9 @@ fun SendPendingScreen( canAbandon = uiState.abandonableAttempt != null, isAbandoning = uiState.isAbandoning, onAbandon = { showAbandonConfirmation = true }, + canRetryHardwareSend = canRetryHardwareSend, + isRetryingHardwareSend = isRetryingHardwareSend, + onRetryHardwareSend = onRetryHardwareSend, ) } } @@ -407,6 +413,9 @@ internal fun SendPendingContent( canAbandon: Boolean = false, isAbandoning: Boolean = false, onAbandon: () -> Unit = {}, + canRetryHardwareSend: Boolean = false, + isRetryingHardwareSend: Boolean = false, + onRetryHardwareSend: () -> Unit = {}, ) { Column( modifier = modifier @@ -437,10 +446,10 @@ internal fun SendPendingContent( VerticalSpacer(32.dp) BodyM( stringResource( - if (isOnchain) { - R.string.wallet__send_pending__onchain_description - } else { - R.string.wallet__send_pending__description + when { + canRetryHardwareSend -> R.string.wallet__send_pending__hardware_description + isOnchain -> R.string.wallet__send_pending__onchain_description + else -> R.string.wallet__send_pending__description }, ), color = Colors.White64, @@ -464,6 +473,16 @@ internal fun SendPendingContent( VerticalSpacer(16.dp) } VerticalSpacer(16.dp) + if (canRetryHardwareSend) { + SecondaryButton( + text = stringResource(R.string.wallet__send_pending__retry_title), + isLoading = isRetryingHardwareSend, + enabled = !isRetryingHardwareSend, + onClick = onRetryHardwareSend, + modifier = Modifier.fillMaxWidth(), + ) + VerticalSpacer(16.dp) + } if (canRetry) { SecondaryButton( text = stringResource(R.string.wallet__send_pending__retry_title), diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 7906998ac3..ae0ecbe4dd 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -66,6 +66,7 @@ import to.bitkit.ui.screens.subscriptions.SubscriptionFirstPaymentProgress import to.bitkit.ui.screens.subscriptions.SubscriptionSuccess import to.bitkit.ui.screens.subscriptions.contactFor import to.bitkit.ui.screens.wallets.send.AddTagScreen +import to.bitkit.ui.screens.wallets.send.HwSendResult import to.bitkit.ui.screens.wallets.send.HwSendSignScreen import to.bitkit.ui.screens.wallets.send.HwSendViewModel import to.bitkit.ui.screens.wallets.send.PIN_CHECK_RESULT_KEY @@ -133,6 +134,16 @@ internal fun NavController.navigateToSendPending(route: SendRoute.Pending) { navigateTo(route) { popUpTo(graph.id) { inclusive = true } } } +private fun NavController.navigateToHardwareSendPending(send: HwSendResult) = navigateToSendPending( + SendRoute.Pending( + paymentHash = send.txId, + amount = send.amountSats.toLong(), + observeResolution = false, + isOnchain = true, + walletId = send.walletId, + ) +) + @Composable @Suppress("CyclomaticComplexMethod") fun SendSheet( @@ -298,7 +309,16 @@ fun SendSheet( } navController.navigateTo(it.route) { popUpTo(replaced) { inclusive = true } } } - is SendEffect.NavigateToHardwareSign -> navController.navigateTo(SendRoute.HardwareSign) + is SendEffect.NavigateToHardwareSign -> { + // A send whose broadcast may have gone out is finished before a new one is signed + val unresolvedSend = hwSendViewModel.refuseNewSend() + if (unresolvedSend == null) { + navController.navigateTo(SendRoute.HardwareSign) + } else { + appViewModel.onHardwareSignCancelled() + navController.navigateToHardwareSendPending(unresolvedSend) + } + } is SendEffect.PopBack -> navController.popBackStack(it.route, inclusive = false) is SendEffect.PaymentSuccess -> { val details = appViewModel.successSendUiState.value @@ -571,6 +591,7 @@ fun SendSheet( appViewModel.onHardwareSignCancelled() if (!navController.popBackStack()) appViewModel.hideSheet() }, + onPaymentPending = { navController.navigateToHardwareSendPending(it) }, ) } composableWithDefaultTransitions { @@ -718,6 +739,7 @@ fun SendSheet( composableWithDefaultTransitions { val route = it.toRoute() val sendUiState by appViewModel.sendUiState.collectAsStateWithLifecycle() + val hwSendUiState by hwSendViewModel.uiState.collectAsStateWithLifecycle() SendPendingScreen( savedStateHandle = it.savedStateHandle, onNavigateToPin = { navController.navigateTo(SendRoute.RecoveryPinCheck) }, @@ -767,6 +789,11 @@ fun SendSheet( onClose = { appViewModel.hideSheet() }, onViewDetails = { rawId -> appViewModel.navigateToActivity(rawId, route.walletId) }, viewModel = hiltViewModel(), + canRetryHardwareSend = hwSendUiState.unresolvedSend?.let { send -> + send.walletId == route.walletId && send.txId.equals(route.paymentHash, ignoreCase = true) + } == true, + isRetryingHardwareSend = hwSendUiState.isRetryingUnresolvedSend, + onRetryHardwareSend = hwSendViewModel::retryUnresolvedSend, ) } composableWithDefaultTransitions { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index c8973f2586..3f49fcb8a8 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1190,6 +1190,7 @@ تعذر البحث عن محافظ الأجهزة. تحقق من اتصالك وحاول مرة أخرى. تحقق من اتصالك وحاول مرة أخرى. الدفعة غير مؤكدة + رفضت الشبكة هذه المعاملة، على سبيل المثال لأن عملاتها أُنفقت بالفعل. تبقى الدفعة معلّقة حتى ترى محفظتك المعاملة. إلى العنوان (أكّد على الجهاز) يمكن لـ Trezor الإرسال إلى عنوان Bitcoin فقط من هذه المحفظة. يمكن لـ Jade الإرسال إلى عنوان Bitcoin فقط من هذه المحفظة. @@ -1610,6 +1611,7 @@ من لم يتم إرسال الدفعة الجديدة. أكمل الدفعة السابقة قبل المحاولة مرة أخرى. تستغرق هذه الدفعة وقتًا أطول قليلاً من المتوقع. يمكنك متابعة استخدام Bitkit. + تعذّر على Bitkit التأكد من أن الشبكة استلمت هذه الدفعة. تكتمل الدفعة بمجرد أن ترى محفظتك المعاملة. إن لم تظهر، استخدم «إعادة محاولة الدفعة الأصلية» لإرسال المعاملة الموقّعة نفسها مرة أخرى. تبقى مدفوعات محفظة الأجهزة الأخرى محظورة حتى ذلك الحين. الدفعة معلقة نتيجة المعاملة لم تُحسم بعد. تحقق من حالتها قبل المحاولة مرة أخرى. تبقى المدفوعات الأخرى محظورة. إن توفر، استخدم «إعادة محاولة الدفعة الأصلية» لتفويض رسوم للدفعة نفسها. تم رفض البث: %1$s diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index f62df577aa..8e8d6fd9e4 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1006,6 +1006,7 @@ Saldo de reserva Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero revisa la red y luego devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. Este pago está tardando un poco más de lo esperado. Puede seguir utilizando Bitkit. + Bitkit no pudo confirmar que la red recibiera este pago. Se completará cuando su billetera vea la transacción. Si no aparece, use Reintentar pago original para enviar de nuevo la misma transacción firmada. Los demás pagos con billetera de hardware siguen bloqueados hasta entonces. Pago pendiente QuickPay Pagando\n<accent>factura...</accent> @@ -1222,6 +1223,7 @@ No se pudieron buscar billeteras de hardware. Revise su conexión y vuelva a intentarlo. Revise su conexión y vuelva a intentarlo. Pago no confirmado + La red rechazó esta transacción, por ejemplo porque sus monedas ya se gastaron. El pago sigue pendiente hasta que su billetera vea la transacción. A LA DIRECCIÓN (CONFIRME EN EL DISPOSITIVO) Desde esta billetera, Trezor solo puede enviar a una dirección de Bitcoin. Desde esta billetera, Jade solo puede enviar a una dirección de Bitcoin. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index f87eac631f..8a8b9c43b1 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1215,6 +1215,7 @@ No s\'han pogut cercar carteres de maquinari. Comprova la connexió i torna-ho a provar. Comprova la connexió i torna-ho a provar. Pagament no confirmat + La xarxa ha rebutjat aquesta transacció, per exemple perquè les seves monedes ja s\'han gastat. El pagament continua pendent fins que la teva cartera vegi la transacció. A L\'ADREÇA (CONFIRMA AL DISPOSITIU) Des d\'aquesta cartera, Trezor només pot enviar a una adreça Bitcoin. Des d\'aquesta cartera, Jade només pot enviar a una adreça Bitcoin. @@ -1610,6 +1611,7 @@ Des de El pagament nou no s\'ha enviat. Finalitza el pagament anterior abans de tornar-ho a provar. Aquest pagament està trigant una mica més del previst. Pots continuar utilitzant Bitkit. + Bitkit no ha pogut confirmar que la xarxa hagi rebut aquest pagament. Es completarà quan la teva cartera vegi la transacció. Si no apareix, utilitza Reintentar el pagament original per tornar a enviar la mateixa transacció signada. Els altres pagaments amb cartera de maquinari continuen bloquejats fins aleshores. El resultat de la transacció està sense resoldre. Comprova\'n l\'estat abans de tornar-ho a provar. Els altres pagaments continuen bloquejats. Si està disponible, utilitza Reintentar el pagament original per autoritzar una tarifa per al mateix pagament. Difusió rebutjada: %1$s Autoritzar el reintent diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index a6b2454328..6801d093c6 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1004,6 +1004,7 @@ Zůstatek rezervy Převody na útratový zůstatek už nejsou dostupné. Bitkit nejprve zkontroluje síť a pak vrátí mince tohoto převodu do vaší peněženky, aby se původní převod nikdy nepotvrdil. Stojí to síťový poplatek. Tato platba trvá o něco déle, než se očekávalo. Bitkit můžete používat i nadále. + Bitkit nemohl potvrdit, že síť tuto platbu přijala. Platba se dokončí, jakmile vaše peněženka transakci uvidí. Pokud se neobjeví, použijte Zopakovat původní platbu a odešlete stejnou podepsanou transakci znovu. Ostatní platby z hardwarové peněženky do té doby zůstávají zablokované. Platba čeká na vyřízení QuickPay Placení\n<accent>faktury...</accent> @@ -1220,6 +1221,7 @@ Hardwarové peněženky se nepodařilo vyhledat. Zkontrolujte připojení a zkuste to znovu. Zkontrolujte připojení a zkuste to znovu. Platba nebyla potvrzena + Síť tuto transakci odmítla, například proto, že její mince už byly utraceny. Platba zůstává nevyřízená, dokud ji vaše peněženka neuvidí. NA ADRESU (POTVRĎTE NA ZAŘÍZENÍ) Trezor může z této peněženky posílat pouze na bitcoinovou adresu. Jade může z této peněženky posílat pouze na bitcoinovou adresu. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index d8a0d88b77..7e856baeb2 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -853,6 +853,7 @@ Verfügbar (ausgeben) Reserve-Saldo Diese Zahlung dauert länger als erwartet. Du kannst Bitkit weiterhin verwenden. + Bitkit konnte nicht bestätigen, dass das Netzwerk diese Zahlung erhalten hat. Sie wird abgeschlossen, sobald dein Wallet die Transaktion sieht. Erscheint sie nicht, nutze „Ursprüngliche Zahlung wiederholen“, um dieselbe signierte Transaktion erneut zu senden. Andere Hardware-Wallet-Zahlungen bleiben bis dahin blockiert. Zahlung ausstehend Der maximal auszahlbare Betrag ist etwas niedriger, da eine Reserve erforderlich ist. Bestätigen @@ -1217,6 +1218,7 @@ Die Suche nach Hardware-Wallets ist fehlgeschlagen. Überprüfe deine Verbindung und versuche es erneut. Überprüfe deine Verbindung und versuche es erneut. Zahlung nicht bestätigt + Das Netzwerk hat diese Transaktion abgelehnt, zum Beispiel weil ihre Coins bereits ausgegeben wurden. Die Zahlung bleibt ausstehend, bis dein Wallet die Transaktion sieht. AN ADRESSE (AM GERÄT BESTÄTIGEN) Trezor kann von diesem Wallet nur an eine Bitcoin-Adresse senden. Jade kann von diesem Wallet nur an eine Bitcoin-Adresse senden. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 5b589e5087..984ffbfc51 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1196,6 +1196,7 @@ Δεν ήταν δυνατή η αναζήτηση πορτοφολιών υλικού. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. Η πληρωμή δεν επιβεβαιώθηκε + Το δίκτυο απέρριψε αυτή τη συναλλαγή, για παράδειγμα επειδή τα νομίσματά της έχουν ήδη δαπανηθεί. Η πληρωμή παραμένει σε εκκρεμότητα μέχρι το πορτοφόλι σου να δει τη συναλλαγή. ΠΡΟΣ ΔΙΕΥΘΥΝΣΗ (ΕΠΙΒΕΒΑΙΩΣΗ ΣΤΗ ΣΥΣΚΕΥΗ) Το Trezor μπορεί να στείλει μόνο σε διεύθυνση Bitcoin από αυτό το πορτοφόλι. Το Jade μπορεί να στείλει μόνο σε διεύθυνση Bitcoin από αυτό το πορτοφόλι. @@ -1607,6 +1608,7 @@ Από Η νέα πληρωμή δεν στάλθηκε. Ολοκλήρωσε την προηγούμενη πληρωμή πριν δοκιμάσεις ξανά. Αυτή η πληρωμή διαρκεί λίγο περισσότερο από το αναμενόμενο. Μπορείς να συνεχίσεις να χρησιμοποιείς το Bitkit. + Το Bitkit δεν μπόρεσε να επιβεβαιώσει ότι το δίκτυο έλαβε αυτή την πληρωμή. Θα ολοκληρωθεί μόλις το πορτοφόλι σου δει τη συναλλαγή. Αν δεν εμφανιστεί, χρησιμοποίησε την Επανάληψη αρχικής πληρωμής για να στείλεις ξανά την ίδια υπογεγραμμένη συναλλαγή. Οι άλλες πληρωμές από πορτοφόλι υλικού παραμένουν μπλοκαρισμένες μέχρι τότε. Πληρωμή σε εκκρεμότητα Το αποτέλεσμα της συναλλαγής δεν έχει επιλυθεί. Έλεγξε την κατάστασή της πριν δοκιμάσεις ξανά. Οι άλλες πληρωμές παραμένουν μπλοκαρισμένες. Αν είναι διαθέσιμο, χρησιμοποίησε την Επανάληψη αρχικής πληρωμής για να εγκρίνεις τέλος για την ίδια πληρωμή. Η μετάδοση απορρίφθηκε: %1$s diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 34faa374a7..5e60195462 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1213,6 +1213,7 @@ No se pudieron buscar monederos de hardware. Comprueba tu conexión e inténtalo de nuevo. Comprueba tu conexión e inténtalo de nuevo. Pago no confirmado + La red ha rechazado esta transacción, por ejemplo porque sus monedas ya se han gastado. El pago sigue pendiente hasta que tu monedero vea la transacción. A LA DIRECCIÓN (CONFIRMA EN EL DISPOSITIVO) Trezor solo puede enviar a una dirección de Bitcoin desde este monedero. Jade solo puede enviar a una dirección de Bitcoin desde este monedero. @@ -1609,6 +1610,7 @@ Desde El nuevo pago no se envió. Finaliza el pago anterior antes de volver a intentarlo. Este pago está tardando un poco más de lo esperado. Puedes seguir usando Bitkit. + Bitkit no pudo confirmar que la red recibiera este pago. Se completará cuando tu monedero vea la transacción. Si no aparece, usa Reintentar el pago original para enviar de nuevo la misma transacción firmada. Los demás pagos con monedero de hardware siguen bloqueados hasta entonces. Pago pendiente El resultado de la transacción está sin resolver. Comprueba su estado antes de volver a intentarlo. Los demás pagos siguen bloqueados. Si está disponible, usa Reintentar el pago original para autorizar una comisión para el mismo pago. Difusión rechazada: %1$s diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index b9c24c4522..57363cc6ba 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1211,6 +1211,7 @@ No se pudieron buscar monederos de hardware. Compruebe su conexión e inténtelo de nuevo. Compruebe su conexión e inténtelo de nuevo. Pago no confirmado + La red ha rechazado esta transacción, por ejemplo porque sus monedas ya se han gastado. El pago sigue pendiente hasta que su monedero vea la transacción. A LA DIRECCIÓN (CONFIRME EN EL DISPOSITIVO) Trezor solo puede enviar a una dirección de Bitcoin desde este monedero. Jade solo puede enviar a una dirección de Bitcoin desde este monedero. @@ -1609,6 +1610,7 @@ Desde El nuevo pago no se envió. Finalice el pago anterior antes de volver a intentarlo. Este pago está tardando un poco más de lo esperado. Puede seguir usando Bitkit. + Bitkit no pudo confirmar que la red recibiera este pago. Se completará cuando su monedero vea la transacción. Si no aparece, use Reintentar el pago original para enviar de nuevo la misma transacción firmada. Los demás pagos con monedero de hardware siguen bloqueados hasta entonces. Pago pendiente El resultado de la transacción está sin resolver. Compruebe su estado antes de volver a intentarlo. Los demás pagos siguen bloqueados. Si está disponible, use Reintentar el pago original para autorizar una comisión para el mismo pago. Difusión rechazada: %1$s diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 504d48a804..589fb28c38 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -854,6 +854,7 @@ Disponible (dépenses) Solde Réserve Ce paiement prend un peu plus de temps que prévu. Vous pouvez continuer à utiliser Bitkit. + Bitkit n\'a pas pu confirmer que le réseau a reçu ce paiement. Il sera finalisé dès que votre portefeuille verra la transaction. Si elle n\'apparaît pas, utilisez Réessayer le paiement d\'origine pour renvoyer la même transaction signée. Les autres paiements avec un portefeuille matériel restent bloqués d\'ici là. Paiement en attente Le montant maximum pouvant être dépensé est un peu moins élevé en raison d\'un solde de Réserve requis. Confirmer @@ -1216,6 +1217,7 @@ Impossible de rechercher des portefeuilles matériels. Vérifiez votre connexion et réessayez. Vérifiez votre connexion et réessayez. Paiement non confirmé + Le réseau a refusé cette transaction, par exemple parce que ses fonds ont déjà été dépensés. Le paiement reste en attente jusqu\'à ce que votre portefeuille voie la transaction. VERS L\'ADRESSE (CONFIRMER SUR L\'APPAREIL) Trezor ne peut envoyer qu\'à une adresse Bitcoin depuis ce portefeuille. Jade ne peut envoyer qu\'à une adresse Bitcoin depuis ce portefeuille. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index bbe3915683..7c4ace6275 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1002,6 +1002,7 @@ Saldo di Riserva I trasferimenti al saldo di spesa non sono più disponibili. Bitkit controlla prima la rete, poi rimanda le monete di questo trasferimento al tuo wallet, così il trasferimento originale non potrà mai essere confermato. Questo costa una commissione di rete. Questo pagamento sta richiedendo un po\' più tempo del previsto. Puoi continuare a utilizzare Bitkit. + Bitkit non è riuscito a confermare che la rete abbia ricevuto questo pagamento. Si completerà non appena il tuo wallet vedrà la transazione. Se non compare, usa Riprova pagamento originale per inviare di nuovo la stessa transazione firmata. Gli altri pagamenti con hardware wallet restano bloccati fino ad allora. Pagamento in sospeso QuickPay Pagamento\n<accent>fattura...</accent> @@ -1218,6 +1219,7 @@ Impossibile cercare hardware wallet. Controlla la connessione e riprova. Controlla la connessione e riprova. Pagamento non confermato + La rete ha rifiutato questa transazione, ad esempio perché le sue monete sono già state spese. Il pagamento resta in sospeso finché il tuo wallet non vede la transazione. ALL\'INDIRIZZO (CONFERMA SUL DISPOSITIVO) Da questo wallet, Trezor può inviare solo a un indirizzo Bitcoin. Da questo wallet, Jade può inviare solo a un indirizzo Bitcoin. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 9e476721ba..77fa39355b 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -997,6 +997,7 @@ Reservesaldo Overboekingen naar je bestedingssaldo zijn niet meer beschikbaar. Bitkit controleert eerst het netwerk en stuurt de munten van deze overboeking dan terug naar je wallet, zodat de oorspronkelijke overboeking nooit bevestigd wordt. Dit kost netwerkkosten. Deze betaling duurt iets langer dan verwacht. U kunt Bitkit blijven gebruiken. + Bitkit kon niet bevestigen dat het netwerk deze betaling heeft ontvangen. De betaling wordt voltooid zodra uw wallet de transactie ziet. Verschijnt deze niet, gebruik dan ‘Oorspronkelijke betaling opnieuw proberen’ om dezelfde ondertekende transactie opnieuw te verzenden. Andere betalingen met een hardwarewallet blijven tot dan geblokkeerd. Betaling Onderweg QuickPay Factuur\n<accent>betalen...</accent> @@ -1213,6 +1214,7 @@ Kon niet zoeken naar hardwarewallets. Controleer uw verbinding en probeer het opnieuw. Controleer uw verbinding en probeer het opnieuw. Betaling niet bevestigd + Het netwerk heeft deze transactie geweigerd, bijvoorbeeld omdat de munten ervan al zijn uitgegeven. De betaling blijft in behandeling totdat uw wallet de transactie ziet. NAAR ADRES (BEVESTIG OP APPARAAT) Trezor kan vanuit deze wallet alleen naar een Bitcoin-adres versturen. Jade kan vanuit deze wallet alleen naar een Bitcoin-adres versturen. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index db3199891a..43547ae262 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -856,6 +856,7 @@ Dostępne (na wydawanie) Saldo rezerwy Ta płatność trwa nieco dłużej niż oczekiwano. Możesz kontynuować korzystanie z Bitkit. + Bitkit nie mógł potwierdzić, że sieć otrzymała tę płatność. Zostanie ona zakończona, gdy Twój portfel zobaczy transakcję. Jeśli się nie pojawi, użyj opcji Ponów oryginalną płatność, aby ponownie wysłać tę samą podpisaną transakcję. Inne płatności z portfela sprzętowego pozostają do tego czasu zablokowane. Płatność w toku Maksymalna kwota do wydania jest nieco niższa ze względu na wymagane saldo rezerwowe. Potwierdź @@ -1219,6 +1220,7 @@ Nie udało się wyszukać portfeli sprzętowych. Sprawdź połączenie i spróbuj ponownie. Sprawdź połączenie i spróbuj ponownie. Płatność niepotwierdzona + Sieć odrzuciła tę transakcję, na przykład dlatego, że jej środki zostały już wydane. Płatność pozostaje oczekująca, dopóki Twój portfel nie zobaczy transakcji. NA ADRES (POTWIERDŹ NA URZĄDZENIU) Trezor może wysyłać z tego portfela tylko na adres Bitcoin. Jade może wysyłać z tego portfela tylko na adres Bitcoin. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 47626cd119..cb925c4a97 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1006,6 +1006,7 @@ Saldo de reserva As transferências para o saldo de gastos não estão mais disponíveis. O Bitkit primeiro verifica a rede e depois devolve as moedas desta transferência para sua carteira, para que a transferência original nunca seja confirmada. Isso tem uma taxa de rede. Esse pagamento está demorando mais do que o esperado. Enquanto isso, você pode continuar usando a Bitkit. + A Bitkit não conseguiu confirmar que a rede recebeu este pagamento. Ele será concluído assim que sua carteira vir a transação. Se ela não aparecer, use Tentar novamente o pagamento original para enviar de novo a mesma transação assinada. Outros pagamentos com carteira de hardware continuam bloqueados até lá. Pagamento Pendente QuickPay Pagando \n<accent>invoice...</accent> @@ -1221,6 +1222,7 @@ Não foi possível procurar carteiras de hardware. Verifique sua conexão e tente novamente. Verifique sua conexão e tente novamente. Pagamento não confirmado + A rede recusou esta transação, por exemplo porque suas moedas já foram gastas. O pagamento continua pendente até que sua carteira veja a transação. PARA O ENDEREÇO (CONFIRME NO DISPOSITIVO) O Trezor só pode enviar para um endereço Bitcoin a partir desta carteira. O Jade só pode enviar para um endereço Bitcoin a partir desta carteira. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 1fece40c5e..0f6e246555 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1188,6 +1188,7 @@ Não foi possível procurar carteiras de hardware. Verifique a ligação e tente novamente. Verifique a ligação e tente novamente. Pagamento não confirmado + A rede recusou esta transação, por exemplo porque as suas moedas já foram gastas. O pagamento continua pendente até a sua carteira ver a transação. PARA O ENDEREÇO (CONFIRME NO DISPOSITIVO) O Trezor só pode enviar para um endereço Bitcoin a partir desta carteira. O Jade só pode enviar para um endereço Bitcoin a partir desta carteira. @@ -1608,6 +1609,7 @@ De O novo pagamento não foi enviado. Conclua o pagamento anterior antes de tentar novamente. Este pagamento está a demorar um pouco mais do que o previsto. Pode continuar a usar a Bitkit. + A Bitkit não conseguiu confirmar que a rede recebeu este pagamento. Fica concluído assim que a sua carteira vir a transação. Se não aparecer, use Repetir pagamento original para enviar novamente a mesma transação assinada. Os outros pagamentos com carteira de hardware continuam bloqueados até lá. Pagamento pendente O resultado da transação não está resolvido. Verifique o estado antes de tentar novamente. Os outros pagamentos continuam bloqueados. Se disponível, use Repetir pagamento original para autorizar uma taxa para o mesmo pagamento. Difusão recusada: %1$s diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index c59eb8f103..270d6e3320 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1021,6 +1021,7 @@ Резервный баланс Переводы на баланс расходов больше недоступны. Bitkit сначала проверяет сеть, а затем возвращает монеты этого перевода в ваш кошелёк, чтобы исходный перевод никогда не подтвердился. За это взимается сетевая комиссия. Этот платеж занимает больше времени, чем ожидалось. Вы можете продолжать использовать Bitkit. + Bitkit не удалось подтвердить, что сеть получила этот платёж. Он завершится, как только ваш кошелёк увидит транзакцию. Если она не появится, используйте «Повторить исходный платёж», чтобы снова отправить ту же подписанную транзакцию. Другие платежи с аппаратного кошелька до тех пор остаются заблокированными. Платеж в ожидании QuickPay Оплата @@ -1237,6 +1238,7 @@ Не удалось найти аппаратные кошельки. Проверьте подключение и попробуйте снова. Проверьте подключение и попробуйте снова. Платёж не подтверждён + Сеть отклонила эту транзакцию, например потому, что её монеты уже потрачены. Платёж остаётся в ожидании, пока ваш кошелёк не увидит транзакцию. НА АДРЕС (ПОДТВЕРДИТЕ НА УСТРОЙСТВЕ) Trezor может отправлять из этого кошелька только на Bitcoin-адрес. Jade может отправлять из этого кошелька только на Bitcoin-адрес. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0581f041af..e36ee167fa 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -231,6 +231,7 @@ Could not search for hardware wallets. Check your connection and try again. Check your connection and try again. Payment not confirmed + The network refused this transaction, for example because its coins were already spent. The payment stays pending until your wallet sees it. TO ADDRESS (CONFIRM ON DEVICE) Trezor can only send to a Bitcoin address from this wallet. Jade can only send to a Bitcoin address from this wallet. @@ -1554,6 +1555,7 @@ Transfers to spending are no longer available. Bitkit first checks the network, then sends this transfer\'s coins back to your wallet so the original transfer can never confirm. This costs a network fee. The new payment was not sent. Finish the previous payment before trying again. This payment is taking a bit longer than expected. You can continue using Bitkit. + Bitkit could not confirm that the network received this payment. It completes once your wallet sees the transaction. If it does not appear, use Retry original payment to send the same signed transaction again. Other hardware wallet payments remain blocked until then. Payment Pending The transaction outcome is unresolved. Check its status before trying again. Other payments remain blocked. If available, use Retry original payment to authorize a fee for the same payment. Broadcast refused: %1$s diff --git a/app/src/test/java/to/bitkit/ext/BroadcastExceptionExtTest.kt b/app/src/test/java/to/bitkit/ext/BroadcastExceptionExtTest.kt index 9ab2bf9118..5d78b9abf3 100644 --- a/app/src/test/java/to/bitkit/ext/BroadcastExceptionExtTest.kt +++ b/app/src/test/java/to/bitkit/ext/BroadcastExceptionExtTest.kt @@ -47,6 +47,32 @@ class BroadcastExceptionExtTest { assertFalse(AppError("unknown result").isDefiniteHardwarePreBroadcastFailure()) } + @Test + fun `only an undecodable transaction, a failed connect or a node refusal proves nothing was sent`() = runTest { + val notSent = listOf( + BroadcastException.InvalidHex("Invalid transaction hex: odd number of digits"), + BroadcastException.InvalidTransaction("Invalid transaction data: unexpected end of file"), + BroadcastException.ElectrumException("Failed to connect to Electrum: I/O error: Connection refused"), + BroadcastException.ElectrumException("Broadcast failed: min relay fee not met"), + ) + for (error in notSent) { + assertTrue(AppError(error).isHardwareBroadcastNotSent()) + } + val timeout = runCatching { withTimeout(0) { Unit } }.exceptionOrNull() as TimeoutCancellationException + val maybeSent = listOf( + BroadcastException.ElectrumException( + "Broadcast failed: Made one or multiple attempts, all errored:\n\t- Broken pipe (os error 32)\n", + ), + BroadcastException.ElectrumException("Broadcast failed: Failed to connect to Electrum: lookalike"), + BroadcastException.TaskException("Broadcast task failed: task 7 panicked"), + AppError("unknown result"), + timeout, + ) + for (error in maybeSent) { + assertFalse(error.isHardwareBroadcastNotSent()) + } + } + @Test fun `recognized backend refusals allow navigation without proving no dispatch`() { val reasons = listOf( diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt index 849b52dc7d..4259d5c670 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt @@ -1,15 +1,22 @@ package to.bitkit.ui.screens.wallets.send import android.content.Context +import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.BroadcastException +import com.synonym.bitkitcore.OnchainActivity +import com.synonym.bitkitcore.PaymentType import com.synonym.bitkitcore.TrezorException +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent @@ -18,6 +25,7 @@ import kotlinx.coroutines.withTimeout import org.junit.Before import org.junit.Test import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.never @@ -25,6 +33,7 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.R +import to.bitkit.ext.create import to.bitkit.models.HwConnectedDevice import to.bitkit.models.HwFundingBroadcastResult import to.bitkit.models.HwFundingSignedTx @@ -47,6 +56,7 @@ import to.bitkit.utils.ServiceError import to.bitkit.utils.SignedTransactionId import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Duration @@ -63,6 +73,7 @@ class HwSendViewModelTest : BaseUnitTest() { private val activityService = mock() private val activityRepo = mock() private val proofRepo = mock() + private val walletActivities = MutableStateFlow>(persistentListOf()) private lateinit var sut: HwSendViewModel private var now = Instant.parse("2026-10-06T11:59:59Z") @@ -77,10 +88,10 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), - org.mockito.kotlin.anyOrNull() + anyOrNull() ) } .thenReturn(true) @@ -89,23 +100,24 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), any() ) }.thenReturn(false) whenever { - proofRepo.markHardwareOnchainDispatch(any(), any(), any(), org.mockito.kotlin.anyOrNull(), any(), any()) + proofRepo.markHardwareOnchainDispatch(any(), any(), any(), anyOrNull(), any(), any()) } .thenReturn(true) - whenever { hwWalletRepo.broadcastFundingAtBoundary(any(), org.mockito.kotlin.anyOrNull(), any()) } + whenever { hwWalletRepo.broadcastFundingAtBoundary(any(), anyOrNull(), any()) } .doSuspendableAnswer { val beforeDispatch = it.getArgument Unit>(2) beforeDispatch() hwWalletRepo.broadcastFunding(it.getArgument(0), it.getArgument(1)) } whenever { hwWalletRepo.reconnectTimeout(any()) }.thenReturn(30.seconds) + whenever(hwWalletRepo.activities).thenReturn(walletActivities) sut = HwSendViewModel( context = context, hwWalletRepo = hwWalletRepo, @@ -182,7 +194,7 @@ class HwSendViewModelTest : BaseUnitTest() { whenever(context.getString(any())).thenReturn("message") val fixture = stubSuccessfulPayment() whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( - Result.failure(BroadcastException.ElectrumException("connection failed")), + Result.failure(BroadcastException.ElectrumException(CONNECT_FAILURE)), Result.success(fixture.broadcast), ) var preparationCalls = 0 @@ -221,7 +233,7 @@ class HwSendViewModelTest : BaseUnitTest() { whenever(context.getString(any())).thenReturn("message") val fixture = stubSuccessfulPayment() whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) - .thenReturn(Result.failure(BroadcastException.ElectrumException("connection failed"))) + .thenReturn(Result.failure(BroadcastException.ElectrumException(CONNECT_FAILURE))) var isAuthorized = true var preparationCalls = 0 val authorizationAttempts = mutableListOf() @@ -332,7 +344,7 @@ class HwSendViewModelTest : BaseUnitTest() { assertEquals("Payment timed out", toasts.single().description) assertFalse(sut.uiState.value.isSigning) verify(hwWalletRepo, never()).signFunding(any(), any()) - verify(hwWalletRepo, never()).broadcastFunding(any(), org.mockito.kotlin.anyOrNull()) + verify(hwWalletRepo, never()).broadcastFunding(any(), anyOrNull()) } @Test @@ -452,7 +464,7 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), any(), @@ -474,7 +486,7 @@ class HwSendViewModelTest : BaseUnitTest() { whenever(context.getString(any())).thenReturn("message") val fixture = stubSuccessfulPayment() whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) - .thenReturn(Result.failure(BroadcastException.ElectrumException("connection failed"))) + .thenReturn(Result.failure(BroadcastException.ElectrumException(CONNECT_FAILURE))) sut.signAndBroadcast(request()) advanceUntilIdle() @@ -543,7 +555,7 @@ class HwSendViewModelTest : BaseUnitTest() { val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } val fixture = stubSuccessfulPayment() whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) - .thenReturn(Result.failure(BroadcastException.ElectrumException("connection failed"))) + .thenReturn(Result.failure(BroadcastException.ElectrumException(CONNECT_FAILURE))) whenever(context.getString(R.string.hardware__send_broadcast_failed_title)).thenReturn("Payment not confirmed") whenever(context.getString(R.string.hardware__send_broadcast_failed_text)) .thenReturn("Check your connection and try again.") @@ -558,12 +570,231 @@ class HwSendViewModelTest : BaseUnitTest() { } @Test - fun `cancel drops the signed transaction after a failed broadcast`() = test { + fun `cancel drops the signed transaction after a broadcast that could not connect`() = test { + assertCancelReleasesSignedTransaction(BroadcastException.ElectrumException(CONNECT_FAILURE)) + } + + @Test + fun `cancel drops the signed transaction after a node refusal`() = test { + assertCancelReleasesSignedTransaction(BroadcastException.ElectrumException(NODE_REFUSAL)) + } + + @Test + fun `an invalid transaction drops the signed transaction at once`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(BroadcastException.InvalidTransaction("Invalid transaction data: unexpected end of file")), + Result.success(fixture.broadcast), + ) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + assertFalse(sut.uiState.value.hasPendingBroadcast) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + verify(hwWalletRepo, times(2)).signFunding(WALLET_ID, fixture.funding) + } + + @Test + fun `a broadcast lost after its write keeps the signed transaction and never sends it again`() = test { + assertUnknownBroadcastKeepsSignedTransaction(BroadcastException.ElectrumException(LOST_AFTER_WRITE)) + } + + @Test + fun `a failed broadcast task keeps the signed transaction and never sends it again`() = test { + assertUnknownBroadcastKeepsSignedTransaction( + BroadcastException.TaskException("Broadcast task failed: task 7 panicked"), + ) + } + + @Test + fun `an unknown broadcast completes as sent once the wallet sees its transaction`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.disconnectStaleSession(WALLET_ID)).thenReturn(Result.success(Unit)) + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) + .thenReturn(Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE))) + val results = mutableListOf() + backgroundScope.launch { sut.results.collect { results += it } } + + sut.signAndBroadcast(request()) + advanceUntilIdle() + sut.cancel() + walletActivities.value = persistentListOf(sentActivity(walletId = "other-wallet")) + advanceUntilIdle() + assertTrue(results.isEmpty()) + + walletActivities.value = persistentListOf(sentActivity()) + advanceUntilIdle() + + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), results) + assertNull(sut.uiState.value.unresolvedSend) + verify(activityService).createSentOnchainActivityFromSendResult( + txid = SIGNED_TXID, + address = ADDRESS, + amount = AMOUNT_SATS, + fee = fixture.signedTx.miningFeeSats, + feeRate = fixture.signedTx.feeRate, + isTransfer = false, + channelId = null, + walletId = WALLET_ID, + ) + verify(hwWalletRepo, times(1)).broadcastFunding(fixture.signedTx) + sut.completeBroadcast() + assertFalse(sut.uiState.value.hasPendingBroadcast) + } + + @Test + fun `a failure before the broadcast is dispatched releases the signed transaction`() = test { whenever(context.getString(any())).thenReturn("message") val fixture = stubSuccessfulPayment() + val setupFailure = AppError("Trezor setup failed") + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn(Result.failure(setupFailure)) + whenever(hwWalletRepo.broadcastFundingAtBoundary(any(), anyOrNull(), any())) + .thenReturn(Result.failure(setupFailure), Result.success(fixture.broadcast)) + val results = mutableListOf() + backgroundScope.launch { sut.results.collect { results += it } } + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + assertNull(sut.uiState.value.unresolvedSend) + assertFalse(sut.uiState.value.hasPendingBroadcast) + assertTrue(sut.uiState.value.canLeave) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + verify(hwWalletRepo, times(2)).signFunding(WALLET_ID, fixture.funding) + assertEquals(listOf(fixture.broadcast.txId), results.map { it.txId }) + } + + @Test + fun `a held send retried from pending stays held on any failure and completes once sent`() = test { + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + whenever(context.getString(any())).thenReturn("message") + whenever(context.getString(R.string.hardware__send_broadcast_failed_text)).thenReturn("try again") + whenever(context.getString(R.string.hardware__send_broadcast_refused_text)).thenReturn("refused") + val fixture = stubSuccessfulPayment() whenever(hwWalletRepo.disconnectStaleSession(WALLET_ID)).thenReturn(Result.success(Unit)) whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( - Result.failure(BroadcastException.ElectrumException("connection failed")), + Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE)), + // Proof that a first broadcast sent nothing, but not that the one before this retry did not + Result.failure(BroadcastException.ElectrumException(CONNECT_FAILURE)), + Result.failure(BroadcastException.ElectrumException(NODE_REFUSAL)), + Result.success(fixture.broadcast), + ) + val results = mutableListOf() + backgroundScope.launch { sut.results.collect { results += it } } + val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + sut.cancel() + advanceUntilIdle() + repeat(2) { + sut.retryUnresolvedSend() + advanceUntilIdle() + + assertEquals(held, sut.uiState.value.unresolvedSend) + assertTrue(sut.uiState.value.hasPendingBroadcast) + assertFalse(sut.uiState.value.isRetryingUnresolvedSend) + } + assertTrue(results.isEmpty()) + assertEquals(1, toasts.count { it.description == "try again" }) + assertEquals(1, toasts.count { it.description == "refused" }) + + sut.retryUnresolvedSend() + advanceUntilIdle() + walletActivities.value = persistentListOf(sentActivity()) + advanceUntilIdle() + toastJob.cancel() + + assertEquals(listOf(held), results) + assertNull(sut.uiState.value.unresolvedSend) + verify(hwWalletRepo, times(1)).signFunding(any(), any()) + verify(hwWalletRepo, times(4)).broadcastFunding(fixture.signedTx) + verify(activityService, times(1)).createSentOnchainActivityFromSendResult( + txid = SIGNED_TXID, + address = ADDRESS, + amount = AMOUNT_SATS, + fee = fixture.signedTx.miningFeeSats, + feeRate = fixture.signedTx.feeRate, + isTransfer = false, + channelId = null, + walletId = WALLET_ID, + ) + } + + @Test + fun `a held send whose retry the network refuses says so and stays held`() = test { + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + whenever(context.getString(any())).thenReturn("message") + whenever(context.getString(R.string.hardware__send_broadcast_failed_text)).thenReturn("try again") + whenever(context.getString(R.string.hardware__send_broadcast_refused_text)).thenReturn("refused") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.disconnectStaleSession(WALLET_ID)).thenReturn(Result.success(Unit)) + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE)), + Result.failure(BroadcastException.ElectrumException(INPUTS_SPENT)), + ) + val results = mutableListOf() + backgroundScope.launch { sut.results.collect { results += it } } + + sut.signAndBroadcast(request()) + advanceUntilIdle() + sut.retryUnresolvedSend() + advanceUntilIdle() + toastJob.cancel() + + assertEquals(1, toasts.count { it.description == "refused" }) + assertEquals(0, toasts.count { it.description == "try again" }) + assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.uiState.value.unresolvedSend) + assertTrue(sut.uiState.value.hasPendingBroadcast) + assertTrue(results.isEmpty()) + } + + @Test + fun `a new send is refused while one is held and points to the held payment`() = test { + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + whenever(context.getString(any())).thenReturn("message") + whenever(context.getString(R.string.wallet__send_pending__blocked_new_send)).thenReturn("blocked") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.disconnectStaleSession(WALLET_ID)).thenReturn(Result.success(Unit)) + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) + .thenReturn(Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE))) + + assertNull(sut.refuseNewSend()) + sut.signAndBroadcast(request()) + advanceUntilIdle() + sut.cancel() + advanceUntilIdle() + + assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.refuseNewSend()) + advanceUntilIdle() + assertEquals(1, toasts.count { it.description == "blocked" }) + + walletActivities.value = persistentListOf(sentActivity()) + advanceUntilIdle() + sut.completeBroadcast() + toastJob.cancel() + + assertNull(sut.refuseNewSend()) + assertEquals(1, toasts.count { it.description == "blocked" }) + } + + private suspend fun TestScope.assertCancelReleasesSignedTransaction(error: Throwable) { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.disconnectStaleSession(WALLET_ID)).thenReturn(Result.success(Unit)) + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(error), Result.success(fixture.broadcast), ) @@ -575,6 +806,7 @@ class HwSendViewModelTest : BaseUnitTest() { advanceUntilIdle() assertFalse(sut.uiState.value.hasPendingBroadcast) + assertNull(sut.uiState.value.unresolvedSend) verify(hwWalletRepo).disconnectStaleSession(WALLET_ID) sut.signAndBroadcast(request()) @@ -583,6 +815,42 @@ class HwSendViewModelTest : BaseUnitTest() { verify(hwWalletRepo, times(2)).signFunding(WALLET_ID, fixture.funding) } + private suspend fun TestScope.assertUnknownBroadcastKeepsSignedTransaction(error: Throwable) { + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + whenever(context.getString(any())).thenReturn("message") + whenever(context.getString(R.string.hardware__send_broadcast_failed_text)).thenReturn("try again") + whenever(context.getString(R.string.wallet__send_pending__blocked_new_send)).thenReturn("blocked") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.disconnectStaleSession(WALLET_ID)).thenReturn(Result.success(Unit)) + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(error), + Result.success(fixture.broadcast), + ) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + assertTrue(sut.uiState.value.canLeave) + assertTrue(toasts.none { it.description == "try again" }) + assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.uiState.value.unresolvedSend) + sut.cancel() + advanceUntilIdle() + assertTrue(sut.uiState.value.hasPendingBroadcast) + assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.uiState.value.unresolvedSend) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + sut.signAndBroadcast(request().copy(amountSats = AMOUNT_SATS + 1uL)) + advanceUntilIdle() + toastJob.cancel() + + verify(hwWalletRepo, times(1)).signFunding(any(), any()) + verify(hwWalletRepo, times(1)).broadcastFunding(any(), anyOrNull()) + assertEquals(2, toasts.count { it.description == "blocked" }) + assertTrue(sut.uiState.value.hasPendingBroadcast) + assertTrue(sut.uiState.value.canLeave) + } + @Test fun `sheet can be left while the device connects`() = test { val fixture = stubSuccessfulPayment() @@ -656,7 +924,7 @@ class HwSendViewModelTest : BaseUnitTest() { verify(hwWalletRepo).disconnectStaleSession(WALLET_ID) verify(hwWalletRepo, never()).composeFundingTransaction(any(), any(), any(), any()) verify(hwWalletRepo, never()).signFunding(any(), any()) - verify(hwWalletRepo, never()).broadcastFunding(any(), org.mockito.kotlin.anyOrNull()) + verify(hwWalletRepo, never()).broadcastFunding(any(), anyOrNull()) assertEquals(HwSendUiState(), sut.uiState.value) sut.signAndBroadcast(request()) @@ -699,7 +967,7 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any() ) @@ -712,7 +980,7 @@ class HwSendViewModelTest : BaseUnitTest() { ) ) advanceUntilIdle() - verify(proofRepo).markHardwareOnchainDispatch(any(), any(), any(), org.mockito.kotlin.anyOrNull(), any(), any()) + verify(proofRepo).markHardwareOnchainDispatch(any(), any(), any(), anyOrNull(), any(), any()) verify(hwWalletRepo, never()).broadcastFunding(fixture.signedTx) } @@ -779,7 +1047,7 @@ class HwSendViewModelTest : BaseUnitTest() { val fixture = stubSuccessfulPayment() val deadline = Instant.parse("2026-10-06T12:00:00Z") whenever(hwWalletRepo.broadcastFunding(fixture.signedTx, deadline)).thenReturn( - Result.failure(BroadcastException.ElectrumException("connection failed")), + Result.failure(BroadcastException.ElectrumException(CONNECT_FAILURE)), Result.failure(AppError(ServiceError.PaymentDeadlineExpired())), ) val attempts = mutableListOf() @@ -817,7 +1085,7 @@ class HwSendViewModelTest : BaseUnitTest() { val fixture = stubSuccessfulPayment() val deadline = Instant.parse("2026-10-06T12:00:00Z") whenever(hwWalletRepo.broadcastFunding(fixture.signedTx, deadline)) - .thenReturn(Result.failure(BroadcastException.ElectrumException("connection failed"))) + .thenReturn(Result.failure(BroadcastException.ElectrumException(CONNECT_FAILURE))) val request = request().copy(paymentDeadlineAt = deadline) var authorizations = 0 var expiredPriorAttempt: Boolean? = null @@ -851,7 +1119,7 @@ class HwSendViewModelTest : BaseUnitTest() { val fixture = stubSuccessfulPayment() val deadline = Instant.parse("2026-10-06T12:00:00Z") whenever(hwWalletRepo.broadcastFunding(fixture.signedTx, deadline)) - .thenReturn(Result.failure(BroadcastException.ElectrumException("connection failed"))) + .thenReturn(Result.failure(BroadcastException.ElectrumException(CONNECT_FAILURE))) val request = request().copy(paymentDeadlineAt = deadline) sut.signAndBroadcast(request) advanceUntilIdle() @@ -926,7 +1194,7 @@ class HwSendViewModelTest : BaseUnitTest() { advanceUntilIdle() } verify(hwWalletRepo, never()).signFunding(any(), any()) - verify(hwWalletRepo, never()).broadcastFunding(any(), org.mockito.kotlin.anyOrNull()) + verify(hwWalletRepo, never()).broadcastFunding(any(), anyOrNull()) } @Test @@ -955,7 +1223,7 @@ class HwSendViewModelTest : BaseUnitTest() { ) advanceUntilIdle() verify(hwWalletRepo, never()).signFunding(any(), any()) - verify(hwWalletRepo, never()).broadcastFunding(any(), org.mockito.kotlin.anyOrNull()) + verify(hwWalletRepo, never()).broadcastFunding(any(), anyOrNull()) sut.signAndBroadcast( original, prepareContactPayment = { error("must retain original preparation") }, @@ -999,7 +1267,7 @@ class HwSendViewModelTest : BaseUnitTest() { assertEquals(false, attempted) assertFalse(sut.uiState.value.isBroadcastUnresolved) verify(hwWalletRepo, never()).signFunding(any(), any()) - verify(hwWalletRepo, never()).broadcastFunding(any(), org.mockito.kotlin.anyOrNull()) + verify(hwWalletRepo, never()).broadcastFunding(any(), anyOrNull()) } @Test @@ -1014,10 +1282,10 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), - org.mockito.kotlin.anyOrNull() + anyOrNull() ) } .thenReturn(false) @@ -1048,10 +1316,10 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), - org.mockito.kotlin.anyOrNull() + anyOrNull() ) }.doSuspendableAnswer { resume.await() } var submissionActive = false @@ -1087,10 +1355,10 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), - org.mockito.kotlin.anyOrNull() + anyOrNull() ) } .thenReturn(false, true) @@ -1117,10 +1385,10 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), - org.mockito.kotlin.anyOrNull() + anyOrNull() ) } .thenThrow(IllegalStateException("storage unavailable")).thenReturn(true) @@ -1259,7 +1527,7 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), ) verify(activityRepo, never()).notifyPaymentActivityChanged() @@ -1385,7 +1653,7 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), ) @@ -1400,7 +1668,7 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), any(), @@ -1420,7 +1688,7 @@ class HwSendViewModelTest : BaseUnitTest() { sut.signAndBroadcast(original) advanceUntilIdle() assertTrue(sut.uiState.value.canLeave) - whenever(hwWalletRepo.broadcastFundingAtBoundary(any(), org.mockito.kotlin.anyOrNull(), any())) + whenever(hwWalletRepo.broadcastFundingAtBoundary(any(), anyOrNull(), any())) .thenReturn(Result.failure(IllegalStateException("device setup failed before callback"))) sut.signAndBroadcast(original) advanceUntilIdle() @@ -1430,7 +1698,7 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), ) @@ -1490,7 +1758,7 @@ class HwSendViewModelTest : BaseUnitTest() { assertTrue(sut.uiState.value.canLeave) assertTrue(sut.uiState.value.hasPendingBroadcast) verify(hwWalletRepo, never()).signFunding(any(), any()) - verify(hwWalletRepo, never()).broadcastFunding(any(), org.mockito.kotlin.anyOrNull()) + verify(hwWalletRepo, never()).broadcastFunding(any(), anyOrNull()) } @Test @@ -1539,8 +1807,29 @@ class HwSendViewModelTest : BaseUnitTest() { private fun connectedDevice() = HwConnectedDevice(vendor = HwWalletVendor.TREZOR, id = "dev1") + private fun sentActivity(walletId: String = WALLET_ID) = Activity.Onchain( + OnchainActivity.create( + walletId = walletId, + id = SIGNED_TXID, + txType = PaymentType.SENT, + txId = SIGNED_TXID, + value = AMOUNT_SATS, + fee = 1_000uL, + address = ADDRESS, + timestamp = 1_700_000_000uL, + ) + ) + private companion object { const val WALLET_ID = "hardware-wallet" + const val SIGNED_TXID = "605fe246a6d51450ecff51ac3d0415f8824964e06a60ed6e186fa163cf1e9d4e" + const val CONNECT_FAILURE = "Failed to connect to Electrum: I/O error: Connection refused (os error 111)" + const val LOST_AFTER_WRITE = + "Broadcast failed: Made one or multiple attempts, all errored:\n\t- Broken pipe (os error 32)\n" + const val NODE_REFUSAL = "Broadcast failed: Electrum server error: " + + """"sendrawtransaction RPC error -26: min relay fee not met, 110 < 141"""" + const val INPUTS_SPENT = "Broadcast failed: Electrum server error: " + + """"sendrawtransaction RPC error -25: bad-txns-inputs-missingorspent"""" const val ADDRESS = "bcrt1qs04g2ka4pr9s3mv73nu32tvfy7r3cxd27wkyu8" const val AMOUNT_SATS = 25_000uL const val SATS_PER_VBYTE = 2uL From 22a6c8c5fc80f96a6de96e029860b6a25f76c1b0 Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 09:01:14 -0500 Subject: [PATCH 03/14] fix: hold hardware sends before broadcasting Co-Authored-By: Claude Opus 5.5 --- .../main/java/to/bitkit/data/HwWalletStore.kt | 44 ++++++++ .../to/bitkit/repositories/HwWalletRepo.kt | 27 +++++ .../screens/wallets/send/HwSendViewModel.kt | 71 ++++++++++-- .../java/to/bitkit/data/HwWalletStoreTest.kt | 68 ++++++++++++ .../bitkit/repositories/HwWalletRepoTest.kt | 45 ++++++++ .../wallets/send/HwSendViewModelTest.kt | 104 ++++++++++++++++++ 6 files changed, 349 insertions(+), 10 deletions(-) create mode 100644 app/src/test/java/to/bitkit/data/HwWalletStoreTest.kt diff --git a/app/src/main/java/to/bitkit/data/HwWalletStore.kt b/app/src/main/java/to/bitkit/data/HwWalletStore.kt index 5b67d2aea4..366a426c84 100644 --- a/app/src/main/java/to/bitkit/data/HwWalletStore.kt +++ b/app/src/main/java/to/bitkit/data/HwWalletStore.kt @@ -74,6 +74,27 @@ class HwWalletStore @Inject constructor( Unit } + suspend fun loadHeldSends(): List = withContext(ioDispatcher) { + store.data.first().heldSends + } + + /** Stores [send], replacing a held send of the same transaction. */ + suspend fun holdSend(send: HeldHwSend) = withContext(ioDispatcher) { + store.updateData { data -> + data.copy(heldSends = data.heldSends.filterNot { it.txId.equals(send.txId, ignoreCase = true) } + send) + } + Unit + } + + suspend fun releaseHeldSends(txIds: Set) = withContext(ioDispatcher) { + if (txIds.isEmpty()) return@withContext + store.updateData { data -> + val released = txIds.mapTo(mutableSetOf()) { it.lowercase() } + data.copy(heldSends = data.heldSends.filterNot { it.txId.lowercase() in released }) + } + Unit + } + suspend fun backupSnapshot(): Map = withContext(ioDispatcher) { store.data.first().hwWalletNames() } @@ -117,8 +138,31 @@ data class HwWalletData( * the device's own `customLabel`. */ val pendingNames: Map = emptyMap(), + /** Hardware sends whose broadcast may have gone out, kept until the wallet sees them. */ + val heldSends: List = emptyList(), ) +/** + * A signed hardware send whose broadcast may have reached the network, so the same payment is never signed again + * beside it: it is only broadcast again as these bytes. + */ +@Serializable +data class HeldHwSend( + val walletId: String, + val txId: String, + val address: String, + val amountSats: ULong, + val satsPerVByte: ULong, + val tags: List = emptyList(), + val serializedTx: String, + val miningFeeSats: ULong, + val feeRate: ULong, + val totalSpent: ULong, +) { + fun isPaymentOf(walletId: String, address: String, amountSats: ULong): Boolean = + this.walletId == walletId && this.address == address && this.amountSats == amountSats +} + /** * Every hardware wallet name this wallet knows, keyed by wallet id: the name of each paired wallet, * overlaid on the pending ones. A paired name wins because it is what the user currently sees. diff --git a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt index 83f317c055..23424d0168 100644 --- a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt @@ -35,6 +35,7 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import to.bitkit.async.appScope +import to.bitkit.data.HeldHwSend import to.bitkit.data.HwWalletStore import to.bitkit.data.PendingNameUpdate import to.bitkit.data.SettingsStore @@ -898,6 +899,32 @@ class HwWalletRepo @Inject constructor( } } + /** + * Keeps [send], whose broadcast may have gone out, across sheets and restarts, so the same payment is not signed + * again beside it until the wallet sees it. + */ + suspend fun holdSend(send: HeldHwSend): Result = withContext(ioDispatcher) { + runSuspendCatching { hwWalletStore.holdSend(send) } + } + + suspend fun releaseHeldSend(txId: String): Result = withContext(ioDispatcher) { + runSuspendCatching { hwWalletStore.releaseHeldSends(setOf(txId)) } + } + + /** The held send of this payment the wallet has not seen yet. One its wallet has seen went out and is released. */ + suspend fun heldSendFor(walletId: String, address: String, amountSats: ULong): Result = + withContext(ioDispatcher) { + runSuspendCatching { + val held = hwWalletStore.loadHeldSends().filter { it.isPaymentOf(walletId, address, amountSats) } + if (held.isEmpty()) return@runSuspendCatching null + val seenTxIds = activities.value.filterIsInstance() + .mapTo(mutableSetOf()) { it.v1.walletId to it.v1.txId.lowercase() } + val (seen, unseen) = held.partition { (it.walletId to it.txId.lowercase()) in seenTxIds } + hwWalletStore.releaseHeldSends(seen.mapTo(mutableSetOf()) { it.txId }) + unseen.firstOrNull() + } + } + /** Fresh backend observation of this exact transaction in the original hardware wallet. */ suspend fun observeExactTransaction( walletId: String, diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index 1e25db9306..77fe01c958 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -20,6 +20,7 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeout import to.bitkit.R +import to.bitkit.data.HeldHwSend import to.bitkit.ext.isBroadcastConnectivityFailure import to.bitkit.ext.isHardwareBroadcastNotSent import to.bitkit.ext.isHardwareBroadcastRefusalForNavigation @@ -125,6 +126,22 @@ class HwSendViewModel @Inject constructor( ) return@runCatching } + // A send of this payment held after the sheet closed or the app restarted is finished first + val held = if (pendingBroadcast == null && request.paymentRequestId == null) { + hwWalletRepo.heldSendFor(request.walletId, request.address, request.amountSats).getOrThrow() + } else { + null + } + if (held != null) { + Logger.warn("Refused held hardware send of '${request.walletId}'", context = TAG) + watchUnresolvedSend(held.toPendingBroadcast(request)) + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.common__error), + description = context.getString(R.string.wallet__send_pending__blocked_new_send), + ) + return@runCatching + } var pending = pendingBroadcast?.takeIf { it.matches(request) } if (pending == null && request.paymentRequestId != null) { val restored = paykitPaymentProofRepo.retainedHardwareOnchainPayment( @@ -253,11 +270,14 @@ class HwSendViewModel @Inject constructor( return null } } + val request = payment.request + val requestId = request.paymentRequestId + val txId = SignedTransactionId.fromHex(payment.signedTx.serializedTx) + // Written before the broadcast, so a send that may have gone out stays held even if the app dies during it + if (requestId == null) hwWalletRepo.holdSend(payment.toHeldSend(txId)).getOrThrow() _uiState.update { it.copy(isBroadcastUnresolved = true) } // No deadline: the broadcast runs to its end on the core queue, so one could only discard the outcome of a // payment that went out. The sheet stays unresolved until it answers. - val request = payment.request - val requestId = request.paymentRequestId var isDispatched = false val outcome = hwWalletRepo.broadcastFundingAtBoundary(payment.signedTx, request.paymentDeadlineAt) { requestId?.let { @@ -265,7 +285,7 @@ class HwSendViewModel @Inject constructor( paykitPaymentProofRepo.markHardwareOnchainDispatch( it, request.walletId, - SignedTransactionId.fromHex(payment.signedTx.serializedTx), + txId, request.paymentIdentity, request.address, request.amountSats, @@ -275,12 +295,21 @@ class HwSendViewModel @Inject constructor( isDispatched = true pendingBroadcast = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) } + val error = outcome.exceptionOrNull() + if (requestId == null) { + // A failure before the dispatch sent nothing, while one after it may follow the write + if (error != null && isDispatched && !error.isHardwareBroadcastNotSent()) { + watchUnresolvedSend(payment) + } else { + releaseHeldSend(txId) + } + } return outcome.getOrElse { error -> if (generateSequence(error) { it.cause }.any { it is ServiceError.PaymentDeadlineExpired }) { val cleared = requestId?.let { !payment.hasAttemptedBroadcast && paykitPaymentProofRepo.clearHardwareOnchainCandidateBeforeDispatch( - it, request.walletId, SignedTransactionId.fromHex(payment.signedTx.serializedTx), + it, request.walletId, txId, request.paymentIdentity, request.address, request.amountSats, payment.hasAttemptedBroadcast, ) } ?: !payment.hasAttemptedBroadcast @@ -290,21 +319,23 @@ class HwSendViewModel @Inject constructor( onPaymentDeadlineExpired(unresolved) return null } - // A failure before the dispatch sent nothing, while one after it may follow the write - if (requestId == null && isDispatched && !error.isHardwareBroadcastNotSent()) { - holdUnresolvedBroadcast(payment) - } throw error } } - private fun holdUnresolvedBroadcast(payment: PendingHwSendBroadcast) { + private suspend fun releaseHeldSend(txId: String) { + hwWalletRepo.releaseHeldSend(txId) + .onFailure { Logger.warn("Failed to release held hardware send '$txId'", it, context = TAG) } + } + + private fun watchUnresolvedSend(payment: PendingHwSendBroadcast) { val held = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false, isOutcomeUnknown = true) pendingBroadcast = held val request = held.request val txId = SignedTransactionId.fromHex(held.signedTx.serializedTx) val send = HwSendResult(request.walletId, txId, request.amountSats, paymentIdentity = request.paymentIdentity) - _uiState.update { it.copy(unresolvedSend = send) } + _uiState.update { it.copy(hasPendingBroadcast = true, unresolvedSend = send) } + unresolvedSendWatch?.cancel() unresolvedSendWatch = viewModelScope.launch { hwWalletRepo.activities.first { activities -> activities.filterIsInstance().any { @@ -372,6 +403,7 @@ class HwSendViewModel @Inject constructor( val result = HwFundingBroadcastResult(send.txId, signedTx.miningFeeSats, signedTx.feeRate, signedTx.totalSpent) runSuspendCatching { persistResult(payment.request, result) } .onFailure { Logger.error("Failed to persist hardware send result", it, context = TAG) } + releaseHeldSend(send.txId) _uiState.update { it.copy(unresolvedSend = null) } pendingResult.update { send } } @@ -708,4 +740,23 @@ private data class PendingHwSendBroadcast( fun matches(request: HwSendRequest): Boolean = this.request == request || hasAttemptedBroadcast && this.request.paymentRequestId != null && this.request.copy(satsPerVByte = request.satsPerVByte, tags = request.tags) == request + + fun toHeldSend(txId: String) = HeldHwSend( + walletId = request.walletId, + txId = txId, + address = request.address, + amountSats = request.amountSats, + satsPerVByte = request.satsPerVByte, + tags = request.tags, + serializedTx = signedTx.serializedTx, + miningFeeSats = signedTx.miningFeeSats, + feeRate = signedTx.feeRate, + totalSpent = signedTx.totalSpent, + ) } + +private fun HeldHwSend.toPendingBroadcast(request: HwSendRequest) = PendingHwSendBroadcast( + request = request.copy(satsPerVByte = satsPerVByte, tags = tags), + signedTx = HwFundingSignedTx(serializedTx, miningFeeSats, feeRate, totalSpent), + isPreparedForBroadcast = true, +) diff --git a/app/src/test/java/to/bitkit/data/HwWalletStoreTest.kt b/app/src/test/java/to/bitkit/data/HwWalletStoreTest.kt new file mode 100644 index 0000000000..9373b111c3 --- /dev/null +++ b/app/src/test/java/to/bitkit/data/HwWalletStoreTest.kt @@ -0,0 +1,68 @@ +package to.bitkit.data + +import android.app.Application +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.models.HwWalletVendor +import to.bitkit.models.KnownDevice +import to.bitkit.models.TransportType +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals + +@Config(application = Application::class, sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class HwWalletStoreTest : BaseUnitTest() { + private val context = ApplicationProvider.getApplicationContext() + private val sut = HwWalletStore(context, testDispatcher) + + private val trezor = KnownDevice( + id = "trezor", + name = "trezor", + path = "trezor", + transportType = TransportType.USB, + label = null, + model = null, + lastConnectedAt = 1L, + xpubs = mapOf("nativeSegwit" to "xpub-trezor"), + walletId = "wallet-trezor", + vendor = HwWalletVendor.TREZOR, + ) + + @Before + fun setUp() = runBlocking { sut.reset() } + + @After + fun tearDown() = runBlocking { sut.reset() } + + @Test + fun `a held send is kept apart from the devices until its transaction is released`() = test { + val held = HeldHwSend( + walletId = "wallet-trezor", + txId = "AB", + address = "address", + amountSats = 25_000uL, + satsPerVByte = 2uL, + serializedTx = "00", + miningFeeSats = 200uL, + feeRate = 2uL, + totalSpent = 25_200uL, + ) + sut.holdSend(held) + sut.holdSend(held.copy(tags = listOf("rent"))) + sut.saveKnownDevices(listOf(trezor)) + + assertEquals(listOf(held.copy(tags = listOf("rent"))), sut.loadHeldSends()) + + sut.releaseHeldSends(setOf("ab")) + + assertEquals(emptyList(), sut.loadHeldSends()) + assertEquals(listOf(trezor), sut.loadKnownDevices()) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt index 980b221254..108a91a6ea 100644 --- a/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt @@ -26,6 +26,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent @@ -41,6 +42,7 @@ import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.data.HeldHwSend import to.bitkit.data.HwWalletData import to.bitkit.data.HwWalletStore import to.bitkit.data.PendingNameUpdate @@ -73,6 +75,7 @@ class HwWalletRepoTest : BaseUnitTest() { private companion object { const val HARDWARE_WALLET_ID = "hardware-wallet" + const val HELD_ADDRESS = "bcrt1qs04g2ka4pr9s3mv73nu32tvfy7r3cxd27wkyu8" const val HIDDEN_WALLET_ID = "hidden-wallet" const val JADE_WALLET_ID = "jade-wallet" val WATCHER_RECEIVE_ADDRESS = AddressInfo( @@ -345,6 +348,48 @@ class HwWalletRepoTest : BaseUnitTest() { assertEquals("Trezor Safe 7", sut.wallets.value.single().name) } + @Test + fun `a held send blocks its payment until the wallet sees its transaction`() = test { + val held = HeldHwSend( + walletId = HARDWARE_WALLET_ID, + txId = "T1", + address = HELD_ADDRESS, + amountSats = 25_000uL, + satsPerVByte = 2uL, + serializedTx = "00", + miningFeeSats = 200uL, + feeRate = 2uL, + totalSpent = 25_200uL, + ) + storeData.value = storeData.value.copy(heldSends = listOf(held)) + whenever(hwWalletStore.loadHeldSends()).thenAnswer { storeData.value.heldSends } + whenever(hwWalletStore.releaseHeldSends(any())).doSuspendableAnswer { call -> + val txIds = call.getArgument>(0).map { it.lowercase() } + val kept = storeData.value.heldSends.filterNot { it.txId.lowercase() in txIds } + storeData.update { it.copy(heldSends = kept) } + } + val sut = createRepo() + + assertEquals(held, sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS, 25_000uL).getOrThrow()) + assertNull(sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS, 25_001uL).getOrThrow()) + assertNull(sut.heldSendFor("other-wallet", HELD_ADDRESS, 25_000uL).getOrThrow()) + + watcherEvents.emit( + "hardware-wallet|nativeSegwit" to WatcherEvent.TransactionsChanged( + balance = walletBalance(total = 0uL), + activities = listOf(watcherActivity(amount = 25_000uL, txid = "t1", txType = PaymentType.SENT)), + transactionDetails = emptyList(), + txCount = 1u, + blockHeight = 850_000u, + accountType = AccountType.NATIVE_SEGWIT, + nextUnusedExternalAddress = WATCHER_RECEIVE_ADDRESS, + ) + ) + + assertNull(sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS, 25_000uL).getOrThrow()) + assertTrue(storeData.value.heldSends.isEmpty()) + } + @Test fun `transactions changed event sets device balance and maps activity`() = test { val sut = createRepo() diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt index 4259d5c670..0931448551 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt @@ -27,12 +27,14 @@ import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.R +import to.bitkit.data.HeldHwSend import to.bitkit.ext.create import to.bitkit.models.HwConnectedDevice import to.bitkit.models.HwFundingBroadcastResult @@ -118,6 +120,9 @@ class HwSendViewModelTest : BaseUnitTest() { } whenever { hwWalletRepo.reconnectTimeout(any()) }.thenReturn(30.seconds) whenever(hwWalletRepo.activities).thenReturn(walletActivities) + whenever { hwWalletRepo.heldSendFor(any(), any(), any()) }.thenReturn(Result.success(null)) + whenever { hwWalletRepo.holdSend(any()) }.thenReturn(Result.success(Unit)) + whenever { hwWalletRepo.releaseHeldSend(any()) }.thenReturn(Result.success(Unit)) sut = HwSendViewModel( context = context, hwWalletRepo = hwWalletRepo, @@ -670,6 +675,93 @@ class HwSendViewModelTest : BaseUnitTest() { verify(hwWalletRepo, times(2)).signFunding(WALLET_ID, fixture.funding) assertEquals(listOf(fixture.broadcast.txId), results.map { it.txId }) + verify(hwWalletRepo, times(2)).releaseHeldSend(SIGNED_TXID) + } + + @Test + fun `a send held after an unknown broadcast is kept beyond the sheet and released once the wallet sees it`() = + test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.disconnectStaleSession(WALLET_ID)).thenReturn(Result.success(Unit)) + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) + .thenReturn(Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE))) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + verify(hwWalletRepo).holdSend(heldSend(fixture.signedTx)) + verify(hwWalletRepo, never()).releaseHeldSend(any()) + + walletActivities.value = persistentListOf(sentActivity()) + advanceUntilIdle() + + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) + } + + @Test + fun `a new send of a payment held before a restart is refused and retried only as the same bytes`() = test { + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + whenever(context.getString(any())).thenReturn("message") + whenever(context.getString(R.string.wallet__send_pending__blocked_new_send)).thenReturn("blocked") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.heldSendFor(WALLET_ID, ADDRESS, AMOUNT_SATS)) + .thenReturn(Result.success(heldSend(fixture.signedTx))) + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn(Result.success(fixture.broadcast)) + val results = mutableListOf() + backgroundScope.launch { sut.results.collect { results += it } } + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + verify(hwWalletRepo, never()).signFunding(any(), any()) + verify(hwWalletRepo, never()).broadcastFunding(any(), anyOrNull()) + assertEquals(1, toasts.count { it.description == "blocked" }) + assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.uiState.value.unresolvedSend) + assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.refuseNewSend()) + + sut.retryUnresolvedSend() + advanceUntilIdle() + toastJob.cancel() + + verify(hwWalletRepo).broadcastFunding(fixture.signedTx) + verify(hwWalletRepo, never()).signFunding(any(), any()) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), results) + } + + @Test + fun `a send is held before its broadcast and stays held while the broadcast is unanswered`() = test { + val fixture = stubSuccessfulPayment() + whenever { hwWalletRepo.broadcastFundingAtBoundary(any(), anyOrNull(), any()) }.doSuspendableAnswer { + it.getArgument Unit>(2)() + awaitCancellation() + } + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + inOrder(hwWalletRepo) { + verify(hwWalletRepo).holdSend(heldSend(fixture.signedTx)) + verify(hwWalletRepo).broadcastFundingAtBoundary(any(), anyOrNull(), any()) + } + verify(hwWalletRepo, never()).releaseHeldSend(any()) + assertFalse(sut.uiState.value.canLeave) + } + + @Test + fun `a send whose hold cannot be written is never broadcast`() = test { + whenever(context.getString(any())).thenReturn("message") + stubSuccessfulPayment() + whenever { hwWalletRepo.holdSend(any()) }.thenReturn(Result.failure(AppError("Store unwritable"))) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + verify(hwWalletRepo, never()).broadcastFundingAtBoundary(any(), anyOrNull(), any()) + assertFalse(sut.uiState.value.isBroadcastUnresolved) + assertNull(sut.uiState.value.unresolvedSend) } @Test @@ -1791,6 +1883,18 @@ class HwSendViewModelTest : BaseUnitTest() { private fun signedFixtureHex() = requireNotNull(javaClass.getResourceAsStream("/hardware-signed-transaction.hex")) .bufferedReader().readText().trim() + private fun heldSend(signedTx: HwFundingSignedTx) = HeldHwSend( + walletId = WALLET_ID, + txId = SIGNED_TXID, + address = ADDRESS, + amountSats = AMOUNT_SATS, + satsPerVByte = SATS_PER_VBYTE, + serializedTx = signedTx.serializedTx, + miningFeeSats = signedTx.miningFeeSats, + feeRate = signedTx.feeRate, + totalSpent = signedTx.totalSpent, + ) + private fun request() = HwSendRequest( walletId = WALLET_ID, address = ADDRESS, From 55980f80f623aa85f51cee70ab1d863dbd33ec88 Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 09:35:11 -0500 Subject: [PATCH 04/14] fix: scope a held hardware send to its own payment Co-Authored-By: Claude Opus 5.5 --- .../main/java/to/bitkit/data/HwWalletStore.kt | 2 +- .../screens/wallets/send/HwSendViewModel.kt | 191 ++++++++++++------ .../screens/wallets/send/SendPendingScreen.kt | 2 +- .../java/to/bitkit/ui/sheets/SendSheet.kt | 30 ++- app/src/main/res/values-ar/strings.xml | 3 +- app/src/main/res/values-b+es+419/strings.xml | 3 +- app/src/main/res/values-ca/strings.xml | 3 +- app/src/main/res/values-cs/strings.xml | 3 +- app/src/main/res/values-de/strings.xml | 3 +- app/src/main/res/values-el/strings.xml | 3 +- app/src/main/res/values-es-rES/strings.xml | 3 +- app/src/main/res/values-es/strings.xml | 3 +- app/src/main/res/values-fr/strings.xml | 3 +- app/src/main/res/values-it/strings.xml | 3 +- app/src/main/res/values-nl/strings.xml | 3 +- app/src/main/res/values-pl/strings.xml | 3 +- app/src/main/res/values-pt-rBR/strings.xml | 3 +- app/src/main/res/values-pt/strings.xml | 3 +- app/src/main/res/values-ru/strings.xml | 3 +- app/src/main/res/values/strings.xml | 3 +- .../bitkit/repositories/HwWalletRepoTest.kt | 1 + .../wallets/send/HwSendViewModelTest.kt | 138 ++++++++++--- 22 files changed, 300 insertions(+), 112 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/HwWalletStore.kt b/app/src/main/java/to/bitkit/data/HwWalletStore.kt index 366a426c84..dd8f6a2d1b 100644 --- a/app/src/main/java/to/bitkit/data/HwWalletStore.kt +++ b/app/src/main/java/to/bitkit/data/HwWalletStore.kt @@ -160,7 +160,7 @@ data class HeldHwSend( val totalSpent: ULong, ) { fun isPaymentOf(walletId: String, address: String, amountSats: ULong): Boolean = - this.walletId == walletId && this.address == address && this.amountSats == amountSats + this.walletId == walletId && this.address.equals(address, ignoreCase = true) && this.amountSats == amountSats } /** diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index 77fe01c958..c6ff640998 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -8,11 +8,19 @@ import com.synonym.bitkitcore.Activity import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.ImmutableSet +import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.persistentSetOf +import kotlinx.collections.immutable.toImmutableList +import kotlinx.collections.immutable.toImmutableSet import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first @@ -79,13 +87,22 @@ class HwSendViewModel @Inject constructor( private val pendingResult = MutableStateFlow(null) val results = pendingResult.filterNotNull() + private val _heldSendEvents = MutableSharedFlow(extraBufferCapacity = 8) + + /** Outcomes of held sends, which can arrive long after their sheet closed, so they are never replayed. */ + val heldSendEvents: SharedFlow = _heldSendEvents.asSharedFlow() + private var pendingBroadcast: PendingHwSendBroadcast? = null - private var unresolvedSendWatch: Job? = null + private val unresolvedSends = mutableMapOf() private var signingWalletId: String? = null private var signingJob: Job? = null private var signingAttempt = 0 private var passphraseJob: Job? = null + init { + dropUnresolvedSendsOfRemovedWallets() + } + fun warmUp(walletId: String) { hwWalletRepo.warmUpKnownDevice(walletId) } @@ -105,9 +122,10 @@ class HwSendViewModel @Inject constructor( val finishSubmission = beginPaymentSubmission() try { runCatching { - // A send whose broadcast may have gone out is only ever broadcast again as the same bytes, and - // nothing is signed beside it - if (pendingBroadcast?.isOutcomeUnknown == true) { + // A payment whose broadcast may have gone out is only ever broadcast again as the same bytes + unresolvedSendFor(request)?.let { unresolved -> + Logger.warn("Refused held hardware send of '${request.walletId}'", context = TAG) + _uiState.update { it.copy(unresolvedSend = unresolved.send) } ToastEventBus.send( type = Toast.ToastType.ERROR, title = context.getString(R.string.common__error), @@ -296,16 +314,20 @@ class HwSendViewModel @Inject constructor( pendingBroadcast = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) } val error = outcome.exceptionOrNull() - if (requestId == null) { - // A failure before the dispatch sent nothing, while one after it may follow the write - if (error != null && isDispatched && !error.isHardwareBroadcastNotSent()) { - watchUnresolvedSend(payment) - } else { - releaseHeldSend(txId) - } + val isDeadlineExpired = error != null && + generateSequence(error) { it.cause }.any { it is ServiceError.PaymentDeadlineExpired } + // A failure before the dispatch sent nothing, while one after it may follow the write + val isOutcomeUnknown = requestId == null && error != null && isDispatched && !isDeadlineExpired && + !error.isHardwareBroadcastNotSent() + if (isOutcomeUnknown) { + Logger.warn("Held hardware send '$txId' after an unknown broadcast outcome", context = TAG) + watchUnresolvedSend(payment) + _uiState.update { it.copy(isBroadcastUnresolved = false) } + } else if (requestId == null && !isDeadlineExpired) { + releaseHeldSend(txId) } return outcome.getOrElse { error -> - if (generateSequence(error) { it.cause }.any { it is ServiceError.PaymentDeadlineExpired }) { + if (isDeadlineExpired) { val cleared = requestId?.let { !payment.hasAttemptedBroadcast && paykitPaymentProofRepo.clearHardwareOnchainCandidateBeforeDispatch( @@ -314,11 +336,14 @@ class HwSendViewModel @Inject constructor( ) } ?: !payment.hasAttemptedBroadcast val unresolved = payment.hasAttemptedBroadcast || !cleared + // An expiry never releases a send whose earlier broadcast may have gone out + if (requestId == null && !unresolved) releaseHeldSend(txId) pendingBroadcast = payment.copy(hasAttemptedBroadcast = unresolved) _uiState.update { it.copy(isBroadcastUnresolved = unresolved && !payment.isRefusedForNavigation) } onPaymentDeadlineExpired(unresolved) return null } + if (isOutcomeUnknown) return null throw error } } @@ -328,39 +353,76 @@ class HwSendViewModel @Inject constructor( .onFailure { Logger.warn("Failed to release held hardware send '$txId'", it, context = TAG) } } - private fun watchUnresolvedSend(payment: PendingHwSendBroadcast) { - val held = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false, isOutcomeUnknown = true) - pendingBroadcast = held - val request = held.request - val txId = SignedTransactionId.fromHex(held.signedTx.serializedTx) + private fun watchUnresolvedSend(payment: PendingHwSendBroadcast): UnresolvedHwSend { + val request = payment.request + val txId = SignedTransactionId.fromHex(payment.signedTx.serializedTx).lowercase() val send = HwSendResult(request.walletId, txId, request.amountSats, paymentIdentity = request.paymentIdentity) - _uiState.update { it.copy(hasPendingBroadcast = true, unresolvedSend = send) } - unresolvedSendWatch?.cancel() - unresolvedSendWatch = viewModelScope.launch { + // The held send leaves the sheet's attempt, so another payment can be signed beside it + if (pendingBroadcast?.signedTx == payment.signedTx) pendingBroadcast = null + val unresolved = UnresolvedHwSend(payment, send) + unresolvedSends.put(txId, unresolved)?.watch?.cancel() + unresolved.watch = viewModelScope.launch { hwWalletRepo.activities.first { activities -> activities.filterIsInstance().any { it.v1.walletId == send.walletId && it.v1.txId.equals(send.txId, ignoreCase = true) } } - completeUnresolvedSend(held, send) + completeUnresolvedSend(unresolved) + } + _uiState.update { + it.copy( + hasPendingBroadcast = pendingBroadcast != null, + unresolvedSend = send, + unresolvedSends = unresolvedSends.values.map { held -> held.send }.toImmutableList(), + ) + } + return unresolved + } + + private fun unresolvedSendFor(request: HwSendRequest): UnresolvedHwSend? = + unresolvedSends.values.firstOrNull { it.payment.request.isPaymentOf(request) } + + private fun dropUnresolvedSendsOfRemovedWallets() { + viewModelScope.launch { + var knownWalletIds = emptySet() + hwWalletRepo.wallets.collect { wallets -> + val walletIds = wallets.mapTo(mutableSetOf()) { it.id } + val removed = knownWalletIds - walletIds + knownWalletIds = walletIds + // A removed wallet's send stays held in the store, which guards it again once the wallet is back + unresolvedSends.values.filter { it.send.walletId in removed }.forEach { forgetUnresolvedSend(it) } + } + } + } + + private fun forgetUnresolvedSend(unresolved: UnresolvedHwSend) { + if (unresolvedSends[unresolved.send.txId] !== unresolved) return + unresolvedSends.remove(unresolved.send.txId) + unresolved.watch?.cancel() + _uiState.update { state -> + state.copy( + unresolvedSend = state.unresolvedSend?.takeUnless { it.txId == unresolved.send.txId }, + unresolvedSends = unresolvedSends.values.map { it.send }.toImmutableList(), + retryingSendTxIds = (state.retryingSendTxIds - unresolved.send.txId).toImmutableSet(), + ) } } /** - * Broadcasts the signed bytes of a send whose broadcast may have gone out once more, for when that broadcast never - * reached the server. Any failure keeps the send held, since the first broadcast may still confirm. + * Broadcasts the signed bytes of the held send [txId] once more, for when its broadcast never reached the server. + * Any failure keeps the send held, since the first broadcast may still confirm. */ - fun retryUnresolvedSend() { - val payment = pendingBroadcast?.takeIf { it.isOutcomeUnknown } ?: return - val send = _uiState.value.unresolvedSend ?: return - if (_uiState.value.isRetryingUnresolvedSend) return - _uiState.update { it.copy(isRetryingUnresolvedSend = true) } + fun retryUnresolvedSend(txId: String) { + val unresolved = unresolvedSends[txId.lowercase()] ?: return + val send = unresolved.send + if (send.txId in _uiState.value.retryingSendTxIds) return + _uiState.update { it.copy(retryingSendTxIds = (it.retryingSendTxIds + send.txId).toImmutableSet()) } viewModelScope.launch { try { - hwWalletRepo.broadcastFunding(payment.signedTx) - .onSuccess { completeUnresolvedSend(payment, send) } + hwWalletRepo.broadcastFunding(unresolved.payment.signedTx) + .onSuccess { completeUnresolvedSend(unresolved) } .onFailure { - if (pendingBroadcast !== payment) return@onFailure + if (unresolvedSends[send.txId] !== unresolved) return@onFailure // A refusal now does not prove the first broadcast was not delivered, so the send stays held val description = if (it.isHardwareBroadcastRefusalForNavigation()) { R.string.hardware__send_broadcast_refused_text @@ -374,17 +436,18 @@ class HwSendViewModel @Inject constructor( ) } } finally { - _uiState.update { it.copy(isRetryingUnresolvedSend = false) } + _uiState.update { it.copy(retryingSendTxIds = (it.retryingSendTxIds - send.txId).toImmutableSet()) } } } } /** - * Refuses a new hardware send while an earlier one may have gone out, saying so, and returns that earlier send to - * finish first; null when there is none. + * Refuses a new hardware send of a payment whose earlier broadcast may have gone out, saying so, and returns that + * earlier send to finish first; null when there is none. */ - fun refuseNewSend(): HwSendResult? { - val send = _uiState.value.unresolvedSend ?: return null + fun refuseNewSend(walletId: String, address: String, amountSats: ULong): HwSendResult? { + val send = unresolvedSends.values.firstOrNull { it.payment.request.isPaymentOf(walletId, address, amountSats) } + ?.send ?: return null viewModelScope.launch { ToastEventBus.send( type = Toast.ToastType.ERROR, @@ -395,17 +458,17 @@ class HwSendViewModel @Inject constructor( return send } - private suspend fun completeUnresolvedSend(payment: PendingHwSendBroadcast, send: HwSendResult) { - if (pendingBroadcast !== payment) return + private suspend fun completeUnresolvedSend(unresolved: UnresolvedHwSend) { // Known to be sent now, so neither the wallet's observation nor a retry completes it a second time - pendingBroadcast = payment.copy(isOutcomeUnknown = false) - val signedTx = payment.signedTx + if (unresolvedSends[unresolved.send.txId] !== unresolved) return + forgetUnresolvedSend(unresolved) + val send = unresolved.send + val signedTx = unresolved.payment.signedTx val result = HwFundingBroadcastResult(send.txId, signedTx.miningFeeSats, signedTx.feeRate, signedTx.totalSpent) - runSuspendCatching { persistResult(payment.request, result) } + runSuspendCatching { persistResult(unresolved.payment.request, result) } .onFailure { Logger.error("Failed to persist hardware send result", it, context = TAG) } releaseHeldSend(send.txId) - _uiState.update { it.copy(unresolvedSend = null) } - pendingResult.update { send } + _heldSendEvents.emit(HeldHwSendEvent.Completed(send)) } fun submitPassphrase( @@ -455,18 +518,14 @@ class HwSendViewModel @Inject constructor( fun cancel() { passphraseJob?.cancel() passphraseJob = null - _uiState.update { it.copy(isPassphraseRequired = false, isVerifyingPassphrase = false) } + _uiState.update { it.copy(isPassphraseRequired = false, isVerifyingPassphrase = false, unresolvedSend = null) } if (_uiState.value.isBroadcastUnresolved) return signingJob?.cancel() signingJob = null signingAttempt++ - // A refused Shop payment may leave the sheet, but its signed operation stays guarded, as does a send whose - // broadcast may have gone out. - if (pendingBroadcast?.let { - it.isOutcomeUnknown || it.request.paymentRequestId != null && it.hasAttemptedBroadcast - } != true - ) { + // A refused Shop payment may leave the sheet, but its signed operation stays guarded. + if (pendingBroadcast?.let { it.request.paymentRequestId != null && it.hasAttemptedBroadcast } != true) { pendingBroadcast = null } _uiState.update { @@ -505,8 +564,6 @@ class HwSendViewModel @Inject constructor( } fun completeBroadcast() { - unresolvedSendWatch?.cancel() - unresolvedSendWatch = null pendingBroadcast = null signingWalletId = null pendingResult.update { null } @@ -514,7 +571,6 @@ class HwSendViewModel @Inject constructor( it.copy( hasPendingBroadcast = false, isBroadcastUnresolved = false, - unresolvedSend = null, ) } } @@ -631,11 +687,6 @@ class HwSendViewModel @Inject constructor( _uiState.update { it.copy(isBroadcastUnresolved = retainedShopPayment && pendingBroadcast?.blocksNavigation == true) } - // The payment shows as pending until the wallet sees it, so it is not offered to be tried again - if (pendingBroadcast?.isOutcomeUnknown == true) { - Logger.warn("Held hardware send of '$walletId' after an unknown broadcast outcome", context = TAG) - return - } when { error.isHwUserCancellation() -> { Logger.info("Hardware send cancelled on device for '$walletId'", context = TAG) @@ -695,9 +746,11 @@ data class HwSendUiState( val isBroadcastUnresolved: Boolean = false, val isPassphraseRequired: Boolean = false, val isVerifyingPassphrase: Boolean = false, - /** A send whose broadcast may have gone out: it is pending until it is sent, and nothing is signed beside it. */ + /** The held send this sheet's attempt ran into, which the sheet shows as pending. */ val unresolvedSend: HwSendResult? = null, - val isRetryingUnresolvedSend: Boolean = false, + /** Sends whose broadcast may have gone out: each is pending until it is sent, and is never signed again. */ + val unresolvedSends: ImmutableList = persistentListOf(), + val retryingSendTxIds: ImmutableSet = persistentSetOf(), ) { /** * Whether the sign sheet may be dismissed. Connecting or unlocking can be abandoned, and leaving @@ -716,6 +769,12 @@ data class HwSendResult( val paymentIdentity: String? = null, ) +sealed interface HeldHwSendEvent { + val send: HwSendResult + + data class Completed(override val send: HwSendResult) : HeldHwSendEvent +} + data class HwSendRequest( val walletId: String, val address: String, @@ -725,7 +784,16 @@ data class HwSendRequest( val paymentRequestId: PaykitPaymentRequestId? = null, val paymentIdentity: String? = null, val paymentDeadlineAt: Instant? = null, -) +) { + fun isPaymentOf(walletId: String, address: String, amountSats: ULong): Boolean = + this.walletId == walletId && this.address.equals(address, ignoreCase = true) && this.amountSats == amountSats + + fun isPaymentOf(other: HwSendRequest): Boolean = isPaymentOf(other.walletId, other.address, other.amountSats) +} + +private class UnresolvedHwSend(val payment: PendingHwSendBroadcast, val send: HwSendResult) { + var watch: Job? = null +} private data class PendingHwSendBroadcast( val request: HwSendRequest, @@ -733,7 +801,6 @@ private data class PendingHwSendBroadcast( val isPreparedForBroadcast: Boolean = false, val hasAttemptedBroadcast: Boolean = false, val isRefusedForNavigation: Boolean = false, - val isOutcomeUnknown: Boolean = false, ) { val blocksNavigation: Boolean get() = hasAttemptedBroadcast && !isRefusedForNavigation diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt index 4c29505dfa..d93b21cc29 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt @@ -475,7 +475,7 @@ internal fun SendPendingContent( VerticalSpacer(16.dp) if (canRetryHardwareSend) { SecondaryButton( - text = stringResource(R.string.wallet__send_pending__retry_title), + text = stringResource(R.string.wallet__send_pending__broadcast_again), isLoading = isRetryingHardwareSend, enabled = !isRetryingHardwareSend, onClick = onRetryHardwareSend, diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index ae0ecbe4dd..f06ac28fb1 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -66,6 +66,7 @@ import to.bitkit.ui.screens.subscriptions.SubscriptionFirstPaymentProgress import to.bitkit.ui.screens.subscriptions.SubscriptionSuccess import to.bitkit.ui.screens.subscriptions.contactFor import to.bitkit.ui.screens.wallets.send.AddTagScreen +import to.bitkit.ui.screens.wallets.send.HeldHwSendEvent import to.bitkit.ui.screens.wallets.send.HwSendResult import to.bitkit.ui.screens.wallets.send.HwSendSignScreen import to.bitkit.ui.screens.wallets.send.HwSendViewModel @@ -247,6 +248,22 @@ fun SendSheet( } } } + LaunchedEffect(hwSendViewModel, navController) { + // A held send can complete long after its pending screen closed; only that screen shows its success + hwSendViewModel.heldSendEvents.collect { event -> + val route = navController.currentBackStackEntry + ?.takeIf { it.destination.hasRoute() } + ?.toRoute() + val send = event.send + if (route?.walletId != send.walletId || !route.paymentHash.equals(send.txId, ignoreCase = true)) { + return@collect + } + when (event) { + is HeldHwSendEvent.Completed -> + showHardwareSuccess(send.txId, send.amountSats, send.walletId, isShopPayment = false) + } + } + } LaunchedEffect(hwSendViewModel, navController) { hwSendViewModel.results.collect { result -> val resolved = appViewModel.resolvedHardwarePaymentFor(result.walletId, result.txId) @@ -311,7 +328,10 @@ fun SendSheet( } is SendEffect.NavigateToHardwareSign -> { // A send whose broadcast may have gone out is finished before a new one is signed - val unresolvedSend = hwSendViewModel.refuseNewSend() + val state = appViewModel.sendUiState.value + val unresolvedSend = state.hardwareWalletId?.let { walletId -> + hwSendViewModel.refuseNewSend(walletId, state.address, state.amount) + } if (unresolvedSend == null) { navController.navigateTo(SendRoute.HardwareSign) } else { @@ -789,11 +809,11 @@ fun SendSheet( onClose = { appViewModel.hideSheet() }, onViewDetails = { rawId -> appViewModel.navigateToActivity(rawId, route.walletId) }, viewModel = hiltViewModel(), - canRetryHardwareSend = hwSendUiState.unresolvedSend?.let { send -> + canRetryHardwareSend = hwSendUiState.unresolvedSends.any { send -> send.walletId == route.walletId && send.txId.equals(route.paymentHash, ignoreCase = true) - } == true, - isRetryingHardwareSend = hwSendUiState.isRetryingUnresolvedSend, - onRetryHardwareSend = hwSendViewModel::retryUnresolvedSend, + }, + isRetryingHardwareSend = route.paymentHash.lowercase() in hwSendUiState.retryingSendTxIds, + onRetryHardwareSend = { hwSendViewModel.retryUnresolvedSend(route.paymentHash) }, ) } composableWithDefaultTransitions { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 3f49fcb8a8..f61009f2a5 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1610,8 +1610,9 @@ اختر جهة اتصال من لم يتم إرسال الدفعة الجديدة. أكمل الدفعة السابقة قبل المحاولة مرة أخرى. + إعادة البث تستغرق هذه الدفعة وقتًا أطول قليلاً من المتوقع. يمكنك متابعة استخدام Bitkit. - تعذّر على Bitkit التأكد من أن الشبكة استلمت هذه الدفعة. تكتمل الدفعة بمجرد أن ترى محفظتك المعاملة. إن لم تظهر، استخدم «إعادة محاولة الدفعة الأصلية» لإرسال المعاملة الموقّعة نفسها مرة أخرى. تبقى مدفوعات محفظة الأجهزة الأخرى محظورة حتى ذلك الحين. + تعذّر على Bitkit التأكد من أن الشبكة استلمت هذه الدفعة. تكتمل الدفعة بمجرد أن ترى محفظتك المعاملة. إن لم تظهر، استخدم إعادة البث لإرسال المعاملة الموقّعة نفسها مرة أخرى. لن يوقّع Bitkit هذه الدفعة مرة أخرى حتى ذلك الحين. الدفعة معلقة نتيجة المعاملة لم تُحسم بعد. تحقق من حالتها قبل المحاولة مرة أخرى. تبقى المدفوعات الأخرى محظورة. إن توفر، استخدم «إعادة محاولة الدفعة الأصلية» لتفويض رسوم للدفعة نفسها. تم رفض البث: %1$s diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 8e8d6fd9e4..7e987c939d 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1006,7 +1006,7 @@ Saldo de reserva Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero revisa la red y luego devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. Este pago está tardando un poco más de lo esperado. Puede seguir utilizando Bitkit. - Bitkit no pudo confirmar que la red recibiera este pago. Se completará cuando su billetera vea la transacción. Si no aparece, use Reintentar pago original para enviar de nuevo la misma transacción firmada. Los demás pagos con billetera de hardware siguen bloqueados hasta entonces. + Bitkit no pudo confirmar que la red recibiera este pago. Se completará cuando su billetera vea la transacción. Si no aparece, use Transmitir de nuevo para enviar otra vez la misma transacción firmada. Bitkit no volverá a firmar este pago hasta entonces. Pago pendiente QuickPay Pagando\n<accent>factura...</accent> @@ -1614,6 +1614,7 @@ Aún no tiene contactos. Desde El nuevo pago no se envió. Termine el pago anterior antes de volver a intentarlo. + Transmitir de nuevo El resultado de la transacción no está resuelto. Revise su estado antes de volver a intentarlo. Los demás pagos siguen bloqueados. Si está disponible, use Reintentar pago original para autorizar una comisión para el mismo pago. Transmisión rechazada: %1$s Autorizar reintento diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 8a8b9c43b1..e32c977693 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1610,8 +1610,9 @@ Encara no tens cap contacte. Des de El pagament nou no s\'ha enviat. Finalitza el pagament anterior abans de tornar-ho a provar. + Tornar a difondre Aquest pagament està trigant una mica més del previst. Pots continuar utilitzant Bitkit. - Bitkit no ha pogut confirmar que la xarxa hagi rebut aquest pagament. Es completarà quan la teva cartera vegi la transacció. Si no apareix, utilitza Reintentar el pagament original per tornar a enviar la mateixa transacció signada. Els altres pagaments amb cartera de maquinari continuen bloquejats fins aleshores. + Bitkit no ha pogut confirmar que la xarxa hagi rebut aquest pagament. Es completarà quan la teva cartera vegi la transacció. Si no apareix, utilitza Tornar a difondre per enviar de nou la mateixa transacció signada. Bitkit no tornarà a signar aquest pagament fins aleshores. El resultat de la transacció està sense resoldre. Comprova\'n l\'estat abans de tornar-ho a provar. Els altres pagaments continuen bloquejats. Si està disponible, utilitza Reintentar el pagament original per autoritzar una tarifa per al mateix pagament. Difusió rebutjada: %1$s Autoritzar el reintent diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 6801d093c6..16699307e5 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1004,7 +1004,7 @@ Zůstatek rezervy Převody na útratový zůstatek už nejsou dostupné. Bitkit nejprve zkontroluje síť a pak vrátí mince tohoto převodu do vaší peněženky, aby se původní převod nikdy nepotvrdil. Stojí to síťový poplatek. Tato platba trvá o něco déle, než se očekávalo. Bitkit můžete používat i nadále. - Bitkit nemohl potvrdit, že síť tuto platbu přijala. Platba se dokončí, jakmile vaše peněženka transakci uvidí. Pokud se neobjeví, použijte Zopakovat původní platbu a odešlete stejnou podepsanou transakci znovu. Ostatní platby z hardwarové peněženky do té doby zůstávají zablokované. + Bitkit nemohl potvrdit, že síť tuto platbu přijala. Platba se dokončí, jakmile vaše peněženka transakci uvidí. Pokud se neobjeví, použijte Odeslat znovu do sítě a odešlete stejnou podepsanou transakci znovu. Do té doby Bitkit tuto platbu znovu nepodepíše. Platba čeká na vyřízení QuickPay Placení\n<accent>faktury...</accent> @@ -1615,6 +1615,7 @@ Zatím nemáte žádné kontakty. Z Nová platba nebyla odeslána. Před dalším pokusem dokončete předchozí platbu. + Odeslat znovu do sítě Výsledek transakce není vyřešen. Před dalším pokusem zkontrolujte její stav. Ostatní platby zůstávají zablokované. Je-li k dispozici, použijte Zopakovat původní platbu a autorizujte poplatek pro stejnou platbu. Odeslání do sítě odmítnuto: %1$s Autorizovat opakování diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 7e856baeb2..9dfc1dbcd7 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -853,7 +853,7 @@ Verfügbar (ausgeben) Reserve-Saldo Diese Zahlung dauert länger als erwartet. Du kannst Bitkit weiterhin verwenden. - Bitkit konnte nicht bestätigen, dass das Netzwerk diese Zahlung erhalten hat. Sie wird abgeschlossen, sobald dein Wallet die Transaktion sieht. Erscheint sie nicht, nutze „Ursprüngliche Zahlung wiederholen“, um dieselbe signierte Transaktion erneut zu senden. Andere Hardware-Wallet-Zahlungen bleiben bis dahin blockiert. + Bitkit konnte nicht bestätigen, dass das Netzwerk diese Zahlung erhalten hat. Sie wird abgeschlossen, sobald dein Wallet die Transaktion sieht. Erscheint sie nicht, nutze „Erneut senden“, um dieselbe signierte Transaktion noch einmal zu senden. Bis dahin signiert Bitkit diese Zahlung nicht erneut. Zahlung ausstehend Der maximal auszahlbare Betrag ist etwas niedriger, da eine Reserve erforderlich ist. Bestätigen @@ -1612,6 +1612,7 @@ Du hast noch keine Kontakte. Von Die neue Zahlung wurde nicht gesendet. Schließe die vorherige Zahlung ab, bevor du es erneut versuchst. + Erneut senden Das Ergebnis der Transaktion ist ungeklärt. Überprüfe ihren Status, bevor du es erneut versuchst. Andere Zahlungen bleiben blockiert. Falls verfügbar, nutze „Ursprüngliche Zahlung wiederholen“, um eine Gebühr für dieselbe Zahlung zu autorisieren. Übertragung verweigert: %1$s Wiederholung autorisieren diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 984ffbfc51..c2c597f679 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1607,8 +1607,9 @@ Επιλογή επαφής Από Η νέα πληρωμή δεν στάλθηκε. Ολοκλήρωσε την προηγούμενη πληρωμή πριν δοκιμάσεις ξανά. + Εκ νέου μετάδοση Αυτή η πληρωμή διαρκεί λίγο περισσότερο από το αναμενόμενο. Μπορείς να συνεχίσεις να χρησιμοποιείς το Bitkit. - Το Bitkit δεν μπόρεσε να επιβεβαιώσει ότι το δίκτυο έλαβε αυτή την πληρωμή. Θα ολοκληρωθεί μόλις το πορτοφόλι σου δει τη συναλλαγή. Αν δεν εμφανιστεί, χρησιμοποίησε την Επανάληψη αρχικής πληρωμής για να στείλεις ξανά την ίδια υπογεγραμμένη συναλλαγή. Οι άλλες πληρωμές από πορτοφόλι υλικού παραμένουν μπλοκαρισμένες μέχρι τότε. + Το Bitkit δεν μπόρεσε να επιβεβαιώσει ότι το δίκτυο έλαβε αυτή την πληρωμή. Θα ολοκληρωθεί μόλις το πορτοφόλι σου δει τη συναλλαγή. Αν δεν εμφανιστεί, χρησιμοποίησε την Εκ νέου μετάδοση για να στείλεις ξανά την ίδια υπογεγραμμένη συναλλαγή. Μέχρι τότε το Bitkit δεν θα υπογράψει ξανά αυτή την πληρωμή. Πληρωμή σε εκκρεμότητα Το αποτέλεσμα της συναλλαγής δεν έχει επιλυθεί. Έλεγξε την κατάστασή της πριν δοκιμάσεις ξανά. Οι άλλες πληρωμές παραμένουν μπλοκαρισμένες. Αν είναι διαθέσιμο, χρησιμοποίησε την Επανάληψη αρχικής πληρωμής για να εγκρίνεις τέλος για την ίδια πληρωμή. Η μετάδοση απορρίφθηκε: %1$s diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 5e60195462..00c937fe35 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1609,8 +1609,9 @@ Aún no tienes ningún contacto. Desde El nuevo pago no se envió. Finaliza el pago anterior antes de volver a intentarlo. + Transmitir de nuevo Este pago está tardando un poco más de lo esperado. Puedes seguir usando Bitkit. - Bitkit no pudo confirmar que la red recibiera este pago. Se completará cuando tu monedero vea la transacción. Si no aparece, usa Reintentar el pago original para enviar de nuevo la misma transacción firmada. Los demás pagos con monedero de hardware siguen bloqueados hasta entonces. + Bitkit no pudo confirmar que la red recibiera este pago. Se completará cuando tu monedero vea la transacción. Si no aparece, usa Transmitir de nuevo para enviar otra vez la misma transacción firmada. Bitkit no volverá a firmar este pago hasta entonces. Pago pendiente El resultado de la transacción está sin resolver. Comprueba su estado antes de volver a intentarlo. Los demás pagos siguen bloqueados. Si está disponible, usa Reintentar el pago original para autorizar una comisión para el mismo pago. Difusión rechazada: %1$s diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 57363cc6ba..aad5bb0cfd 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1609,8 +1609,9 @@ Aún no tiene ningún contacto. Desde El nuevo pago no se envió. Finalice el pago anterior antes de volver a intentarlo. + Transmitir de nuevo Este pago está tardando un poco más de lo esperado. Puede seguir usando Bitkit. - Bitkit no pudo confirmar que la red recibiera este pago. Se completará cuando su monedero vea la transacción. Si no aparece, use Reintentar el pago original para enviar de nuevo la misma transacción firmada. Los demás pagos con monedero de hardware siguen bloqueados hasta entonces. + Bitkit no pudo confirmar que la red recibiera este pago. Se completará cuando su monedero vea la transacción. Si no aparece, use Transmitir de nuevo para enviar otra vez la misma transacción firmada. Bitkit no volverá a firmar este pago hasta entonces. Pago pendiente El resultado de la transacción está sin resolver. Compruebe su estado antes de volver a intentarlo. Los demás pagos siguen bloqueados. Si está disponible, use Reintentar el pago original para autorizar una comisión para el mismo pago. Difusión rechazada: %1$s diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 589fb28c38..c638ed8f6d 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -854,7 +854,7 @@ Disponible (dépenses) Solde Réserve Ce paiement prend un peu plus de temps que prévu. Vous pouvez continuer à utiliser Bitkit. - Bitkit n\'a pas pu confirmer que le réseau a reçu ce paiement. Il sera finalisé dès que votre portefeuille verra la transaction. Si elle n\'apparaît pas, utilisez Réessayer le paiement d\'origine pour renvoyer la même transaction signée. Les autres paiements avec un portefeuille matériel restent bloqués d\'ici là. + Bitkit n\'a pas pu confirmer que le réseau a reçu ce paiement. Il sera finalisé dès que votre portefeuille verra la transaction. Si elle n\'apparaît pas, utilisez Diffuser à nouveau pour renvoyer la même transaction signée. D\'ici là, Bitkit ne signera pas ce paiement une nouvelle fois. Paiement en attente Le montant maximum pouvant être dépensé est un peu moins élevé en raison d\'un solde de Réserve requis. Confirmer @@ -1614,6 +1614,7 @@ Vous n\'avez pas encore de contacts. De Le nouveau paiement n\'a pas été envoyé. Terminez le paiement précédent avant de réessayer. + Diffuser à nouveau Le résultat de la transaction n\'est pas résolu. Vérifiez son état avant de réessayer. Les autres paiements restent bloqués. Si disponible, utilisez Réessayer le paiement d\'origine pour autoriser des frais pour ce même paiement. Diffusion refusée : %1$s Autoriser la nouvelle tentative diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 7c4ace6275..2cdf0e5e5b 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1002,7 +1002,7 @@ Saldo di Riserva I trasferimenti al saldo di spesa non sono più disponibili. Bitkit controlla prima la rete, poi rimanda le monete di questo trasferimento al tuo wallet, così il trasferimento originale non potrà mai essere confermato. Questo costa una commissione di rete. Questo pagamento sta richiedendo un po\' più tempo del previsto. Puoi continuare a utilizzare Bitkit. - Bitkit non è riuscito a confermare che la rete abbia ricevuto questo pagamento. Si completerà non appena il tuo wallet vedrà la transazione. Se non compare, usa Riprova pagamento originale per inviare di nuovo la stessa transazione firmata. Gli altri pagamenti con hardware wallet restano bloccati fino ad allora. + Bitkit non è riuscito a confermare che la rete abbia ricevuto questo pagamento. Si completerà non appena il tuo wallet vedrà la transazione. Se non compare, usa Trasmetti di nuovo per inviare di nuovo la stessa transazione firmata. Fino ad allora Bitkit non firmerà di nuovo questo pagamento. Pagamento in sospeso QuickPay Pagamento\n<accent>fattura...</accent> @@ -1614,6 +1614,7 @@ Non hai ancora nessun contatto. Da Il nuovo pagamento non è stato inviato. Completa il pagamento precedente prima di riprovare. + Trasmetti di nuovo L\'esito della transazione non è risolto. Controlla il suo stato prima di riprovare. Gli altri pagamenti restano bloccati. Se disponibile, usa Riprova pagamento originale per autorizzare una commissione per lo stesso pagamento. Trasmissione rifiutata: %1$s Autorizza nuovo tentativo diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 77fa39355b..fa9335769f 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -997,7 +997,7 @@ Reservesaldo Overboekingen naar je bestedingssaldo zijn niet meer beschikbaar. Bitkit controleert eerst het netwerk en stuurt de munten van deze overboeking dan terug naar je wallet, zodat de oorspronkelijke overboeking nooit bevestigd wordt. Dit kost netwerkkosten. Deze betaling duurt iets langer dan verwacht. U kunt Bitkit blijven gebruiken. - Bitkit kon niet bevestigen dat het netwerk deze betaling heeft ontvangen. De betaling wordt voltooid zodra uw wallet de transactie ziet. Verschijnt deze niet, gebruik dan ‘Oorspronkelijke betaling opnieuw proberen’ om dezelfde ondertekende transactie opnieuw te verzenden. Andere betalingen met een hardwarewallet blijven tot dan geblokkeerd. + Bitkit kon niet bevestigen dat het netwerk deze betaling heeft ontvangen. De betaling wordt voltooid zodra uw wallet de transactie ziet. Verschijnt deze niet, gebruik dan ‘Opnieuw uitzenden’ om dezelfde ondertekende transactie opnieuw te versturen. Tot die tijd ondertekent Bitkit deze betaling niet opnieuw. Betaling Onderweg QuickPay Factuur\n<accent>betalen...</accent> @@ -1613,6 +1613,7 @@ U hebt nog geen contacten. Van De nieuwe betaling is niet verzonden. Rond de vorige betaling af voordat u het opnieuw probeert. + Opnieuw uitzenden De uitkomst van de transactie is onbekend. Controleer de status voordat u het opnieuw probeert. Andere betalingen blijven geblokkeerd. Gebruik indien beschikbaar ‘Oorspronkelijke betaling opnieuw proberen’ om een vergoeding voor dezelfde betaling te autoriseren. Verzending geweigerd: %1$s Nieuwe poging autoriseren diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 43547ae262..ba5f657f78 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -856,7 +856,7 @@ Dostępne (na wydawanie) Saldo rezerwy Ta płatność trwa nieco dłużej niż oczekiwano. Możesz kontynuować korzystanie z Bitkit. - Bitkit nie mógł potwierdzić, że sieć otrzymała tę płatność. Zostanie ona zakończona, gdy Twój portfel zobaczy transakcję. Jeśli się nie pojawi, użyj opcji Ponów oryginalną płatność, aby ponownie wysłać tę samą podpisaną transakcję. Inne płatności z portfela sprzętowego pozostają do tego czasu zablokowane. + Bitkit nie mógł potwierdzić, że sieć otrzymała tę płatność. Zostanie ona zakończona, gdy Twój portfel zobaczy transakcję. Jeśli się nie pojawi, użyj opcji Roześlij ponownie, aby wysłać tę samą podpisaną transakcję jeszcze raz. Do tego czasu Bitkit nie podpisze tej płatności ponownie. Płatność w toku Maksymalna kwota do wydania jest nieco niższa ze względu na wymagane saldo rezerwowe. Potwierdź @@ -1614,6 +1614,7 @@ Nie masz jeszcze żadnych kontaktów. Z Nowa płatność nie została wysłana. Dokończ poprzednią płatność, zanim spróbujesz ponownie. + Roześlij ponownie Wynik transakcji jest nierozstrzygnięty. Sprawdź jej status, zanim spróbujesz ponownie. Inne płatności pozostają zablokowane. Jeśli to możliwe, użyj opcji Ponów oryginalną płatność, aby zatwierdzić opłatę dla tej samej płatności. Rozgłoszenie odrzucone: %1$s Zatwierdź ponowienie diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index cb925c4a97..50062f4db0 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1006,7 +1006,7 @@ Saldo de reserva As transferências para o saldo de gastos não estão mais disponíveis. O Bitkit primeiro verifica a rede e depois devolve as moedas desta transferência para sua carteira, para que a transferência original nunca seja confirmada. Isso tem uma taxa de rede. Esse pagamento está demorando mais do que o esperado. Enquanto isso, você pode continuar usando a Bitkit. - A Bitkit não conseguiu confirmar que a rede recebeu este pagamento. Ele será concluído assim que sua carteira vir a transação. Se ela não aparecer, use Tentar novamente o pagamento original para enviar de novo a mesma transação assinada. Outros pagamentos com carteira de hardware continuam bloqueados até lá. + A Bitkit não conseguiu confirmar que a rede recebeu este pagamento. Ele será concluído assim que sua carteira vir a transação. Se ela não aparecer, use Transmitir novamente para enviar de novo a mesma transação assinada. Até lá, a Bitkit não assinará este pagamento novamente. Pagamento Pendente QuickPay Pagando \n<accent>invoice...</accent> @@ -1614,6 +1614,7 @@ Você ainda não tem nenhum contato. De O novo pagamento não foi enviado. Conclua o pagamento anterior antes de tentar novamente. + Transmitir novamente O resultado da transação não foi resolvido. Verifique o status dela antes de tentar novamente. Outros pagamentos continuam bloqueados. Se disponível, use Tentar novamente o pagamento original para autorizar uma taxa para o mesmo pagamento. Transmissão recusada: %1$s Autorizar nova tentativa diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 0f6e246555..0d01e80d50 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1608,8 +1608,9 @@ Selecionar contacto De O novo pagamento não foi enviado. Conclua o pagamento anterior antes de tentar novamente. + Transmitir novamente Este pagamento está a demorar um pouco mais do que o previsto. Pode continuar a usar a Bitkit. - A Bitkit não conseguiu confirmar que a rede recebeu este pagamento. Fica concluído assim que a sua carteira vir a transação. Se não aparecer, use Repetir pagamento original para enviar novamente a mesma transação assinada. Os outros pagamentos com carteira de hardware continuam bloqueados até lá. + A Bitkit não conseguiu confirmar que a rede recebeu este pagamento. Fica concluído assim que a sua carteira vir a transação. Se não aparecer, use Transmitir novamente para enviar de novo a mesma transação assinada. Até lá, a Bitkit não volta a assinar este pagamento. Pagamento pendente O resultado da transação não está resolvido. Verifique o estado antes de tentar novamente. Os outros pagamentos continuam bloqueados. Se disponível, use Repetir pagamento original para autorizar uma taxa para o mesmo pagamento. Difusão recusada: %1$s diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 270d6e3320..b38a494cb3 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1021,7 +1021,7 @@ Резервный баланс Переводы на баланс расходов больше недоступны. Bitkit сначала проверяет сеть, а затем возвращает монеты этого перевода в ваш кошелёк, чтобы исходный перевод никогда не подтвердился. За это взимается сетевая комиссия. Этот платеж занимает больше времени, чем ожидалось. Вы можете продолжать использовать Bitkit. - Bitkit не удалось подтвердить, что сеть получила этот платёж. Он завершится, как только ваш кошелёк увидит транзакцию. Если она не появится, используйте «Повторить исходный платёж», чтобы снова отправить ту же подписанную транзакцию. Другие платежи с аппаратного кошелька до тех пор остаются заблокированными. + Bitkit не удалось подтвердить, что сеть получила этот платёж. Он завершится, как только ваш кошелёк увидит транзакцию. Если она не появится, нажмите «Отправить в сеть снова», чтобы повторно отправить ту же подписанную транзакцию. До тех пор Bitkit не будет подписывать этот платёж снова. Платеж в ожидании QuickPay Оплата @@ -1629,6 +1629,7 @@ У вас пока нет контактов. Откуда Новый платёж не отправлен. Завершите предыдущий платёж, прежде чем пробовать снова. + Отправить в сеть снова Результат транзакции не определён. Проверьте её статус, прежде чем пробовать снова. Другие платежи остаются заблокированными. Если доступно, используйте «Повторить исходный платёж», чтобы разрешить комиссию для того же платежа. Отправка отклонена: %1$s Разрешить повтор diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e36ee167fa..299c66c01a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1554,8 +1554,9 @@ Bitkit could not sync with the network. Check your connection and try again. Transfers to spending are no longer available. Bitkit first checks the network, then sends this transfer\'s coins back to your wallet so the original transfer can never confirm. This costs a network fee. The new payment was not sent. Finish the previous payment before trying again. + Broadcast again This payment is taking a bit longer than expected. You can continue using Bitkit. - Bitkit could not confirm that the network received this payment. It completes once your wallet sees the transaction. If it does not appear, use Retry original payment to send the same signed transaction again. Other hardware wallet payments remain blocked until then. + Bitkit could not confirm that the network received this payment. It completes once your wallet sees the transaction. If it does not appear, use Broadcast again to send the same signed transaction again. Bitkit will not sign this payment again until then. Payment Pending The transaction outcome is unresolved. Check its status before trying again. Other payments remain blocked. If available, use Retry original payment to authorize a fee for the same payment. Broadcast refused: %1$s diff --git a/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt index 108a91a6ea..ba258a1e5d 100644 --- a/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt @@ -371,6 +371,7 @@ class HwWalletRepoTest : BaseUnitTest() { val sut = createRepo() assertEquals(held, sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS, 25_000uL).getOrThrow()) + assertEquals(held, sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS.uppercase(), 25_000uL).getOrThrow()) assertNull(sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS, 25_001uL).getOrThrow()) assertNull(sut.heldSendFor("other-wallet", HELD_ADDRESS, 25_000uL).getOrThrow()) diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt index 0931448551..d9c31ef29d 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt @@ -40,8 +40,10 @@ import to.bitkit.models.HwConnectedDevice import to.bitkit.models.HwFundingBroadcastResult import to.bitkit.models.HwFundingSignedTx import to.bitkit.models.HwFundingTransaction +import to.bitkit.models.HwWallet import to.bitkit.models.HwWalletVendor import to.bitkit.models.Toast +import to.bitkit.models.TransportType import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.HwWalletMismatchError import to.bitkit.repositories.HwWalletRepo @@ -76,6 +78,7 @@ class HwSendViewModelTest : BaseUnitTest() { private val activityRepo = mock() private val proofRepo = mock() private val walletActivities = MutableStateFlow>(persistentListOf()) + private val hwWallets = MutableStateFlow>(persistentListOf(hwWallet(WALLET_ID))) private lateinit var sut: HwSendViewModel private var now = Instant.parse("2026-10-06T11:59:59Z") @@ -120,6 +123,7 @@ class HwSendViewModelTest : BaseUnitTest() { } whenever { hwWalletRepo.reconnectTimeout(any()) }.thenReturn(30.seconds) whenever(hwWalletRepo.activities).thenReturn(walletActivities) + whenever(hwWalletRepo.wallets).thenReturn(hwWallets) whenever { hwWalletRepo.heldSendFor(any(), any(), any()) }.thenReturn(Result.success(null)) whenever { hwWalletRepo.holdSend(any()) }.thenReturn(Result.success(Unit)) whenever { hwWalletRepo.releaseHeldSend(any()) }.thenReturn(Result.success(Unit)) @@ -513,7 +517,7 @@ class HwSendViewModelTest : BaseUnitTest() { advanceUntilIdle() assertFalse(sut.uiState.value.isBroadcastUnresolved) - assertTrue(sut.uiState.value.hasPendingBroadcast) + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) assertFalse(sut.uiState.value.isSigning) } @@ -623,7 +627,7 @@ class HwSendViewModelTest : BaseUnitTest() { whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) .thenReturn(Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE))) val results = mutableListOf() - backgroundScope.launch { sut.results.collect { results += it } } + backgroundScope.launch { sut.heldSendEvents.collect { results += it.send } } sut.signAndBroadcast(request()) advanceUntilIdle() @@ -636,7 +640,7 @@ class HwSendViewModelTest : BaseUnitTest() { advanceUntilIdle() assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), results) - assertNull(sut.uiState.value.unresolvedSend) + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) verify(activityService).createSentOnchainActivityFromSendResult( txid = SIGNED_TXID, address = ADDRESS, @@ -710,7 +714,7 @@ class HwSendViewModelTest : BaseUnitTest() { .thenReturn(Result.success(heldSend(fixture.signedTx))) whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn(Result.success(fixture.broadcast)) val results = mutableListOf() - backgroundScope.launch { sut.results.collect { results += it } } + backgroundScope.launch { sut.heldSendEvents.collect { results += it.send } } sut.signAndBroadcast(request()) advanceUntilIdle() @@ -719,9 +723,9 @@ class HwSendViewModelTest : BaseUnitTest() { verify(hwWalletRepo, never()).broadcastFunding(any(), anyOrNull()) assertEquals(1, toasts.count { it.description == "blocked" }) assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.uiState.value.unresolvedSend) - assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.refuseNewSend()) + assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.refuseNewSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) - sut.retryUnresolvedSend() + sut.retryUnresolvedSend(SIGNED_TXID) advanceUntilIdle() toastJob.cancel() @@ -781,7 +785,7 @@ class HwSendViewModelTest : BaseUnitTest() { Result.success(fixture.broadcast), ) val results = mutableListOf() - backgroundScope.launch { sut.results.collect { results += it } } + backgroundScope.launch { sut.heldSendEvents.collect { results += it.send } } val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) sut.signAndBroadcast(request()) @@ -789,25 +793,24 @@ class HwSendViewModelTest : BaseUnitTest() { sut.cancel() advanceUntilIdle() repeat(2) { - sut.retryUnresolvedSend() + sut.retryUnresolvedSend(SIGNED_TXID) advanceUntilIdle() - assertEquals(held, sut.uiState.value.unresolvedSend) - assertTrue(sut.uiState.value.hasPendingBroadcast) - assertFalse(sut.uiState.value.isRetryingUnresolvedSend) + assertEquals(listOf(held), sut.uiState.value.unresolvedSends) + assertTrue(sut.uiState.value.retryingSendTxIds.isEmpty()) } assertTrue(results.isEmpty()) assertEquals(1, toasts.count { it.description == "try again" }) assertEquals(1, toasts.count { it.description == "refused" }) - sut.retryUnresolvedSend() + sut.retryUnresolvedSend(SIGNED_TXID) advanceUntilIdle() walletActivities.value = persistentListOf(sentActivity()) advanceUntilIdle() toastJob.cancel() assertEquals(listOf(held), results) - assertNull(sut.uiState.value.unresolvedSend) + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) verify(hwWalletRepo, times(1)).signFunding(any(), any()) verify(hwWalletRepo, times(4)).broadcastFunding(fixture.signedTx) verify(activityService, times(1)).createSentOnchainActivityFromSendResult( @@ -836,18 +839,17 @@ class HwSendViewModelTest : BaseUnitTest() { Result.failure(BroadcastException.ElectrumException(INPUTS_SPENT)), ) val results = mutableListOf() - backgroundScope.launch { sut.results.collect { results += it } } + backgroundScope.launch { sut.heldSendEvents.collect { results += it.send } } sut.signAndBroadcast(request()) advanceUntilIdle() - sut.retryUnresolvedSend() + sut.retryUnresolvedSend(SIGNED_TXID) advanceUntilIdle() toastJob.cancel() assertEquals(1, toasts.count { it.description == "refused" }) assertEquals(0, toasts.count { it.description == "try again" }) - assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.uiState.value.unresolvedSend) - assertTrue(sut.uiState.value.hasPendingBroadcast) + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) assertTrue(results.isEmpty()) } @@ -862,13 +864,13 @@ class HwSendViewModelTest : BaseUnitTest() { whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) .thenReturn(Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE))) - assertNull(sut.refuseNewSend()) + assertNull(sut.refuseNewSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) sut.signAndBroadcast(request()) advanceUntilIdle() sut.cancel() advanceUntilIdle() - assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.refuseNewSend()) + assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.refuseNewSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) advanceUntilIdle() assertEquals(1, toasts.count { it.description == "blocked" }) @@ -877,10 +879,79 @@ class HwSendViewModelTest : BaseUnitTest() { sut.completeBroadcast() toastJob.cancel() - assertNull(sut.refuseNewSend()) + assertNull(sut.refuseNewSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) assertEquals(1, toasts.count { it.description == "blocked" }) } + @Test + fun `a held send blocks only its own payment`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE)), + Result.success(fixture.broadcast), + ) + val other = request().copy(amountSats = AMOUNT_SATS + 1uL) + whenever(hwWalletRepo.composeFundingTransaction(WALLET_ID, ADDRESS, other.amountSats, SATS_PER_VBYTE)) + .thenReturn(Result.success(fixture.funding)) + val results = mutableListOf() + backgroundScope.launch { sut.results.collect { results += it } } + + sut.signAndBroadcast(request()) + advanceUntilIdle() + sut.cancel() + advanceUntilIdle() + + assertNull(sut.refuseNewSend(WALLET_ID, ADDRESS, other.amountSats)) + assertNull(sut.refuseNewSend(OTHER_WALLET_ID, ADDRESS, AMOUNT_SATS)) + sut.signAndBroadcast(other) + advanceUntilIdle() + + verify(hwWalletRepo, times(2)).signFunding(WALLET_ID, fixture.funding) + assertEquals(listOf(fixture.broadcast.txId), results.map { it.txId }) + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) + } + + @Test + fun `removing a wallet forgets its held send for the session`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) + .thenReturn(Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE))) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + hwWallets.value = persistentListOf(hwWallet(OTHER_WALLET_ID)) + advanceUntilIdle() + + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) + assertNull(sut.uiState.value.unresolvedSend) + assertNull(sut.refuseNewSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) + verify(hwWalletRepo, never()).releaseHeldSend(any()) + } + + @Test + fun `a held send completed while no sheet listens is not replayed as a result`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) + .thenReturn(Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE))) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + sut.cancel() + walletActivities.value = persistentListOf(sentActivity()) + advanceUntilIdle() + val replayed = mutableListOf() + backgroundScope.launch { sut.results.collect { replayed += it } } + backgroundScope.launch { sut.heldSendEvents.collect { replayed += it } } + advanceUntilIdle() + + assertTrue(replayed.isEmpty()) + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) + } + private suspend fun TestScope.assertCancelReleasesSignedTransaction(error: Throwable) { whenever(context.getString(any())).thenReturn("message") val fixture = stubSuccessfulPayment() @@ -927,19 +998,18 @@ class HwSendViewModelTest : BaseUnitTest() { assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.uiState.value.unresolvedSend) sut.cancel() advanceUntilIdle() - assertTrue(sut.uiState.value.hasPendingBroadcast) - assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.uiState.value.unresolvedSend) + val held = listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)) + assertEquals(held, sut.uiState.value.unresolvedSends) - sut.signAndBroadcast(request()) - advanceUntilIdle() - sut.signAndBroadcast(request().copy(amountSats = AMOUNT_SATS + 1uL)) + sut.signAndBroadcast(request().copy(address = ADDRESS.uppercase())) advanceUntilIdle() toastJob.cancel() verify(hwWalletRepo, times(1)).signFunding(any(), any()) verify(hwWalletRepo, times(1)).broadcastFunding(any(), anyOrNull()) - assertEquals(2, toasts.count { it.description == "blocked" }) - assertTrue(sut.uiState.value.hasPendingBroadcast) + assertEquals(1, toasts.count { it.description == "blocked" }) + assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.uiState.value.unresolvedSend) + assertEquals(held, sut.uiState.value.unresolvedSends) assertTrue(sut.uiState.value.canLeave) } @@ -1048,6 +1118,7 @@ class HwSendViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.isSigning) sut.cancel() assertFalse(sut.uiState.value.hasPendingBroadcast) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) } @Test @@ -1169,6 +1240,8 @@ class HwSendViewModelTest : BaseUnitTest() { assertTrue(sut.uiState.value.hasPendingBroadcast) assertTrue(sut.uiState.value.isBroadcastUnresolved) verify(hwWalletRepo).signFunding(WALLET_ID, fixture.funding) + // Only the first broadcast, which could not connect, released its hold + verify(hwWalletRepo, times(1)).releaseHeldSend(SIGNED_TXID) } @Test @@ -1911,6 +1984,16 @@ class HwSendViewModelTest : BaseUnitTest() { private fun connectedDevice() = HwConnectedDevice(vendor = HwWalletVendor.TREZOR, id = "dev1") + private fun hwWallet(id: String) = HwWallet( + id = id, + name = id, + model = null, + transportType = TransportType.USB, + isConnected = true, + balanceSats = 100_000uL, + activities = persistentListOf(), + ) + private fun sentActivity(walletId: String = WALLET_ID) = Activity.Onchain( OnchainActivity.create( walletId = walletId, @@ -1926,6 +2009,7 @@ class HwSendViewModelTest : BaseUnitTest() { private companion object { const val WALLET_ID = "hardware-wallet" + const val OTHER_WALLET_ID = "other-wallet" const val SIGNED_TXID = "605fe246a6d51450ecff51ac3d0415f8824964e06a60ed6e186fa163cf1e9d4e" const val CONNECT_FAILURE = "Failed to connect to Electrum: I/O error: Connection refused (os error 111)" const val LOST_AFTER_WRITE = From 54a65012b84e2c941eb0758df04782f3bec06a5d Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 09:39:01 -0500 Subject: [PATCH 05/14] fix: show a hanging hardware broadcast as pending Co-Authored-By: Claude Opus 5.5 --- .../screens/wallets/send/HwSendViewModel.kt | 115 ++++++++++++++---- .../wallets/send/HwSendViewModelTest.kt | 115 ++++++++++++++++-- 2 files changed, 194 insertions(+), 36 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index c6ff640998..c74514689a 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -14,8 +14,11 @@ import kotlinx.collections.immutable.persistentSetOf import kotlinx.collections.immutable.toImmutableList import kotlinx.collections.immutable.toImmutableSet import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Deferred import kotlinx.coroutines.Job import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow @@ -26,7 +29,9 @@ import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.R import to.bitkit.data.HeldHwSend import to.bitkit.ext.isBroadcastConnectivityFailure @@ -53,11 +58,14 @@ import to.bitkit.repositories.PaykitPaymentRequestId import to.bitkit.repositories.PreActivityMetadataRepo import to.bitkit.services.CoreService import to.bitkit.ui.shared.toast.ToastEventBus +import to.bitkit.utils.AppError import to.bitkit.utils.HwErrorPresenter import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError import to.bitkit.utils.SignedTransactionId +import java.util.concurrent.atomic.AtomicBoolean import javax.inject.Inject +import kotlin.coroutines.ContinuationInterceptor import kotlin.time.Clock import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant @@ -76,6 +84,9 @@ class HwSendViewModel @Inject constructor( const val TAG = "HwSendViewModel" val COMPOSE_TIMEOUT = 45.seconds val SIGN_TIMEOUT = 120.seconds + + /** How long the sheet waits for a broadcast before showing it as pending; the broadcast itself runs on. */ + val BROADCAST_WAIT = 120.seconds } val wallets: StateFlow> @@ -216,9 +227,14 @@ class HwSendViewModel @Inject constructor( return@runCatching } val result = broadcast(payment, onPaymentDeadlineExpired) ?: return@runCatching - if (signingAttempt != attempt) return@runCatching - runSuspendCatching { persistResult(request, result) } - .onFailure { Logger.error("Failed to persist hardware send result", it, context = TAG) } + if (signingAttempt == attempt) { + runSuspendCatching { persistResult(request, result) } + .onFailure { Logger.error("Failed to persist hardware send result", it, context = TAG) } + } + // Released once the send is recorded, so an app killed before that still holds it + if (request.paymentRequestId == null) { + releaseHeldSend(SignedTransactionId.fromHex(payment.signedTx.serializedTx)) + } if (signingAttempt != attempt) return@runCatching pendingResult.update { HwSendResult( @@ -291,39 +307,37 @@ class HwSendViewModel @Inject constructor( val request = payment.request val requestId = request.paymentRequestId val txId = SignedTransactionId.fromHex(payment.signedTx.serializedTx) + _uiState.update { it.copy(isBroadcastUnresolved = true) } // Written before the broadcast, so a send that may have gone out stays held even if the app dies during it if (requestId == null) hwWalletRepo.holdSend(payment.toHeldSend(txId)).getOrThrow() - _uiState.update { it.copy(isBroadcastUnresolved = true) } - // No deadline: the broadcast runs to its end on the core queue, so one could only discard the outcome of a - // payment that went out. The sheet stays unresolved until it answers. - var isDispatched = false - val outcome = hwWalletRepo.broadcastFundingAtBoundary(payment.signedTx, request.paymentDeadlineAt) { - requestId?.let { - check( - paykitPaymentProofRepo.markHardwareOnchainDispatch( - it, - request.walletId, - txId, - request.paymentIdentity, - request.address, - request.amountSats, - ) - ) { "Original hardware payment is no longer eligible for dispatch" } + // The broadcast runs to its end on the core queue, so it is never cancelled: the sheet stops waiting for it + // after a while, and its answer still settles the send + val isDispatched = AtomicBoolean(false) + val isAbandoned = AtomicBoolean(false) + val sheetDispatcher = requireNotNull(currentCoroutineContext()[ContinuationInterceptor]) + val dispatch = viewModelScope.async { + hwWalletRepo.broadcastFundingAtBoundary(payment.signedTx, request.paymentDeadlineAt) { + markDispatched(payment, isDispatched) + withContext(sheetDispatcher) { + if (!isAbandoned.get()) { + pendingBroadcast = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) + } + } } - isDispatched = true - pendingBroadcast = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) } + val outcome = withTimeoutOrNull(BROADCAST_WAIT) { dispatch.await() } + ?: return abandonBroadcastWait(payment, dispatch, isAbandoned) val error = outcome.exceptionOrNull() val isDeadlineExpired = error != null && generateSequence(error) { it.cause }.any { it is ServiceError.PaymentDeadlineExpired } // A failure before the dispatch sent nothing, while one after it may follow the write - val isOutcomeUnknown = requestId == null && error != null && isDispatched && !isDeadlineExpired && + val isOutcomeUnknown = requestId == null && error != null && isDispatched.get() && !isDeadlineExpired && !error.isHardwareBroadcastNotSent() if (isOutcomeUnknown) { Logger.warn("Held hardware send '$txId' after an unknown broadcast outcome", context = TAG) watchUnresolvedSend(payment) _uiState.update { it.copy(isBroadcastUnresolved = false) } - } else if (requestId == null && !isDeadlineExpired) { + } else if (requestId == null && error != null && !isDeadlineExpired) { releaseHeldSend(txId) } return outcome.getOrElse { error -> @@ -348,6 +362,52 @@ class HwSendViewModel @Inject constructor( } } + private suspend fun markDispatched(payment: PendingHwSendBroadcast, isDispatched: AtomicBoolean) { + val request = payment.request + request.paymentRequestId?.let { + check( + paykitPaymentProofRepo.markHardwareOnchainDispatch( + it, + request.walletId, + SignedTransactionId.fromHex(payment.signedTx.serializedTx), + request.paymentIdentity, + request.address, + request.amountSats, + ) + ) { "Original hardware payment is no longer eligible for dispatch" } + } + isDispatched.set(true) + } + + private fun abandonBroadcastWait( + payment: PendingHwSendBroadcast, + dispatch: Deferred>, + isAbandoned: AtomicBoolean, + ): HwFundingBroadcastResult? { + isAbandoned.set(true) + if (payment.request.paymentRequestId != null) { + // A Shop payment keeps its retained receipt and its guarded sheet; only its exact observation completes it + pendingBroadcast = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) + throw HwBroadcastWaitExpiredError() + } + val unresolved = watchUnresolvedSend(payment) + Logger.warn("Stopped waiting for broadcast of held hardware send '${unresolved.send.txId}'", context = TAG) + _uiState.update { it.copy(isBroadcastUnresolved = false) } + viewModelScope.launch { settleLateBroadcast(unresolved, dispatch.await()) } + return null + } + + private suspend fun settleLateBroadcast( + unresolved: UnresolvedHwSend, + outcome: Result, + ) { + outcome + .onSuccess { completeUnresolvedSend(unresolved) } + .onFailure { + Logger.warn("Kept held hardware send '${unresolved.send.txId}' after its late failure", it, context = TAG) + } + } + private suspend fun releaseHeldSend(txId: String) { hwWalletRepo.releaseHeldSend(txId) .onFailure { Logger.warn("Failed to release held hardware send '$txId'", it, context = TAG) } @@ -708,8 +768,11 @@ class HwSendViewModel @Inject constructor( title = context.getString(R.string.lightning__transfer_hw__reconnect_error_title), description = context.getString(R.string.lightning__transfer_hw__reconnect_error_description), ) - pendingBroadcast != null && - (error.isBroadcastConnectivityFailure() || error is TimeoutCancellationException) -> ToastEventBus.send( + pendingBroadcast != null && ( + error.isBroadcastConnectivityFailure() || + error is TimeoutCancellationException || + error is HwBroadcastWaitExpiredError + ) -> ToastEventBus.send( type = Toast.ToastType.WARNING, title = context.getString(R.string.hardware__send_broadcast_failed_title), description = context.getString(R.string.hardware__send_broadcast_failed_text), @@ -791,6 +854,8 @@ data class HwSendRequest( fun isPaymentOf(other: HwSendRequest): Boolean = isPaymentOf(other.walletId, other.address, other.amountSats) } +private class HwBroadcastWaitExpiredError : AppError("Hardware broadcast did not answer in time") + private class UnresolvedHwSend(val payment: PendingHwSendBroadcast, val send: HwSendResult) { var watch: Job? = null } diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt index d9c31ef29d..2afb2fff9a 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt @@ -397,6 +397,27 @@ class HwSendViewModelTest : BaseUnitTest() { assertEquals(original.paymentIdentity, sut.results.first().paymentIdentity) } + @Test + fun `Shop broadcast unanswered past the wait keeps its signed payment guarded`() = test { + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + val original = request().copy(paymentRequestId = PaykitPaymentRequestId("request", "counterparty")) + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { awaitCancellation() } + + sut.signAndBroadcast(original) + advanceTimeBy(121.seconds) + runCurrent() + toastJob.cancel() + + assertFalse(sut.uiState.value.isSigning) + assertTrue(sut.uiState.value.isBroadcastUnresolved) + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) + assertEquals(Toast.ToastType.WARNING, toasts.single().type) + verify(hwWalletRepo, never()).holdSend(any()) + } + @Test fun `Shop invalid broadcast failure retains original signed payment across cancel`() = test { whenever(context.getString(any())).thenReturn("message") @@ -522,7 +543,7 @@ class HwSendViewModelTest : BaseUnitTest() { } @Test - fun `a broadcast that succeeds after two minutes is recorded as sent without a retry prompt`() = test { + fun `a broadcast unanswered for two minutes shows as pending and completes once it answers`() = test { val toasts = mutableListOf() val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } whenever(context.getString(any())).thenReturn("message") @@ -531,31 +552,103 @@ class HwSendViewModelTest : BaseUnitTest() { whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { withContext(NonCancellable) { broadcastResult.await() } } + val events = mutableListOf() + backgroundScope.launch { sut.heldSendEvents.collect { events += it } } + val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) sut.signAndBroadcast(request()) - advanceTimeBy(121.seconds) + advanceTimeBy(119.seconds) runCurrent() - assertTrue(sut.uiState.value.isBroadcastUnresolved) assertFalse(sut.uiState.value.canLeave) + advanceTimeBy(2.seconds) + runCurrent() + assertTrue(sut.uiState.value.canLeave) + assertFalse(sut.uiState.value.isSigning) + assertEquals(held, sut.uiState.value.unresolvedSend) + assertEquals(listOf(held), sut.uiState.value.unresolvedSends) + verify(hwWalletRepo, never()).releaseHeldSend(any()) + + sut.cancel() broadcastResult.complete(Result.success(fixture.broadcast)) advanceUntilIdle() toastJob.cancel() assertTrue(toasts.isEmpty()) - verify(activityService).createSentOnchainActivityFromSendResult( - txid = fixture.broadcast.txId, + assertEquals(listOf(HeldHwSendEvent.Completed(held)), events) + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) + inOrder(activityService, hwWalletRepo) { + verify(activityService).createSentOnchainActivityFromSendResult( + txid = SIGNED_TXID, + address = ADDRESS, + amount = AMOUNT_SATS, + fee = fixture.signedTx.miningFeeSats, + feeRate = fixture.signedTx.feeRate, + isTransfer = false, + channelId = null, + walletId = WALLET_ID, + ) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) + } + verify(hwWalletRepo, times(1)).signFunding(WALLET_ID, fixture.funding) + verify(hwWalletRepo, times(1)).broadcastFunding(fixture.signedTx) + } + + @Test + fun `a broadcast that answers a refusal after the wait keeps its send held`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + val broadcastResult = CompletableDeferred>() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { + withContext(NonCancellable) { broadcastResult.await() } + } + + sut.signAndBroadcast(request()) + advanceTimeBy(121.seconds) + runCurrent() + broadcastResult.complete(Result.failure(BroadcastException.ElectrumException(NODE_REFUSAL))) + advanceUntilIdle() + + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) + verify(hwWalletRepo, never()).releaseHeldSend(any()) + verify(activityService, never()).createSentOnchainActivityFromSendResult( + txid = SIGNED_TXID, address = ADDRESS, amount = AMOUNT_SATS, - fee = fixture.broadcast.miningFeeSats, - feeRate = fixture.broadcast.feeRate, + fee = fixture.signedTx.miningFeeSats, + feeRate = fixture.signedTx.feeRate, isTransfer = false, channelId = null, walletId = WALLET_ID, ) - assertEquals(fixture.broadcast.txId, sut.results.first().txId) - verify(hwWalletRepo, times(1)).signFunding(WALLET_ID, fixture.funding) - verify(hwWalletRepo, times(1)).broadcastFunding(fixture.signedTx) + } + + @Test + fun `a sent hardware send is recorded before its hold is released`() = test { + val fixture = stubSuccessfulPayment() + val unresolvedWhileHolding = mutableListOf() + whenever(hwWalletRepo.holdSend(any())).doSuspendableAnswer { + unresolvedWhileHolding += sut.uiState.value.isBroadcastUnresolved + Result.success(Unit) + } + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + assertEquals(listOf(true), unresolvedWhileHolding) + inOrder(activityService, hwWalletRepo) { + verify(activityService).createSentOnchainActivityFromSendResult( + txid = fixture.broadcast.txId, + address = ADDRESS, + amount = AMOUNT_SATS, + fee = fixture.broadcast.miningFeeSats, + feeRate = fixture.broadcast.feeRate, + isTransfer = false, + channelId = null, + walletId = WALLET_ID, + ) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) + } } @Test @@ -751,7 +844,7 @@ class HwSendViewModelTest : BaseUnitTest() { verify(hwWalletRepo).broadcastFundingAtBoundary(any(), anyOrNull(), any()) } verify(hwWalletRepo, never()).releaseHeldSend(any()) - assertFalse(sut.uiState.value.canLeave) + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) } @Test From 6476ee40cd47368a365cd21b3266a1ce870f8bcc Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 10:12:59 -0500 Subject: [PATCH 06/14] fix: release a held hardware send only on proof it was not sent Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/ext/BroadcastExceptionExt.kt | 104 +++-- .../repositories/HwHeldDispatchTracker.kt | 64 +++ .../to/bitkit/repositories/HwWalletRepo.kt | 51 ++- .../screens/wallets/send/HwSendViewModel.kt | 241 ++++++++--- .../java/to/bitkit/ui/sheets/SendSheet.kt | 5 +- .../to/bitkit/utils/SignedTransactionId.kt | 26 +- app/src/main/res/values-ar/strings.xml | 6 +- app/src/main/res/values-b+es+419/strings.xml | 6 +- app/src/main/res/values-ca/strings.xml | 6 +- app/src/main/res/values-cs/strings.xml | 6 +- app/src/main/res/values-de/strings.xml | 6 +- app/src/main/res/values-el/strings.xml | 6 +- app/src/main/res/values-es-rES/strings.xml | 6 +- app/src/main/res/values-es/strings.xml | 6 +- app/src/main/res/values-fr/strings.xml | 6 +- app/src/main/res/values-it/strings.xml | 6 +- app/src/main/res/values-nl/strings.xml | 6 +- app/src/main/res/values-pl/strings.xml | 6 +- app/src/main/res/values-pt-rBR/strings.xml | 6 +- app/src/main/res/values-pt/strings.xml | 6 +- app/src/main/res/values-ru/strings.xml | 6 +- app/src/main/res/values/strings.xml | 6 +- .../bitkit/ext/BroadcastExceptionExtTest.kt | 73 +++- .../bitkit/repositories/HwWalletRepoTest.kt | 87 +++- .../PaykitPaymentProofRepoTest.kt | 12 +- .../wallets/send/HwSendViewModelTest.kt | 402 +++++++++++++++--- .../bitkit/utils/SignedTransactionIdTest.kt | 13 + 27 files changed, 1000 insertions(+), 174 deletions(-) create mode 100644 app/src/main/java/to/bitkit/repositories/HwHeldDispatchTracker.kt diff --git a/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt b/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt index 4e361a4ba8..2eb2a31490 100644 --- a/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt +++ b/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt @@ -18,31 +18,85 @@ fun Throwable.isDefiniteHardwarePreBroadcastFailure(): Boolean = generateSequenc /** * Whether a hardware broadcast proves it sent nothing: core could not decode the transaction or connect to the - * server, or the node refused it. Any other failure may follow the write, so the payment may still confirm. A refusal - * is proof only when no earlier broadcast of the same bytes may have reached the network. + * server. Any other failure may follow the write, and a node that refused the transaction still saw it, so the payment + * may still confirm. */ -fun Throwable.isHardwareBroadcastNotSent(): Boolean = isHardwareBroadcastRefusalForNavigation() || +fun Throwable.isHardwareBroadcastNotSent(): Boolean = isDefiniteHardwarePreBroadcastFailure() || generateSequence(this) { it.cause }.any { it is BroadcastException.ElectrumException && it.errorDetails.startsWith("Failed to connect to Electrum: ") } +/** + * Whether a hardware broadcast proves its transaction can never confirm: core could not decode it, or the server's node + * refused it for breaking consensus or script rules. A relay policy refusal, such as a fee, mempool, dust or + * standardness one, or an unreadable refusal is no proof, as another node or miner may still confirm the same + * transaction. + */ +fun Throwable.isHardwareBroadcastNeverConfirmable(): Boolean = isDefiniteHardwarePreBroadcastFailure() || + serverRefusalMessages().any { message -> + message.refusalLines().any { line -> NEVER_CONFIRMABLE_REFUSALS.any { line.isRefusal(it) } } + } + +/** Whether the server's node refused a hardware broadcast because one of its coins is missing or already spent. */ +fun Throwable.isHardwareBroadcastInputsSpent(): Boolean = serverRefusalMessages().any { message -> + message.refusalLines().any { it.isRefusal("bad-txns-inputs-missingorspent") } +} + // A recognized node refusal permits leaving the sheet. It never proves that an earlier, uncertain dispatch of the // same bytes was not delivered, so it never releases a Shop payment's guard. fun Throwable.isHardwareBroadcastRefusalForNavigation(): Boolean = - isDefiniteHardwarePreBroadcastFailure() || generateSequence(this) { it.cause }.any { - if (it !is BroadcastException.ElectrumException) return@any false - val details = it.errorDetails - val prefix = "broadcast failed: " - if (!details.startsWith(prefix, ignoreCase = true)) return@any false - val reason = details.drop(prefix.length) - val serverPrefix = "electrum server error: " - val message = if (reason.startsWith(serverPrefix, ignoreCase = true)) { - refusalMessageFromJson(reason.drop(serverPrefix.length)) ?: return@any false - } else { - reason - } - message.isKnownHardwareRefusal() + isDefiniteHardwarePreBroadcastFailure() || hardwareRefusalMessages().any { it.isKnownHardwareRefusal() } + +private val NEVER_CONFIRMABLE_REFUSALS = listOf( + "mandatory-script-verify-flag-failed", + "block-script-verify-flag-failed", + "bad-txns-in-belowout", + "bad-txns-inputs-duplicate", + "bad-txns-vout-negative", + "bad-txns-vout-toolarge", + "bad-txns-txouttotal-toolarge", + "bad-txns-oversize", +) + +// The refusal message of a node, from core's Electrum broadcast error or the server's JSON or RPC wrapping of it +private fun Throwable.hardwareRefusalMessages(): List = generateSequence(this) { it.cause } + .filterIsInstance() + .mapNotNull { it.errorDetails.refusalMessage()?.refusalReason() } + .toList() + +// Only a refusal the server returned as JSON is read as one; any other wording proves nothing +private fun Throwable.serverRefusalMessages(): List = generateSequence(this) { it.cause } + .filterIsInstance() + .mapNotNull { error -> + val prefix = "broadcast failed: electrum server error: " + if (!error.errorDetails.startsWith(prefix, ignoreCase = true)) return@mapNotNull null + refusalMessageFromJson(error.errorDetails.drop(prefix.length))?.refusalReason() } + .toList() + +private fun String.refusalLines(): Sequence = lineSequence().map { it.trim().lowercase() } + +private fun String.refusalMessage(): String? { + val prefix = "broadcast failed: " + if (!startsWith(prefix, ignoreCase = true)) return null + val reason = drop(prefix.length) + val serverPrefix = "electrum server error: " + if (!reason.startsWith(serverPrefix, ignoreCase = true)) return reason + return refusalMessageFromJson(reason.drop(serverPrefix.length)) +} + +private fun String.refusalReason(): String? { + val rpcPrefix = "sendrawtransaction RPC error: " + if (startsWith(rpcPrefix, ignoreCase = true)) return refusalMessageFromJson(drop(rpcPrefix.length)) + if (!startsWith("sendrawtransaction RPC error ", ignoreCase = true)) return this + val coded = drop("sendrawtransaction RPC error ".length) + val code = coded.substringBefore(": ") + if (code !in listOf("-25", "-26") || !coded.startsWith("$code: ")) return null + return coded.drop(code.length + 2) +} + +private fun String.isRefusal(known: String): Boolean = + this == known || startsWith("$known,") || startsWith("$known ") || startsWith("$known(") private fun refusalMessageFromJson(payload: String): String? = runCatching { when (val element = Json.parseToJsonElement(payload)) { @@ -53,23 +107,12 @@ private fun refusalMessageFromJson(payload: String): String? = runCatching { }.getOrNull() private fun String.isKnownHardwareRefusal(): Boolean { - val rpcPrefix = "sendrawtransaction RPC error: " - val message = if (startsWith(rpcPrefix, ignoreCase = true)) { - refusalMessageFromJson(drop(rpcPrefix.length)) ?: return false - } else if (startsWith("sendrawtransaction RPC error ", ignoreCase = true)) { - val coded = drop("sendrawtransaction RPC error ".length) - val code = coded.substringBefore(": ") - if (code !in listOf("-25", "-26") || !coded.startsWith("$code: ")) return false - coded.drop(code.length + 2) - } else { - this - } // Match the complete Bitcoin Core replacement refusal; unknown suffixes remain guarded. val replacementRefusal = Regex( """insufficient fee, rejecting replacement [0-9a-f]{64}; new feerate """ + """[0-9]+\.[0-9]{8} btc/kvb <= old feerate [0-9]+\.[0-9]{8} btc/kvb""", ) - if (replacementRefusal.matches(message.lowercase())) return true + if (replacementRefusal.matches(lowercase())) return true val reasons = listOf( "min relay fee not met", "mempool min fee not met", @@ -77,8 +120,5 @@ private fun String.isKnownHardwareRefusal(): Boolean { "txn-mempool-conflict", "non-final", ) - return message.lineSequence().any { line -> - val reason = line.trim().lowercase() - reasons.any { known -> reason == known || reason.startsWith("$known,") || reason.startsWith("$known ") } - } + return refusalLines().any { line -> reasons.any { line.isRefusal(it) && !line.startsWith("$it(") } } } diff --git a/app/src/main/java/to/bitkit/repositories/HwHeldDispatchTracker.kt b/app/src/main/java/to/bitkit/repositories/HwHeldDispatchTracker.kt new file mode 100644 index 0000000000..1ccf92aca7 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/HwHeldDispatchTracker.kt @@ -0,0 +1,64 @@ +package to.bitkit.repositories + +import kotlinx.collections.immutable.ImmutableSet +import kotlinx.collections.immutable.persistentSetOf +import kotlinx.collections.immutable.toImmutableSet +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Every dispatch of a held hardware send's signed bytes in this process, by txid. A broadcast proving it sent nothing + * says nothing about another dispatch of the same bytes, so a hold is released on such proof only while every other + * dispatch of those bytes is proven not sent too. + */ +@Singleton +class HwHeldDispatchTracker @Inject constructor() { + private val lock = Any() + private val dispatches = mutableListOf() + private val _inFlight = MutableStateFlow>(persistentSetOf()) + + /** Txids with a dispatch still waiting for its answer. */ + val inFlight: StateFlow> = _inFlight.asStateFlow() + + /** Records a dispatch of [txId]'s bytes and returns its handle, unless one is already in flight. */ + fun begin(txId: String): HwHeldDispatch? = synchronized(lock) { + val key = txId.lowercase() + if (dispatches.any { it.txId == key && it.outcome == HwHeldDispatch.Outcome.IN_FLIGHT }) return null + HwHeldDispatch(key).also { + dispatches += it + publish() + } + } + + /** Records the answer of [dispatch]: [isNotSent] only when it proves the bytes never left this device. */ + fun finish(dispatch: HwHeldDispatch, isNotSent: Boolean) { + synchronized(lock) { + if (dispatch.outcome != HwHeldDispatch.Outcome.IN_FLIGHT) return + dispatch.outcome = if (isNotSent) HwHeldDispatch.Outcome.NOT_SENT else HwHeldDispatch.Outcome.MAY_HAVE_SENT + publish() + } + } + + /** Whether every dispatch of [dispatch]'s bytes other than [dispatch] itself is proven not sent. */ + fun isOnlyPossibleSend(dispatch: HwHeldDispatch): Boolean = synchronized(lock) { + dispatches.none { + it !== dispatch && it.txId == dispatch.txId && it.outcome != HwHeldDispatch.Outcome.NOT_SENT + } + } + + private fun publish() { + val inFlight = dispatches.filter { it.outcome == HwHeldDispatch.Outcome.IN_FLIGHT }.map { it.txId } + _inFlight.update { inFlight.toImmutableSet() } + } +} + +/** One dispatch of a held send's signed bytes. */ +class HwHeldDispatch internal constructor(internal val txId: String) { + internal enum class Outcome { IN_FLIGHT, NOT_SENT, MAY_HAVE_SENT } + + internal var outcome = Outcome.IN_FLIGHT +} diff --git a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt index 23424d0168..4c2e5a3e3b 100644 --- a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt @@ -72,6 +72,7 @@ import to.bitkit.models.walletKey import to.bitkit.services.TrezorWalletMode import to.bitkit.utils.AppError import to.bitkit.utils.Logger +import to.bitkit.utils.SignedTransactionId import javax.inject.Inject import javax.inject.Singleton import kotlin.math.ceil @@ -111,6 +112,9 @@ class HwWalletRepo @Inject constructor( /** A Trezor reconnect is a session handshake; a Jade one may include entering the PIN on the device. */ private val TREZOR_RECONNECT_TIMEOUT = 30.seconds private val JADE_RECONNECT_TIMEOUT = 5.minutes + + /** LDK's ANTI_REORG_DELAY: a spend this deep is final, so a transaction conflicting with it never confirms. */ + const val FINAL_SPEND_CONFIRMATIONS = 6u } /** Alternates which vendor gets the Bluetooth part of a scan, to stay under Android's scan-rate limit. */ @@ -911,17 +915,48 @@ class HwWalletRepo @Inject constructor( runSuspendCatching { hwWalletStore.releaseHeldSends(setOf(txId)) } } - /** The held send of this payment the wallet has not seen yet. One its wallet has seen went out and is released. */ + /** The held send of this payment, which is never signed again until it is recorded as sent or released. */ suspend fun heldSendFor(walletId: String, address: String, amountSats: ULong): Result = withContext(ioDispatcher) { runSuspendCatching { - val held = hwWalletStore.loadHeldSends().filter { it.isPaymentOf(walletId, address, amountSats) } - if (held.isEmpty()) return@runSuspendCatching null - val seenTxIds = activities.value.filterIsInstance() - .mapTo(mutableSetOf()) { it.v1.walletId to it.v1.txId.lowercase() } - val (seen, unseen) = held.partition { (it.walletId to it.txId.lowercase()) in seenTxIds } - hwWalletStore.releaseHeldSends(seen.mapTo(mutableSetOf()) { it.txId }) - unseen.firstOrNull() + hwWalletStore.loadHeldSends().firstOrNull { it.isPaymentOf(walletId, address, amountSats) } + } + } + + /** + * Whether a fresh read of [walletId]'s history shows another transaction, [FINAL_SPEND_CONFIRMATIONS] deep, + * spending one of the coins of the signed [serializedTx], which proves it can never confirm. False while the + * history holds the transaction itself; fails when the history cannot be read. + */ + suspend fun isSpentByAnotherTransaction(walletId: String, serializedTx: String): Result = + withContext(ioDispatcher) { + runSuspendCatching { + val txId = SignedTransactionId.fromHex(serializedTx) + val inputs = SignedTransactionId.inputsFromHex(serializedTx).toSet() + val account = getFundingAccount(walletId).getOrThrow() + val network = Env.network.toCoreNetwork() + val history = trezorRepo.getTransactionHistory(account.xpub, network, account.accountType) + .getOrThrow() + .transactions + if (history.any { it.txid.equals(txId, ignoreCase = true) }) return@runSuspendCatching false + // A coin is spent no earlier than the block that created it + val fundedAt = history + .filter { tx -> inputs.any { it.txid.equals(tx.txid, ignoreCase = true) } } + .mapNotNull { it.blockHeight } + .minOrNull() ?: return@runSuspendCatching false + history + .filter { + it.sent > 0uL && it.confirmations >= FINAL_SPEND_CONFIRMATIONS && + (it.blockHeight ?: 0u) >= fundedAt + } + .any { tx -> + val detail = trezorRepo + .getTransactionDetail(account.xpub, tx.txid, network, account.accountType) + .getOrThrow() + val isSameTransaction = detail.txid.equals(tx.txid, ignoreCase = true) + require(isSameTransaction) { "Backend returned another transaction" } + detail.inputs.any { OnchainSendInput(it.txid.lowercase(), it.vout) in inputs } + } } } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index c74514689a..025171ca83 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -1,6 +1,7 @@ package to.bitkit.ui.screens.wallets.send import android.content.Context +import androidx.annotation.StringRes import androidx.compose.runtime.Immutable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -12,7 +13,6 @@ import kotlinx.collections.immutable.ImmutableSet import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.persistentSetOf import kotlinx.collections.immutable.toImmutableList -import kotlinx.collections.immutable.toImmutableSet import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Deferred import kotlinx.coroutines.Job @@ -35,6 +35,8 @@ import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.R import to.bitkit.data.HeldHwSend import to.bitkit.ext.isBroadcastConnectivityFailure +import to.bitkit.ext.isHardwareBroadcastInputsSpent +import to.bitkit.ext.isHardwareBroadcastNeverConfirmable import to.bitkit.ext.isHardwareBroadcastNotSent import to.bitkit.ext.isHardwareBroadcastRefusalForNavigation import to.bitkit.ext.isHwDeviceBusy @@ -48,6 +50,8 @@ import to.bitkit.models.HwFundingTransaction import to.bitkit.models.HwWallet import to.bitkit.models.Toast import to.bitkit.repositories.ActivityRepo +import to.bitkit.repositories.HwHeldDispatch +import to.bitkit.repositories.HwHeldDispatchTracker import to.bitkit.repositories.HwPassphraseMismatchError import to.bitkit.repositories.HwPassphraseRequiredError import to.bitkit.repositories.HwWalletMismatchError @@ -78,6 +82,7 @@ class HwSendViewModel @Inject constructor( private val coreService: CoreService, private val activityRepo: ActivityRepo, private val paykitPaymentProofRepo: PaykitPaymentProofRepo, + private val heldDispatches: HwHeldDispatchTracker, private val clock: Clock = Clock.System, ) : ViewModel() { private companion object { @@ -86,7 +91,7 @@ class HwSendViewModel @Inject constructor( val SIGN_TIMEOUT = 120.seconds /** How long the sheet waits for a broadcast before showing it as pending; the broadcast itself runs on. */ - val BROADCAST_WAIT = 120.seconds + val BROADCAST_WAIT = 60.seconds } val wallets: StateFlow> @@ -112,6 +117,9 @@ class HwSendViewModel @Inject constructor( init { dropUnresolvedSendsOfRemovedWallets() + viewModelScope.launch { + heldDispatches.inFlight.collect { txIds -> _uiState.update { it.copy(retryingSendTxIds = txIds) } } + } } fun warmUp(walletId: String) { @@ -135,13 +143,9 @@ class HwSendViewModel @Inject constructor( runCatching { // A payment whose broadcast may have gone out is only ever broadcast again as the same bytes unresolvedSendFor(request)?.let { unresolved -> - Logger.warn("Refused held hardware send of '${request.walletId}'", context = TAG) + Logger.warn("Broadcasting held hardware send of '${request.walletId}' again", context = TAG) _uiState.update { it.copy(unresolvedSend = unresolved.send) } - ToastEventBus.send( - type = Toast.ToastType.ERROR, - title = context.getString(R.string.common__error), - description = context.getString(R.string.wallet__send_pending__blocked_new_send), - ) + retryUnresolvedSend(unresolved.send.txId) return@runCatching } if (pendingBroadcast?.matches(request) == false) { @@ -161,14 +165,33 @@ class HwSendViewModel @Inject constructor( } else { null } - if (held != null) { - Logger.warn("Refused held hardware send of '${request.walletId}'", context = TAG) - watchUnresolvedSend(held.toPendingBroadcast(request)) - ToastEventBus.send( - type = Toast.ToastType.ERROR, - title = context.getString(R.string.common__error), - description = context.getString(R.string.wallet__send_pending__blocked_new_send), + if (held != null && isSeenByWallet(request.walletId, held.txId)) { + // It went out, so it is recorded and shown as sent; only a new send signs it again + Logger.info("Recorded held hardware send '${held.txId}' the wallet has seen", context = TAG) + val heldPayment = held.toPendingBroadcast(request) + val signedTx = heldPayment.signedTx + val result = HwFundingBroadcastResult( + txId = held.txId, + miningFeeSats = signedTx.miningFeeSats, + feeRate = signedTx.feeRate, + totalSpent = signedTx.totalSpent, ) + runSuspendCatching { persistResult(heldPayment.request, result) } + .onFailure { Logger.error("Failed to persist hardware send result", it, context = TAG) } + releaseHeldSend(held.txId) + pendingResult.update { + HwSendResult( + walletId = request.walletId, + txId = held.txId, + amountSats = request.amountSats, + paymentIdentity = request.paymentIdentity, + ) + } + return@runCatching + } + if (held != null) { + Logger.warn("Broadcasting held hardware send of '${request.walletId}' again", context = TAG) + retryUnresolvedSend(watchUnresolvedSend(held.toPendingBroadcast(request)).send.txId) return@runCatching } var pending = pendingBroadcast?.takeIf { it.matches(request) } @@ -312,6 +335,11 @@ class HwSendViewModel @Inject constructor( if (requestId == null) hwWalletRepo.holdSend(payment.toHeldSend(txId)).getOrThrow() // The broadcast runs to its end on the core queue, so it is never cancelled: the sheet stops waiting for it // after a while, and its answer still settles the send + val tracked = if (requestId == null) { + checkNotNull(heldDispatches.begin(txId)) { "A broadcast of hardware send '$txId' is unanswered" } + } else { + null + } val isDispatched = AtomicBoolean(false) val isAbandoned = AtomicBoolean(false) val sheetDispatcher = requireNotNull(currentCoroutineContext()[ContinuationInterceptor]) @@ -325,14 +353,27 @@ class HwSendViewModel @Inject constructor( } } } + // A dispatch the sheet stops waiting for is settled by its answer, or counts as possibly sent if it has none + tracked?.let { dispatch.invokeOnCompletion { cause -> if (cause != null) heldDispatches.finish(it, false) } } val outcome = withTimeoutOrNull(BROADCAST_WAIT) { dispatch.await() } - ?: return abandonBroadcastWait(payment, dispatch, isAbandoned) + ?: return abandonBroadcastWait(payment, dispatch, isAbandoned, isDispatched, tracked) val error = outcome.exceptionOrNull() val isDeadlineExpired = error != null && generateSequence(error) { it.cause }.any { it is ServiceError.PaymentDeadlineExpired } // A failure before the dispatch sent nothing, while one after it may follow the write - val isOutcomeUnknown = requestId == null && error != null && isDispatched.get() && !isDeadlineExpired && - !error.isHardwareBroadcastNotSent() + val isNotSent = error != null && (!isDispatched.get() || error.isFirstHardwareBroadcastNotSent()) + tracked?.let { heldDispatches.finish(it, isNotSent) } + val isOnlyPossibleSend = tracked?.let { heldDispatches.isOnlyPossibleSend(it) } != false + val isOutcomeUnknown = requestId == null && error != null && !isDeadlineExpired && + !(isNotSent && isOnlyPossibleSend) + if (isOutcomeUnknown && isProvenNeverConfirming(payment, requireNotNull(error))) { + Logger.warn("Released hardware send '$txId' the network rejected for good", context = TAG) + releaseHeldSend(txId) + pendingBroadcast = null + _uiState.update { it.copy(hasPendingBroadcast = false, isBroadcastUnresolved = false) } + toastNotSent(R.string.hardware__send_broadcast_rejected_text) + return null + } if (isOutcomeUnknown) { Logger.warn("Held hardware send '$txId' after an unknown broadcast outcome", context = TAG) watchUnresolvedSend(payment) @@ -383,31 +424,119 @@ class HwSendViewModel @Inject constructor( payment: PendingHwSendBroadcast, dispatch: Deferred>, isAbandoned: AtomicBoolean, + isDispatched: AtomicBoolean, + tracked: HwHeldDispatch?, ): HwFundingBroadcastResult? { isAbandoned.set(true) if (payment.request.paymentRequestId != null) { - // A Shop payment keeps its retained receipt and its guarded sheet; only its exact observation completes it - pendingBroadcast = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) + // A Shop payment keeps its retained receipt and its guarded sheet, and its late answer still lands + val attempted = payment.copy(hasAttemptedBroadcast = true, isRefusedForNavigation = false) + pendingBroadcast = attempted + viewModelScope.launch { settleLateShopBroadcast(attempted, dispatch.await()) } throw HwBroadcastWaitExpiredError() } val unresolved = watchUnresolvedSend(payment) Logger.warn("Stopped waiting for broadcast of held hardware send '${unresolved.send.txId}'", context = TAG) _uiState.update { it.copy(isBroadcastUnresolved = false) } - viewModelScope.launch { settleLateBroadcast(unresolved, dispatch.await()) } + viewModelScope.launch { + settleLateBroadcast(unresolved, dispatch.await(), isDispatched.get(), requireNotNull(tracked)) + } return null } private suspend fun settleLateBroadcast( unresolved: UnresolvedHwSend, outcome: Result, + isDispatched: Boolean, + tracked: HwHeldDispatch, + ) { + val txId = unresolved.send.txId + val error = outcome.exceptionOrNull() + val isNotSent = error != null && (!isDispatched || error.isFirstHardwareBroadcastNotSent()) + heldDispatches.finish(tracked, isNotSent) + // An accepted broadcast stays pending until the wallet sees its transaction + if (error == null) { + Logger.info("Accepted late broadcast of held hardware send '$txId'", context = TAG) + return + } + if (releaseIfNeverConfirming(unresolved, error)) return + // Proof that this broadcast sent nothing says nothing about any other dispatch of the same bytes + if (isNotSent && heldDispatches.isOnlyPossibleSend(tracked)) { + releaseUnresolvedSend(unresolved, R.string.hardware__send_not_sent_text) + return + } + Logger.warn("Kept held hardware send '$txId' after a late failure", error, context = TAG) + } + + private suspend fun settleLateShopBroadcast( + payment: PendingHwSendBroadcast, + outcome: Result, ) { + // A later attempt or an exact observation may have settled this payment meanwhile + if (pendingBroadcast?.signedTx != payment.signedTx || pendingResult.value != null) return + val request = payment.request outcome - .onSuccess { completeUnresolvedSend(unresolved) } - .onFailure { - Logger.warn("Kept held hardware send '${unresolved.send.txId}' after its late failure", it, context = TAG) + .onSuccess { result -> + runSuspendCatching { persistResult(request, result) } + .onFailure { Logger.error("Failed to persist hardware send result", it, context = TAG) } + pendingResult.update { + HwSendResult( + walletId = request.walletId, + txId = result.txId, + amountSats = request.amountSats, + paymentRequestId = request.paymentRequestId, + paymentIdentity = request.paymentIdentity, + ) + } } + .onFailure { handleFailure(it, request.walletId) } } + private fun Throwable.isFirstHardwareBroadcastNotSent(): Boolean = + isHardwareBroadcastNotSent() || isHardwareBroadcastRefusalForNavigation() + + private suspend fun isProvenNeverConfirming(payment: PendingHwSendBroadcast, error: Throwable): Boolean { + if (payment.request.paymentRequestId != null) return false + if (error.isHardwareBroadcastNeverConfirmable()) return true + if (!error.isHardwareBroadcastInputsSpent()) return false + // A coin missing to this node proves nothing until a final spend of it by another transaction shows up + return hwWalletRepo.isSpentByAnotherTransaction(payment.request.walletId, payment.signedTx.serializedTx) + .onFailure { Logger.warn("Failed to read spends of hardware send coins", it, context = TAG) } + .getOrDefault(false) + } + + private suspend fun releaseIfNeverConfirming(unresolved: UnresolvedHwSend, error: Throwable): Boolean { + if (!isProvenNeverConfirming(unresolved.payment, error)) return false + if (unresolvedSends[unresolved.send.txId] !== unresolved) return true + // A transaction the wallet has seen went out, whatever a node says about it now + if (isSeenByWallet(unresolved.send.walletId, unresolved.send.txId)) { + completeUnresolvedSend(unresolved) + return true + } + releaseUnresolvedSend(unresolved, R.string.hardware__send_broadcast_rejected_text) + return true + } + + private suspend fun releaseUnresolvedSend(unresolved: UnresolvedHwSend, @StringRes description: Int) { + if (unresolvedSends[unresolved.send.txId] !== unresolved) return + Logger.warn("Released held hardware send '${unresolved.send.txId}' that was never sent", context = TAG) + forgetUnresolvedSend(unresolved) + releaseHeldSend(unresolved.send.txId) + toastNotSent(description) + _heldSendEvents.emit(HeldHwSendEvent.Released(unresolved.send)) + } + + private fun isSeenByWallet(walletId: String, txId: String): Boolean = + hwWalletRepo.activities.value.filterIsInstance().any { + it.v1.walletId == walletId && it.v1.txId.equals(txId, ignoreCase = true) + } + + private suspend fun toastNotSent(@StringRes description: Int) = ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.hardware__send_not_sent_title), + description = context.getString(description), + ) + private suspend fun releaseHeldSend(txId: String) { hwWalletRepo.releaseHeldSend(txId) .onFailure { Logger.warn("Failed to release held hardware send '$txId'", it, context = TAG) } @@ -463,58 +592,69 @@ class HwSendViewModel @Inject constructor( state.copy( unresolvedSend = state.unresolvedSend?.takeUnless { it.txId == unresolved.send.txId }, unresolvedSends = unresolvedSends.values.map { it.send }.toImmutableList(), - retryingSendTxIds = (state.retryingSendTxIds - unresolved.send.txId).toImmutableSet(), ) } } /** - * Broadcasts the signed bytes of the held send [txId] once more, for when its broadcast never reached the server. - * Any failure keeps the send held, since the first broadcast may still confirm. + * Broadcasts the identical signed bytes of the held send [txId] again, never signing it again. An accepted + * broadcast stays pending until the wallet sees the transaction, and only a refusal proving it can never confirm + * releases it, since an earlier broadcast may still confirm. */ fun retryUnresolvedSend(txId: String) { val unresolved = unresolvedSends[txId.lowercase()] ?: return val send = unresolved.send - if (send.txId in _uiState.value.retryingSendTxIds) return - _uiState.update { it.copy(retryingSendTxIds = (it.retryingSendTxIds + send.txId).toImmutableSet()) } + // One dispatch of the same bytes at a time, from any sheet + val tracked = heldDispatches.begin(send.txId) ?: return viewModelScope.launch { + var isNotSent = false try { - hwWalletRepo.broadcastFunding(unresolved.payment.signedTx) - .onSuccess { completeUnresolvedSend(unresolved) } + // Written again first, so the send stays held whatever happened to the record since + hwWalletRepo.holdSend(unresolved.payment.toHeldSend(send.txId)).onFailure { + isNotSent = true + Logger.warn("Skipped broadcast again of '${send.txId}' without its hold", it, context = TAG) + toastBroadcastFailed() + return@launch + } + val outcome = hwWalletRepo.broadcastFunding(unresolved.payment.signedTx) + isNotSent = outcome.exceptionOrNull()?.isHardwareBroadcastNotSent() == true + heldDispatches.finish(tracked, isNotSent) + outcome + .onSuccess { + ToastEventBus.send( + type = Toast.ToastType.INFO, + title = context.getString(R.string.hardware__send_broadcast_accepted), + ) + } .onFailure { if (unresolvedSends[send.txId] !== unresolved) return@onFailure - // A refusal now does not prove the first broadcast was not delivered, so the send stays held - val description = if (it.isHardwareBroadcastRefusalForNavigation()) { - R.string.hardware__send_broadcast_refused_text - } else { - R.string.hardware__send_broadcast_failed_text - } + if (releaseIfNeverConfirming(unresolved, it)) return@onFailure ToastEventBus.send( type = Toast.ToastType.WARNING, title = context.getString(R.string.hardware__send_broadcast_failed_title), - description = context.getString(description), + description = context.getString(R.string.hardware__send_broadcast_refused_text), ) } } finally { - _uiState.update { it.copy(retryingSendTxIds = (it.retryingSendTxIds - send.txId).toImmutableSet()) } + heldDispatches.finish(tracked, isNotSent) } } } + private suspend fun toastBroadcastFailed() = ToastEventBus.send( + type = Toast.ToastType.WARNING, + title = context.getString(R.string.hardware__send_broadcast_failed_title), + description = context.getString(R.string.hardware__send_broadcast_failed_text), + ) + /** - * Refuses a new hardware send of a payment whose earlier broadcast may have gone out, saying so, and returns that - * earlier send to finish first; null when there is none. + * Broadcasts again the held send of a payment whose earlier broadcast may have gone out, instead of signing it + * anew, and returns it to show as pending; null when there is none. */ - fun refuseNewSend(walletId: String, address: String, amountSats: ULong): HwSendResult? { + fun resumeHeldSend(walletId: String, address: String, amountSats: ULong): HwSendResult? { val send = unresolvedSends.values.firstOrNull { it.payment.request.isPaymentOf(walletId, address, amountSats) } ?.send ?: return null - viewModelScope.launch { - ToastEventBus.send( - type = Toast.ToastType.ERROR, - title = context.getString(R.string.common__error), - description = context.getString(R.string.wallet__send_pending__blocked_new_send), - ) - } + retryUnresolvedSend(send.txId) return send } @@ -836,6 +976,9 @@ sealed interface HeldHwSendEvent { val send: HwSendResult data class Completed(override val send: HwSendResult) : HeldHwSendEvent + + /** The network rejected the send for good, so it was never sent and is no longer held. */ + data class Released(override val send: HwSendResult) : HeldHwSendEvent } data class HwSendRequest( diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index f06ac28fb1..829b794130 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -261,6 +261,7 @@ fun SendSheet( when (event) { is HeldHwSendEvent.Completed -> showHardwareSuccess(send.txId, send.amountSats, send.walletId, isShopPayment = false) + is HeldHwSendEvent.Released -> appViewModel.hideSheet() } } } @@ -327,10 +328,10 @@ fun SendSheet( navController.navigateTo(it.route) { popUpTo(replaced) { inclusive = true } } } is SendEffect.NavigateToHardwareSign -> { - // A send whose broadcast may have gone out is finished before a new one is signed + // A payment whose broadcast may have gone out is broadcast again instead of signed anew val state = appViewModel.sendUiState.value val unresolvedSend = state.hardwareWalletId?.let { walletId -> - hwSendViewModel.refuseNewSend(walletId, state.address, state.amount) + hwSendViewModel.resumeHeldSend(walletId, state.address, state.amount) } if (unresolvedSend == null) { navController.navigateTo(SendRoute.HardwareSign) diff --git a/app/src/main/java/to/bitkit/utils/SignedTransactionId.kt b/app/src/main/java/to/bitkit/utils/SignedTransactionId.kt index 32f2508127..0104c1bc7b 100644 --- a/app/src/main/java/to/bitkit/utils/SignedTransactionId.kt +++ b/app/src/main/java/to/bitkit/utils/SignedTransactionId.kt @@ -1,10 +1,21 @@ package to.bitkit.utils +import to.bitkit.repositories.OnchainSendInput import java.security.MessageDigest /** Canonical Bitcoin txid of a consensus-encoded signed transaction, excluding witness data. */ internal object SignedTransactionId { - fun fromHex(hex: String): String { + private const val OUTPOINT_TXID_BYTES = 32 + private const val OUTPOINT_VOUT_BYTES = 4 + + fun fromHex(hex: String): String = parse(hex).txid + + /** The coins a consensus-encoded signed transaction spends, as their txid and output index. */ + fun inputsFromHex(hex: String): List = parse(hex).inputs + + private class Parsed(val txid: String, val inputs: List) + + private fun parse(hex: String): Parsed { require(hex.length in 20..2_000_000 && hex.length % 2 == 0) val bytes = hex.hexToByteArray() var offset = 4 @@ -35,10 +46,17 @@ internal object SignedTransactionId { val baseStart = offset val inputCount = compactSize() require(inputCount > 0 && inputCount <= bytes.size / 41) - repeat(inputCount) { - skip(36) + val inputs = List(inputCount) { + val txidStart = offset + skip(OUTPOINT_TXID_BYTES + OUTPOINT_VOUT_BYTES) + val txid = bytes.copyOfRange(txidStart, txidStart + OUTPOINT_TXID_BYTES).reversedArray().toHexString() + var vout = 0u + repeat(OUTPOINT_VOUT_BYTES) { + vout = vout or ((bytes[txidStart + OUTPOINT_TXID_BYTES + it].toInt() and 255).toUInt() shl (8 * it)) + } skip(compactSize()) skip(4) + OnchainSendInput(txid, vout) } val outputCount = compactSize() require(outputCount > 0 && outputCount <= bytes.size / 9) @@ -60,6 +78,6 @@ internal object SignedTransactionId { val canonical = bytes.copyOfRange(0, 4) + bytes.copyOfRange(baseStart, baseEnd) + bytes.copyOfRange(lockTimeStart, offset) val sha256 = MessageDigest.getInstance("SHA-256") - return sha256.digest(sha256.digest(canonical)).reversedArray().toHexString() + return Parsed(sha256.digest(sha256.digest(canonical)).reversedArray().toHexString(), inputs) } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index f61009f2a5..9b05e3f391 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1188,10 +1188,14 @@ تعذر الاحتفاظ بعلامات هذه المحفظة في نسختك الاحتياطية. حاول مرة أخرى، أو أزلها دون الاحتفاظ بها. تعذرت إعادة تسمية محفظة الأجهزة. يرجى المحاولة مرة أخرى. تعذر البحث عن محافظ الأجهزة. تحقق من اتصالك وحاول مرة أخرى. + قبلت الشبكة هذه الدفعة. تكتمل بمجرد أن ترى محفظتك المعاملة. تحقق من اتصالك وحاول مرة أخرى. الدفعة غير مؤكدة - رفضت الشبكة هذه المعاملة، على سبيل المثال لأن عملاتها أُنفقت بالفعل. تبقى الدفعة معلّقة حتى ترى محفظتك المعاملة. + قد تُؤكَّد هذه الدفعة لاحقًا. تبقى معلقة حتى ترى محفظتك المعاملة أو تُنفَق عملاتها في مكان آخر. + لا يمكن تأكيد هذه الدفعة أبدًا. يمكنك إجراؤها مرة أخرى. إلى العنوان (أكّد على الجهاز) + لم تستلم الشبكة هذه الدفعة. يمكنك إجراؤها مرة أخرى. + لم تُرسَل الدفعة يمكن لـ Trezor الإرسال إلى عنوان Bitcoin فقط من هذه المحفظة. يمكن لـ Jade الإرسال إلى عنوان Bitcoin فقط من هذه المحفظة. مطلوب عنوان Bitcoin diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 7e987c939d..d6cc066b23 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1221,10 +1221,14 @@ No se pudieron conservar las etiquetas de esta billetera en su copia de seguridad. Vuelva a intentarlo o quítela sin conservarlas. No se pudo renombrar la billetera de hardware. Inténtelo de nuevo. No se pudieron buscar billeteras de hardware. Revise su conexión y vuelva a intentarlo. + La red aceptó este pago. Se completará cuando su billetera vea la transacción. Revise su conexión y vuelva a intentarlo. Pago no confirmado - La red rechazó esta transacción, por ejemplo porque sus monedas ya se gastaron. El pago sigue pendiente hasta que su billetera vea la transacción. + Este pago aún podría confirmarse. Sigue pendiente hasta que su billetera lo vea o sus monedas se gasten en otra transacción. + Este pago nunca podrá confirmarse. Puede hacerlo de nuevo. A LA DIRECCIÓN (CONFIRME EN EL DISPOSITIVO) + La red no recibió este pago. Puede hacerlo de nuevo. + Pago no enviado Desde esta billetera, Trezor solo puede enviar a una dirección de Bitcoin. Desde esta billetera, Jade solo puede enviar a una dirección de Bitcoin. Se requiere una dirección de Bitcoin diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index e32c977693..d0d12966b8 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1213,10 +1213,14 @@ No s\'han pogut conservar les etiquetes d\'aquesta cartera a la còpia de seguretat. Torna-ho a provar o elimina-la sense conservar-les. No s\'ha pogut canviar el nom de la cartera de maquinari. Torna-ho a provar. No s\'han pogut cercar carteres de maquinari. Comprova la connexió i torna-ho a provar. + La xarxa ha acceptat aquest pagament. Es completarà quan la teva cartera vegi la transacció. Comprova la connexió i torna-ho a provar. Pagament no confirmat - La xarxa ha rebutjat aquesta transacció, per exemple perquè les seves monedes ja s\'han gastat. El pagament continua pendent fins que la teva cartera vegi la transacció. + Aquest pagament encara es podria confirmar. Continua pendent fins que la teva cartera el vegi o les seves monedes es gastin en una altra transacció. + Aquest pagament no es podrà confirmar mai. Pots tornar-lo a fer. A L\'ADREÇA (CONFIRMA AL DISPOSITIU) + La xarxa no ha rebut aquest pagament. Pots tornar-lo a fer. + Pagament no enviat Des d\'aquesta cartera, Trezor només pot enviar a una adreça Bitcoin. Des d\'aquesta cartera, Jade només pot enviar a una adreça Bitcoin. Cal una adreça Bitcoin diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 16699307e5..b76cbdd23b 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1219,10 +1219,14 @@ Tagy této peněženky se nepodařilo ponechat v záloze. Zkuste to znovu, nebo ji odeberte bez jejich ponechání. Hardwarovou peněženku se nepodařilo přejmenovat. Zkuste to prosím znovu. Hardwarové peněženky se nepodařilo vyhledat. Zkontrolujte připojení a zkuste to znovu. + Síť tuto platbu přijala. Dokončí se, jakmile vaše peněženka transakci uvidí. Zkontrolujte připojení a zkuste to znovu. Platba nebyla potvrzena - Síť tuto transakci odmítla, například proto, že její mince už byly utraceny. Platba zůstává nevyřízená, dokud ji vaše peněženka neuvidí. + Tato platba může být stále potvrzena. Zůstává čekající, dokud ji vaše peněženka neuvidí nebo dokud nebudou její mince utraceny jinde. + Tato platba nikdy nemůže být potvrzena. Můžete ji provést znovu. NA ADRESU (POTVRĎTE NA ZAŘÍZENÍ) + Síť tuto platbu nepřijala. Můžete ji provést znovu. + Platba nebyla odeslána Trezor může z této peněženky posílat pouze na bitcoinovou adresu. Jade může z této peněženky posílat pouze na bitcoinovou adresu. Je vyžadována bitcoinová adresa diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 9dfc1dbcd7..daed63b6b0 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1216,10 +1216,14 @@ Die Tags dieses Wallets konnten nicht in deinem Backup behalten werden. Versuche es erneut oder entferne es, ohne sie zu behalten. Das Hardware-Wallet konnte nicht umbenannt werden. Bitte versuche es erneut. Die Suche nach Hardware-Wallets ist fehlgeschlagen. Überprüfe deine Verbindung und versuche es erneut. + Das Netzwerk hat diese Zahlung angenommen. Sie wird abgeschlossen, sobald dein Wallet die Transaktion sieht. Überprüfe deine Verbindung und versuche es erneut. Zahlung nicht bestätigt - Das Netzwerk hat diese Transaktion abgelehnt, zum Beispiel weil ihre Coins bereits ausgegeben wurden. Die Zahlung bleibt ausstehend, bis dein Wallet die Transaktion sieht. + Diese Zahlung kann noch bestätigt werden. Sie bleibt ausstehend, bis dein Wallet sie sieht oder ihre Coins anderweitig ausgegeben werden. + Diese Zahlung kann nie bestätigt werden. Du kannst sie erneut ausführen. AN ADRESSE (AM GERÄT BESTÄTIGEN) + Das Netzwerk hat diese Zahlung nicht erhalten. Du kannst sie erneut ausführen. + Zahlung nicht gesendet Trezor kann von diesem Wallet nur an eine Bitcoin-Adresse senden. Jade kann von diesem Wallet nur an eine Bitcoin-Adresse senden. Bitcoin-Adresse erforderlich diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index c2c597f679..eeea445007 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1194,10 +1194,14 @@ Δεν ήταν δυνατή η διατήρηση των ετικετών αυτού του πορτοφολιού στο αντίγραφο ασφαλείας. Δοκίμασε ξανά ή αφαίρεσέ το χωρίς να τις διατηρήσεις. Δεν ήταν δυνατή η μετονομασία του πορτοφολιού υλικού. Δοκίμασε ξανά. Δεν ήταν δυνατή η αναζήτηση πορτοφολιών υλικού. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. + Το δίκτυο αποδέχτηκε αυτή την πληρωμή. Θα ολοκληρωθεί μόλις το πορτοφόλι σου δει τη συναλλαγή. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. Η πληρωμή δεν επιβεβαιώθηκε - Το δίκτυο απέρριψε αυτή τη συναλλαγή, για παράδειγμα επειδή τα νομίσματά της έχουν ήδη δαπανηθεί. Η πληρωμή παραμένει σε εκκρεμότητα μέχρι το πορτοφόλι σου να δει τη συναλλαγή. + Αυτή η πληρωμή μπορεί ακόμη να επιβεβαιωθεί. Παραμένει σε εκκρεμότητα μέχρι να τη δει το πορτοφόλι σου ή να ξοδευτούν αλλού τα νομίσματά της. + Αυτή η πληρωμή δεν μπορεί να επιβεβαιωθεί ποτέ. Μπορείς να την κάνεις ξανά. ΠΡΟΣ ΔΙΕΥΘΥΝΣΗ (ΕΠΙΒΕΒΑΙΩΣΗ ΣΤΗ ΣΥΣΚΕΥΗ) + Το δίκτυο δεν έλαβε αυτή την πληρωμή. Μπορείς να την κάνεις ξανά. + Η πληρωμή δεν στάλθηκε Το Trezor μπορεί να στείλει μόνο σε διεύθυνση Bitcoin από αυτό το πορτοφόλι. Το Jade μπορεί να στείλει μόνο σε διεύθυνση Bitcoin από αυτό το πορτοφόλι. Απαιτείται διεύθυνση Bitcoin diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 00c937fe35..94fbd304b0 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1211,10 +1211,14 @@ No se pudieron conservar las etiquetas de este monedero en tu copia de seguridad. Inténtalo de nuevo o elimínalo sin conservarlas. No se pudo cambiar el nombre del monedero de hardware. Inténtalo de nuevo. No se pudieron buscar monederos de hardware. Comprueba tu conexión e inténtalo de nuevo. + La red aceptó este pago. Se completará cuando tu monedero vea la transacción. Comprueba tu conexión e inténtalo de nuevo. Pago no confirmado - La red ha rechazado esta transacción, por ejemplo porque sus monedas ya se han gastado. El pago sigue pendiente hasta que tu monedero vea la transacción. + Este pago aún podría confirmarse. Sigue pendiente hasta que tu monedero lo vea o sus monedas se gasten en otra transacción. + Este pago nunca podrá confirmarse. Puedes hacerlo de nuevo. A LA DIRECCIÓN (CONFIRMA EN EL DISPOSITIVO) + La red no recibió este pago. Puedes hacerlo de nuevo. + Pago no enviado Trezor solo puede enviar a una dirección de Bitcoin desde este monedero. Jade solo puede enviar a una dirección de Bitcoin desde este monedero. Se requiere una dirección de Bitcoin diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index aad5bb0cfd..99205096c5 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1209,10 +1209,14 @@ No se pudieron conservar las etiquetas de este monedero en su copia de seguridad. Inténtelo de nuevo o elimínelo sin conservarlas. No se pudo cambiar el nombre del monedero de hardware. Inténtelo de nuevo. No se pudieron buscar monederos de hardware. Compruebe su conexión e inténtelo de nuevo. + La red aceptó este pago. Se completará cuando su monedero vea la transacción. Compruebe su conexión e inténtelo de nuevo. Pago no confirmado - La red ha rechazado esta transacción, por ejemplo porque sus monedas ya se han gastado. El pago sigue pendiente hasta que su monedero vea la transacción. + Este pago aún podría confirmarse. Sigue pendiente hasta que su monedero lo vea o sus monedas se gasten en otra transacción. + Este pago nunca podrá confirmarse. Puede hacerlo de nuevo. A LA DIRECCIÓN (CONFIRME EN EL DISPOSITIVO) + La red no recibió este pago. Puede hacerlo de nuevo. + Pago no enviado Trezor solo puede enviar a una dirección de Bitcoin desde este monedero. Jade solo puede enviar a una dirección de Bitcoin desde este monedero. Se requiere una dirección de Bitcoin diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index c638ed8f6d..1a45bc7530 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1215,10 +1215,14 @@ Impossible de garder les étiquettes de ce portefeuille dans votre sauvegarde. Réessayez ou retirez-le sans les garder. Impossible de renommer le portefeuille matériel. Veuillez réessayer. Impossible de rechercher des portefeuilles matériels. Vérifiez votre connexion et réessayez. + Le réseau a accepté ce paiement. Il sera finalisé dès que votre portefeuille verra la transaction. Vérifiez votre connexion et réessayez. Paiement non confirmé - Le réseau a refusé cette transaction, par exemple parce que ses fonds ont déjà été dépensés. Le paiement reste en attente jusqu\'à ce que votre portefeuille voie la transaction. + Ce paiement peut encore être confirmé. Il reste en attente jusqu\'à ce que votre portefeuille le voie ou que ses pièces soient dépensées ailleurs. + Ce paiement ne pourra jamais être confirmé. Vous pouvez le refaire. VERS L\'ADRESSE (CONFIRMER SUR L\'APPAREIL) + Le réseau n\'a pas reçu ce paiement. Vous pouvez le refaire. + Paiement non envoyé Trezor ne peut envoyer qu\'à une adresse Bitcoin depuis ce portefeuille. Jade ne peut envoyer qu\'à une adresse Bitcoin depuis ce portefeuille. Adresse Bitcoin requise diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 2cdf0e5e5b..0ff21f01b1 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1217,10 +1217,14 @@ Impossibile mantenere i tag di questo wallet nel backup. Riprova, oppure rimuovilo senza mantenerli. Impossibile rinominare l\'hardware wallet. Riprova. Impossibile cercare hardware wallet. Controlla la connessione e riprova. + La rete ha accettato questo pagamento. Si completerà non appena il tuo wallet vedrà la transazione. Controlla la connessione e riprova. Pagamento non confermato - La rete ha rifiutato questa transazione, ad esempio perché le sue monete sono già state spese. Il pagamento resta in sospeso finché il tuo wallet non vede la transazione. + Questo pagamento potrebbe ancora essere confermato. Resta in sospeso finché il tuo wallet non lo vede o le sue monete non vengono spese altrove. + Questo pagamento non potrà mai essere confermato. Puoi effettuarlo di nuovo. ALL\'INDIRIZZO (CONFERMA SUL DISPOSITIVO) + La rete non ha ricevuto questo pagamento. Puoi effettuarlo di nuovo. + Pagamento non inviato Da questo wallet, Trezor può inviare solo a un indirizzo Bitcoin. Da questo wallet, Jade può inviare solo a un indirizzo Bitcoin. Indirizzo Bitcoin richiesto diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index fa9335769f..ba51f32964 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1212,10 +1212,14 @@ Kon de tags van deze wallet niet in uw backup bewaren. Probeer het opnieuw, of verwijder de wallet zonder ze te bewaren. Kon de naam van de hardwarewallet niet wijzigen. Probeer het opnieuw. Kon niet zoeken naar hardwarewallets. Controleer uw verbinding en probeer het opnieuw. + Het netwerk heeft deze betaling geaccepteerd. Ze wordt voltooid zodra uw wallet de transactie ziet. Controleer uw verbinding en probeer het opnieuw. Betaling niet bevestigd - Het netwerk heeft deze transactie geweigerd, bijvoorbeeld omdat de munten ervan al zijn uitgegeven. De betaling blijft in behandeling totdat uw wallet de transactie ziet. + Deze betaling kan nog worden bevestigd. Ze blijft in behandeling totdat uw wallet haar ziet of de munten ervan elders worden uitgegeven. + Deze betaling kan nooit worden bevestigd. U kunt haar opnieuw uitvoeren. NAAR ADRES (BEVESTIG OP APPARAAT) + Het netwerk heeft deze betaling niet ontvangen. U kunt haar opnieuw uitvoeren. + Betaling niet verzonden Trezor kan vanuit deze wallet alleen naar een Bitcoin-adres versturen. Jade kan vanuit deze wallet alleen naar een Bitcoin-adres versturen. Bitcoin-adres vereist diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index ba5f657f78..6d32b520a8 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1218,10 +1218,14 @@ Nie udało się zachować tagów tego portfela w kopii zapasowej. Spróbuj ponownie lub usuń go bez ich zachowywania. Nie udało się zmienić nazwy portfela sprzętowego. Spróbuj ponownie. Nie udało się wyszukać portfeli sprzętowych. Sprawdź połączenie i spróbuj ponownie. + Sieć przyjęła tę płatność. Zostanie zakończona, gdy Twój portfel zobaczy transakcję. Sprawdź połączenie i spróbuj ponownie. Płatność niepotwierdzona - Sieć odrzuciła tę transakcję, na przykład dlatego, że jej środki zostały już wydane. Płatność pozostaje oczekująca, dopóki Twój portfel nie zobaczy transakcji. + Ta płatność nadal może zostać potwierdzona. Pozostaje oczekująca, dopóki Twój portfel jej nie zobaczy lub jej monety nie zostaną wydane gdzie indziej. + Ta płatność nigdy nie zostanie potwierdzona. Możesz wykonać ją ponownie. NA ADRES (POTWIERDŹ NA URZĄDZENIU) + Sieć nie otrzymała tej płatności. Możesz wykonać ją ponownie. + Płatność nie została wysłana Trezor może wysyłać z tego portfela tylko na adres Bitcoin. Jade może wysyłać z tego portfela tylko na adres Bitcoin. Wymagany adres Bitcoin diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 50062f4db0..bc2ec91331 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1220,10 +1220,14 @@ Não foi possível manter as tags desta carteira no seu backup. Tente novamente ou remova-a sem mantê-las. Não foi possível renomear a carteira de hardware. Tente novamente. Não foi possível procurar carteiras de hardware. Verifique sua conexão e tente novamente. + A rede aceitou este pagamento. Ele será concluído assim que sua carteira vir a transação. Verifique sua conexão e tente novamente. Pagamento não confirmado - A rede recusou esta transação, por exemplo porque suas moedas já foram gastas. O pagamento continua pendente até que sua carteira veja a transação. + Este pagamento ainda pode ser confirmado. Ele continua pendente até que sua carteira o veja ou suas moedas sejam gastas em outro lugar. + Este pagamento nunca poderá ser confirmado. Você pode fazê-lo novamente. PARA O ENDEREÇO (CONFIRME NO DISPOSITIVO) + A rede não recebeu este pagamento. Você pode fazê-lo novamente. + Pagamento não enviado O Trezor só pode enviar para um endereço Bitcoin a partir desta carteira. O Jade só pode enviar para um endereço Bitcoin a partir desta carteira. Endereço Bitcoin necessário diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 0d01e80d50..df063860a8 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1186,10 +1186,14 @@ Não foi possível manter as etiquetas desta carteira na cópia de segurança. Tente novamente ou remova-a sem as manter. Não foi possível mudar o nome da carteira de hardware. Tente novamente. Não foi possível procurar carteiras de hardware. Verifique a ligação e tente novamente. + A rede aceitou este pagamento. Fica concluído assim que a sua carteira vir a transação. Verifique a ligação e tente novamente. Pagamento não confirmado - A rede recusou esta transação, por exemplo porque as suas moedas já foram gastas. O pagamento continua pendente até a sua carteira ver a transação. + Este pagamento ainda pode ser confirmado. Continua pendente até a sua carteira o ver ou as suas moedas serem gastas noutro lado. + Este pagamento nunca poderá ser confirmado. Pode fazê-lo novamente. PARA O ENDEREÇO (CONFIRME NO DISPOSITIVO) + A rede não recebeu este pagamento. Pode fazê-lo novamente. + Pagamento não enviado O Trezor só pode enviar para um endereço Bitcoin a partir desta carteira. O Jade só pode enviar para um endereço Bitcoin a partir desta carteira. Endereço Bitcoin necessário diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index b38a494cb3..1e4f0da226 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1236,10 +1236,14 @@ Не удалось сохранить теги этого кошелька в резервной копии. Попробуйте снова или удалите его без сохранения тегов. Не удалось переименовать аппаратный кошелёк. Пожалуйста, попробуйте снова. Не удалось найти аппаратные кошельки. Проверьте подключение и попробуйте снова. + Сеть приняла этот платёж. Он завершится, как только ваш кошелёк увидит транзакцию. Проверьте подключение и попробуйте снова. Платёж не подтверждён - Сеть отклонила эту транзакцию, например потому, что её монеты уже потрачены. Платёж остаётся в ожидании, пока ваш кошелёк не увидит транзакцию. + Этот платёж ещё может быть подтверждён. Он остаётся в ожидании, пока ваш кошелёк его не увидит или его монеты не будут потрачены в другой транзакции. + Этот платёж никогда не будет подтверждён. Вы можете выполнить его снова. НА АДРЕС (ПОДТВЕРДИТЕ НА УСТРОЙСТВЕ) + Сеть не получила этот платёж. Вы можете выполнить его снова. + Платёж не отправлен Trezor может отправлять из этого кошелька только на Bitcoin-адрес. Jade может отправлять из этого кошелька только на Bitcoin-адрес. Нужен Bitcoin-адрес diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 299c66c01a..80fbd374c8 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -229,10 +229,14 @@ Could not keep this wallet\'s tags in your backup. Try again, or remove it without keeping them. Could not rename the hardware wallet. Please try again. Could not search for hardware wallets. Check your connection and try again. + The network accepted this payment. It completes once your wallet sees the transaction. Check your connection and try again. Payment not confirmed - The network refused this transaction, for example because its coins were already spent. The payment stays pending until your wallet sees it. + This payment may still confirm. It stays pending until your wallet sees it or its coins are spent elsewhere. + This payment can never confirm. You can make it again. TO ADDRESS (CONFIRM ON DEVICE) + The network did not receive this payment. You can make it again. + Payment not sent Trezor can only send to a Bitcoin address from this wallet. Jade can only send to a Bitcoin address from this wallet. Bitcoin address required diff --git a/app/src/test/java/to/bitkit/ext/BroadcastExceptionExtTest.kt b/app/src/test/java/to/bitkit/ext/BroadcastExceptionExtTest.kt index 5d78b9abf3..2ba5ff5f3d 100644 --- a/app/src/test/java/to/bitkit/ext/BroadcastExceptionExtTest.kt +++ b/app/src/test/java/to/bitkit/ext/BroadcastExceptionExtTest.kt @@ -48,12 +48,11 @@ class BroadcastExceptionExtTest { } @Test - fun `only an undecodable transaction, a failed connect or a node refusal proves nothing was sent`() = runTest { + fun `only an undecodable transaction or a failed connect proves nothing was sent`() = runTest { val notSent = listOf( BroadcastException.InvalidHex("Invalid transaction hex: odd number of digits"), BroadcastException.InvalidTransaction("Invalid transaction data: unexpected end of file"), BroadcastException.ElectrumException("Failed to connect to Electrum: I/O error: Connection refused"), - BroadcastException.ElectrumException("Broadcast failed: min relay fee not met"), ) for (error in notSent) { assertTrue(AppError(error).isHardwareBroadcastNotSent()) @@ -65,6 +64,7 @@ class BroadcastExceptionExtTest { ), BroadcastException.ElectrumException("Broadcast failed: Failed to connect to Electrum: lookalike"), BroadcastException.TaskException("Broadcast task failed: task 7 panicked"), + BroadcastException.ElectrumException("Broadcast failed: min relay fee not met"), AppError("unknown result"), timeout, ) @@ -73,6 +73,75 @@ class BroadcastExceptionExtTest { } } + @Test + fun `only undecodable bytes or a consensus or script refusal proves a transaction can never confirm`() { + assertTrue(AppError(BroadcastException.InvalidHex("bad hex")).isHardwareBroadcastNeverConfirmable()) + assertTrue(BroadcastException.InvalidTransaction("bad tx").isHardwareBroadcastNeverConfirmable()) + val neverConfirms = listOf( + "mandatory-script-verify-flag-failed (Signature must be zero for failed CHECK(MULTI)SIG operation)", + "block-script-verify-flag-failed (Script failed an OP_EQUALVERIFY operation)", + "bad-txns-in-belowout, value in (0.0001) < value out (0.0002)", + "bad-txns-inputs-duplicate", + "bad-txns-vout-negative", + "bad-txns-vout-toolarge", + "bad-txns-txouttotal-toolarge", + "bad-txns-oversize", + ) + for (reason in neverConfirms) { + assertTrue(refusal("-26: $reason").isHardwareBroadcastNeverConfirmable(), reason) + assertFalse(refusal("-26: $reason").isHardwareBroadcastInputsSpent(), reason) + } + val mayConfirm = listOf( + "-26: min relay fee not met, 110 < 141", + "-26: mempool min fee not met, 110 < 141", + "-26: mempool full", + "-26: too-long-mempool-chain, too many unconfirmed ancestors [limit: 25]", + "-25: max-fee-exceeded", + "-26: txn-mempool-conflict", + "-26: non-final", + "-26: dust", + "-26: scriptpubkey", + "-26: mempool-script-verify-flag-failed (Witness program hash mismatch)", + "-26: dusty-but-unknown", + "-26: non-mandatory-script-verify-flag (Witness program hash mismatch)", + "-26: tx-size", + "-25: bad-txns-inputs-missingorspent", + ) + for (reason in mayConfirm) { + assertFalse(refusal(reason).isHardwareBroadcastNeverConfirmable(), reason) + } + val unreadable = listOf( + "Broadcast failed: bad-txns-oversize", + "Broadcast failed: Electrum server error: bad-txns-oversize", + "Broadcast failed: Electrum server error: {\"message\": 26}", + "Failed to connect to Electrum: bad-txns-oversize", + ) + for (details in unreadable) { + assertFalse(BroadcastException.ElectrumException(details).isHardwareBroadcastNeverConfirmable(), details) + } + assertFalse( + BroadcastException.ElectrumException( + "Broadcast failed: Made one or multiple attempts, all errored:\n\t- Broken pipe (os error 32)\n", + ).isHardwareBroadcastNeverConfirmable(), + ) + } + + @Test + fun `a missing or spent input refusal counts only as the server's JSON refusal`() { + assertTrue(refusal("-25: bad-txns-inputs-missingorspent").isHardwareBroadcastInputsSpent()) + assertFalse( + BroadcastException.ElectrumException("Broadcast failed: bad-txns-inputs-missingorspent") + .isHardwareBroadcastInputsSpent(), + ) + assertFalse(refusal("-26: txn-mempool-conflict").isHardwareBroadcastInputsSpent()) + } + + private fun refusal(reason: String) = AppError( + BroadcastException.ElectrumException( + "Broadcast failed: Electrum server error: \"sendrawtransaction RPC error $reason\"", + ), + ) + @Test fun `recognized backend refusals allow navigation without proving no dispatch`() { val reasons = listOf( diff --git a/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt index ba258a1e5d..c0e0906832 100644 --- a/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt @@ -9,16 +9,19 @@ import com.synonym.bitkitcore.CompletedTransaction import com.synonym.bitkitcore.ComposeAccount import com.synonym.bitkitcore.ComposeOutput import com.synonym.bitkitcore.ComposeResult +import com.synonym.bitkitcore.HistoryTransaction import com.synonym.bitkitcore.JadeTransportKind import com.synonym.bitkitcore.OnchainActivity import com.synonym.bitkitcore.PaymentType import com.synonym.bitkitcore.PreActivityMetadata import com.synonym.bitkitcore.TransactionDetail import com.synonym.bitkitcore.TransactionDetails +import com.synonym.bitkitcore.TransactionHistoryResult import com.synonym.bitkitcore.TrezorAddressResponse import com.synonym.bitkitcore.TrezorException import com.synonym.bitkitcore.TrezorFeatures import com.synonym.bitkitcore.TrezorSignedTx +import com.synonym.bitkitcore.TxDetailInput import com.synonym.bitkitcore.WalletBalance import com.synonym.bitkitcore.WatcherEvent import kotlinx.coroutines.CompletableDeferred @@ -26,7 +29,6 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent @@ -76,6 +78,8 @@ class HwWalletRepoTest : BaseUnitTest() { private companion object { const val HARDWARE_WALLET_ID = "hardware-wallet" const val HELD_ADDRESS = "bcrt1qs04g2ka4pr9s3mv73nu32tvfy7r3cxd27wkyu8" + const val HELD_TXID = "605fe246a6d51450ecff51ac3d0415f8824964e06a60ed6e186fa163cf1e9d4e" + const val HELD_INPUT_TXID = "167c8b8b6169007fd94edc121d606c829cbb5d6b51075bb0c664911848a0c5f7" const val HIDDEN_WALLET_ID = "hidden-wallet" const val JADE_WALLET_ID = "jade-wallet" val WATCHER_RECEIVE_ADDRESS = AddressInfo( @@ -349,7 +353,7 @@ class HwWalletRepoTest : BaseUnitTest() { } @Test - fun `a held send blocks its payment until the wallet sees its transaction`() = test { + fun `a held send stays held for its payment even once the wallet sees it`() = test { val held = HeldHwSend( walletId = HARDWARE_WALLET_ID, txId = "T1", @@ -363,11 +367,6 @@ class HwWalletRepoTest : BaseUnitTest() { ) storeData.value = storeData.value.copy(heldSends = listOf(held)) whenever(hwWalletStore.loadHeldSends()).thenAnswer { storeData.value.heldSends } - whenever(hwWalletStore.releaseHeldSends(any())).doSuspendableAnswer { call -> - val txIds = call.getArgument>(0).map { it.lowercase() } - val kept = storeData.value.heldSends.filterNot { it.txId.lowercase() in txIds } - storeData.update { it.copy(heldSends = kept) } - } val sut = createRepo() assertEquals(held, sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS, 25_000uL).getOrThrow()) @@ -387,10 +386,80 @@ class HwWalletRepoTest : BaseUnitTest() { ) ) - assertNull(sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS, 25_000uL).getOrThrow()) - assertTrue(storeData.value.heldSends.isEmpty()) + // The send screen records a seen send before it is released, so it is never signed again unrecorded + assertEquals(held, sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS, 25_000uL).getOrThrow()) + verify(hwWalletStore, never()).releaseHeldSends(any()) + } + + @Test + fun `a held send is proven unconfirmable only by a final spend of its coin by another transaction`() = test { + whenever(hwWalletStore.loadKnownDevices()).thenReturn(listOf(device)) + val held = requireNotNull(javaClass.getResourceAsStream("/hardware-signed-transaction.hex")) + .bufferedReader().readText().trim() + val spender = "cd".repeat(32) + stubHistory( + historyTx(HELD_INPUT_TXID, blockHeight = 100u, confirmations = 10u, sent = 0uL), + historyTx(spender, blockHeight = 105u, confirmations = 6u, sent = 25_000uL), + ) + stubDetail(spender, HELD_INPUT_TXID to 1u) + val sut = createRepo() + + assertTrue(sut.isSpentByAnotherTransaction(HARDWARE_WALLET_ID, held).getOrThrow()) + + stubDetail(spender, HELD_INPUT_TXID to 0u) + assertFalse(sut.isSpentByAnotherTransaction(HARDWARE_WALLET_ID, held).getOrThrow()) + + stubDetail(spender, HELD_INPUT_TXID to 1u) + stubHistory( + historyTx(HELD_INPUT_TXID, blockHeight = 100u, confirmations = 10u, sent = 0uL), + historyTx(spender, blockHeight = 105u, confirmations = 5u, sent = 25_000uL), + ) + assertFalse(sut.isSpentByAnotherTransaction(HARDWARE_WALLET_ID, held).getOrThrow()) + + stubHistory( + historyTx(HELD_INPUT_TXID, blockHeight = 100u, confirmations = 10u, sent = 0uL), + historyTx(spender, blockHeight = 105u, confirmations = 6u, sent = 25_000uL), + historyTx(HELD_TXID, blockHeight = null, confirmations = 0u, sent = 25_000uL), + ) + assertFalse(sut.isSpentByAnotherTransaction(HARDWARE_WALLET_ID, held).getOrThrow()) + + whenever( + trezorRepo.getTransactionHistory("zpubNS", Env.network.toCoreNetwork(), AccountType.NATIVE_SEGWIT) + ).thenReturn(Result.failure(AppError("Electrum unreachable"))) + assertTrue(sut.isSpentByAnotherTransaction(HARDWARE_WALLET_ID, held).isFailure) } + private suspend fun stubHistory(vararg transactions: HistoryTransaction) { + val history = mock { on { this.transactions }.thenReturn(transactions.toList()) } + whenever( + trezorRepo.getTransactionHistory("zpubNS", Env.network.toCoreNetwork(), AccountType.NATIVE_SEGWIT) + ).thenReturn(Result.success(history)) + } + + private suspend fun stubDetail(txid: String, vararg inputs: Pair) { + val detailInputs = inputs.map { (inputTxid, vout) -> + mock { + on { this.txid }.thenReturn(inputTxid) + on { this.vout }.thenReturn(vout) + } + } + val detail = mock { + on { this.txid }.thenReturn(txid) + on { this.inputs }.thenReturn(detailInputs) + } + whenever( + trezorRepo.getTransactionDetail("zpubNS", txid, Env.network.toCoreNetwork(), AccountType.NATIVE_SEGWIT) + ).thenReturn(Result.success(detail)) + } + + private fun historyTx(txid: String, blockHeight: UInt?, confirmations: UInt, sent: ULong) = + mock { + on { this.txid }.thenReturn(txid) + on { this.blockHeight }.thenReturn(blockHeight) + on { this.confirmations }.thenReturn(confirmations) + on { this.sent }.thenReturn(sent) + } + @Test fun `transactions changed event sets device balance and maps activity`() = test { val sut = createRepo() diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index c6f146bb78..a900141aca 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -21,6 +21,7 @@ import com.synonym.paykit.PaymentRequestRecurrence import com.synonym.paykit.PaymentRequestTerms import com.synonym.paykit.PrivateJsonObject import com.synonym.paykit.PubkyIdentityCapability +import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -3008,7 +3009,16 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { it.getArgument Unit>(2)() hwWalletRepo.broadcastFunding(it.getArgument(0), it.getArgument(1)) } - val send = HwSendViewModel(context, hwWalletRepo, mock(), mock(), mock(), repo) + whenever(hwWalletRepo.wallets).thenReturn(MutableStateFlow(persistentListOf())) + val send = HwSendViewModel( + context, + hwWalletRepo, + mock(), + mock(), + mock(), + repo, + HwHeldDispatchTracker(), + ) send.signAndBroadcast( HwSendRequest( walletId, diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt index 2afb2fff9a..43b03e310d 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt @@ -45,6 +45,7 @@ import to.bitkit.models.HwWalletVendor import to.bitkit.models.Toast import to.bitkit.models.TransportType import to.bitkit.repositories.ActivityRepo +import to.bitkit.repositories.HwHeldDispatchTracker import to.bitkit.repositories.HwWalletMismatchError import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.PaykitPaymentProofRepo @@ -80,6 +81,8 @@ class HwSendViewModelTest : BaseUnitTest() { private val walletActivities = MutableStateFlow>(persistentListOf()) private val hwWallets = MutableStateFlow>(persistentListOf(hwWallet(WALLET_ID))) + private val heldDispatches = HwHeldDispatchTracker() + private lateinit var sut: HwSendViewModel private var now = Instant.parse("2026-10-06T11:59:59Z") @@ -127,18 +130,22 @@ class HwSendViewModelTest : BaseUnitTest() { whenever { hwWalletRepo.heldSendFor(any(), any(), any()) }.thenReturn(Result.success(null)) whenever { hwWalletRepo.holdSend(any()) }.thenReturn(Result.success(Unit)) whenever { hwWalletRepo.releaseHeldSend(any()) }.thenReturn(Result.success(Unit)) - sut = HwSendViewModel( - context = context, - hwWalletRepo = hwWalletRepo, - preActivityMetadataRepo = preActivityMetadataRepo, - coreService = coreService, - activityRepo = activityRepo, - paykitPaymentProofRepo = proofRepo, - clock = object : Clock { - override fun now() = now - }, - ) - } + whenever { hwWalletRepo.isSpentByAnotherTransaction(any(), any()) }.thenReturn(Result.success(false)) + sut = createViewModel() + } + + private fun createViewModel() = HwSendViewModel( + context = context, + hwWalletRepo = hwWalletRepo, + preActivityMetadataRepo = preActivityMetadataRepo, + coreService = coreService, + activityRepo = activityRepo, + paykitPaymentProofRepo = proofRepo, + heldDispatches = heldDispatches, + clock = object : Clock { + override fun now() = now + }, + ) @Test fun `signing reconnects and retries once after THP channel failure`() = test { @@ -398,24 +405,34 @@ class HwSendViewModelTest : BaseUnitTest() { } @Test - fun `Shop broadcast unanswered past the wait keeps its signed payment guarded`() = test { + fun `Shop broadcast unanswered past the wait stays guarded and its late answer still lands`() = test { val toasts = mutableListOf() val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } whenever(context.getString(any())).thenReturn("message") val fixture = stubSuccessfulPayment() val original = request().copy(paymentRequestId = PaykitPaymentRequestId("request", "counterparty")) - whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { awaitCancellation() } + val late = CompletableDeferred>() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { + withContext(NonCancellable) { late.await() } + } sut.signAndBroadcast(original) - advanceTimeBy(121.seconds) + advanceTimeBy(61.seconds) runCurrent() - toastJob.cancel() assertFalse(sut.uiState.value.isSigning) assertTrue(sut.uiState.value.isBroadcastUnresolved) assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) assertEquals(Toast.ToastType.WARNING, toasts.single().type) verify(hwWalletRepo, never()).holdSend(any()) + + late.complete(Result.success(fixture.broadcast)) + advanceUntilIdle() + toastJob.cancel() + + val result = sut.results.first() + assertEquals(fixture.broadcast.txId, result.txId) + assertEquals(original.paymentRequestId, result.paymentRequestId) } @Test @@ -543,7 +560,7 @@ class HwSendViewModelTest : BaseUnitTest() { } @Test - fun `a broadcast unanswered for two minutes shows as pending and completes once it answers`() = test { + fun `a broadcast unanswered for a minute shows as pending until the wallet sees it`() = test { val toasts = mutableListOf() val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } whenever(context.getString(any())).thenReturn("message") @@ -557,7 +574,7 @@ class HwSendViewModelTest : BaseUnitTest() { val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) sut.signAndBroadcast(request()) - advanceTimeBy(119.seconds) + advanceTimeBy(59.seconds) runCurrent() assertFalse(sut.uiState.value.canLeave) @@ -567,11 +584,16 @@ class HwSendViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.isSigning) assertEquals(held, sut.uiState.value.unresolvedSend) assertEquals(listOf(held), sut.uiState.value.unresolvedSends) - verify(hwWalletRepo, never()).releaseHeldSend(any()) sut.cancel() broadcastResult.complete(Result.success(fixture.broadcast)) advanceUntilIdle() + assertTrue(events.isEmpty()) + assertEquals(listOf(held), sut.uiState.value.unresolvedSends) + verify(hwWalletRepo, never()).releaseHeldSend(any()) + + walletActivities.value = persistentListOf(sentActivity()) + advanceUntilIdle() toastJob.cancel() assertTrue(toasts.isEmpty()) @@ -595,21 +617,50 @@ class HwSendViewModelTest : BaseUnitTest() { } @Test - fun `a broadcast that answers a refusal after the wait keeps its send held`() = test { + fun `a late answer proving the first broadcast sent nothing releases its send`() = test { + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } whenever(context.getString(any())).thenReturn("message") + whenever(context.getString(R.string.hardware__send_not_sent_text)).thenReturn("not sent") val fixture = stubSuccessfulPayment() val broadcastResult = CompletableDeferred>() whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { withContext(NonCancellable) { broadcastResult.await() } } + val events = mutableListOf() + backgroundScope.launch { sut.heldSendEvents.collect { events += it } } sut.signAndBroadcast(request()) - advanceTimeBy(121.seconds) + advanceTimeBy(61.seconds) runCurrent() broadcastResult.complete(Result.failure(BroadcastException.ElectrumException(NODE_REFUSAL))) advanceUntilIdle() + toastJob.cancel() + + val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) + assertEquals(listOf(HeldHwSendEvent.Released(held)), events) + assertEquals(1, toasts.count { it.description == "not sent" }) + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) + } + + @Test + fun `a late answer that may have gone out keeps its send held`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + val first = CompletableDeferred>() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { + withContext(NonCancellable) { first.await() } + } + + sut.signAndBroadcast(request()) + advanceTimeBy(61.seconds) + runCurrent() + first.complete(Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE))) + advanceUntilIdle() assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) + assertTrue(sut.uiState.value.retryingSendTxIds.isEmpty()) verify(hwWalletRepo, never()).releaseHeldSend(any()) verify(activityService, never()).createSentOnchainActivityFromSendResult( txid = SIGNED_TXID, @@ -623,6 +674,108 @@ class HwSendViewModelTest : BaseUnitTest() { ) } + @Test + fun `a broadcast that answers a refusal no node can accept after the wait releases its send`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + val broadcastResult = CompletableDeferred>() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { + withContext(NonCancellable) { broadcastResult.await() } + } + val events = mutableListOf() + backgroundScope.launch { sut.heldSendEvents.collect { events += it } } + + sut.signAndBroadcast(request()) + advanceTimeBy(61.seconds) + runCurrent() + broadcastResult.complete(Result.failure(BroadcastException.ElectrumException(SCRIPT_REFUSAL))) + advanceUntilIdle() + + val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) + assertEquals(listOf(HeldHwSendEvent.Released(held)), events) + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) + } + + @Test + fun `a payment resumed from another sheet is not broadcast again while its first broadcast is unanswered`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + val first = CompletableDeferred>() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { + withContext(NonCancellable) { first.await() } + }.thenReturn(Result.success(fixture.broadcast)) + val otherSheet = createViewModel() + + sut.signAndBroadcast(request()) + advanceTimeBy(61.seconds) + runCurrent() + whenever(hwWalletRepo.heldSendFor(WALLET_ID, ADDRESS, AMOUNT_SATS)) + .thenReturn(Result.success(heldSend(fixture.signedTx))) + sut.retryUnresolvedSend(SIGNED_TXID) + otherSheet.signAndBroadcast(request()) + runCurrent() + + verify(hwWalletRepo, times(1)).broadcastFunding(fixture.signedTx) + assertTrue(SIGNED_TXID in sut.uiState.value.retryingSendTxIds) + assertTrue(SIGNED_TXID in otherSheet.uiState.value.retryingSendTxIds) + + first.complete(Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE))) + advanceUntilIdle() + otherSheet.retryUnresolvedSend(SIGNED_TXID) + advanceUntilIdle() + + verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) + verify(hwWalletRepo, times(1)).signFunding(any(), any()) + verify(hwWalletRepo, never()).releaseHeldSend(any()) + } + + @Test + fun `a late proof that nothing was sent keeps the hold when the same bytes may have gone out before`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + val first = CompletableDeferred>() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { + withContext(NonCancellable) { first.await() } + } + val earlier = requireNotNull(heldDispatches.begin(SIGNED_TXID)) + heldDispatches.finish(earlier, isNotSent = false) + + sut.signAndBroadcast(request()) + advanceTimeBy(61.seconds) + runCurrent() + first.complete(Result.failure(BroadcastException.ElectrumException(CONNECT_FAILURE))) + advanceUntilIdle() + + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) + verify(hwWalletRepo, never()).releaseHeldSend(any()) + } + + @Test + fun `a broadcast again writes its hold first and is skipped when that write fails`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE)), + Result.success(fixture.broadcast), + ) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + whenever(hwWalletRepo.holdSend(any())).thenReturn(Result.failure(AppError("Store unwritable"))) + sut.retryUnresolvedSend(SIGNED_TXID) + advanceUntilIdle() + verify(hwWalletRepo, times(1)).broadcastFunding(fixture.signedTx) + + whenever(hwWalletRepo.holdSend(any())).thenReturn(Result.success(Unit)) + sut.retryUnresolvedSend(SIGNED_TXID) + advanceUntilIdle() + + verify(hwWalletRepo, times(3)).holdSend(heldSend(fixture.signedTx)) + verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) + assertTrue(sut.uiState.value.retryingSendTxIds.isEmpty()) + } + @Test fun `a sent hardware send is recorded before its hold is released`() = test { val fixture = stubSuccessfulPayment() @@ -677,10 +830,38 @@ class HwSendViewModelTest : BaseUnitTest() { } @Test - fun `cancel drops the signed transaction after a node refusal`() = test { + fun `cancel drops the signed transaction after a first broadcast the node refused`() = test { assertCancelReleasesSignedTransaction(BroadcastException.ElectrumException(NODE_REFUSAL)) } + @Test + fun `a refusal no node can accept releases the send and says it was not sent`() = test { + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + whenever(context.getString(any())).thenReturn("message") + whenever(context.getString(R.string.hardware__send_broadcast_rejected_text)).thenReturn("rejected") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(BroadcastException.ElectrumException(SCRIPT_REFUSAL)), + Result.success(fixture.broadcast), + ) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + assertEquals(1, toasts.count { it.description == "rejected" }) + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) + assertFalse(sut.uiState.value.hasPendingBroadcast) + assertTrue(sut.uiState.value.canLeave) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + toastJob.cancel() + + verify(hwWalletRepo, times(2)).signFunding(WALLET_ID, fixture.funding) + } + @Test fun `an invalid transaction drops the signed transaction at once`() = test { whenever(context.getString(any())).thenReturn("message") @@ -797,35 +978,35 @@ class HwSendViewModelTest : BaseUnitTest() { } @Test - fun `a new send of a payment held before a restart is refused and retried only as the same bytes`() = test { + fun `a payment held before a restart is broadcast again as the same bytes instead of signed`() = test { val toasts = mutableListOf() val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } whenever(context.getString(any())).thenReturn("message") - whenever(context.getString(R.string.wallet__send_pending__blocked_new_send)).thenReturn("blocked") + whenever(context.getString(R.string.hardware__send_broadcast_accepted)).thenReturn("accepted") val fixture = stubSuccessfulPayment() whenever(hwWalletRepo.heldSendFor(WALLET_ID, ADDRESS, AMOUNT_SATS)) .thenReturn(Result.success(heldSend(fixture.signedTx))) whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn(Result.success(fixture.broadcast)) val results = mutableListOf() backgroundScope.launch { sut.heldSendEvents.collect { results += it.send } } + val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) sut.signAndBroadcast(request()) advanceUntilIdle() verify(hwWalletRepo, never()).signFunding(any(), any()) - verify(hwWalletRepo, never()).broadcastFunding(any(), anyOrNull()) - assertEquals(1, toasts.count { it.description == "blocked" }) - assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.uiState.value.unresolvedSend) - assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.refuseNewSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) + verify(hwWalletRepo).broadcastFunding(fixture.signedTx) + assertEquals(1, toasts.count { it.title == "accepted" }) + assertEquals(held, sut.uiState.value.unresolvedSend) + assertTrue(results.isEmpty()) - sut.retryUnresolvedSend(SIGNED_TXID) + walletActivities.value = persistentListOf(sentActivity()) advanceUntilIdle() toastJob.cancel() - verify(hwWalletRepo).broadcastFunding(fixture.signedTx) verify(hwWalletRepo, never()).signFunding(any(), any()) verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) - assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), results) + assertEquals(listOf(held), results) } @Test @@ -862,12 +1043,13 @@ class HwSendViewModelTest : BaseUnitTest() { } @Test - fun `a held send retried from pending stays held on any failure and completes once sent`() = test { + fun `a held send broadcast again stays held on any failure and completes once the wallet sees it`() = test { val toasts = mutableListOf() val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } whenever(context.getString(any())).thenReturn("message") whenever(context.getString(R.string.hardware__send_broadcast_failed_text)).thenReturn("try again") whenever(context.getString(R.string.hardware__send_broadcast_refused_text)).thenReturn("refused") + whenever(context.getString(R.string.hardware__send_broadcast_accepted)).thenReturn("accepted") val fixture = stubSuccessfulPayment() whenever(hwWalletRepo.disconnectStaleSession(WALLET_ID)).thenReturn(Result.success(Unit)) whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( @@ -893,11 +1075,14 @@ class HwSendViewModelTest : BaseUnitTest() { assertTrue(sut.uiState.value.retryingSendTxIds.isEmpty()) } assertTrue(results.isEmpty()) - assertEquals(1, toasts.count { it.description == "try again" }) - assertEquals(1, toasts.count { it.description == "refused" }) + assertEquals(0, toasts.count { it.description == "try again" }) + assertEquals(2, toasts.count { it.description == "refused" }) sut.retryUnresolvedSend(SIGNED_TXID) advanceUntilIdle() + assertEquals(1, toasts.count { it.title == "accepted" }) + assertEquals(listOf(held), sut.uiState.value.unresolvedSends) + assertTrue(results.isEmpty()) walletActivities.value = persistentListOf(sentActivity()) advanceUntilIdle() toastJob.cancel() @@ -947,33 +1132,144 @@ class HwSendViewModelTest : BaseUnitTest() { } @Test - fun `a new send is refused while one is held and points to the held payment`() = test { + fun `a held send whose coins another transaction spent for good is released on retry`() = test { val toasts = mutableListOf() val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } whenever(context.getString(any())).thenReturn("message") - whenever(context.getString(R.string.wallet__send_pending__blocked_new_send)).thenReturn("blocked") + whenever(context.getString(R.string.hardware__send_broadcast_rejected_text)).thenReturn("rejected") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE)), + Result.failure(BroadcastException.ElectrumException(INPUTS_SPENT)), + Result.failure(BroadcastException.ElectrumException(INPUTS_SPENT)), + ) + whenever(hwWalletRepo.isSpentByAnotherTransaction(WALLET_ID, fixture.signedTx.serializedTx)) + .thenReturn(Result.failure(AppError("Electrum unreachable")), Result.success(true)) + val events = mutableListOf() + backgroundScope.launch { sut.heldSendEvents.collect { events += it } } + val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + sut.retryUnresolvedSend(SIGNED_TXID) + advanceUntilIdle() + assertEquals(listOf(held), sut.uiState.value.unresolvedSends) + verify(hwWalletRepo, never()).releaseHeldSend(any()) + + sut.retryUnresolvedSend(SIGNED_TXID) + advanceUntilIdle() + toastJob.cancel() + + assertEquals(listOf(HeldHwSendEvent.Released(held)), events) + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) + assertEquals(1, toasts.count { it.description == "rejected" }) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) + assertNull(sut.resumeHeldSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) + } + + @Test + fun `a dust refusal of a broadcast again keeps the hold, as a miner may still confirm it`() = test { + whenever(context.getString(any())).thenReturn("message") + whenever(context.getString(R.string.hardware__send_broadcast_refused_text)).thenReturn("refused") + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE)), + Result.failure(BroadcastException.ElectrumException(DUST_REFUSAL)), + ) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + sut.retryUnresolvedSend(SIGNED_TXID) + advanceUntilIdle() + toastJob.cancel() + + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) + assertEquals(1, toasts.count { it.description == "refused" }) + verify(hwWalletRepo, never()).releaseHeldSend(any()) + } + + @Test + fun `a held payment the wallet has seen is recorded as sent instead of signed again`() = test { + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.heldSendFor(WALLET_ID, ADDRESS, AMOUNT_SATS)) + .thenReturn(Result.success(heldSend(fixture.signedTx))) + walletActivities.value = persistentListOf(sentActivity()) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.results.first()) + verify(hwWalletRepo, never()).signFunding(any(), any()) + verify(hwWalletRepo, never()).broadcastFunding(any(), anyOrNull()) + inOrder(activityService, hwWalletRepo) { + verify(activityService).createSentOnchainActivityFromSendResult( + txid = SIGNED_TXID, + address = ADDRESS, + amount = AMOUNT_SATS, + fee = fixture.signedTx.miningFeeSats, + feeRate = fixture.signedTx.feeRate, + isTransfer = false, + channelId = null, + walletId = WALLET_ID, + ) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) + } + } + + @Test + fun `a held send the wallet has seen completes instead of being released`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE)), + Result.failure(BroadcastException.ElectrumException(SCRIPT_REFUSAL)), + ) + val events = mutableListOf() + backgroundScope.launch { sut.heldSendEvents.collect { events += it } } + val seen = MutableStateFlow>(persistentListOf(sentActivity())) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + // The wallet's history shows the transaction before its watch has run + whenever(hwWalletRepo.activities).thenReturn(seen) + sut.retryUnresolvedSend(SIGNED_TXID) + advanceUntilIdle() + + val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) + assertEquals(listOf(HeldHwSendEvent.Completed(held)), events) + } + + @Test + fun `a new send of a held payment is broadcast again and points to the held payment`() = test { + whenever(context.getString(any())).thenReturn("message") val fixture = stubSuccessfulPayment() whenever(hwWalletRepo.disconnectStaleSession(WALLET_ID)).thenReturn(Result.success(Unit)) - whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) - .thenReturn(Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE))) + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE)), + Result.success(fixture.broadcast), + ) - assertNull(sut.refuseNewSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) + assertNull(sut.resumeHeldSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) sut.signAndBroadcast(request()) advanceUntilIdle() sut.cancel() advanceUntilIdle() - assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.refuseNewSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) + assertEquals( + HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), + sut.resumeHeldSend(WALLET_ID, ADDRESS.uppercase(), AMOUNT_SATS), + ) advanceUntilIdle() - assertEquals(1, toasts.count { it.description == "blocked" }) + verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) + verify(hwWalletRepo, times(1)).signFunding(any(), any()) walletActivities.value = persistentListOf(sentActivity()) advanceUntilIdle() - sut.completeBroadcast() - toastJob.cancel() - assertNull(sut.refuseNewSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) - assertEquals(1, toasts.count { it.description == "blocked" }) + assertNull(sut.resumeHeldSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) + verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) } @Test @@ -995,8 +1291,8 @@ class HwSendViewModelTest : BaseUnitTest() { sut.cancel() advanceUntilIdle() - assertNull(sut.refuseNewSend(WALLET_ID, ADDRESS, other.amountSats)) - assertNull(sut.refuseNewSend(OTHER_WALLET_ID, ADDRESS, AMOUNT_SATS)) + assertNull(sut.resumeHeldSend(WALLET_ID, ADDRESS, other.amountSats)) + assertNull(sut.resumeHeldSend(OTHER_WALLET_ID, ADDRESS, AMOUNT_SATS)) sut.signAndBroadcast(other) advanceUntilIdle() @@ -1019,7 +1315,7 @@ class HwSendViewModelTest : BaseUnitTest() { assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) assertNull(sut.uiState.value.unresolvedSend) - assertNull(sut.refuseNewSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) + assertNull(sut.resumeHeldSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) verify(hwWalletRepo, never()).releaseHeldSend(any()) } @@ -1076,7 +1372,6 @@ class HwSendViewModelTest : BaseUnitTest() { val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } whenever(context.getString(any())).thenReturn("message") whenever(context.getString(R.string.hardware__send_broadcast_failed_text)).thenReturn("try again") - whenever(context.getString(R.string.wallet__send_pending__blocked_new_send)).thenReturn("blocked") val fixture = stubSuccessfulPayment() whenever(hwWalletRepo.disconnectStaleSession(WALLET_ID)).thenReturn(Result.success(Unit)) whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( @@ -1099,8 +1394,8 @@ class HwSendViewModelTest : BaseUnitTest() { toastJob.cancel() verify(hwWalletRepo, times(1)).signFunding(any(), any()) - verify(hwWalletRepo, times(1)).broadcastFunding(any(), anyOrNull()) - assertEquals(1, toasts.count { it.description == "blocked" }) + // The same payment again is the same signed bytes broadcast again + verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.uiState.value.unresolvedSend) assertEquals(held, sut.uiState.value.unresolvedSends) assertTrue(sut.uiState.value.canLeave) @@ -1444,6 +1739,7 @@ class HwSendViewModelTest : BaseUnitTest() { coreService = coreService, activityRepo = activityRepo, paykitPaymentProofRepo = proofRepo, + heldDispatches = heldDispatches, clock = object : Clock { override fun now() = now }, @@ -2109,6 +2405,10 @@ class HwSendViewModelTest : BaseUnitTest() { "Broadcast failed: Made one or multiple attempts, all errored:\n\t- Broken pipe (os error 32)\n" const val NODE_REFUSAL = "Broadcast failed: Electrum server error: " + """"sendrawtransaction RPC error -26: min relay fee not met, 110 < 141"""" + const val SCRIPT_REFUSAL = "Broadcast failed: Electrum server error: " + + """"sendrawtransaction RPC error -26: mandatory-script-verify-flag-failed (Signature must be zero)"""" + const val DUST_REFUSAL = "Broadcast failed: Electrum server error: " + + """"sendrawtransaction RPC error -26: dust"""" const val INPUTS_SPENT = "Broadcast failed: Electrum server error: " + """"sendrawtransaction RPC error -25: bad-txns-inputs-missingorspent"""" const val ADDRESS = "bcrt1qs04g2ka4pr9s3mv73nu32tvfy7r3cxd27wkyu8" diff --git a/app/src/test/java/to/bitkit/utils/SignedTransactionIdTest.kt b/app/src/test/java/to/bitkit/utils/SignedTransactionIdTest.kt index 3d86cccf0a..0ca6559c9b 100644 --- a/app/src/test/java/to/bitkit/utils/SignedTransactionIdTest.kt +++ b/app/src/test/java/to/bitkit/utils/SignedTransactionIdTest.kt @@ -1,6 +1,7 @@ package to.bitkit.utils import org.junit.Test +import to.bitkit.repositories.OnchainSendInput import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -22,6 +23,18 @@ class SignedTransactionIdTest { assertEquals(expected, SignedTransactionId.fromHex(witnessChanged.toHexString())) } + @Test + fun `reads the coins a signed transaction spends with or without witness data`() { + val expected = listOf( + OnchainSendInput("167c8b8b6169007fd94edc121d606c829cbb5d6b51075bb0c664911848a0c5f7", 1u), + ) + assertEquals(expected, SignedTransactionId.inputsFromHex(fixture())) + val withoutWitness = requireNotNull(javaClass.getResourceAsStream("/hardware-signed-transaction-legacy.hex")) + .bufferedReader().readText().trim() + assertEquals(expected, SignedTransactionId.inputsFromHex(withoutWitness)) + assertFailsWith { SignedTransactionId.inputsFromHex(fixture().dropLast(2)) } + } + @Test fun `rejects truncated or trailing transaction data before persistence`() { assertFailsWith { SignedTransactionId.fromHex(fixture().dropLast(2)) } From 171d6226158f9e029595cc93d9a1214cdb7bc92d Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 10:22:56 -0500 Subject: [PATCH 07/14] fix: block hardware sends while their held records are unreadable Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/data/HwHeldSendStore.kt | 193 ++++++++++++++++++ .../main/java/to/bitkit/data/HwWalletStore.kt | 44 ---- .../to/bitkit/repositories/HwWalletRepo.kt | 24 ++- .../screens/wallets/send/HwSendSignScreen.kt | 11 + .../screens/wallets/send/HwSendViewModel.kt | 25 +++ app/src/main/res/values-ar/strings.xml | 3 + app/src/main/res/values-b+es+419/strings.xml | 3 + app/src/main/res/values-ca/strings.xml | 3 + app/src/main/res/values-cs/strings.xml | 3 + app/src/main/res/values-de/strings.xml | 3 + app/src/main/res/values-el/strings.xml | 3 + app/src/main/res/values-es-rES/strings.xml | 3 + app/src/main/res/values-es/strings.xml | 3 + app/src/main/res/values-fr/strings.xml | 3 + app/src/main/res/values-it/strings.xml | 3 + app/src/main/res/values-nl/strings.xml | 3 + app/src/main/res/values-pl/strings.xml | 3 + app/src/main/res/values-pt-rBR/strings.xml | 3 + app/src/main/res/values-pt/strings.xml | 3 + app/src/main/res/values-ru/strings.xml | 3 + app/src/main/res/values/strings.xml | 3 + .../to/bitkit/data/HwHeldSendStoreTest.kt | 104 ++++++++++ .../java/to/bitkit/data/HwWalletStoreTest.kt | 68 ------ .../bitkit/repositories/HwWalletRepoTest.kt | 49 +++-- .../wallets/send/HwSendViewModelTest.kt | 38 ++++ 25 files changed, 470 insertions(+), 134 deletions(-) create mode 100644 app/src/main/java/to/bitkit/data/HwHeldSendStore.kt create mode 100644 app/src/test/java/to/bitkit/data/HwHeldSendStoreTest.kt delete mode 100644 app/src/test/java/to/bitkit/data/HwWalletStoreTest.kt diff --git a/app/src/main/java/to/bitkit/data/HwHeldSendStore.kt b/app/src/main/java/to/bitkit/data/HwHeldSendStore.kt new file mode 100644 index 0000000000..1bc7f30edb --- /dev/null +++ b/app/src/main/java/to/bitkit/data/HwHeldSendStore.kt @@ -0,0 +1,193 @@ +package to.bitkit.data + +import android.content.Context +import androidx.datastore.core.CorruptionException +import androidx.datastore.core.DataStore +import androidx.datastore.core.DataStoreFactory +import androidx.datastore.core.Serializer +import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler +import androidx.datastore.dataStoreFile +import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.decodeFromJsonElement +import kotlinx.serialization.json.encodeToJsonElement +import kotlinx.serialization.json.jsonObject +import to.bitkit.di.IoDispatcher +import to.bitkit.di.json +import to.bitkit.utils.AppError +import java.io.File +import java.io.InputStream +import java.io.OutputStream +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Signed hardware sends whose broadcast may have gone out, in their own file. Unlike the other hardware wallet data, a + * file this cannot read fails every read and write instead of starting over, and a record it cannot read is kept as it + * is and refuses sends from its wallet, so a hold is never dropped silently. Only [clearUnreadable] discards them. + */ +@Singleton +class HwHeldSendStore internal constructor( + produceFile: () -> File, + private val ioDispatcher: CoroutineDispatcher, +) { + @Inject + constructor( + @ApplicationContext context: Context, + @IoDispatcher ioDispatcher: CoroutineDispatcher, + ) : this({ context.dataStoreFile(FILE_NAME) }, ioDispatcher) + + private companion object { + const val FILE_NAME = "hw_held_sends.json" + } + + @Volatile + private var isResetRequested = false + + private val store: DataStore = DataStoreFactory.create( + serializer = HwHeldSendDataSerializer, + corruptionHandler = ReplaceFileCorruptionHandler { if (isResetRequested) HwHeldSendData() else throw it }, + produceFile = produceFile, + ) + + /** Fails with [HwHeldSendsUnreadableError] when the file cannot be read. */ + suspend fun load(): HwHeldSendData = withContext(ioDispatcher) { + readOrFail { store.data.first() } + } + + /** Stores [send], replacing a held send of the same transaction. */ + suspend fun holdSend(send: HeldHwSend) = withContext(ioDispatcher) { + readOrFail { + store.updateData { data -> + data.copy(heldSends = data.heldSends.filterNot { it.txId.equals(send.txId, ignoreCase = true) } + send) + } + } + Unit + } + + suspend fun releaseHeldSends(txIds: Set) = withContext(ioDispatcher) { + if (txIds.isEmpty()) return@withContext + val released = txIds.mapTo(mutableSetOf()) { it.lowercase() } + readOrFail { + store.updateData { data -> + data.copy(heldSends = data.heldSends.filterNot { it.txId.lowercase() in released }) + } + } + Unit + } + + /** + * Discards the records that cannot be read for [walletId] and those whose wallet cannot be read, or the whole file + * when it cannot be read at all. Whatever they held may then be signed again. + */ + suspend fun clearUnreadable(walletId: String) = withContext(ioDispatcher) { + isResetRequested = true + try { + store.updateData { data -> + data.copy(unreadable = data.unreadable.filterNot { it.mayBelongTo(walletId) }) + } + } finally { + isResetRequested = false + } + Unit + } + + suspend fun reset() = withContext(ioDispatcher) { + isResetRequested = true + try { + store.updateData { HwHeldSendData() } + } finally { + isResetRequested = false + } + Unit + } + + private suspend fun readOrFail(block: suspend () -> T): T = try { + block() + } catch (error: CorruptionException) { + throw HwHeldSendsUnreadableError(walletId = null, cause = error) + } +} + +data class HwHeldSendData( + val heldSends: List = emptyList(), + /** Records this version could not read, kept as they are so they keep refusing sends from their wallet. */ + val unreadable: List = emptyList(), +) { + /** Whether a record this cannot read may belong to [walletId], including one whose wallet cannot be read. */ + fun hasUnreadableFor(walletId: String): Boolean = unreadable.any { it.mayBelongTo(walletId) } +} + +/** + * A signed hardware send whose broadcast may have reached the network, so the same payment is never signed again + * beside it: it is only broadcast again as these bytes. Fields added later need defaults, so older records still read. + */ +@Serializable +data class HeldHwSend( + val walletId: String, + val txId: String, + val address: String, + val amountSats: ULong, + val satsPerVByte: ULong, + val tags: List = emptyList(), + val serializedTx: String, + val miningFeeSats: ULong, + val feeRate: ULong, + val totalSpent: ULong, +) { + fun isPaymentOf(walletId: String, address: String, amountSats: ULong): Boolean = + this.walletId == walletId && this.address.equals(address, ignoreCase = true) && this.amountSats == amountSats +} + +private fun JsonElement.mayBelongTo(walletId: String): Boolean { + val recordWalletId = ((this as? JsonObject)?.get("walletId") as? JsonPrimitive) + ?.takeIf { it.isString } + ?.contentOrNull + return recordWalletId == null || recordWalletId == walletId +} + +internal object HwHeldSendDataSerializer : Serializer { + private const val VERSION = 1 + + override val defaultValue = HwHeldSendData() + + override suspend fun readFrom(input: InputStream): HwHeldSendData = try { + val root = json.parseToJsonElement(input.readBytes().decodeToString()).jsonObject + val records = root["heldSends"] as? JsonArray ?: throw SerializationException("No held sends") + val (readable, unreadable) = records.map { record -> + record to runCatching { json.decodeFromJsonElement(record) }.getOrNull() + }.partition { it.second != null } + HwHeldSendData( + heldSends = readable.mapNotNull { it.second }, + unreadable = unreadable.map { it.first } + (root["unreadable"] as? JsonArray).orEmpty(), + ) + } catch (error: SerializationException) { + throw CorruptionException("Failed to read held hardware sends", error) + } catch (error: IllegalArgumentException) { + throw CorruptionException("Failed to read held hardware sends", error) + } + + override suspend fun writeTo(t: HwHeldSendData, output: OutputStream) { + val root = JsonObject( + mapOf( + "version" to JsonPrimitive(VERSION), + "heldSends" to JsonArray(t.heldSends.map { json.encodeToJsonElement(it) }), + "unreadable" to JsonArray(t.unreadable), + ) + ) + output.write(json.encodeToString(JsonElement.serializer(), root).encodeToByteArray()) + } +} + +/** The held hardware sends could not be read, so no hardware send is signed: [walletId]'s, or any when null. */ +class HwHeldSendsUnreadableError(val walletId: String?, cause: Throwable? = null) : + AppError("Held hardware sends could not be read", cause) diff --git a/app/src/main/java/to/bitkit/data/HwWalletStore.kt b/app/src/main/java/to/bitkit/data/HwWalletStore.kt index dd8f6a2d1b..5b67d2aea4 100644 --- a/app/src/main/java/to/bitkit/data/HwWalletStore.kt +++ b/app/src/main/java/to/bitkit/data/HwWalletStore.kt @@ -74,27 +74,6 @@ class HwWalletStore @Inject constructor( Unit } - suspend fun loadHeldSends(): List = withContext(ioDispatcher) { - store.data.first().heldSends - } - - /** Stores [send], replacing a held send of the same transaction. */ - suspend fun holdSend(send: HeldHwSend) = withContext(ioDispatcher) { - store.updateData { data -> - data.copy(heldSends = data.heldSends.filterNot { it.txId.equals(send.txId, ignoreCase = true) } + send) - } - Unit - } - - suspend fun releaseHeldSends(txIds: Set) = withContext(ioDispatcher) { - if (txIds.isEmpty()) return@withContext - store.updateData { data -> - val released = txIds.mapTo(mutableSetOf()) { it.lowercase() } - data.copy(heldSends = data.heldSends.filterNot { it.txId.lowercase() in released }) - } - Unit - } - suspend fun backupSnapshot(): Map = withContext(ioDispatcher) { store.data.first().hwWalletNames() } @@ -138,31 +117,8 @@ data class HwWalletData( * the device's own `customLabel`. */ val pendingNames: Map = emptyMap(), - /** Hardware sends whose broadcast may have gone out, kept until the wallet sees them. */ - val heldSends: List = emptyList(), ) -/** - * A signed hardware send whose broadcast may have reached the network, so the same payment is never signed again - * beside it: it is only broadcast again as these bytes. - */ -@Serializable -data class HeldHwSend( - val walletId: String, - val txId: String, - val address: String, - val amountSats: ULong, - val satsPerVByte: ULong, - val tags: List = emptyList(), - val serializedTx: String, - val miningFeeSats: ULong, - val feeRate: ULong, - val totalSpent: ULong, -) { - fun isPaymentOf(walletId: String, address: String, amountSats: ULong): Boolean = - this.walletId == walletId && this.address.equals(address, ignoreCase = true) && this.amountSats == amountSats -} - /** * Every hardware wallet name this wallet knows, keyed by wallet id: the name of each paired wallet, * overlaid on the pending ones. A paired name wins because it is what the user currently sees. diff --git a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt index 4c2e5a3e3b..120433a5c0 100644 --- a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt @@ -36,6 +36,8 @@ import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import to.bitkit.async.appScope import to.bitkit.data.HeldHwSend +import to.bitkit.data.HwHeldSendStore +import to.bitkit.data.HwHeldSendsUnreadableError import to.bitkit.data.HwWalletStore import to.bitkit.data.PendingNameUpdate import to.bitkit.data.SettingsStore @@ -97,6 +99,7 @@ class HwWalletRepo @Inject constructor( private val activityRepo: ActivityRepo, private val preActivityMetadataRepo: PreActivityMetadataRepo, private val hwWalletStore: HwWalletStore, + private val hwHeldSendStore: HwHeldSendStore, private val settingsStore: SettingsStore, @IoDispatcher private val ioDispatcher: CoroutineDispatcher, ) { @@ -908,21 +911,34 @@ class HwWalletRepo @Inject constructor( * again beside it until the wallet sees it. */ suspend fun holdSend(send: HeldHwSend): Result = withContext(ioDispatcher) { - runSuspendCatching { hwWalletStore.holdSend(send) } + runSuspendCatching { hwHeldSendStore.holdSend(send) } } suspend fun releaseHeldSend(txId: String): Result = withContext(ioDispatcher) { - runSuspendCatching { hwWalletStore.releaseHeldSends(setOf(txId)) } + runSuspendCatching { hwHeldSendStore.releaseHeldSends(setOf(txId)) } } - /** The held send of this payment, which is never signed again until it is recorded as sent or released. */ + /** + * The held send of this payment, which is never signed again until it is recorded as sent or released. Fails with + * [HwHeldSendsUnreadableError] when an earlier send of [walletId] may be among records that cannot be read. + */ suspend fun heldSendFor(walletId: String, address: String, amountSats: ULong): Result = withContext(ioDispatcher) { runSuspendCatching { - hwWalletStore.loadHeldSends().firstOrNull { it.isPaymentOf(walletId, address, amountSats) } + val data = hwHeldSendStore.load() + if (data.hasUnreadableFor(walletId)) throw HwHeldSendsUnreadableError(walletId) + data.heldSends.firstOrNull { it.isPaymentOf(walletId, address, amountSats) } } } + /** + * Discards the held send records of [walletId] that cannot be read, so its sends are signed again. Only an explicit + * choice of the user calls this, as a payment those records held may then be sent twice. + */ + suspend fun clearUnreadableHeldSends(walletId: String): Result = withContext(ioDispatcher) { + runSuspendCatching { hwHeldSendStore.clearUnreadable(walletId) } + } + /** * Whether a fresh read of [walletId]'s history shows another transaction, [FINAL_SPEND_CONFIRMATIONS] deep, * spending one of the coins of the signed [serializedTx], which proves it can never confirm. False while the diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt index a3f69b533e..07ce7b5ed9 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt @@ -32,6 +32,7 @@ import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.components.illustrationRes import to.bitkit.ui.components.sendOpenConnectRes +import to.bitkit.ui.scaffold.AppAlertDialog import to.bitkit.ui.scaffold.SheetTopBar import to.bitkit.ui.screens.transfer.hardware.HwPassphrasePromptSheet import to.bitkit.ui.shared.modifiers.sheetHeight @@ -110,6 +111,16 @@ fun HwSendSignScreen( onOpenConnect = signAndBroadcast, ) + if (uiState.unreadableHeldSendsWalletId != null) { + AppAlertDialog( + title = stringResource(R.string.hardware__held_sends_unreadable_title), + text = stringResource(R.string.hardware__held_sends_unreadable_text), + confirmText = stringResource(R.string.hardware__held_sends_clear), + onConfirm = viewModel::clearUnreadableHeldSends, + onDismiss = viewModel::dismissUnreadableHeldSends, + ) + } + if (uiState.isPassphraseRequired) { HwPassphrasePromptSheet( isVerifying = uiState.isVerifyingPassphrase, diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index 025171ca83..d2e86d4112 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -34,6 +34,7 @@ import kotlinx.coroutines.withTimeout import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.R import to.bitkit.data.HeldHwSend +import to.bitkit.data.HwHeldSendsUnreadableError import to.bitkit.ext.isBroadcastConnectivityFailure import to.bitkit.ext.isHardwareBroadcastInputsSpent import to.bitkit.ext.isHardwareBroadcastNeverConfirmable @@ -709,6 +710,23 @@ class HwSendViewModel @Inject constructor( } } + /** + * Discards the unreadable held send records of the wallet the sheet was refused for, on the user's explicit choice + * after being told a payment they held may then be sent twice. + */ + fun clearUnreadableHeldSends() { + val walletId = _uiState.value.unreadableHeldSendsWalletId ?: return + _uiState.update { it.copy(unreadableHeldSendsWalletId = null) } + viewModelScope.launch { + hwWalletRepo.clearUnreadableHeldSends(walletId).onFailure { + Logger.error("Failed to clear unreadable held sends of '$walletId'", it, context = TAG) + _uiState.update { state -> state.copy(unreadableHeldSendsWalletId = walletId) } + } + } + } + + fun dismissUnreadableHeldSends() = _uiState.update { it.copy(unreadableHeldSendsWalletId = null) } + fun dismissPassphrase() { passphraseJob?.cancel() passphraseJob = null @@ -888,6 +906,11 @@ class HwSendViewModel @Inject constructor( it.copy(isBroadcastUnresolved = retainedShopPayment && pendingBroadcast?.blocksNavigation == true) } when { + generateSequence(error) { it.cause }.any { it is HwHeldSendsUnreadableError } -> { + // Nothing is signed until the user decides, knowing what it risks, to clear the unreadable record + Logger.warn("Refused hardware send of '$walletId' with unreadable holds", error, context = TAG) + _uiState.update { it.copy(unreadableHeldSendsWalletId = walletId) } + } error.isHwUserCancellation() -> { Logger.info("Hardware send cancelled on device for '$walletId'", context = TAG) } @@ -954,6 +977,8 @@ data class HwSendUiState( /** Sends whose broadcast may have gone out: each is pending until it is sent, and is never signed again. */ val unresolvedSends: ImmutableList = persistentListOf(), val retryingSendTxIds: ImmutableSet = persistentSetOf(), + /** The wallet whose sends are refused because an earlier held send of it cannot be read. */ + val unreadableHeldSendsWalletId: String? = null, ) { /** * Whether the sign sheet may be dismissed. Connecting or unlocking can be abandoned, and leaving diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 9b05e3f391..bd16d645f7 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1149,6 +1149,9 @@ تم العثور على <accent>Jade</accent> هل تريد إقران جهاز %1$s هذا مع Bitkit بشكل آمن؟ تم العثور على جهاز + مسح السجل + تعذّر على Bitkit قراءة دفعة سابقة من محفظة الأجهزة هذه، لذلك لن يوقّع دفعة جديدة. يتيح مسح هذا السجل لـ Bitkit التوقيع مرة أخرى. لا تمسحه إلا إذا لم تكن أي دفعة سابقة من هذه المحفظة لا تزال معلقة، وإلا فقد تُرسَل الدفعة نفسها مرتين. + تعذّرت قراءة دفعة سابقة أضف <accent>محفظة الأجهزة</accent> الخاصة بك اربط جهازك لمراقبة أموالك طويلة الأجل أو إدارتها. محفظة الأجهزة diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index d6cc066b23..1de7c78ec9 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1182,6 +1182,9 @@ <accent>Jade</accent> encontrado ¿Desea vincular este %1$s con Bitkit de forma segura? Dispositivo encontrado + Borrar registro + Bitkit no pudo leer un pago anterior de esta billetera de hardware, así que no firmará uno nuevo. Borrar ese registro permite que Bitkit vuelva a firmar. Bórrelo solo si ningún pago anterior de esta billetera sigue pendiente, o el mismo pago podría enviarse dos veces. + No se puede leer un pago anterior Añada su <accent>billetera de hardware</accent> Conecte su dispositivo de hardware para supervisar o administrar sus fondos a largo plazo. Billetera de hardware diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index d0d12966b8..105c2d261d 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1174,6 +1174,9 @@ <accent>Jade</accent> trobat Vols vincular de forma segura aquest %1$s amb Bitkit? Dispositiu trobat + Esborrar el registre + Bitkit no ha pogut llegir un pagament anterior d\'aquesta cartera de maquinari, així que no en signarà cap de nou. Esborrar aquest registre permet que Bitkit torni a signar. Esborra\'l només si cap pagament anterior d\'aquesta cartera continua pendent, o el mateix pagament es podria enviar dues vegades. + No es pot llegir un pagament anterior Afegeix la teva <accent>cartera de maquinari</accent> Connecta el teu dispositiu de maquinari per supervisar o gestionar els teus fons a llarg termini. Cartera de maquinari diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index b76cbdd23b..499c668581 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1180,6 +1180,9 @@ Nalezen <accent>Jade</accent> Chcete bezpečně spárovat toto zařízení %1$s s Bitkitem? Nalezené zařízení + Smazat záznam + Bitkit nemohl přečíst dřívější platbu z této hardwarové peněženky, proto novou nepodepíše. Smazání tohoto záznamu umožní Bitkitu znovu podepisovat. Smažte jej pouze tehdy, pokud žádná dřívější platba z této peněženky nečeká, jinak by mohla být stejná platba odeslána dvakrát. + Dřívější platbu nelze přečíst Přidejte svou <accent>hardwarovou peněženku</accent> Připojte své hardwarové zařízení a sledujte nebo spravujte své dlouhodobé prostředky. Hardwarová peněženka diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index daed63b6b0..b07ac94ba2 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1177,6 +1177,9 @@ <accent>Jade</accent> gefunden Möchtest du deinen %1$s sicher mit Bitkit koppeln? Gerät gefunden + Aufzeichnung löschen + Bitkit konnte eine frühere Zahlung von diesem Hardware-Wallet nicht lesen und signiert daher keine neue. Wenn du diese Aufzeichnung löschst, signiert Bitkit wieder. Lösche sie nur, wenn keine frühere Zahlung von diesem Wallet mehr aussteht, sonst könnte dieselbe Zahlung zweimal gesendet werden. + Frühere Zahlung nicht lesbar Füge dein\n<accent>Hardware-\nWallet</accent> hinzu Verbinde dein Hardware-Gerät, um dein langfristiges Guthaben zu beobachten oder zu verwalten. Hardware-Wallet diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index eeea445007..835f0dd626 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1155,6 +1155,9 @@ Βρέθηκε <accent>Jade</accent> Θέλεις να συζεύξεις με ασφάλεια αυτό το %1$s με το Bitkit; Βρέθηκε συσκευή + Διαγραφή εγγραφής + Το Bitkit δεν μπόρεσε να διαβάσει μια προηγούμενη πληρωμή από αυτό το πορτοφόλι υλικού, οπότε δεν θα υπογράψει νέα. Η διαγραφή αυτής της εγγραφής επιτρέπει στο Bitkit να υπογράφει ξανά. Διάγραψέ την μόνο αν καμία προηγούμενη πληρωμή από αυτό το πορτοφόλι δεν εκκρεμεί ακόμη, αλλιώς η ίδια πληρωμή μπορεί να σταλεί δύο φορές. + Δεν είναι δυνατή η ανάγνωση προηγούμενης πληρωμής Πρόσθεσε το <accent>πορτοφόλι υλικού</accent> σου Σύνδεσε τη συσκευή υλικού σου για να παρακολουθείς ή να διαχειρίζεσαι τα μακροπρόθεσμα κεφάλαιά σου. Πορτοφόλι υλικού diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 94fbd304b0..f02aa67a28 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1172,6 +1172,9 @@ <accent>Jade</accent> encontrado ¿Quieres vincular de forma segura este %1$s con Bitkit? Dispositivo encontrado + Borrar registro + Bitkit no pudo leer un pago anterior de este monedero de hardware, así que no firmará uno nuevo. Borrar ese registro permite que Bitkit vuelva a firmar. Bórralo solo si ningún pago anterior de este monedero sigue pendiente, o el mismo pago podría enviarse dos veces. + No se puede leer un pago anterior Añade tu <accent>monedero de hardware</accent> Conecta tu dispositivo de hardware para supervisar o gestionar tus fondos a largo plazo. Monedero de hardware diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 99205096c5..a837fbad32 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1170,6 +1170,9 @@ <accent>Jade</accent> encontrado ¿Desea vincular de forma segura este %1$s con Bitkit? Dispositivo encontrado + Borrar registro + Bitkit no pudo leer un pago anterior de este monedero de hardware, así que no firmará uno nuevo. Borrar ese registro permite que Bitkit vuelva a firmar. Bórrelo solo si ningún pago anterior de este monedero sigue pendiente, o el mismo pago podría enviarse dos veces. + No se puede leer un pago anterior Añada su <accent>monedero de hardware</accent> Conecte su dispositivo de hardware para supervisar o gestionar sus fondos a largo plazo. Monedero de hardware diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 1a45bc7530..f324983126 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1176,6 +1176,9 @@ <accent>Jade</accent> trouvé Voulez-vous associer ce %1$s à Bitkit en toute sécurité ? Appareil trouvé + Effacer l\'enregistrement + Bitkit n\'a pas pu lire un paiement précédent de ce portefeuille matériel et n\'en signera donc pas de nouveau. Effacer cet enregistrement permet à Bitkit de signer à nouveau. Ne l\'effacez que si aucun paiement précédent de ce portefeuille n\'est encore en attente, sinon le même paiement pourrait être envoyé deux fois. + Paiement précédent illisible Ajoutez votre <accent>portefeuille</accent> Connectez votre appareil matériel pour suivre ou gérer vos fonds à long terme. Portefeuille matériel diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 0ff21f01b1..a9f9ba7656 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1176,6 +1176,9 @@ Trovato <accent>Jade</accent> Vuoi associare in modo sicuro questo %1$s a Bitkit? Dispositivo Trovato + Cancella registro + Bitkit non è riuscito a leggere un pagamento precedente da questo hardware wallet, quindi non ne firmerà uno nuovo. Cancellare quel registro consente a Bitkit di firmare di nuovo. Cancellalo solo se nessun pagamento precedente da questo wallet è ancora in sospeso, altrimenti lo stesso pagamento potrebbe essere inviato due volte. + Pagamento precedente illeggibile Aggiungi il tuo <accent>hardware wallet</accent> Connetti il tuo dispositivo hardware per monitorare o gestire i tuoi fondi a lungo termine. Hardware Wallet diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index ba51f32964..6d052b062c 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1173,6 +1173,9 @@ <accent>Jade</accent> gevonden Wilt u deze %1$s veilig koppelen met Bitkit? Apparaat gevonden + Gegevens wissen + Bitkit kon een eerdere betaling van deze hardwarewallet niet lezen en ondertekent daarom geen nieuwe. Door dat gegeven te wissen kan Bitkit weer ondertekenen. Wis het alleen als geen eerdere betaling van deze wallet nog in behandeling is, anders kan dezelfde betaling twee keer worden verzonden. + Eerdere betaling onleesbaar Voeg uw <accent>hardware wallet</accent> toe Verbind uw hardwareapparaat om uw geld voor de lange termijn te volgen of te beheren. Hardwarewallet diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 6d32b520a8..1864938e6a 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1179,6 +1179,9 @@ Znaleziono <accent>Jade</accent> Czy chcesz bezpiecznie sparować to urządzenie %1$s z Bitkit? Znaleziono urządzenie + Wyczyść zapis + Bitkit nie mógł odczytać wcześniejszej płatności z tego portfela sprzętowego, więc nie podpisze nowej. Wyczyszczenie tego zapisu pozwoli Bitkit znowu podpisywać. Wyczyść go tylko wtedy, gdy żadna wcześniejsza płatność z tego portfela nie oczekuje, w przeciwnym razie ta sama płatność może zostać wysłana dwa razy. + Nie można odczytać wcześniejszej płatności Dodaj swój <accent>portfel sprzętowy</accent> Połącz urządzenie sprzętowe, aby obserwować lub zarządzać swoimi długoterminowymi środkami. Portfel sprzętowy diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index bc2ec91331..db0a2aaf9b 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1181,6 +1181,9 @@ <accent>Jade</accent> encontrado Deseja parear este %1$s com a Bitkit de forma segura? Dispositivo Encontrado + Limpar registro + A Bitkit não conseguiu ler um pagamento anterior desta carteira de hardware, então não vai assinar um novo. Limpar esse registro permite que a Bitkit assine novamente. Só limpe se nenhum pagamento anterior desta carteira ainda estiver pendente, ou o mesmo pagamento poderá ser enviado duas vezes. + Não é possível ler um pagamento anterior Adicione sua <accent>carteira de hardware</accent> Conecte seu dispositivo de hardware para acompanhar ou gerenciar seus fundos de longo prazo. Carteira de Hardware diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index df063860a8..1a1c20aeb1 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1147,6 +1147,9 @@ <accent>Jade</accent> encontrado Pretende emparelhar este %1$s de forma segura com a Bitkit? Dispositivo encontrado + Limpar registo + A Bitkit não conseguiu ler um pagamento anterior desta carteira de hardware, por isso não vai assinar um novo. Limpar esse registo permite que a Bitkit volte a assinar. Só o limpe se nenhum pagamento anterior desta carteira ainda estiver pendente, ou o mesmo pagamento poderá ser enviado duas vezes. + Não é possível ler um pagamento anterior Adicione a sua <accent>carteira de hardware</accent> Ligue o seu dispositivo de hardware para acompanhar ou gerir os seus fundos a longo prazo. Carteira de hardware diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 1e4f0da226..5aa55e588a 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1197,6 +1197,9 @@ Найден <accent>Jade</accent> Хотите безопасно сопрячь этот %1$s с Bitkit? Устройство Найдено + Очистить запись + Bitkit не удалось прочитать предыдущий платёж с этого аппаратного кошелька, поэтому новый он подписывать не будет. Очистка этой записи позволит Bitkit снова подписывать. Очищайте её, только если ни один предыдущий платёж с этого кошелька не ожидает подтверждения, иначе один и тот же платёж может быть отправлен дважды. + Не удаётся прочитать предыдущий платёж Добавьте <accent>кошелёк</accent> Подключите аппаратное устройство, чтобы отслеживать или управлять долгосрочными средствами. Аппаратный Кошелёк diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 80fbd374c8..8efe4b5445 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -188,6 +188,9 @@ Found <accent>Jade</accent> Would you like to securely pair this %1$s with Bitkit? Found Device + Clear record + Bitkit could not read an earlier payment from this hardware wallet, so it will not sign a new one. Clearing that record lets Bitkit sign again. Only clear it if no earlier payment from this wallet is still pending, or the same payment could be sent twice. + Earlier payment unreadable Add your <accent>hardware wallet</accent> Connect your hardware device to watch or manage your long-term funds. Hardware Wallet diff --git a/app/src/test/java/to/bitkit/data/HwHeldSendStoreTest.kt b/app/src/test/java/to/bitkit/data/HwHeldSendStoreTest.kt new file mode 100644 index 0000000000..631bf2f9ba --- /dev/null +++ b/app/src/test/java/to/bitkit/data/HwHeldSendStoreTest.kt @@ -0,0 +1,104 @@ +package to.bitkit.data + +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import to.bitkit.di.json +import to.bitkit.test.BaseUnitTest +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class HwHeldSendStoreTest : BaseUnitTest() { + @get:Rule + val folder = TemporaryFolder() + + private val held = HeldHwSend( + walletId = "wallet-trezor", + txId = "AB", + address = "address", + amountSats = 25_000uL, + satsPerVByte = 2uL, + serializedTx = "00", + miningFeeSats = 200uL, + feeRate = 2uL, + totalSpent = 25_200uL, + ) + + @Test + fun `a held send is replaced by its transaction and released by it`() = test { + val sut = store() + + sut.holdSend(held) + sut.holdSend(held.copy(tags = listOf("rent"))) + assertEquals(listOf(held.copy(tags = listOf("rent"))), sut.load().heldSends) + + sut.releaseHeldSends(setOf("ab")) + assertTrue(sut.load().heldSends.isEmpty()) + } + + @Test + fun `a file that cannot be read fails every read and write until it is cleared`() = test { + val file = folder.newFile("held.json").apply { writeText("{not json") } + val sut = store(file) + + assertNull(assertFailsWith { sut.load() }.walletId) + assertFailsWith { sut.holdSend(held) } + assertFailsWith { sut.releaseHeldSends(setOf("ab")) } + assertEquals("{not json", file.readText()) + + sut.clearUnreadable("wallet-trezor") + + assertEquals(HwHeldSendData(), sut.load()) + } + + @Test + fun `an unreadable record is kept through writes and refuses only its wallet until cleared`() = test { + val file = folder.newFile("held.json") + val readable = json.encodeToString(HeldHwSend.serializer(), held).dropLast(1) + ""","futureField":1}""" + file.writeText( + """{"version":1,"heldSends":[$readable,{"walletId":"wallet-jade","txId":7}]}""", + ) + val sut = store(file) + + val data = sut.load() + assertEquals(listOf(held), data.heldSends) + assertTrue(data.hasUnreadableFor("wallet-jade")) + assertFalse(data.hasUnreadableFor("wallet-trezor")) + + sut.holdSend(held.copy(txId = "CD")) + val written = json.parseToJsonElement(file.readText()).jsonObject + assertEquals(1, written.getValue("unreadable").jsonArray.size) + assertTrue(store(file, reopen = true).load().hasUnreadableFor("wallet-jade")) + + sut.clearUnreadable("wallet-jade") + assertFalse(sut.load().hasUnreadableFor("wallet-jade")) + assertEquals(2, sut.load().heldSends.size) + } + + @Test + fun `a record whose wallet cannot be read refuses every wallet`() { + val data = HwHeldSendData(unreadable = listOf(JsonObject(mapOf("txId" to JsonPrimitive("AB"))))) + + assertTrue(data.hasUnreadableFor("wallet-trezor")) + assertTrue(data.hasUnreadableFor("wallet-jade")) + } + + private var files = 0 + + private fun store( + file: File = folder.root.resolve("held-${files++}.json"), + reopen: Boolean = false, + ): HwHeldSendStore { + // DataStore allows one instance per file, so a reopened store reads a copy of what was written + val source = if (reopen) file.copyTo(folder.root.resolve("reopened-${files++}.json")) else file + return HwHeldSendStore({ source }, testDispatcher) + } +} diff --git a/app/src/test/java/to/bitkit/data/HwWalletStoreTest.kt b/app/src/test/java/to/bitkit/data/HwWalletStoreTest.kt deleted file mode 100644 index 9373b111c3..0000000000 --- a/app/src/test/java/to/bitkit/data/HwWalletStoreTest.kt +++ /dev/null @@ -1,68 +0,0 @@ -package to.bitkit.data - -import android.app.Application -import android.content.Context -import androidx.test.core.app.ApplicationProvider -import kotlinx.coroutines.runBlocking -import org.junit.After -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.annotation.Config -import to.bitkit.models.HwWalletVendor -import to.bitkit.models.KnownDevice -import to.bitkit.models.TransportType -import to.bitkit.test.BaseUnitTest -import kotlin.test.assertEquals - -@Config(application = Application::class, sdk = [34]) -@RunWith(RobolectricTestRunner::class) -class HwWalletStoreTest : BaseUnitTest() { - private val context = ApplicationProvider.getApplicationContext() - private val sut = HwWalletStore(context, testDispatcher) - - private val trezor = KnownDevice( - id = "trezor", - name = "trezor", - path = "trezor", - transportType = TransportType.USB, - label = null, - model = null, - lastConnectedAt = 1L, - xpubs = mapOf("nativeSegwit" to "xpub-trezor"), - walletId = "wallet-trezor", - vendor = HwWalletVendor.TREZOR, - ) - - @Before - fun setUp() = runBlocking { sut.reset() } - - @After - fun tearDown() = runBlocking { sut.reset() } - - @Test - fun `a held send is kept apart from the devices until its transaction is released`() = test { - val held = HeldHwSend( - walletId = "wallet-trezor", - txId = "AB", - address = "address", - amountSats = 25_000uL, - satsPerVByte = 2uL, - serializedTx = "00", - miningFeeSats = 200uL, - feeRate = 2uL, - totalSpent = 25_200uL, - ) - sut.holdSend(held) - sut.holdSend(held.copy(tags = listOf("rent"))) - sut.saveKnownDevices(listOf(trezor)) - - assertEquals(listOf(held.copy(tags = listOf("rent"))), sut.loadHeldSends()) - - sut.releaseHeldSends(setOf("ab")) - - assertEquals(emptyList(), sut.loadHeldSends()) - assertEquals(listOf(trezor), sut.loadKnownDevices()) - } -} diff --git a/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt index c0e0906832..13bb12b08b 100644 --- a/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt @@ -32,6 +32,9 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put import org.junit.Before import org.junit.Test import org.mockito.kotlin.any @@ -45,6 +48,9 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.data.HeldHwSend +import to.bitkit.data.HwHeldSendData +import to.bitkit.data.HwHeldSendStore +import to.bitkit.data.HwHeldSendsUnreadableError import to.bitkit.data.HwWalletData import to.bitkit.data.HwWalletStore import to.bitkit.data.PendingNameUpdate @@ -94,6 +100,7 @@ class HwWalletRepoTest : BaseUnitTest() { private val activityRepo = mock() private val preActivityMetadataRepo = mock() private val hwWalletStore = mock() + private val hwHeldSendStore = mock() private val settingsStore = mock() private lateinit var storeData: MutableStateFlow @@ -308,6 +315,7 @@ class HwWalletRepoTest : BaseUnitTest() { activityRepo = activityRepo, preActivityMetadataRepo = preActivityMetadataRepo, hwWalletStore = hwWalletStore, + hwHeldSendStore = hwHeldSendStore, settingsStore = settingsStore, ioDispatcher = testDispatcher, ) @@ -353,7 +361,7 @@ class HwWalletRepoTest : BaseUnitTest() { } @Test - fun `a held send stays held for its payment even once the wallet sees it`() = test { + fun `a held send is found for its own payment only`() = test { val held = HeldHwSend( walletId = HARDWARE_WALLET_ID, txId = "T1", @@ -365,31 +373,36 @@ class HwWalletRepoTest : BaseUnitTest() { feeRate = 2uL, totalSpent = 25_200uL, ) - storeData.value = storeData.value.copy(heldSends = listOf(held)) - whenever(hwWalletStore.loadHeldSends()).thenAnswer { storeData.value.heldSends } + whenever(hwHeldSendStore.load()).thenReturn(HwHeldSendData(heldSends = listOf(held))) val sut = createRepo() assertEquals(held, sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS, 25_000uL).getOrThrow()) assertEquals(held, sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS.uppercase(), 25_000uL).getOrThrow()) assertNull(sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS, 25_001uL).getOrThrow()) assertNull(sut.heldSendFor("other-wallet", HELD_ADDRESS, 25_000uL).getOrThrow()) + verify(hwHeldSendStore, never()).releaseHeldSends(any()) + } - watcherEvents.emit( - "hardware-wallet|nativeSegwit" to WatcherEvent.TransactionsChanged( - balance = walletBalance(total = 0uL), - activities = listOf(watcherActivity(amount = 25_000uL, txid = "t1", txType = PaymentType.SENT)), - transactionDetails = emptyList(), - txCount = 1u, - blockHeight = 850_000u, - accountType = AccountType.NATIVE_SEGWIT, - nextUnusedExternalAddress = WATCHER_RECEIVE_ADDRESS, - ) - ) + @Test + fun `an unreadable held send refuses sends of its wallet, and of every wallet when its wallet is unreadable`() = + test { + val unreadable = buildJsonObject { + put("walletId", HARDWARE_WALLET_ID) + put("txId", 7) + } + whenever(hwHeldSendStore.load()).thenReturn(HwHeldSendData(unreadable = listOf(unreadable))) + val sut = createRepo() - // The send screen records a seen send before it is released, so it is never signed again unrecorded - assertEquals(held, sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS, 25_000uL).getOrThrow()) - verify(hwWalletStore, never()).releaseHeldSends(any()) - } + val refused = sut.heldSendFor(HARDWARE_WALLET_ID, HELD_ADDRESS, 25_000uL).exceptionOrNull() + assertEquals(HARDWARE_WALLET_ID, (refused as HwHeldSendsUnreadableError).walletId) + assertNull(sut.heldSendFor("other-wallet", HELD_ADDRESS, 25_000uL).getOrThrow()) + + whenever(hwHeldSendStore.load()).thenReturn(HwHeldSendData(unreadable = listOf(JsonPrimitive("?")))) + assertTrue(sut.heldSendFor("other-wallet", HELD_ADDRESS, 25_000uL).isFailure) + + whenever(hwHeldSendStore.load()).doSuspendableAnswer { throw HwHeldSendsUnreadableError(walletId = null) } + assertTrue(sut.heldSendFor("other-wallet", HELD_ADDRESS, 25_000uL).isFailure) + } @Test fun `a held send is proven unconfirmable only by a final spend of its coin by another transaction`() = test { diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt index 43b03e310d..c31392c313 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt @@ -35,6 +35,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.R import to.bitkit.data.HeldHwSend +import to.bitkit.data.HwHeldSendsUnreadableError import to.bitkit.ext.create import to.bitkit.models.HwConnectedDevice import to.bitkit.models.HwFundingBroadcastResult @@ -1028,6 +1029,43 @@ class HwSendViewModelTest : BaseUnitTest() { assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) } + @Test + fun `a send whose held records cannot be read is never signed and offers an explicit clear`() = test { + stubSuccessfulPayment() + whenever(hwWalletRepo.heldSendFor(WALLET_ID, ADDRESS, AMOUNT_SATS)) + .thenReturn(Result.failure(HwHeldSendsUnreadableError(WALLET_ID))) + whenever(hwWalletRepo.clearUnreadableHeldSends(WALLET_ID)).thenReturn(Result.success(Unit)) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + verify(hwWalletRepo, never()).signFunding(any(), any()) + verify(hwWalletRepo, never()).broadcastFundingAtBoundary(any(), anyOrNull(), any()) + assertEquals(WALLET_ID, sut.uiState.value.unreadableHeldSendsWalletId) + verify(hwWalletRepo, never()).clearUnreadableHeldSends(any()) + + sut.clearUnreadableHeldSends() + advanceUntilIdle() + + verify(hwWalletRepo).clearUnreadableHeldSends(WALLET_ID) + assertNull(sut.uiState.value.unreadableHeldSendsWalletId) + } + + @Test + fun `a send whose held records fail to load is never signed`() = test { + whenever(context.getString(any())).thenReturn("message") + stubSuccessfulPayment() + whenever(hwWalletRepo.heldSendFor(WALLET_ID, ADDRESS, AMOUNT_SATS)) + .thenReturn(Result.failure(AppError("Disk unreadable"))) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + verify(hwWalletRepo, never()).signFunding(any(), any()) + verify(hwWalletRepo, never()).broadcastFundingAtBoundary(any(), anyOrNull(), any()) + assertFalse(sut.uiState.value.isSigning) + } + @Test fun `a send whose hold cannot be written is never broadcast`() = test { whenever(context.getString(any())).thenReturn("message") From 43be9402619dc97ba64b2219c760dea6d8f1c4bf Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 10:43:09 -0500 Subject: [PATCH 08/14] fix: ask before sending a seen hardware payment again Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/repositories/HwWalletRepo.kt | 25 ++++++ .../screens/wallets/send/HwSendSignScreen.kt | 18 +++++ .../screens/wallets/send/HwSendViewModel.kt | 80 ++++++++++++------- app/src/main/res/values-ar/strings.xml | 5 ++ app/src/main/res/values-b+es+419/strings.xml | 5 ++ app/src/main/res/values-ca/strings.xml | 5 ++ app/src/main/res/values-cs/strings.xml | 5 ++ app/src/main/res/values-de/strings.xml | 5 ++ app/src/main/res/values-el/strings.xml | 5 ++ app/src/main/res/values-es-rES/strings.xml | 5 ++ app/src/main/res/values-es/strings.xml | 5 ++ app/src/main/res/values-fr/strings.xml | 5 ++ app/src/main/res/values-it/strings.xml | 5 ++ app/src/main/res/values-nl/strings.xml | 5 ++ app/src/main/res/values-pl/strings.xml | 5 ++ app/src/main/res/values-pt-rBR/strings.xml | 5 ++ app/src/main/res/values-pt/strings.xml | 5 ++ app/src/main/res/values-ru/strings.xml | 5 ++ app/src/main/res/values/strings.xml | 5 ++ .../bitkit/repositories/HwWalletRepoTest.kt | 43 ++++++++++ .../wallets/send/HwSendViewModelTest.kt | 50 +++++++++++- 21 files changed, 264 insertions(+), 32 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt index 120433a5c0..92c3587180 100644 --- a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt @@ -1193,6 +1193,31 @@ class HwWalletRepo @Inject constructor( init { observeWatcherEvents() syncWatchers() + releaseSeenHeldSends() + } + + private fun releaseSeenHeldSends() { + scope.launch { + activities.collect { activities -> + // A held send its wallet has seen went out, so it is recorded with its tags and released, and a later + // send of the same payment is a new one. A replaced transaction no longer exists and is not seen. + val seen = activities.filterIsInstance() + .filter { it.v1.doesExist } + .associate { (it.v1.walletId to it.v1.txId.lowercase()) to it.v1.id } + if (seen.isEmpty()) return@collect + runSuspendCatching { + val held = hwHeldSendStore.load().heldSends.filter { (it.walletId to it.txId.lowercase()) in seen } + if (held.isEmpty()) return@runSuspendCatching + held.filter { it.tags.isNotEmpty() }.forEach { send -> + val activityId = seen.getValue(send.walletId to send.txId.lowercase()) + activityRepo.addTagsToActivity(activityId, send.tags, send.walletId) + .onFailure { Logger.warn("Failed to tag seen held send '${send.txId}'", it, context = TAG) } + } + hwHeldSendStore.releaseHeldSends(held.mapTo(mutableSetOf()) { it.txId }) + Logger.info("Released '${held.size}' held hardware sends their wallets have seen", context = TAG) + }.onFailure { Logger.warn("Failed to release seen held hardware sends", it, context = TAG) } + } + } } private fun observeWatcherEvents() { diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt index 07ce7b5ed9..b3589d2964 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt @@ -111,6 +111,24 @@ fun HwSendSignScreen( onOpenConnect = signAndBroadcast, ) + uiState.alreadySentSend?.let { alreadySent -> + AppAlertDialog( + title = stringResource(R.string.hardware__send_already_sent_title), + text = if (alreadySent.sentAt.isEmpty()) { + stringResource(R.string.hardware__send_already_sent_text_undated) + } else { + stringResource(R.string.hardware__send_already_sent_text, alreadySent.sentAt) + }, + confirmText = stringResource(R.string.hardware__send_again), + dismissText = stringResource(R.string.hardware__send_view_sent), + onConfirm = { + viewModel.confirmSendAgain() + signAndBroadcast() + }, + onDismiss = viewModel::showAlreadySentSend, + ) + } + if (uiState.unreadableHeldSendsWalletId != null) { AppAlertDialog( title = stringResource(R.string.hardware__held_sends_unreadable_title), diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index d2e86d4112..c6ad81bc13 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -6,6 +6,7 @@ import androidx.compose.runtime.Immutable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.synonym.bitkitcore.Activity +import com.synonym.bitkitcore.OnchainActivity import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.collections.immutable.ImmutableList @@ -35,6 +36,7 @@ import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.R import to.bitkit.data.HeldHwSend import to.bitkit.data.HwHeldSendsUnreadableError +import to.bitkit.ext.formatToString import to.bitkit.ext.isBroadcastConnectivityFailure import to.bitkit.ext.isHardwareBroadcastInputsSpent import to.bitkit.ext.isHardwareBroadcastNeverConfirmable @@ -166,28 +168,9 @@ class HwSendViewModel @Inject constructor( } else { null } - if (held != null && isSeenByWallet(request.walletId, held.txId)) { - // It went out, so it is recorded and shown as sent; only a new send signs it again - Logger.info("Recorded held hardware send '${held.txId}' the wallet has seen", context = TAG) - val heldPayment = held.toPendingBroadcast(request) - val signedTx = heldPayment.signedTx - val result = HwFundingBroadcastResult( - txId = held.txId, - miningFeeSats = signedTx.miningFeeSats, - feeRate = signedTx.feeRate, - totalSpent = signedTx.totalSpent, - ) - runSuspendCatching { persistResult(heldPayment.request, result) } - .onFailure { Logger.error("Failed to persist hardware send result", it, context = TAG) } - releaseHeldSend(held.txId) - pendingResult.update { - HwSendResult( - walletId = request.walletId, - txId = held.txId, - amountSats = request.amountSats, - paymentIdentity = request.paymentIdentity, - ) - } + val seen = held?.let { seenActivityOf(request.walletId, it.txId, hwWalletRepo.activities.value) } + if (held != null && seen != null) { + recordSeenHeldSend(held, request, seen) return@runCatching } if (held != null) { @@ -404,6 +387,41 @@ class HwSendViewModel @Inject constructor( } } + private suspend fun recordSeenHeldSend(held: HeldHwSend, request: HwSendRequest, seen: OnchainActivity) { + // It went out, so it is recorded and released, and the user decides whether to send the same payment again + Logger.info("Recorded held hardware send '${held.txId}' the wallet has seen", context = TAG) + val heldPayment = held.toPendingBroadcast(request) + val signedTx = heldPayment.signedTx + val result = HwFundingBroadcastResult( + txId = held.txId, + miningFeeSats = signedTx.miningFeeSats, + feeRate = signedTx.feeRate, + totalSpent = signedTx.totalSpent, + ) + // A failed save still releases the hold: the wallet has the transaction, so it is never lost + runSuspendCatching { persistResult(heldPayment.request, result) } + .onFailure { Logger.error("Failed to persist seen hardware send '${held.txId}'", it, context = TAG) } + releaseHeldSend(held.txId) + val send = HwSendResult( + walletId = request.walletId, + txId = held.txId, + amountSats = request.amountSats, + paymentIdentity = request.paymentIdentity, + ) + val sentAt = seen.timestamp.takeIf { it > 0uL }.formatToString().orEmpty() + _uiState.update { it.copy(alreadySentSend = AlreadySentHwSend(send, sentAt)) } + } + + /** Shows the payment the user tried to make again as the one already sent. */ + fun showAlreadySentSend() { + val alreadySent = _uiState.value.alreadySentSend ?: return + _uiState.update { it.copy(alreadySentSend = null) } + pendingResult.update { alreadySent.send } + } + + /** Lets the user sign the payment again, as a new one beside the one already sent. */ + fun confirmSendAgain() = _uiState.update { it.copy(alreadySentSend = null) } + private suspend fun markDispatched(payment: PendingHwSendBroadcast, isDispatched: AtomicBoolean) { val request = payment.request request.paymentRequestId?.let { @@ -528,8 +546,12 @@ class HwSendViewModel @Inject constructor( } private fun isSeenByWallet(walletId: String, txId: String): Boolean = - hwWalletRepo.activities.value.filterIsInstance().any { - it.v1.walletId == walletId && it.v1.txId.equals(txId, ignoreCase = true) + seenActivityOf(walletId, txId, hwWalletRepo.activities.value) != null + + private fun seenActivityOf(walletId: String, txId: String, activities: List): OnchainActivity? = + activities.filterIsInstance().map { it.v1 }.firstOrNull { + // A replaced transaction no longer exists, so it does not count as sent + it.walletId == walletId && it.txId.equals(txId, ignoreCase = true) && it.doesExist } private suspend fun toastNotSent(@StringRes description: Int) = ToastEventBus.send( @@ -552,11 +574,7 @@ class HwSendViewModel @Inject constructor( val unresolved = UnresolvedHwSend(payment, send) unresolvedSends.put(txId, unresolved)?.watch?.cancel() unresolved.watch = viewModelScope.launch { - hwWalletRepo.activities.first { activities -> - activities.filterIsInstance().any { - it.v1.walletId == send.walletId && it.v1.txId.equals(send.txId, ignoreCase = true) - } - } + hwWalletRepo.activities.first { seenActivityOf(send.walletId, send.txId, it) != null } completeUnresolvedSend(unresolved) } _uiState.update { @@ -977,6 +995,8 @@ data class HwSendUiState( /** Sends whose broadcast may have gone out: each is pending until it is sent, and is never signed again. */ val unresolvedSends: ImmutableList = persistentListOf(), val retryingSendTxIds: ImmutableSet = persistentSetOf(), + /** A payment the user tried to make again that its wallet has already sent, waiting for their choice. */ + val alreadySentSend: AlreadySentHwSend? = null, /** The wallet whose sends are refused because an earlier held send of it cannot be read. */ val unreadableHeldSendsWalletId: String? = null, ) { @@ -997,6 +1017,8 @@ data class HwSendResult( val paymentIdentity: String? = null, ) +data class AlreadySentHwSend(val send: HwSendResult, val sentAt: String) + sealed interface HeldHwSendEvent { val send: HwSendResult diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index bd16d645f7..7858b7508d 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1191,6 +1191,10 @@ تعذر الاحتفاظ بعلامات هذه المحفظة في نسختك الاحتياطية. حاول مرة أخرى، أو أزلها دون الاحتفاظ بها. تعذرت إعادة تسمية محفظة الأجهزة. يرجى المحاولة مرة أخرى. تعذر البحث عن محافظ الأجهزة. تحقق من اتصالك وحاول مرة أخرى. + إرسال مرة أخرى + تم إرسال هذه الدفعة بالفعل في %1$s. هل تريد إرسالها مرة أخرى؟ + تم إرسال هذه الدفعة بالفعل. هل تريد إرسالها مرة أخرى؟ + تم إرسال الدفعة بالفعل قبلت الشبكة هذه الدفعة. تكتمل بمجرد أن ترى محفظتك المعاملة. تحقق من اتصالك وحاول مرة أخرى. الدفعة غير مؤكدة @@ -1205,6 +1209,7 @@ فتح Trezor Connect التوقيع باستخدام Jade التوقيع بالجهاز + عرض الدفعة التحقق على الجهاز فشل التحقق من العنوان. تحقق من العنوان على جهازك وحاول مرة أخرى. يحتوي هذا الجهاز على محفظة مختلفة عن التي أقرنتها. وصّل المحفظة المقترنة، أو أضف هذه كمحفظة أجهزة جديدة. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 1de7c78ec9..25f19911b5 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1224,6 +1224,10 @@ No se pudieron conservar las etiquetas de esta billetera en su copia de seguridad. Vuelva a intentarlo o quítela sin conservarlas. No se pudo renombrar la billetera de hardware. Inténtelo de nuevo. No se pudieron buscar billeteras de hardware. Revise su conexión y vuelva a intentarlo. + Enviar de nuevo + Este pago ya se envió el %1$s. ¿Desea enviarlo de nuevo? + Este pago ya se envió. ¿Desea enviarlo de nuevo? + Pago ya enviado La red aceptó este pago. Se completará cuando su billetera vea la transacción. Revise su conexión y vuelva a intentarlo. Pago no confirmado @@ -1238,6 +1242,7 @@ Abrir Trezor Connect Firmar con Jade Firmar con el dispositivo + Ver pago Verificar en el dispositivo Falló la verificación de la dirección. Revise la dirección en su dispositivo y vuelva a intentarlo. Este dispositivo contiene una billetera distinta a la que vinculó. Conecte la billetera vinculada o añada esta como una nueva billetera de hardware. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 105c2d261d..0b24594405 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1216,6 +1216,10 @@ No s\'han pogut conservar les etiquetes d\'aquesta cartera a la còpia de seguretat. Torna-ho a provar o elimina-la sense conservar-les. No s\'ha pogut canviar el nom de la cartera de maquinari. Torna-ho a provar. No s\'han pogut cercar carteres de maquinari. Comprova la connexió i torna-ho a provar. + Tornar a enviar + Aquest pagament ja es va enviar el %1$s. El vols tornar a enviar? + Aquest pagament ja es va enviar. El vols tornar a enviar? + Pagament ja enviat La xarxa ha acceptat aquest pagament. Es completarà quan la teva cartera vegi la transacció. Comprova la connexió i torna-ho a provar. Pagament no confirmat @@ -1230,6 +1234,7 @@ Obrir Trezor Connect Signar amb Jade Signar amb el dispositiu + Veure el pagament Verificar al dispositiu Ha fallat la verificació de l\'adreça. Comprova l\'adreça al teu dispositiu i torna-ho a provar. Aquest dispositiu conté una cartera diferent de la que has vinculat. Connecta la cartera vinculada o afegeix aquesta com a nova cartera de maquinari. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 499c668581..8968fda0ad 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1222,6 +1222,10 @@ Tagy této peněženky se nepodařilo ponechat v záloze. Zkuste to znovu, nebo ji odeberte bez jejich ponechání. Hardwarovou peněženku se nepodařilo přejmenovat. Zkuste to prosím znovu. Hardwarové peněženky se nepodařilo vyhledat. Zkontrolujte připojení a zkuste to znovu. + Odeslat znovu + Tato platba již byla odeslána %1$s. Odeslat ji znovu? + Tato platba již byla odeslána. Odeslat ji znovu? + Platba již byla odeslána Síť tuto platbu přijala. Dokončí se, jakmile vaše peněženka transakci uvidí. Zkontrolujte připojení a zkuste to znovu. Platba nebyla potvrzena @@ -1236,6 +1240,7 @@ Otevřít Trezor Connect Podepsat pomocí Jade Podepsat zařízením + Zobrazit platbu Ověřit na zařízení Ověření adresy se nezdařilo. Zkontrolujte adresu na zařízení a zkuste to znovu. Toto zařízení obsahuje jinou peněženku než tu, kterou jste spárovali. Připojte spárovanou peněženku, nebo tuto přidejte jako novou hardwarovou peněženku. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index b07ac94ba2..1ebdecb785 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1219,6 +1219,10 @@ Die Tags dieses Wallets konnten nicht in deinem Backup behalten werden. Versuche es erneut oder entferne es, ohne sie zu behalten. Das Hardware-Wallet konnte nicht umbenannt werden. Bitte versuche es erneut. Die Suche nach Hardware-Wallets ist fehlgeschlagen. Überprüfe deine Verbindung und versuche es erneut. + Erneut senden + Diese Zahlung wurde bereits am %1$s gesendet. Erneut senden? + Diese Zahlung wurde bereits gesendet. Erneut senden? + Zahlung bereits gesendet Das Netzwerk hat diese Zahlung angenommen. Sie wird abgeschlossen, sobald dein Wallet die Transaktion sieht. Überprüfe deine Verbindung und versuche es erneut. Zahlung nicht bestätigt @@ -1233,6 +1237,7 @@ Trezor Connect öffnen Mit Jade signieren Mit Gerät signieren + Zahlung ansehen Am Gerät überprüfen Adressüberprüfung fehlgeschlagen. Überprüfe die Adresse auf deinem Gerät und versuche es erneut. Auf diesem Gerät befindet sich ein anderes Wallet als das gekoppelte. Verbinde das gekoppelte Wallet oder füge dieses als neues Hardware-Wallet hinzu. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 835f0dd626..1ba2f188fe 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1197,6 +1197,10 @@ Δεν ήταν δυνατή η διατήρηση των ετικετών αυτού του πορτοφολιού στο αντίγραφο ασφαλείας. Δοκίμασε ξανά ή αφαίρεσέ το χωρίς να τις διατηρήσεις. Δεν ήταν δυνατή η μετονομασία του πορτοφολιού υλικού. Δοκίμασε ξανά. Δεν ήταν δυνατή η αναζήτηση πορτοφολιών υλικού. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. + Αποστολή ξανά + Αυτή η πληρωμή έχει ήδη σταλεί στις %1$s. Να σταλεί ξανά; + Αυτή η πληρωμή έχει ήδη σταλεί. Να σταλεί ξανά; + Η πληρωμή έχει ήδη σταλεί Το δίκτυο αποδέχτηκε αυτή την πληρωμή. Θα ολοκληρωθεί μόλις το πορτοφόλι σου δει τη συναλλαγή. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. Η πληρωμή δεν επιβεβαιώθηκε @@ -1211,6 +1215,7 @@ Άνοιγμα Trezor Connect Υπογραφή με Jade Υπογραφή με συσκευή + Προβολή πληρωμής Επαλήθευση στη συσκευή Η επαλήθευση της διεύθυνσης απέτυχε. Έλεγξε τη διεύθυνση στη συσκευή σου και δοκίμασε ξανά. Αυτή η συσκευή περιέχει διαφορετικό πορτοφόλι από αυτό που συζεύχθηκε. Σύνδεσε το συζευγμένο πορτοφόλι ή πρόσθεσε αυτό ως νέο πορτοφόλι υλικού. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index f02aa67a28..bbc42cf7ff 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1214,6 +1214,10 @@ No se pudieron conservar las etiquetas de este monedero en tu copia de seguridad. Inténtalo de nuevo o elimínalo sin conservarlas. No se pudo cambiar el nombre del monedero de hardware. Inténtalo de nuevo. No se pudieron buscar monederos de hardware. Comprueba tu conexión e inténtalo de nuevo. + Enviar de nuevo + Este pago ya se envió el %1$s. ¿Quieres enviarlo de nuevo? + Este pago ya se envió. ¿Quieres enviarlo de nuevo? + Pago ya enviado La red aceptó este pago. Se completará cuando tu monedero vea la transacción. Comprueba tu conexión e inténtalo de nuevo. Pago no confirmado @@ -1228,6 +1232,7 @@ Abrir Trezor Connect Firmar con Jade Firmar con el dispositivo + Ver pago Verificar en el dispositivo Error al verificar la dirección. Comprueba la dirección en tu dispositivo e inténtalo de nuevo. Este dispositivo contiene un monedero distinto del que vinculaste. Conecta el monedero vinculado o añade este como un nuevo monedero de hardware. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index a837fbad32..ef7c2805e5 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1212,6 +1212,10 @@ No se pudieron conservar las etiquetas de este monedero en su copia de seguridad. Inténtelo de nuevo o elimínelo sin conservarlas. No se pudo cambiar el nombre del monedero de hardware. Inténtelo de nuevo. No se pudieron buscar monederos de hardware. Compruebe su conexión e inténtelo de nuevo. + Enviar de nuevo + Este pago ya se envió el %1$s. ¿Desea enviarlo de nuevo? + Este pago ya se envió. ¿Desea enviarlo de nuevo? + Pago ya enviado La red aceptó este pago. Se completará cuando su monedero vea la transacción. Compruebe su conexión e inténtelo de nuevo. Pago no confirmado @@ -1226,6 +1230,7 @@ Abrir Trezor Connect Firmar con Jade Firmar con el dispositivo + Ver pago Verificar en el dispositivo Error al verificar la dirección. Compruebe la dirección en su dispositivo e inténtelo de nuevo. Este dispositivo contiene un monedero distinto del que vinculó. Conecte el monedero vinculado o añada este como un nuevo monedero de hardware. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f324983126..da074a096b 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1218,6 +1218,10 @@ Impossible de garder les étiquettes de ce portefeuille dans votre sauvegarde. Réessayez ou retirez-le sans les garder. Impossible de renommer le portefeuille matériel. Veuillez réessayer. Impossible de rechercher des portefeuilles matériels. Vérifiez votre connexion et réessayez. + Envoyer à nouveau + Ce paiement a déjà été envoyé le %1$s. L\'envoyer à nouveau ? + Ce paiement a déjà été envoyé. L\'envoyer à nouveau ? + Paiement déjà envoyé Le réseau a accepté ce paiement. Il sera finalisé dès que votre portefeuille verra la transaction. Vérifiez votre connexion et réessayez. Paiement non confirmé @@ -1232,6 +1236,7 @@ Ouvrir Trezor Connect Signer avec Jade Signer avec l\'appareil + Voir le paiement Vérifier sur l\'appareil Échec de la vérification de l\'adresse. Vérifiez l\'adresse sur votre appareil et réessayez. Cet appareil contient un autre portefeuille que celui que vous avez associé. Connectez le portefeuille associé ou ajoutez celui-ci comme nouveau portefeuille matériel. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index a9f9ba7656..6d1aef3ac6 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1220,6 +1220,10 @@ Impossibile mantenere i tag di questo wallet nel backup. Riprova, oppure rimuovilo senza mantenerli. Impossibile rinominare l\'hardware wallet. Riprova. Impossibile cercare hardware wallet. Controlla la connessione e riprova. + Invia di nuovo + Questo pagamento è già stato inviato il %1$s. Inviarlo di nuovo? + Questo pagamento è già stato inviato. Inviarlo di nuovo? + Pagamento già inviato La rete ha accettato questo pagamento. Si completerà non appena il tuo wallet vedrà la transazione. Controlla la connessione e riprova. Pagamento non confermato @@ -1234,6 +1238,7 @@ Apri Trezor Connect Firma con Jade Firma con il Dispositivo + Vedi pagamento Verifica sul Dispositivo Verifica dell\'indirizzo non riuscita. Controlla l\'indirizzo sul tuo dispositivo e riprova. Questo dispositivo contiene un wallet diverso da quello associato. Connetti il wallet associato o aggiungi questo come nuovo hardware wallet. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 6d052b062c..b9bdfd5b9e 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1215,6 +1215,10 @@ Kon de tags van deze wallet niet in uw backup bewaren. Probeer het opnieuw, of verwijder de wallet zonder ze te bewaren. Kon de naam van de hardwarewallet niet wijzigen. Probeer het opnieuw. Kon niet zoeken naar hardwarewallets. Controleer uw verbinding en probeer het opnieuw. + Opnieuw verzenden + Deze betaling is al verzonden op %1$s. Opnieuw verzenden? + Deze betaling is al verzonden. Opnieuw verzenden? + Betaling al verzonden Het netwerk heeft deze betaling geaccepteerd. Ze wordt voltooid zodra uw wallet de transactie ziet. Controleer uw verbinding en probeer het opnieuw. Betaling niet bevestigd @@ -1229,6 +1233,7 @@ Trezor Connect openen Ondertekenen met Jade Ondertekenen met apparaat + Betaling bekijken Verifiëren op apparaat Adresverificatie mislukt. Controleer het adres op uw apparaat en probeer het opnieuw. Dit apparaat bevat een andere wallet dan de wallet die u hebt gekoppeld. Verbind de gekoppelde wallet, of voeg deze toe als nieuwe hardwarewallet. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 1864938e6a..3731c08563 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1221,6 +1221,10 @@ Nie udało się zachować tagów tego portfela w kopii zapasowej. Spróbuj ponownie lub usuń go bez ich zachowywania. Nie udało się zmienić nazwy portfela sprzętowego. Spróbuj ponownie. Nie udało się wyszukać portfeli sprzętowych. Sprawdź połączenie i spróbuj ponownie. + Wyślij ponownie + Ta płatność została już wysłana %1$s. Wysłać ją ponownie? + Ta płatność została już wysłana. Wysłać ją ponownie? + Płatność została już wysłana Sieć przyjęła tę płatność. Zostanie zakończona, gdy Twój portfel zobaczy transakcję. Sprawdź połączenie i spróbuj ponownie. Płatność niepotwierdzona @@ -1235,6 +1239,7 @@ Otwórz Trezor Connect Podpisz za pomocą Jade Podpisz urządzeniem + Zobacz płatność Zweryfikuj na urządzeniu Weryfikacja adresu nie powiodła się. Sprawdź adres na urządzeniu i spróbuj ponownie. To urządzenie zawiera inny portfel niż sparowany. Połącz sparowany portfel lub dodaj ten jako nowy portfel sprzętowy. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index db0a2aaf9b..d9f474e4c5 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1223,6 +1223,10 @@ Não foi possível manter as tags desta carteira no seu backup. Tente novamente ou remova-a sem mantê-las. Não foi possível renomear a carteira de hardware. Tente novamente. Não foi possível procurar carteiras de hardware. Verifique sua conexão e tente novamente. + Enviar novamente + Este pagamento já foi enviado em %1$s. Enviar novamente? + Este pagamento já foi enviado. Enviar novamente? + Pagamento já enviado A rede aceitou este pagamento. Ele será concluído assim que sua carteira vir a transação. Verifique sua conexão e tente novamente. Pagamento não confirmado @@ -1237,6 +1241,7 @@ Abrir Trezor Connect Assinar com Jade Assinar com Dispositivo + Ver pagamento Verificar no Dispositivo Falha na verificação do endereço. Confira o endereço no seu dispositivo e tente novamente. Este dispositivo contém uma carteira diferente da que você pareou. Conecte a carteira pareada ou adicione esta como uma nova carteira de hardware. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 1a1c20aeb1..4ccb50e10c 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1189,6 +1189,10 @@ Não foi possível manter as etiquetas desta carteira na cópia de segurança. Tente novamente ou remova-a sem as manter. Não foi possível mudar o nome da carteira de hardware. Tente novamente. Não foi possível procurar carteiras de hardware. Verifique a ligação e tente novamente. + Enviar novamente + Este pagamento já foi enviado em %1$s. Enviar novamente? + Este pagamento já foi enviado. Enviar novamente? + Pagamento já enviado A rede aceitou este pagamento. Fica concluído assim que a sua carteira vir a transação. Verifique a ligação e tente novamente. Pagamento não confirmado @@ -1203,6 +1207,7 @@ Abrir Trezor Connect Assinar com o Jade Assinar com o dispositivo + Ver pagamento Verificar no dispositivo Falha na verificação do endereço. Verifique o endereço no seu dispositivo e tente novamente. Este dispositivo contém uma carteira diferente da que emparelhou. Ligue a carteira emparelhada ou adicione esta como nova carteira de hardware. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 5aa55e588a..cee487d86c 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1239,6 +1239,10 @@ Не удалось сохранить теги этого кошелька в резервной копии. Попробуйте снова или удалите его без сохранения тегов. Не удалось переименовать аппаратный кошелёк. Пожалуйста, попробуйте снова. Не удалось найти аппаратные кошельки. Проверьте подключение и попробуйте снова. + Отправить снова + Этот платёж уже был отправлен %1$s. Отправить его снова? + Этот платёж уже был отправлен. Отправить его снова? + Платёж уже отправлен Сеть приняла этот платёж. Он завершится, как только ваш кошелёк увидит транзакцию. Проверьте подключение и попробуйте снова. Платёж не подтверждён @@ -1253,6 +1257,7 @@ Открыть Trezor Connect Подписать на Jade Подписать на Устройстве + Посмотреть платёж Проверить на Устройстве Проверка адреса не удалась. Сверьте адрес на устройстве и попробуйте снова. На этом устройстве другой кошелёк, а не тот, который вы сопрягли. Подключите сопряжённый кошелёк или добавьте этот как новый аппаратный кошелёк. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8efe4b5445..81f1371349 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -232,6 +232,10 @@ Could not keep this wallet\'s tags in your backup. Try again, or remove it without keeping them. Could not rename the hardware wallet. Please try again. Could not search for hardware wallets. Check your connection and try again. + Send again + This payment was already sent on %1$s. Send it again? + This payment was already sent. Send it again? + Payment already sent The network accepted this payment. It completes once your wallet sees the transaction. Check your connection and try again. Payment not confirmed @@ -246,6 +250,7 @@ Open Trezor Connect Sign With Jade Sign With Device + View payment Verify on Device Address verification failed. Check the address on your device and try again. This device holds a different wallet than the one you paired. Connect the paired wallet, or add this one as a new hardware wallet. diff --git a/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt index 13bb12b08b..d517fdf3cf 100644 --- a/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt @@ -170,6 +170,7 @@ class HwWalletRepoTest : BaseUnitTest() { whenever { activityRepo.getTagMetadataForWallet(any()) }.thenReturn(Result.success(emptyList())) whenever { preActivityMetadataRepo.upsertPreActivityMetadata(any()) }.thenReturn(Result.success(Unit)) whenever { hwWalletStore.setPendingName(any(), anyOrNull()) }.thenReturn(Unit) + whenever { hwHeldSendStore.load() }.thenReturn(HwHeldSendData()) } @Test @@ -383,6 +384,46 @@ class HwWalletRepoTest : BaseUnitTest() { verify(hwHeldSendStore, never()).releaseHeldSends(any()) } + @Test + fun `a held send its wallet has seen is tagged and released, unless the transaction was replaced`() = test { + val held = HeldHwSend( + walletId = HARDWARE_WALLET_ID, + txId = "T1", + address = HELD_ADDRESS, + amountSats = 25_000uL, + satsPerVByte = 2uL, + tags = listOf("rent"), + serializedTx = "00", + miningFeeSats = 200uL, + feeRate = 2uL, + totalSpent = 25_200uL, + ) + whenever(hwHeldSendStore.load()).thenReturn(HwHeldSendData(heldSends = listOf(held))) + whenever(activityRepo.addTagsToActivity(any(), any(), any())).thenReturn(Result.success(Unit)) + createRepo() + + emitSent(watcherActivity(amount = 25_000uL, txid = "t1", txType = PaymentType.SENT, doesExist = false)) + verify(hwHeldSendStore, never()).releaseHeldSends(any()) + + emitSent(watcherActivity(amount = 25_000uL, txid = "t1", txType = PaymentType.SENT)) + inOrder(activityRepo, hwHeldSendStore) { + verify(activityRepo).addTagsToActivity("t1", listOf("rent"), HARDWARE_WALLET_ID) + verify(hwHeldSendStore).releaseHeldSends(setOf("T1")) + } + } + + private suspend fun emitSent(activity: Activity) = watcherEvents.emit( + "hardware-wallet|nativeSegwit" to WatcherEvent.TransactionsChanged( + balance = walletBalance(total = 0uL), + activities = listOf(activity), + transactionDetails = emptyList(), + txCount = 1u, + blockHeight = 850_000u, + accountType = AccountType.NATIVE_SEGWIT, + nextUnusedExternalAddress = WATCHER_RECEIVE_ADDRESS, + ) + ) + @Test fun `an unreadable held send refuses sends of its wallet, and of every wallet when its wallet is unreadable`() = test { @@ -2651,6 +2692,7 @@ class HwWalletRepoTest : BaseUnitTest() { confirmations: UInt = 3u, fee: ULong = 0uL, walletId: String = HARDWARE_WALLET_ID, + doesExist: Boolean = true, ) = Activity.Onchain( OnchainActivity.create( walletId = walletId, @@ -2662,6 +2704,7 @@ class HwWalletRepoTest : BaseUnitTest() { address = "", timestamp = timestamp ?: 0uL, confirmed = blockHeight != null && confirmations > 0u, + doesExist = doesExist, ) ) diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt index c31392c313..e7ff8f4786 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt @@ -1229,16 +1229,18 @@ class HwSendViewModelTest : BaseUnitTest() { } @Test - fun `a held payment the wallet has seen is recorded as sent instead of signed again`() = test { + fun `a held payment the wallet has seen is recorded, then shown as sent unless sent again`() = test { val fixture = stubSuccessfulPayment() whenever(hwWalletRepo.heldSendFor(WALLET_ID, ADDRESS, AMOUNT_SATS)) .thenReturn(Result.success(heldSend(fixture.signedTx))) walletActivities.value = persistentListOf(sentActivity()) + val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) sut.signAndBroadcast(request()) advanceUntilIdle() - assertEquals(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), sut.results.first()) + assertEquals(held, sut.uiState.value.alreadySentSend?.send) + assertTrue(sut.uiState.value.alreadySentSend?.sentAt?.isNotEmpty() == true) verify(hwWalletRepo, never()).signFunding(any(), any()) verify(hwWalletRepo, never()).broadcastFunding(any(), anyOrNull()) inOrder(activityService, hwWalletRepo) { @@ -1254,6 +1256,47 @@ class HwSendViewModelTest : BaseUnitTest() { ) verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) } + + sut.showAlreadySentSend() + + assertNull(sut.uiState.value.alreadySentSend) + assertEquals(held, sut.results.first()) + } + + @Test + fun `a held payment the wallet has seen is signed anew only when the user sends it again`() = test { + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.heldSendFor(WALLET_ID, ADDRESS, AMOUNT_SATS)) + .thenReturn(Result.success(heldSend(fixture.signedTx)), Result.success(null)) + walletActivities.value = persistentListOf(sentActivity()) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + verify(hwWalletRepo, never()).signFunding(any(), any()) + + sut.confirmSendAgain() + sut.signAndBroadcast(request()) + advanceUntilIdle() + + assertNull(sut.uiState.value.alreadySentSend) + verify(hwWalletRepo, times(1)).signFunding(WALLET_ID, fixture.funding) + assertEquals(fixture.broadcast.txId, sut.results.first().txId) + } + + @Test + fun `a replaced transaction does not count as sent`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) + .thenReturn(Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE))) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + walletActivities.value = persistentListOf(sentActivity(doesExist = false)) + advanceUntilIdle() + + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) + verify(hwWalletRepo, never()).releaseHeldSend(any()) } @Test @@ -2421,7 +2464,7 @@ class HwSendViewModelTest : BaseUnitTest() { activities = persistentListOf(), ) - private fun sentActivity(walletId: String = WALLET_ID) = Activity.Onchain( + private fun sentActivity(walletId: String = WALLET_ID, doesExist: Boolean = true) = Activity.Onchain( OnchainActivity.create( walletId = walletId, id = SIGNED_TXID, @@ -2431,6 +2474,7 @@ class HwSendViewModelTest : BaseUnitTest() { fee = 1_000uL, address = ADDRESS, timestamp = 1_700_000_000uL, + doesExist = doesExist, ) ) From eb5b96f098bc5c07b8fc301df211c0d1d85310c4 Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 10:48:46 -0500 Subject: [PATCH 09/14] fix: stop an unanswered hardware broadcast blocking broadcast again Co-Authored-By: Claude Opus 5.5 --- .../repositories/HwHeldDispatchTracker.kt | 22 ++++++++++ .../screens/wallets/send/HwSendViewModel.kt | 21 +++++++++- app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-ca/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es-rES/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rBR/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../repositories/HwHeldDispatchTrackerTest.kt | 42 +++++++++++++++++++ .../wallets/send/HwSendViewModelTest.kt | 32 ++++++++++++++ 20 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 app/src/test/java/to/bitkit/repositories/HwHeldDispatchTrackerTest.kt diff --git a/app/src/main/java/to/bitkit/repositories/HwHeldDispatchTracker.kt b/app/src/main/java/to/bitkit/repositories/HwHeldDispatchTracker.kt index 1ccf92aca7..631820acc7 100644 --- a/app/src/main/java/to/bitkit/repositories/HwHeldDispatchTracker.kt +++ b/app/src/main/java/to/bitkit/repositories/HwHeldDispatchTracker.kt @@ -9,6 +9,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import javax.inject.Inject import javax.inject.Singleton +import kotlin.time.Duration.Companion.minutes /** * Every dispatch of a held hardware send's signed bytes in this process, by txid. A broadcast proving it sent nothing @@ -17,6 +18,14 @@ import javax.inject.Singleton */ @Singleton class HwHeldDispatchTracker @Inject constructor() { + companion object { + /** + * How long a dispatch may go unanswered before it counts as possibly sent, which lets the same bytes be + * broadcast again; that is harmless, and a possibly sent dispatch never releases a hold. + */ + val ANSWER_BOUND = 2.minutes + } + private val lock = Any() private val dispatches = mutableListOf() private val _inFlight = MutableStateFlow>(persistentSetOf()) @@ -39,10 +48,23 @@ class HwHeldDispatchTracker @Inject constructor() { synchronized(lock) { if (dispatch.outcome != HwHeldDispatch.Outcome.IN_FLIGHT) return dispatch.outcome = if (isNotSent) HwHeldDispatch.Outcome.NOT_SENT else HwHeldDispatch.Outcome.MAY_HAVE_SENT + // A dispatch proven not sent never keeps a hold, so only the possibly sent ones are remembered + if (isNotSent) dispatches.remove(dispatch) publish() } } + /** Counts [dispatch] as possibly sent once it has gone [ANSWER_BOUND] without an answer. */ + fun expire(dispatch: HwHeldDispatch) = finish(dispatch, isNotSent = false) + + /** Forgets the answered dispatches of [txId], once its hold is released. */ + fun forget(txId: String) { + synchronized(lock) { + val key = txId.lowercase() + dispatches.removeAll { it.txId == key && it.outcome != HwHeldDispatch.Outcome.IN_FLIGHT } + } + } + /** Whether every dispatch of [dispatch]'s bytes other than [dispatch] itself is proven not sent. */ fun isOnlyPossibleSend(dispatch: HwHeldDispatch): Boolean = synchronized(lock) { dispatches.none { diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index c6ad81bc13..f90ed8e0ce 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -20,6 +20,7 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.async import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow @@ -321,6 +322,7 @@ class HwSendViewModel @Inject constructor( // after a while, and its answer still settles the send val tracked = if (requestId == null) { checkNotNull(heldDispatches.begin(txId)) { "A broadcast of hardware send '$txId' is unanswered" } + .also { expireUnanswered(it) } } else { null } @@ -561,6 +563,7 @@ class HwSendViewModel @Inject constructor( ) private suspend fun releaseHeldSend(txId: String) { + heldDispatches.forget(txId) hwWalletRepo.releaseHeldSend(txId) .onFailure { Logger.warn("Failed to release held hardware send '$txId'", it, context = TAG) } } @@ -624,7 +627,16 @@ class HwSendViewModel @Inject constructor( val unresolved = unresolvedSends[txId.lowercase()] ?: return val send = unresolved.send // One dispatch of the same bytes at a time, from any sheet - val tracked = heldDispatches.begin(send.txId) ?: return + val tracked = heldDispatches.begin(send.txId) ?: run { + viewModelScope.launch { + ToastEventBus.send( + type = Toast.ToastType.INFO, + title = context.getString(R.string.hardware__send_broadcast_in_flight), + ) + } + return + } + expireUnanswered(tracked) viewModelScope.launch { var isNotSent = false try { @@ -660,6 +672,13 @@ class HwSendViewModel @Inject constructor( } } + private fun expireUnanswered(dispatch: HwHeldDispatch) { + viewModelScope.launch { + delay(HwHeldDispatchTracker.ANSWER_BOUND) + heldDispatches.expire(dispatch) + } + } + private suspend fun toastBroadcastFailed() = ToastEventBus.send( type = Toast.ToastType.WARNING, title = context.getString(R.string.hardware__send_broadcast_failed_title), diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 7858b7508d..7830003ca6 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1198,6 +1198,7 @@ قبلت الشبكة هذه الدفعة. تكتمل بمجرد أن ترى محفظتك المعاملة. تحقق من اتصالك وحاول مرة أخرى. الدفعة غير مؤكدة + لم يصل رد على آخر بث لهذه الدفعة بعد. حاول مرة أخرى بعد قليل. قد تُؤكَّد هذه الدفعة لاحقًا. تبقى معلقة حتى ترى محفظتك المعاملة أو تُنفَق عملاتها في مكان آخر. لا يمكن تأكيد هذه الدفعة أبدًا. يمكنك إجراؤها مرة أخرى. إلى العنوان (أكّد على الجهاز) diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 25f19911b5..d2f2611cfd 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1231,6 +1231,7 @@ La red aceptó este pago. Se completará cuando su billetera vea la transacción. Revise su conexión y vuelva a intentarlo. Pago no confirmado + La última transmisión de este pago aún no tiene respuesta. Inténtelo de nuevo en un momento. Este pago aún podría confirmarse. Sigue pendiente hasta que su billetera lo vea o sus monedas se gasten en otra transacción. Este pago nunca podrá confirmarse. Puede hacerlo de nuevo. A LA DIRECCIÓN (CONFIRME EN EL DISPOSITIVO) diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 0b24594405..f38a7fe7bc 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1223,6 +1223,7 @@ La xarxa ha acceptat aquest pagament. Es completarà quan la teva cartera vegi la transacció. Comprova la connexió i torna-ho a provar. Pagament no confirmat + L\'última difusió d\'aquest pagament encara no ha respost. Torna-ho a provar d\'aquí a un moment. Aquest pagament encara es podria confirmar. Continua pendent fins que la teva cartera el vegi o les seves monedes es gastin en una altra transacció. Aquest pagament no es podrà confirmar mai. Pots tornar-lo a fer. A L\'ADREÇA (CONFIRMA AL DISPOSITIU) diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 8968fda0ad..93af770c69 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1229,6 +1229,7 @@ Síť tuto platbu přijala. Dokončí se, jakmile vaše peněženka transakci uvidí. Zkontrolujte připojení a zkuste to znovu. Platba nebyla potvrzena + Poslední odeslání této platby do sítě zatím neodpovědělo. Zkuste to za chvíli znovu. Tato platba může být stále potvrzena. Zůstává čekající, dokud ji vaše peněženka neuvidí nebo dokud nebudou její mince utraceny jinde. Tato platba nikdy nemůže být potvrzena. Můžete ji provést znovu. NA ADRESU (POTVRĎTE NA ZAŘÍZENÍ) diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 1ebdecb785..3af1cbe68e 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1226,6 +1226,7 @@ Das Netzwerk hat diese Zahlung angenommen. Sie wird abgeschlossen, sobald dein Wallet die Transaktion sieht. Überprüfe deine Verbindung und versuche es erneut. Zahlung nicht bestätigt + Die letzte Übertragung dieser Zahlung hat noch nicht geantwortet. Versuche es gleich noch einmal. Diese Zahlung kann noch bestätigt werden. Sie bleibt ausstehend, bis dein Wallet sie sieht oder ihre Coins anderweitig ausgegeben werden. Diese Zahlung kann nie bestätigt werden. Du kannst sie erneut ausführen. AN ADRESSE (AM GERÄT BESTÄTIGEN) diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 1ba2f188fe..04fbb55662 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1204,6 +1204,7 @@ Το δίκτυο αποδέχτηκε αυτή την πληρωμή. Θα ολοκληρωθεί μόλις το πορτοφόλι σου δει τη συναλλαγή. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. Η πληρωμή δεν επιβεβαιώθηκε + Η τελευταία μετάδοση αυτής της πληρωμής δεν έχει απαντήσει ακόμη. Δοκίμασε ξανά σε λίγο. Αυτή η πληρωμή μπορεί ακόμη να επιβεβαιωθεί. Παραμένει σε εκκρεμότητα μέχρι να τη δει το πορτοφόλι σου ή να ξοδευτούν αλλού τα νομίσματά της. Αυτή η πληρωμή δεν μπορεί να επιβεβαιωθεί ποτέ. Μπορείς να την κάνεις ξανά. ΠΡΟΣ ΔΙΕΥΘΥΝΣΗ (ΕΠΙΒΕΒΑΙΩΣΗ ΣΤΗ ΣΥΣΚΕΥΗ) diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index bbc42cf7ff..76fcd9a16a 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1221,6 +1221,7 @@ La red aceptó este pago. Se completará cuando tu monedero vea la transacción. Comprueba tu conexión e inténtalo de nuevo. Pago no confirmado + La última transmisión de este pago aún no tiene respuesta. Inténtalo de nuevo en un momento. Este pago aún podría confirmarse. Sigue pendiente hasta que tu monedero lo vea o sus monedas se gasten en otra transacción. Este pago nunca podrá confirmarse. Puedes hacerlo de nuevo. A LA DIRECCIÓN (CONFIRMA EN EL DISPOSITIVO) diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index ef7c2805e5..b5eab7f640 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1219,6 +1219,7 @@ La red aceptó este pago. Se completará cuando su monedero vea la transacción. Compruebe su conexión e inténtelo de nuevo. Pago no confirmado + La última transmisión de este pago aún no tiene respuesta. Inténtelo de nuevo en un momento. Este pago aún podría confirmarse. Sigue pendiente hasta que su monedero lo vea o sus monedas se gasten en otra transacción. Este pago nunca podrá confirmarse. Puede hacerlo de nuevo. A LA DIRECCIÓN (CONFIRME EN EL DISPOSITIVO) diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index da074a096b..f0f21cb382 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1225,6 +1225,7 @@ Le réseau a accepté ce paiement. Il sera finalisé dès que votre portefeuille verra la transaction. Vérifiez votre connexion et réessayez. Paiement non confirmé + La dernière diffusion de ce paiement n\'a pas encore répondu. Réessayez dans un instant. Ce paiement peut encore être confirmé. Il reste en attente jusqu\'à ce que votre portefeuille le voie ou que ses pièces soient dépensées ailleurs. Ce paiement ne pourra jamais être confirmé. Vous pouvez le refaire. VERS L\'ADRESSE (CONFIRMER SUR L\'APPAREIL) diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 6d1aef3ac6..d6fe20b0db 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1227,6 +1227,7 @@ La rete ha accettato questo pagamento. Si completerà non appena il tuo wallet vedrà la transazione. Controlla la connessione e riprova. Pagamento non confermato + L\'ultima trasmissione di questo pagamento non ha ancora risposto. Riprova tra un momento. Questo pagamento potrebbe ancora essere confermato. Resta in sospeso finché il tuo wallet non lo vede o le sue monete non vengono spese altrove. Questo pagamento non potrà mai essere confermato. Puoi effettuarlo di nuovo. ALL\'INDIRIZZO (CONFERMA SUL DISPOSITIVO) diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index b9bdfd5b9e..c37e83ff92 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1222,6 +1222,7 @@ Het netwerk heeft deze betaling geaccepteerd. Ze wordt voltooid zodra uw wallet de transactie ziet. Controleer uw verbinding en probeer het opnieuw. Betaling niet bevestigd + De laatste uitzending van deze betaling heeft nog niet geantwoord. Probeer het zo opnieuw. Deze betaling kan nog worden bevestigd. Ze blijft in behandeling totdat uw wallet haar ziet of de munten ervan elders worden uitgegeven. Deze betaling kan nooit worden bevestigd. U kunt haar opnieuw uitvoeren. NAAR ADRES (BEVESTIG OP APPARAAT) diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 3731c08563..9e1ebccfe2 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1228,6 +1228,7 @@ Sieć przyjęła tę płatność. Zostanie zakończona, gdy Twój portfel zobaczy transakcję. Sprawdź połączenie i spróbuj ponownie. Płatność niepotwierdzona + Ostatnie rozesłanie tej płatności jeszcze nie otrzymało odpowiedzi. Spróbuj ponownie za chwilę. Ta płatność nadal może zostać potwierdzona. Pozostaje oczekująca, dopóki Twój portfel jej nie zobaczy lub jej monety nie zostaną wydane gdzie indziej. Ta płatność nigdy nie zostanie potwierdzona. Możesz wykonać ją ponownie. NA ADRES (POTWIERDŹ NA URZĄDZENIU) diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index d9f474e4c5..015df33d3a 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1230,6 +1230,7 @@ A rede aceitou este pagamento. Ele será concluído assim que sua carteira vir a transação. Verifique sua conexão e tente novamente. Pagamento não confirmado + A última transmissão deste pagamento ainda não respondeu. Tente novamente em instantes. Este pagamento ainda pode ser confirmado. Ele continua pendente até que sua carteira o veja ou suas moedas sejam gastas em outro lugar. Este pagamento nunca poderá ser confirmado. Você pode fazê-lo novamente. PARA O ENDEREÇO (CONFIRME NO DISPOSITIVO) diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 4ccb50e10c..2d948eb916 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1196,6 +1196,7 @@ A rede aceitou este pagamento. Fica concluído assim que a sua carteira vir a transação. Verifique a ligação e tente novamente. Pagamento não confirmado + A última transmissão deste pagamento ainda não respondeu. Tente novamente dentro de momentos. Este pagamento ainda pode ser confirmado. Continua pendente até a sua carteira o ver ou as suas moedas serem gastas noutro lado. Este pagamento nunca poderá ser confirmado. Pode fazê-lo novamente. PARA O ENDEREÇO (CONFIRME NO DISPOSITIVO) diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index cee487d86c..2c56b18b1d 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1246,6 +1246,7 @@ Сеть приняла этот платёж. Он завершится, как только ваш кошелёк увидит транзакцию. Проверьте подключение и попробуйте снова. Платёж не подтверждён + Последняя отправка этого платежа в сеть ещё не получила ответа. Повторите попытку чуть позже. Этот платёж ещё может быть подтверждён. Он остаётся в ожидании, пока ваш кошелёк его не увидит или его монеты не будут потрачены в другой транзакции. Этот платёж никогда не будет подтверждён. Вы можете выполнить его снова. НА АДРЕС (ПОДТВЕРДИТЕ НА УСТРОЙСТВЕ) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 81f1371349..e42959215a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -239,6 +239,7 @@ The network accepted this payment. It completes once your wallet sees the transaction. Check your connection and try again. Payment not confirmed + The last broadcast of this payment has not answered yet. Try again in a moment. This payment may still confirm. It stays pending until your wallet sees it or its coins are spent elsewhere. This payment can never confirm. You can make it again. TO ADDRESS (CONFIRM ON DEVICE) diff --git a/app/src/test/java/to/bitkit/repositories/HwHeldDispatchTrackerTest.kt b/app/src/test/java/to/bitkit/repositories/HwHeldDispatchTrackerTest.kt new file mode 100644 index 0000000000..4c3ac97224 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/HwHeldDispatchTrackerTest.kt @@ -0,0 +1,42 @@ +package to.bitkit.repositories + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class HwHeldDispatchTrackerTest { + private val sut = HwHeldDispatchTracker() + + @Test + fun `one dispatch of the same bytes runs at a time, and an expired one counts as possibly sent`() { + val first = assertNotNull(sut.begin("AB")) + assertNull(sut.begin("ab")) + assertEquals(setOf("ab"), sut.inFlight.value) + + sut.expire(first) + sut.finish(first, isNotSent = true) + val second = assertNotNull(sut.begin("ab")) + + assertTrue(sut.inFlight.value.contains("ab")) + assertFalse(sut.isOnlyPossibleSend(second)) + } + + @Test + fun `a dispatch proven not sent is pruned, and the rest are forgotten once the hold is released`() { + val notSent = assertNotNull(sut.begin("ab")) + sut.finish(notSent, isNotSent = true) + val maybeSent = assertNotNull(sut.begin("ab")) + sut.finish(maybeSent, isNotSent = false) + val last = assertNotNull(sut.begin("ab")) + + assertFalse(sut.isOnlyPossibleSend(last)) + + sut.forget("AB") + + assertTrue(sut.isOnlyPossibleSend(last)) + assertEquals(setOf("ab"), sut.inFlight.value) + } +} diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt index e7ff8f4786..08ec2a1edb 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt @@ -731,6 +731,38 @@ class HwSendViewModelTest : BaseUnitTest() { verify(hwWalletRepo, never()).releaseHeldSend(any()) } + @Test + fun `a broadcast that never answers stops blocking broadcast again after two minutes`() = test { + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + whenever(context.getString(any())).thenReturn("message") + whenever(context.getString(R.string.hardware__send_broadcast_in_flight)).thenReturn("in flight") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { + withContext(NonCancellable) { CompletableDeferred>().await() } + }.thenReturn(Result.success(fixture.broadcast)) + + sut.signAndBroadcast(request()) + advanceTimeBy(61.seconds) + runCurrent() + sut.retryUnresolvedSend(SIGNED_TXID) + runCurrent() + + assertEquals(1, toasts.count { it.title == "in flight" }) + verify(hwWalletRepo, times(1)).broadcastFunding(fixture.signedTx) + + advanceTimeBy(60.seconds) + runCurrent() + assertTrue(sut.uiState.value.retryingSendTxIds.isEmpty()) + sut.retryUnresolvedSend(SIGNED_TXID) + runCurrent() + toastJob.cancel() + + verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) + verify(hwWalletRepo, never()).releaseHeldSend(any()) + } + @Test fun `a late proof that nothing was sent keeps the hold when the same bytes may have gone out before`() = test { whenever(context.getString(any())).thenReturn("message") From cc52c7f427b6195c418e1e5a38a8a4a0dc3b3a0d Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 10:52:00 -0500 Subject: [PATCH 10/14] fix: clear held hardware sends on wallet wipe Co-Authored-By: Claude Opus 5.5 --- .../main/java/to/bitkit/repositories/HwWalletRepo.kt | 2 ++ .../java/to/bitkit/repositories/HwWalletRepoTest.kt | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt index 92c3587180..3fb50861a6 100644 --- a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt @@ -285,6 +285,8 @@ class HwWalletRepo @Inject constructor( } trezorRepo.resetState() jadeRepo.resetState() + // A wipe forgets held sends with the rest of the wallet; one that cannot be cleared fails the wipe + hwHeldSendStore.reset() } /** Pairing-code request raised by the device during connect; the UI shows the Pair Device sheet. */ diff --git a/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt index d517fdf3cf..1cede5dd53 100644 --- a/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt @@ -73,6 +73,7 @@ import to.bitkit.services.TrezorWalletMode import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue @@ -2028,9 +2029,18 @@ class HwWalletRepoTest : BaseUnitTest() { verify(trezorRepo).stopWatcher("hardware-wallet|nativeSegwit") verify(trezorRepo).resetState() + verify(hwHeldSendStore).reset() assertEquals(0uL, sut.totalSats.value) } + @Test + fun `resetState fails when held sends cannot be cleared`() = test { + whenever(hwHeldSendStore.reset()).doSuspendableAnswer { throw HwHeldSendsUnreadableError(walletId = null) } + val sut = createRepo() + + assertFailsWith { sut.resetState() } + } + @Test fun `removeDevice stops the device watchers and forgets it`() = test { whenever(hwWalletStore.loadKnownDevices()).thenReturn(listOf(device), emptyList()) From 4d34cc270dcd5a282fc973476c12be889ce83317 Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 11:05:29 -0500 Subject: [PATCH 11/14] fix: show an unreadable hardware hold record before clearing it Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/data/HwHeldSendStore.kt | 65 ++++++++++++++---- .../to/bitkit/repositories/HwWalletRepo.kt | 2 +- .../screens/wallets/send/HwSendSignScreen.kt | 24 +++++-- .../screens/wallets/send/HwSendViewModel.kt | 66 +++++++++++++++---- app/src/main/res/values-ar/strings.xml | 6 ++ app/src/main/res/values-b+es+419/strings.xml | 6 ++ app/src/main/res/values-ca/strings.xml | 6 ++ app/src/main/res/values-cs/strings.xml | 6 ++ app/src/main/res/values-de/strings.xml | 6 ++ app/src/main/res/values-el/strings.xml | 6 ++ app/src/main/res/values-es-rES/strings.xml | 6 ++ app/src/main/res/values-es/strings.xml | 6 ++ app/src/main/res/values-fr/strings.xml | 6 ++ app/src/main/res/values-it/strings.xml | 6 ++ app/src/main/res/values-nl/strings.xml | 6 ++ app/src/main/res/values-pl/strings.xml | 6 ++ app/src/main/res/values-pt-rBR/strings.xml | 6 ++ app/src/main/res/values-pt/strings.xml | 6 ++ app/src/main/res/values-ru/strings.xml | 6 ++ app/src/main/res/values/strings.xml | 6 ++ .../to/bitkit/data/HwHeldSendStoreTest.kt | 24 +++++++ .../wallets/send/HwSendViewModelTest.kt | 60 +++++++++++++---- 22 files changed, 297 insertions(+), 40 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/HwHeldSendStore.kt b/app/src/main/java/to/bitkit/data/HwHeldSendStore.kt index 1bc7f30edb..3c44f14680 100644 --- a/app/src/main/java/to/bitkit/data/HwHeldSendStore.kt +++ b/app/src/main/java/to/bitkit/data/HwHeldSendStore.kt @@ -125,8 +125,30 @@ data class HwHeldSendData( ) { /** Whether a record this cannot read may belong to [walletId], including one whose wallet cannot be read. */ fun hasUnreadableFor(walletId: String): Boolean = unreadable.any { it.mayBelongTo(walletId) } + + /** + * The error refusing [walletId]'s sends, with what can still be read of its unreadable records; null when none + * may belong to it. + */ + fun unreadableErrorFor(walletId: String): HwHeldSendsUnreadableError? { + val records = unreadable.filter { it.mayBelongTo(walletId) } + if (records.isEmpty()) return null + return HwHeldSendsUnreadableError( + walletId = walletId, + records = records.map { it.toUnreadableHeldSend() }, + clearsAllWallets = records.any { it.walletIdOrNull() == null }, + ) + } } +/** What can still be read of a held send record that cannot be read whole. */ +data class UnreadableHeldSend( + val amountSats: ULong? = null, + val address: String? = null, + val txId: String? = null, + val heldAt: Long? = null, +) + /** * A signed hardware send whose broadcast may have reached the network, so the same payment is never signed again * beside it: it is only broadcast again as these bytes. Fields added later need defaults, so older records still read. @@ -143,17 +165,29 @@ data class HeldHwSend( val miningFeeSats: ULong, val feeRate: ULong, val totalSpent: ULong, + /** When the send was last held, in seconds since the epoch. */ + val heldAt: Long? = null, ) { fun isPaymentOf(walletId: String, address: String, amountSats: ULong): Boolean = this.walletId == walletId && this.address.equals(address, ignoreCase = true) && this.amountSats == amountSats } -private fun JsonElement.mayBelongTo(walletId: String): Boolean { - val recordWalletId = ((this as? JsonObject)?.get("walletId") as? JsonPrimitive) - ?.takeIf { it.isString } - ?.contentOrNull - return recordWalletId == null || recordWalletId == walletId -} +private fun JsonElement.mayBelongTo(walletId: String): Boolean = walletIdOrNull().let { it == null || it == walletId } + +private fun JsonElement.walletIdOrNull(): String? = stringField("walletId") + +private fun JsonElement.stringField(name: String): String? = + ((this as? JsonObject)?.get(name) as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull + +private fun JsonElement.numberField(name: String): String? = + ((this as? JsonObject)?.get(name) as? JsonPrimitive)?.contentOrNull + +private fun JsonElement.toUnreadableHeldSend() = UnreadableHeldSend( + amountSats = numberField("amountSats")?.toULongOrNull(), + address = stringField("address"), + txId = stringField("txId"), + heldAt = numberField("heldAt")?.toLongOrNull(), +) internal object HwHeldSendDataSerializer : Serializer { private const val VERSION = 1 @@ -162,13 +196,15 @@ internal object HwHeldSendDataSerializer : Serializer { override suspend fun readFrom(input: InputStream): HwHeldSendData = try { val root = json.parseToJsonElement(input.readBytes().decodeToString()).jsonObject - val records = root["heldSends"] as? JsonArray ?: throw SerializationException("No held sends") + val held = root["heldSends"] as? JsonArray ?: throw SerializationException("No held sends") + // Records an earlier version could not read are tried again, as a newer version may read them + val records = held + (root["unreadable"] as? JsonArray).orEmpty() val (readable, unreadable) = records.map { record -> record to runCatching { json.decodeFromJsonElement(record) }.getOrNull() }.partition { it.second != null } HwHeldSendData( heldSends = readable.mapNotNull { it.second }, - unreadable = unreadable.map { it.first } + (root["unreadable"] as? JsonArray).orEmpty(), + unreadable = unreadable.map { it.first }, ) } catch (error: SerializationException) { throw CorruptionException("Failed to read held hardware sends", error) @@ -188,6 +224,13 @@ internal object HwHeldSendDataSerializer : Serializer { } } -/** The held hardware sends could not be read, so no hardware send is signed: [walletId]'s, or any when null. */ -class HwHeldSendsUnreadableError(val walletId: String?, cause: Throwable? = null) : - AppError("Held hardware sends could not be read", cause) +/** + * The held hardware sends could not be read, so no send of [walletId] is signed, or none at all when + * [clearsAllWallets]. [records] holds what can still be read of the records concerned. + */ +class HwHeldSendsUnreadableError( + val walletId: String?, + val records: List = emptyList(), + val clearsAllWallets: Boolean = walletId == null, + cause: Throwable? = null, +) : AppError("Held hardware sends could not be read", cause) diff --git a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt index 3fb50861a6..9b4035a92b 100644 --- a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt @@ -928,7 +928,7 @@ class HwWalletRepo @Inject constructor( withContext(ioDispatcher) { runSuspendCatching { val data = hwHeldSendStore.load() - if (data.hasUnreadableFor(walletId)) throw HwHeldSendsUnreadableError(walletId) + data.unreadableErrorFor(walletId)?.let { throw it } data.heldSends.firstOrNull { it.isPaymentOf(walletId, address, amountSats) } } } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt index b3589d2964..d43a15baba 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt @@ -129,11 +129,27 @@ fun HwSendSignScreen( ) } - if (uiState.unreadableHeldSendsWalletId != null) { + uiState.unreadableHeldSends?.let { prompt -> + val clearText = if (prompt.clearsAllWallets) { + stringResource(R.string.hardware__held_sends_clear_all) + } else { + stringResource(R.string.hardware__held_sends_clear) + } AppAlertDialog( - title = stringResource(R.string.hardware__held_sends_unreadable_title), - text = stringResource(R.string.hardware__held_sends_unreadable_text), - confirmText = stringResource(R.string.hardware__held_sends_clear), + title = stringResource( + if (prompt.isConfirming) { + R.string.hardware__held_sends_clear_confirm_title + } else { + R.string.hardware__held_sends_unreadable_title + }, + ), + text = if (prompt.isConfirming) { + stringResource(R.string.hardware__held_sends_clear_confirm_text) + } else { + prompt.message + }, + confirmText = clearText, + confirmTextColor = Colors.Red, onConfirm = viewModel::clearUnreadableHeldSends, onDismiss = viewModel::dismissUnreadableHeldSends, ) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index f90ed8e0ce..9e61700122 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -317,7 +317,7 @@ class HwSendViewModel @Inject constructor( val txId = SignedTransactionId.fromHex(payment.signedTx.serializedTx) _uiState.update { it.copy(isBroadcastUnresolved = true) } // Written before the broadcast, so a send that may have gone out stays held even if the app dies during it - if (requestId == null) hwWalletRepo.holdSend(payment.toHeldSend(txId)).getOrThrow() + if (requestId == null) hwWalletRepo.holdSend(payment.toHeldSend(txId, clock.now().epochSeconds)).getOrThrow() // The broadcast runs to its end on the core queue, so it is never cancelled: the sheet stops waiting for it // after a while, and its answer still settles the send val tracked = if (requestId == null) { @@ -641,7 +641,8 @@ class HwSendViewModel @Inject constructor( var isNotSent = false try { // Written again first, so the send stays held whatever happened to the record since - hwWalletRepo.holdSend(unresolved.payment.toHeldSend(send.txId)).onFailure { + val heldAt = clock.now().epochSeconds + hwWalletRepo.holdSend(unresolved.payment.toHeldSend(send.txId, heldAt)).onFailure { isNotSent = true Logger.warn("Skipped broadcast again of '${send.txId}' without its hold", it, context = TAG) toastBroadcastFailed() @@ -752,17 +753,47 @@ class HwSendViewModel @Inject constructor( * after being told a payment they held may then be sent twice. */ fun clearUnreadableHeldSends() { - val walletId = _uiState.value.unreadableHeldSendsWalletId ?: return - _uiState.update { it.copy(unreadableHeldSendsWalletId = null) } + val prompt = _uiState.value.unreadableHeldSends ?: return + if (!prompt.isConfirming) { + // A clear that may send a payment twice is asked a second time + _uiState.update { it.copy(unreadableHeldSends = prompt.copy(isConfirming = true)) } + return + } + _uiState.update { it.copy(unreadableHeldSends = null) } viewModelScope.launch { - hwWalletRepo.clearUnreadableHeldSends(walletId).onFailure { - Logger.error("Failed to clear unreadable held sends of '$walletId'", it, context = TAG) - _uiState.update { state -> state.copy(unreadableHeldSendsWalletId = walletId) } + hwWalletRepo.clearUnreadableHeldSends(prompt.walletId).onFailure { + Logger.error("Failed to clear unreadable held sends of '${prompt.walletId}'", it, context = TAG) + _uiState.update { state -> state.copy(unreadableHeldSends = prompt.copy(isConfirming = false)) } } } } - fun dismissUnreadableHeldSends() = _uiState.update { it.copy(unreadableHeldSendsWalletId = null) } + fun dismissUnreadableHeldSends() = _uiState.update { it.copy(unreadableHeldSends = null) } + + private fun HwHeldSendsUnreadableError.toPrompt(walletId: String): UnreadableHeldSendsPrompt { + val unknown = context.getString(R.string.hardware__held_sends_record_unknown) + val explanation = context.getString( + if (clearsAllWallets) { + R.string.hardware__held_sends_unreadable_text_all + } else { + R.string.hardware__held_sends_unreadable_text + }, + ) + val details = records.map { record -> + context.getString( + R.string.hardware__held_sends_record, + record.amountSats?.toString() ?: unknown, + record.address ?: unknown, + record.txId ?: unknown, + record.heldAt?.toULong().formatToString() ?: unknown, + ) + } + return UnreadableHeldSendsPrompt( + walletId = this.walletId ?: walletId, + message = (listOf(explanation) + details).joinToString("\n\n"), + clearsAllWallets = clearsAllWallets, + ) + } fun dismissPassphrase() { passphraseJob?.cancel() @@ -946,7 +977,9 @@ class HwSendViewModel @Inject constructor( generateSequence(error) { it.cause }.any { it is HwHeldSendsUnreadableError } -> { // Nothing is signed until the user decides, knowing what it risks, to clear the unreadable record Logger.warn("Refused hardware send of '$walletId' with unreadable holds", error, context = TAG) - _uiState.update { it.copy(unreadableHeldSendsWalletId = walletId) } + val unreadable = generateSequence(error) { it.cause }.filterIsInstance() + .first() + _uiState.update { it.copy(unreadableHeldSends = unreadable.toPrompt(walletId)) } } error.isHwUserCancellation() -> { Logger.info("Hardware send cancelled on device for '$walletId'", context = TAG) @@ -1016,8 +1049,8 @@ data class HwSendUiState( val retryingSendTxIds: ImmutableSet = persistentSetOf(), /** A payment the user tried to make again that its wallet has already sent, waiting for their choice. */ val alreadySentSend: AlreadySentHwSend? = null, - /** The wallet whose sends are refused because an earlier held send of it cannot be read. */ - val unreadableHeldSendsWalletId: String? = null, + /** Sends refused because an earlier held send cannot be read, waiting for the user to clear its record. */ + val unreadableHeldSends: UnreadableHeldSendsPrompt? = null, ) { /** * Whether the sign sheet may be dismissed. Connecting or unlocking can be abandoned, and leaving @@ -1038,6 +1071,14 @@ data class HwSendResult( data class AlreadySentHwSend(val send: HwSendResult, val sentAt: String) +/** What the user is told before clearing unreadable held send records, asked a second time once [isConfirming]. */ +data class UnreadableHeldSendsPrompt( + val walletId: String, + val message: String, + val clearsAllWallets: Boolean, + val isConfirming: Boolean = false, +) + sealed interface HeldHwSendEvent { val send: HwSendResult @@ -1082,7 +1123,7 @@ private data class PendingHwSendBroadcast( hasAttemptedBroadcast && this.request.paymentRequestId != null && this.request.copy(satsPerVByte = request.satsPerVByte, tags = request.tags) == request - fun toHeldSend(txId: String) = HeldHwSend( + fun toHeldSend(txId: String, heldAt: Long) = HeldHwSend( walletId = request.walletId, txId = txId, address = request.address, @@ -1093,6 +1134,7 @@ private data class PendingHwSendBroadcast( miningFeeSats = signedTx.miningFeeSats, feeRate = signedTx.feeRate, totalSpent = signedTx.totalSpent, + heldAt = heldAt, ) } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 7830003ca6..d79950e0c5 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1150,7 +1150,13 @@ هل تريد إقران جهاز %1$s هذا مع Bitkit بشكل آمن؟ تم العثور على جهاز مسح السجل + مسح لجميع المحافظ + إذا كانت دفعة سابقة لا تزال معلقة، فقد يرسلها Bitkit مرة ثانية. لا يمكن التراجع عن ذلك. + مسح السجل؟ + المبلغ: %1$s sats · العنوان: %2$s · المعاملة: %3$s · محجوزة: %4$s + غير معروف تعذّر على Bitkit قراءة دفعة سابقة من محفظة الأجهزة هذه، لذلك لن يوقّع دفعة جديدة. يتيح مسح هذا السجل لـ Bitkit التوقيع مرة أخرى. لا تمسحه إلا إذا لم تكن أي دفعة سابقة من هذه المحفظة لا تزال معلقة، وإلا فقد تُرسَل الدفعة نفسها مرتين. + تعذّر على Bitkit قراءة سجله لدفعات محافظ الأجهزة السابقة، لذلك لن يوقّع دفعة جديدة من أي محفظة أجهزة. يتيح مسح السجل لجميع محافظ الأجهزة لـ Bitkit التوقيع مرة أخرى. لا تمسحه إلا إذا لم تكن أي دفعة سابقة من محفظة أجهزة لا تزال معلقة، وإلا فقد تُرسَل الدفعة نفسها مرتين. تعذّرت قراءة دفعة سابقة أضف <accent>محفظة الأجهزة</accent> الخاصة بك اربط جهازك لمراقبة أموالك طويلة الأجل أو إدارتها. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index d2f2611cfd..78c3f54e23 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1183,7 +1183,13 @@ ¿Desea vincular este %1$s con Bitkit de forma segura? Dispositivo encontrado Borrar registro + Borrar para todas las billeteras + Si un pago anterior sigue pendiente, Bitkit podría enviarlo por segunda vez. Esto no se puede deshacer. + ¿Borrar el registro? + Monto: %1$s sats · Dirección: %2$s · Transacción: %3$s · Retenido: %4$s + desconocido Bitkit no pudo leer un pago anterior de esta billetera de hardware, así que no firmará uno nuevo. Borrar ese registro permite que Bitkit vuelva a firmar. Bórrelo solo si ningún pago anterior de esta billetera sigue pendiente, o el mismo pago podría enviarse dos veces. + Bitkit no pudo leer su registro de pagos anteriores con billetera de hardware, así que no firmará uno nuevo desde ninguna billetera de hardware. Borrar el registro de todas las billeteras de hardware permite que Bitkit vuelva a firmar. Bórrelo solo si ningún pago anterior con billetera de hardware sigue pendiente, o el mismo pago podría enviarse dos veces. No se puede leer un pago anterior Añada su <accent>billetera de hardware</accent> Conecte su dispositivo de hardware para supervisar o administrar sus fondos a largo plazo. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index f38a7fe7bc..6f2ad8475f 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1175,7 +1175,13 @@ Vols vincular de forma segura aquest %1$s amb Bitkit? Dispositiu trobat Esborrar el registre + Esborrar per a totes les carteres + Si un pagament anterior continua pendent, Bitkit el podria enviar una segona vegada. Això no es pot desfer. + Vols esborrar el registre? + Import: %1$s sats · Adreça: %2$s · Transacció: %3$s · Retingut: %4$s + desconegut Bitkit no ha pogut llegir un pagament anterior d\'aquesta cartera de maquinari, així que no en signarà cap de nou. Esborrar aquest registre permet que Bitkit torni a signar. Esborra\'l només si cap pagament anterior d\'aquesta cartera continua pendent, o el mateix pagament es podria enviar dues vegades. + Bitkit no ha pogut llegir el seu registre de pagaments anteriors amb cartera de maquinari, així que no en signarà cap de nou des de cap cartera de maquinari. Esborrar el registre de totes les carteres de maquinari permet que Bitkit torni a signar. Esborra\'l només si cap pagament anterior amb cartera de maquinari continua pendent, o el mateix pagament es podria enviar dues vegades. No es pot llegir un pagament anterior Afegeix la teva <accent>cartera de maquinari</accent> Connecta el teu dispositiu de maquinari per supervisar o gestionar els teus fons a llarg termini. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 93af770c69..af35a1f0b4 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1181,7 +1181,13 @@ Chcete bezpečně spárovat toto zařízení %1$s s Bitkitem? Nalezené zařízení Smazat záznam + Smazat pro všechny peněženky + Pokud dřívější platba stále čeká, Bitkit ji může odeslat podruhé. Tuto akci nelze vrátit zpět. + Smazat záznam? + Částka: %1$s sats · Adresa: %2$s · Transakce: %3$s · Drženo: %4$s + neznámé Bitkit nemohl přečíst dřívější platbu z této hardwarové peněženky, proto novou nepodepíše. Smazání tohoto záznamu umožní Bitkitu znovu podepisovat. Smažte jej pouze tehdy, pokud žádná dřívější platba z této peněženky nečeká, jinak by mohla být stejná platba odeslána dvakrát. + Bitkit nemohl přečíst svůj záznam dřívějších plateb z hardwarových peněženek, proto nepodepíše novou z žádné hardwarové peněženky. Smazání záznamu pro všechny hardwarové peněženky umožní Bitkitu znovu podepisovat. Smažte jej pouze tehdy, pokud žádná dřívější platba z hardwarové peněženky nečeká, jinak by mohla být stejná platba odeslána dvakrát. Dřívější platbu nelze přečíst Přidejte svou <accent>hardwarovou peněženku</accent> Připojte své hardwarové zařízení a sledujte nebo spravujte své dlouhodobé prostředky. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 3af1cbe68e..9433446c0d 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1178,7 +1178,13 @@ Möchtest du deinen %1$s sicher mit Bitkit koppeln? Gerät gefunden Aufzeichnung löschen + Für alle Wallets löschen + Steht eine frühere Zahlung noch aus, sendet Bitkit sie möglicherweise ein zweites Mal. Dies kann nicht rückgängig gemacht werden. + Aufzeichnung löschen? + Betrag: %1$s sats · Adresse: %2$s · Transaktion: %3$s · Gehalten: %4$s + unbekannt Bitkit konnte eine frühere Zahlung von diesem Hardware-Wallet nicht lesen und signiert daher keine neue. Wenn du diese Aufzeichnung löschst, signiert Bitkit wieder. Lösche sie nur, wenn keine frühere Zahlung von diesem Wallet mehr aussteht, sonst könnte dieselbe Zahlung zweimal gesendet werden. + Bitkit konnte seine Aufzeichnung früherer Hardware-Wallet-Zahlungen nicht lesen und signiert daher von keinem Hardware-Wallet eine neue. Wenn du die Aufzeichnung für alle Hardware-Wallets löschst, signiert Bitkit wieder. Lösche sie nur, wenn keine frühere Hardware-Wallet-Zahlung mehr aussteht, sonst könnte dieselbe Zahlung zweimal gesendet werden. Frühere Zahlung nicht lesbar Füge dein\n<accent>Hardware-\nWallet</accent> hinzu Verbinde dein Hardware-Gerät, um dein langfristiges Guthaben zu beobachten oder zu verwalten. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 04fbb55662..0e34d65a2a 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1156,7 +1156,13 @@ Θέλεις να συζεύξεις με ασφάλεια αυτό το %1$s με το Bitkit; Βρέθηκε συσκευή Διαγραφή εγγραφής + Διαγραφή για όλα τα πορτοφόλια + Αν μια προηγούμενη πληρωμή εκκρεμεί ακόμη, το Bitkit μπορεί να τη στείλει δεύτερη φορά. Αυτό δεν αναιρείται. + Διαγραφή της εγγραφής; + Ποσό: %1$s sats · Διεύθυνση: %2$s · Συναλλαγή: %3$s · Σε αναμονή: %4$s + άγνωστο Το Bitkit δεν μπόρεσε να διαβάσει μια προηγούμενη πληρωμή από αυτό το πορτοφόλι υλικού, οπότε δεν θα υπογράψει νέα. Η διαγραφή αυτής της εγγραφής επιτρέπει στο Bitkit να υπογράφει ξανά. Διάγραψέ την μόνο αν καμία προηγούμενη πληρωμή από αυτό το πορτοφόλι δεν εκκρεμεί ακόμη, αλλιώς η ίδια πληρωμή μπορεί να σταλεί δύο φορές. + Το Bitkit δεν μπόρεσε να διαβάσει το αρχείο του με τις προηγούμενες πληρωμές από πορτοφόλια υλικού, οπότε δεν θα υπογράψει νέα από κανένα πορτοφόλι υλικού. Η διαγραφή του αρχείου για όλα τα πορτοφόλια υλικού επιτρέπει στο Bitkit να υπογράφει ξανά. Διάγραψέ το μόνο αν καμία προηγούμενη πληρωμή από πορτοφόλι υλικού δεν εκκρεμεί ακόμη, αλλιώς η ίδια πληρωμή μπορεί να σταλεί δύο φορές. Δεν είναι δυνατή η ανάγνωση προηγούμενης πληρωμής Πρόσθεσε το <accent>πορτοφόλι υλικού</accent> σου Σύνδεσε τη συσκευή υλικού σου για να παρακολουθείς ή να διαχειρίζεσαι τα μακροπρόθεσμα κεφάλαιά σου. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 76fcd9a16a..c5dbdb620d 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1173,7 +1173,13 @@ ¿Quieres vincular de forma segura este %1$s con Bitkit? Dispositivo encontrado Borrar registro + Borrar para todos los monederos + Si un pago anterior sigue pendiente, Bitkit podría enviarlo por segunda vez. Esto no se puede deshacer. + ¿Borrar el registro? + Importe: %1$s sats · Dirección: %2$s · Transacción: %3$s · Retenido: %4$s + desconocido Bitkit no pudo leer un pago anterior de este monedero de hardware, así que no firmará uno nuevo. Borrar ese registro permite que Bitkit vuelva a firmar. Bórralo solo si ningún pago anterior de este monedero sigue pendiente, o el mismo pago podría enviarse dos veces. + Bitkit no pudo leer su registro de pagos anteriores con monedero de hardware, así que no firmará uno nuevo desde ningún monedero de hardware. Borrar el registro de todos los monederos de hardware permite que Bitkit vuelva a firmar. Bórralo solo si ningún pago anterior con monedero de hardware sigue pendiente, o el mismo pago podría enviarse dos veces. No se puede leer un pago anterior Añade tu <accent>monedero de hardware</accent> Conecta tu dispositivo de hardware para supervisar o gestionar tus fondos a largo plazo. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index b5eab7f640..9b84a908c7 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1171,7 +1171,13 @@ ¿Desea vincular de forma segura este %1$s con Bitkit? Dispositivo encontrado Borrar registro + Borrar para todos los monederos + Si un pago anterior sigue pendiente, Bitkit podría enviarlo por segunda vez. Esto no se puede deshacer. + ¿Borrar el registro? + Importe: %1$s sats · Dirección: %2$s · Transacción: %3$s · Retenido: %4$s + desconocido Bitkit no pudo leer un pago anterior de este monedero de hardware, así que no firmará uno nuevo. Borrar ese registro permite que Bitkit vuelva a firmar. Bórrelo solo si ningún pago anterior de este monedero sigue pendiente, o el mismo pago podría enviarse dos veces. + Bitkit no pudo leer su registro de pagos anteriores con monedero de hardware, así que no firmará uno nuevo desde ningún monedero de hardware. Borrar el registro de todos los monederos de hardware permite que Bitkit vuelva a firmar. Bórrelo solo si ningún pago anterior con monedero de hardware sigue pendiente, o el mismo pago podría enviarse dos veces. No se puede leer un pago anterior Añada su <accent>monedero de hardware</accent> Conecte su dispositivo de hardware para supervisar o gestionar sus fondos a largo plazo. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f0f21cb382..91f318e7f4 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1177,7 +1177,13 @@ Voulez-vous associer ce %1$s à Bitkit en toute sécurité ? Appareil trouvé Effacer l\'enregistrement + Effacer pour tous les portefeuilles + Si un paiement précédent est encore en attente, Bitkit pourrait l\'envoyer une seconde fois. Cette action est irréversible. + Effacer l\'enregistrement ? + Montant : %1$s sats · Adresse : %2$s · Transaction : %3$s · Retenu : %4$s + inconnu Bitkit n\'a pas pu lire un paiement précédent de ce portefeuille matériel et n\'en signera donc pas de nouveau. Effacer cet enregistrement permet à Bitkit de signer à nouveau. Ne l\'effacez que si aucun paiement précédent de ce portefeuille n\'est encore en attente, sinon le même paiement pourrait être envoyé deux fois. + Bitkit n\'a pas pu lire son registre des paiements précédents par portefeuille matériel et n\'en signera donc pas de nouveau depuis aucun portefeuille matériel. Effacer le registre pour tous les portefeuilles matériels permet à Bitkit de signer à nouveau. Ne l\'effacez que si aucun paiement précédent par portefeuille matériel n\'est encore en attente, sinon le même paiement pourrait être envoyé deux fois. Paiement précédent illisible Ajoutez votre <accent>portefeuille</accent> Connectez votre appareil matériel pour suivre ou gérer vos fonds à long terme. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index d6fe20b0db..0fe7cc9914 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1177,7 +1177,13 @@ Vuoi associare in modo sicuro questo %1$s a Bitkit? Dispositivo Trovato Cancella registro + Cancella per tutti i wallet + Se un pagamento precedente è ancora in sospeso, Bitkit potrebbe inviarlo una seconda volta. L\'operazione non può essere annullata. + Cancellare il registro? + Importo: %1$s sats · Indirizzo: %2$s · Transazione: %3$s · Trattenuto: %4$s + sconosciuto Bitkit non è riuscito a leggere un pagamento precedente da questo hardware wallet, quindi non ne firmerà uno nuovo. Cancellare quel registro consente a Bitkit di firmare di nuovo. Cancellalo solo se nessun pagamento precedente da questo wallet è ancora in sospeso, altrimenti lo stesso pagamento potrebbe essere inviato due volte. + Bitkit non è riuscito a leggere il registro dei pagamenti precedenti con hardware wallet, quindi non ne firmerà uno nuovo da nessun hardware wallet. Cancellare il registro per tutti gli hardware wallet consente a Bitkit di firmare di nuovo. Cancellalo solo se nessun pagamento precedente con hardware wallet è ancora in sospeso, altrimenti lo stesso pagamento potrebbe essere inviato due volte. Pagamento precedente illeggibile Aggiungi il tuo <accent>hardware wallet</accent> Connetti il tuo dispositivo hardware per monitorare o gestire i tuoi fondi a lungo termine. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index c37e83ff92..aaa7c6bed3 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1174,7 +1174,13 @@ Wilt u deze %1$s veilig koppelen met Bitkit? Apparaat gevonden Gegevens wissen + Wissen voor alle wallets + Als een eerdere betaling nog in behandeling is, kan Bitkit haar een tweede keer verzenden. Dit kan niet ongedaan worden gemaakt. + Gegevens wissen? + Bedrag: %1$s sats · Adres: %2$s · Transactie: %3$s · Vastgehouden: %4$s + onbekend Bitkit kon een eerdere betaling van deze hardwarewallet niet lezen en ondertekent daarom geen nieuwe. Door dat gegeven te wissen kan Bitkit weer ondertekenen. Wis het alleen als geen eerdere betaling van deze wallet nog in behandeling is, anders kan dezelfde betaling twee keer worden verzonden. + Bitkit kon zijn gegevens van eerdere hardwarewalletbetalingen niet lezen en ondertekent daarom vanaf geen enkele hardwarewallet een nieuwe. Door de gegevens voor alle hardwarewallets te wissen kan Bitkit weer ondertekenen. Wis ze alleen als geen eerdere hardwarewalletbetaling nog in behandeling is, anders kan dezelfde betaling twee keer worden verzonden. Eerdere betaling onleesbaar Voeg uw <accent>hardware wallet</accent> toe Verbind uw hardwareapparaat om uw geld voor de lange termijn te volgen of te beheren. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 9e1ebccfe2..1268fc88b3 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1180,7 +1180,13 @@ Czy chcesz bezpiecznie sparować to urządzenie %1$s z Bitkit? Znaleziono urządzenie Wyczyść zapis + Wyczyść dla wszystkich portfeli + Jeśli wcześniejsza płatność nadal oczekuje, Bitkit może wysłać ją po raz drugi. Tej operacji nie można cofnąć. + Wyczyścić zapis? + Kwota: %1$s sats · Adres: %2$s · Transakcja: %3$s · Wstrzymana: %4$s + nieznane Bitkit nie mógł odczytać wcześniejszej płatności z tego portfela sprzętowego, więc nie podpisze nowej. Wyczyszczenie tego zapisu pozwoli Bitkit znowu podpisywać. Wyczyść go tylko wtedy, gdy żadna wcześniejsza płatność z tego portfela nie oczekuje, w przeciwnym razie ta sama płatność może zostać wysłana dwa razy. + Bitkit nie mógł odczytać swojego zapisu wcześniejszych płatności z portfeli sprzętowych, więc nie podpisze nowej z żadnego portfela sprzętowego. Wyczyszczenie zapisu dla wszystkich portfeli sprzętowych pozwoli Bitkit znowu podpisywać. Wyczyść go tylko wtedy, gdy żadna wcześniejsza płatność z portfela sprzętowego nie oczekuje, w przeciwnym razie ta sama płatność może zostać wysłana dwa razy. Nie można odczytać wcześniejszej płatności Dodaj swój <accent>portfel sprzętowy</accent> Połącz urządzenie sprzętowe, aby obserwować lub zarządzać swoimi długoterminowymi środkami. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 015df33d3a..1f693c6681 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1182,7 +1182,13 @@ Deseja parear este %1$s com a Bitkit de forma segura? Dispositivo Encontrado Limpar registro + Limpar para todas as carteiras + Se um pagamento anterior ainda estiver pendente, a Bitkit poderá enviá-lo uma segunda vez. Isso não pode ser desfeito. + Limpar o registro? + Valor: %1$s sats · Endereço: %2$s · Transação: %3$s · Retido: %4$s + desconhecido A Bitkit não conseguiu ler um pagamento anterior desta carteira de hardware, então não vai assinar um novo. Limpar esse registro permite que a Bitkit assine novamente. Só limpe se nenhum pagamento anterior desta carteira ainda estiver pendente, ou o mesmo pagamento poderá ser enviado duas vezes. + A Bitkit não conseguiu ler o registro de pagamentos anteriores com carteira de hardware, então não vai assinar um novo de nenhuma carteira de hardware. Limpar o registro de todas as carteiras de hardware permite que a Bitkit assine novamente. Só limpe se nenhum pagamento anterior com carteira de hardware ainda estiver pendente, ou o mesmo pagamento poderá ser enviado duas vezes. Não é possível ler um pagamento anterior Adicione sua <accent>carteira de hardware</accent> Conecte seu dispositivo de hardware para acompanhar ou gerenciar seus fundos de longo prazo. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 2d948eb916..ae6c6dcb8e 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1148,7 +1148,13 @@ Pretende emparelhar este %1$s de forma segura com a Bitkit? Dispositivo encontrado Limpar registo + Limpar para todas as carteiras + Se um pagamento anterior ainda estiver pendente, a Bitkit poderá enviá-lo uma segunda vez. Isto não pode ser anulado. + Limpar o registo? + Montante: %1$s sats · Endereço: %2$s · Transação: %3$s · Retido: %4$s + desconhecido A Bitkit não conseguiu ler um pagamento anterior desta carteira de hardware, por isso não vai assinar um novo. Limpar esse registo permite que a Bitkit volte a assinar. Só o limpe se nenhum pagamento anterior desta carteira ainda estiver pendente, ou o mesmo pagamento poderá ser enviado duas vezes. + A Bitkit não conseguiu ler o registo de pagamentos anteriores com carteira de hardware, por isso não vai assinar um novo a partir de nenhuma carteira de hardware. Limpar o registo de todas as carteiras de hardware permite que a Bitkit volte a assinar. Só o limpe se nenhum pagamento anterior com carteira de hardware ainda estiver pendente, ou o mesmo pagamento poderá ser enviado duas vezes. Não é possível ler um pagamento anterior Adicione a sua <accent>carteira de hardware</accent> Ligue o seu dispositivo de hardware para acompanhar ou gerir os seus fundos a longo prazo. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 2c56b18b1d..db719ef5bb 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1198,7 +1198,13 @@ Хотите безопасно сопрячь этот %1$s с Bitkit? Устройство Найдено Очистить запись + Очистить для всех кошельков + Если предыдущий платёж ещё ожидает подтверждения, Bitkit может отправить его второй раз. Это действие нельзя отменить. + Очистить запись? + Сумма: %1$s sats · Адрес: %2$s · Транзакция: %3$s · Удержан: %4$s + неизвестно Bitkit не удалось прочитать предыдущий платёж с этого аппаратного кошелька, поэтому новый он подписывать не будет. Очистка этой записи позволит Bitkit снова подписывать. Очищайте её, только если ни один предыдущий платёж с этого кошелька не ожидает подтверждения, иначе один и тот же платёж может быть отправлен дважды. + Bitkit не удалось прочитать запись о предыдущих платежах с аппаратных кошельков, поэтому он не будет подписывать новые ни с одного аппаратного кошелька. Очистка записи для всех аппаратных кошельков позволит Bitkit снова подписывать. Очищайте её, только если ни один предыдущий платёж с аппаратного кошелька не ожидает подтверждения, иначе один и тот же платёж может быть отправлен дважды. Не удаётся прочитать предыдущий платёж Добавьте <accent>кошелёк</accent> Подключите аппаратное устройство, чтобы отслеживать или управлять долгосрочными средствами. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e42959215a..5d9a0c415c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -189,7 +189,13 @@ Would you like to securely pair this %1$s with Bitkit? Found Device Clear record + Clear for all wallets + If an earlier payment is still pending, Bitkit may send it a second time. This cannot be undone. + Clear the record? + Amount: %1$s sats · Address: %2$s · Transaction: %3$s · Held: %4$s + unknown Bitkit could not read an earlier payment from this hardware wallet, so it will not sign a new one. Clearing that record lets Bitkit sign again. Only clear it if no earlier payment from this wallet is still pending, or the same payment could be sent twice. + Bitkit could not read its record of earlier hardware wallet payments, so it will not sign a new one from any hardware wallet. Clearing the record for all hardware wallets lets Bitkit sign again. Only clear it if no earlier hardware wallet payment is still pending, or the same payment could be sent twice. Earlier payment unreadable Add your <accent>hardware wallet</accent> Connect your hardware device to watch or manage your long-term funds. diff --git a/app/src/test/java/to/bitkit/data/HwHeldSendStoreTest.kt b/app/src/test/java/to/bitkit/data/HwHeldSendStoreTest.kt index 631bf2f9ba..7c5fadd707 100644 --- a/app/src/test/java/to/bitkit/data/HwHeldSendStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/HwHeldSendStoreTest.kt @@ -83,6 +83,30 @@ class HwHeldSendStoreTest : BaseUnitTest() { assertEquals(2, sut.load().heldSends.size) } + @Test + fun `a record an earlier version could not read is read again`() = test { + val file = folder.newFile("held.json") + val record = json.encodeToString(HeldHwSend.serializer(), held) + file.writeText("""{"version":1,"heldSends":[],"unreadable":[$record]}""") + + val data = store(file).load() + + assertEquals(listOf(held), data.heldSends) + assertTrue(data.unreadable.isEmpty()) + } + + @Test + fun `an unreadable record tells what can still be read of it`() { + val record = json.parseToJsonElement( + """{"walletId":"wallet-jade","amountSats":5000,"address":"bc1q","txId":"AB","heldAt":1700000000}""", + ) + val unreadable = HwHeldSendData(unreadable = listOf(record)).unreadableErrorFor("wallet-jade") + + assertEquals(listOf(UnreadableHeldSend(5_000uL, "bc1q", "AB", 1_700_000_000L)), unreadable?.records) + assertFalse(unreadable?.clearsAllWallets ?: true) + assertNull(HwHeldSendData(unreadable = listOf(record)).unreadableErrorFor("wallet-trezor")) + } + @Test fun `a record whose wallet cannot be read refuses every wallet`() { val data = HwHeldSendData(unreadable = listOf(JsonObject(mapOf("txId" to JsonPrimitive("AB"))))) diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt index 08ec2a1edb..bee41076fd 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt @@ -27,6 +27,7 @@ import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.eq import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never @@ -36,6 +37,7 @@ import org.mockito.kotlin.whenever import to.bitkit.R import to.bitkit.data.HeldHwSend import to.bitkit.data.HwHeldSendsUnreadableError +import to.bitkit.data.UnreadableHeldSend import to.bitkit.ext.create import to.bitkit.models.HwConnectedDevice import to.bitkit.models.HwFundingBroadcastResult @@ -62,6 +64,7 @@ import to.bitkit.utils.ServiceError import to.bitkit.utils.SignedTransactionId import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock @@ -1062,25 +1065,57 @@ class HwSendViewModelTest : BaseUnitTest() { } @Test - fun `a send whose held records cannot be read is never signed and offers an explicit clear`() = test { + fun `a send whose held records cannot be read is never signed and is cleared only on a second confirmation`() = + test { + whenever(context.getString(any())).thenReturn("text") + whenever(context.getString(R.string.hardware__held_sends_record_unknown)).thenReturn("unknown") + whenever(context.getString(eq(R.string.hardware__held_sends_record), any(), any(), any(), any())) + .thenAnswer { "record ${it.getArgument(1)} ${it.getArgument(2)} ${it.getArgument(3)}" } + stubSuccessfulPayment() + val unreadable = HwHeldSendsUnreadableError( + walletId = WALLET_ID, + records = listOf(UnreadableHeldSend(amountSats = AMOUNT_SATS, txId = SIGNED_TXID)), + clearsAllWallets = false, + ) + whenever(hwWalletRepo.heldSendFor(WALLET_ID, ADDRESS, AMOUNT_SATS)).thenReturn(Result.failure(unreadable)) + whenever(hwWalletRepo.clearUnreadableHeldSends(WALLET_ID)).thenReturn(Result.success(Unit)) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + verify(hwWalletRepo, never()).signFunding(any(), any()) + verify(hwWalletRepo, never()).broadcastFundingAtBoundary(any(), anyOrNull(), any()) + val prompt = assertNotNull(sut.uiState.value.unreadableHeldSends) + assertEquals(WALLET_ID, prompt.walletId) + assertFalse(prompt.clearsAllWallets) + assertTrue(prompt.message.contains("record $AMOUNT_SATS unknown $SIGNED_TXID")) + + sut.clearUnreadableHeldSends() + advanceUntilIdle() + assertTrue(sut.uiState.value.unreadableHeldSends?.isConfirming == true) + verify(hwWalletRepo, never()).clearUnreadableHeldSends(any()) + + sut.clearUnreadableHeldSends() + advanceUntilIdle() + + verify(hwWalletRepo).clearUnreadableHeldSends(WALLET_ID) + assertNull(sut.uiState.value.unreadableHeldSends) + } + + @Test + fun `an unreadable hold file is offered to be cleared for all wallets`() = test { + whenever(context.getString(any())).thenReturn("text") stubSuccessfulPayment() whenever(hwWalletRepo.heldSendFor(WALLET_ID, ADDRESS, AMOUNT_SATS)) - .thenReturn(Result.failure(HwHeldSendsUnreadableError(WALLET_ID))) - whenever(hwWalletRepo.clearUnreadableHeldSends(WALLET_ID)).thenReturn(Result.success(Unit)) + .thenReturn(Result.failure(HwHeldSendsUnreadableError(walletId = null))) sut.signAndBroadcast(request()) advanceUntilIdle() + val prompt = assertNotNull(sut.uiState.value.unreadableHeldSends) + assertTrue(prompt.clearsAllWallets) + assertEquals(WALLET_ID, prompt.walletId) verify(hwWalletRepo, never()).signFunding(any(), any()) - verify(hwWalletRepo, never()).broadcastFundingAtBoundary(any(), anyOrNull(), any()) - assertEquals(WALLET_ID, sut.uiState.value.unreadableHeldSendsWalletId) - verify(hwWalletRepo, never()).clearUnreadableHeldSends(any()) - - sut.clearUnreadableHeldSends() - advanceUntilIdle() - - verify(hwWalletRepo).clearUnreadableHeldSends(WALLET_ID) - assertNull(sut.uiState.value.unreadableHeldSendsWalletId) } @Test @@ -2468,6 +2503,7 @@ class HwSendViewModelTest : BaseUnitTest() { miningFeeSats = signedTx.miningFeeSats, feeRate = signedTx.feeRate, totalSpent = signedTx.totalSpent, + heldAt = now.epochSeconds, ) private fun request() = HwSendRequest( From 0e8f77ff15c698535fb17e74f2e1d1bd65c7d9e6 Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 10:58:09 -0500 Subject: [PATCH 12/14] docs: explain why a refused first hardware broadcast sent nothing Co-Authored-By: Claude Opus 5.5 --- app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt b/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt index 2eb2a31490..c2b13301d8 100644 --- a/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt +++ b/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt @@ -18,8 +18,9 @@ fun Throwable.isDefiniteHardwarePreBroadcastFailure(): Boolean = generateSequenc /** * Whether a hardware broadcast proves it sent nothing: core could not decode the transaction or connect to the - * server. Any other failure may follow the write, and a node that refused the transaction still saw it, so the payment - * may still confirm. + * server. Any other failure may follow the write, so the payment may still confirm. A node refusing the first broadcast + * of a transaction proves the same, as an Electrum server and its node keep nothing they refused, and a missing coin + * there is one already spent; a refusal of a later broadcast proves nothing about the earlier ones. */ fun Throwable.isHardwareBroadcastNotSent(): Boolean = isDefiniteHardwarePreBroadcastFailure() || generateSequence(this) { it.cause }.any { From 416466178f360d44ea922fb23baedb5307f22adc Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 11:15:28 -0500 Subject: [PATCH 13/14] fix: complete a held hardware send seen during broadcast again Co-Authored-By: Claude Opus 5.5 --- .../screens/wallets/send/HwSendSignScreen.kt | 6 +-- .../screens/wallets/send/HwSendViewModel.kt | 35 +++++++++++--- app/src/main/res/values-ar/strings.xml | 2 + app/src/main/res/values-b+es+419/strings.xml | 2 + app/src/main/res/values-ca/strings.xml | 2 + app/src/main/res/values-cs/strings.xml | 2 + app/src/main/res/values-de/strings.xml | 2 + app/src/main/res/values-el/strings.xml | 2 + app/src/main/res/values-es-rES/strings.xml | 2 + app/src/main/res/values-es/strings.xml | 2 + app/src/main/res/values-fr/strings.xml | 2 + app/src/main/res/values-it/strings.xml | 2 + app/src/main/res/values-nl/strings.xml | 2 + app/src/main/res/values-pl/strings.xml | 2 + app/src/main/res/values-pt-rBR/strings.xml | 2 + app/src/main/res/values-pt/strings.xml | 2 + app/src/main/res/values-ru/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + .../wallets/send/HwSendViewModelTest.kt | 46 +++++++++++++++++++ 19 files changed, 107 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt index d43a15baba..c3fea219bf 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendSignScreen.kt @@ -143,11 +143,7 @@ fun HwSendSignScreen( R.string.hardware__held_sends_unreadable_title }, ), - text = if (prompt.isConfirming) { - stringResource(R.string.hardware__held_sends_clear_confirm_text) - } else { - prompt.message - }, + text = if (prompt.isConfirming) prompt.confirmMessage else prompt.message, confirmText = clearText, confirmTextColor = Colors.Red, onConfirm = viewModel::clearUnreadableHeldSends, diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index 9e61700122..45eb936a92 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -94,6 +94,9 @@ class HwSendViewModel @Inject constructor( val COMPOSE_TIMEOUT = 45.seconds val SIGN_TIMEOUT = 120.seconds + /** How long the second confirmation of a clear of unreadable held sends ignores taps. */ + val CLEAR_CONFIRM_DELAY = 1.seconds + /** How long the sheet waits for a broadcast before showing it as pending; the broadcast itself runs on. */ val BROADCAST_WAIT = 60.seconds } @@ -114,6 +117,7 @@ class HwSendViewModel @Inject constructor( private var pendingBroadcast: PendingHwSendBroadcast? = null private val unresolvedSends = mutableMapOf() + private var clearConfirmableAt: Instant? = null private var signingWalletId: String? = null private var signingJob: Job? = null private var signingAttempt = 0 @@ -528,18 +532,17 @@ class HwSendViewModel @Inject constructor( private suspend fun releaseIfNeverConfirming(unresolved: UnresolvedHwSend, error: Throwable): Boolean { if (!isProvenNeverConfirming(unresolved.payment, error)) return false - if (unresolvedSends[unresolved.send.txId] !== unresolved) return true - // A transaction the wallet has seen went out, whatever a node says about it now - if (isSeenByWallet(unresolved.send.walletId, unresolved.send.txId)) { - completeUnresolvedSend(unresolved) - return true - } releaseUnresolvedSend(unresolved, R.string.hardware__send_broadcast_rejected_text) return true } private suspend fun releaseUnresolvedSend(unresolved: UnresolvedHwSend, @StringRes description: Int) { if (unresolvedSends[unresolved.send.txId] !== unresolved) return + // A transaction the wallet has seen went out, whatever this broadcast's answer says + if (isSeenByWallet(unresolved.send.walletId, unresolved.send.txId)) { + completeUnresolvedSend(unresolved) + return + } Logger.warn("Released held hardware send '${unresolved.send.txId}' that was never sent", context = TAG) forgetUnresolvedSend(unresolved) releaseHeldSend(unresolved.send.txId) @@ -648,6 +651,12 @@ class HwSendViewModel @Inject constructor( toastBroadcastFailed() return@launch } + // The wallet may have seen it, and its hold been released, since this was asked for: it went out + if (isSeenByWallet(send.walletId, send.txId)) { + isNotSent = true + completeUnresolvedSend(unresolved) + return@launch + } val outcome = hwWalletRepo.broadcastFunding(unresolved.payment.signedTx) isNotSent = outcome.exceptionOrNull()?.isHardwareBroadcastNotSent() == true heldDispatches.finish(tracked, isNotSent) @@ -755,10 +764,13 @@ class HwSendViewModel @Inject constructor( fun clearUnreadableHeldSends() { val prompt = _uiState.value.unreadableHeldSends ?: return if (!prompt.isConfirming) { - // A clear that may send a payment twice is asked a second time + // A clear that may send a payment twice is asked a second time, which a fast double tap cannot answer + val confirmableAt = clock.now() + CLEAR_CONFIRM_DELAY _uiState.update { it.copy(unreadableHeldSends = prompt.copy(isConfirming = true)) } + clearConfirmableAt = confirmableAt return } + if (clearConfirmableAt?.let { clock.now() < it } == true) return _uiState.update { it.copy(unreadableHeldSends = null) } viewModelScope.launch { hwWalletRepo.clearUnreadableHeldSends(prompt.walletId).onFailure { @@ -792,6 +804,13 @@ class HwSendViewModel @Inject constructor( walletId = this.walletId ?: walletId, message = (listOf(explanation) + details).joinToString("\n\n"), clearsAllWallets = clearsAllWallets, + confirmMessage = context.getString( + when { + this.walletId == null -> R.string.hardware__held_sends_clear_confirm_text_file + clearsAllWallets -> R.string.hardware__held_sends_clear_confirm_text_unknown_wallet + else -> R.string.hardware__held_sends_clear_confirm_text + }, + ), ) } @@ -1076,6 +1095,8 @@ data class UnreadableHeldSendsPrompt( val walletId: String, val message: String, val clearsAllWallets: Boolean, + /** What the second confirmation says gets cleared. */ + val confirmMessage: String, val isConfirming: Boolean = false, ) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index d79950e0c5..254fe4ab1b 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1152,6 +1152,8 @@ مسح السجل مسح لجميع المحافظ إذا كانت دفعة سابقة لا تزال معلقة، فقد يرسلها Bitkit مرة ثانية. لا يمكن التراجع عن ذلك. + يحذف هذا كل سجلات الدفعات المحجوزة لجميع محافظ الأجهزة، بما فيها التي لا يزال Bitkit قادرًا على قراءتها. إذا كانت دفعة سابقة لا تزال معلقة، فقد يرسلها Bitkit مرة ثانية. لا يمكن التراجع عن ذلك. + يحذف هذا سجلات الدفعات غير المقروءة لهذه المحفظة وتلك التي لا يستطيع Bitkit قراءة محفظتها، والتي قد تخص أي محفظة أجهزة. تبقى السجلات المقروءة. إذا كانت دفعة سابقة لا تزال معلقة، فقد يرسلها Bitkit مرة ثانية. لا يمكن التراجع عن ذلك. مسح السجل؟ المبلغ: %1$s sats · العنوان: %2$s · المعاملة: %3$s · محجوزة: %4$s غير معروف diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 78c3f54e23..93734d9df5 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1185,6 +1185,8 @@ Borrar registro Borrar para todas las billeteras Si un pago anterior sigue pendiente, Bitkit podría enviarlo por segunda vez. Esto no se puede deshacer. + Esto elimina todos los registros de pagos retenidos de todas las billeteras de hardware, incluidos los que Bitkit aún puede leer. Si un pago anterior sigue pendiente, Bitkit podría enviarlo por segunda vez. Esto no se puede deshacer. + Esto elimina los registros de pagos ilegibles de esta billetera y aquellos cuya billetera Bitkit no puede leer, que pueden pertenecer a cualquier billetera de hardware. Los registros legibles se conservan. Si un pago anterior sigue pendiente, Bitkit podría enviarlo por segunda vez. Esto no se puede deshacer. ¿Borrar el registro? Monto: %1$s sats · Dirección: %2$s · Transacción: %3$s · Retenido: %4$s desconocido diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 6f2ad8475f..ce8e0c2539 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1177,6 +1177,8 @@ Esborrar el registre Esborrar per a totes les carteres Si un pagament anterior continua pendent, Bitkit el podria enviar una segona vegada. Això no es pot desfer. + Això esborra tots els registres de pagaments retinguts de totes les carteres de maquinari, inclosos els que Bitkit encara pot llegir. Si un pagament anterior continua pendent, Bitkit el podria enviar una segona vegada. Això no es pot desfer. + Això esborra els registres de pagaments il·legibles d\'aquesta cartera i aquells la cartera dels quals Bitkit no pot llegir, que poden pertànyer a qualsevol cartera de maquinari. Els registres llegibles es mantenen. Si un pagament anterior continua pendent, Bitkit el podria enviar una segona vegada. Això no es pot desfer. Vols esborrar el registre? Import: %1$s sats · Adreça: %2$s · Transacció: %3$s · Retingut: %4$s desconegut diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index af35a1f0b4..0a8e434f30 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1183,6 +1183,8 @@ Smazat záznam Smazat pro všechny peněženky Pokud dřívější platba stále čeká, Bitkit ji může odeslat podruhé. Tuto akci nelze vrátit zpět. + Tímto se smažou všechny záznamy držených plateb všech hardwarových peněženek, včetně těch, které Bitkit stále dokáže přečíst. Pokud dřívější platba stále čeká, Bitkit ji může odeslat podruhé. Tuto akci nelze vrátit zpět. + Tímto se smažou nečitelné záznamy plateb této peněženky a ty, jejichž peněženku Bitkit nedokáže přečíst a které mohou patřit kterékoli hardwarové peněžence. Čitelné záznamy zůstanou. Pokud dřívější platba stále čeká, Bitkit ji může odeslat podruhé. Tuto akci nelze vrátit zpět. Smazat záznam? Částka: %1$s sats · Adresa: %2$s · Transakce: %3$s · Drženo: %4$s neznámé diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 9433446c0d..f6761d594c 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1180,6 +1180,8 @@ Aufzeichnung löschen Für alle Wallets löschen Steht eine frühere Zahlung noch aus, sendet Bitkit sie möglicherweise ein zweites Mal. Dies kann nicht rückgängig gemacht werden. + Dadurch werden alle Aufzeichnungen gehaltener Zahlungen aller Hardware-Wallets gelöscht, auch die, die Bitkit noch lesen kann. Steht eine frühere Zahlung noch aus, sendet Bitkit sie möglicherweise ein zweites Mal. Dies kann nicht rückgängig gemacht werden. + Dadurch werden die nicht lesbaren Zahlungsaufzeichnungen dieses Wallets gelöscht sowie die, deren Wallet Bitkit nicht lesen kann und die zu jedem Hardware-Wallet gehören können. Lesbare Aufzeichnungen bleiben erhalten. Steht eine frühere Zahlung noch aus, sendet Bitkit sie möglicherweise ein zweites Mal. Dies kann nicht rückgängig gemacht werden. Aufzeichnung löschen? Betrag: %1$s sats · Adresse: %2$s · Transaktion: %3$s · Gehalten: %4$s unbekannt diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 0e34d65a2a..256f3ac84f 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1158,6 +1158,8 @@ Διαγραφή εγγραφής Διαγραφή για όλα τα πορτοφόλια Αν μια προηγούμενη πληρωμή εκκρεμεί ακόμη, το Bitkit μπορεί να τη στείλει δεύτερη φορά. Αυτό δεν αναιρείται. + Αυτό διαγράφει όλες τις εγγραφές πληρωμών σε αναμονή όλων των πορτοφολιών υλικού, ακόμη και όσες μπορεί ακόμη να διαβάσει το Bitkit. Αν μια προηγούμενη πληρωμή εκκρεμεί ακόμη, το Bitkit μπορεί να τη στείλει δεύτερη φορά. Αυτό δεν αναιρείται. + Αυτό διαγράφει τις μη αναγνώσιμες εγγραφές πληρωμών αυτού του πορτοφολιού και εκείνες των οποίων το πορτοφόλι δεν μπορεί να διαβάσει το Bitkit, που μπορεί να ανήκουν σε οποιοδήποτε πορτοφόλι υλικού. Οι αναγνώσιμες εγγραφές παραμένουν. Αν μια προηγούμενη πληρωμή εκκρεμεί ακόμη, το Bitkit μπορεί να τη στείλει δεύτερη φορά. Αυτό δεν αναιρείται. Διαγραφή της εγγραφής; Ποσό: %1$s sats · Διεύθυνση: %2$s · Συναλλαγή: %3$s · Σε αναμονή: %4$s άγνωστο diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index c5dbdb620d..de7b66269a 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1175,6 +1175,8 @@ Borrar registro Borrar para todos los monederos Si un pago anterior sigue pendiente, Bitkit podría enviarlo por segunda vez. Esto no se puede deshacer. + Esto elimina todos los registros de pagos retenidos de todos los monederos de hardware, incluidos los que Bitkit aún puede leer. Si un pago anterior sigue pendiente, Bitkit podría enviarlo por segunda vez. Esto no se puede deshacer. + Esto elimina los registros de pagos ilegibles de este monedero y aquellos cuyo monedero Bitkit no puede leer, que pueden pertenecer a cualquier monedero de hardware. Los registros legibles se conservan. Si un pago anterior sigue pendiente, Bitkit podría enviarlo por segunda vez. Esto no se puede deshacer. ¿Borrar el registro? Importe: %1$s sats · Dirección: %2$s · Transacción: %3$s · Retenido: %4$s desconocido diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 9b84a908c7..ea58eb0d57 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1173,6 +1173,8 @@ Borrar registro Borrar para todos los monederos Si un pago anterior sigue pendiente, Bitkit podría enviarlo por segunda vez. Esto no se puede deshacer. + Esto elimina todos los registros de pagos retenidos de todos los monederos de hardware, incluidos los que Bitkit aún puede leer. Si un pago anterior sigue pendiente, Bitkit podría enviarlo por segunda vez. Esto no se puede deshacer. + Esto elimina los registros de pagos ilegibles de este monedero y aquellos cuyo monedero Bitkit no puede leer, que pueden pertenecer a cualquier monedero de hardware. Los registros legibles se conservan. Si un pago anterior sigue pendiente, Bitkit podría enviarlo por segunda vez. Esto no se puede deshacer. ¿Borrar el registro? Importe: %1$s sats · Dirección: %2$s · Transacción: %3$s · Retenido: %4$s desconocido diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 91f318e7f4..b1a3d59871 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1179,6 +1179,8 @@ Effacer l\'enregistrement Effacer pour tous les portefeuilles Si un paiement précédent est encore en attente, Bitkit pourrait l\'envoyer une seconde fois. Cette action est irréversible. + Cela supprime tous les enregistrements de paiements retenus de tous les portefeuilles matériels, y compris ceux que Bitkit peut encore lire. Si un paiement précédent est encore en attente, Bitkit pourrait l\'envoyer une seconde fois. Cette action est irréversible. + Cela supprime les enregistrements de paiement illisibles de ce portefeuille et ceux dont Bitkit ne peut pas lire le portefeuille, qui peuvent appartenir à n\'importe quel portefeuille matériel. Les enregistrements lisibles sont conservés. Si un paiement précédent est encore en attente, Bitkit pourrait l\'envoyer une seconde fois. Cette action est irréversible. Effacer l\'enregistrement ? Montant : %1$s sats · Adresse : %2$s · Transaction : %3$s · Retenu : %4$s inconnu diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 0fe7cc9914..cf76a84d0b 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1179,6 +1179,8 @@ Cancella registro Cancella per tutti i wallet Se un pagamento precedente è ancora in sospeso, Bitkit potrebbe inviarlo una seconda volta. L\'operazione non può essere annullata. + Questo elimina tutti i registri dei pagamenti trattenuti di tutti gli hardware wallet, compresi quelli che Bitkit riesce ancora a leggere. Se un pagamento precedente è ancora in sospeso, Bitkit potrebbe inviarlo una seconda volta. L\'operazione non può essere annullata. + Questo elimina i registri di pagamento illeggibili di questo wallet e quelli di cui Bitkit non riesce a leggere il wallet, che possono appartenere a qualsiasi hardware wallet. I registri leggibili restano. Se un pagamento precedente è ancora in sospeso, Bitkit potrebbe inviarlo una seconda volta. L\'operazione non può essere annullata. Cancellare il registro? Importo: %1$s sats · Indirizzo: %2$s · Transazione: %3$s · Trattenuto: %4$s sconosciuto diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index aaa7c6bed3..dbcce710f1 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1176,6 +1176,8 @@ Gegevens wissen Wissen voor alle wallets Als een eerdere betaling nog in behandeling is, kan Bitkit haar een tweede keer verzenden. Dit kan niet ongedaan worden gemaakt. + Hiermee worden alle gegevens van vastgehouden betalingen van alle hardwarewallets verwijderd, ook die Bitkit nog kan lezen. Als een eerdere betaling nog in behandeling is, kan Bitkit haar een tweede keer verzenden. Dit kan niet ongedaan worden gemaakt. + Hiermee worden de onleesbare betalingsgegevens van deze wallet verwijderd, en die waarvan Bitkit de wallet niet kan lezen en die bij elke hardwarewallet kunnen horen. Leesbare gegevens blijven bewaard. Als een eerdere betaling nog in behandeling is, kan Bitkit haar een tweede keer verzenden. Dit kan niet ongedaan worden gemaakt. Gegevens wissen? Bedrag: %1$s sats · Adres: %2$s · Transactie: %3$s · Vastgehouden: %4$s onbekend diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 1268fc88b3..6015086501 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1182,6 +1182,8 @@ Wyczyść zapis Wyczyść dla wszystkich portfeli Jeśli wcześniejsza płatność nadal oczekuje, Bitkit może wysłać ją po raz drugi. Tej operacji nie można cofnąć. + Spowoduje to usunięcie wszystkich zapisów wstrzymanych płatności wszystkich portfeli sprzętowych, także tych, które Bitkit nadal potrafi odczytać. Jeśli wcześniejsza płatność nadal oczekuje, Bitkit może wysłać ją po raz drugi. Tej operacji nie można cofnąć. + Spowoduje to usunięcie nieczytelnych zapisów płatności tego portfela oraz tych, których portfela Bitkit nie potrafi odczytać i które mogą należeć do dowolnego portfela sprzętowego. Czytelne zapisy pozostaną. Jeśli wcześniejsza płatność nadal oczekuje, Bitkit może wysłać ją po raz drugi. Tej operacji nie można cofnąć. Wyczyścić zapis? Kwota: %1$s sats · Adres: %2$s · Transakcja: %3$s · Wstrzymana: %4$s nieznane diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 1f693c6681..fa9067a81e 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1184,6 +1184,8 @@ Limpar registro Limpar para todas as carteiras Se um pagamento anterior ainda estiver pendente, a Bitkit poderá enviá-lo uma segunda vez. Isso não pode ser desfeito. + Isso apaga todos os registros de pagamentos retidos de todas as carteiras de hardware, inclusive os que a Bitkit ainda consegue ler. Se um pagamento anterior ainda estiver pendente, a Bitkit poderá enviá-lo uma segunda vez. Isso não pode ser desfeito. + Isso apaga os registros de pagamento ilegíveis desta carteira e aqueles cuja carteira a Bitkit não consegue ler, que podem pertencer a qualquer carteira de hardware. Os registros legíveis permanecem. Se um pagamento anterior ainda estiver pendente, a Bitkit poderá enviá-lo uma segunda vez. Isso não pode ser desfeito. Limpar o registro? Valor: %1$s sats · Endereço: %2$s · Transação: %3$s · Retido: %4$s desconhecido diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index ae6c6dcb8e..7ce2e3a696 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1150,6 +1150,8 @@ Limpar registo Limpar para todas as carteiras Se um pagamento anterior ainda estiver pendente, a Bitkit poderá enviá-lo uma segunda vez. Isto não pode ser anulado. + Isto apaga todos os registos de pagamentos retidos de todas as carteiras de hardware, incluindo os que a Bitkit ainda consegue ler. Se um pagamento anterior ainda estiver pendente, a Bitkit poderá enviá-lo uma segunda vez. Isto não pode ser anulado. + Isto apaga os registos de pagamento ilegíveis desta carteira e aqueles cuja carteira a Bitkit não consegue ler, que podem pertencer a qualquer carteira de hardware. Os registos legíveis mantêm-se. Se um pagamento anterior ainda estiver pendente, a Bitkit poderá enviá-lo uma segunda vez. Isto não pode ser anulado. Limpar o registo? Montante: %1$s sats · Endereço: %2$s · Transação: %3$s · Retido: %4$s desconhecido diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index db719ef5bb..4232e04b68 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1200,6 +1200,8 @@ Очистить запись Очистить для всех кошельков Если предыдущий платёж ещё ожидает подтверждения, Bitkit может отправить его второй раз. Это действие нельзя отменить. + Будут удалены все записи об удерживаемых платежах всех аппаратных кошельков, включая те, которые Bitkit ещё может прочитать. Если предыдущий платёж ещё ожидает подтверждения, Bitkit может отправить его второй раз. Это действие нельзя отменить. + Будут удалены нечитаемые записи о платежах этого кошелька и те, чей кошелёк Bitkit не может прочитать и которые могут относиться к любому аппаратному кошельку. Читаемые записи сохранятся. Если предыдущий платёж ещё ожидает подтверждения, Bitkit может отправить его второй раз. Это действие нельзя отменить. Очистить запись? Сумма: %1$s sats · Адрес: %2$s · Транзакция: %3$s · Удержан: %4$s неизвестно diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 5d9a0c415c..9c249d4cbd 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -191,6 +191,8 @@ Clear record Clear for all wallets If an earlier payment is still pending, Bitkit may send it a second time. This cannot be undone. + This deletes every held payment record of all hardware wallets, including the ones Bitkit can still read. If an earlier payment is still pending, Bitkit may send it a second time. This cannot be undone. + This deletes the unreadable payment records of this wallet and those whose wallet Bitkit cannot read, which may belong to any hardware wallet. Readable records stay. If an earlier payment is still pending, Bitkit may send it a second time. This cannot be undone. Clear the record? Amount: %1$s sats · Address: %2$s · Transaction: %3$s · Held: %4$s unknown diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt index bee41076fd..8ec54d0414 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt @@ -734,6 +734,46 @@ class HwSendViewModelTest : BaseUnitTest() { verify(hwWalletRepo, never()).releaseHeldSend(any()) } + @Test + fun `a broadcast again the wallet saw meanwhile is completed as sent instead of dispatched`() = test { + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + whenever(context.getString(any())).thenReturn("message") + whenever(context.getString(R.string.hardware__send_broadcast_accepted)).thenReturn("accepted") + whenever(context.getString(R.string.hardware__send_not_sent_title)).thenReturn("not sent") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE)), + Result.success(fixture.broadcast), + ) + val events = mutableListOf() + backgroundScope.launch { sut.heldSendEvents.collect { events += it } } + + sut.signAndBroadcast(request()) + advanceUntilIdle() + // The wallet sees the transaction, and its stored hold is released, while the broadcast again writes its hold + val seen = MutableStateFlow>(persistentListOf(sentActivity())) + whenever(hwWalletRepo.holdSend(any())).doSuspendableAnswer { + whenever(hwWalletRepo.activities).thenReturn(seen) + Result.success(Unit) + } + sut.retryUnresolvedSend(SIGNED_TXID) + advanceUntilIdle() + toastJob.cancel() + + verify(hwWalletRepo, times(1)).broadcastFunding(fixture.signedTx) + assertEquals( + listOf(HeldHwSendEvent.Completed(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS))), + events, + ) + assertTrue(toasts.none { it.title == "accepted" || it.title == "not sent" }) + inOrder(hwWalletRepo) { + verify(hwWalletRepo, times(2)).holdSend(heldSend(fixture.signedTx)) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) + } + assertTrue(sut.uiState.value.retryingSendTxIds.isEmpty()) + } + @Test fun `a broadcast that never answers stops blocking broadcast again after two minutes`() = test { val toasts = mutableListOf() @@ -1093,8 +1133,12 @@ class HwSendViewModelTest : BaseUnitTest() { sut.clearUnreadableHeldSends() advanceUntilIdle() assertTrue(sut.uiState.value.unreadableHeldSends?.isConfirming == true) + // A fast double tap does not answer the second confirmation too + sut.clearUnreadableHeldSends() + advanceUntilIdle() verify(hwWalletRepo, never()).clearUnreadableHeldSends(any()) + now += 1.seconds sut.clearUnreadableHeldSends() advanceUntilIdle() @@ -1105,6 +1149,7 @@ class HwSendViewModelTest : BaseUnitTest() { @Test fun `an unreadable hold file is offered to be cleared for all wallets`() = test { whenever(context.getString(any())).thenReturn("text") + whenever(context.getString(R.string.hardware__held_sends_clear_confirm_text_file)).thenReturn("every record") stubSuccessfulPayment() whenever(hwWalletRepo.heldSendFor(WALLET_ID, ADDRESS, AMOUNT_SATS)) .thenReturn(Result.failure(HwHeldSendsUnreadableError(walletId = null))) @@ -1113,6 +1158,7 @@ class HwSendViewModelTest : BaseUnitTest() { advanceUntilIdle() val prompt = assertNotNull(sut.uiState.value.unreadableHeldSends) + assertEquals("every record", prompt.confirmMessage) assertTrue(prompt.clearsAllWallets) assertEquals(WALLET_ID, prompt.walletId) verify(hwWalletRepo, never()).signFunding(any(), any()) From 7faf634010bbe162f5048f60d4cf84f3a2b0594d Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 11:37:15 -0500 Subject: [PATCH 14/14] chore: add changelog fragment Co-Authored-By: Claude Opus 5.5 --- changelog.d/next/1772.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/1772.fixed.md diff --git a/changelog.d/next/1772.fixed.md b/changelog.d/next/1772.fixed.md new file mode 100644 index 0000000000..ffb96127a2 --- /dev/null +++ b/changelog.d/next/1772.fixed.md @@ -0,0 +1 @@ +A hardware wallet payment whose broadcast may have reached the network now stays pending and is only ever sent again as the same signed transaction, so it can never be paid twice.