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..3c44f14680 --- /dev/null +++ b/app/src/main/java/to/bitkit/data/HwHeldSendStore.kt @@ -0,0 +1,236 @@ +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) } + + /** + * 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. + */ +@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, + /** 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 = 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 + + override val defaultValue = HwHeldSendData() + + override suspend fun readFrom(input: InputStream): HwHeldSendData = try { + val root = json.parseToJsonElement(input.readBytes().decodeToString()).jsonObject + 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 }, + ) + } 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 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/ext/BroadcastExceptionExt.kt b/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt index 076410ed36..c2b13301d8 100644 --- a/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt +++ b/app/src/main/java/to/bitkit/ext/BroadcastExceptionExt.kt @@ -16,22 +16,88 @@ 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. 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 { + 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)) { @@ -42,23 +108,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", @@ -66,8 +121,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..631820acc7 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/HwHeldDispatchTracker.kt @@ -0,0 +1,86 @@ +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 +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 + * 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() { + 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()) + + /** 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 + // 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 { + 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 83f317c055..9b4035a92b 100644 --- a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt @@ -35,6 +35,9 @@ 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.HwHeldSendStore +import to.bitkit.data.HwHeldSendsUnreadableError import to.bitkit.data.HwWalletStore import to.bitkit.data.PendingNameUpdate import to.bitkit.data.SettingsStore @@ -71,6 +74,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 @@ -95,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, ) { @@ -110,6 +115,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. */ @@ -277,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. */ @@ -898,6 +908,76 @@ 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 { hwHeldSendStore.holdSend(send) } + } + + suspend fun releaseHeldSend(txId: String): Result = withContext(ioDispatcher) { + runSuspendCatching { hwHeldSendStore.releaseHeldSends(setOf(txId)) } + } + + /** + * 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 { + val data = hwHeldSendStore.load() + data.unreadableErrorFor(walletId)?.let { throw it } + 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 + * 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 } + } + } + } + /** Fresh backend observation of this exact transaction in the original hardware wallet. */ suspend fun observeExactTransaction( walletId: String, @@ -1115,6 +1195,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 703136b785..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 @@ -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 @@ -56,6 +57,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 +87,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( @@ -106,6 +111,46 @@ 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, + ) + } + + 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( + if (prompt.isConfirming) { + R.string.hardware__held_sends_clear_confirm_title + } else { + R.string.hardware__held_sends_unreadable_title + }, + ), + text = if (prompt.isConfirming) prompt.confirmMessage else prompt.message, + confirmText = clearText, + confirmTextColor = Colors.Red, + 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 3cd0b4f7d3..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 @@ -1,24 +1,47 @@ 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 +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 +import kotlinx.collections.immutable.ImmutableSet +import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.persistentSetOf +import kotlinx.collections.immutable.toImmutableList 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.delay +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 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.data.HwHeldSendsUnreadableError +import to.bitkit.ext.formatToString 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 import to.bitkit.ext.isHwFirmwareError @@ -31,6 +54,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 @@ -41,11 +66,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 @@ -58,13 +86,19 @@ 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 { const val TAG = "HwSendViewModel" val COMPOSE_TIMEOUT = 45.seconds val SIGN_TIMEOUT = 120.seconds - val BROADCAST_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 } val wallets: StateFlow> @@ -76,12 +110,26 @@ 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 val unresolvedSends = mutableMapOf() + private var clearConfirmableAt: Instant? = null private var signingWalletId: String? = null private var signingJob: Job? = null private var signingAttempt = 0 private var passphraseJob: Job? = null + init { + dropUnresolvedSendsOfRemovedWallets() + viewModelScope.launch { + heldDispatches.inFlight.collect { txIds -> _uiState.update { it.copy(retryingSendTxIds = txIds) } } + } + } + fun warmUp(walletId: String) { hwWalletRepo.warmUpKnownDevice(walletId) } @@ -101,6 +149,13 @@ class HwSendViewModel @Inject constructor( val finishSubmission = beginPaymentSubmission() try { runCatching { + // A payment whose broadcast may have gone out is only ever broadcast again as the same bytes + unresolvedSendFor(request)?.let { unresolved -> + Logger.warn("Broadcasting held hardware send of '${request.walletId}' again", context = TAG) + _uiState.update { it.copy(unresolvedSend = unresolved.send) } + retryUnresolvedSend(unresolved.send.txId) + return@runCatching + } if (pendingBroadcast?.matches(request) == false) { ToastEventBus.send( type = Toast.ToastType.ERROR, @@ -112,6 +167,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 + } + 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) { + 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) } if (pending == null && request.paymentRequestId != null) { val restored = paykitPaymentProofRepo.retainedHardwareOnchainPayment( @@ -168,9 +239,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( @@ -240,48 +316,409 @@ class HwSendViewModel @Inject constructor( return null } } + val request = payment.request + val requestId = request.paymentRequestId + val txId = SignedTransactionId.fromHex(payment.signedTx.serializedTx) _uiState.update { it.copy(isBroadcastUnresolved = true) } - return withTimeout(BROADCAST_TIMEOUT) { - val request = payment.request - val requestId = request.paymentRequestId - 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) + // 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, 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) { + checkNotNull(heldDispatches.begin(txId)) { "A broadcast of hardware send '$txId' is unanswered" } + .also { expireUnanswered(it) } + } else { + null + } + 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) + } } } - }.getOrElse { error -> - if (generateSequence(error) { it.cause }.any { it is ServiceError.PaymentDeadlineExpired }) { - val request = payment.request - val cleared = request.paymentRequestId?.let { requestId -> + } + // 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, 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 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) + _uiState.update { it.copy(isBroadcastUnresolved = false) } + } else if (requestId == null && error != null && !isDeadlineExpired) { + releaseHeldSend(txId) + } + return outcome.getOrElse { error -> + if (isDeadlineExpired) { + val cleared = requestId?.let { !payment.hasAttemptedBroadcast && paykitPaymentProofRepo.clearHardwareOnchainCandidateBeforeDispatch( - requestId, request.walletId, SignedTransactionId.fromHex(payment.signedTx.serializedTx), + it, request.walletId, txId, request.paymentIdentity, request.address, request.amountSats, payment.hasAttemptedBroadcast, ) } ?: !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 } } + 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 { + 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, + isDispatched: AtomicBoolean, + tracked: HwHeldDispatch?, + ): HwFundingBroadcastResult? { + isAbandoned.set(true) + if (payment.request.paymentRequestId != null) { + // 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(), 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 { 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 + 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) + toastNotSent(description) + _heldSendEvents.emit(HeldHwSendEvent.Released(unresolved.send)) + } + + private fun isSeenByWallet(walletId: String, txId: String): Boolean = + 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( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.hardware__send_not_sent_title), + description = context.getString(description), + ) + + 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) } + } + + 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) + // 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 { seenActivityOf(send.walletId, send.txId, it) != null } + 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(), + ) + } + } + + /** + * 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 + // One dispatch of the same bytes at a time, from any sheet + 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 { + // Written again first, so the send stays held whatever happened to the record since + 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() + 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) + 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 + 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(R.string.hardware__send_broadcast_refused_text), + ) + } + } finally { + heldDispatches.finish(tracked, isNotSent) + } + } + } + + 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), + description = context.getString(R.string.hardware__send_broadcast_failed_text), + ) + + /** + * 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 resumeHeldSend(walletId: String, address: String, amountSats: ULong): HwSendResult? { + val send = unresolvedSends.values.firstOrNull { it.payment.request.isPaymentOf(walletId, address, amountSats) } + ?.send ?: return null + retryUnresolvedSend(send.txId) + return send + } + + 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 + 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(unresolved.payment.request, result) } + .onFailure { Logger.error("Failed to persist hardware send result", it, context = TAG) } + releaseHeldSend(send.txId) + _heldSendEvents.emit(HeldHwSendEvent.Completed(send)) + } + fun submitPassphrase( walletId: String, passphrase: String, @@ -320,6 +757,63 @@ 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 prompt = _uiState.value.unreadableHeldSends ?: return + if (!prompt.isConfirming) { + // 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 { + 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(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, + 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 + }, + ), + ) + } + fun dismissPassphrase() { passphraseJob?.cancel() passphraseJob = null @@ -329,7 +823,7 @@ 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() @@ -499,6 +993,13 @@ 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) + 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) } @@ -519,8 +1020,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), @@ -557,6 +1061,15 @@ data class HwSendUiState( val isBroadcastUnresolved: Boolean = false, val isPassphraseRequired: Boolean = false, val isVerifyingPassphrase: Boolean = false, + /** The held send this sheet's attempt ran into, which the sheet shows as pending. */ + val unresolvedSend: HwSendResult? = null, + /** 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, + /** 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 @@ -575,6 +1088,27 @@ data class HwSendResult( val paymentIdentity: String? = null, ) +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, + /** What the second confirmation says gets cleared. */ + val confirmMessage: String, + val isConfirming: Boolean = false, +) + +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( val walletId: String, val address: String, @@ -584,7 +1118,18 @@ 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 HwBroadcastWaitExpiredError : AppError("Hardware broadcast did not answer in time") + +private class UnresolvedHwSend(val payment: PendingHwSendBroadcast, val send: HwSendResult) { + var watch: Job? = null +} private data class PendingHwSendBroadcast( val request: HwSendRequest, @@ -598,4 +1143,24 @@ 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, heldAt: Long) = 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, + heldAt = heldAt, + ) } + +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/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..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 @@ -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__broadcast_again), + 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..829b794130 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,8 @@ 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 import to.bitkit.ui.screens.wallets.send.PIN_CHECK_RESULT_KEY @@ -133,6 +135,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( @@ -236,6 +248,23 @@ 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) + is HeldHwSendEvent.Released -> appViewModel.hideSheet() + } + } + } LaunchedEffect(hwSendViewModel, navController) { hwSendViewModel.results.collect { result -> val resolved = appViewModel.resolvedHardwarePaymentFor(result.walletId, result.txId) @@ -298,7 +327,19 @@ fun SendSheet( } navController.navigateTo(it.route) { popUpTo(replaced) { inclusive = true } } } - is SendEffect.NavigateToHardwareSign -> navController.navigateTo(SendRoute.HardwareSign) + is SendEffect.NavigateToHardwareSign -> { + // 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.resumeHeldSend(walletId, state.address, state.amount) + } + 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 +612,7 @@ fun SendSheet( appViewModel.onHardwareSignCancelled() if (!navController.popBackStack()) appViewModel.hideSheet() }, + onPaymentPending = { navController.navigateToHardwareSendPending(it) }, ) } composableWithDefaultTransitions { @@ -718,6 +760,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 +810,11 @@ fun SendSheet( onClose = { appViewModel.hideSheet() }, onViewDetails = { rawId -> appViewModel.navigateToActivity(rawId, route.walletId) }, viewModel = hiltViewModel(), + canRetryHardwareSend = hwSendUiState.unresolvedSends.any { send -> + send.walletId == route.walletId && send.txId.equals(route.paymentHash, ignoreCase = true) + }, + isRetryingHardwareSend = route.paymentHash.lowercase() in hwSendUiState.retryingSendTxIds, + onRetryHardwareSend = { hwSendViewModel.retryUnresolvedSend(route.paymentHash) }, ) } composableWithDefaultTransitions { 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 c8973f2586..254fe4ab1b 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1149,6 +1149,17 @@ تم العثور على <accent>Jade</accent> هل تريد إقران جهاز %1$s هذا مع Bitkit بشكل آمن؟ تم العثور على جهاز + مسح السجل + مسح لجميع المحافظ + إذا كانت دفعة سابقة لا تزال معلقة، فقد يرسلها Bitkit مرة ثانية. لا يمكن التراجع عن ذلك. + يحذف هذا كل سجلات الدفعات المحجوزة لجميع محافظ الأجهزة، بما فيها التي لا يزال Bitkit قادرًا على قراءتها. إذا كانت دفعة سابقة لا تزال معلقة، فقد يرسلها Bitkit مرة ثانية. لا يمكن التراجع عن ذلك. + يحذف هذا سجلات الدفعات غير المقروءة لهذه المحفظة وتلك التي لا يستطيع Bitkit قراءة محفظتها، والتي قد تخص أي محفظة أجهزة. تبقى السجلات المقروءة. إذا كانت دفعة سابقة لا تزال معلقة، فقد يرسلها Bitkit مرة ثانية. لا يمكن التراجع عن ذلك. + مسح السجل؟ + المبلغ: %1$s sats · العنوان: %2$s · المعاملة: %3$s · محجوزة: %4$s + غير معروف + تعذّر على Bitkit قراءة دفعة سابقة من محفظة الأجهزة هذه، لذلك لن يوقّع دفعة جديدة. يتيح مسح هذا السجل لـ Bitkit التوقيع مرة أخرى. لا تمسحه إلا إذا لم تكن أي دفعة سابقة من هذه المحفظة لا تزال معلقة، وإلا فقد تُرسَل الدفعة نفسها مرتين. + تعذّر على Bitkit قراءة سجله لدفعات محافظ الأجهزة السابقة، لذلك لن يوقّع دفعة جديدة من أي محفظة أجهزة. يتيح مسح السجل لجميع محافظ الأجهزة لـ Bitkit التوقيع مرة أخرى. لا تمسحه إلا إذا لم تكن أي دفعة سابقة من محفظة أجهزة لا تزال معلقة، وإلا فقد تُرسَل الدفعة نفسها مرتين. + تعذّرت قراءة دفعة سابقة أضف <accent>محفظة الأجهزة</accent> الخاصة بك اربط جهازك لمراقبة أموالك طويلة الأجل أو إدارتها. محفظة الأجهزة @@ -1188,15 +1199,26 @@ تعذر الاحتفاظ بعلامات هذه المحفظة في نسختك الاحتياطية. حاول مرة أخرى، أو أزلها دون الاحتفاظ بها. تعذرت إعادة تسمية محفظة الأجهزة. يرجى المحاولة مرة أخرى. تعذر البحث عن محافظ الأجهزة. تحقق من اتصالك وحاول مرة أخرى. + إرسال مرة أخرى + تم إرسال هذه الدفعة بالفعل في %1$s. هل تريد إرسالها مرة أخرى؟ + تم إرسال هذه الدفعة بالفعل. هل تريد إرسالها مرة أخرى؟ + تم إرسال الدفعة بالفعل + قبلت الشبكة هذه الدفعة. تكتمل بمجرد أن ترى محفظتك المعاملة. تحقق من اتصالك وحاول مرة أخرى. الدفعة غير مؤكدة + لم يصل رد على آخر بث لهذه الدفعة بعد. حاول مرة أخرى بعد قليل. + قد تُؤكَّد هذه الدفعة لاحقًا. تبقى معلقة حتى ترى محفظتك المعاملة أو تُنفَق عملاتها في مكان آخر. + لا يمكن تأكيد هذه الدفعة أبدًا. يمكنك إجراؤها مرة أخرى. إلى العنوان (أكّد على الجهاز) + لم تستلم الشبكة هذه الدفعة. يمكنك إجراؤها مرة أخرى. + لم تُرسَل الدفعة يمكن لـ Trezor الإرسال إلى عنوان Bitcoin فقط من هذه المحفظة. يمكن لـ Jade الإرسال إلى عنوان Bitcoin فقط من هذه المحفظة. مطلوب عنوان Bitcoin فتح Trezor Connect التوقيع باستخدام Jade التوقيع بالجهاز + عرض الدفعة التحقق على الجهاز فشل التحقق من العنوان. تحقق من العنوان على جهازك وحاول مرة أخرى. يحتوي هذا الجهاز على محفظة مختلفة عن التي أقرنتها. وصّل المحفظة المقترنة، أو أضف هذه كمحفظة أجهزة جديدة. @@ -1609,7 +1631,9 @@ اختر جهة اتصال من لم يتم إرسال الدفعة الجديدة. أكمل الدفعة السابقة قبل المحاولة مرة أخرى. + إعادة البث تستغرق هذه الدفعة وقتًا أطول قليلاً من المتوقع. يمكنك متابعة استخدام 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 f62df577aa..93734d9df5 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 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> @@ -1181,6 +1182,17 @@ <accent>Jade</accent> encontrado ¿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. + 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 + 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. Billetera de hardware @@ -1220,15 +1232,26 @@ 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 + 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) + 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 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. @@ -1612,6 +1635,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 f87eac631f..ce8e0c2539 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1174,6 +1174,17 @@ <accent>Jade</accent> trobat 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. + 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 + 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. Cartera de maquinari @@ -1213,15 +1224,26 @@ 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 + 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) + 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 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. @@ -1609,7 +1631,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 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 a6b2454328..0a8e434f30 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 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> @@ -1179,6 +1180,17 @@ Nalezen <accent>Jade</accent> 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. + 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é + 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. Hardwarová peněženka @@ -1218,15 +1230,26 @@ 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 + 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Í) + 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 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. @@ -1613,6 +1636,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 d8a0d88b77..f6761d594c 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 „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 @@ -1176,6 +1177,17 @@ <accent>Jade</accent> gefunden 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. + 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 + 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. Hardware-Wallet @@ -1215,15 +1227,26 @@ 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 + 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) + 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 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. @@ -1610,6 +1633,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 5b589e5087..256f3ac84f 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1155,6 +1155,17 @@ Βρέθηκε <accent>Jade</accent> Θέλεις να συζεύξεις με ασφάλεια αυτό το %1$s με το Bitkit; Βρέθηκε συσκευή + Διαγραφή εγγραφής + Διαγραφή για όλα τα πορτοφόλια + Αν μια προηγούμενη πληρωμή εκκρεμεί ακόμη, το Bitkit μπορεί να τη στείλει δεύτερη φορά. Αυτό δεν αναιρείται. + Αυτό διαγράφει όλες τις εγγραφές πληρωμών σε αναμονή όλων των πορτοφολιών υλικού, ακόμη και όσες μπορεί ακόμη να διαβάσει το Bitkit. Αν μια προηγούμενη πληρωμή εκκρεμεί ακόμη, το Bitkit μπορεί να τη στείλει δεύτερη φορά. Αυτό δεν αναιρείται. + Αυτό διαγράφει τις μη αναγνώσιμες εγγραφές πληρωμών αυτού του πορτοφολιού και εκείνες των οποίων το πορτοφόλι δεν μπορεί να διαβάσει το Bitkit, που μπορεί να ανήκουν σε οποιοδήποτε πορτοφόλι υλικού. Οι αναγνώσιμες εγγραφές παραμένουν. Αν μια προηγούμενη πληρωμή εκκρεμεί ακόμη, το Bitkit μπορεί να τη στείλει δεύτερη φορά. Αυτό δεν αναιρείται. + Διαγραφή της εγγραφής; + Ποσό: %1$s sats · Διεύθυνση: %2$s · Συναλλαγή: %3$s · Σε αναμονή: %4$s + άγνωστο + Το Bitkit δεν μπόρεσε να διαβάσει μια προηγούμενη πληρωμή από αυτό το πορτοφόλι υλικού, οπότε δεν θα υπογράψει νέα. Η διαγραφή αυτής της εγγραφής επιτρέπει στο Bitkit να υπογράφει ξανά. Διάγραψέ την μόνο αν καμία προηγούμενη πληρωμή από αυτό το πορτοφόλι δεν εκκρεμεί ακόμη, αλλιώς η ίδια πληρωμή μπορεί να σταλεί δύο φορές. + Το Bitkit δεν μπόρεσε να διαβάσει το αρχείο του με τις προηγούμενες πληρωμές από πορτοφόλια υλικού, οπότε δεν θα υπογράψει νέα από κανένα πορτοφόλι υλικού. Η διαγραφή του αρχείου για όλα τα πορτοφόλια υλικού επιτρέπει στο Bitkit να υπογράφει ξανά. Διάγραψέ το μόνο αν καμία προηγούμενη πληρωμή από πορτοφόλι υλικού δεν εκκρεμεί ακόμη, αλλιώς η ίδια πληρωμή μπορεί να σταλεί δύο φορές. + Δεν είναι δυνατή η ανάγνωση προηγούμενης πληρωμής Πρόσθεσε το <accent>πορτοφόλι υλικού</accent> σου Σύνδεσε τη συσκευή υλικού σου για να παρακολουθείς ή να διαχειρίζεσαι τα μακροπρόθεσμα κεφάλαιά σου. Πορτοφόλι υλικού @@ -1194,15 +1205,26 @@ Δεν ήταν δυνατή η διατήρηση των ετικετών αυτού του πορτοφολιού στο αντίγραφο ασφαλείας. Δοκίμασε ξανά ή αφαίρεσέ το χωρίς να τις διατηρήσεις. Δεν ήταν δυνατή η μετονομασία του πορτοφολιού υλικού. Δοκίμασε ξανά. Δεν ήταν δυνατή η αναζήτηση πορτοφολιών υλικού. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. + Αποστολή ξανά + Αυτή η πληρωμή έχει ήδη σταλεί στις %1$s. Να σταλεί ξανά; + Αυτή η πληρωμή έχει ήδη σταλεί. Να σταλεί ξανά; + Η πληρωμή έχει ήδη σταλεί + Το δίκτυο αποδέχτηκε αυτή την πληρωμή. Θα ολοκληρωθεί μόλις το πορτοφόλι σου δει τη συναλλαγή. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. Η πληρωμή δεν επιβεβαιώθηκε + Η τελευταία μετάδοση αυτής της πληρωμής δεν έχει απαντήσει ακόμη. Δοκίμασε ξανά σε λίγο. + Αυτή η πληρωμή μπορεί ακόμη να επιβεβαιωθεί. Παραμένει σε εκκρεμότητα μέχρι να τη δει το πορτοφόλι σου ή να ξοδευτούν αλλού τα νομίσματά της. + Αυτή η πληρωμή δεν μπορεί να επιβεβαιωθεί ποτέ. Μπορείς να την κάνεις ξανά. ΠΡΟΣ ΔΙΕΥΘΥΝΣΗ (ΕΠΙΒΕΒΑΙΩΣΗ ΣΤΗ ΣΥΣΚΕΥΗ) + Το δίκτυο δεν έλαβε αυτή την πληρωμή. Μπορείς να την κάνεις ξανά. + Η πληρωμή δεν στάλθηκε Το Trezor μπορεί να στείλει μόνο σε διεύθυνση Bitcoin από αυτό το πορτοφόλι. Το Jade μπορεί να στείλει μόνο σε διεύθυνση Bitcoin από αυτό το πορτοφόλι. Απαιτείται διεύθυνση Bitcoin Άνοιγμα Trezor Connect Υπογραφή με Jade Υπογραφή με συσκευή + Προβολή πληρωμής Επαλήθευση στη συσκευή Η επαλήθευση της διεύθυνσης απέτυχε. Έλεγξε τη διεύθυνση στη συσκευή σου και δοκίμασε ξανά. Αυτή η συσκευή περιέχει διαφορετικό πορτοφόλι από αυτό που συζεύχθηκε. Σύνδεσε το συζευγμένο πορτοφόλι ή πρόσθεσε αυτό ως νέο πορτοφόλι υλικού. @@ -1606,7 +1628,9 @@ Επιλογή επαφής Από Η νέα πληρωμή δεν στάλθηκε. Ολοκλήρωσε την προηγούμενη πληρωμή πριν δοκιμάσεις ξανά. + Εκ νέου μετάδοση Αυτή η πληρωμή διαρκεί λίγο περισσότερο από το αναμενόμενο. Μπορείς να συνεχίσεις να χρησιμοποιείς το 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 34faa374a7..de7b66269a 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1172,6 +1172,17 @@ <accent>Jade</accent> encontrado ¿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. + 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 + 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. Monedero de hardware @@ -1211,15 +1222,26 @@ 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 + 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) + 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 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. @@ -1608,7 +1630,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 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 b9c24c4522..ea58eb0d57 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1170,6 +1170,17 @@ <accent>Jade</accent> encontrado ¿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. + 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 + 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. Monedero de hardware @@ -1209,15 +1220,26 @@ 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 + 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) + 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 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. @@ -1608,7 +1630,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 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 504d48a804..b1a3d59871 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 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 @@ -1175,6 +1176,17 @@ <accent>Jade</accent> trouvé 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. + 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 + 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. Portefeuille matériel @@ -1214,15 +1226,26 @@ 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é + 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) + 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 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. @@ -1612,6 +1635,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 bbe3915683..cf76a84d0b 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 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> @@ -1175,6 +1176,17 @@ Trovato <accent>Jade</accent> 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. + 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 + 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. Hardware Wallet @@ -1216,15 +1228,26 @@ 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 + 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) + 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 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. @@ -1612,6 +1635,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 9e476721ba..dbcce710f1 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 ‘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> @@ -1172,6 +1173,17 @@ <accent>Jade</accent> gevonden 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. + 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 + 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. Hardwarewallet @@ -1211,15 +1223,26 @@ 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 + 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) + 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 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. @@ -1611,6 +1634,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 db3199891a..6015086501 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 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ź @@ -1178,6 +1179,17 @@ Znaleziono <accent>Jade</accent> 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ąć. + 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 + 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. Portfel sprzętowy @@ -1217,15 +1229,26 @@ 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 + 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) + 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 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. @@ -1612,6 +1635,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 47626cd119..fa9067a81e 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 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> @@ -1180,6 +1181,17 @@ <accent>Jade</accent> encontrado 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. + 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 + 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. Carteira de Hardware @@ -1219,15 +1231,26 @@ 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 + 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) + 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 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. @@ -1612,6 +1635,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 1fece40c5e..7ce2e3a696 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1147,6 +1147,17 @@ <accent>Jade</accent> encontrado 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. + 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 + 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. Carteira de hardware @@ -1186,15 +1197,26 @@ 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 + 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) + 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 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. @@ -1607,7 +1629,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 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 c59eb8f103..4232e04b68 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 не удалось подтвердить, что сеть получила этот платёж. Он завершится, как только ваш кошелёк увидит транзакцию. Если она не появится, нажмите «Отправить в сеть снова», чтобы повторно отправить ту же подписанную транзакцию. До тех пор Bitkit не будет подписывать этот платёж снова. Платеж в ожидании QuickPay Оплата @@ -1196,6 +1197,17 @@ Найден <accent>Jade</accent> Хотите безопасно сопрячь этот %1$s с Bitkit? Устройство Найдено + Очистить запись + Очистить для всех кошельков + Если предыдущий платёж ещё ожидает подтверждения, Bitkit может отправить его второй раз. Это действие нельзя отменить. + Будут удалены все записи об удерживаемых платежах всех аппаратных кошельков, включая те, которые Bitkit ещё может прочитать. Если предыдущий платёж ещё ожидает подтверждения, Bitkit может отправить его второй раз. Это действие нельзя отменить. + Будут удалены нечитаемые записи о платежах этого кошелька и те, чей кошелёк Bitkit не может прочитать и которые могут относиться к любому аппаратному кошельку. Читаемые записи сохранятся. Если предыдущий платёж ещё ожидает подтверждения, Bitkit может отправить его второй раз. Это действие нельзя отменить. + Очистить запись? + Сумма: %1$s sats · Адрес: %2$s · Транзакция: %3$s · Удержан: %4$s + неизвестно + Bitkit не удалось прочитать предыдущий платёж с этого аппаратного кошелька, поэтому новый он подписывать не будет. Очистка этой записи позволит Bitkit снова подписывать. Очищайте её, только если ни один предыдущий платёж с этого кошелька не ожидает подтверждения, иначе один и тот же платёж может быть отправлен дважды. + Bitkit не удалось прочитать запись о предыдущих платежах с аппаратных кошельков, поэтому он не будет подписывать новые ни с одного аппаратного кошелька. Очистка записи для всех аппаратных кошельков позволит Bitkit снова подписывать. Очищайте её, только если ни один предыдущий платёж с аппаратного кошелька не ожидает подтверждения, иначе один и тот же платёж может быть отправлен дважды. + Не удаётся прочитать предыдущий платёж Добавьте <accent>кошелёк</accent> Подключите аппаратное устройство, чтобы отслеживать или управлять долгосрочными средствами. Аппаратный Кошелёк @@ -1235,15 +1247,26 @@ Не удалось сохранить теги этого кошелька в резервной копии. Попробуйте снова или удалите его без сохранения тегов. Не удалось переименовать аппаратный кошелёк. Пожалуйста, попробуйте снова. Не удалось найти аппаратные кошельки. Проверьте подключение и попробуйте снова. + Отправить снова + Этот платёж уже был отправлен %1$s. Отправить его снова? + Этот платёж уже был отправлен. Отправить его снова? + Платёж уже отправлен + Сеть приняла этот платёж. Он завершится, как только ваш кошелёк увидит транзакцию. Проверьте подключение и попробуйте снова. Платёж не подтверждён + Последняя отправка этого платежа в сеть ещё не получила ответа. Повторите попытку чуть позже. + Этот платёж ещё может быть подтверждён. Он остаётся в ожидании, пока ваш кошелёк его не увидит или его монеты не будут потрачены в другой транзакции. + Этот платёж никогда не будет подтверждён. Вы можете выполнить его снова. НА АДРЕС (ПОДТВЕРДИТЕ НА УСТРОЙСТВЕ) + Сеть не получила этот платёж. Вы можете выполнить его снова. + Платёж не отправлен Trezor может отправлять из этого кошелька только на Bitcoin-адрес. Jade может отправлять из этого кошелька только на Bitcoin-адрес. Нужен Bitcoin-адрес Открыть Trezor Connect Подписать на Jade Подписать на Устройстве + Посмотреть платёж Проверить на Устройстве Проверка адреса не удалась. Сверьте адрес на устройстве и попробуйте снова. На этом устройстве другой кошелёк, а не тот, который вы сопрягли. Подключите сопряжённый кошелёк или добавьте этот как новый аппаратный кошелёк. @@ -1627,6 +1650,7 @@ У вас пока нет контактов. Откуда Новый платёж не отправлен. Завершите предыдущий платёж, прежде чем пробовать снова. + Отправить в сеть снова Результат транзакции не определён. Проверьте её статус, прежде чем пробовать снова. Другие платежи остаются заблокированными. Если доступно, используйте «Повторить исходный платёж», чтобы разрешить комиссию для того же платежа. Отправка отклонена: %1$s Разрешить повтор diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0581f041af..9c249d4cbd 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -188,6 +188,17 @@ Found <accent>Jade</accent> 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. + 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 + 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. Hardware Wallet @@ -229,15 +240,26 @@ 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 + 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) + 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 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. @@ -1553,7 +1575,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 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/data/HwHeldSendStoreTest.kt b/app/src/test/java/to/bitkit/data/HwHeldSendStoreTest.kt new file mode 100644 index 0000000000..7c5fadd707 --- /dev/null +++ b/app/src/test/java/to/bitkit/data/HwHeldSendStoreTest.kt @@ -0,0 +1,128 @@ +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 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"))))) + + 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/ext/BroadcastExceptionExtTest.kt b/app/src/test/java/to/bitkit/ext/BroadcastExceptionExtTest.kt index 9ab2bf9118..2ba5ff5f3d 100644 --- a/app/src/test/java/to/bitkit/ext/BroadcastExceptionExtTest.kt +++ b/app/src/test/java/to/bitkit/ext/BroadcastExceptionExtTest.kt @@ -47,6 +47,101 @@ class BroadcastExceptionExtTest { assertFalse(AppError("unknown result").isDefiniteHardwarePreBroadcastFailure()) } + @Test + 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"), + ) + 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"), + BroadcastException.ElectrumException("Broadcast failed: min relay fee not met"), + AppError("unknown result"), + timeout, + ) + for (error in maybeSent) { + assertFalse(error.isHardwareBroadcastNotSent()) + } + } + + @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/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/repositories/HwWalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/HwWalletRepoTest.kt index 980b221254..1cede5dd53 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 @@ -29,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 @@ -41,6 +47,10 @@ 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.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 @@ -63,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 @@ -73,6 +84,9 @@ 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( @@ -87,6 +101,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 @@ -156,6 +171,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 @@ -301,6 +317,7 @@ class HwWalletRepoTest : BaseUnitTest() { activityRepo = activityRepo, preActivityMetadataRepo = preActivityMetadataRepo, hwWalletStore = hwWalletStore, + hwHeldSendStore = hwHeldSendStore, settingsStore = settingsStore, ioDispatcher = testDispatcher, ) @@ -345,6 +362,159 @@ class HwWalletRepoTest : BaseUnitTest() { assertEquals("Trezor Safe 7", sut.wallets.value.single().name) } + @Test + fun `a held send is found for its own payment only`() = 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, + ) + 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()) + } + + @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 { + val unreadable = buildJsonObject { + put("walletId", HARDWARE_WALLET_ID) + put("txId", 7) + } + whenever(hwHeldSendStore.load()).thenReturn(HwHeldSendData(unreadable = listOf(unreadable))) + val sut = createRepo() + + 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 { + 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() @@ -1859,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()) @@ -2523,6 +2702,7 @@ class HwWalletRepoTest : BaseUnitTest() { confirmations: UInt = 3u, fee: ULong = 0uL, walletId: String = HARDWARE_WALLET_ID, + doesExist: Boolean = true, ) = Activity.Onchain( OnchainActivity.create( walletId = walletId, @@ -2534,6 +2714,7 @@ class HwWalletRepoTest : BaseUnitTest() { address = "", timestamp = timestamp ?: 0uL, confirmed = blockHeight != null && confirmations > 0u, + doesExist = doesExist, ) ) 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 0fef39c0a1..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 @@ -1,15 +1,23 @@ 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 import kotlinx.coroutines.withContext @@ -17,20 +25,30 @@ 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.eq +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.data.HwHeldSendsUnreadableError +import to.bitkit.data.UnreadableHeldSend +import to.bitkit.ext.create 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.HwHeldDispatchTracker import to.bitkit.repositories.HwWalletMismatchError import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.PaykitPaymentProofRepo @@ -46,6 +64,8 @@ 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 import kotlin.time.Duration @@ -62,6 +82,10 @@ class HwSendViewModelTest : BaseUnitTest() { private val activityService = mock() private val activityRepo = mock() private val proofRepo = mock() + 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") @@ -76,10 +100,10 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), - org.mockito.kotlin.anyOrNull() + anyOrNull() ) } .thenReturn(true) @@ -88,36 +112,45 @@ 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) - sut = HwSendViewModel( - context = context, - hwWalletRepo = hwWalletRepo, - preActivityMetadataRepo = preActivityMetadataRepo, - coreService = coreService, - activityRepo = activityRepo, - paykitPaymentProofRepo = proofRepo, - clock = object : Clock { - override fun now() = now - }, - ) + 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)) + 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 { val funding = HwFundingTransaction( @@ -181,7 +214,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 @@ -220,7 +253,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() @@ -278,254 +311,1236 @@ class HwSendViewModelTest : BaseUnitTest() { true } - sut.signAndBroadcast(request(), prepareContactPayment, authorizeContactPayment) + sut.signAndBroadcast(request(), prepareContactPayment, authorizeContactPayment) + advanceUntilIdle() + assertTrue(sut.uiState.value.isPassphraseRequired) + + sut.submitPassphrase(WALLET_ID, "hidden wallet") { + sut.signAndBroadcast(request(), prepareContactPayment, authorizeContactPayment) + } + advanceUntilIdle() + + assertEquals(1, preparationCalls) + assertEquals(listOf(false), authorizationAttempts) + verify(hwWalletRepo).broadcastFunding(fixture.signedTx) + assertFalse(sut.uiState.value.isPassphraseRequired) + } + + @Test + fun `a device holding another wallet shows the wallet mismatch`() = test { + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + whenever(hwWalletRepo.needsPassphrase(WALLET_ID)).thenReturn(false) + whenever(hwWalletRepo.ensureConnected(WALLET_ID)).thenReturn(Result.failure(HwWalletMismatchError())) + whenever(context.getString(R.string.common__error)).thenReturn("Error") + whenever(context.getString(R.string.hardware__wallet_mismatch)).thenReturn("Different wallet") + + sut.signAndBroadcast(request()) + advanceUntilIdle() + toastJob.cancel() + + assertEquals(Toast.ToastType.ERROR, toasts.single().type) + assertEquals("Different wallet", toasts.single().description) + verify(hwWalletRepo, never()).composeFundingTransaction(any(), any(), any(), any()) + } + + @Test + fun `composition timeout shows payment timeout`() = test { + val timeout = runCatching { withTimeout(0) { Unit } }.exceptionOrNull() as TimeoutCancellationException + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + whenever(hwWalletRepo.needsPassphrase(WALLET_ID)).thenReturn(false) + whenever(hwWalletRepo.ensureConnected(WALLET_ID)).thenReturn(Result.success(connectedDevice())) + whenever(hwWalletRepo.composeFundingTransaction(WALLET_ID, ADDRESS, AMOUNT_SATS, SATS_PER_VBYTE)) + .thenReturn(Result.failure(timeout)) + whenever(context.getString(R.string.common__error)).thenReturn("Error") + whenever(context.getString(R.string.wallet__payment_timeout)).thenReturn("Payment timed out") + + sut.signAndBroadcast(request()) + advanceUntilIdle() + toastJob.cancel() + + assertEquals(Toast.ToastType.ERROR, toasts.single().type) + assertEquals("Payment timed out", toasts.single().description) + assertFalse(sut.uiState.value.isSigning) + verify(hwWalletRepo, never()).signFunding(any(), any()) + verify(hwWalletRepo, never()).broadcastFunding(any(), anyOrNull()) + } + + @Test + fun `broadcast result survives collector reattachment until acknowledged`() = test { + val fixture = stubSuccessfulPayment() + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + assertEquals(fixture.broadcast.txId, sut.results.first().txId) + assertTrue(sut.uiState.value.isBroadcastUnresolved) + + sut.completeBroadcast() + + assertFalse(sut.uiState.value.isBroadcastUnresolved) + } + + @Test + fun `Shop broadcast connectivity failure retains original signed payment across cancel`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + val original = request().copy( + paymentRequestId = PaykitPaymentRequestId("request", "counterparty"), + paymentIdentity = "original-identity", + ) + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(BroadcastException.ElectrumException("connection failed")), + Result.success(fixture.broadcast), + ) + sut.signAndBroadcast(original) + advanceUntilIdle() + assertTrue(sut.uiState.value.isBroadcastUnresolved) + sut.cancel() + advanceUntilIdle() + assertTrue(sut.uiState.value.hasPendingBroadcast) + sut.signAndBroadcast(original) + advanceUntilIdle() + verify(hwWalletRepo, times(1)).signFunding(WALLET_ID, fixture.funding) + verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) + assertEquals(original.paymentRequestId, sut.results.first().paymentRequestId) + assertEquals(original.paymentIdentity, sut.results.first().paymentIdentity) + } + + @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")) + val late = CompletableDeferred>() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).doSuspendableAnswer { + withContext(NonCancellable) { late.await() } + } + + sut.signAndBroadcast(original) + advanceTimeBy(61.seconds) + runCurrent() + + 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 + fun `Shop invalid broadcast failure retains original signed payment across cancel`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + val original = request().copy( + paymentRequestId = PaykitPaymentRequestId("request", "counterparty"), + paymentIdentity = "original-identity", + ) + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure(BroadcastException.InvalidTransaction("invalid transaction")), + Result.success(fixture.broadcast), + ) + sut.signAndBroadcast(original) + advanceUntilIdle() + assertFalse(sut.uiState.value.isBroadcastUnresolved) + assertTrue(sut.uiState.value.canLeave) + sut.cancel() + advanceUntilIdle() + assertTrue(sut.uiState.value.hasPendingBroadcast) + assertTrue(sut.uiState.value.canLeave) + sut.signAndBroadcast(original) + advanceUntilIdle() + verify(hwWalletRepo, times(1)).signFunding(WALLET_ID, fixture.funding) + verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) + assertEquals(original.paymentRequestId, sut.results.first().paymentRequestId) + assertEquals(original.paymentIdentity, sut.results.first().paymentIdentity) + } + + @Test + fun `Shop backend refusal allows leaving while retaining original signed payment`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + val original = request().copy( + paymentRequestId = PaykitPaymentRequestId("request", "counterparty"), + paymentIdentity = "original-identity", + ) + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( + Result.failure( + BroadcastException.ElectrumException( + """Broadcast failed: Electrum server error: "sendrawtransaction RPC error -26: """ + + """insufficient fee, rejecting replacement """ + + """b3f63e62aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; new feerate """ + + """0.00001000 BTC/kvB <= old feerate 0.00001018 BTC/kvB"""", + ), + ), + Result.failure( + BroadcastException.ElectrumException( + """Broadcast failed: Electrum server error: "sendrawtransaction RPC error -25: """ + + """bad-txns-inputs-missingorspent"""", + ), + ), + ) + sut.signAndBroadcast(original) + advanceUntilIdle() + assertTrue(sut.uiState.value.canLeave) + assertTrue(sut.uiState.value.hasPendingBroadcast) + sut.cancel() + advanceUntilIdle() + assertTrue(sut.uiState.value.canLeave) + assertTrue(sut.uiState.value.hasPendingBroadcast) + sut.signAndBroadcast(original) + advanceUntilIdle() + verify(hwWalletRepo, times(1)).signFunding(WALLET_ID, fixture.funding) + verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) + verify(proofRepo, times(2)).markHardwareOnchainDispatch( + requireNotNull(original.paymentRequestId), + WALLET_ID, + SignedTransactionId.fromHex(fixture.signedTx.serializedTx), + original.paymentIdentity, + original.address, + original.amountSats, + ) + verify(proofRepo, never()).clearHardwareOnchainCandidateBeforeDispatch( + any(), + any(), + any(), + anyOrNull(), + any(), + any(), + any(), + ) + assertTrue(sut.uiState.value.canLeave) + assertTrue(sut.uiState.value.hasPendingBroadcast) + verify(proofRepo, times(2)).markHardwareRefusedForNavigation( + requireNotNull(original.paymentRequestId), + WALLET_ID, + SignedTransactionId.fromHex(fixture.signedTx.serializedTx), + original.paymentIdentity, + original.address, + original.amountSats, + ) + } + + @Test + fun `broadcast connectivity failure unblocks navigation`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)) + .thenReturn(Result.failure(BroadcastException.ElectrumException(CONNECT_FAILURE))) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + assertFalse(sut.uiState.value.isBroadcastUnresolved) + assertTrue(sut.uiState.value.hasPendingBroadcast) + assertFalse(sut.uiState.value.isSigning) + } + + @Test + fun `broadcast timeout unblocks navigation`() = test { + whenever(context.getString(any())).thenReturn("message") + val fixture = stubSuccessfulPayment() + val timeout = runCatching { withTimeout(Duration.ZERO) { Unit } } + .exceptionOrNull() as TimeoutCancellationException + whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn(Result.failure(timeout)) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + assertFalse(sut.uiState.value.isBroadcastUnresolved) + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) + assertFalse(sut.uiState.value.isSigning) + } + + @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") + 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 } } + val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) + + sut.signAndBroadcast(request()) + advanceTimeBy(59.seconds) + runCurrent() + 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) + + 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()) + 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 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(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, + address = ADDRESS, + amount = AMOUNT_SATS, + fee = fixture.signedTx.miningFeeSats, + feeRate = fixture.signedTx.feeRate, + isTransfer = false, + channelId = null, + walletId = WALLET_ID, + ) + } + + @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 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() + 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") + 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() + 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 + fun `broadcast failure warns the payment was not confirmed`() = test { + 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(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.") + + sut.signAndBroadcast(request()) + advanceUntilIdle() + toastJob.cancel() + + assertEquals(Toast.ToastType.WARNING, toasts.single().type) + assertEquals("Payment not confirmed", toasts.single().title) + assertEquals("Check your connection and try again.", toasts.single().description) + } + + @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 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") + 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.heldSendEvents.collect { results += it.send } } + + 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) + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) + 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 }) + 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 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.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).broadcastFunding(fixture.signedTx) + assertEquals(1, toasts.count { it.title == "accepted" }) + assertEquals(held, sut.uiState.value.unresolvedSend) + assertTrue(results.isEmpty()) + + walletActivities.value = persistentListOf(sentActivity()) + advanceUntilIdle() + toastJob.cancel() + + verify(hwWalletRepo, never()).signFunding(any(), any()) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) + assertEquals(listOf(held), 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()) + 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 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) + // 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() + + 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") + 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))) + + sut.signAndBroadcast(request()) + 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()) + } + + @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") + 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 + 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( + 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.heldSendEvents.collect { results += it.send } } + val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + sut.cancel() + advanceUntilIdle() + repeat(2) { + sut.retryUnresolvedSend(SIGNED_TXID) + advanceUntilIdle() + + assertEquals(listOf(held), sut.uiState.value.unresolvedSends) + assertTrue(sut.uiState.value.retryingSendTxIds.isEmpty()) + } + assertTrue(results.isEmpty()) + 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() + + assertEquals(listOf(held), results) + 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( + 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.heldSendEvents.collect { results += it.send } } + + sut.signAndBroadcast(request()) advanceUntilIdle() - assertTrue(sut.uiState.value.isPassphraseRequired) - - sut.submitPassphrase(WALLET_ID, "hidden wallet") { - sut.signAndBroadcast(request(), prepareContactPayment, authorizeContactPayment) - } + sut.retryUnresolvedSend(SIGNED_TXID) advanceUntilIdle() + toastJob.cancel() - assertEquals(1, preparationCalls) - assertEquals(listOf(false), authorizationAttempts) - verify(hwWalletRepo).broadcastFunding(fixture.signedTx) - assertFalse(sut.uiState.value.isPassphraseRequired) + assertEquals(1, toasts.count { it.description == "refused" }) + assertEquals(0, toasts.count { it.description == "try again" }) + assertEquals(listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)), sut.uiState.value.unresolvedSends) + assertTrue(results.isEmpty()) } @Test - fun `a device holding another wallet shows the wallet mismatch`() = 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(hwWalletRepo.needsPassphrase(WALLET_ID)).thenReturn(false) - whenever(hwWalletRepo.ensureConnected(WALLET_ID)).thenReturn(Result.failure(HwWalletMismatchError())) - whenever(context.getString(R.string.common__error)).thenReturn("Error") - whenever(context.getString(R.string.hardware__wallet_mismatch)).thenReturn("Different wallet") + 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(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(Toast.ToastType.ERROR, toasts.single().type) - assertEquals("Different wallet", toasts.single().description) - verify(hwWalletRepo, never()).composeFundingTransaction(any(), any(), any(), any()) + 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 `composition timeout shows payment timeout`() = test { - val timeout = runCatching { withTimeout(0) { Unit } }.exceptionOrNull() as TimeoutCancellationException + 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) } } - whenever(hwWalletRepo.needsPassphrase(WALLET_ID)).thenReturn(false) - whenever(hwWalletRepo.ensureConnected(WALLET_ID)).thenReturn(Result.success(connectedDevice())) - whenever(hwWalletRepo.composeFundingTransaction(WALLET_ID, ADDRESS, AMOUNT_SATS, SATS_PER_VBYTE)) - .thenReturn(Result.failure(timeout)) - whenever(context.getString(R.string.common__error)).thenReturn("Error") - whenever(context.getString(R.string.wallet__payment_timeout)).thenReturn("Payment timed out") + 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(Toast.ToastType.ERROR, toasts.single().type) - 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()) + 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 `broadcast result survives collector reattachment until acknowledged`() = 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(fixture.broadcast.txId, sut.results.first().txId) - assertTrue(sut.uiState.value.isBroadcastUnresolved) + 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) { + 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) + } - sut.completeBroadcast() + sut.showAlreadySentSend() - assertFalse(sut.uiState.value.isBroadcastUnresolved) + assertNull(sut.uiState.value.alreadySentSend) + assertEquals(held, sut.results.first()) } @Test - fun `Shop broadcast connectivity failure retains original signed payment across cancel`() = test { - whenever(context.getString(any())).thenReturn("message") + fun `a held payment the wallet has seen is signed anew only when the user sends it again`() = test { val fixture = stubSuccessfulPayment() - val original = request().copy( - paymentRequestId = PaykitPaymentRequestId("request", "counterparty"), - paymentIdentity = "original-identity", - ) - whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( - Result.failure(BroadcastException.ElectrumException("connection failed")), - Result.success(fixture.broadcast), - ) - sut.signAndBroadcast(original) - advanceUntilIdle() - assertTrue(sut.uiState.value.isBroadcastUnresolved) - sut.cancel() + 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() - assertTrue(sut.uiState.value.hasPendingBroadcast) - sut.signAndBroadcast(original) + 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) - verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) - assertEquals(original.paymentRequestId, sut.results.first().paymentRequestId) - assertEquals(original.paymentIdentity, sut.results.first().paymentIdentity) + assertEquals(fixture.broadcast.txId, sut.results.first().txId) } @Test - fun `Shop invalid broadcast failure retains original signed payment across cancel`() = 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 + fun `a held send the wallet has seen completes instead of being released`() = test { whenever(context.getString(any())).thenReturn("message") val fixture = stubSuccessfulPayment() - val original = request().copy( - paymentRequestId = PaykitPaymentRequestId("request", "counterparty"), - paymentIdentity = "original-identity", - ) whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( - Result.failure(BroadcastException.InvalidTransaction("invalid transaction")), - Result.success(fixture.broadcast), + Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE)), + Result.failure(BroadcastException.ElectrumException(SCRIPT_REFUSAL)), ) - sut.signAndBroadcast(original) - advanceUntilIdle() - assertFalse(sut.uiState.value.isBroadcastUnresolved) - assertTrue(sut.uiState.value.canLeave) - sut.cancel() + val events = mutableListOf() + backgroundScope.launch { sut.heldSendEvents.collect { events += it } } + val seen = MutableStateFlow>(persistentListOf(sentActivity())) + + sut.signAndBroadcast(request()) advanceUntilIdle() - assertTrue(sut.uiState.value.hasPendingBroadcast) - assertTrue(sut.uiState.value.canLeave) - sut.signAndBroadcast(original) + // The wallet's history shows the transaction before its watch has run + whenever(hwWalletRepo.activities).thenReturn(seen) + sut.retryUnresolvedSend(SIGNED_TXID) advanceUntilIdle() - verify(hwWalletRepo, times(1)).signFunding(WALLET_ID, fixture.funding) - verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) - assertEquals(original.paymentRequestId, sut.results.first().paymentRequestId) - assertEquals(original.paymentIdentity, sut.results.first().paymentIdentity) + + val held = HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS) + assertEquals(listOf(HeldHwSendEvent.Completed(held)), events) } @Test - fun `Shop backend refusal allows leaving while retaining original signed payment`() = 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() - val original = request().copy( - paymentRequestId = PaykitPaymentRequestId("request", "counterparty"), - paymentIdentity = "original-identity", - ) + whenever(hwWalletRepo.disconnectStaleSession(WALLET_ID)).thenReturn(Result.success(Unit)) whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn( - Result.failure( - BroadcastException.ElectrumException( - """Broadcast failed: Electrum server error: "sendrawtransaction RPC error -26: """ + - """insufficient fee, rejecting replacement """ + - """b3f63e62aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; new feerate """ + - """0.00001000 BTC/kvB <= old feerate 0.00001018 BTC/kvB"""", - ), - ), - Result.failure( - BroadcastException.ElectrumException( - """Broadcast failed: Electrum server error: "sendrawtransaction RPC error -25: """ + - """bad-txns-inputs-missingorspent"""", - ), - ), + Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE)), + Result.success(fixture.broadcast), ) - sut.signAndBroadcast(original) + + assertNull(sut.resumeHeldSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) + sut.signAndBroadcast(request()) advanceUntilIdle() - assertTrue(sut.uiState.value.canLeave) - assertTrue(sut.uiState.value.hasPendingBroadcast) sut.cancel() advanceUntilIdle() - assertTrue(sut.uiState.value.canLeave) - assertTrue(sut.uiState.value.hasPendingBroadcast) - sut.signAndBroadcast(original) + + assertEquals( + HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS), + sut.resumeHeldSend(WALLET_ID, ADDRESS.uppercase(), AMOUNT_SATS), + ) advanceUntilIdle() - verify(hwWalletRepo, times(1)).signFunding(WALLET_ID, fixture.funding) verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) - verify(proofRepo, times(2)).markHardwareOnchainDispatch( - requireNotNull(original.paymentRequestId), - WALLET_ID, - SignedTransactionId.fromHex(fixture.signedTx.serializedTx), - original.paymentIdentity, - original.address, - original.amountSats, - ) - verify(proofRepo, never()).clearHardwareOnchainCandidateBeforeDispatch( - any(), - any(), - any(), - org.mockito.kotlin.anyOrNull(), - any(), - any(), - any(), - ) - assertTrue(sut.uiState.value.canLeave) - assertTrue(sut.uiState.value.hasPendingBroadcast) - verify(proofRepo, times(2)).markHardwareRefusedForNavigation( - requireNotNull(original.paymentRequestId), - WALLET_ID, - SignedTransactionId.fromHex(fixture.signedTx.serializedTx), - original.paymentIdentity, - original.address, - original.amountSats, - ) + verify(hwWalletRepo, times(1)).signFunding(any(), any()) + + walletActivities.value = persistentListOf(sentActivity()) + advanceUntilIdle() + + assertNull(sut.resumeHeldSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) + verify(hwWalletRepo, times(2)).broadcastFunding(fixture.signedTx) } @Test - fun `broadcast connectivity failure unblocks navigation`() = 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("connection failed"))) + 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() - assertFalse(sut.uiState.value.isBroadcastUnresolved) - assertTrue(sut.uiState.value.hasPendingBroadcast) - assertFalse(sut.uiState.value.isSigning) + assertNull(sut.resumeHeldSend(WALLET_ID, ADDRESS, other.amountSats)) + assertNull(sut.resumeHeldSend(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 `broadcast timeout unblocks navigation`() = test { + fun `removing a wallet forgets its held send for the session`() = test { whenever(context.getString(any())).thenReturn("message") val fixture = stubSuccessfulPayment() - val timeout = runCatching { withTimeout(Duration.ZERO) { Unit } } - .exceptionOrNull() as TimeoutCancellationException - whenever(hwWalletRepo.broadcastFunding(fixture.signedTx)).thenReturn(Result.failure(timeout)) + 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() - assertFalse(sut.uiState.value.isBroadcastUnresolved) - assertTrue(sut.uiState.value.hasPendingBroadcast) - assertFalse(sut.uiState.value.isSigning) + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) + assertNull(sut.uiState.value.unresolvedSend) + assertNull(sut.resumeHeldSend(WALLET_ID, ADDRESS, AMOUNT_SATS)) + verify(hwWalletRepo, never()).releaseHeldSend(any()) } @Test - fun `broadcast failure warns the payment was not confirmed`() = test { - val toasts = mutableListOf() - val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + 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("connection failed"))) - 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.") + .thenReturn(Result.failure(BroadcastException.ElectrumException(LOST_AFTER_WRITE))) sut.signAndBroadcast(request()) advanceUntilIdle() - toastJob.cancel() + 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() - assertEquals(Toast.ToastType.WARNING, toasts.single().type) - assertEquals("Payment not confirmed", toasts.single().title) - assertEquals("Check your connection and try again.", toasts.single().description) + assertTrue(replayed.isEmpty()) + assertTrue(sut.uiState.value.unresolvedSends.isEmpty()) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) } - @Test - fun `cancel drops the signed transaction after a failed broadcast`() = test { + 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(BroadcastException.ElectrumException("connection failed")), + Result.failure(error), Result.success(fixture.broadcast), ) @@ -537,6 +1552,7 @@ class HwSendViewModelTest : BaseUnitTest() { advanceUntilIdle() assertFalse(sut.uiState.value.hasPendingBroadcast) + assertNull(sut.uiState.value.unresolvedSend) verify(hwWalletRepo).disconnectStaleSession(WALLET_ID) sut.signAndBroadcast(request()) @@ -545,6 +1561,40 @@ 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") + 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() + val held = listOf(HwSendResult(WALLET_ID, SIGNED_TXID, AMOUNT_SATS)) + assertEquals(held, sut.uiState.value.unresolvedSends) + + sut.signAndBroadcast(request().copy(address = ADDRESS.uppercase())) + advanceUntilIdle() + toastJob.cancel() + + verify(hwWalletRepo, times(1)).signFunding(any(), any()) + // 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) + } + @Test fun `sheet can be left while the device connects`() = test { val fixture = stubSuccessfulPayment() @@ -618,7 +1668,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()) @@ -650,6 +1700,7 @@ class HwSendViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.isSigning) sut.cancel() assertFalse(sut.uiState.value.hasPendingBroadcast) + verify(hwWalletRepo).releaseHeldSend(SIGNED_TXID) } @Test @@ -661,7 +1712,7 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any() ) @@ -674,7 +1725,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) } @@ -741,7 +1792,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() @@ -771,6 +1822,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 @@ -779,7 +1832,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 @@ -813,7 +1866,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() @@ -880,6 +1933,7 @@ class HwSendViewModelTest : BaseUnitTest() { coreService = coreService, activityRepo = activityRepo, paykitPaymentProofRepo = proofRepo, + heldDispatches = heldDispatches, clock = object : Clock { override fun now() = now }, @@ -888,7 +1942,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 @@ -917,7 +1971,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") }, @@ -961,7 +2015,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 @@ -976,10 +2030,10 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), - org.mockito.kotlin.anyOrNull() + anyOrNull() ) } .thenReturn(false) @@ -1010,10 +2064,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 @@ -1049,10 +2103,10 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), - org.mockito.kotlin.anyOrNull() + anyOrNull() ) } .thenReturn(false, true) @@ -1079,10 +2133,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) @@ -1221,7 +2275,7 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), ) verify(activityRepo, never()).notifyPaymentActivityChanged() @@ -1347,7 +2401,7 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), ) @@ -1362,7 +2416,7 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), any(), @@ -1382,7 +2436,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() @@ -1392,7 +2446,7 @@ class HwSendViewModelTest : BaseUnitTest() { any(), any(), any(), - org.mockito.kotlin.anyOrNull(), + anyOrNull(), any(), any(), ) @@ -1452,7 +2506,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 @@ -1485,6 +2539,19 @@ 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, + heldAt = now.epochSeconds, + ) + private fun request() = HwSendRequest( walletId = WALLET_ID, address = ADDRESS, @@ -1501,8 +2568,45 @@ 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, doesExist: Boolean = true) = 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, + doesExist = doesExist, + ) + ) + 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 = + "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" const val AMOUNT_SATS = 25_000uL const val SATS_PER_VBYTE = 2uL 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)) } 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.