From faf45ae4f77d88ba44d7f25e6a52009ff7f753f8 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Fri, 27 Nov 2026 22:08:47 -0300 Subject: [PATCH 01/33] feat: add wear spark payment calls and send keys Co-Authored-By: Claude Fable 5.2 --- .../java/to/bitkit/wear/security/Bip39.kt | 6 + .../to/bitkit/wear/services/SparkSendKey.kt | 54 +++++++ .../bitkit/wear/services/WatchSparkService.kt | 104 ++++++++++++- .../java/to/bitkit/wear/security/Fakes.kt | 3 + .../to/bitkit/wear/services/SparkFixtures.kt | 124 ++++++++++++++++ .../bitkit/wear/services/SparkSendKeyTest.kt | 44 ++++++ .../wear/services/WatchSparkServiceTest.kt | 138 ++++++++++++++++-- 7 files changed, 456 insertions(+), 17 deletions(-) create mode 100644 wear/src/main/java/to/bitkit/wear/services/SparkSendKey.kt create mode 100644 wear/src/test/java/to/bitkit/wear/services/SparkFixtures.kt create mode 100644 wear/src/test/java/to/bitkit/wear/services/SparkSendKeyTest.kt diff --git a/wear/src/main/java/to/bitkit/wear/security/Bip39.kt b/wear/src/main/java/to/bitkit/wear/security/Bip39.kt index 82f941e83d..3d41c7d665 100644 --- a/wear/src/main/java/to/bitkit/wear/security/Bip39.kt +++ b/wear/src/main/java/to/bitkit/wear/security/Bip39.kt @@ -2,6 +2,7 @@ package to.bitkit.wear.security import com.synonym.bitkitcore.getBip39Suggestions import com.synonym.bitkitcore.isValidBip39Word +import com.synonym.bitkitcore.mnemonicToSeed import com.synonym.bitkitcore.validateMnemonic import javax.inject.Inject import javax.inject.Singleton @@ -29,6 +30,9 @@ interface Bip39 { /** Checks the words and the checksum of [words], which must already be lowercase. */ fun validate(words: List): Bip39Validation + + /** The BIP39 seed of [mnemonic] with its optional [passphrase]. */ + fun toSeed(mnemonic: String, passphrase: String?): ByteArray } sealed interface Bip39Validation { @@ -62,4 +66,6 @@ class CoreBip39 @Inject constructor() : Bip39 { return runCatching { validateMnemonic(words.joinToString(" ")) } .fold(onSuccess = { Bip39Validation.Valid }, onFailure = { Bip39Validation.InvalidChecksum }) } + + override fun toSeed(mnemonic: String, passphrase: String?): ByteArray = mnemonicToSeed(mnemonic, passphrase) } diff --git a/wear/src/main/java/to/bitkit/wear/services/SparkSendKey.kt b/wear/src/main/java/to/bitkit/wear/services/SparkSendKey.kt new file mode 100644 index 0000000000..d6bb519c5a --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/services/SparkSendKey.kt @@ -0,0 +1,54 @@ +package to.bitkit.wear.services + +import java.nio.ByteBuffer +import java.security.MessageDigest +import java.util.UUID +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec + +/** + * The idempotency key of a Spark send of an invoice. Spark makes one transfer per key, so a retry under the same key + * never pays the invoice twice: it gets back the transfer an earlier try committed, or sends when none did. A key + * whose payment failed can't send again, so the next attempt takes the next key. + * + * Keys derive from the wallet seed, the payment hash and the attempt number, so a restored wallet derives the same + * keys, no other wallet can, and the operators can't link a transfer to its invoice. iOS derives the same keys. + * + * A copy of the phone's `to.bitkit.services.SparkSendKey`: the watch and the phone share one wallet, so both must + * derive the same key for an invoice, and Spark then pays it once even when both try. Keep the two in sync. + */ +object SparkSendKey { + private val NAMESPACE = UUID.fromString("794acd96-39bc-4fd1-a09f-02b269a4a34d") + private val LABEL = "bitkit spark send key".encodeToByteArray() + private const val HMAC = "HmacSHA256" + private const val UUID_BYTES = 16 + + /** The secret all send keys derive from: an HMAC-SHA256 of a fixed label, keyed with the BIP39 [seed]. */ + fun secret(seed: ByteArray): ByteArray = Mac.getInstance(HMAC).run { + init(SecretKeySpec(seed, HMAC)) + doFinal(LABEL) + } + + /** + * The key of attempt [attempt] at paying the invoice with [paymentHash]: a UUIDv5 of [secret], the hash's 32 bytes + * and [attempt] as 4 bytes big-endian. + */ + fun key(secret: ByteArray, paymentHash: String, attempt: Int): String { + require(attempt >= 0) { "Attempt '$attempt' is negative" } + val name = secret + paymentHash.hexToByteArray() + ByteBuffer.allocate(Int.SIZE_BYTES) + .putInt(attempt) + .array() + val namespace = ByteBuffer.allocate(UUID_BYTES) + .putLong(NAMESPACE.mostSignificantBits) + .putLong(NAMESPACE.leastSignificantBits) + .array() + val hash = MessageDigest.getInstance("SHA-1").run { + update(namespace) + digest(name) + } + hash[6] = (hash[6].toInt() and 0x0f or 0x50).toByte() + hash[8] = (hash[8].toInt() and 0x3f or 0x80).toByte() + val bytes = ByteBuffer.wrap(hash, 0, UUID_BYTES) + return UUID(bytes.long, bytes.long).toString() + } +} diff --git a/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt b/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt index ddb19c1c21..3a6b523944 100644 --- a/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt +++ b/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt @@ -7,11 +7,22 @@ import breez_sdk_spark.Config import breez_sdk_spark.EventListener import breez_sdk_spark.GetInfoRequest import breez_sdk_spark.GetInfoResponse +import breez_sdk_spark.InputType +import breez_sdk_spark.ListPaymentsRequest import breez_sdk_spark.MaxFee import breez_sdk_spark.MaxOnchainFee +import breez_sdk_spark.Payment +import breez_sdk_spark.PaymentRequest +import breez_sdk_spark.PrepareSendPaymentRequest +import breez_sdk_spark.PrepareSendPaymentResponse +import breez_sdk_spark.ReceivePaymentMethod +import breez_sdk_spark.ReceivePaymentRequest import breez_sdk_spark.SdkBuilder import breez_sdk_spark.SdkEvent import breez_sdk_spark.Seed +import breez_sdk_spark.SendPaymentMethod +import breez_sdk_spark.SendPaymentOptions +import breez_sdk_spark.SendPaymentRequest import breez_sdk_spark.SyncWalletRequest import breez_sdk_spark.defaultConfig import breez_sdk_spark.parseSparkConfig @@ -27,10 +38,12 @@ import to.bitkit.wear.env.Env import to.bitkit.wear.env.LocalSparkSettings import to.bitkit.wear.env.WalletNetwork import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.security.Bip39 import to.bitkit.wear.security.WalletSeed import to.bitkit.wear.utils.AppError import to.bitkit.wear.utils.Logger import java.io.File +import java.math.BigInteger import java.util.Base64 import javax.inject.Inject import javax.inject.Singleton @@ -44,6 +57,7 @@ import breez_sdk_spark.Network as SparkNetwork @Singleton class WatchSparkService @Inject constructor( @ApplicationContext private val context: Context, + private val bip39: Bip39, ) { companion object { private const val TAG = "WatchSparkService" @@ -93,6 +107,13 @@ class WatchSparkService @Inject constructor( WalletNetwork.REGTEST -> SparkNetwork.REGTEST else -> null } + + /** + * Returns as soon as the payment starts, as on the phone, so the call is short and the payment's completion + * arrives as an event. + */ + internal fun bolt11SendOptions(prefersSpark: Boolean): SendPaymentOptions = + SendPaymentOptions.Bolt11Invoice(preferSpark = prefersSpark, completionTimeoutSecs = null) } private val mutex = Mutex() @@ -101,6 +122,10 @@ class WatchSparkService @Inject constructor( private var sdk: BreezSdkInterface? = null private var listenerId: String? = null + /** The connected wallet's [SparkSendKey.secret], derived from its seed at [connect]. */ + @Volatile + private var sendKeySecret: ByteArray? = null + private val _events = MutableSharedFlow(extraBufferCapacity = 64) val events: SharedFlow = _events.asSharedFlow() @@ -112,6 +137,12 @@ class WatchSparkService @Inject constructor( val isSupported: Boolean get() = sparkNetwork(Env.network, Env.breezApiKey) != null + /** + * On regtest, an invoice that carries a Spark address is paid as a Spark transfer, as on the phone. Bitkit's own + * invoices carry none, so they are paid over Lightning through Spark's provider, as on mainnet. + */ + val prefersSpark: Boolean get() = Env.network == WalletNetwork.REGTEST + /** Whether a wallet wipe is running: nothing connects during it. */ @Volatile var isWiping: Boolean = false @@ -149,10 +180,19 @@ class WatchSparkService @Inject constructor( * cannot be disconnected either, stays referenced without a listener, so the next [disconnect] reaches it and a * wipe never deletes the storage under it. */ - suspend fun connect(seed: WalletSeed, wipeToken: Int): Boolean = connectWith(wipeToken) { build(seed) } + suspend fun connect(seed: WalletSeed, wipeToken: Int): Boolean { + val secret = SparkSendKey.secret(bip39.toSeed(seed.mnemonic, seed.passphrase)) + return connectWith(wipeToken, secret) { build(seed) } + } - internal suspend fun connectWith(wipeToken: Int, build: suspend () -> BreezSdkInterface): Boolean = mutex.withLock { + internal suspend fun connectWith( + wipeToken: Int, + sendKeySecret: ByteArray? = null, + build: suspend () -> BreezSdkInterface, + ): Boolean = mutex.withLock { if (!isCurrent(wipeToken)) throw SparkError.WipeInProgress() + // The secret comes before the SDK, so a send that finds the wallet connected can derive its key. + sendKeySecret?.let { this.sendKeySecret = it } sdk?.let { if (listenerId == null) listenerId = it.addEventListener(listener) return@withLock false @@ -213,6 +253,7 @@ class WatchSparkService @Inject constructor( current.disconnect() sdk = null listenerId = null + sendKeySecret = null Logger.info("Disconnected Spark wallet", context = TAG) } } @@ -242,6 +283,65 @@ class WatchSparkService @Inject constructor( suspend fun getInfo(): GetInfoResponse = requireSdk().getInfo(GetInfoRequest(ensureSynced = false)) + /** The wallet's Spark identity public key, in hex: what its Spark address encodes. Read from local state. */ + suspend fun identityPubkey(): String = getInfo().identityPubkey + + /** Creates a BOLT11 invoice paid into the Spark balance; amountless without [amountSats]. */ + suspend fun receiveBolt11(amountSats: ULong?, description: String, expirySecs: UInt): String { + val method = ReceivePaymentMethod.Bolt11Invoice( + description = description, + amountSats = amountSats, + expirySecs = expirySecs, + paymentHash = null, + receiverIdentityPublicKey = null, + preimage = null, + ) + return requireSdk().receivePayment(ReceivePaymentRequest(method)).paymentRequest + } + + /** + * Reads [input] with the SDK's own parser. Only for a BOLT11 invoice or a Spark address, which it reads without + * a network call: anything else could be sent to a name server or an LNURL host. + */ + suspend fun parse(input: String): InputType = requireSdk().parse(input) + + /** Prices a send of [paymentRequest], a BOLT11 invoice or a Spark address; [amountSats] when it names none. */ + suspend fun prepareSend(paymentRequest: String, amountSats: ULong?): PrepareSendPaymentResponse = + requireSdk().prepareSendPayment( + PrepareSendPaymentRequest( + paymentRequest = PaymentRequest.Input(input = paymentRequest), + amount = amountSats?.let { BigInteger.valueOf(it.toLong()) }, + tokenIdentifier = null, + conversionOptions = null, + feePolicy = null, + ), + ) + + /** The idempotency key of attempt [attempt] at paying the invoice with [paymentHash], see [SparkSendKey]. */ + fun sendKey(paymentHash: String, attempt: Int): String { + val secret = sendKeySecret ?: throw SparkError.NotConnected() + return SparkSendKey.key(secret, paymentHash, attempt) + } + + /** + * Sends [prepared] as one step that its caller cannot cancel, so a send is never dropped halfway. Spark makes + * one payment per [idempotencyKey], a UUID that becomes the payment's id. + */ + suspend fun send(prepared: PrepareSendPaymentResponse, idempotencyKey: String): Payment { + val options = when (prepared.paymentMethod) { + is SendPaymentMethod.Bolt11Invoice -> bolt11SendOptions(prefersSpark) + else -> null + } + val current = requireSdk() + return withContext(NonCancellable) { + current.sendPayment(SendPaymentRequest(prepared, options, idempotencyKey)).payment + } + } + + /** The wallet's payments from Spark's local list, newest first; at most [limit] when given. */ + suspend fun listPayments(limit: UInt? = null): List = + requireSdk().listPayments(ListPaymentsRequest(limit = limit, sortAscending = false)).payments + private fun requireSdk(): BreezSdkInterface = sdk ?: throw SparkError.NotConnected() } diff --git a/wear/src/test/java/to/bitkit/wear/security/Fakes.kt b/wear/src/test/java/to/bitkit/wear/security/Fakes.kt index 03510f397e..2a9e957b88 100644 --- a/wear/src/test/java/to/bitkit/wear/security/Fakes.kt +++ b/wear/src/test/java/to/bitkit/wear/security/Fakes.kt @@ -25,6 +25,9 @@ class FakeBip39 : Bip39 { else -> Bip39Validation.InvalidChecksum } } + + override fun toSeed(mnemonic: String, passphrase: String?): ByteArray = + "$mnemonic|${passphrase.orEmpty()}".encodeToByteArray() } class FakeForegroundMonitor(isForeground: Boolean = true) : ForegroundMonitor { diff --git a/wear/src/test/java/to/bitkit/wear/services/SparkFixtures.kt b/wear/src/test/java/to/bitkit/wear/services/SparkFixtures.kt new file mode 100644 index 0000000000..cbb1fcab16 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/services/SparkFixtures.kt @@ -0,0 +1,124 @@ +package to.bitkit.wear.services + +import breez_sdk_spark.BitcoinNetwork +import breez_sdk_spark.Bolt11Invoice +import breez_sdk_spark.Bolt11InvoiceDetails +import breez_sdk_spark.Bolt11RouteHint +import breez_sdk_spark.Bolt11RouteHintHop +import breez_sdk_spark.GetInfoResponse +import breez_sdk_spark.InputType +import breez_sdk_spark.Payment +import breez_sdk_spark.PaymentDetails +import breez_sdk_spark.PaymentMethod +import breez_sdk_spark.PaymentRequestSource +import breez_sdk_spark.PaymentStatus +import breez_sdk_spark.PaymentType +import breez_sdk_spark.SparkAddressDetails +import breez_sdk_spark.SparkHtlcDetails +import breez_sdk_spark.SparkHtlcStatus +import java.math.BigInteger + +/** + * What Breez SDK 0.28.3 printed on the local regtest Spark stack for one wallet's invoices and Spark address + * (2026-11-27). [IDENTITY] is the wallet's `getInfo().identityPubkey`. An invoice made with Bitkit's settings names + * only [PROVIDER_NODE], Spark's Lightning node, as payee and [PROVIDER_HINT], a channel of that node. With the SDK's + * `preferSparkOverLightning` on, the invoice also carries [SPARK_ADDRESS_HINT], whose node is the identity. + */ +object SparkFixtures { + const val IDENTITY = "02698b27ac308b275671b3ca25436346469d04a5bba578ae39feba1d65897a6abc" + const val OTHER_IDENTITY = "03a1b2c3d4e5f60718293a4b5c6d7e8f9001122334455667788990aabbccddeeff" + const val PROVIDER_NODE = "0313ee54b3e35eed377248c83e77004972a3807af648a22ea1e8a9d22ef8b9a11c" + const val SPARK_ADDRESS = "sparkrt1pgssy6vty7krpze82ecm8j39gd35v35aqjjmhftc4culawsavkyh564u2uv8v0" + const val PAYMENT_HASH = "0a00a78ffbde5c36ad8220a26bb2609347bbf7e7c195622c42b81f088ccf1f6e" + const val TIMESTAMP = 1_795_827_219uL + const val EXPIRY = 3_600uL + + val PROVIDER_HINT = hint("026ccad2762df4865753f7adc464acdbb9ae4509d0f2109789b91941cfe0e67261", "1x1026x2") + val SPARK_ADDRESS_HINT = hint(IDENTITY, "16000000x16000000x1") + + fun hint(srcNodeId: String, shortChannelId: String) = Bolt11RouteHint( + listOf( + Bolt11RouteHintHop( + srcNodeId = srcNodeId, + shortChannelId = shortChannelId, + feesBaseMsat = 0u, + feesProportionalMillionths = 0u, + cltvExpiryDelta = 0u, + htlcMinimumMsat = null, + htlcMaximumMsat = null, + ), + ), + ) + + /** An invoice as Bitkit creates it, unless other [hints] are given. */ + fun invoice( + bolt11: String = "lnbcrt1invoice", + paymentHash: String = PAYMENT_HASH, + amountMsat: ULong? = null, + hints: List = listOf(PROVIDER_HINT), + ) = Bolt11InvoiceDetails( + amountMsat = amountMsat, + description = "", + descriptionHash = null, + expiry = EXPIRY, + invoice = Bolt11Invoice(bolt11, PaymentRequestSource(null, null)), + minFinalCltvExpiryDelta = 60uL, + network = BitcoinNetwork.REGTEST, + payeePubkey = PROVIDER_NODE, + paymentHash = paymentHash, + paymentSecret = "secret", + routingHints = hints, + timestamp = TIMESTAMP, + ) + + fun invoiceInput( + bolt11: String = "lnbcrt1invoice", + paymentHash: String = PAYMENT_HASH, + hints: List = listOf(PROVIDER_HINT), + ): InputType = InputType.Bolt11Invoice(invoice(bolt11, paymentHash, hints = hints)) + + fun sparkAddressInput(identity: String = IDENTITY, address: String = SPARK_ADDRESS): InputType = + InputType.SparkAddress( + SparkAddressDetails(address, identity, BitcoinNetwork.REGTEST, PaymentRequestSource(null, null)), + ) + + fun info(balanceSats: ULong, identityPubkey: String = IDENTITY) = GetInfoResponse( + identityPubkey = identityPubkey, + balanceSats = balanceSats, + tokenBalances = emptyMap(), + recoverableFundsSats = 0uL, + lastSyncError = null, + lastSyncedAt = 1uL, + ) + + fun payment( + id: String, + status: PaymentStatus, + type: PaymentType = PaymentType.SEND, + paymentHash: String? = PAYMENT_HASH, + amountSats: Long = 1_000, + feeSats: Long = 3, + timestamp: ULong = TIMESTAMP, + ) = Payment( + id = id, + paymentType = type, + status = status, + amount = BigInteger.valueOf(amountSats), + fees = BigInteger.valueOf(feeSats), + timestamp = timestamp, + method = PaymentMethod.LIGHTNING, + details = paymentHash?.let { + PaymentDetails.Lightning( + description = null, + invoice = "lnbcrt1invoice", + destinationPubkey = PROVIDER_NODE, + htlcDetails = SparkHtlcDetails(it, null, TIMESTAMP + EXPIRY, SparkHtlcStatus.WAITING_FOR_PREIMAGE), + lnurlPayInfo = null, + lnurlWithdrawInfo = null, + lnurlReceiveMetadata = null, + conversionInfo = null, + ) + }, + conversionDetails = null, + ) +} diff --git a/wear/src/test/java/to/bitkit/wear/services/SparkSendKeyTest.kt b/wear/src/test/java/to/bitkit/wear/services/SparkSendKeyTest.kt new file mode 100644 index 0000000000..71ab74fa33 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/services/SparkSendKeyTest.kt @@ -0,0 +1,44 @@ +package to.bitkit.wear.services + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals + +class SparkSendKeyTest { + private companion object { + /** The BIP39 seed of `abandon … about` with passphrase `TREZOR`, from the BIP39 test vectors. */ + const val SEED = "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e534955" + + "31f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04" + + /** Bytes 0 to 31. */ + const val PAYMENT_HASH = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + } + + // The phone's SparkSendKeyTest and iOS's SparkSendKeyTests assert the same vector, so the watch, the phone and a + // wallet restored on the other app all derive the same keys. + @Test + fun `derives the shared test vector`() { + val secret = SparkSendKey.secret(SEED.hexToByteArray()) + + assertEquals("577ceb10411255cef07e3f49bd7e5239de07586c7457f65ee72ee53737361a98", secret.toHexString()) + assertEquals("8d92d8bf-76f3-56fe-8958-8e440acb64fc", SparkSendKey.key(secret, PAYMENT_HASH, 0)) + assertEquals("712dea1f-8268-5e52-a280-aac86bc60b59", SparkSendKey.key(secret, PAYMENT_HASH, 1)) + } + + @Test + fun `reads the payment hash in either case`() { + val secret = SparkSendKey.secret(SEED.hexToByteArray()) + + assertEquals( + SparkSendKey.key(secret, PAYMENT_HASH, 0), + SparkSendKey.key(secret, PAYMENT_HASH.uppercase(), 0), + ) + } + + @Test + fun `another seed derives other keys`() { + val other = SparkSendKey.secret(ByteArray(64)) + + assertNotEquals("8d92d8bf-76f3-56fe-8958-8e440acb64fc", SparkSendKey.key(other, PAYMENT_HASH, 0)) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt b/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt index 1194403b4d..19e3feee3e 100644 --- a/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt +++ b/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt @@ -4,8 +4,20 @@ import android.content.Context import breez_sdk_spark.BreezSdkInterface import breez_sdk_spark.ChainApiType import breez_sdk_spark.Config +import breez_sdk_spark.FeePolicy import breez_sdk_spark.LeafOptimizationConfig +import breez_sdk_spark.ListPaymentsRequest +import breez_sdk_spark.ListPaymentsResponse import breez_sdk_spark.Network +import breez_sdk_spark.PaymentStatus +import breez_sdk_spark.PrepareSendPaymentResponse +import breez_sdk_spark.ReceivePaymentMethod +import breez_sdk_spark.ReceivePaymentRequest +import breez_sdk_spark.ReceivePaymentResponse +import breez_sdk_spark.SendPaymentMethod +import breez_sdk_spark.SendPaymentOptions +import breez_sdk_spark.SendPaymentRequest +import breez_sdk_spark.SendPaymentResponse import breez_sdk_spark.TokenOptimizationConfig import kotlinx.coroutines.Job import kotlinx.coroutines.launch @@ -24,7 +36,9 @@ import org.mockito.kotlin.whenever import to.bitkit.wear.env.Env import to.bitkit.wear.env.LocalSparkSettings import to.bitkit.wear.env.WalletNetwork +import to.bitkit.wear.security.FakeBip39 import java.io.File +import java.math.BigInteger import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse @@ -83,9 +97,103 @@ class WatchSparkServiceTest { assertNull(WatchSparkService.sparkNetwork(WalletNetwork.BITCOIN, "key")) } + @Test + fun `a send key needs the connected wallet's secret and is gone after the disconnect`() = runTest { + val sut = WatchSparkService(mock(), FakeBip39()) + val sdk = connectedSdk() + assertFailsWith { sut.sendKey(SparkFixtures.PAYMENT_HASH, 0) } + + sut.connectWith(assertNotNull(sut.wipeToken()), sendKeySecret = ByteArray(32) { 1 }) { sdk } + + val key = sut.sendKey(SparkFixtures.PAYMENT_HASH, 0) + assertEquals(SparkSendKey.key(ByteArray(32) { 1 }, SparkFixtures.PAYMENT_HASH, 0), key) + assertTrue(key != sut.sendKey(SparkFixtures.PAYMENT_HASH, 1)) + + sut.disconnect() + assertFailsWith { sut.sendKey(SparkFixtures.PAYMENT_HASH, 0) } + } + + @Test + fun `a receive invoice is asked of spark without an amount, a hash or another receiver`() = runTest { + val sut = WatchSparkService(mock(), FakeBip39()) + val sdk = connectedSdk() + whenever(sdk.receivePayment(any())).thenReturn(ReceivePaymentResponse("lnbcrt1invoice", BigInteger.ZERO, null)) + sut.connectWith(assertNotNull(sut.wipeToken())) { sdk } + + assertEquals("lnbcrt1invoice", sut.receiveBolt11(amountSats = null, description = "", expirySecs = 3_600u)) + + val expected = ReceivePaymentMethod.Bolt11Invoice("", null, 3_600u, null, null, null) + verify(sdk).receivePayment(ReceivePaymentRequest(expected)) + } + + @Test + fun `a send carries its idempotency key and returns once the payment starts`() = runTest { + val sut = WatchSparkService(mock(), FakeBip39()) + val sdk = connectedSdk() + val prepared = PrepareSendPaymentResponse( + SendPaymentMethod.Bolt11Invoice(SparkFixtures.invoice(), null, 4uL), + BigInteger.valueOf(500), + null, + null, + FeePolicy.FEES_EXCLUDED, + ) + val payment = SparkFixtures.payment("key", PaymentStatus.PENDING) + whenever(sdk.sendPayment(any())).thenReturn(SendPaymentResponse(payment)) + sut.connectWith(assertNotNull(sut.wipeToken())) { sdk } + + assertEquals(payment, sut.send(prepared, "key")) + + val options = SendPaymentOptions.Bolt11Invoice(preferSpark = sut.prefersSpark, completionTimeoutSecs = null) + verify(sdk).sendPayment(SendPaymentRequest(prepared, options, "key")) + } + + @Test + fun `a send whose caller gives up still reaches spark`() = runTest { + val sut = WatchSparkService(mock(), FakeBip39()) + val sdk = connectedSdk() + val prepared = PrepareSendPaymentResponse( + SendPaymentMethod.Bolt11Invoice(SparkFixtures.invoice(), null, 4uL), + BigInteger.valueOf(500), + null, + null, + FeePolicy.FEES_EXCLUDED, + ) + lateinit var caller: Job + var isSent = false + whenever(sdk.sendPayment(any())).doSuspendableAnswer { + caller.cancel() + yield() + isSent = true + SendPaymentResponse(SparkFixtures.payment("key", PaymentStatus.PENDING)) + } + sut.connectWith(assertNotNull(sut.wipeToken())) { sdk } + + caller = launch { sut.send(prepared, "key") } + caller.join() + + assertTrue(isSent) + } + + @Test + fun `payments are listed newest first, up to the limit`() = runTest { + val sut = WatchSparkService(mock(), FakeBip39()) + val sdk = connectedSdk() + whenever(sdk.listPayments(any())).thenReturn(ListPaymentsResponse(emptyList())) + sut.connectWith(assertNotNull(sut.wipeToken())) { sdk } + + sut.listPayments(20u) + + verify(sdk).listPayments(ListPaymentsRequest(limit = 20u, sortAscending = false)) + } + + private suspend fun connectedSdk(): BreezSdkInterface = mock().also { + whenever(it.addEventListener(any())).thenReturn("listener") + whenever(it.removeEventListener(any())).thenReturn(true) + } + @Test fun `no wipe token is handed out while a wipe runs, and one read before a wipe is refused after it`() = runTest { - val sut = WatchSparkService(mock()) + val sut = WatchSparkService(mock(), FakeBip39()) val before = assertNotNull(sut.wipeToken()) assertTrue(sut.isCurrent(before)) @@ -102,7 +210,7 @@ class WatchSparkServiceTest { @Test fun `a current token connects once`() = runTest { - val sut = WatchSparkService(mock()) + val sut = WatchSparkService(mock(), FakeBip39()) val sdk = mock() whenever(sdk.addEventListener(any())).thenReturn("listener") whenever(sdk.removeEventListener(any())).thenReturn(true) @@ -118,7 +226,7 @@ class WatchSparkServiceTest { @Test fun `a connect whose caller gives up after the sdk is built keeps it, so it is disconnected later`() = runTest { - val sut = WatchSparkService(mock()) + val sut = WatchSparkService(mock(), FakeBip39()) val sdk = mock() lateinit var caller: Job whenever(sdk.addEventListener(any())).doSuspendableAnswer { @@ -139,7 +247,7 @@ class WatchSparkServiceTest { @Test fun `an sdk whose listener cannot be added is disconnected at once`() = runTest { - val sut = WatchSparkService(mock()) + val sut = WatchSparkService(mock(), FakeBip39()) val sdk = mock() whenever(sdk.addEventListener(any())).thenAnswer { throw SparkError.NotConnected() } val token = assertNotNull(sut.wipeToken()) @@ -152,7 +260,7 @@ class WatchSparkServiceTest { @Test fun `an sdk built while a wipe began is disconnected and never used`() = runTest { - val sut = WatchSparkService(mock()) + val sut = WatchSparkService(mock(), FakeBip39()) val sdk = mock() val token = assertNotNull(sut.wipeToken()) @@ -170,7 +278,7 @@ class WatchSparkServiceTest { @Test fun `an sdk that gets no listener and cannot be disconnected is kept for the next disconnect`() = runTest { - val sut = WatchSparkService(mock()) + val sut = WatchSparkService(mock(), FakeBip39()) val sdk = mock() var failures = 1 whenever(sdk.addEventListener(any())).thenAnswer { throw SparkError.NotConnected() } @@ -187,7 +295,7 @@ class WatchSparkServiceTest { @Test fun `an sdk built during a wipe that cannot be disconnected fails the wipe, which keeps the storage`() = runTest { - val sut = WatchSparkService(context()) + val sut = WatchSparkService(context(), FakeBip39()) val sdk = mock() val storage = storage() whenever(sdk.disconnect()).thenAnswer { throw SparkError.NotConnected() } @@ -208,7 +316,7 @@ class WatchSparkServiceTest { @Test fun `a stale token is refused over an sdk kept by a disconnect that failed, which gets no listener`() = runTest { - val sut = WatchSparkService(mock()) + val sut = WatchSparkService(mock(), FakeBip39()) val sdk = connected(sut) whenever(sdk.disconnect()).thenAnswer { throw SparkError.NotConnected() } val token = assertNotNull(sut.wipeToken()) @@ -222,7 +330,7 @@ class WatchSparkServiceTest { @Test fun `a listener that cannot be removed does not stop the disconnect`() = runTest { - val sut = WatchSparkService(mock()) + val sut = WatchSparkService(mock(), FakeBip39()) val sdk = connected(sut) whenever(sdk.removeEventListener(any())).thenAnswer { throw SparkError.NotConnected() } @@ -234,7 +342,7 @@ class WatchSparkServiceTest { @Test fun `a disconnect that fails keeps the sdk, so the next one reaches it`() = runTest { - val sut = WatchSparkService(mock()) + val sut = WatchSparkService(mock(), FakeBip39()) val sdk = connected(sut) var failures = 1 whenever(sdk.disconnect()).thenAnswer { if (failures-- > 0) throw SparkError.NotConnected() } @@ -250,7 +358,7 @@ class WatchSparkServiceTest { @Test fun `a listener removed by a disconnect that failed is not removed twice`() = runTest { - val sut = WatchSparkService(mock()) + val sut = WatchSparkService(mock(), FakeBip39()) val sdk = connected(sut) var failures = 1 whenever(sdk.disconnect()).thenAnswer { if (failures-- > 0) throw SparkError.NotConnected() } @@ -263,7 +371,7 @@ class WatchSparkServiceTest { @Test fun `an sdk kept by a disconnect that failed gets its listener back when it connects again`() = runTest { - val sut = WatchSparkService(mock()) + val sut = WatchSparkService(mock(), FakeBip39()) val sdk = connected(sut) whenever(sdk.disconnect()).thenAnswer { throw SparkError.NotConnected() } assertFailsWith { sut.disconnect() } @@ -276,7 +384,7 @@ class WatchSparkServiceTest { @Test fun `a wipe tries a disconnect that failed again, then deletes the storage`() = runTest { - val sut = WatchSparkService(context()) + val sut = WatchSparkService(context(), FakeBip39()) val sdk = connected(sut) val storage = storage() var failures = 1 @@ -291,7 +399,7 @@ class WatchSparkServiceTest { @Test fun `a wipe that cannot disconnect spark fails, and keeps the sdk and its storage`() = runTest { - val sut = WatchSparkService(context()) + val sut = WatchSparkService(context(), FakeBip39()) val sdk = connected(sut) val storage = storage() whenever(sdk.disconnect()).thenAnswer { throw SparkError.NotConnected() } @@ -305,7 +413,7 @@ class WatchSparkServiceTest { @Test fun `a disconnect whose caller is cancelled still disconnects`() = runTest { - val sut = WatchSparkService(mock()) + val sut = WatchSparkService(mock(), FakeBip39()) val sdk = connected(sut) lateinit var caller: Job whenever(sdk.removeEventListener(any())).doSuspendableAnswer { From 925ac668817697972e18a90a4bc817325338597c Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Fri, 27 Nov 2026 22:08:48 -0300 Subject: [PATCH 02/33] feat: add wear payments repository with self-send guard Co-Authored-By: Claude Fable 5.2 --- .../to/bitkit/wear/data/OwnInvoiceStore.kt | 65 ++ .../java/to/bitkit/wear/di/SecurityModule.kt | 18 + .../java/to/bitkit/wear/models/Payments.kt | 132 +++ .../bitkit/wear/repositories/PaymentsRepo.kt | 417 ++++++++++ .../to/bitkit/wear/services/InputDecoder.kt | 28 + .../to/bitkit/wear/services/SelfSendGuard.kt | 60 ++ .../bitkit/wear/data/OwnInvoiceStoreTest.kt | 103 +++ .../wear/repositories/PaymentsRepoTest.kt | 755 ++++++++++++++++++ .../bitkit/wear/services/SelfSendGuardTest.kt | 93 +++ 9 files changed, 1671 insertions(+) create mode 100644 wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt create mode 100644 wear/src/main/java/to/bitkit/wear/models/Payments.kt create mode 100644 wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt create mode 100644 wear/src/main/java/to/bitkit/wear/services/InputDecoder.kt create mode 100644 wear/src/main/java/to/bitkit/wear/services/SelfSendGuard.kt create mode 100644 wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt create mode 100644 wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt create mode 100644 wear/src/test/java/to/bitkit/wear/services/SelfSendGuardTest.kt diff --git a/wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt b/wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt new file mode 100644 index 0000000000..d3308e3e10 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt @@ -0,0 +1,65 @@ +package to.bitkit.wear.data + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringSetPreferencesKey +import kotlinx.coroutines.flow.first +import javax.inject.Inject +import javax.inject.Singleton + +/** + * The payment hashes of the invoices this wallet created and that can still be paid, which the wallet refuses to pay + * itself. The watch adds each invoice it creates; a paired phone's hashes can be merged in with [add] too. + */ +interface OwnInvoiceStore { + /** Remembers the invoice with [paymentHash], in hex, until [expiresAtSecs], its expiry in epoch seconds. */ + suspend fun add(paymentHash: String, expiresAtSecs: ULong) + + /** Whether [paymentHash], in hex of either case, is an unexpired invoice of this wallet. */ + suspend fun contains(paymentHash: String): Boolean +} + +/** + * [OwnInvoiceStore] in the watch's settings file, so the wallet's wipe clears it with the settings. Expired invoices + * are dropped on every [add], as nobody can pay them, and at most [MAX_INVOICES] are kept: the ones that expire last. + */ +@Singleton +class SettingsOwnInvoiceStore internal constructor( + private val dataStore: DataStore, + private val nowSecs: () -> ULong, +) : OwnInvoiceStore { + companion object { + const val MAX_INVOICES = 200 + private const val SEPARATOR = ':' + private const val MILLIS_PER_SEC = 1_000L + } + + @Inject + constructor(dataStore: DataStore) : + this(dataStore, { (System.currentTimeMillis() / MILLIS_PER_SEC).toULong() }) + + private val key = stringSetPreferencesKey("own_invoices") + + override suspend fun add(paymentHash: String, expiresAtSecs: ULong) { + val now = nowSecs() + dataStore.edit { prefs -> + val invoices = decode(prefs[key]) + (paymentHash.lowercase() to expiresAtSecs) + prefs[key] = invoices.entries + .filter { it.value > now } + .sortedByDescending { it.value } + .take(MAX_INVOICES) + .mapTo(HashSet()) { "${it.key}$SEPARATOR${it.value}" } + } + } + + override suspend fun contains(paymentHash: String): Boolean { + val expiresAt = decode(dataStore.data.first()[key])[paymentHash.lowercase()] ?: return false + return expiresAt > nowSecs() + } + + private fun decode(entries: Set?): Map = entries.orEmpty().mapNotNull { entry -> + val expiresAt = entry.substringAfter(SEPARATOR, "").toULongOrNull() ?: return@mapNotNull null + entry.substringBefore(SEPARATOR) to expiresAt + }.toMap() +} diff --git a/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt b/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt index 50569961da..7f5651e14d 100644 --- a/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt +++ b/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt @@ -18,7 +18,9 @@ import to.bitkit.wear.data.ConnectivityNetworkMonitor import to.bitkit.wear.data.ForegroundMonitor import to.bitkit.wear.data.NetworkMonitor import to.bitkit.wear.data.NfcMonitor +import to.bitkit.wear.data.OwnInvoiceStore import to.bitkit.wear.data.ProcessForegroundMonitor +import to.bitkit.wear.data.SettingsOwnInvoiceStore import to.bitkit.wear.data.WipeMarker import to.bitkit.wear.data.settingsDataStore import to.bitkit.wear.env.Env @@ -30,6 +32,10 @@ import to.bitkit.wear.security.KeyguardDeviceLock import to.bitkit.wear.security.KeystoreSeedStore import to.bitkit.wear.security.SeedKey import to.bitkit.wear.security.SeedStore +import to.bitkit.wear.services.CoreInputDecoder +import to.bitkit.wear.services.InputDecoder +import to.bitkit.wear.services.SelfSendGuard +import to.bitkit.wear.services.WalletSelfSendGuard import java.io.File import javax.inject.Singleton @@ -60,6 +66,18 @@ abstract class SecurityModule { @Singleton abstract fun bindBip39(bip39: CoreBip39): Bip39 + @Binds + @Singleton + abstract fun bindInputDecoder(decoder: CoreInputDecoder): InputDecoder + + @Binds + @Singleton + abstract fun bindOwnInvoiceStore(store: SettingsOwnInvoiceStore): OwnInvoiceStore + + @Binds + @Singleton + abstract fun bindSelfSendGuard(guard: WalletSelfSendGuard): SelfSendGuard + companion object { private const val SEED_DIR = "seed" private const val SETTINGS_NAME = "settings" diff --git a/wear/src/main/java/to/bitkit/wear/models/Payments.kt b/wear/src/main/java/to/bitkit/wear/models/Payments.kt new file mode 100644 index 0000000000..8a1206ab3e --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/models/Payments.kt @@ -0,0 +1,132 @@ +package to.bitkit.wear.models + +import breez_sdk_spark.PrepareSendPaymentResponse +import com.synonym.bitkitcore.LnurlPayData +import to.bitkit.wear.utils.AppError + +/** An amountless BOLT11 invoice of this wallet, for the receive QR. [expiresAtSecs] is in epoch seconds. */ +data class ReceiveInvoice( + val bolt11: String, + val paymentHash: String, + val expiresAtSecs: ULong, +) { + fun isExpired(nowSecs: ULong): Boolean = nowSecs >= expiresAtSecs +} + +/** What a scanned or opened payment input asks for, before anything is priced. */ +sealed interface SendRequest { + /** The amount the input fixes, or null when the wearer picks it. */ + val fixedAmountSats: ULong? + + /** One short line naming who is paid, or null when the input names nobody. */ + val payee: String? + + /** A BOLT11 invoice; [amountSats] is null for an amountless one. */ + data class Invoice( + val bolt11: String, + val amountSats: ULong?, + val description: String?, + ) : SendRequest { + override val fixedAmountSats: ULong? get() = amountSats + override val payee: String? get() = description + } + + /** + * An LNURL-pay request or a Lightning address, which takes any whole amount from [minSats] to [maxSats]. [payee] + * is the Lightning address, or else the host that answered. + */ + data class Lnurl( + val data: LnurlPayData, + val minSats: ULong, + val maxSats: ULong, + override val payee: String?, + ) : SendRequest { + override val fixedAmountSats: ULong? get() = minSats.takeIf { it == maxSats } + } + + /** A Spark address, which names no amount. */ + data class SparkAddress(val address: String) : SendRequest { + override val fixedAmountSats: ULong? get() = null + override val payee: String? get() = null + } +} + +/** + * A send that Spark priced and the checks passed: what the review screen shows and the hold confirms. It is only made + * by `PaymentsRepo.prepare` and sent by `PaymentsRepo.send`. + */ +class PreparedSend internal constructor( + val amountSats: ULong, + val feeSats: ULong, + val payee: String?, + internal val response: PrepareSendPaymentResponse, + /** The invoice's payment hash, or null for a Spark address. */ + internal val paymentHash: String?, + /** The idempotency key of a send without a payment hash, made once so a repeated send pays once. */ + internal val transferKey: String?, +) { + val totalSats: ULong get() = amountSats + feeSats +} + +enum class PaymentState { Completed, Pending, Failed } + +/** A payment of this wallet as the activity list shows it. [timestampSecs] is in epoch seconds. */ +data class WatchPayment( + val id: String, + val isSent: Boolean, + val amountSats: ULong, + val feeSats: ULong, + val timestampSecs: ULong, + val state: PaymentState, +) + +/** + * Why an input cannot be paid, or a send did not go through. Every case but [Unknown] means nothing left the wallet + * for this request. + */ +sealed class SendError(message: String, cause: Throwable? = null) : AppError(message, cause) { + /** The wallet is not connected and synced, so it neither prices nor sends. */ + class NotReady : SendError("The wallet is not ready to pay") + + /** The input is not a payment request at all, or it cannot be read. */ + class Invalid(cause: Throwable? = null) : SendError("The payment request cannot be read", cause) + + /** A payment request the watch does not pay, such as an on-chain address. */ + class Unsupported : SendError("The watch cannot pay this kind of request") + + class Expired(cause: Throwable? = null) : SendError("The invoice has expired", cause) + + /** The request pays this wallet, which the phone and the watch share. */ + class OwnInvoice : SendError("The payment request was created by this wallet") + + /** The request names no amount and none was given. */ + class AmountRequired : SendError("The payment request needs an amount") + + /** The amount is zero, or outside what the LNURL service takes, in sats. */ + class AmountOutOfRange(val minSats: ULong, val maxSats: ULong) : + SendError("The amount is outside '$minSats' to '$maxSats' sats") + + /** The balance does not cover the amount and its fee; [shortfallSats] is what is missing, when known. */ + class InsufficientBalance(val shortfallSats: ULong?) : SendError("The balance is '$shortfallSats' sats short") + + /** This wallet already paid the invoice. */ + class AlreadyPaid : SendError("The invoice is already paid") + + /** A send of this invoice is still under way, from the watch or the phone. */ + class InFlight : SendError("A payment of this invoice is under way") + + /** Spark refused or failed the payment. */ + class Failed(cause: Throwable? = null) : SendError("The payment failed", cause) + + /** + * The send was handed to Spark and its outcome could not be learned: it may have been paid. Never shown as a + * plain failure; the activity list tells once Spark lists it, and sending the same invoice again cannot pay twice. + */ + class Unknown(cause: Throwable? = null) : SendError("The payment's outcome is not known yet", cause) +} + +/** Why an invoice to receive with could not be made. */ +sealed class ReceiveError(message: String, cause: Throwable? = null) : AppError(message, cause) { + /** The wallet is not connected and synced, so Spark cannot make an invoice. */ + class NotReady : ReceiveError("The wallet is not ready to receive") +} diff --git a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt new file mode 100644 index 0000000000..d36cd21bb1 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -0,0 +1,417 @@ +package to.bitkit.wear.repositories + +import breez_sdk_spark.Bolt11InvoiceDetails +import breez_sdk_spark.InputType +import breez_sdk_spark.Payment +import breez_sdk_spark.PaymentDetails +import breez_sdk_spark.PaymentStatus +import breez_sdk_spark.PaymentType +import breez_sdk_spark.PrepareSendPaymentResponse +import breez_sdk_spark.SdkEvent +import breez_sdk_spark.SdkException +import breez_sdk_spark.SendPaymentMethod +import com.synonym.bitkitcore.LightningInvoice +import com.synonym.bitkitcore.LnurlPayData +import com.synonym.bitkitcore.Scanner +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.channelFlow +import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.mapNotNull +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull +import to.bitkit.wear.data.OwnInvoiceStore +import to.bitkit.wear.di.IoDispatcher +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.models.PaymentState +import to.bitkit.wear.models.PreparedSend +import to.bitkit.wear.models.ReceiveError +import to.bitkit.wear.models.ReceiveInvoice +import to.bitkit.wear.models.SendError +import to.bitkit.wear.models.SendRequest +import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.services.InputDecoder +import to.bitkit.wear.services.SelfSendGuard +import to.bitkit.wear.services.WatchSparkService +import to.bitkit.wear.utils.Logger +import java.net.URI +import java.util.Collections +import java.util.UUID +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Duration.Companion.seconds + +/** + * Receiving and sending with the watch's Spark wallet. Everything that reaches Spark needs the wallet at + * [WalletStatus.Ready]: connected and synced in this session. Nothing here connects the wallet; `WalletRepo` does. + */ +@Singleton +class PaymentsRepo @Inject constructor( + @IoDispatcher private val ioDispatcher: CoroutineDispatcher, + private val sparkService: WatchSparkService, + private val walletRepo: WalletRepo, + private val inputDecoder: InputDecoder, + private val selfSendGuard: SelfSendGuard, + private val ownInvoiceStore: OwnInvoiceStore, +) { + companion object { + private const val TAG = "PaymentsRepo" + private const val MSATS_PER_SAT = 1_000uL + + /** How long a receive invoice lives. The receive screen makes a new one when it expires. */ + const val INVOICE_EXPIRY_SECS = 3_600u + + /** How many payments the activity list shows. */ + const val RECENT_PAYMENTS_LIMIT = 20 + + /** How long [send] waits for a payment that Spark took to settle, before it reports it as pending. */ + val SETTLE_TIMEOUT = 60.seconds + + /** Every bitcoin there will be, in sats: no amount is above it. */ + private const val MAX_SATS = 2_100_000_000_000_000uL + + private val SPARK_ADDRESS = Regex("^(spark|sp)(rt|t|s|l)?1[02-9ac-hj-np-z]+$", RegexOption.IGNORE_CASE) + private const val SPARK_SCHEME = "spark:" + + /** [input] without its `spark:` scheme when it has the shape of a Spark address, or null. */ + internal fun sparkAddressOrNull(input: String): String? { + val text = if (input.startsWith(SPARK_SCHEME, ignoreCase = true)) input.drop(SPARK_SCHEME.length) else input + return text.takeIf { SPARK_ADDRESS.matches(it) } + } + } + + private val sendMutex = Mutex() + + /** Keys of sends whose outcome was not learned, so a later refusal under the same key is not read as unsent. */ + private val uncertainKeys: MutableSet = Collections.synchronizedSet(HashSet()) + + /** Emits whenever Spark reports a payment or a sync, so the activity list reads [recentPayments] again. */ + val paymentChanges: Flow get() = sparkService.events.map { } + + /** + * Whether a send goes out without the hold to pay (QuickPay). Always false until the watch has QuickPay settings + * (PR 3), which check [prepared] against the wearer's limit here and nowhere else. + */ + @Suppress("FunctionOnlyReturningConstant", "UNUSED_PARAMETER") + fun skipConfirmation(prepared: PreparedSend): Boolean = false + + /** + * Creates an amountless BOLT11 invoice paid into the Spark balance, valid for [INVOICE_EXPIRY_SECS], and + * remembers it as this wallet's own, which the self-send guard refuses to pay. An invoice that cannot be + * remembered is not handed out. + */ + suspend fun createInvoice(): Result = withContext(ioDispatcher) { + runSuspendCatching { + if (!isReady()) throw ReceiveError.NotReady() + val bolt11 = sparkService.receiveBolt11(amountSats = null, description = "", INVOICE_EXPIRY_SECS) + val details = (sparkService.parse(bolt11) as InputType.Bolt11Invoice).v1 + // Remembered before it is shown, so the watch never pays an invoice it handed out. + ownInvoiceStore.add(details.paymentHash, details.expiresAt) + ReceiveInvoice(bolt11, details.paymentHash, details.expiresAt) + }.onFailure { + Logger.error("Failed to create an invoice", it, context = TAG) + } + } + + /** + * Waits until [invoice] is paid and returns the payment. It never ends by itself otherwise: the caller cancels + * it when the invoice expires or the screen closes. A payment that arrived before the call, or while the wallet + * was disconnected, is found in Spark's list, which is read at the start and after every sync. + */ + suspend fun awaitPaid(invoice: ReceiveInvoice): WatchPayment = withContext(ioDispatcher) { + channelFlow { + launch(start = CoroutineStart.UNDISPATCHED) { + sparkService.events.collect { event -> + val paid = event.payment()?.takeIf { it.isReceiptOf(invoice) } + ?: if (event is SdkEvent.Synced) findReceipt(invoice) else null + paid?.let { send(it) } + } + } + findReceipt(invoice)?.let { send(it) } + }.first().toWatchPayment() + } + + private suspend fun findReceipt(invoice: ReceiveInvoice): Payment? = + runSuspendCatching { sparkService.listPayments().firstOrNull { it.isReceiptOf(invoice) } }.getOrNull() + + /** + * Reads a payment input: a BOLT11 invoice, an LNURL-pay link, a Lightning address, a BIP21 URI with a + * `lightning` parameter or a Spark address, each with or without its URI scheme. An LNURL or a Lightning address + * is fetched from its host. Fails with a [SendError]: [SendError.Invalid], [SendError.Unsupported], + * [SendError.Expired], and [SendError.OwnInvoice] when the wallet is ready to tell. A Spark address needs the + * wallet ready ([SendError.NotReady]); the other inputs are read without it, and [prepare] checks them again. + */ + suspend fun parse(input: String): Result = withContext(ioDispatcher) { + runSuspendCatching { + val text = input.trim() + val sparkAddress = sparkAddressOrNull(text) + val request = if (sparkAddress != null) SendRequest.SparkAddress(sparkAddress) else decode(text) + when (request) { + is SendRequest.Invoice -> if (isReady()) ensureNotOwn(request.bolt11) + is SendRequest.SparkAddress -> { + if (!isReady()) throw SendError.NotReady() + ensureNotOwn(request.address) + } + is SendRequest.Lnurl -> Unit + } + request + }.onFailure { + Logger.warn("Failed to read a payment input", it, context = TAG) + } + } + + private suspend fun decode(text: String): SendRequest { + val scanned = runSuspendCatching { inputDecoder.decode(text) }.getOrElse { throw SendError.Invalid(it) } + return when (scanned) { + is Scanner.Lightning -> scanned.invoice.toRequest() + is Scanner.LnurlPay -> scanned.data.toRequest(text) + is Scanner.OnChain -> { + val bolt11 = scanned.invoice.params?.get("lightning") ?: throw SendError.Unsupported() + val invoice = runSuspendCatching { inputDecoder.decode(bolt11) as? Scanner.Lightning } + .getOrElse { throw SendError.Invalid(it) } + invoice?.invoice?.toRequest() ?: throw SendError.Unsupported() + } + else -> throw SendError.Unsupported() + } + } + + private fun LightningInvoice.toRequest(): SendRequest.Invoice { + if (isExpired) throw SendError.Expired() + return SendRequest.Invoice(bolt11, amountSatoshis.takeIf { it > 0uL }, description?.takeIf { it.isNotBlank() }) + } + + private fun LnurlPayData.toRequest(input: String): SendRequest.Lnurl { + val minSats = (minSendable + MSATS_PER_SAT - 1uL) / MSATS_PER_SAT + val maxSats = maxSendable / MSATS_PER_SAT + if (maxSats == 0uL || minSats > maxSats) throw SendError.Invalid() + val payee = lnurlPayee(input, this) + return SendRequest.Lnurl(this, minSats.coerceAtLeast(1uL), maxSats.coerceAtMost(MAX_SATS), payee) + } + + /** The Lightning address when [input] is one, or else the host of the LNURL callback. */ + private fun lnurlPayee(input: String, data: LnurlPayData): String? { + val address = input.substringAfter(':').takeIf { '@' in it && !it.contains('/') } + return address ?: runCatching { URI(data.callback).host }.getOrNull() + } + + /** + * Prices a send of [request] and runs every check that comes before the hold to pay. [amountSats] is needed when + * the request fixes no amount ([SendRequest.fixedAmountSats] is null) and ignored when it does. For an LNURL + * request it fetches the invoice of that amount from the service. Fails with a [SendError]: + * [SendError.NotReady], [SendError.AmountRequired], [SendError.AmountOutOfRange], [SendError.Expired], + * [SendError.OwnInvoice], [SendError.InsufficientBalance], [SendError.Invalid] when an LNURL service answers with + * an invoice of another amount, and [SendError.Failed] when Spark cannot price it. Nothing is paid here. + */ + suspend fun prepare(request: SendRequest, amountSats: ULong? = null): Result = + withContext(ioDispatcher) { + runSuspendCatching { + if (!isReady()) throw SendError.NotReady() + val amount = request.fixedAmountSats ?: amountSats ?: throw SendError.AmountRequired() + when (request) { + is SendRequest.Invoice -> { + ensureAmount(amount, 1uL, MAX_SATS) + prepare(request.bolt11, amount, isAmountInRequest = request.amountSats != null, request.payee) + } + is SendRequest.Lnurl -> { + ensureAmount(amount, request.minSats, request.maxSats) + prepare(lnurlInvoice(request, amount), amount, isAmountInRequest = true, request.payee) + } + is SendRequest.SparkAddress -> { + ensureAmount(amount, 1uL, MAX_SATS) + prepare(request.address, amount, isAmountInRequest = false, request.payee) + } + } + }.onFailure { + Logger.warn("Failed to prepare a send", it, context = TAG) + } + } + + private fun ensureAmount(amountSats: ULong, minSats: ULong, maxSats: ULong) { + if (amountSats < minSats || amountSats > maxSats) throw SendError.AmountOutOfRange(minSats, maxSats) + } + + /** The invoice the LNURL service gives for [amountSats], refused unless it is for exactly that amount. */ + private suspend fun lnurlInvoice(request: SendRequest.Lnurl, amountSats: ULong): String { + val bolt11 = runSuspendCatching { inputDecoder.lnurlInvoice(request.data, amountSats * MSATS_PER_SAT) } + .getOrElse { throw SendError.Failed(it) } + val invoice = runSuspendCatching { (inputDecoder.decode(bolt11) as Scanner.Lightning).invoice } + .getOrElse { throw SendError.Invalid(it) } + if (invoice.amountSatoshis != amountSats) throw SendError.Invalid() + if (invoice.isExpired) throw SendError.Expired() + return bolt11 + } + + private suspend fun prepare( + paymentRequest: String, + amountSats: ULong, + isAmountInRequest: Boolean, + payee: String?, + ): PreparedSend { + ensureNotOwn(paymentRequest) + val response = runSuspendCatching { + sparkService.prepareSend(paymentRequest, amountSats.takeIf { !isAmountInRequest }) + }.getOrElse { throw it.toSendError() } + val (feeSats, paymentHash) = when (val method = response.paymentMethod) { + is SendPaymentMethod.Bolt11Invoice -> method.feeSats() to method.invoiceDetails.paymentHash + is SendPaymentMethod.SparkAddress -> method.fee.toLong().toULong() to null + else -> throw SendError.Unsupported() + } + val balanceSats = sparkService.getInfo().balanceSats + val totalSats = amountSats + feeSats + if (totalSats > balanceSats) throw SendError.InsufficientBalance(totalSats - balanceSats) + val transferKey = if (paymentHash == null) UUID.randomUUID().toString() else null + return PreparedSend(amountSats, feeSats, payee, response, paymentHash, transferKey) + } + + /** + * Refuses [paymentRequest], a BOLT11 invoice or a Spark address, when [SelfSendGuard] says it pays this wallet. + * A request the SDK cannot read, or a guard that cannot tell, refuses it too. + */ + private suspend fun ensureNotOwn(paymentRequest: String) { + val input = runSuspendCatching { sparkService.parse(paymentRequest) }.getOrElse { throw SendError.Invalid(it) } + if (input !is InputType.Bolt11Invoice && input !is InputType.SparkAddress) throw SendError.Invalid() + val isOwn = runSuspendCatching { selfSendGuard.isOwn(input) }.getOrElse { throw SendError.NotReady() } + if (isOwn) throw SendError.OwnInvoice() + } + + private fun SendPaymentMethod.Bolt11Invoice.feeSats(): ULong = + sparkTransferFeeSats?.takeIf { sparkService.prefersSpark } ?: lightningFeeSats + + /** + * Pays [prepared] and returns the payment: [PaymentState.Completed], or [PaymentState.Pending] when Spark took + * it and it did not settle within [SETTLE_TIMEOUT]. Once Spark has the send, the caller cannot cancel it. Fails + * with a [SendError]: [SendError.NotReady], [SendError.AlreadyPaid], [SendError.InFlight] (also while another + * send runs), [SendError.Expired], [SendError.InsufficientBalance], [SendError.Failed], and [SendError.Unknown] + * when the payment may have gone out. + * + * An invoice is sent under the idempotency key the phone derives for it too, so Spark pays it once however often + * and from whichever device it is sent; each attempt Spark lists as failed moves to the next key. + */ + suspend fun send(prepared: PreparedSend): Result = withContext(ioDispatcher) { + runSuspendCatching { + if (!sendMutex.tryLock()) throw SendError.InFlight() + try { + if (!isReady()) throw SendError.NotReady() + val key = prepared.transferKey ?: invoiceKey(checkNotNull(prepared.paymentHash)) + sendWatched(prepared.response, key).toWatchPayment() + } finally { + sendMutex.unlock() + } + }.onFailure { + Logger.error("Failed to send a payment", it, context = TAG) + } + } + + /** + * The key of the next attempt at the invoice with [paymentHash], after Spark's list shows that no earlier send of + * it completed or is still pending. A list that cannot be read refuses the send. + */ + private suspend fun invoiceKey(paymentHash: String): String { + val listed = runSuspendCatching { sparkService.listPayments() }.getOrElse { throw SendError.NotReady() } + val states = listed.filter { it.sendHash().equals(paymentHash, ignoreCase = true) }.map { it.status } + if (PaymentStatus.COMPLETED in states) throw SendError.AlreadyPaid() + if (PaymentStatus.PENDING in states) throw SendError.InFlight() + val failed = listed.filter { it.status == PaymentStatus.FAILED }.mapTo(HashSet()) { it.id } + var attempt = 0 + while (sparkService.sendKey(paymentHash, attempt) in failed) attempt++ + return sparkService.sendKey(paymentHash, attempt) + } + + /** Sends under [key] while already listening for the payment's outcome, which can arrive before the call ends. */ + private suspend fun sendWatched(response: PrepareSendPaymentResponse, key: String): Payment = coroutineScope { + val settled = MutableStateFlow>(emptyMap()) + val watcher = launch(start = CoroutineStart.UNDISPATCHED) { + sparkService.events.mapNotNull { it.payment() } + .filter { it.status != PaymentStatus.PENDING } + .collect { payment -> settled.update { it + (payment.id to payment) } } + } + try { + val sent = runSuspendCatching { sparkService.send(response, key) }.getOrElse { recoverSend(it, key) } + val payment = if (sent.status == PaymentStatus.PENDING) { + withTimeoutOrNull(SETTLE_TIMEOUT) { settled.first { sent.id in it }.getValue(sent.id) } ?: sent + } else { + sent + } + if (payment.status == PaymentStatus.FAILED) throw SendError.Failed() + uncertainKeys.remove(key) + Logger.info("Sent payment '${payment.id}' with status '${payment.status}'", context = TAG) + payment + } finally { + watcher.cancel() + } + } + + /** + * What a send that threw under [key] comes to. Spark refuses an expired invoice and a short balance before + * anything goes out. Any other error can follow a transfer Spark committed, so Spark's list decides: a payment + * it shows under the key is this send, and a send it does not show is [SendError.Unknown]. + */ + private suspend fun recoverSend(error: Throwable, key: String): Payment { + val isRefusal = error.isInvoiceExpired() || error is SdkException.InsufficientFunds + if (isRefusal && key !in uncertainKeys) throw error.toSendError() + val listed = runSuspendCatching { sparkService.listPayments().firstOrNull { it.id == key } }.getOrNull() + if (listed == null) { + uncertainKeys.add(key) + throw SendError.Unknown(error) + } + return listed + } + + /** The wallet's newest payments, at most [limit], from Spark's local list. It needs Spark connected. */ + suspend fun recentPayments(limit: Int = RECENT_PAYMENTS_LIMIT): Result> = + withContext(ioDispatcher) { + runSuspendCatching { sparkService.listPayments(limit.toUInt()).map { it.toWatchPayment() } } + .onFailure { Logger.warn("Failed to list payments", it, context = TAG) } + } + + private fun isReady(): Boolean = walletRepo.walletState.value.status == WalletStatus.Ready +} + +private val Bolt11InvoiceDetails.expiresAt: ULong get() = timestamp + expiry + +private fun SdkEvent.payment(): Payment? = when (this) { + is SdkEvent.PaymentSucceeded -> payment + is SdkEvent.PaymentPending -> payment + is SdkEvent.PaymentFailed -> payment + else -> null +} + +private fun Payment.lightningHash(): String? = (details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash + +private fun Payment.sendHash(): String? = lightningHash()?.takeIf { paymentType == PaymentType.SEND } + +private fun Payment.isReceiptOf(invoice: ReceiveInvoice): Boolean = + paymentType == PaymentType.RECEIVE && status == PaymentStatus.COMPLETED && + lightningHash().equals(invoice.paymentHash, ignoreCase = true) + +private fun Payment.toWatchPayment() = WatchPayment( + id = id, + isSent = paymentType == PaymentType.SEND, + amountSats = amount.toLong().toULong(), + feeSats = fees.toLong().toULong(), + timestampSecs = timestamp, + state = when (status) { + PaymentStatus.COMPLETED -> PaymentState.Completed + PaymentStatus.PENDING -> PaymentState.Pending + PaymentStatus.FAILED -> PaymentState.Failed + }, +) + +/** Spark refuses an expired Lightning invoice with this input error, at prepare and again at send. */ +private fun Throwable.isInvoiceExpired(): Boolean = + this is SdkException.InvalidInput && v1.contains("invoice has expired", ignoreCase = true) + +private fun Throwable.toSendError(): SendError = when { + this is SendError -> this + isInvoiceExpired() -> SendError.Expired(this) + this is SdkException.InsufficientFunds -> SendError.InsufficientBalance(null) + else -> SendError.Failed(this) +} diff --git a/wear/src/main/java/to/bitkit/wear/services/InputDecoder.kt b/wear/src/main/java/to/bitkit/wear/services/InputDecoder.kt new file mode 100644 index 0000000000..ebe4e9cfee --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/services/InputDecoder.kt @@ -0,0 +1,28 @@ +package to.bitkit.wear.services + +import com.synonym.bitkitcore.LnurlPayData +import com.synonym.bitkitcore.Scanner +import com.synonym.bitkitcore.getLnurlInvoiceForPayData +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Reads payment inputs the way the phone does. Every bitkit-core payment call of the watch goes through this + * interface. Both calls can reach the network: an LNURL or a Lightning address is fetched from its host. + */ +interface InputDecoder { + /** Decodes a BOLT11 invoice, an LNURL, a Lightning address or a BIP21 URI, with or without its URI scheme. */ + suspend fun decode(input: String): Scanner + + /** Asks the LNURL-pay service of [data] for a BOLT11 invoice of [amountMsats]. */ + suspend fun lnurlInvoice(data: LnurlPayData, amountMsats: ULong): String +} + +/** [InputDecoder] backed by bitkit-core, as on the phone. */ +@Singleton +class CoreInputDecoder @Inject constructor() : InputDecoder { + override suspend fun decode(input: String): Scanner = com.synonym.bitkitcore.decode(input) + + override suspend fun lnurlInvoice(data: LnurlPayData, amountMsats: ULong): String = + getLnurlInvoiceForPayData(data, amountMsats, null) +} diff --git a/wear/src/main/java/to/bitkit/wear/services/SelfSendGuard.kt b/wear/src/main/java/to/bitkit/wear/services/SelfSendGuard.kt new file mode 100644 index 0000000000..babfaf9009 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/services/SelfSendGuard.kt @@ -0,0 +1,60 @@ +package to.bitkit.wear.services + +import breez_sdk_spark.InputType +import to.bitkit.wear.data.OwnInvoiceStore +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Tells whether a payment input pays this wallet. The phone and the watch share one Spark wallet, so neither may pay + * a request the other, or itself, created. `PaymentsRepo` asks before every prepare, and a check that fails refuses + * the send. + */ +interface SelfSendGuard { + /** Whether [input], read by the SDK's parser, pays this wallet. Throws when the wallet's identity is unknown. */ + suspend fun isOwn(input: InputType): Boolean +} + +/** + * Recognises a request of this wallet in two ways: + * - by the wallet's Spark identity public key, the one thing both devices share and an input can carry: a Spark + * address encodes it, and a BOLT11 invoice carries it as the node of a route hint hop with the short channel id + * [SPARK_ADDRESS_HINT_SCID], when the wallet that made it asked Spark to include its Spark address; + * - by payment hash, for the invoices in [OwnInvoiceStore]: the ones this device created, and a paired device's once + * they are shared with it. + * + * The identity alone does not recognise Bitkit's invoices: Bitkit creates them without the Spark address hint (the + * SDK's `preferSparkOverLightning` is off), and such an invoice names only Spark's provider node, which every Spark + * wallet shares. Verified on the local regtest stack with SDK 0.28.3. So an invoice the phone created is refused on + * the watch only once its hash reached the watch's [OwnInvoiceStore]. + */ +@Singleton +class WalletSelfSendGuard @Inject constructor( + private val sparkService: WatchSparkService, + private val ownInvoiceStore: OwnInvoiceStore, +) : SelfSendGuard { + companion object { + /** + * The route hint short channel id under which an invoice carries its Spark address, as the SDK's parser + * prints it: the phone's `SPARK_ADDRESS_HINT_SCID`, 17592187092992000001, as block x transaction x output. + */ + const val SPARK_ADDRESS_HINT_SCID = "16000000x16000000x1" + + /** Whether [input] names [identityPubkey], this wallet's Spark identity in hex, as the wallet it pays. */ + fun namesIdentity(input: InputType, identityPubkey: String): Boolean = when (input) { + is InputType.SparkAddress -> input.v1.identityPublicKey.equals(identityPubkey, ignoreCase = true) + is InputType.Bolt11Invoice -> input.v1.routingHints.any { hint -> + hint.hops.any { + it.shortChannelId == SPARK_ADDRESS_HINT_SCID && + it.srcNodeId.equals(identityPubkey, ignoreCase = true) + } + } + else -> false + } + } + + override suspend fun isOwn(input: InputType): Boolean { + if (input is InputType.Bolt11Invoice && ownInvoiceStore.contains(input.v1.paymentHash)) return true + return namesIdentity(input, sparkService.identityPubkey()) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt new file mode 100644 index 0000000000..8eef3e89d5 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt @@ -0,0 +1,103 @@ +package to.bitkit.wear.data + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.job +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import to.bitkit.wear.test.BaseUnitTest +import java.io.File +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** An [OwnInvoiceStore] in memory. */ +class FakeOwnInvoiceStore : OwnInvoiceStore { + val invoices = mutableMapOf() + var failure: Throwable? = null + + override suspend fun add(paymentHash: String, expiresAtSecs: ULong) { + failure?.let { throw it } + invoices[paymentHash.lowercase()] = expiresAtSecs + } + + override suspend fun contains(paymentHash: String): Boolean = paymentHash.lowercase() in invoices +} + +/** The store against the real settings file, in a temporary directory. Each [open] is a new process. */ +class OwnInvoiceStoreTest : BaseUnitTest() { + @get:Rule + val folder = TemporaryFolder() + + private val settingsFile by lazy { File(folder.root, "datastore/settings.preferences_pb") } + private var scope: CoroutineScope? = null + private var now = 1_000uL + + @Test + fun `an added invoice is known in either case until it expires, also after a restart`() = test { + open().first.add("AB".repeat(32), expiresAtSecs = 2_000uL) + close() + val sut = open().first + + assertTrue(sut.contains("ab".repeat(32))) + assertTrue(sut.contains("AB".repeat(32))) + assertFalse(sut.contains("cd".repeat(32))) + + now = 2_000uL + assertFalse(sut.contains("ab".repeat(32))) + close() + } + + @Test + fun `adding drops the expired invoices`() = test { + val sut = open().first + sut.add("aa".repeat(32), expiresAtSecs = 1_500uL) + now = 1_600uL + + sut.add("bb".repeat(32), expiresAtSecs = 3_000uL) + now = 1_000uL + + assertFalse(sut.contains("aa".repeat(32))) + assertTrue(sut.contains("bb".repeat(32))) + close() + } + + @Test + fun `it keeps the invoices that expire last when there are too many`() = test { + val sut = open().first + val count = SettingsOwnInvoiceStore.MAX_INVOICES + 1 + + repeat(count) { sut.add(hash(it), expiresAtSecs = 2_000uL + it.toULong()) } + + assertFalse(sut.contains(hash(0))) + assertTrue(sut.contains(hash(1))) + assertTrue(sut.contains(hash(count - 1))) + close() + } + + @Test + fun `the wallet's wipe forgets the invoices with the settings`() = test { + val (sut, settings) = open() + sut.add("ab".repeat(32), expiresAtSecs = 2_000uL) + + settings.finishWipe() + + assertFalse(sut.contains("ab".repeat(32))) + close() + } + + private fun hash(index: Int) = index.toString(radix = 16).padStart(64, '0') + + private fun open(): Pair { + val opened = CoroutineScope(testDispatcher + Job()).also { scope = it } + val dataStore = settingsDataStore(opened) { settingsFile } + val settings = SettingsStore(dataStore, WipeMarker(lazy { File(folder.root, "seed") })) + return SettingsOwnInvoiceStore(dataStore) { now } to settings + } + + private suspend fun close() { + scope?.coroutineContext?.job?.cancelAndJoin() + scope = null + } +} diff --git a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt new file mode 100644 index 0000000000..09c9a435d0 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -0,0 +1,755 @@ +package to.bitkit.wear.repositories + +import breez_sdk_spark.FeePolicy +import breez_sdk_spark.Payment +import breez_sdk_spark.PaymentStatus +import breez_sdk_spark.PaymentType +import breez_sdk_spark.PrepareSendPaymentResponse +import breez_sdk_spark.SdkEvent +import breez_sdk_spark.SdkException +import breez_sdk_spark.SendPaymentMethod +import com.synonym.bitkitcore.LightningInvoice +import com.synonym.bitkitcore.LnurlPayData +import com.synonym.bitkitcore.NetworkType +import com.synonym.bitkitcore.OnChainInvoice +import com.synonym.bitkitcore.Scanner +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import 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.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.wear.data.FakeOwnInvoiceStore +import to.bitkit.wear.models.PaymentState +import to.bitkit.wear.models.PreparedSend +import to.bitkit.wear.models.ReceiveError +import to.bitkit.wear.models.ReceiveInvoice +import to.bitkit.wear.models.SendError +import to.bitkit.wear.models.SendRequest +import to.bitkit.wear.services.InputDecoder +import to.bitkit.wear.services.SparkError +import to.bitkit.wear.services.SparkFixtures +import to.bitkit.wear.services.SparkFixtures.IDENTITY +import to.bitkit.wear.services.SparkFixtures.OTHER_IDENTITY +import to.bitkit.wear.services.SparkFixtures.PAYMENT_HASH +import to.bitkit.wear.services.SparkFixtures.PROVIDER_HINT +import to.bitkit.wear.services.SparkFixtures.SPARK_ADDRESS +import to.bitkit.wear.services.SparkFixtures.SPARK_ADDRESS_HINT +import to.bitkit.wear.services.SparkFixtures.invoiceInput +import to.bitkit.wear.services.SparkFixtures.payment +import to.bitkit.wear.services.SparkFixtures.sparkAddressInput +import to.bitkit.wear.services.WalletSelfSendGuard +import to.bitkit.wear.services.WatchSparkService +import to.bitkit.wear.test.BaseUnitTest +import java.math.BigInteger +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +@OptIn(ExperimentalCoroutinesApi::class) +class PaymentsRepoTest : BaseUnitTest() { + private companion object { + const val BOLT11 = "lnbcrt1invoice" + const val LNURL_BOLT11 = "lnbcrt1fromlnurl" + const val BALANCE = 10_000uL + const val FEE = 4uL + } + + private val sparkService = mock() + private val walletRepo = mock() + private val events = MutableSharedFlow() + private val walletState = MutableStateFlow(WalletState(WalletStatus.Ready, BALANCE, hasSynced = true)) + private val ownInvoices = FakeOwnInvoiceStore() + private val decoder = FakeInputDecoder() + + private lateinit var sut: PaymentsRepo + + @Before + fun setUp() { + whenever(sparkService.events).thenReturn(events) + whenever(walletRepo.walletState).thenReturn(walletState) + whenever { sparkService.identityPubkey() }.thenReturn(IDENTITY) + whenever { sparkService.getInfo() }.thenReturn(SparkFixtures.info(BALANCE)) + whenever { sparkService.listPayments(anyOrNull()) }.thenReturn(emptyList()) + whenever(sparkService.sendKey(any(), any())).thenAnswer { "key-${it.arguments[1]}" } + whenever { sparkService.parse(BOLT11) }.thenReturn(invoiceInput(BOLT11)) + whenever { sparkService.prepareSend(eq(BOLT11), anyOrNull()) }.thenReturn(prepared()) + sut = PaymentsRepo( + testDispatcher, + sparkService, + walletRepo, + decoder, + WalletSelfSendGuard(sparkService, ownInvoices), + ownInvoices, + ) + } + + // region receive + + @Test + fun `an invoice is amountless, remembered as the wallet's own and returned with its hash and expiry`() = test { + whenever(sparkService.receiveBolt11(null, "", PaymentsRepo.INVOICE_EXPIRY_SECS)).thenReturn(BOLT11) + + val invoice = sut.createInvoice().getOrThrow() + + val expiresAt = SparkFixtures.TIMESTAMP + SparkFixtures.EXPIRY + assertEquals(ReceiveInvoice(BOLT11, PAYMENT_HASH, expiresAt), invoice) + assertEquals(mapOf(PAYMENT_HASH to expiresAt), ownInvoices.invoices) + assertFalse(invoice.isExpired(expiresAt - 1uL)) + assertTrue(invoice.isExpired(expiresAt)) + } + + @Test + fun `no invoice is made unless the wallet is ready`() = test { + for (status in WalletStatus.entries - WalletStatus.Ready) { + walletState.update { it.copy(status = status) } + + assertIs(sut.createInvoice().exceptionOrNull(), "$status") + } + verify(sparkService, never()).receiveBolt11(anyOrNull(), any(), any()) + } + + @Test + fun `an invoice that cannot be remembered is not handed out`() = test { + whenever(sparkService.receiveBolt11(null, "", PaymentsRepo.INVOICE_EXPIRY_SECS)).thenReturn(BOLT11) + ownInvoices.failure = IllegalStateException("disk") + + assertIs(sut.createInvoice().exceptionOrNull()) + } + + @Test + fun `waiting for an invoice ends with its payment and skips other payments`() = test { + val paid = async { sut.awaitPaid(invoice()) } + + events.emit(SdkEvent.PaymentSucceeded(receipt("other", paymentHash = "ff".repeat(32)))) + events.emit(SdkEvent.PaymentSucceeded(payment("sent", PaymentStatus.COMPLETED))) + events.emit(SdkEvent.PaymentPending(receipt("pending", status = PaymentStatus.PENDING))) + assertFalse(paid.isCompleted) + events.emit(SdkEvent.PaymentSucceeded(receipt("paid", amountSats = 2_100))) + + val received = paid.await() + assertEquals("paid", received.id) + assertEquals(2_100uL, received.amountSats) + assertFalse(received.isSent) + assertEquals(PaymentState.Completed, received.state) + } + + @Test + fun `waiting for an invoice finds a payment that arrived before the wait`() = test { + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(receipt("paid"))) + + assertEquals("paid", sut.awaitPaid(invoice()).id) + } + + @Test + fun `waiting for an invoice reads spark's list again after a sync`() = test { + val paid = async { sut.awaitPaid(invoice()) } + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(receipt("paid"))) + + events.emit(SdkEvent.Synced) + + assertEquals("paid", paid.await().id) + } + + // endregion + + // region parse + + @Test + fun `an invoice is read with its amount, and without one when it is amountless`() = test { + decoder.inputs["lightning:$BOLT11"] = lightning(BOLT11, amountSats = 500uL, description = "Coffee") + decoder.inputs["amountless"] = lightning(BOLT11, amountSats = 0uL, description = "") + + assertEquals(SendRequest.Invoice(BOLT11, 500uL, "Coffee"), sut.parse(" lightning:$BOLT11 ").getOrThrow()) + val amountless = sut.parse("amountless").getOrThrow() + assertEquals(SendRequest.Invoice(BOLT11, null, null), amountless) + assertNull(amountless.fixedAmountSats) + } + + @Test + fun `an expired invoice and an unreadable input are refused when read`() = test { + decoder.inputs["expired"] = lightning(BOLT11, isExpired = true) + + assertIs(sut.parse("expired").exceptionOrNull()) + assertIs(sut.parse("nonsense").exceptionOrNull()) + } + + @Test + fun `an lnurl is read with its range in whole sats, named by its host`() = test { + decoder.inputs["lnurl1abc"] = Scanner.LnurlPay(lnurl(minMsat = 1_001uL, maxMsat = 5_999uL)) + + val request = assertIs(sut.parse("lnurl1abc").getOrThrow()) + + assertEquals(2uL, request.minSats) + assertEquals(5uL, request.maxSats) + assertEquals("pay.example", request.payee) + assertNull(request.fixedAmountSats) + } + + @Test + fun `a lightning address is named by its address, and a fixed lnurl amount is fixed`() = test { + val fixed = Scanner.LnurlPay(lnurl(minMsat = 21_000uL, maxMsat = 21_000uL)) + decoder.inputs["lightning:satoshi@pay.example"] = fixed + + val request = sut.parse("lightning:satoshi@pay.example").getOrThrow() + + assertEquals("satoshi@pay.example", request.payee) + assertEquals(21uL, request.fixedAmountSats) + } + + @Test + fun `an lnurl that takes less than one sat is refused`() = test { + decoder.inputs["lnurl1abc"] = Scanner.LnurlPay(lnurl(minMsat = 1uL, maxMsat = 999uL)) + + assertIs(sut.parse("lnurl1abc").exceptionOrNull()) + } + + @Test + fun `a bitcoin uri is paid by its lightning invoice, and refused without one`() = test { + decoder.inputs["bitcoin:bcrt1q?lightning=$BOLT11"] = onchain(mapOf("lightning" to BOLT11)) + decoder.inputs["bitcoin:bcrt1q"] = onchain(emptyMap()) + decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 500uL) + + assertEquals( + SendRequest.Invoice(BOLT11, 500uL, null), + sut.parse("bitcoin:bcrt1q?lightning=$BOLT11").getOrThrow(), + ) + assertIs(sut.parse("bitcoin:bcrt1q").exceptionOrNull()) + } + + @Test + fun `a spark address is read by the sdk and never sent to the decoder`() = test { + whenever(sparkService.parse(SPARK_ADDRESS)).thenReturn(sparkAddressInput(OTHER_IDENTITY)) + + assertEquals(SendRequest.SparkAddress(SPARK_ADDRESS), sut.parse("spark:$SPARK_ADDRESS").getOrThrow()) + assertEquals(emptyList(), decoder.decoded) + } + + @Test + fun `a spark address needs the wallet ready, while an invoice is read without it`() = test { + walletState.update { it.copy(status = WalletStatus.Connecting) } + decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 500uL) + + assertIs(sut.parse(SPARK_ADDRESS).exceptionOrNull()) + assertTrue(sut.parse(BOLT11).isSuccess) + verify(sparkService, never()).parse(any()) + } + + @Test + fun `only a spark address has the shape of one`() { + assertEquals(SPARK_ADDRESS, PaymentsRepo.sparkAddressOrNull(SPARK_ADDRESS)) + assertEquals(SPARK_ADDRESS, PaymentsRepo.sparkAddressOrNull("SPARK:$SPARK_ADDRESS")) + assertEquals("sp1pgss", PaymentsRepo.sparkAddressOrNull("sp1pgss")) + for (other in listOf(BOLT11, "lnurl1abc", "satoshi@pay.example", "bcrt1qabc", "spark1", "sparkle1abc")) { + assertNull(PaymentsRepo.sparkAddressOrNull(other), other) + } + } + + // endregion + + // region self-send guard + + @Test + fun `this wallet's own spark address is refused when read`() = test { + whenever(sparkService.parse(SPARK_ADDRESS)).thenReturn(sparkAddressInput(IDENTITY)) + + assertIs(sut.parse(SPARK_ADDRESS).exceptionOrNull()) + } + + @Test + fun `an invoice this watch created is refused when read and never priced`() = test { + decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 500uL) + ownInvoices.add(PAYMENT_HASH, ULong.MAX_VALUE) + + assertIs(sut.parse(BOLT11).exceptionOrNull()) + assertIs(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull()) + verify(sparkService, never()).prepareSend(any(), anyOrNull()) + } + + @Test + fun `an invoice read before the wallet was ready is still refused before it is priced`() = test { + decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 500uL) + ownInvoices.add(PAYMENT_HASH, ULong.MAX_VALUE) + walletState.update { it.copy(status = WalletStatus.Connecting) } + val request = sut.parse(BOLT11).getOrThrow() + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.prepare(request).exceptionOrNull()) + verify(sparkService, never()).prepareSend(any(), anyOrNull()) + } + + @Test + fun `an invoice whose spark address hint names this wallet is refused before it is priced`() = test { + val hints = listOf(PROVIDER_HINT, SPARK_ADDRESS_HINT) + whenever(sparkService.parse(BOLT11)).thenReturn(invoiceInput(BOLT11, hints = hints)) + + assertIs(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull()) + verify(sparkService, never()).prepareSend(any(), anyOrNull()) + } + + @Test + fun `this wallet's own spark address is refused before it is priced`() = test { + whenever(sparkService.parse(SPARK_ADDRESS)).thenReturn(sparkAddressInput(IDENTITY)) + + val result = sut.prepare(SendRequest.SparkAddress(SPARK_ADDRESS), amountSats = 500uL) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).prepareSend(any(), anyOrNull()) + } + + @Test + fun `the invoice an lnurl resolves to is refused when this watch created it`() = test { + decoder.lnurlInvoices[500_000uL] = LNURL_BOLT11 + decoder.inputs[LNURL_BOLT11] = lightning(LNURL_BOLT11, amountSats = 500uL) + whenever(sparkService.parse(LNURL_BOLT11)).thenReturn(invoiceInput(LNURL_BOLT11)) + ownInvoices.add(PAYMENT_HASH, ULong.MAX_VALUE) + + val result = sut.prepare(SendRequest.Lnurl(lnurl(), 1uL, 1_000uL, "pay.example"), amountSats = 500uL) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).prepareSend(any(), anyOrNull()) + } + + @Test + fun `an input the guard cannot check is refused`() = test { + whenever(sparkService.identityPubkey()).doSuspendableAnswer { throw SparkError.NotConnected() } + + assertIs(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull()) + verify(sparkService, never()).prepareSend(any(), anyOrNull()) + } + + @Test + fun `another wallet's invoice and spark address pass the guard`() = test { + whenever(sparkService.parse(SPARK_ADDRESS)).thenReturn(sparkAddressInput(OTHER_IDENTITY)) + whenever(sparkService.prepareSend(SPARK_ADDRESS, 500uL)).thenReturn(preparedTransfer()) + ownInvoices.add("ff".repeat(32), ULong.MAX_VALUE) + + assertTrue(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).isSuccess) + assertTrue(sut.prepare(SendRequest.SparkAddress(SPARK_ADDRESS), amountSats = 500uL).isSuccess) + } + + // endregion + + // region prepare + + @Test + fun `nothing is priced unless the wallet is ready`() = test { + for (status in WalletStatus.entries - WalletStatus.Ready) { + walletState.update { it.copy(status = status) } + + val result = sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)) + + assertIs(result.exceptionOrNull(), "$status") + } + verify(sparkService, never()).prepareSend(any(), anyOrNull()) + } + + @Test + fun `an invoice with an amount is priced at it, with the lightning fee`() = test { + val prepared = sut.prepare(SendRequest.Invoice(BOLT11, 500uL, "Coffee"), amountSats = 9uL).getOrThrow() + + verify(sparkService).prepareSend(BOLT11, null) + assertEquals(500uL, prepared.amountSats) + assertEquals(FEE, prepared.feeSats) + assertEquals(504uL, prepared.totalSats) + assertEquals("Coffee", prepared.payee) + } + + @Test + fun `a spark transfer fee applies only where spark is preferred`() = test { + whenever(sparkService.prepareSend(eq(BOLT11), anyOrNull())).thenReturn(prepared(sparkTransferFeeSats = 0uL)) + + assertEquals(FEE, sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).getOrThrow().feeSats) + + whenever(sparkService.prefersSpark).thenReturn(true) + assertEquals(0uL, sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).getOrThrow().feeSats) + } + + @Test + fun `an amountless invoice needs an amount above zero and is priced at it`() = test { + val request = SendRequest.Invoice(BOLT11, null, null) + + assertIs(sut.prepare(request).exceptionOrNull()) + assertIs(sut.prepare(request, amountSats = 0uL).exceptionOrNull()) + assertEquals(700uL, sut.prepare(request, amountSats = 700uL).getOrThrow().amountSats) + verify(sparkService).prepareSend(BOLT11, 700uL) + } + + @Test + fun `an amount and fee above the balance are refused with the shortfall`() = test { + val error = sut.prepare(SendRequest.Invoice(BOLT11, BALANCE - FEE + 1uL, null)).exceptionOrNull() + + assertEquals(1uL, assertIs(error).shortfallSats) + assertTrue(sut.prepare(SendRequest.Invoice(BOLT11, BALANCE - FEE, null)).isSuccess) + } + + @Test + fun `spark's refusals at pricing are told apart`() = test { + val request = SendRequest.Invoice(BOLT11, 500uL, null) + var refusal: Throwable = SdkException.InvalidInput("Invoice has expired") + whenever(sparkService.prepareSend(eq(BOLT11), anyOrNull())).doSuspendableAnswer { throw refusal } + + assertIs(sut.prepare(request).exceptionOrNull()) + + refusal = SdkException.InsufficientFunds(null) + assertIs(sut.prepare(request).exceptionOrNull()) + + refusal = SdkException.Generic("boom") + assertIs(sut.prepare(request).exceptionOrNull()) + } + + @Test + fun `an lnurl amount outside its range is refused before the service is asked`() = test { + val request = SendRequest.Lnurl(lnurl(), minSats = 10uL, maxSats = 20uL, payee = null) + + for (amount in listOf(9uL, 21uL)) { + val error = assertIs(sut.prepare(request, amount).exceptionOrNull()) + assertEquals(10uL to 20uL, error.minSats to error.maxSats) + } + assertIs(sut.prepare(request).exceptionOrNull()) + assertEquals(emptyList(), decoder.requestedMsats) + } + + @Test + fun `an lnurl is priced by the invoice its service gives for the amount`() = test { + decoder.lnurlInvoices[15_000uL] = LNURL_BOLT11 + decoder.inputs[LNURL_BOLT11] = lightning(LNURL_BOLT11, amountSats = 15uL) + whenever(sparkService.parse(LNURL_BOLT11)).thenReturn(invoiceInput(LNURL_BOLT11, "cc".repeat(32))) + whenever(sparkService.prepareSend(LNURL_BOLT11, null)).thenReturn(prepared()) + + val request = SendRequest.Lnurl(lnurl(), minSats = 10uL, maxSats = 20uL, payee = "satoshi@pay.example") + val prepared = sut.prepare(request, amountSats = 15uL).getOrThrow() + + assertEquals(15uL, prepared.amountSats) + assertEquals("satoshi@pay.example", prepared.payee) + } + + @Test + fun `an lnurl invoice for another amount, or an expired one, is refused`() = test { + val request = SendRequest.Lnurl(lnurl(), minSats = 10uL, maxSats = 20uL, payee = null) + decoder.lnurlInvoices[15_000uL] = LNURL_BOLT11 + + decoder.inputs[LNURL_BOLT11] = lightning(LNURL_BOLT11, amountSats = 16uL) + assertIs(sut.prepare(request, amountSats = 15uL).exceptionOrNull()) + + decoder.inputs[LNURL_BOLT11] = lightning(LNURL_BOLT11, amountSats = 15uL, isExpired = true) + assertIs(sut.prepare(request, amountSats = 15uL).exceptionOrNull()) + + assertIs(sut.prepare(request, amountSats = 12uL).exceptionOrNull()) + verify(sparkService, never()).prepareSend(any(), anyOrNull()) + } + + @Test + fun `quickpay never skips the confirmation yet`() = test { + assertFalse(sut.skipConfirmation(preparedSend())) + } + + // endregion + + // region send + + @Test + fun `nothing is sent unless the wallet is ready`() = test { + val prepared = preparedSend() + for (status in WalletStatus.entries - WalletStatus.Ready) { + walletState.update { it.copy(status = status) } + + assertIs(sut.send(prepared).exceptionOrNull(), "$status") + } + verify(sparkService, never()).send(any(), any()) + } + + @Test + fun `an invoice is sent under its first key and returns the completed payment`() = test { + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.COMPLETED)) + + val sent = sut.send(preparedSend()).getOrThrow() + + verify(sparkService).send(any(), eq("key-0")) + assertEquals(PaymentState.Completed, sent.state) + assertTrue(sent.isSent) + assertEquals(1_000uL, sent.amountSats) + assertEquals(3uL, sent.feeSats) + } + + @Test + fun `an attempt spark lists as failed moves the send to the next key`() = test { + whenever(sparkService.listPayments(anyOrNull())).thenReturn( + listOf(payment("key-0", PaymentStatus.FAILED), payment("key-1", PaymentStatus.FAILED)), + ) + whenever(sparkService.send(any(), eq("key-2"))).thenReturn(payment("key-2", PaymentStatus.COMPLETED)) + + assertTrue(sut.send(preparedSend()).isSuccess) + verify(sparkService).send(any(), eq("key-2")) + } + + @Test + fun `an invoice spark lists as paid or pending is not sent again`() = test { + val paid = listOf(payment("random", PaymentStatus.COMPLETED)) + whenever(sparkService.listPayments(anyOrNull())).thenReturn(paid) + assertIs(sut.send(preparedSend()).exceptionOrNull()) + + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment("random", PaymentStatus.PENDING, paymentHash = PAYMENT_HASH.uppercase()))) + assertIs(sut.send(preparedSend()).exceptionOrNull()) + + verify(sparkService, never()).send(any(), any()) + } + + @Test + fun `a received payment of the same hash does not stop a send`() = test { + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(receipt("received"))) + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.COMPLETED)) + + assertTrue(sut.send(preparedSend()).isSuccess) + } + + @Test + fun `a payment list that cannot be read refuses the send`() = test { + whenever(sparkService.listPayments(anyOrNull())) + .doSuspendableAnswer { throw SdkException.StorageException("locked") } + + assertIs(sut.send(preparedSend()).exceptionOrNull()) + verify(sparkService, never()).send(any(), any()) + } + + @Test + fun `a pending send completes with the event that arrives while spark is still sending`() = test { + whenever(sparkService.send(any(), eq("key-0"))).doSuspendableAnswer { + events.emit(SdkEvent.PaymentSucceeded(payment("key-0", PaymentStatus.COMPLETED))) + payment("key-0", PaymentStatus.PENDING) + } + + assertEquals(PaymentState.Completed, sut.send(preparedSend()).getOrThrow().state) + } + + @Test + fun `a pending send waits for its own outcome and fails with it`() = test { + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.PENDING)) + val sending = async { sut.send(preparedSend()) } + + events.emit(SdkEvent.PaymentSucceeded(payment("another", PaymentStatus.COMPLETED))) + assertFalse(sending.isCompleted) + events.emit(SdkEvent.PaymentFailed(payment("key-0", PaymentStatus.FAILED))) + + assertIs(sending.await().exceptionOrNull()) + } + + @Test + fun `a send that does not settle in time is reported as pending`() = test { + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.PENDING)) + + val sent = sut.send(preparedSend()).getOrThrow() + + assertEquals(PaymentState.Pending, sent.state) + assertEquals(PaymentsRepo.SETTLE_TIMEOUT.inWholeMilliseconds, testScheduler.currentTime) + } + + @Test + fun `a send spark fails at once is a failure`() = test { + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.FAILED)) + + assertIs(sut.send(preparedSend()).exceptionOrNull()) + } + + @Test + fun `spark's refusals before anything goes out are told apart`() = test { + val prepared = preparedSend() + var refusal: Throwable = SdkException.InvalidInput("invoice has expired") + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw refusal } + + assertIs(sut.send(prepared).exceptionOrNull()) + + refusal = SdkException.InsufficientFunds(null) + assertIs(sut.send(prepared).exceptionOrNull()) + } + + @Test + fun `a send that throws without a trace has an unknown outcome, never a plain failure`() = test { + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw SdkException.NetworkException("reset") } + + assertIs(sut.send(preparedSend()).exceptionOrNull()) + } + + @Test + fun `after an unknown outcome a refusal under the same key stays unknown`() = test { + val prepared = preparedSend() + var refusal: Throwable = SdkException.NetworkException("reset") + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw refusal } + sut.send(prepared) + + refusal = SdkException.InsufficientFunds(null) + + assertIs(sut.send(prepared).exceptionOrNull()) + } + + @Test + fun `a send that throws after spark took it returns the payment spark lists under its key`() = test { + whenever(sparkService.send(any(), any())).doSuspendableAnswer { + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment("key-0", PaymentStatus.COMPLETED))) + throw SdkException.NetworkException("reset") + } + + assertEquals(PaymentState.Completed, sut.send(preparedSend()).getOrThrow().state) + } + + @Test + fun `a second send is refused while one runs`() = test { + val release = CompletableDeferred() + whenever(sparkService.send(any(), any())).doSuspendableAnswer { release.await() } + val first = async { sut.send(preparedSend()) } + + assertIs(sut.send(preparedSend()).exceptionOrNull()) + + release.complete(payment("key-0", PaymentStatus.COMPLETED)) + assertTrue(first.await().isSuccess) + } + + @Test + fun `a spark address is sent under one key of its own, without reading the list`() = test { + whenever(sparkService.parse(SPARK_ADDRESS)).thenReturn(sparkAddressInput(OTHER_IDENTITY)) + whenever(sparkService.prepareSend(SPARK_ADDRESS, 500uL)).thenReturn(preparedTransfer()) + val keys = mutableListOf() + whenever(sparkService.send(any(), any())).thenAnswer { + keys += it.arguments[1] as String + payment(keys.last(), PaymentStatus.COMPLETED, paymentHash = null) + } + val prepared = sut.prepare(SendRequest.SparkAddress(SPARK_ADDRESS), amountSats = 500uL).getOrThrow() + + sut.send(prepared).getOrThrow() + sut.send(prepared).getOrThrow() + + assertEquals(2uL, prepared.feeSats) + assertEquals(1, keys.distinct().size) + verify(sparkService, never()).sendKey(any(), any()) + } + + // endregion + + @Test + fun `recent payments are the newest of spark's list, as the activity list shows them`() = test { + whenever(sparkService.listPayments(20u)).thenReturn( + listOf(payment("sent", PaymentStatus.PENDING), receipt("received", amountSats = 77)), + ) + + val payments = sut.recentPayments().getOrThrow() + + assertEquals(listOf("sent", "received"), payments.map { it.id }) + assertEquals(listOf(true, false), payments.map { it.isSent }) + assertEquals(listOf(PaymentState.Pending, PaymentState.Completed), payments.map { it.state }) + assertEquals(77uL, payments[1].amountSats) + assertEquals(SparkFixtures.TIMESTAMP, payments[0].timestampSecs) + } + + @Test + fun `recent payments fail while spark is not connected`() = test { + whenever(sparkService.listPayments(anyOrNull())).doSuspendableAnswer { throw SparkError.NotConnected() } + + assertIs(sut.recentPayments().exceptionOrNull()) + } + + @Test + fun `every spark event tells the activity list to read again`() = test { + var changes = 0 + val collecting = launch { sut.paymentChanges.collect { changes++ } } + + events.emit(SdkEvent.Synced) + events.emit(SdkEvent.PaymentSucceeded(receipt("paid"))) + + assertEquals(2, changes) + collecting.cancel() + } + + private suspend fun preparedSend(): PreparedSend = + sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).getOrThrow() + + private fun invoice() = ReceiveInvoice(BOLT11, PAYMENT_HASH, SparkFixtures.TIMESTAMP + SparkFixtures.EXPIRY) + + private fun receipt( + id: String, + status: PaymentStatus = PaymentStatus.COMPLETED, + paymentHash: String = PAYMENT_HASH, + amountSats: Long = 1_000, + ) = payment(id, status, PaymentType.RECEIVE, paymentHash, amountSats, feeSats = 0) + + private fun prepared(sparkTransferFeeSats: ULong? = null) = PrepareSendPaymentResponse( + paymentMethod = SendPaymentMethod.Bolt11Invoice(SparkFixtures.invoice(BOLT11), sparkTransferFeeSats, FEE), + amount = BigInteger.valueOf(500), + tokenIdentifier = null, + conversionEstimate = null, + feePolicy = FeePolicy.FEES_EXCLUDED, + ) + + private fun preparedTransfer() = PrepareSendPaymentResponse( + paymentMethod = SendPaymentMethod.SparkAddress(SPARK_ADDRESS, BigInteger.valueOf(2), null), + amount = BigInteger.valueOf(500), + tokenIdentifier = null, + conversionEstimate = null, + feePolicy = FeePolicy.FEES_EXCLUDED, + ) + + private fun lightning( + bolt11: String, + amountSats: ULong = 500uL, + description: String? = null, + isExpired: Boolean = false, + ) = Scanner.Lightning( + LightningInvoice( + bolt11 = bolt11, + paymentHash = PAYMENT_HASH.hexToByteArray(), + amountSatoshis = amountSats, + timestampSeconds = SparkFixtures.TIMESTAMP, + expirySeconds = SparkFixtures.EXPIRY, + isExpired = isExpired, + description = description, + networkType = NetworkType.REGTEST, + payeeNodeId = null, + ), + ) + + private fun lnurl(minMsat: ULong = 1_000uL, maxMsat: ULong = 1_000_000uL) = LnurlPayData( + uri = "lnurl1abc", + callback = "https://pay.example/lnurlp/satoshi/callback", + minSendable = minMsat, + maxSendable = maxMsat, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + + private fun onchain(params: Map) = + Scanner.OnChain(OnChainInvoice("bcrt1q", amountSatoshis = 0uL, label = null, message = null, params = params)) +} + +/** An [InputDecoder] over fixed answers; an input or an amount it has none for fails, as an unreadable one does. */ +private class FakeInputDecoder : InputDecoder { + val inputs = mutableMapOf() + val lnurlInvoices = mutableMapOf() + val decoded = mutableListOf() + val requestedMsats = mutableListOf() + + override suspend fun decode(input: String): Scanner { + decoded += input + return inputs[input] ?: error("unreadable") + } + + override suspend fun lnurlInvoice(data: LnurlPayData, amountMsats: ULong): String { + requestedMsats += amountMsats + return lnurlInvoices[amountMsats] ?: error("no invoice") + } +} diff --git a/wear/src/test/java/to/bitkit/wear/services/SelfSendGuardTest.kt b/wear/src/test/java/to/bitkit/wear/services/SelfSendGuardTest.kt new file mode 100644 index 0000000000..bfbfca983d --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/services/SelfSendGuardTest.kt @@ -0,0 +1,93 @@ +package to.bitkit.wear.services + +import kotlinx.coroutines.test.runTest +import org.junit.Test +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import to.bitkit.wear.data.FakeOwnInvoiceStore +import to.bitkit.wear.services.SparkFixtures.IDENTITY +import to.bitkit.wear.services.SparkFixtures.OTHER_IDENTITY +import to.bitkit.wear.services.SparkFixtures.PAYMENT_HASH +import to.bitkit.wear.services.SparkFixtures.PROVIDER_HINT +import to.bitkit.wear.services.SparkFixtures.PROVIDER_NODE +import to.bitkit.wear.services.SparkFixtures.SPARK_ADDRESS_HINT +import to.bitkit.wear.services.SparkFixtures.hint +import to.bitkit.wear.services.SparkFixtures.invoiceInput +import to.bitkit.wear.services.SparkFixtures.sparkAddressInput +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class SelfSendGuardTest { + private val sparkService = mock() + private val store = FakeOwnInvoiceStore() + private val sut = WalletSelfSendGuard(sparkService, store) + + @Test + fun `a spark address of this wallet's identity is its own, in either case`() = runTest { + whenever(sparkService.identityPubkey()).thenReturn(IDENTITY) + + assertTrue(sut.isOwn(sparkAddressInput(IDENTITY))) + assertTrue(sut.isOwn(sparkAddressInput(IDENTITY.uppercase()))) + assertFalse(sut.isOwn(sparkAddressInput(OTHER_IDENTITY))) + } + + @Test + fun `an invoice whose spark address hint names this wallet's identity is its own`() = runTest { + whenever(sparkService.identityPubkey()).thenReturn(IDENTITY) + + assertTrue(sut.isOwn(invoiceInput(hints = listOf(PROVIDER_HINT, SPARK_ADDRESS_HINT)))) + } + + @Test + fun `an invoice with another wallet's spark address hint is not its own`() = runTest { + whenever(sparkService.identityPubkey()).thenReturn(IDENTITY) + val other = hint(OTHER_IDENTITY, WalletSelfSendGuard.SPARK_ADDRESS_HINT_SCID) + + assertFalse(sut.isOwn(invoiceInput(hints = listOf(PROVIDER_HINT, other)))) + } + + @Test + fun `the identity under another short channel id is an ordinary route hint`() = runTest { + whenever(sparkService.identityPubkey()).thenReturn(IDENTITY) + + assertFalse(sut.isOwn(invoiceInput(hints = listOf(hint(IDENTITY, "1x1026x2"))))) + } + + @Test + fun `an invoice as bitkit creates it names only spark's provider, so the identity does not recognise it`() = + runTest { + whenever(sparkService.identityPubkey()).thenReturn(IDENTITY) + + assertFalse(sut.isOwn(invoiceInput())) + // The provider's node is every Spark wallet's payee, never this wallet's identity. + assertFalse(WalletSelfSendGuard.namesIdentity(invoiceInput(), PROVIDER_NODE)) + } + + @Test + fun `an invoice this wallet remembers creating is its own, without a hint and in either case`() = runTest { + whenever(sparkService.identityPubkey()).thenReturn(IDENTITY) + store.add(PAYMENT_HASH, ULong.MAX_VALUE) + + assertTrue(sut.isOwn(invoiceInput())) + assertTrue(sut.isOwn(invoiceInput(paymentHash = PAYMENT_HASH.uppercase()))) + assertFalse(sut.isOwn(invoiceInput(paymentHash = "ff".repeat(32)))) + } + + @Test + fun `a remembered invoice is its own even when the identity cannot be read`() = runTest { + whenever(sparkService.identityPubkey()).doSuspendableAnswer { throw SparkError.NotConnected() } + store.add(PAYMENT_HASH, ULong.MAX_VALUE) + + assertTrue(sut.isOwn(invoiceInput())) + } + + @Test + fun `an unknown identity fails the check instead of passing the input`() = runTest { + whenever(sparkService.identityPubkey()).doSuspendableAnswer { throw SparkError.NotConnected() } + + assertFailsWith { sut.isOwn(invoiceInput()) } + assertFailsWith { sut.isOwn(sparkAddressInput()) } + } +} From 37b2614a07e5877c6cf83d21454ff37007618927 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 01:30:24 -0300 Subject: [PATCH 03/33] feat: refuse own spark invoices in the phone's self-send guard Co-Authored-By: Claude Fable 5.2 --- .../main/java/to/bitkit/data/CacheStore.kt | 27 ++++++++ .../to/bitkit/repositories/LightningRepo.kt | 4 ++ .../java/to/bitkit/repositories/SparkRepo.kt | 23 ++++++- .../java/to/bitkit/services/SparkService.kt | 34 +++++++++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 12 +++- .../java/to/bitkit/data/CacheStoreTest.kt | 34 ++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 45 +++++++++++++ .../to/bitkit/services/SparkServiceTest.kt | 46 +++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 66 +++++++++++++++++++ 9 files changed, 287 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 18f0dc060b..bfbc831421 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -34,6 +34,9 @@ import kotlin.time.Clock */ internal const val MAX_SPARK_SEND_HASHES = 100 +/** How many unexpired invoices of the wallet's own are remembered; the ones that expire last are kept. */ +internal const val MAX_SPARK_OWN_INVOICES = 200 + /** * How long past its invoice's expiry a send no listing shows may still be pending: no send starts after the expiry, * and one settles within its HTLC timeout, which LDK caps at 1008 blocks (about a week) and Spark's routes keep @@ -167,6 +170,25 @@ class CacheStore internal constructor( } } + /** + * Remembers the Spark invoice with [paymentHash] as one this wallet created, until [expiresAt] in epoch seconds, + * so the wallet refuses to pay it. Invoices expired at [now] are dropped, as nobody can pay them. A paired + * device's invoices are added the same way. + */ + suspend fun addSparkOwnInvoice(paymentHash: String, expiresAt: Long, now: Long) { + store.updateData { data -> + val invoices = (data.sparkOwnInvoices + (paymentHash.lowercase() to expiresAt)).entries + .filter { it.value > now } + .sortedByDescending { it.value } + .take(MAX_SPARK_OWN_INVOICES) + data.copy(sparkOwnInvoices = invoices.associate { it.key to it.value }) + } + } + + /** Whether [paymentHash] is a Spark invoice of this wallet that has not expired at [now], in epoch seconds. */ + suspend fun hasSparkOwnInvoice(paymentHash: String, now: Long): Boolean = + store.data.first().sparkOwnInvoices[paymentHash.lowercase()]?.let { it > now } == true + suspend fun removeSparkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkSendHashes) return @@ -434,6 +456,11 @@ data class AppCacheData( val sparkSendHashes: List = listOf(), /** Invoice expiry in epoch seconds of the [sparkSendHashes] that know it. */ val sparkSendExpiries: Map = mapOf(), + /** + * Payment hashes of the unexpired Spark invoices this wallet created, with their expiry in epoch seconds, which + * the wallet refuses to pay: such an invoice names only Spark's provider, so nothing in it tells whose it is. + */ + val sparkOwnInvoices: Map = mapOf(), /** * Spark's sends whose outcome it didn't report, by hash, with when they started in epoch seconds, kept across a * restart until Spark settles them. diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index aa4408f4f9..00fd3a7d75 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -3133,6 +3133,10 @@ class LightningRepo @Inject constructor( /** Whether Spark alone can pay [amountSats], which it does whenever the node cannot. */ fun canSendWithSpark(amountSats: ULong): Boolean = sparkRepo.canSend(amountSats) + /** Whether [bolt11], with [paymentHash] in hex, pays this wallet's Spark balance, see [SparkRepo.isOwnInvoice]. */ + suspend fun isOwnSparkInvoice(bolt11: String, paymentHash: String): Boolean = + sparkRepo.isOwnInvoice(bolt11, paymentHash) + /** Whether Spark's whole balance covers a withdrawal debiting [debitSats], its fees included. */ fun canWithdrawWithSpark(debitSats: ULong): Boolean = sparkRepo.canWithdraw(debitSats) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 1f3272fc0b..0b67b00b1f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -529,11 +529,32 @@ class SparkRepo @Inject constructor( /** A withdrawal's debit already holds its fees, so it is weighed against the whole balance. */ fun canWithdraw(debitSats: ULong): Boolean = _state.value.isReady && _state.value.balanceSats >= debitSats + /** Creates a Spark invoice and remembers it as this wallet's own, which [isOwnInvoice] then recognises. */ suspend fun createInvoice(amountSats: ULong?, description: String, expirySecs: UInt): Result = withContext(bgDispatcher) { - runSuspendCatching { sparkService.receiveBolt11(amountSats, description, expirySecs) } + runSuspendCatching { + sparkService.receiveBolt11(amountSats, description, expirySecs).also { rememberOwnInvoice(it) } + } } + private suspend fun rememberOwnInvoice(bolt11: String) { + val invoice = sparkService.invoiceDetails(bolt11) ?: return + val expiresAt = SparkService.invoiceExpiresAt(invoice.timestamp, invoice.expiry) + cacheStore.addSparkOwnInvoice(invoice.paymentHash, expiresAt.toEpochSeconds(), clock.now().epochSeconds) + } + + /** + * Whether [bolt11], with [paymentHash] in hex, pays this Spark wallet: an unexpired invoice this wallet remembers + * creating, or one that carries this wallet's Spark address. The second check needs Spark connected and is + * skipped without it. An invoice a paired watch created is known only once its hash was added to the cache. + */ + suspend fun isOwnInvoice(bolt11: String, paymentHash: String): Boolean = withContext(bgDispatcher) { + val isRemembered = runSuspendCatching { cacheStore.hasSparkOwnInvoice(paymentHash, clock.now().epochSeconds) } + .onFailure { Logger.warn("Failed to read the wallet's own Spark invoices", it, context = TAG) } + .getOrDefault(false) + isRemembered || runSuspendCatching { sparkService.carriesOwnSparkAddress(bolt11) }.getOrDefault(false) + } + /** Returns the Lightning routing fee plus Spark's 0.25% service fee for paying [bolt11]. */ suspend fun estimateFeeSats(bolt11: String, amountSats: ULong?): Result = withContext(bgDispatcher) { runSuspendCatching { diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 21564fa141..b05e959780 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -1,5 +1,6 @@ package to.bitkit.services +import breez_sdk_spark.Bolt11InvoiceDetails import breez_sdk_spark.BreezSdk import breez_sdk_spark.ChainApiType import breez_sdk_spark.CheckRecoverFundsRequest @@ -151,6 +152,29 @@ class SparkService @Inject constructor( /** Whether [shortChannelIds], an invoice's route hint hops, carry a Spark address. */ internal fun hasSparkAddressHint(shortChannelIds: List): Boolean = SPARK_ADDRESS_HINT_SCID in shortChannelIds + + private const val SCID_BLOCK_SHIFT = 40 + private const val SCID_TX_SHIFT = 16 + private const val SCID_TX_MASK = 0xFFFFFFuL + private const val SCID_OUTPUT_MASK = 0xFFFFuL + + /** [SPARK_ADDRESS_HINT_SCID] as the SDK's parser prints a hop's: block x transaction x output. */ + internal val sparkAddressHintScid: String = SPARK_ADDRESS_HINT_SCID.let { + "${it shr SCID_BLOCK_SHIFT}x${(it shr SCID_TX_SHIFT) and SCID_TX_MASK}x${it and SCID_OUTPUT_MASK}" + } + + /** + * Whether [invoice] carries the Spark address of the wallet with [identityPubkey], its Spark identity in hex: + * the node of the Spark address hint is the identity of the wallet that asked for the invoice. Bitkit's own + * invoices carry no such hint, so this only recognises invoices made with the SDK's + * `preferSparkOverLightning` on. + */ + internal fun namesSparkIdentity(invoice: Bolt11InvoiceDetails, identityPubkey: String): Boolean = + invoice.routingHints.any { hint -> + hint.hops.any { + it.shortChannelId == sparkAddressHintScid && it.srcNodeId.equals(identityPubkey, ignoreCase = true) + } + } } private val mutex = Mutex() @@ -336,7 +360,15 @@ class SparkService @Inject constructor( /** When [bolt11] expires, in epoch seconds, read by the SDK's own parser; null when it isn't a BOLT11 invoice. */ suspend fun invoiceExpiresAt(bolt11: String): ULong? = - (requireSdk().parse(bolt11) as? InputType.Bolt11Invoice)?.v1?.let { invoiceExpiresAt(it.timestamp, it.expiry) } + invoiceDetails(bolt11)?.let { invoiceExpiresAt(it.timestamp, it.expiry) } + + /** [bolt11] as the SDK's own parser reads it; null when it isn't a BOLT11 invoice. */ + suspend fun invoiceDetails(bolt11: String): Bolt11InvoiceDetails? = + (requireSdk().parse(bolt11) as? InputType.Bolt11Invoice)?.v1 + + /** Whether [bolt11] carries this wallet's own Spark address, see [namesSparkIdentity]. */ + suspend fun carriesOwnSparkAddress(bolt11: String): Boolean = + invoiceDetails(bolt11)?.let { namesSparkIdentity(it, getInfo().identityPubkey) } == true /** * This wallet's Lightning send of [bolt11] as the Spark operators record it, without the local history: null when diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index bb6370fd50..ada94e8b00 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3940,7 +3940,15 @@ class AppViewModel @Inject constructor( return@takeIf canSend } - private suspend fun LightningInvoice.isOwnInvoice(): Boolean = isPayee(lightningRepo.awaitNodeId()) + /** + * Whether this wallet created the invoice: the node is its payee, or it pays the wallet's Spark balance, which + * the phone and a paired watch share. + */ + private suspend fun LightningInvoice.isOwnInvoice(): Boolean = + isPayee(lightningRepo.awaitNodeId()) || isOwnSparkInvoice() + + private suspend fun LightningInvoice.isOwnSparkInvoice(): Boolean = + lightningRepo.isOwnSparkInvoice(bolt11, paymentHash.toHex()) private fun LightningInvoice.isPayee(nodeId: String?): Boolean { val payee = payeeNodeId?.toHex() ?: return false @@ -3951,7 +3959,7 @@ class AppViewModel @Inject constructor( params: Map?, walletGeneration: Long? = connectionRecovery.currentGeneration(), ): Boolean = decodeLightningParam(params).also { requireCurrentPaymentPreparation(walletGeneration) } - ?.isPayee(lightningRepo.getLastKnownNodeId()) == true + ?.let { it.isPayee(lightningRepo.getLastKnownNodeId()) || it.isOwnSparkInvoice() } == true private suspend fun decodeLightningParam(params: Map?): LightningInvoice? = params?.get("lightning")?.let { bolt11 -> diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index bc0673fce4..7c5a73eb56 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -35,6 +35,40 @@ class CacheStoreTest : BaseUnitTest() { @After fun tearDown() = runBlocking { sut.reset() } + @Test + fun `an own spark invoice is known in either case until it expires`() = test { + sut.addSparkOwnInvoice("AB12", expiresAt = 2_000, now = 1_000) + + assertTrue(sut.hasSparkOwnInvoice("ab12", now = 1_999)) + assertTrue(sut.hasSparkOwnInvoice("AB12", now = 1_999)) + assertFalse(sut.hasSparkOwnInvoice("ab12", now = 2_000)) + assertFalse(sut.hasSparkOwnInvoice("cd34", now = 1_000)) + } + + @Test + fun `adding an own spark invoice drops the expired ones and keeps those that expire last`() = test { + sut.addSparkOwnInvoice("expired", expiresAt = 1_500, now = 1_000) + sut.addSparkOwnInvoice("first", expiresAt = 3_000, now = 1_600) + + assertEquals(mapOf("first" to 3_000L), sut.data.first().sparkOwnInvoices) + + repeat(MAX_SPARK_OWN_INVOICES) { sut.addSparkOwnInvoice("hash$it", expiresAt = 3_001L + it, now = 1_600) } + + val kept = sut.data.first().sparkOwnInvoices + assertEquals(MAX_SPARK_OWN_INVOICES, kept.size) + assertFalse("first" in kept) + assertTrue("hash0" in kept) + } + + @Test + fun `a wallet reset forgets the own spark invoices`() = test { + sut.addSparkOwnInvoice("ab12", expiresAt = 2_000, now = 1_000) + + sut.reset() + + assertFalse(sut.hasSparkOwnInvoice("ab12", now = 1_000)) + } + @Test fun `a spark send attempt drops expired ones and restores the earlier one`() = test { sut.setSparkSendAttempt("OLD", attempt = 2, amountSats = 100uL, expiresAt = 1_500, now = 1_000) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 24b027e868..c63c5242dc 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -187,6 +187,51 @@ class SparkRepoTest : BaseUnitTest() { } } + @Test + fun `an invoice spark creates is remembered as the wallet's own until it expires`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val created = now.epochSeconds.toULong() + val details = mock { + on { paymentHash } doReturn "AB12" + on { timestamp } doReturn created + on { expiry } doReturn 3_600uL + } + whenever { sparkService.receiveBolt11(null, "", 3_600u) }.thenReturn("lnbcrt1own") + whenever { sparkService.invoiceDetails("lnbcrt1own") }.thenReturn(details) + whenever { sparkService.carriesOwnSparkAddress(any()) }.thenReturn(false) + val sut = createSut(cacheStore = store) + + assertEquals("lnbcrt1own", sut.createInvoice(null, "", 3_600u).getOrThrow()) + + assertEquals(mapOf("ab12" to now.epochSeconds + 3_600), store.data.first().sparkOwnInvoices) + assertTrue(sut.isOwnInvoice("lnbcrt1own", "ab12")) + assertFalse(sut.isOwnInvoice("lnbcrt1other", "cd34")) + + now += 3_600.seconds + assertFalse(sut.isOwnInvoice("lnbcrt1own", "ab12")) + } + + @Test + fun `an invoice that carries this wallet's spark address is its own without being remembered`() = test { + whenever { sparkService.carriesOwnSparkAddress("lnbcrt1hint") }.thenReturn(true) + whenever { sparkService.carriesOwnSparkAddress("lnbcrt1other") }.thenReturn(false) + val sut = createSut(cacheStore = CacheStore(InMemoryDataStore(AppCacheData()), clock)) + + assertTrue(sut.isOwnInvoice("lnbcrt1hint", "ab12")) + assertFalse(sut.isOwnInvoice("lnbcrt1other", "cd34")) + } + + @Test + fun `a remembered invoice is the wallet's own while spark is not connected`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + store.addSparkOwnInvoice("ab12", now.epochSeconds + 60, now.epochSeconds) + whenever { sparkService.carriesOwnSparkAddress(any()) }.doSuspendableAnswer { throw SparkError.NotConnected() } + val sut = createSut(cacheStore = store) + + assertTrue(sut.isOwnInvoice("lnbcrt1own", "AB12")) + assertFalse(sut.isOwnInvoice("lnbcrt1other", "cd34")) + } + @Test fun `imports a restored exit backup once Spark connects`() = test { whenever { sparkService.importExitState(any()) }.thenReturn(ImportUnilateralExitStateResponse(2u, 0u, 0u, 0u)) diff --git a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt index 422e11b8b3..0b841e4b67 100644 --- a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt @@ -1,9 +1,15 @@ package to.bitkit.services +import breez_sdk_spark.BitcoinNetwork +import breez_sdk_spark.Bolt11Invoice +import breez_sdk_spark.Bolt11InvoiceDetails +import breez_sdk_spark.Bolt11RouteHint +import breez_sdk_spark.Bolt11RouteHintHop import breez_sdk_spark.ChainApiType import breez_sdk_spark.Config import breez_sdk_spark.LeafOptimizationConfig import breez_sdk_spark.Network +import breez_sdk_spark.PaymentRequestSource import breez_sdk_spark.SendPaymentOptions import breez_sdk_spark.SparkConfig import breez_sdk_spark.TokenOptimizationConfig @@ -28,6 +34,11 @@ import kotlin.test.assertNull import kotlin.test.assertTrue class SparkServiceTest { + private companion object { + const val SPARK_IDENTITY = "02698b27ac308b275671b3ca25436346469d04a5bba578ae39feba1d65897a6abc" + const val SPARK_PROVIDER_NODE = "0313ee54b3e35eed377248c83e77004972a3807af648a22ea1e8a9d22ef8b9a11c" + } + @get:Rule val tempFolder = TemporaryFolder() @@ -71,6 +82,22 @@ class SparkServiceTest { assertFalse(SparkService.hasSparkAddressHint(emptyList())) } + // What SDK 0.28.3 printed on the local regtest Spark stack (2026-11-27) for a wallet whose identity is + // SPARK_IDENTITY: an invoice made with Bitkit's settings carries only the provider's channel hint, and one made + // with `preferSparkOverLightning` on also carries the Spark address hint, whose node is the identity. + @Test + fun `an invoice names a spark identity only by its spark address hint`() { + val providerHint = hint("026ccad2762df4865753f7adc464acdbb9ae4509d0f2109789b91941cfe0e67261", "1x1026x2") + val sparkHint = hint(SPARK_IDENTITY, "16000000x16000000x1") + + assertEquals("16000000x16000000x1", SparkService.sparkAddressHintScid) + assertTrue(SparkService.namesSparkIdentity(invoice(providerHint, sparkHint), SPARK_IDENTITY)) + assertTrue(SparkService.namesSparkIdentity(invoice(providerHint, sparkHint), SPARK_IDENTITY.uppercase())) + assertFalse(SparkService.namesSparkIdentity(invoice(providerHint), SPARK_IDENTITY)) + assertFalse(SparkService.namesSparkIdentity(invoice(providerHint, sparkHint), SPARK_PROVIDER_NODE)) + assertFalse(SparkService.namesSparkIdentity(invoice(hint(SPARK_IDENTITY, "1x1026x2")), SPARK_IDENTITY)) + } + @Test fun `an invoice expiry past the largest time stays at the largest time`() { val farOff = SparkService.invoiceExpiresAt(timestamp = ULong.MAX_VALUE - 1uL, expiry = 3_600uL) @@ -160,6 +187,25 @@ class SparkServiceTest { assertNull(config.watchtowerFeeLadderEnabled) } + private fun hint(srcNodeId: String, shortChannelId: String) = Bolt11RouteHint( + listOf(Bolt11RouteHintHop(srcNodeId, shortChannelId, 0u, 0u, 0u, null, null)), + ) + + private fun invoice(vararg hints: Bolt11RouteHint) = Bolt11InvoiceDetails( + amountMsat = null, + description = "", + descriptionHash = null, + expiry = 3_600uL, + invoice = Bolt11Invoice("lnbcrt1invoice", PaymentRequestSource(null, null)), + minFinalCltvExpiryDelta = 60uL, + network = BitcoinNetwork.REGTEST, + payeePubkey = SPARK_PROVIDER_NODE, + paymentHash = "0a00a78ffbde5c36ad8220a26bb2609347bbf7e7c195622c42b81f088ccf1f6e", + paymentSecret = "secret", + routingHints = hints.toList(), + timestamp = 1_795_827_219uL, + ) + @Test fun `invoices carry no spark address on any network, so every payment is a lightning payment bitkit records`() { Network.entries.forEach { network -> diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 672cf8b27a..c0610c6dd8 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -420,6 +420,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Before fun setUp() { + whenever { lightningRepo.isOwnSparkInvoice(any(), any()) }.thenReturn(false) whenever { privatePaykitAddressReservationRepo.needsPublicAddressRotation(any()) } .thenReturn(Result.success(false)) whenever(privatePaykitRepo.isProfileDeletionInProgress).thenReturn(isProfileDeletionInProgress) @@ -12226,6 +12227,71 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.currentSheet.value) } + @Test + fun `lightning scan of own spark invoice shows self payment toast without paying`() = test { + val bolt11 = "lnbcrt1ownsparkquickpay" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u, payeeNodeId = FOREIGN_NODE_ID.fromHex()) + whenever(lightningRepo.awaitNodeId()).thenReturn(OWN_NODE_ID) + whenever(lightningRepo.isOwnSparkInvoice(bolt11, "010203")).thenReturn(true) + sut.setIsAuthenticated(true) + runCurrent() + clearInvocations(toastManager) + + sut.onScanResult(bolt11) + advanceUntilIdle() + + val toastCaptor = argumentCaptor() + verify(toastManager).enqueue(toastCaptor.capture()) + assertEquals("SelfPaymentToast", toastCaptor.lastValue.testTag) + verify(lightningRepo, never()).canSend(any()) + verify(quickPayRepo, never()).canApply(any()) + assertNull(sut.quickPayData.value) + assertNull(sut.sendUiState.value.decodedInvoice) + assertNull(sut.currentSheet.value) + } + + @Test + fun `unified scan with own spark invoice falls back to onchain`() = test { + val bolt11 = "lnbcrt1ownsparkunified" + val uri = "bitcoin:$REGTEST_ADDRESS?amount=0.00001&lightning=$bolt11" + stubUnifiedScan(uri = uri, bolt11 = bolt11, amountSats = 1_000u, payeeNodeId = FOREIGN_NODE_ID.fromHex()) + whenever(lightningRepo.awaitNodeId()).thenReturn(OWN_NODE_ID) + whenever(lightningRepo.isOwnSparkInvoice(bolt11, "010203")).thenReturn(true) + sut.setIsAuthenticated(true) + + sut.onScanResult(uri) + advanceUntilIdle() + + assertEquals(SendMethod.ONCHAIN, sut.sendUiState.value.payMethod) + assertNull(sut.sendUiState.value.decodedInvoice) + assertFalse(sut.sendUiState.value.isUnified) + verify(lightningRepo, never()).canSend(any()) + } + + @Test + fun `unified scan with own spark invoice and no savings shows self payment toast`() = test { + val bolt11 = "lnbcrt1ownsparkunifiednosavings" + val uri = "bitcoin:$REGTEST_ADDRESS?amount=0.00001&lightning=$bolt11" + stubUnifiedScan(uri = uri, bolt11 = bolt11, amountSats = 1_000u, payeeNodeId = FOREIGN_NODE_ID.fromHex()) + balanceState.value = BalanceState(maxSendOnchainSats = 0u) + whenever(lightningRepo.awaitNodeId()).thenReturn(OWN_NODE_ID) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + whenever(lightningRepo.isOwnSparkInvoice(bolt11, "010203")).thenReturn(true) + sut.setIsAuthenticated(true) + runCurrent() + clearInvocations(toastManager) + + sut.onScanResult(uri) + advanceUntilIdle() + + val toastCaptor = argumentCaptor() + verify(toastManager).enqueue(toastCaptor.capture()) + assertEquals("SelfPaymentToast", toastCaptor.lastValue.testTag) + verify(lightningRepo, never()).canSend(any()) + assertNull(sut.sendUiState.value.decodedInvoice) + } + @Test fun `lightning scan of foreign invoice still uses QuickPay`() = test { val bolt11 = "lnbcrt1foreignquickpay" From ea866e63f99fa46c8d877ff262388dd42a0684e1 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 01:30:25 -0300 Subject: [PATCH 04/33] docs: describe wear payments and the self-send guard Co-Authored-By: Claude Fable 5.2 --- docs/wear.md | 70 +++++++++++++++++++++++++++-- journeys/send/own-invoice-guard.xml | 12 ++++- 2 files changed, 77 insertions(+), 5 deletions(-) diff --git a/docs/wear.md b/docs/wear.md index 222af2f6ab..4e7f93ef28 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -64,11 +64,14 @@ Breez SDK, with no LDK node, no Room database and no Firebase. The phone is only - `security`: `SeedStore` with its Keystore-backed implementation, `SeedKey` (the AndroidKeyStore seam), `DeviceLock` (screen lock state) and `Bip39`, the one interface every BIP39 call goes through. `CoreBip39` backs it with bitkit-core, as on the phone. -- `services/WatchSparkService`: connect, disconnect, sync, info and storage wipe, with the phone's SDK settings and - the local regtest fixture. Payments, and the idempotency keys they use, come with PR 2. +- `services`: `WatchSparkService` (connect, disconnect, sync, info, storage wipe, invoices, sends and the payment + list, with the phone's SDK settings and the local regtest fixture), `SparkSendKey` (the idempotency keys of + sends, a copy of the phone's), `InputDecoder` (bitkit-core's reader of payment inputs) and `SelfSendGuard`. - `repositories`: `WalletRepo` (wallet state and balance, restore, start, lock, background and network handling, - wipe and its recovery at launch) and `CurrencyRepo` (Blocktank rates and the unit shown first). -- `data`: `SettingsStore` (display settings and the wipe's notes, with `WipeMarker` for the note itself), the rates + wipe and its recovery at launch), `PaymentsRepo` (receive, read an input, price, send, recent payments; see + Payments) and `CurrencyRepo` (Blocktank rates and the unit shown first). +- `data`: `SettingsStore` (display settings and the wipe's notes, with `WipeMarker` for the note itself), + `OwnInvoiceStore` (the invoices this wallet created, in the settings file), the rates client, `NetworkMonitor` (`ConnectivityManager`'s default network, online once the system validated it), `NfcMonitor` (the NFC adapter's state) and `ForegroundMonitor` (the process lifecycle: whether the app is on screen). @@ -162,6 +165,65 @@ On-screen copy stays short: a title or one line of at most about six words per s clear; no stacked button lists. Icon and text buttons morph their shape on press and the theme uses the expressive (spring) motion scheme. Icons are vector drawables in `res/drawable`, with no icon library. +## Payments + +`PaymentsRepo` holds every payment rule; the screens only show what it returns. Everything that reaches Spark needs +the wallet connected and synced (`WalletStatus.Ready`): no invoice is made, nothing is priced and nothing is sent +in any other state. + +- **Receive.** An amountless BOLT11 invoice from Spark, valid for one hour. The receive screen waits for its + payment, which arrives as an SDK event; Spark's payment list is read at the start of the wait and after every + sync, so a payment that landed while the wallet was disconnected is found too. +- **Inputs.** A BOLT11 invoice, an LNURL-pay link, a Lightning address and a BIP21 URI with a `lightning` + parameter are read by bitkit-core, as on the phone. A Spark address is read by the Breez SDK's parser, since + bitkit-core has no such type; only text with the shape of a Spark address is handed to it, because the SDK's + parser may look other text up on the network. On-chain addresses and every other input are refused. +- **Pricing.** Before the hold to pay, a send is priced by Spark and checked: the amount (an amountless invoice + and a Spark address need one, an LNURL amount has to be in the service's range), expiry, the self-send guard, and + the balance against the amount plus its fee. The invoice an LNURL service returns has to be for exactly the + amount asked. +- **Sending.** The send call cannot be cancelled by the screen that started it, and one send runs at a time. It + returns when Spark has the payment; the result then waits up to a minute for it to settle and reports it as + pending after that. +- **Paying once.** An invoice is sent under an idempotency key derived from the wallet seed, the payment hash and + the attempt number (`SparkSendKey`, the same derivation as the phone and iOS). Spark makes one transfer per key, + so the same invoice sent from the watch and the phone, or twice from the watch, is paid once. Before each send + Spark's payment list is read: an invoice it shows paid or pending is not sent again, and each attempt it shows + failed moves the send to the next key. A list that cannot be read refuses the send. The watch keeps no record of + its own; Spark's list is the record. +- **Unknown outcome.** When the send call fails after Spark may have taken the payment and Spark's list does not + show it, the result is "unknown", never "failed". The activity list tells once Spark lists it, and sending the + invoice again cannot pay twice. +- **QuickPay.** `PaymentsRepo.skipConfirmation` is the one place that decides whether a send skips the hold to + pay. It is always false until the watch has QuickPay settings (PR 3). + +### Self-send guard + +The phone and the watch share one Spark wallet, so neither may pay a request the other, or itself, created. Both +refuse with "Cannot Pay Own Invoice". Two checks recognise such a request: + +- **Spark identity.** Both devices have the wallet's Spark identity public key (`getInfo().identityPubkey`). A + Spark address encodes it, and a BOLT11 invoice carries it as the node of a route hint hop with the short + channel id 17592187092992000001 (`16000000x16000000x1`) when the wallet that made it had the SDK's + `preferSparkOverLightning` on. +- **Payment hash.** Each device remembers the payment hashes of the invoices it created on Spark until they + expire, at most 200, and refuses to pay them. The watch keeps them in its settings file, which the wallet's wipe + clears (`OwnInvoiceStore`); the phone keeps them in its cache store (`sparkOwnInvoices`). + +The second check exists because Bitkit creates its invoices with `preferSparkOverLightning` off: such an invoice +names Spark's provider node as its payee and one of that node's channels as its only route hint, which every Spark +wallet's invoices share, and nothing in it tells whose it is. This was read from invoices made with SDK 0.28.3 on +the local regtest stack on 2026-11-27: with the setting off the invoice had the provider's hint alone, and with it +on it gained the hint above, whose node equalled the identity key. The SDK itself prices a payment of the wallet's +own invoice without complaint. + +**Known gap.** A device does not know the invoices the other one created: the watch pays an invoice the phone made, +and the phone one the watch made, until the two share their hashes. Both stores take hashes from outside +(`OwnInvoiceStore.add`, `CacheStore.addSparkOwnInvoice`), which the pairing work (PR 4) uses to merge them. An +unpaired watch has no way to learn the phone's invoices. The watch runs the guard when an input is read, if the +wallet is ready then, and always before a send is priced, also on the invoice an LNURL service returns; a guard +that cannot tell refuses the send. + ## Seed storage The watch holds the full recovery phrase and passphrase, because Breez needs them to open the wallet. diff --git a/journeys/send/own-invoice-guard.xml b/journeys/send/own-invoice-guard.xml index d429b74ce3..4b0629d514 100644 --- a/journeys/send/own-invoice-guard.xml +++ b/journeys/send/own-invoice-guard.xml @@ -9,7 +9,10 @@ host are eaten there and the device shell splits the URI at the `&` before `lightning=`, leaving an on-chain-only URI. Wrap the whole remote command in double quotes and the URI in single quotes so one level survives to the device. Android only for now: `bitkit-ios` has no - own-invoice guard. + own-invoice guard. The last steps repeat the check with an invoice the wallet created on Spark, + which names Spark's provider as its payee, so the app knows it by the payment hash it kept when + it created it. They need Spark connected (the precondition table in `journeys/README.md`) and an invoice amount + above the channel's receiving capacity, which is what makes Receive create it on Spark. Tap Receive on the home screen (tag "Receive") @@ -28,6 +31,13 @@ Open Settings ▸ QuickPay (tag "QuickpaySettings"), turn QuickPay on, and return to the wallet overview Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<own invoice>" to.bitkit.dev` Verify from a screenshot that the "Cannot Pay Own Invoice" toast is visible and the QuickPay screen did not open + With QuickPay still on, tap Receive (tag "Receive"), tap Edit (tag "SpecifyInvoiceButton"), tap the amount field (tag "ReceiveNumberPadTextField"), enter an amount above the channel's receiving capacity shown on Settings ▸ Advanced ▸ Lightning Connections, tap Continue (tag "ReceiveNumberPadSubmit"), then tap QR Code (tag "ShowQrReceive") + Read the unified `bitcoin:` URI from the QR element's content-desc and take the `lightning=` value as the own Spark invoice; never type it. Press the device back button until the wallet overview is visible + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<own Spark invoice>" to.bitkit.dev` + Verify from a screenshot that the "Cannot Pay Own Invoice" toast is visible (tag "SelfPaymentToast") and that neither the QuickPay screen nor the Confirm screen opened + Run `adb shell "am start -a android.intent.action.VIEW -d '<unified bitcoin: URI of the Spark invoice>' to.bitkit.dev"` with the quoting described above + Verify that the send amount screen (tag "send_amount_screen") is visible with the SAVINGS source selected, and that the app log contains "Skipped own lightning invoice in unified URI, defaulting to onchain" + Press the device back button until the wallet overview is visible Open Settings ▸ QuickPay and turn QuickPay back off if it was off before this journey From 269907ee3bc06297ee1bf46904d832e15d7c1d0f Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 02:16:58 -0300 Subject: [PATCH 05/33] refactor: share the wear balance amount rows Co-Authored-By: Claude Opus 5.5 --- .../bitkit/wear/ui/components/AmountRows.kt | 180 ++++++++++++++++++ .../wear/ui/screens/home/BalancePage.kt | 161 ++-------------- .../wear/ui/screens/home/HomeViewModel.kt | 26 ++- 3 files changed, 210 insertions(+), 157 deletions(-) create mode 100644 wear/src/main/java/to/bitkit/wear/ui/components/AmountRows.kt diff --git a/wear/src/main/java/to/bitkit/wear/ui/components/AmountRows.kt b/wear/src/main/java/to/bitkit/wear/ui/components/AmountRows.kt new file mode 100644 index 0000000000..2a03945502 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/components/AmountRows.kt @@ -0,0 +1,180 @@ +package to.bitkit.wear.ui.components + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.wear.compose.material3.Text +import to.bitkit.wear.ui.screens.home.DisplayAmount +import to.bitkit.wear.ui.theme.AppTextStyles +import to.bitkit.wear.ui.theme.Colors + +/** The space between the large amount and its symbol, as on the phone. */ +private val SYMBOL_SPACING = 8.dp + +/** The large amount's size on a [SMALL_SCREEN_DP] screen. */ +private const val LARGE_SP_SMALL_SCREEN = 26f + +/** The large amount's size on a [LARGE_SCREEN_DP] screen; sizes in between are interpolated. */ +private const val LARGE_SP_LARGE_SCREEN = 30f + +/** The width of the small round screen. */ +private const val SMALL_SCREEN_DP = 192f + +/** The width of the large round screen. */ +private const val LARGE_SCREEN_DP = 227f + +/** The smallest size of the small row: Wear's minimum for essential text (WO-V14). */ +private const val MIN_SMALL_ROW_SP = 12f + +/** The gap between the small and the large row on a [SMALL_SCREEN_DP] screen; the phone's 12dp is too wide here. */ +private const val ROW_GAP_DP_SMALL_SCREEN = 3f + +/** The gap between the small and the large row on a [LARGE_SCREEN_DP] screen; sizes in between are interpolated. */ +private const val ROW_GAP_DP_LARGE_SCREEN = 4f + +@Composable +private fun screenProgress(): Float { + val widthDp = LocalConfiguration.current.screenWidthDp.toFloat() + return ((widthDp - SMALL_SCREEN_DP) / (LARGE_SCREEN_DP - SMALL_SCREEN_DP)).coerceIn(0f, 1f) +} + +@Composable +private fun amountScale(): Float { + val largeSp = LARGE_SP_SMALL_SCREEN + (LARGE_SP_LARGE_SCREEN - LARGE_SP_SMALL_SCREEN) * screenProgress() + return largeSp / AppTextStyles.Display.fontSize.value +} + +/** The gap between a [SmallAmountRow] and the [LargeAmountRow] below it, for this screen's size. */ +@Composable +fun amountRowGap(): Dp = + (ROW_GAP_DP_SMALL_SCREEN + (ROW_GAP_DP_LARGE_SCREEN - ROW_GAP_DP_SMALL_SCREEN) * screenProgress()).dp + +/** + * An amount in the phone's large balance style (`Display`), with its symbol drawn apart, scaled for the round screen + * and shrunk further only when it would not fit [maxWidth]. + */ +@Composable +fun LargeAmountRow( + amount: DisplayAmount, + maxWidth: Dp, + amountTag: String, + symbolTag: String, + modifier: Modifier = Modifier, +) { + val style = rememberFittedDisplayStyle(amount, maxWidth) + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = modifier + ) { + if (!amount.isSymbolSuffix) { + LargeSymbol( + symbol = amount.symbol, + style = style, + modifier = Modifier + .padding(end = SYMBOL_SPACING) + .testTag(symbolTag) + ) + } + Text( + text = amount.text.uppercase(), + style = style, + maxLines = 1, + modifier = Modifier.testTag(amountTag) + ) + if (amount.isSymbolSuffix) { + LargeSymbol( + symbol = amount.symbol, + style = style, + modifier = Modifier + .padding(start = SYMBOL_SPACING) + .testTag(symbolTag) + ) + } + } +} + +@Composable +private fun LargeSymbol( + symbol: String, + style: TextStyle, + modifier: Modifier = Modifier, +) { + Text( + text = symbol.uppercase(), + style = style.merge(fontWeight = FontWeight.ExtraBold, color = Colors.White64), + maxLines = 1, + modifier = modifier + ) +} + +@Composable +private fun rememberFittedDisplayStyle(amount: DisplayAmount, maxWidth: Dp): TextStyle { + val measurer = rememberTextMeasurer() + val density = LocalDensity.current + val scale = amountScale() + val base = AppTextStyles.Display.merge( + color = Colors.White, + fontSize = AppTextStyles.Display.fontSize * scale, + lineHeight = AppTextStyles.Display.lineHeight * scale, + letterSpacing = AppTextStyles.Display.letterSpacing * scale, + ) + return remember(amount, maxWidth, density, base) { + val symbolStyle = base.merge(fontWeight = FontWeight.ExtraBold) + val width = measurer.measure(amount.text.uppercase(), base, maxLines = 1).size.width + + measurer.measure(amount.symbol.uppercase(), symbolStyle, maxLines = 1).size.width + + with(density) { SYMBOL_SPACING.toPx() } + val fit = with(density) { maxWidth.toPx() } / width + if (fit >= 1f) { + base + } else { + base.merge( + fontSize = base.fontSize * fit, + lineHeight = base.lineHeight * fit, + letterSpacing = base.letterSpacing * fit, + ) + } + } +} + +/** An amount in the phone's small balance row style (`CaptionM`), uppercased and dimmed. */ +@Composable +fun SmallAmountRow( + amount: DisplayAmount, + amountTag: String, + modifier: Modifier = Modifier, +) { + val scale = amountScale() + val fontSize = (AppTextStyles.CaptionM.fontSize.value * scale).coerceAtLeast(MIN_SMALL_ROW_SP) + val style = AppTextStyles.CaptionM.merge( + color = Colors.White64, + fontSize = fontSize.sp, + lineHeight = AppTextStyles.CaptionM.lineHeight * (fontSize / AppTextStyles.CaptionM.fontSize.value), + letterSpacing = AppTextStyles.CaptionM.letterSpacing * scale, + ) + Row( + verticalAlignment = Alignment.Bottom, + horizontalArrangement = Arrangement.spacedBy(4.dp), + modifier = modifier + ) { + if (!amount.isSymbolSuffix) Text(text = amount.symbol.uppercase(), style = style) + Text( + text = amount.text.uppercase(), + style = style, + modifier = Modifier.testTag(amountTag) + ) + if (amount.isSymbolSuffix) Text(text = amount.symbol.uppercase(), style = style) + } +} diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/home/BalancePage.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/home/BalancePage.kt index b2b0c02f16..1fc2cdb623 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/home/BalancePage.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/home/BalancePage.kt @@ -8,7 +8,6 @@ import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size @@ -20,21 +19,14 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.TextStyle -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.wear.compose.material3.FilledTonalIconButton @@ -49,15 +41,17 @@ import to.bitkit.wear.ui.animations.LARGE_ROW_SWAP_SCALE import to.bitkit.wear.ui.animations.SMALL_ROW_SWAP_SCALE import to.bitkit.wear.ui.components.BezelLoading import to.bitkit.wear.ui.components.CenteredScreen +import to.bitkit.wear.ui.components.LargeAmountRow import to.bitkit.wear.ui.components.NfcHint import to.bitkit.wear.ui.components.NfcHintState +import to.bitkit.wear.ui.components.SmallAmountRow import to.bitkit.wear.ui.components.VerticalSpacer import to.bitkit.wear.ui.components.WearPreview import to.bitkit.wear.ui.components.WearPreviewDevices +import to.bitkit.wear.ui.components.amountRowGap import to.bitkit.wear.ui.components.isAmbient import to.bitkit.wear.ui.components.nfcHintState import to.bitkit.wear.ui.modifiers.clickableAlpha -import to.bitkit.wear.ui.theme.AppTextStyles import to.bitkit.wear.ui.theme.Colors /** The offline icon's distance from the top edge, which keeps it below the time. */ @@ -72,49 +66,9 @@ private val OFFLINE_TOUCH_PADDING = 15.dp /** The NFC hint's distance from the bottom edge, which keeps it above the page indicator. */ private val NFC_HINT_BOTTOM_PADDING = 22.dp -/** The space between the large balance and its symbol, as on the phone. */ -private val SYMBOL_SPACING = 8.dp - /** The side margin of the balance, which sits at the round screen's widest point, as a share of the screen width. */ private const val BALANCE_SIDE_INSET_FRACTION = 0.05f -/** The large balance's size on a [SMALL_SCREEN_DP] screen. */ -private const val LARGE_SP_SMALL_SCREEN = 26f - -/** The large balance's size on a [LARGE_SCREEN_DP] screen; sizes in between are interpolated. */ -private const val LARGE_SP_LARGE_SCREEN = 30f - -/** The width of the small round screen. */ -private const val SMALL_SCREEN_DP = 192f - -/** The width of the large round screen. */ -private const val LARGE_SCREEN_DP = 227f - -/** The smallest size of the secondary row: Wear's minimum for essential text (WO-V14). */ -private const val MIN_SMALL_ROW_SP = 12f - -/** The gap between the small and the large row on a [SMALL_SCREEN_DP] screen; the phone's 12dp is too wide here. */ -private const val ROW_GAP_DP_SMALL_SCREEN = 3f - -/** The gap between the small and the large row on a [LARGE_SCREEN_DP] screen; sizes in between are interpolated. */ -private const val ROW_GAP_DP_LARGE_SCREEN = 4f - -@Composable -private fun screenProgress(): Float { - val widthDp = LocalConfiguration.current.screenWidthDp.toFloat() - return ((widthDp - SMALL_SCREEN_DP) / (LARGE_SCREEN_DP - SMALL_SCREEN_DP)).coerceIn(0f, 1f) -} - -@Composable -private fun balanceScale(): Float { - val largeSp = LARGE_SP_SMALL_SCREEN + (LARGE_SP_LARGE_SCREEN - LARGE_SP_SMALL_SCREEN) * screenProgress() - return largeSp / AppTextStyles.Display.fontSize.value -} - -@Composable -private fun rowGap(): Dp = - (ROW_GAP_DP_SMALL_SCREEN + (ROW_GAP_DP_LARGE_SCREEN - ROW_GAP_DP_SMALL_SCREEN) * screenProgress()).dp - /** The opacity of the Bitkit mark that stands in for a balance that is hidden or not known yet. */ private const val MARK_ALPHA = 0.4f @@ -244,10 +198,14 @@ private fun BalanceHeader( if (it == EnterExitState.Visible) 1f else SMALL_ROW_SWAP_SCALE } state.amount?.let { - SmallRow(amount = it, modifier = Modifier.swapScale(SMALL_ROW_ORIGIN) { scale }) + SmallAmountRow( + amount = it, + amountTag = "WatchHomeBalanceSecondary", + modifier = Modifier.swapScale(SMALL_ROW_ORIGIN) { scale } + ) } } - VerticalSpacer(rowGap()) + VerticalSpacer(amountRowGap()) AnimatedContent( targetState = largeRowState, transitionSpec = { BalanceAnimations.swapLargeRowTransition using SizeTransform(clip = false) }, @@ -259,9 +217,11 @@ private fun BalanceHeader( if (it == EnterExitState.Visible) 1f else LARGE_ROW_SWAP_SCALE } state.amount?.let { - LargeRow( + LargeAmountRow( amount = it, maxWidth = maxRowWidth, + amountTag = "WatchHomeBalance", + symbolTag = "WatchHomeBalanceSymbol", modifier = Modifier.swapScale(LARGE_ROW_ORIGIN) { scale } ) } @@ -285,103 +245,6 @@ private fun Modifier.swapScale(origin: TransformOrigin, scale: () -> Float): Mod transformOrigin = origin } -@Composable -private fun LargeRow( - amount: DisplayAmount, - maxWidth: Dp, - modifier: Modifier = Modifier, -) { - val style = rememberFittedDisplayStyle(amount, maxWidth) - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = modifier - ) { - if (!amount.isSymbolSuffix) { - LargeSymbol(symbol = amount.symbol, style = style, modifier = Modifier.padding(end = SYMBOL_SPACING)) - } - Text( - text = amount.text.uppercase(), - style = style, - maxLines = 1, - modifier = Modifier.testTag("WatchHomeBalance") - ) - if (amount.isSymbolSuffix) { - LargeSymbol(symbol = amount.symbol, style = style, modifier = Modifier.padding(start = SYMBOL_SPACING)) - } - } -} - -@Composable -private fun LargeSymbol( - symbol: String, - style: TextStyle, - modifier: Modifier = Modifier, -) { - Text( - text = symbol.uppercase(), - style = style.merge(fontWeight = FontWeight.ExtraBold, color = Colors.White64), - maxLines = 1, - modifier = modifier.testTag("WatchHomeBalanceSymbol") - ) -} - -@Composable -private fun rememberFittedDisplayStyle(amount: DisplayAmount, maxWidth: Dp): TextStyle { - val measurer = rememberTextMeasurer() - val density = LocalDensity.current - val scale = balanceScale() - val base = AppTextStyles.Display.merge( - color = Colors.White, - fontSize = AppTextStyles.Display.fontSize * scale, - lineHeight = AppTextStyles.Display.lineHeight * scale, - letterSpacing = AppTextStyles.Display.letterSpacing * scale, - ) - return remember(amount, maxWidth, density, base) { - val symbolStyle = base.merge(fontWeight = FontWeight.ExtraBold) - val width = measurer.measure(amount.text.uppercase(), base, maxLines = 1).size.width + - measurer.measure(amount.symbol.uppercase(), symbolStyle, maxLines = 1).size.width + - with(density) { SYMBOL_SPACING.toPx() } - val fit = with(density) { maxWidth.toPx() } / width - if (fit >= 1f) { - base - } else { - base.merge( - fontSize = base.fontSize * fit, - lineHeight = base.lineHeight * fit, - letterSpacing = base.letterSpacing * fit, - ) - } - } -} - -@Composable -private fun SmallRow( - amount: DisplayAmount, - modifier: Modifier = Modifier, -) { - val scale = balanceScale() - val fontSize = (AppTextStyles.CaptionM.fontSize.value * scale).coerceAtLeast(MIN_SMALL_ROW_SP) - val style = AppTextStyles.CaptionM.merge( - color = Colors.White64, - fontSize = fontSize.sp, - lineHeight = AppTextStyles.CaptionM.lineHeight * (fontSize / AppTextStyles.CaptionM.fontSize.value), - letterSpacing = AppTextStyles.CaptionM.letterSpacing * scale, - ) - Row( - verticalAlignment = Alignment.Bottom, - horizontalArrangement = Arrangement.spacedBy(4.dp), - modifier = modifier - ) { - if (!amount.isSymbolSuffix) Text(text = amount.symbol.uppercase(), style = style) - Text( - text = amount.text.uppercase(), - style = style, - modifier = Modifier.testTag("WatchHomeBalanceSecondary") - ) - if (amount.isSymbolSuffix) Text(text = amount.symbol.uppercase(), style = style) - } -} - @Immutable private data class RowState( val isBitcoinPrimary: Boolean, diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeViewModel.kt index 309c86280e..f50b0d6f35 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeViewModel.kt @@ -133,14 +133,8 @@ internal fun homeUiState( ): HomeUiState { // A balance no sync confirmed this session, such as 0 for a wallet restored offline, is never shown. val sats = wallet.balanceSats?.takeIf { wallet.hasSynced }?.toLong() - val bitcoin = sats?.let { DisplayAmount(BITCOIN_SYMBOL, it.formatToModernDisplay(locale)) } - val fiat = sats?.let { amount -> - rates.rateFor(settings.selectedCurrency)?.let { rate -> - fiatValue(amount, rate)?.let { - DisplayAmount(rate.currencySymbol, it.formatCurrency(locale), isSymbolSuffix(rate.quote)) - } - } - } + val bitcoin = sats?.let { bitcoinAmount(it, locale) } + val fiat = sats?.let { fiatAmount(it, rates, settings.selectedCurrency, locale) } val showsFiatFirst = settings.primaryDisplay == PrimaryDisplay.FIAT && fiat != null return HomeUiState( isReady = wallet.status == WalletStatus.Ready, @@ -156,6 +150,22 @@ internal fun homeUiState( ) } +/** [sats] in bitcoin, as the balance shows it. */ +fun bitcoinAmount(sats: Long, locale: Locale = Locale.getDefault()): DisplayAmount = + DisplayAmount(BITCOIN_SYMBOL, sats.formatToModernDisplay(locale)) + +/** [sats] in [currency] at its rate in [rates], or null without that rate. */ +fun fiatAmount( + sats: Long, + rates: List, + currency: String, + locale: Locale = Locale.getDefault(), +): DisplayAmount? { + val rate = rates.rateFor(currency) ?: return null + val value = fiatValue(sats, rate) ?: return null + return DisplayAmount(rate.currencySymbol, value.formatCurrency(locale), isSymbolSuffix(rate.quote)) +} + @Immutable data class HomeUiState( val isReady: Boolean = false, From 123df0607264a54b4e1e6470924653a572a285e8 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 02:16:59 -0300 Subject: [PATCH 06/33] feat: add wear qr, screen awake and hold to pay components Co-Authored-By: Claude Opus 5.5 --- wear/build.gradle.kts | 1 + .../to/bitkit/wear/ui/components/HoldToPay.kt | 99 +++++++++++++++++++ .../to/bitkit/wear/ui/components/QrCode.kt | 78 +++++++++++++++ .../bitkit/wear/ui/components/ScreenAwake.kt | 28 ++++++ wear/src/main/res/drawable/ic_bolt.xml | 11 +++ wear/src/main/res/drawable/ic_close.xml | 11 +++ wear/src/main/res/drawable/ic_history.xml | 11 +++ wear/src/main/res/drawable/ic_north_east.xml | 11 +++ wear/src/main/res/drawable/ic_qr_code.xml | 11 +++ wear/src/main/res/drawable/ic_schedule.xml | 11 +++ wear/src/main/res/drawable/ic_south_west.xml | 11 +++ 11 files changed, 283 insertions(+) create mode 100644 wear/src/main/java/to/bitkit/wear/ui/components/HoldToPay.kt create mode 100644 wear/src/main/java/to/bitkit/wear/ui/components/QrCode.kt create mode 100644 wear/src/main/java/to/bitkit/wear/ui/components/ScreenAwake.kt create mode 100644 wear/src/main/res/drawable/ic_bolt.xml create mode 100644 wear/src/main/res/drawable/ic_close.xml create mode 100644 wear/src/main/res/drawable/ic_history.xml create mode 100644 wear/src/main/res/drawable/ic_north_east.xml create mode 100644 wear/src/main/res/drawable/ic_qr_code.xml create mode 100644 wear/src/main/res/drawable/ic_schedule.xml create mode 100644 wear/src/main/res/drawable/ic_south_west.xml diff --git a/wear/build.gradle.kts b/wear/build.gradle.kts index cc3f01ca8e..b9d3c05fda 100644 --- a/wear/build.gradle.kts +++ b/wear/build.gradle.kts @@ -228,6 +228,7 @@ dependencies { implementation(libs.datastore.preferences) implementation(libs.kotlinx.collections.immutable) implementation(libs.bitkit.core) + implementation(libs.zxing) implementation(libs.breez.sdk.spark) { exclude(group = "net.java.dev.jna", module = "jna") } // Lifecycle implementation(libs.lifecycle.viewmodel.compose) diff --git a/wear/src/main/java/to/bitkit/wear/ui/components/HoldToPay.kt b/wear/src/main/java/to/bitkit/wear/ui/components/HoldToPay.kt new file mode 100644 index 0000000000..caa811329c --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/components/HoldToPay.kt @@ -0,0 +1,99 @@ +package to.bitkit.wear.ui.components + +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.tween +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.PressInteraction +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.wear.compose.material3.CircularProgressIndicator +import kotlinx.coroutines.flow.collectLatest +import kotlin.time.Duration.Companion.milliseconds + +/** How long the wearer holds the pay button before the payment goes out. */ +val HOLD_TO_PAY_DURATION = 1_200.milliseconds + +/** How many light ticks the hold gives on its way; the last one is the confirming haptic. */ +private const val HOLD_STEPS = 4 + +/** How long the ring takes to empty again after an early release. */ +private val RELEASE_DURATION = 200.milliseconds + +/** The progress of a hold to pay, shared by the button that is held and the ring that fills around the bezel. */ +@Stable +class HoldToPayState internal constructor() { + /** The pressed state of the held button; pass it to the button as its interaction source. */ + val interactionSource = MutableInteractionSource() + internal val progress = Animatable(0f) +} + +/** + * Follows the presses of [HoldToPayState.interactionSource]: while [enabled] and held, the ring fills over + * [HOLD_TO_PAY_DURATION] with a light tick at each step and a confirming haptic at the end, and only then + * [onComplete] runs. Releasing early empties the ring and pays nothing; a tap never pays. + */ +@Composable +fun rememberHoldToPayState( + enabled: Boolean, + onComplete: () -> Unit, +): HoldToPayState { + val state = remember { HoldToPayState() } + val haptic = LocalHapticFeedback.current + val currentOnComplete by rememberUpdatedState(onComplete) + LaunchedEffect(state, enabled) { + if (!enabled) { + state.progress.snapTo(0f) + return@LaunchedEffect + } + state.interactionSource.interactions.collectLatest { interaction -> + when (interaction) { + is PressInteraction.Press -> { + state.progress.snapTo(0f) + val step = HOLD_TO_PAY_DURATION / HOLD_STEPS + for (index in 1..HOLD_STEPS) { + state.progress.animateTo( + targetValue = index.toFloat() / HOLD_STEPS, + animationSpec = tween(step.inWholeMilliseconds.toInt(), easing = LinearEasing), + ) + if (index < HOLD_STEPS) haptic.performHapticFeedback(HapticFeedbackType.SegmentTick) + } + haptic.performHapticFeedback(HapticFeedbackType.Confirm) + currentOnComplete() + } + is PressInteraction.Release, is PressInteraction.Cancel -> state.progress.animateTo( + targetValue = 0f, + animationSpec = tween(RELEASE_DURATION.inWholeMilliseconds.toInt()), + ) + } + } + } + return state +} + +/** The ring of a hold to pay around the screen edge, in the geometry of [BezelLoading]. Empty until held. */ +@Composable +fun HoldToPayRing( + state: HoldToPayState, + modifier: Modifier = Modifier, +) { + if (isAmbient()) return + CircularProgressIndicator( + progress = { state.progress.value }, + strokeWidth = BezelStrokeWidth, + modifier = modifier + .fillMaxSize() + .padding(BezelPadding) + .clearAndSetSemantics {} + ) +} diff --git a/wear/src/main/java/to/bitkit/wear/ui/components/QrCode.kt b/wear/src/main/java/to/bitkit/wear/ui/components/QrCode.kt new file mode 100644 index 0000000000..f4206d71d2 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/components/QrCode.kt @@ -0,0 +1,78 @@ +package to.bitkit.wear.ui.components + +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.FilterQuality +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.layout.ContentScale +import androidx.core.graphics.createBitmap +import com.google.zxing.BarcodeFormat +import com.google.zxing.EncodeHintType +import com.google.zxing.qrcode.QRCodeWriter +import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.ui.theme.Colors +import to.bitkit.wear.utils.Logger + +private const val TAG = "QrCode" + +/** The quiet zone around the code, in modules: the four the QR standard asks for. */ +private const val QUIET_ZONE_MODULES = 4 + +/** + * [content] as a black-on-white QR code with its quiet zone, filling its square. Error correction is level L, which + * keeps the modules of a long invoice as large as the small screen allows. Each module is one pixel of the bitmap, + * scaled up without smoothing, so the edges stay sharp at any size. The code is drawn off the main thread; the white + * square shows until it is ready. + */ +@Composable +fun QrCode( + content: String, + contentDescription: String?, + modifier: Modifier = Modifier, +) { + val bitmap by produceState(initialValue = null, content) { + value = withContext(Dispatchers.Default) { + runSuspendCatching { qrBitmap(content) } + .onFailure { Logger.error("Failed to draw a QR code", it, context = TAG) } + .getOrNull() + } + } + Box(modifier = modifier.background(Colors.White)) { + bitmap?.let { + Image( + bitmap = it, + contentDescription = contentDescription, + contentScale = ContentScale.FillBounds, + filterQuality = FilterQuality.None, + modifier = Modifier.fillMaxSize() + ) + } + } +} + +private fun qrBitmap(content: String): ImageBitmap { + val hints = mapOf( + EncodeHintType.MARGIN to QUIET_ZONE_MODULES, + EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.L, + ) + val matrix = QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, 0, 0, hints) + val pixels = IntArray(matrix.width * matrix.height) { index -> + if (matrix[index % matrix.width, index / matrix.width]) BLACK else WHITE + } + val bitmap = createBitmap(matrix.width, matrix.height) + bitmap.setPixels(pixels, 0, matrix.width, 0, 0, matrix.width, matrix.height) + return bitmap.asImageBitmap() +} + +private const val BLACK = 0xFF000000.toInt() +private const val WHITE = 0xFFFFFFFF.toInt() diff --git a/wear/src/main/java/to/bitkit/wear/ui/components/ScreenAwake.kt b/wear/src/main/java/to/bitkit/wear/ui/components/ScreenAwake.kt new file mode 100644 index 0000000000..6044c8dfaa --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/components/ScreenAwake.kt @@ -0,0 +1,28 @@ +package to.bitkit.wear.ui.components + +import android.view.WindowManager +import androidx.activity.compose.LocalActivity +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect + +/** + * Keeps the screen on while the calling screen is shown, and at full brightness when [isBright], as for a QR code + * that another device scans. Both are undone when the screen leaves. + */ +@Composable +fun ScreenAwake(isBright: Boolean = false) { + val window = LocalActivity.current?.window ?: return + DisposableEffect(window, isBright) { + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + val brightness = window.attributes.screenBrightness + if (isBright) { + window.attributes = window.attributes.apply { + screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_FULL + } + } + onDispose { + window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + if (isBright) window.attributes = window.attributes.apply { screenBrightness = brightness } + } + } +} diff --git a/wear/src/main/res/drawable/ic_bolt.xml b/wear/src/main/res/drawable/ic_bolt.xml new file mode 100644 index 0000000000..be20ffbe02 --- /dev/null +++ b/wear/src/main/res/drawable/ic_bolt.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/wear/src/main/res/drawable/ic_close.xml b/wear/src/main/res/drawable/ic_close.xml new file mode 100644 index 0000000000..3de2bd3359 --- /dev/null +++ b/wear/src/main/res/drawable/ic_close.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/wear/src/main/res/drawable/ic_history.xml b/wear/src/main/res/drawable/ic_history.xml new file mode 100644 index 0000000000..dab35b37c1 --- /dev/null +++ b/wear/src/main/res/drawable/ic_history.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/wear/src/main/res/drawable/ic_north_east.xml b/wear/src/main/res/drawable/ic_north_east.xml new file mode 100644 index 0000000000..1988229766 --- /dev/null +++ b/wear/src/main/res/drawable/ic_north_east.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/wear/src/main/res/drawable/ic_qr_code.xml b/wear/src/main/res/drawable/ic_qr_code.xml new file mode 100644 index 0000000000..c24393b80f --- /dev/null +++ b/wear/src/main/res/drawable/ic_qr_code.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/wear/src/main/res/drawable/ic_schedule.xml b/wear/src/main/res/drawable/ic_schedule.xml new file mode 100644 index 0000000000..3908a72633 --- /dev/null +++ b/wear/src/main/res/drawable/ic_schedule.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/wear/src/main/res/drawable/ic_south_west.xml b/wear/src/main/res/drawable/ic_south_west.xml new file mode 100644 index 0000000000..348f5b5909 --- /dev/null +++ b/wear/src/main/res/drawable/ic_south_west.xml @@ -0,0 +1,11 @@ + + + + + From 53ca4793e51f338f26c55265357d6c85091bbd11 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 02:16:59 -0300 Subject: [PATCH 07/33] feat: add wear receive, send and activity screens Co-Authored-By: Claude Opus 5.5 --- docs/screens-map.md | 22 +- wear/src/main/AndroidManifest.xml | 12 + .../java/to/bitkit/wear/ui/LaunchRequest.kt | 31 ++ .../java/to/bitkit/wear/ui/MainActivity.kt | 21 +- .../src/main/java/to/bitkit/wear/ui/Routes.kt | 19 +- .../java/to/bitkit/wear/ui/WearNavHost.kt | 60 +- .../screens/activity/ActivityDetailScreen.kt | 124 +++++ .../ui/screens/activity/ActivityScreen.kt | 202 +++++++ .../ui/screens/activity/ActivityViewModel.kt | 78 +++ .../bitkit/wear/ui/screens/home/HomePage.kt | 9 +- .../bitkit/wear/ui/screens/home/HomeScreen.kt | 6 + .../ui/screens/receive/ReceiveQrScreen.kt | 240 ++++++++ .../wear/ui/screens/receive/ReceiveScreen.kt | 59 ++ .../ui/screens/receive/ReceiveViewModel.kt | 95 ++++ .../bitkit/wear/ui/screens/send/SendScreen.kt | 517 ++++++++++++++++++ .../wear/ui/screens/send/SendViewModel.kt | 297 ++++++++++ wear/src/main/res/values-ar/strings.xml | 32 ++ wear/src/main/res/values-b+es+419/strings.xml | 32 ++ wear/src/main/res/values-ca/strings.xml | 32 ++ wear/src/main/res/values-cs/strings.xml | 32 ++ wear/src/main/res/values-de/strings.xml | 32 ++ wear/src/main/res/values-el/strings.xml | 32 ++ wear/src/main/res/values-es-rES/strings.xml | 32 ++ wear/src/main/res/values-es/strings.xml | 32 ++ wear/src/main/res/values-fr/strings.xml | 32 ++ wear/src/main/res/values-it/strings.xml | 32 ++ wear/src/main/res/values-nl/strings.xml | 32 ++ wear/src/main/res/values-pl/strings.xml | 32 ++ wear/src/main/res/values-pt-rBR/strings.xml | 32 ++ wear/src/main/res/values-pt/strings.xml | 32 ++ wear/src/main/res/values-ru/strings.xml | 32 ++ wear/src/main/res/values/strings.xml | 32 ++ .../to/bitkit/wear/ui/LaunchRequestTest.kt | 31 ++ .../screens/activity/ActivityViewModelTest.kt | 104 ++++ .../screens/receive/ReceiveViewModelTest.kt | 139 +++++ .../wear/ui/screens/send/SendViewModelTest.kt | 307 +++++++++++ 36 files changed, 2879 insertions(+), 6 deletions(-) create mode 100644 wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt create mode 100644 wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt create mode 100644 wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt create mode 100644 wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt create mode 100644 wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt create mode 100644 wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveScreen.kt create mode 100644 wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt create mode 100644 wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt create mode 100644 wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt create mode 100644 wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt create mode 100644 wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt create mode 100644 wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt create mode 100644 wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt diff --git a/docs/screens-map.md b/docs/screens-map.md index b89b7bd47d..e5d8b0597c 100644 --- a/docs/screens-map.md +++ b/docs/screens-map.md @@ -370,7 +370,7 @@ Amount entry stays in dollars with a BTC equivalent; QR and shared payment amoun ## Wear OS -The watch app's screens, under `wear/src/main/java/to/bitkit/wear`. None has a design yet. `HomeScreen.kt` and `SettingsScreen.kt` share their file names with phone screens and have their own rows here. +The watch app's screens, under `wear/src/main/java/to/bitkit/wear`. None has a design yet. `HomeScreen.kt`, `SettingsScreen.kt`, `ActivityDetailScreen.kt` and `ReceiveQrScreen.kt` share their file names with phone screens and have their own rows here. ### ui/components @@ -382,6 +382,13 @@ Layout scaffolds that other screens build on, not screens of their own. | ListScreen.kt | `n/a` | | MessageScreen.kt | `n/a` | +### ui/screens/activity + +| Android | Figma | +| - | - | +| ActivityDetailScreen.kt | `todo` | +| ActivityScreen.kt | `todo` | + ### ui/screens/home | Android | Figma | @@ -394,6 +401,13 @@ Layout scaffolds that other screens build on, not screens of their own. | - | - | | OnboardingScreen.kt | `todo` | +### ui/screens/receive + +| Android | Figma | +| - | - | +| ReceiveQrScreen.kt | `todo` | +| ReceiveScreen.kt | `todo` | + ### ui/screens/removed | Android | Figma | @@ -409,6 +423,12 @@ Layout scaffolds that other screens build on, not screens of their own. | RestoreStartScreen.kt | `todo` | | RestoreWordScreen.kt | `todo` | +### ui/screens/send + +| Android | Figma | +| - | - | +| SendScreen.kt | `todo` | + ### ui/screens/settings | Android | Figma | diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index e3605fc509..84492b4b6f 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -56,12 +56,24 @@ + + + + + + + + + + + diff --git a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt new file mode 100644 index 0000000000..0fccedb934 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt @@ -0,0 +1,31 @@ +package to.bitkit.wear.ui + +import android.content.Intent + +/** What an intent that opened the app asks for, beyond showing it. */ +sealed interface LaunchRequest { + /** Pay the payment input of a `lightning:`, `bitcoin:` or `spark:` link. */ + data class Send(val input: String) : LaunchRequest + + /** Show the receive QR, as from the tile. */ + data object Receive : LaunchRequest + + companion object { + /** The extra that asks for [Receive], set by the tile. */ + const val EXTRA_OPEN = "to.bitkit.wear.OPEN" + const val OPEN_RECEIVE = "receive" + + private val SEND_SCHEMES = setOf("lightning", "bitcoin", "spark") + + /** The request of an intent with [action], [data] and the [open] extra, or null for a plain launch. */ + fun from(action: String?, data: String?, open: String?): LaunchRequest? { + if (open == OPEN_RECEIVE) return Receive + if (action != Intent.ACTION_VIEW || data.isNullOrBlank()) return null + val scheme = data.substringBefore(':', missingDelimiterValue = "").lowercase() + return if (scheme in SEND_SCHEMES) Send(data) else null + } + + fun from(intent: Intent?): LaunchRequest? = + intent?.let { from(it.action, it.dataString, it.getStringExtra(EXTRA_OPEN)) } + } +} diff --git a/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt b/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt index fc264dfd3c..8ab754f533 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt @@ -1,11 +1,14 @@ package to.bitkit.wear.ui +import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId @@ -30,9 +33,14 @@ class MainActivity : ComponentActivity() { private val startViewModel: StartViewModel by viewModels() + /** What the intent that opened the app asks for, until the navigation shows it. */ + private var launchRequest by mutableStateOf(null) + override fun onCreate(savedInstanceState: Bundle?) { val splashScreen = installSplashScreen() super.onCreate(savedInstanceState) + // A recreated activity has shown its intent's request already. + if (savedInstanceState == null) launchRequest = LaunchRequest.from(intent) val splashStart = TimeSource.Monotonic.markNow() splashScreen.setKeepOnScreenCondition { startViewModel.uiState.value.isStarting && splashStart.elapsedNow() < SPLASH_LIMIT @@ -46,7 +54,13 @@ class MainActivity : ComponentActivity() { } ) { val uiState by startViewModel.uiState.collectAsStateWithLifecycle() - uiState.startRoute?.let { WearNavHost(startRoute = it) } + uiState.startRoute?.let { + WearNavHost( + startRoute = it, + launchRequest = launchRequest, + onLaunchRequestHandle = { launchRequest = null }, + ) + } if (uiState.isStarting) BezelLoading() if (uiState.isRecoveryFailed) { StartErrorScreen( @@ -60,6 +74,11 @@ class MainActivity : ComponentActivity() { } } + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + LaunchRequest.from(intent)?.let { launchRequest = it } + } + override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) // The keyguard covers the window without stopping the activity, so regaining focus is how an unlock shows. diff --git a/wear/src/main/java/to/bitkit/wear/ui/Routes.kt b/wear/src/main/java/to/bitkit/wear/ui/Routes.kt index 13baaf11b1..4e459737a2 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/Routes.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/Routes.kt @@ -1,5 +1,7 @@ package to.bitkit.wear.ui +import android.net.Uri + object Routes { const val ONBOARDING = "onboarding" @@ -12,10 +14,25 @@ object Routes { const val RESTORE_PASSPHRASE = "restore/passphrase" const val WALLET_REMOVED = "wallet_removed" - /** The home pager, with the balance and settings pages. */ + /** The home pager, with the balance, receive, activity and settings pages. */ const val HOME = "home" const val ABOUT = "about" + + /** The full-screen QR of a receive invoice. */ + const val RECEIVE_QR = "receive/qr" + + /** The send flow for the payment input in [SEND_INPUT], from a deeplink. */ + const val SEND_INPUT = "input" + const val SEND = "send?$SEND_INPUT={$SEND_INPUT}" + + /** One payment of the activity list, by its id in [ACTIVITY_PAYMENT_ID]. */ + const val ACTIVITY_PAYMENT_ID = "id" + const val ACTIVITY_DETAIL = "activity/{$ACTIVITY_PAYMENT_ID}" const val UNSUPPORTED = "unsupported" fun restoreWord(index: Int): String = "restore/word/$index" + + fun send(input: String): String = "send?$SEND_INPUT=${Uri.encode(input)}" + + fun activityDetail(paymentId: String): String = "activity/${Uri.encode(paymentId)}" } diff --git a/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt b/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt index 88e43003b1..4813d78cc7 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt @@ -5,6 +5,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel @@ -18,8 +19,11 @@ import androidx.wear.compose.navigation.SwipeDismissableNavHost import androidx.wear.compose.navigation.composable import androidx.wear.compose.navigation.rememberSwipeDismissableNavController import to.bitkit.wear.ext.navigateTo +import to.bitkit.wear.ui.screens.activity.ActivityDetailScreen +import to.bitkit.wear.ui.screens.activity.ActivityViewModel import to.bitkit.wear.ui.screens.home.HomeScreen import to.bitkit.wear.ui.screens.onboarding.OnboardingScreen +import to.bitkit.wear.ui.screens.receive.ReceiveQrScreen import to.bitkit.wear.ui.screens.removed.WalletRemovedScreen import to.bitkit.wear.ui.screens.restore.RestoreChecksumScreen import to.bitkit.wear.ui.screens.restore.RestoreEffect @@ -27,20 +31,31 @@ import to.bitkit.wear.ui.screens.restore.RestorePassphraseScreen import to.bitkit.wear.ui.screens.restore.RestoreStartScreen import to.bitkit.wear.ui.screens.restore.RestoreViewModel import to.bitkit.wear.ui.screens.restore.RestoreWordScreen +import to.bitkit.wear.ui.screens.send.SendScreen import to.bitkit.wear.ui.screens.settings.AboutScreen import to.bitkit.wear.ui.screens.unsupported.UnsupportedScreen +import to.bitkit.wear.utils.Logger @Composable fun WearNavHost( startRoute: String, + launchRequest: LaunchRequest?, + onLaunchRequestHandle: () -> Unit, modifier: Modifier = Modifier, ) { val navController = rememberSwipeDismissableNavController() var isRestoreSaving by remember { mutableStateOf(false) } + var isSending by remember { mutableStateOf(false) } + val currentOnLaunchRequestHandle by rememberUpdatedState(onLaunchRequestHandle) + LaunchedEffect(launchRequest) { + val request = launchRequest ?: return@LaunchedEffect + currentOnLaunchRequestHandle() + navController.showLaunchRequest(request) + } SwipeDismissableNavHost( navController = navController, startDestination = startRoute, - userSwipeEnabled = !isRestoreSaving, + userSwipeEnabled = !isRestoreSaving && !isSending, modifier = modifier ) { composable(Routes.ONBOARDING) { @@ -55,6 +70,8 @@ fun WearNavHost( } composable(Routes.HOME) { HomeScreen( + onReceiveClick = { navController.navigateTo(Routes.RECEIVE_QR) }, + onPaymentClick = { navController.navigateTo(Routes.activityDetail(it)) }, onAboutClick = { navController.navigateTo(Routes.ABOUT) }, onWalletRemove = { navController.navigateClearingBackStack(Routes.ONBOARDING) }, onSeedKeyLoss = { navController.navigateClearingBackStack(Routes.WALLET_REMOVED) }, @@ -63,6 +80,28 @@ fun WearNavHost( composable(Routes.ABOUT) { AboutScreen() } + composable(Routes.RECEIVE_QR) { + ReceiveQrScreen() + } + composable( + route = Routes.SEND, + arguments = listOf(navArgument(Routes.SEND_INPUT) { type = NavType.StringType }), + ) { + SendScreen( + onClose = { navController.popBackStack(Routes.SEND, inclusive = true) }, + onBusyChange = { isSending = it }, + ) + } + composable( + route = Routes.ACTIVITY_DETAIL, + arguments = listOf(navArgument(Routes.ACTIVITY_PAYMENT_ID) { type = NavType.StringType }), + ) { + val homeEntry = remember(it) { navController.getBackStackEntry(Routes.HOME) } + ActivityDetailScreen( + paymentId = it.arguments?.getString(Routes.ACTIVITY_PAYMENT_ID).orEmpty(), + viewModel = hiltViewModel(homeEntry), + ) + } composable(Routes.UNSUPPORTED) { UnsupportedScreen() } @@ -129,6 +168,25 @@ private fun NavController.showRestoreWord(index: Int) { } } +/** + * Opens what [request] asks for above Home: the send flow of a deeplink or the receive QR. Without a wallet, or + * outside Home's back stack, such as during the restore, the request is dropped. + */ +private fun NavController.showLaunchRequest(request: LaunchRequest) { + val hasHome = runCatching { getBackStackEntry(Routes.HOME) }.isSuccess + if (!hasHome) { + Logger.info("Dropped launch request '${request::class.simpleName}' outside home", context = TAG) + return + } + popBackStack(Routes.HOME, inclusive = false) + when (request) { + is LaunchRequest.Send -> navigateTo(Routes.send(request.input)) + LaunchRequest.Receive -> navigateTo(Routes.RECEIVE_QR) + } +} + +private const val TAG = "WearNavHost" + /** Navigates to [route] as the only screen, so swiping back leaves the app instead of returning. */ fun NavController.navigateClearingBackStack(route: String) { navigateTo(route) { popUpTo(graph.id) { inclusive = true } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt new file mode 100644 index 0000000000..9d8214c230 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt @@ -0,0 +1,124 @@ +package to.bitkit.wear.ui.screens.activity + +import android.text.format.DateUtils +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.Text +import to.bitkit.wear.R +import to.bitkit.wear.models.PaymentState +import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.ui.components.CenteredScreen +import to.bitkit.wear.ui.components.LargeAmountRow +import to.bitkit.wear.ui.components.WearPreview +import to.bitkit.wear.ui.components.WearPreviewDevices +import to.bitkit.wear.ui.components.isAmbient +import to.bitkit.wear.ui.screens.home.bitcoinAmount +import to.bitkit.wear.ui.theme.Colors + +/** The size of the status icon beside the status word. */ +private val STATUS_ICON_SIZE = 18.dp + +/** + * One payment of the activity list: its amount, the fee of a send, when it was made and its status. It reads the + * payment from the list's [viewModel], which belongs to Home. + */ +@Composable +fun ActivityDetailScreen( + paymentId: String, + viewModel: ActivityViewModel, + modifier: Modifier = Modifier, +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val payment = uiState.payment(paymentId) ?: return + Content(payment = payment, isAmbient = isAmbient(), modifier = modifier) +} + +@Composable +private fun Content( + payment: WatchPayment, + isAmbient: Boolean, + modifier: Modifier = Modifier, +) { + CenteredScreen(modifier = modifier) { + if (!isAmbient) { + BoxWithConstraints(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth()) { + LargeAmountRow( + amount = bitcoinAmount(payment.amountSats.toLong()), + maxWidth = maxWidth, + amountTag = "WatchActivityDetailAmount", + symbolTag = "WatchActivityDetailSymbol", + ) + } + } + if (payment.isSent && payment.feeSats > 0uL && !isAmbient) { + val fee = bitcoinAmount(payment.feeSats.toLong()) + Line( + text = stringResource(R.string.send__fee, "${fee.symbol} ${fee.text}"), + modifier = Modifier.testTag("WatchActivityDetailFee") + ) + } + val context = LocalContext.current + Line( + text = DateUtils.formatDateTime( + context, + payment.timestampSecs.toLong() * DateUtils.SECOND_IN_MILLIS, + DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_MONTH, + ), + modifier = Modifier.testTag("WatchActivityDetailTime") + ) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + DirectionIcon(payment = payment, modifier = Modifier.size(STATUS_ICON_SIZE)) + Text( + text = stringResource(payment.state.text()), + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.testTag("WatchActivityDetailStatus") + ) + } + } +} + +private fun PaymentState.text(): Int = when (this) { + PaymentState.Completed -> R.string.activity__status_completed + PaymentState.Pending -> R.string.activity__status_pending + PaymentState.Failed -> R.string.activity__status_failed +} + +@Composable +private fun Line( + text: String, + modifier: Modifier = Modifier, +) { + Text( + text = text, + style = MaterialTheme.typography.bodySmall, + color = Colors.White64, + textAlign = TextAlign.Center, + maxLines = 1, + modifier = modifier + ) +} + +@WearPreviewDevices +@Composable +private fun Preview() { + WearPreview { + Content(payment = PreviewPayment, isAmbient = false) + } +} diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt new file mode 100644 index 0000000000..f9af16c3e6 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt @@ -0,0 +1,202 @@ +package to.bitkit.wear.ui.screens.activity + +import android.text.format.DateUtils +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.material3.FilledTonalButton +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.ListHeader +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.SurfaceTransformation +import androidx.wear.compose.material3.Text +import androidx.wear.compose.material3.lazy.transformedHeight +import kotlinx.collections.immutable.persistentListOf +import to.bitkit.wear.R +import to.bitkit.wear.models.BITCOIN_SYMBOL +import to.bitkit.wear.models.PaymentState +import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.models.formatToModernDisplay +import to.bitkit.wear.ui.components.BezelLoading +import to.bitkit.wear.ui.components.CenteredScreen +import to.bitkit.wear.ui.components.ListScreen +import to.bitkit.wear.ui.components.WearPreview +import to.bitkit.wear.ui.components.WearPreviewDevices +import to.bitkit.wear.ui.components.isAmbient +import to.bitkit.wear.ui.theme.Colors + +/** The size of the empty state's icon. */ +private val EMPTY_ICON_SIZE = 40.dp + +/** The opacity of the icons that stand in for the list while it is empty, loading or hidden. */ +private const val DIM_ALPHA = 0.4f + +/** + * The activity page of the home pager: the newest payments, each with its direction, amount and how long ago it + * was. A tap opens its detail ([onPaymentClick]). Ambient mode hides the amounts. + */ +@Composable +fun ActivityScreen( + onPaymentClick: (String) -> Unit, + modifier: Modifier = Modifier, + viewModel: ActivityViewModel = hiltViewModel(), +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + Content( + uiState = uiState, + isAmbient = isAmbient(), + onPaymentClick = onPaymentClick, + modifier = modifier + ) +} + +@Composable +private fun Content( + uiState: ActivityUiState, + isAmbient: Boolean, + onPaymentClick: (String) -> Unit, + modifier: Modifier = Modifier, +) { + when { + isAmbient -> CenteredScreen(modifier = modifier) { DimIcon(modifier = Modifier.testTag("WatchActivityHidden")) } + !uiState.isLoaded -> CenteredScreen(overlay = { BezelLoading() }, modifier = modifier) { DimIcon() } + uiState.payments.isEmpty() -> CenteredScreen(modifier = modifier) { + DimIcon() + Text( + text = stringResource(R.string.activity__empty), + style = MaterialTheme.typography.titleSmall, + color = Colors.White64, + modifier = Modifier.testTag("WatchActivityEmpty") + ) + } + else -> List(uiState = uiState, onPaymentClick = onPaymentClick, modifier = modifier) + } +} + +@Composable +private fun List( + uiState: ActivityUiState, + onPaymentClick: (String) -> Unit, + modifier: Modifier = Modifier, +) { + Box(modifier = modifier.fillMaxSize()) { + ListScreen { spec -> + item { + ListHeader( + transformation = SurfaceTransformation(spec), + modifier = Modifier.transformedHeight(this, spec) + ) { + Text(stringResource(R.string.activity__title)) + } + } + uiState.payments.forEachIndexed { index, payment -> + item(key = payment.id) { + FilledTonalButton( + onClick = { onPaymentClick(payment.id) }, + icon = { DirectionIcon(payment = payment) }, + label = { Text(text = payment.amountText(), maxLines = 1) }, + secondaryLabel = { + Text(text = relativeTime(payment.timestampSecs.toLong(), uiState.nowSecs), maxLines = 1) + }, + transformation = SurfaceTransformation(spec), + modifier = Modifier + .fillMaxWidth() + .transformedHeight(this, spec) + .testTag("WatchActivityItem-$index") + ) + } + } + } + } +} + +/** The payment's direction, or its state when it is not completed. */ +@Composable +internal fun DirectionIcon( + payment: WatchPayment, + modifier: Modifier = Modifier, +) { + val (icon, description) = when { + payment.state == PaymentState.Pending -> R.drawable.ic_schedule to R.string.activity__status_pending + payment.state == PaymentState.Failed -> R.drawable.ic_close to R.string.activity__status_failed + payment.isSent -> R.drawable.ic_north_east to R.string.activity__sent + else -> R.drawable.ic_south_west to R.string.activity__received + } + Icon( + painter = painterResource(icon), + contentDescription = stringResource(description), + tint = if (payment.state == PaymentState.Failed) MaterialTheme.colorScheme.error else Colors.Brand, + modifier = modifier + ) +} + +/** The payment's amount in bitcoin, with the phone's sign for its direction. */ +internal fun WatchPayment.amountText(): String { + val sign = if (isSent) "-" else "+" + return "$sign $BITCOIN_SYMBOL ${amountSats.toLong().formatToModernDisplay()}" +} + +/** How long ago [timestampSecs] was; a time ahead of the watch's clock, set by Spark's servers, counts as now. */ +private fun relativeTime(timestampSecs: Long, nowSecs: Long): String = DateUtils.getRelativeTimeSpanString( + timestampSecs.coerceAtMost(nowSecs) * DateUtils.SECOND_IN_MILLIS, + nowSecs * DateUtils.SECOND_IN_MILLIS, + DateUtils.MINUTE_IN_MILLIS, + DateUtils.FORMAT_ABBREV_RELATIVE, +).toString() + +@Composable +private fun DimIcon(modifier: Modifier = Modifier) { + Icon( + painter = painterResource(R.drawable.ic_history), + contentDescription = null, + tint = Colors.White.copy(alpha = DIM_ALPHA), + modifier = modifier.size(EMPTY_ICON_SIZE) + ) +} + +@WearPreviewDevices +@Composable +private fun Preview() { + WearPreview { + Content( + uiState = ActivityUiState( + payments = persistentListOf( + PreviewPayment, + PreviewPayment.copy(id = "2", isSent = false, amountSats = 50_000uL, timestampSecs = 1_000uL), + PreviewPayment.copy(id = "3", state = PaymentState.Pending), + ), + isLoaded = true, + nowSecs = 4_000, + ), + isAmbient = false, + onPaymentClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewEmpty() { + WearPreview { + Content(uiState = ActivityUiState(isLoaded = true), isAmbient = false, onPaymentClick = {}) + } +} + +internal val PreviewPayment = WatchPayment( + id = "1", + isSent = true, + amountSats = 21_000uL, + feeSats = 3uL, + timestampSecs = 3_400uL, + state = PaymentState.Completed, +) diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt new file mode 100644 index 0000000000..c0ef8afca9 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt @@ -0,0 +1,78 @@ +package to.bitkit.wear.ui.screens.activity + +import androidx.compose.runtime.Immutable +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.toImmutableList +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.merge +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.repositories.PaymentsRepo +import to.bitkit.wear.repositories.WalletRepo +import to.bitkit.wear.repositories.WalletStatus +import java.time.Instant +import javax.inject.Inject + +/** + * The newest payments from Spark's local list, read whenever the wallet becomes connected and after every payment or + * sync. While Spark is disconnected the last list stays on screen. + */ +@HiltViewModel +class ActivityViewModel internal constructor( + private val paymentsRepo: PaymentsRepo, + private val walletRepo: WalletRepo, + private val nowSecs: () -> Long, +) : ViewModel() { + @Inject + constructor( + paymentsRepo: PaymentsRepo, + walletRepo: WalletRepo, + ) : this(paymentsRepo, walletRepo, { Instant.now().epochSecond }) + + private val _uiState = MutableStateFlow(ActivityUiState()) + val uiState: StateFlow = _uiState.asStateFlow() + + init { + viewModelScope.launch { + val connected = walletRepo.walletState + .map { it.status in connectedStatuses } + .distinctUntilChanged() + .filter { it } + .map { } + merge(connected, paymentsRepo.paymentChanges).collectLatest { load() } + } + } + + private suspend fun load() { + paymentsRepo.recentPayments().onSuccess { payments -> + _uiState.update { + it.copy(payments = payments.toImmutableList(), isLoaded = true, nowSecs = nowSecs()) + } + } + } +} + +/** Spark's local list can be read while Spark is connected, synced or not. */ +private val connectedStatuses = setOf(WalletStatus.Ready, WalletStatus.Offline) + +@Immutable +data class ActivityUiState( + val payments: ImmutableList = persistentListOf(), + /** Whether a list was read this session; until then the loading ring shows. */ + val isLoaded: Boolean = false, + /** When the list was read, in epoch seconds, which the relative times count from. */ + val nowSecs: Long = 0, +) { + fun payment(id: String): WatchPayment? = payments.firstOrNull { it.id == id } +} diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomePage.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomePage.kt index 88c59322e4..5ef80a8825 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomePage.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomePage.kt @@ -4,7 +4,12 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf /** The pages of the home pager. */ -enum class HomePage { Balance, Settings } +enum class HomePage { Balance, Receive, Activity, Settings } /** The home pages in swipe order; the pager opens on the first. Add a page by listing it here. */ -val HOME_PAGES: ImmutableList = persistentListOf(HomePage.Balance, HomePage.Settings) +val HOME_PAGES: ImmutableList = persistentListOf( + HomePage.Balance, + HomePage.Receive, + HomePage.Activity, + HomePage.Settings, +) diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeScreen.kt index 23cfb8b733..cf7c37dddd 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeScreen.kt @@ -16,6 +16,8 @@ import androidx.wear.compose.material3.HorizontalPagerScaffold import kotlinx.collections.immutable.ImmutableList import to.bitkit.wear.ui.components.LocalListBottomInset import to.bitkit.wear.ui.components.PageIndicatorPadding +import to.bitkit.wear.ui.screens.activity.ActivityScreen +import to.bitkit.wear.ui.screens.receive.ReceiveScreen import to.bitkit.wear.ui.screens.settings.SettingsScreen /** @@ -26,6 +28,8 @@ import to.bitkit.wear.ui.screens.settings.SettingsScreen */ @Composable fun HomeScreen( + onReceiveClick: () -> Unit, + onPaymentClick: (String) -> Unit, onAboutClick: () -> Unit, onWalletRemove: () -> Unit, onSeedKeyLoss: () -> Unit, @@ -47,6 +51,8 @@ fun HomeScreen( CompositionLocalProvider(LocalListBottomInset provides PageIndicatorPadding) { when (pages[page]) { HomePage.Balance -> BalancePage(viewModel = viewModel) + HomePage.Receive -> ReceiveScreen(onQrClick = onReceiveClick) + HomePage.Activity -> ActivityScreen(onPaymentClick = onPaymentClick) HomePage.Settings -> SettingsScreen(onAboutClick = onAboutClick) } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt new file mode 100644 index 0000000000..eaa7549ef5 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt @@ -0,0 +1,240 @@ +package to.bitkit.wear.ui.screens.receive + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.material3.FilledTonalIconButton +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.IconButtonDefaults +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.Text +import to.bitkit.wear.R +import to.bitkit.wear.ui.components.BezelLoading +import to.bitkit.wear.ui.components.CenteredScreen +import to.bitkit.wear.ui.components.QrCode +import to.bitkit.wear.ui.components.ScreenAwake +import to.bitkit.wear.ui.components.SmallAmountRow +import to.bitkit.wear.ui.components.WearPreview +import to.bitkit.wear.ui.components.WearPreviewDevices +import to.bitkit.wear.ui.components.isAmbient +import to.bitkit.wear.ui.modifiers.clickableAlpha +import to.bitkit.wear.ui.screens.home.DisplayAmount +import to.bitkit.wear.ui.theme.Colors + +/** The QR's side as a share of the screen: the largest square inside the round screen (1/√2). */ +private const val QR_SIZE_FRACTION = 0.707f + +/** The size of the check and of the dimmed QR icon. */ +private val MARK_SIZE = 56.dp + +/** The opacity of the QR icon that stands in for the hidden QR in ambient mode. */ +private const val HIDDEN_ALPHA = 0.4f + +/** + * The receive QR, as large as the round screen allows, at full brightness and with the screen kept on while it + * shows. Ambient mode hides it. A paid invoice turns into a check with the amount and its own haptic; a tap on the + * check makes a new invoice. + */ +@Composable +fun ReceiveQrScreen( + modifier: Modifier = Modifier, + viewModel: ReceiveViewModel = hiltViewModel(), +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val haptic = LocalHapticFeedback.current + val isPaid = uiState.paidAmount != null + LaunchedEffect(isPaid) { + // A firm click, unlike the confirm pattern a send ends with, so the two never feel alike. + if (isPaid) haptic.performHapticFeedback(HapticFeedbackType.LongPress) + } + Content( + uiState = uiState, + isAmbient = isAmbient(), + onRefreshClick = viewModel::onRefreshClick, + modifier = modifier + ) +} + +@Composable +private fun Content( + uiState: ReceiveUiState, + isAmbient: Boolean, + onRefreshClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val qrContent = uiState.qrContent + val paidAmount = uiState.paidAmount + when { + paidAmount != null -> Paid(amount = paidAmount, onClick = onRefreshClick, modifier = modifier) + qrContent != null && isAmbient -> Hidden(modifier = modifier) + qrContent != null -> Qr(content = qrContent, modifier = modifier) + uiState.isError -> Error(onRetryClick = onRefreshClick, modifier = modifier) + else -> CenteredScreen( + overlay = { BezelLoading() }, + modifier = modifier + ) { + QrIcon(modifier = Modifier.testTag("WatchReceiveLoading")) + } + } +} + +@Composable +private fun Qr( + content: String, + modifier: Modifier = Modifier, +) { + ScreenAwake(isBright = true) + BoxWithConstraints( + contentAlignment = Alignment.Center, + modifier = modifier.fillMaxSize() + ) { + QrCode( + content = content, + contentDescription = stringResource(R.string.receive__title), + modifier = Modifier + .size(minOf(maxWidth, maxHeight) * QR_SIZE_FRACTION) + .testTag("WatchReceiveQr") + ) + } +} + +@Composable +private fun Hidden(modifier: Modifier = Modifier) { + val description = stringResource(R.string.receive__hidden) + CenteredScreen(modifier = modifier) { + QrIcon( + modifier = Modifier + .semantics { contentDescription = description } + .testTag("WatchReceiveHidden") + ) + } +} + +@Composable +private fun QrIcon(modifier: Modifier = Modifier) { + Icon( + painter = painterResource(R.drawable.ic_qr_code), + contentDescription = null, + tint = Colors.White.copy(alpha = HIDDEN_ALPHA), + modifier = modifier.size(MARK_SIZE) + ) +} + +@Composable +private fun Paid( + amount: DisplayAmount, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + CenteredScreen(modifier = modifier) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier + .clickableAlpha(onClickLabel = stringResource(R.string.receive__new), onClick = onClick) + .testTag("WatchReceivePaid") + ) { + Icon( + painter = painterResource(R.drawable.ic_check), + contentDescription = stringResource(R.string.receive__paid), + tint = Colors.Brand, + modifier = Modifier.size(MARK_SIZE) + ) + SmallAmountRow(amount = amount, amountTag = "WatchReceivePaidAmount") + } + } +} + +@Composable +private fun Error( + onRetryClick: () -> Unit, + modifier: Modifier = Modifier, +) { + CenteredScreen(modifier = modifier) { + Text( + text = stringResource(R.string.receive__error), + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.error, + textAlign = TextAlign.Center, + modifier = Modifier.testTag("WatchReceiveError") + ) + FilledTonalIconButton( + onClick = onRetryClick, + shapes = IconButtonDefaults.animatedShapes(), + modifier = Modifier.testTag("WatchReceiveRetry") + ) { + Icon( + painter = painterResource(R.drawable.ic_refresh), + contentDescription = stringResource(R.string.common__retry), + ) + } + } +} + +@WearPreviewDevices +@Composable +private fun Preview() { + WearPreview { + Content( + uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), + isAmbient = false, + onRefreshClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewPaid() { + WearPreview { + Content( + uiState = ReceiveUiState(paidAmount = DisplayAmount(symbol = "₿", text = "21 000")), + isAmbient = false, + onRefreshClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewAmbient() { + WearPreview { + Content( + uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), + isAmbient = true, + onRefreshClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewError() { + WearPreview { + Content( + uiState = ReceiveUiState(isError = true), + isAmbient = false, + onRefreshClick = {}, + ) + } +} + +private const val PREVIEW_INVOICE = "LNBCRT1P5EXAMPLEPP5QQQSYQCYQ5RQWZQFQQQSYQCYQ5RQWZQFQQQSYQCYQ5RQWZQFQYPQDQ0XQRRSS" diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveScreen.kt new file mode 100644 index 0000000000..33d5847a7b --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveScreen.kt @@ -0,0 +1,59 @@ +package to.bitkit.wear.ui.screens.receive + +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.wear.compose.material3.FilledIconButton +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.IconButtonDefaults +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.Text +import to.bitkit.wear.R +import to.bitkit.wear.ui.components.CenteredScreen +import to.bitkit.wear.ui.components.WearPreview +import to.bitkit.wear.ui.components.WearPreviewDevices + +/** The size of the receive button: the page's one large control. */ +private val BUTTON_SIZE = 88.dp + +/** The size of the QR icon inside the button. */ +private val ICON_SIZE = 44.dp + +/** The receive page of the home pager: one large round button that opens the receive QR. */ +@Composable +fun ReceiveScreen( + onQrClick: () -> Unit, + modifier: Modifier = Modifier, +) { + CenteredScreen(modifier = modifier) { + FilledIconButton( + onClick = onQrClick, + shapes = IconButtonDefaults.animatedShapes(), + modifier = Modifier + .size(BUTTON_SIZE) + .testTag("WatchReceiveOpen") + ) { + Icon( + painter = painterResource(R.drawable.ic_qr_code), + contentDescription = null, + modifier = Modifier.size(ICON_SIZE) + ) + } + Text( + text = stringResource(R.string.receive__title), + style = MaterialTheme.typography.titleSmall, + ) + } +} + +@WearPreviewDevices +@Composable +private fun Preview() { + WearPreview { + ReceiveScreen(onQrClick = {}) + } +} diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt new file mode 100644 index 0000000000..8f576ba916 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt @@ -0,0 +1,95 @@ +package to.bitkit.wear.ui.screens.receive + +import androidx.compose.runtime.Immutable +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import to.bitkit.wear.env.Env +import to.bitkit.wear.repositories.PaymentsRepo +import to.bitkit.wear.repositories.WalletRepo +import to.bitkit.wear.repositories.WalletStatus +import to.bitkit.wear.ui.screens.home.DisplayAmount +import to.bitkit.wear.ui.screens.home.bitcoinAmount +import to.bitkit.wear.utils.Logger +import java.time.Instant +import javax.inject.Inject +import kotlin.time.Duration.Companion.seconds + +/** + * The receive QR: an amountless invoice made once the wallet is ready, shown until it is paid or nearly expired. + * A nearly expired invoice is replaced by a new one; a paid one turns into a check until the wearer asks for a new + * invoice. + */ +@HiltViewModel +class ReceiveViewModel internal constructor( + private val paymentsRepo: PaymentsRepo, + private val walletRepo: WalletRepo, + private val nowSecs: () -> Long, +) : ViewModel() { + companion object { + private const val TAG = "ReceiveViewModel" + + /** How long before its expiry an invoice is replaced, so a payer never scans one that is about to expire. */ + val EXPIRY_MARGIN = 60.seconds + } + + @Inject + constructor( + paymentsRepo: PaymentsRepo, + walletRepo: WalletRepo, + ) : this(paymentsRepo, walletRepo, { Instant.now().epochSecond }) + + private val _uiState = MutableStateFlow(ReceiveUiState()) + val uiState: StateFlow = _uiState.asStateFlow() + + private var job: Job? = null + + init { + refresh() + } + + /** Makes a new invoice: after an error, and after the last one was paid. */ + fun onRefreshClick() = refresh() + + private fun refresh() { + job?.cancel() + job = viewModelScope.launch { + while (true) { + _uiState.update { ReceiveUiState(isLoading = true) } + walletRepo.walletState.first { it.status == WalletStatus.Ready } + val invoice = paymentsRepo.createInvoice().getOrElse { + _uiState.update { state -> state.copy(isLoading = false, isError = true) } + return@launch + } + if (Env.isDebug) Logger.debug("Showing invoice '${invoice.bolt11}'", context = TAG) + _uiState.update { it.copy(qrContent = invoice.bolt11.uppercase(), isLoading = false) } + val lifetime = (invoice.expiresAtSecs.toLong() - nowSecs()).seconds - EXPIRY_MARGIN + val paid = withTimeoutOrNull(lifetime.coerceAtLeast(0.seconds)) { paymentsRepo.awaitPaid(invoice) } + if (paid != null) { + Logger.info("Received payment '${paid.id}'", context = TAG) + _uiState.update { ReceiveUiState(paidAmount = bitcoinAmount(paid.amountSats.toLong())) } + return@launch + } + Logger.debug("Replacing invoice '${invoice.paymentHash}' before it expires", context = TAG) + } + } + } +} + +@Immutable +data class ReceiveUiState( + /** The uppercased invoice the QR shows, or null while there is none to show. */ + val qrContent: String? = null, + val isLoading: Boolean = false, + val isError: Boolean = false, + /** What the paid invoice brought in, shown with the check. */ + val paidAmount: DisplayAmount? = null, +) diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt new file mode 100644 index 0000000000..665943d944 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt @@ -0,0 +1,517 @@ +package to.bitkit.wear.ui.screens.send + +import androidx.activity.compose.BackHandler +import androidx.annotation.DrawableRes +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.material3.EdgeButton +import androidx.wear.compose.material3.EdgeButtonSize +import androidx.wear.compose.material3.FilledTonalIconButton +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.IconButtonDefaults +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.Text +import to.bitkit.wear.R +import to.bitkit.wear.models.formatToModernDisplay +import to.bitkit.wear.ui.components.BezelLoading +import to.bitkit.wear.ui.components.CenteredScreen +import to.bitkit.wear.ui.components.HoldToPayRing +import to.bitkit.wear.ui.components.LargeAmountRow +import to.bitkit.wear.ui.components.ScreenAwake +import to.bitkit.wear.ui.components.SmallAmountRow +import to.bitkit.wear.ui.components.WearPreview +import to.bitkit.wear.ui.components.WearPreviewDevices +import to.bitkit.wear.ui.components.amountRowGap +import to.bitkit.wear.ui.components.rememberHoldToPayState +import to.bitkit.wear.ui.screens.home.DisplayAmount +import to.bitkit.wear.ui.theme.Colors + +/** The size of the icon that tops a status: the check, the cross, the clock and the bolt while loading. */ +private val STATUS_ICON_SIZE = 48.dp + +/** The opacity of the bolt that shows while the send is loading or under way. */ +private const val LOADING_ICON_ALPHA = 0.4f + +/** + * The send flow of a deeplink: review with the hold to pay, the send under way, and its result, which closes the + * flow by itself ([onClose]). The amount entry shows only for an input that names no amount. While a send is under + * way the screen stays on and cannot be left ([onBusyChange]). + */ +@Composable +fun SendScreen( + onClose: () -> Unit, + onBusyChange: (Boolean) -> Unit, + modifier: Modifier = Modifier, + viewModel: SendViewModel = hiltViewModel(), +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val currentOnClose by rememberUpdatedState(onClose) + val currentOnBusyChange by rememberUpdatedState(onBusyChange) + val haptic = LocalHapticFeedback.current + LaunchedEffect(viewModel) { + viewModel.effects.collect { + when (it) { + SendEffect.Close -> currentOnClose() + } + } + } + LaunchedEffect(uiState.isBusy) { currentOnBusyChange(uiState.isBusy) } + val step = uiState.step + LaunchedEffect(step is SendStep.Done, step is SendStep.Failed) { + when (step) { + is SendStep.Done if step.result == SendResult.Sent -> + haptic.performHapticFeedback(HapticFeedbackType.Confirm) + is SendStep.Failed -> haptic.performHapticFeedback(HapticFeedbackType.Reject) + else -> Unit + } + } + BackHandler(enabled = uiState.isBusy) {} + Content( + uiState = uiState, + onAmountChange = viewModel::onAmountChange, + onAmountConfirm = viewModel::onAmountConfirm, + onHoldComplete = viewModel::onHoldComplete, + onCloseClick = viewModel::onCloseClick, + modifier = modifier + ) +} + +@Composable +private fun Content( + uiState: SendUiState, + onAmountChange: (String) -> Unit, + onAmountConfirm: () -> Unit, + onHoldComplete: () -> Unit, + onCloseClick: () -> Unit, + modifier: Modifier = Modifier, +) { + when (val step = uiState.step) { + SendStep.Loading -> Loading(isOffline = uiState.isOffline, modifier = modifier) + is SendStep.Amount -> Amount( + step = step, + text = uiState.amountText, + onTextChange = onAmountChange, + onConfirm = onAmountConfirm, + modifier = modifier + ) + is SendStep.Review -> Review( + step = step, + isHoldEnabled = uiState.isHoldEnabled, + isOffline = !uiState.isWalletReady, + onHoldComplete = onHoldComplete, + modifier = modifier + ) + is SendStep.Sending -> Sending(isWaiting = step.isWaiting, modifier = modifier) + is SendStep.Done -> Done(step = step, modifier = modifier) + is SendStep.Failed -> Failed(failure = step.failure, onCloseClick = onCloseClick, modifier = modifier) + } +} + +@Composable +private fun Loading( + isOffline: Boolean, + modifier: Modifier = Modifier, +) { + CenteredScreen( + overlay = { BezelLoading() }, + modifier = modifier + ) { + StatusIcon( + icon = R.drawable.ic_bolt, + tint = Colors.White.copy(alpha = LOADING_ICON_ALPHA), + modifier = Modifier.testTag("WatchSendLoading") + ) + if (isOffline) OfflineLine() + } +} + +@Composable +private fun Amount( + step: SendStep.Amount, + text: String, + onTextChange: (String) -> Unit, + onConfirm: () -> Unit, + modifier: Modifier = Modifier, +) { + CenteredScreen( + edgeButton = { + EdgeButton( + onClick = onConfirm, + buttonSize = EdgeButtonSize.Small, + modifier = Modifier.testTag("WatchSendAmountConfirm") + ) { + Icon( + painter = painterResource(R.drawable.ic_arrow_forward), + contentDescription = stringResource(R.string.send__amount_confirm), + ) + } + }, + modifier = modifier + ) { + AmountField( + value = text, + onValueChange = onTextChange, + onDone = onConfirm, + modifier = Modifier + .fillMaxWidth() + .testTag("WatchSendAmountInput") + ) + val min = step.minSats + val max = step.maxSats + when { + step.isOutOfRange -> Line( + text = stringResource(R.string.send__error_out_of_range), + color = MaterialTheme.colorScheme.error, + modifier = Modifier.testTag("WatchSendAmountError") + ) + min != null && max != null -> Line( + text = stringResource( + R.string.send__amount_range, + min.toLong().formatToModernDisplay(), + max.toLong().formatToModernDisplay(), + ), + modifier = Modifier.testTag("WatchSendAmountRange") + ) + } + } +} + +@Composable +private fun AmountField( + value: String, + onValueChange: (String) -> Unit, + onDone: () -> Unit, + modifier: Modifier = Modifier, +) { + BasicTextField( + value = value, + onValueChange = onValueChange, + singleLine = true, + textStyle = MaterialTheme.typography.titleMedium.copy( + color = MaterialTheme.colorScheme.onSurface, + textAlign = TextAlign.Center, + ), + cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done), + keyboardActions = KeyboardActions(onDone = { onDone() }), + decorationBox = { innerTextField -> + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .background(MaterialTheme.colorScheme.surfaceContainer, CircleShape) + .border(1.dp, MaterialTheme.colorScheme.outline, CircleShape) + .padding(horizontal = 16.dp, vertical = 8.dp) + ) { + if (value.isEmpty()) { + Text( + text = stringResource(R.string.send__amount_placeholder), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + } + innerTextField() + } + }, + modifier = modifier + ) +} + +@Composable +private fun Review( + step: SendStep.Review, + isHoldEnabled: Boolean, + isOffline: Boolean, + onHoldComplete: () -> Unit, + modifier: Modifier = Modifier, +) { + val holdState = rememberHoldToPayState(enabled = isHoldEnabled, onComplete = onHoldComplete) + CenteredScreen( + edgeButton = { + EdgeButton( + // A tap never pays: only the hold that rememberHoldToPayState follows does. + onClick = {}, + enabled = isHoldEnabled, + buttonSize = EdgeButtonSize.Medium, + interactionSource = holdState.interactionSource, + modifier = Modifier.testTag("WatchSendHold") + ) { + Text(stringResource(R.string.send__hold)) + } + }, + overlay = { HoldToPayRing(state = holdState) }, + modifier = modifier + ) { + BoxWithConstraints(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth()) { + LargeAmountRow( + amount = step.amount, + maxWidth = maxWidth, + amountTag = "WatchSendAmount", + symbolTag = "WatchSendAmountSymbol", + ) + } + step.fiat?.let { + SmallAmountRow( + amount = it, + amountTag = "WatchSendFiat", + modifier = Modifier.padding(top = amountRowGap()) + ) + } + step.fee?.let { + Line( + text = stringResource(R.string.send__fee, "${it.symbol} ${it.text}"), + modifier = Modifier.testTag("WatchSendFee") + ) + } + when { + isOffline -> OfflineLine() + step.payee != null -> Line(text = step.payee, modifier = Modifier.testTag("WatchSendPayee")) + } + } +} + +@Composable +private fun Sending( + isWaiting: Boolean, + modifier: Modifier = Modifier, +) { + ScreenAwake() + CenteredScreen( + overlay = { BezelLoading() }, + modifier = modifier + ) { + StatusIcon( + icon = R.drawable.ic_bolt, + tint = Colors.White.copy(alpha = LOADING_ICON_ALPHA), + modifier = Modifier.testTag("WatchSendSending") + ) + if (isWaiting) { + Line(text = stringResource(R.string.send__waiting), modifier = Modifier.testTag("WatchSendWaiting")) + } + } +} + +@Composable +private fun Done( + step: SendStep.Done, + modifier: Modifier = Modifier, +) { + CenteredScreen(modifier = modifier) { + when (step.result) { + SendResult.Sent -> { + StatusIcon(icon = R.drawable.ic_check, tint = Colors.Brand) + Text( + text = stringResource(R.string.send__sent), + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.testTag("WatchSendSent") + ) + SmallAmountRow(amount = step.amount, amountTag = "WatchSendResultAmount") + } + SendResult.Pending -> { + StatusIcon(icon = R.drawable.ic_schedule, tint = Colors.White64) + Text( + text = stringResource(R.string.send__pending), + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.testTag("WatchSendPending") + ) + } + SendResult.Unknown -> { + StatusIcon(icon = R.drawable.ic_schedule, tint = Colors.White64) + Text( + text = stringResource(R.string.send__unknown), + style = MaterialTheme.typography.titleMedium, + textAlign = TextAlign.Center, + modifier = Modifier.testTag("WatchSendUnknown") + ) + } + } + } +} + +@Composable +private fun Failed( + failure: SendFailure, + onCloseClick: () -> Unit, + modifier: Modifier = Modifier, +) { + CenteredScreen(modifier = modifier) { + StatusIcon(icon = R.drawable.ic_close, tint = MaterialTheme.colorScheme.error) + Text( + text = stringResource(failure.text), + style = MaterialTheme.typography.titleSmall, + textAlign = TextAlign.Center, + modifier = Modifier.testTag("WatchSendError") + ) + FilledTonalIconButton( + onClick = onCloseClick, + shapes = IconButtonDefaults.animatedShapes(), + modifier = Modifier.testTag("WatchSendClose") + ) { + Icon( + painter = painterResource(R.drawable.ic_check), + contentDescription = stringResource(R.string.common__ok), + ) + } + } +} + +@Composable +private fun StatusIcon( + @DrawableRes icon: Int, + tint: Color, + modifier: Modifier = Modifier, +) { + Icon( + painter = painterResource(icon), + contentDescription = null, + tint = tint, + modifier = modifier.size(STATUS_ICON_SIZE) + ) +} + +@Composable +private fun OfflineLine(modifier: Modifier = Modifier) { + Line(text = stringResource(R.string.send__offline), modifier = modifier.testTag("WatchSendOffline")) +} + +@Composable +private fun Line( + text: String, + modifier: Modifier = Modifier, + color: Color = Colors.White64, +) { + Text( + text = text, + style = MaterialTheme.typography.bodySmall, + color = color, + textAlign = TextAlign.Center, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = modifier + ) +} + +@WearPreviewDevices +@Composable +private fun PreviewReview() { + WearPreview { + Content( + uiState = SendUiState(step = PreviewReviewStep, isWalletReady = true), + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewReviewOffline() { + WearPreview { + Content( + uiState = SendUiState(step = PreviewReviewStep, isOffline = true), + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewAmount() { + WearPreview { + Content( + uiState = SendUiState(step = SendStep.Amount(minSats = 1uL, maxSats = 100_000uL), amountText = "2100"), + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewSending() { + WearPreview { + Content( + uiState = SendUiState(step = SendStep.Sending(isWaiting = true)), + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewSent() { + WearPreview { + Content( + uiState = SendUiState(step = SendStep.Done(SendResult.Sent, PreviewBitcoin)), + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewFailed() { + WearPreview { + Content( + uiState = SendUiState(step = SendStep.Failed(SendFailure.OwnInvoice)), + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +private val PreviewBitcoin = DisplayAmount(symbol = "₿", text = "21 000") + +private val PreviewReviewStep = SendStep.Review( + amount = PreviewBitcoin, + fiat = DisplayAmount(symbol = "$", text = "20.39"), + fee = DisplayAmount(symbol = "₿", text = "250"), + payee = "Coffee", +) diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt new file mode 100644 index 0000000000..56882e7d4b --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt @@ -0,0 +1,297 @@ +package to.bitkit.wear.ui.screens.send + +import androidx.annotation.StringRes +import androidx.compose.runtime.Immutable +import androidx.lifecycle.SavedStateHandle +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import to.bitkit.wear.R +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.models.PaymentState +import to.bitkit.wear.models.PreparedSend +import to.bitkit.wear.models.SendError +import to.bitkit.wear.models.SendRequest +import to.bitkit.wear.repositories.CurrencyRepo +import to.bitkit.wear.repositories.PaymentsRepo +import to.bitkit.wear.repositories.WalletRepo +import to.bitkit.wear.repositories.WalletStatus +import to.bitkit.wear.ui.Routes +import to.bitkit.wear.ui.screens.home.DisplayAmount +import to.bitkit.wear.ui.screens.home.bitcoinAmount +import to.bitkit.wear.ui.screens.home.fiatAmount +import to.bitkit.wear.utils.Logger +import javax.inject.Inject +import kotlin.time.Duration.Companion.seconds + +/** + * The send flow for one payment input from a deeplink: it waits for the wallet, reads the input, asks for an amount + * only when the input names none, prices the send and shows it for review. The send goes out only after the hold to + * pay completes, unless [PaymentsRepo.skipConfirmation] says otherwise, and the result closes the flow by itself. + */ +@HiltViewModel +class SendViewModel @Inject constructor( + savedStateHandle: SavedStateHandle, + private val paymentsRepo: PaymentsRepo, + private val walletRepo: WalletRepo, + private val currencyRepo: CurrencyRepo, + private val settingsStore: SettingsStore, +) : ViewModel() { + companion object { + private const val TAG = "SendViewModel" + + /** How long a send runs before the screen says it is waiting for the network. */ + val WAITING_HINT_DELAY = 3.seconds + + /** How long the sent check shows before the flow closes. */ + val SENT_CLOSE_DELAY = 2.seconds + + /** How long a pending or unknown outcome shows before the flow closes. */ + val PENDING_CLOSE_DELAY = 3.seconds + + /** The fee shows on review only from this share of the amount, in percent; a smaller fee needs no line. */ + const val FEE_SHOWN_PERCENT = 1uL + + /** The longest amount the wearer can type, in digits: more than every bitcoin there will be, in sats. */ + const val MAX_AMOUNT_DIGITS = 16 + } + + private val input: String = savedStateHandle.get(Routes.SEND_INPUT).orEmpty() + + private val _uiState = MutableStateFlow(SendUiState()) + val uiState: StateFlow = _uiState.asStateFlow() + + private val _effects = Channel(Channel.BUFFERED) + val effects: Flow = _effects.receiveAsFlow() + + private var request: SendRequest? = null + private var prepared: PreparedSend? = null + + init { + viewModelScope.launch { + walletRepo.walletState.collect { wallet -> + _uiState.update { + it.copy( + isWalletReady = wallet.status == WalletStatus.Ready, + isOffline = wallet.status == WalletStatus.Offline, + ) + } + } + } + viewModelScope.launch { start() } + } + + fun onAmountChange(text: String) { + val digits = text.filter { it.isDigit() }.take(MAX_AMOUNT_DIGITS) + _uiState.update { state -> + val step = state.step as? SendStep.Amount ?: return@update state + state.copy(amountText = digits, step = step.copy(isOutOfRange = false)) + } + } + + fun onAmountConfirm() { + val step = _uiState.value.step as? SendStep.Amount ?: return + val request = request ?: return + val amount = _uiState.value.amountText.toULongOrNull() + if (amount == null || amount == 0uL || !step.contains(amount)) { + _uiState.update { it.copy(step = step.copy(isOutOfRange = true)) } + return + } + viewModelScope.launch { prepare(request, amount) } + } + + /** Sends the reviewed payment once the hold to pay completes, while the wallet is ready. */ + fun onHoldComplete() { + val prepared = prepared ?: return + val state = _uiState.value + if (state.step !is SendStep.Review || !state.isWalletReady) return + send(prepared) + } + + /** Closes the flow from a failure's one action. */ + fun onCloseClick() { + _effects.trySend(SendEffect.Close) + } + + private suspend fun start() { + _uiState.update { it.copy(step = SendStep.Loading) } + walletRepo.walletState.first { it.status == WalletStatus.Ready } + val parsed = paymentsRepo.parse(input).getOrElse { + fail(it) + return + } + request = parsed + if (parsed.fixedAmountSats == null) { + _uiState.update { it.copy(step = amountStep(parsed)) } + return + } + prepare(parsed, amountSats = null) + } + + private suspend fun prepare(request: SendRequest, amountSats: ULong?) { + _uiState.update { it.copy(step = SendStep.Loading) } + val result = paymentsRepo.prepare(request, amountSats).getOrElse { + if (it is SendError.AmountOutOfRange && request.fixedAmountSats == null) { + _uiState.update { state -> state.copy(step = amountStep(request).copy(isOutOfRange = true)) } + } else { + fail(it) + } + return + } + prepared = result + if (paymentsRepo.skipConfirmation(result)) { + send(result) + return + } + _uiState.update { it.copy(step = review(result, request)) } + } + + private suspend fun review(prepared: PreparedSend, request: SendRequest): SendStep.Review { + val currency = settingsStore.data.first().selectedCurrency + val amount = prepared.amountSats.toLong() + val isFeeShown = prepared.feeSats > 0uL && prepared.feeSats * 100uL >= prepared.amountSats * FEE_SHOWN_PERCENT + return SendStep.Review( + amount = bitcoinAmount(amount), + fiat = fiatAmount(amount, currencyRepo.rates.value, currency), + fee = if (isFeeShown) bitcoinAmount(prepared.feeSats.toLong()) else null, + payee = (prepared.payee ?: request.payee)?.takeIf { it.isNotBlank() }, + ) + } + + private fun send(prepared: PreparedSend) { + _uiState.update { it.copy(step = SendStep.Sending()) } + viewModelScope.launch { + val hint = launch { + delay(WAITING_HINT_DELAY) + _uiState.update { state -> + val step = state.step as? SendStep.Sending ?: return@update state + state.copy(step = step.copy(isWaiting = true)) + } + } + val result = paymentsRepo.send(prepared) + hint.cancel() + val outcome = result.fold( + onSuccess = { + when (it.state) { + PaymentState.Completed -> SendResult.Sent + PaymentState.Pending -> SendResult.Pending + PaymentState.Failed -> null + } + }, + onFailure = { if (it is SendError.Unknown) SendResult.Unknown else null }, + ) + if (outcome == null) { + fail(result.exceptionOrNull()) + return@launch + } + Logger.info("Finished send with outcome '$outcome'", context = TAG) + val amount = bitcoinAmount(prepared.amountSats.toLong()) + _uiState.update { it.copy(step = SendStep.Done(outcome, amount)) } + delay(if (outcome == SendResult.Sent) SENT_CLOSE_DELAY else PENDING_CLOSE_DELAY) + _effects.send(SendEffect.Close) + } + } + + private fun fail(error: Throwable?) { + _uiState.update { it.copy(step = SendStep.Failed(SendFailure.of(error))) } + } + + private fun amountStep(request: SendRequest): SendStep.Amount = when (request) { + is SendRequest.Lnurl -> SendStep.Amount(minSats = request.minSats, maxSats = request.maxSats) + else -> SendStep.Amount() + } +} + +/** What the send screen shows. */ +sealed interface SendStep { + /** Waiting for the wallet, reading the input or pricing the send. */ + data object Loading : SendStep + + /** The wearer types the amount of an input that names none, within [minSats] to [maxSats] when known. */ + data class Amount( + val minSats: ULong? = null, + val maxSats: ULong? = null, + val isOutOfRange: Boolean = false, + ) : SendStep { + fun contains(amountSats: ULong): Boolean = + (minSats == null || amountSats >= minSats) && (maxSats == null || amountSats <= maxSats) + } + + /** The priced send with the hold to pay. [fee] is set only when it is worth showing. */ + data class Review( + val amount: DisplayAmount, + val fiat: DisplayAmount?, + val fee: DisplayAmount?, + val payee: String?, + ) : SendStep + + /** The send is under way; [isWaiting] once it took longer than a moment. */ + data class Sending(val isWaiting: Boolean = false) : SendStep + + /** The send went out: sent, pending, or with an outcome not known yet. */ + data class Done(val result: SendResult, val amount: DisplayAmount) : SendStep + + /** Nothing was sent, for [failure]. */ + data class Failed(val failure: SendFailure) : SendStep +} + +enum class SendResult { Sent, Pending, Unknown } + +/** Why nothing was sent, with its one-line copy. */ +enum class SendFailure(@StringRes val text: Int) { + NotReady(R.string.send__error_not_ready), + Invalid(R.string.send__error_invalid), + Unsupported(R.string.send__error_unsupported), + Expired(R.string.send__error_expired), + OwnInvoice(R.string.send__error_own_invoice), + OutOfRange(R.string.send__error_out_of_range), + Insufficient(R.string.send__error_insufficient), + AlreadyPaid(R.string.send__error_already_paid), + InFlight(R.string.send__error_in_flight), + Failed(R.string.send__error_failed), + ; + + companion object { + fun of(error: Throwable?): SendFailure = when (error) { + is SendError.NotReady -> NotReady + is SendError.Invalid -> Invalid + is SendError.Unsupported -> Unsupported + is SendError.Expired -> Expired + is SendError.OwnInvoice -> OwnInvoice + is SendError.AmountOutOfRange -> OutOfRange + is SendError.InsufficientBalance -> Insufficient + is SendError.AlreadyPaid -> AlreadyPaid + is SendError.InFlight -> InFlight + else -> Failed + } + } +} + +sealed interface SendEffect { + /** The flow is over: back to the screen the deeplink found. */ + data object Close : SendEffect +} + +@Immutable +data class SendUiState( + val step: SendStep = SendStep.Loading, + val amountText: String = "", + val isWalletReady: Boolean = false, + val isOffline: Boolean = false, +) { + /** Whether the hold to pay can start: only on review with the wallet ready. */ + val isHoldEnabled: Boolean get() = step is SendStep.Review && isWalletReady + + /** Whether the flow must not be left by a swipe, since a send is under way. */ + val isBusy: Boolean get() = step is SendStep.Sending +} diff --git a/wear/src/main/res/values-ar/strings.xml b/wear/src/main/res/values-ar/strings.xml index d77908a7e0..4566148638 100644 --- a/wear/src/main/res/values-ar/strings.xml +++ b/wear/src/main/res/values-ar/strings.xml @@ -1,6 +1,13 @@ حول + لا يوجد نشاط + تم الاستلام + تم الإرسال + مكتمل + فشل + معلق + النشاط التالي حسنًا إعادة المحاولة @@ -11,6 +18,11 @@ غير متصل تبديل الوحدة استعادة + تعذّر إنشاء الفاتورة + رمز QR مخفي + فاتورة جديدة + مدفوع + استلام تمت إزالة المحفظة مراجعة عبارة غير صالحة @@ -34,6 +46,26 @@ لا تطابق الكلمة %1$d %1$d/%2$d + متابعة + المبلغ + %1$s – %2$s + مدفوعة مسبقًا + انتهت صلاحية الفاتورة + فشل الدفع + الدفع معلق + رصيد غير كافٍ + فاتورة غير صالحة + المحفظة غير جاهزة + خارج النطاق + لا يمكن دفع فاتورتك + غير مدعوم + الرسوم %1$s + اضغط مطولًا للدفع + غير متصل + معلق + تم الإرسال + تحقق من النشاط + في انتظار الشبكة إزالة المحفظة إزالة المحفظة؟ تعذّرت إزالة المحفظة diff --git a/wear/src/main/res/values-b+es+419/strings.xml b/wear/src/main/res/values-b+es+419/strings.xml index 4e53c73b69..8a82550475 100644 --- a/wear/src/main/res/values-b+es+419/strings.xml +++ b/wear/src/main/res/values-b+es+419/strings.xml @@ -1,6 +1,13 @@ Acerca de + Sin actividad + Recibido + Enviado + Completado + Fallido + Pendiente + Actividad Siguiente OK Re-intentar @@ -11,6 +18,11 @@ Sin conexión Cambiar unidad Restaurar + No se creó la factura + QR oculto + Nueva factura + Pagado + Recibir Billetera eliminada Revisar Frase no válida @@ -31,6 +43,26 @@ Sin coincidencias Palabra %1$d %1$d/%2$d + Continuar + Monto + %1$s – %2$s + Ya pagada + Factura vencida + Pago fallido + Pago pendiente + Fondos insuficientes + Factura no válida + Wallet no lista + Fuera de rango + Es su propia factura + No compatible + Comisión %1$s + Mantén para pagar + Sin conexión + Pendiente + Enviado + Revisa la actividad + Esperando la red Eliminar billetera ¿Eliminar billetera? No se pudo eliminar la billetera diff --git a/wear/src/main/res/values-ca/strings.xml b/wear/src/main/res/values-ca/strings.xml index 3e58d95e8f..33e56949d7 100644 --- a/wear/src/main/res/values-ca/strings.xml +++ b/wear/src/main/res/values-ca/strings.xml @@ -1,6 +1,13 @@ Quant a + Sense activitat + Rebut + Enviat + Completat + Ha fallat + Pendent + Activitat Següent OK Reintentar @@ -11,6 +18,11 @@ Sense connexió Canvia la unitat Restaurar + No s\'ha creat la factura + QR amagat + Nova factura + Pagat + Rebre Cartera eliminada Revisa Frase no vàlida @@ -31,6 +43,26 @@ Cap coincidència Paraula %1$d %1$d/%2$d + Continua + Import + %1$s – %2$s + Ja pagada + Factura caducada + El pagament ha fallat + Pagament pendent + Fons insuficients + Factura no vàlida + Wallet no a punt + Fora de rang + És la teva factura + No compatible + Comissió %1$s + Mantén per pagar + Sense connexió + Pendent + Enviat + Revisa l\'activitat + Esperant la xarxa Elimina la cartera Eliminar la cartera? No s\'ha pogut eliminar la cartera diff --git a/wear/src/main/res/values-cs/strings.xml b/wear/src/main/res/values-cs/strings.xml index efbb98c777..d98e3b0348 100644 --- a/wear/src/main/res/values-cs/strings.xml +++ b/wear/src/main/res/values-cs/strings.xml @@ -1,6 +1,13 @@ O aplikaci + Žádná aktivita + Přijato + Odesláno + Dokončeno + Selhání + Zpracovávání + Aktivita Další OK Opakovat @@ -11,6 +18,11 @@ Offline Přepnout jednotku Obnovit + Fakturu nelze vytvořit + QR skryt + Nová faktura + Zaplaceno + Přijmout Peněženka odebrána Zkontrolovat Neplatná fráze @@ -32,6 +44,26 @@ Žádná shoda Slovo %1$d %1$d/%2$d + Pokračovat + Částka + %1$s – %2$s + Již zaplaceno + Faktura vypršela + Platba selhala + Platba se zpracovává + Nedostatek prostředků + Neplatná faktura + Peněženka není připravena + Mimo rozsah + Vlastní fakturu nelze zaplatit + Nepodporováno + Poplatek %1$s + Podržte pro platbu + Offline + Zpracovávání + Odesláno + Zkontrolujte aktivitu + Čekání na síť Odebrat peněženku Odebrat peněženku? Peněženku nelze odebrat diff --git a/wear/src/main/res/values-de/strings.xml b/wear/src/main/res/values-de/strings.xml index 7d67c14a89..23cec9c0cb 100644 --- a/wear/src/main/res/values-de/strings.xml +++ b/wear/src/main/res/values-de/strings.xml @@ -1,6 +1,13 @@ Über + Keine Aktivität + Empfangen + Gesendet + Abgeschlossen + Fehlgeschlagen + Ausstehend + Aktivität Weiter OK Wiederholen @@ -11,6 +18,11 @@ Offline Einheit wechseln Wiederherstellen + Rechnung nicht erstellt + QR versteckt + Neue Rechnung + Bezahlt + Empfangen Wallet entfernt Prüfen Ungültige Phrase @@ -30,6 +42,26 @@ Kein Treffer Wort %1$d %1$d/%2$d + Weiter + Betrag + %1$s – %2$s + Bereits bezahlt + Rechnung abgelaufen + Zahlung fehlgeschlagen + Zahlung ausstehend + Nicht genug Guthaben + Ungültige Rechnung + Wallet nicht bereit + Außerhalb des Bereichs + Eigene Rechnung nicht bezahlbar + Nicht unterstützt + Gebühr %1$s + Halten zum Bezahlen + Offline + Ausstehend + Gesendet + Aktivität prüfen + Warte auf Netzwerk Wallet entfernen Wallet entfernen? Wallet konnte nicht entfernt werden diff --git a/wear/src/main/res/values-el/strings.xml b/wear/src/main/res/values-el/strings.xml index 9fc49df17c..7d371e62dd 100644 --- a/wear/src/main/res/values-el/strings.xml +++ b/wear/src/main/res/values-el/strings.xml @@ -1,6 +1,13 @@ Σχετικά + Καμία δραστηριότητα + Ελήφθη + Στάλθηκε + Ολοκληρώθηκε + Απέτυχε + Εκκρεμεί + Δραστηριότητα Επόμενο ΟΚ Δοκιμάστε Ξανά @@ -11,6 +18,11 @@ Εκτός σύνδεσης Αλλαγή μονάδας Επαναφορά + Αποτυχία τιμολογίου + QR κρυφό + Νέο τιμολόγιο + Πληρώθηκε + Λήψη Το πορτοφόλι αφαιρέθηκε Έλεγχος Μη έγκυρη φράση @@ -30,6 +42,26 @@ Καμία αντιστοιχία Λέξη %1$d %1$d/%2$d + Συνέχεια + Ποσό + %1$s – %2$s + Ήδη πληρωμένο + Το τιμολόγιο έληξε + Η πληρωμή απέτυχε + Πληρωμή σε εκκρεμότητα + Ανεπαρκές υπόλοιπο + Μη έγκυρο τιμολόγιο + Το πορτοφόλι δεν είναι έτοιμο + Εκτός ορίων + Δικό σου τιμολόγιο + Δεν υποστηρίζεται + Χρέωση %1$s + Κράτα για πληρωμή + Εκτός σύνδεσης + Εκκρεμεί + Στάλθηκε + Δες τη δραστηριότητα + Αναμονή για δίκτυο Αφαίρεση πορτοφολιού Αφαίρεση πορτοφολιού; Αδυναμία αφαίρεσης πορτοφολιού diff --git a/wear/src/main/res/values-es-rES/strings.xml b/wear/src/main/res/values-es-rES/strings.xml index e643f9068e..e8c1c44a2e 100644 --- a/wear/src/main/res/values-es-rES/strings.xml +++ b/wear/src/main/res/values-es-rES/strings.xml @@ -1,6 +1,13 @@ Acerca de + Sin actividad + Recibido + Enviado + Completado + Fallido + Pendiente + Actividad Siguiente OK Vuelva a intentarlo @@ -11,6 +18,11 @@ Sin conexión Cambiar unidad Restaurar + No se creó la factura + QR oculto + Nueva factura + Pagado + Recibir Cartera eliminada Revisar Frase no válida @@ -31,6 +43,26 @@ Sin coincidencias Palabra %1$d %1$d/%2$d + Continuar + Importe + %1$s – %2$s + Ya pagada + Factura caducada + Pago fallido + Pago pendiente + Fondos insuficientes + Factura no válida + Wallet no lista + Fuera de rango + Es tu propia factura + No compatible + Comisión %1$s + Mantén para pagar + Sin conexión + Pendiente + Enviado + Revisa la actividad + Esperando a la red Eliminar cartera ¿Eliminar cartera? No se pudo eliminar la cartera diff --git a/wear/src/main/res/values-es/strings.xml b/wear/src/main/res/values-es/strings.xml index e643f9068e..e8c1c44a2e 100644 --- a/wear/src/main/res/values-es/strings.xml +++ b/wear/src/main/res/values-es/strings.xml @@ -1,6 +1,13 @@ Acerca de + Sin actividad + Recibido + Enviado + Completado + Fallido + Pendiente + Actividad Siguiente OK Vuelva a intentarlo @@ -11,6 +18,11 @@ Sin conexión Cambiar unidad Restaurar + No se creó la factura + QR oculto + Nueva factura + Pagado + Recibir Cartera eliminada Revisar Frase no válida @@ -31,6 +43,26 @@ Sin coincidencias Palabra %1$d %1$d/%2$d + Continuar + Importe + %1$s – %2$s + Ya pagada + Factura caducada + Pago fallido + Pago pendiente + Fondos insuficientes + Factura no válida + Wallet no lista + Fuera de rango + Es tu propia factura + No compatible + Comisión %1$s + Mantén para pagar + Sin conexión + Pendiente + Enviado + Revisa la actividad + Esperando a la red Eliminar cartera ¿Eliminar cartera? No se pudo eliminar la cartera diff --git a/wear/src/main/res/values-fr/strings.xml b/wear/src/main/res/values-fr/strings.xml index ac0f85915c..f8ae296319 100644 --- a/wear/src/main/res/values-fr/strings.xml +++ b/wear/src/main/res/values-fr/strings.xml @@ -1,6 +1,13 @@ À propos + Aucune activité + Reçu + Envoyé + Terminé + Échec + En attente + Activité Suivant OK Réessayer @@ -11,6 +18,11 @@ Hors ligne Changer d\'unité Restaurer + Facture non créée + QR masqué + Nouvelle facture + Payé + Recevoir Wallet supprimé Vérifier Phrase invalide @@ -31,6 +43,26 @@ Aucune correspondance Mot %1$d %1$d/%2$d + Continuer + Montant + %1$s – %2$s + Déjà payée + Facture expirée + Échec du paiement + Paiement en attente + Fonds insuffisants + Facture invalide + Wallet pas prêt + Hors limites + Votre propre facture + Non pris en charge + Frais %1$s + Maintenir pour payer + Hors ligne + En attente + Envoyé + Voir l\'activité + En attente du réseau Supprimer le wallet Supprimer le wallet ? Impossible de supprimer le wallet diff --git a/wear/src/main/res/values-it/strings.xml b/wear/src/main/res/values-it/strings.xml index ac1448fff0..a00cc50b29 100644 --- a/wear/src/main/res/values-it/strings.xml +++ b/wear/src/main/res/values-it/strings.xml @@ -1,6 +1,13 @@ Informazioni + Nessuna attività + Ricevuto + Inviato + Completato + Fallito + In sospeso + Attività Avanti OK Riprova @@ -11,6 +18,11 @@ Offline Cambia unità Ripristina + Fattura non creata + QR nascosto + Nuova fattura + Pagato + Ricevi Portafoglio rimosso Rivedi Frase non valida @@ -31,6 +43,26 @@ Nessuna corrispondenza Parola %1$d %1$d/%2$d + Continua + Importo + %1$s – %2$s + Già pagata + Fattura scaduta + Pagamento fallito + Pagamento in sospeso + Fondi insufficienti + Fattura non valida + Wallet non pronto + Fuori intervallo + È la tua fattura + Non supportato + Commissione %1$s + Tieni premuto per pagare + Offline + In sospeso + Inviato + Controlla l\'attività + In attesa della rete Rimuovi portafoglio Rimuovere il portafoglio? Impossibile rimuovere il portafoglio diff --git a/wear/src/main/res/values-nl/strings.xml b/wear/src/main/res/values-nl/strings.xml index 75263df1a7..592ad14625 100644 --- a/wear/src/main/res/values-nl/strings.xml +++ b/wear/src/main/res/values-nl/strings.xml @@ -1,6 +1,13 @@ Over + Geen activiteit + Ontvangen + Verzonden + Voltooid + Mislukt + In behandeling + Activiteit Volgende OK Opnieuw proberen @@ -11,6 +18,11 @@ Offline Eenheid wisselen Herstellen + Factuur niet gemaakt + QR verborgen + Nieuwe factuur + Betaald + Ontvangen Wallet verwijderd Controleren Ongeldige zin @@ -30,6 +42,26 @@ Geen overeenkomst Woord %1$d %1$d/%2$d + Doorgaan + Bedrag + %1$s – %2$s + Al betaald + Factuur verlopen + Betaling mislukt + Betaling in behandeling + Onvoldoende saldo + Ongeldige factuur + Wallet niet gereed + Buiten bereik + Eigen factuur + Niet ondersteund + Kosten %1$s + Houd vast om te betalen + Offline + In behandeling + Verzonden + Bekijk activiteit + Wachten op netwerk Wallet verwijderen Wallet verwijderen? Wallet verwijderen mislukt diff --git a/wear/src/main/res/values-pl/strings.xml b/wear/src/main/res/values-pl/strings.xml index 33f8c03095..157b5bd3c4 100644 --- a/wear/src/main/res/values-pl/strings.xml +++ b/wear/src/main/res/values-pl/strings.xml @@ -1,6 +1,13 @@ O aplikacji + Brak aktywności + Otrzymano + Wysłano + Zakończono + Niepowodzenie + Oczekuje + Aktywność Dalej OK Spróbuj ponownie @@ -11,6 +18,11 @@ Offline Zmień jednostkę Odzyskaj + Nie utworzono faktury + QR ukryty + Nowa faktura + Opłacono + Odbierz Portfel usunięty Sprawdź Nieprawidłowa fraza @@ -32,6 +44,26 @@ Brak dopasowań Słowo %1$d %1$d/%2$d + Dalej + Kwota + %1$s – %2$s + Już opłacona + Faktura wygasła + Płatność nieudana + Płatność oczekuje + Za mało środków + Nieprawidłowa faktura + Portfel nie jest gotowy + Poza zakresem + Własna faktura + Nieobsługiwane + Opłata %1$s + Przytrzymaj, aby zapłacić + Offline + Oczekuje + Wysłano + Sprawdź aktywność + Czekam na sieć Usuń portfel Usunąć portfel? Nie udało się usunąć portfela diff --git a/wear/src/main/res/values-pt-rBR/strings.xml b/wear/src/main/res/values-pt-rBR/strings.xml index 2674519abd..b29d1ea097 100644 --- a/wear/src/main/res/values-pt-rBR/strings.xml +++ b/wear/src/main/res/values-pt-rBR/strings.xml @@ -1,6 +1,13 @@ Sobre + Sem atividade + Recebido + Enviado + Concluído + Falha + Pendente + Atividade Próximo OK Tentar novamente @@ -11,6 +18,11 @@ Sem conexão Alternar unidade Restaurar + Invoice não criado + QR oculto + Novo invoice + Pago + Receber Carteira removida Revisar Frase inválida @@ -31,6 +43,26 @@ Nenhuma correspondência Palavra %1$d %1$d/%2$d + Continuar + Valor + %1$s – %2$s + Já pago + Invoice expirado + Pagamento falhou + Pagamento pendente + Saldo insuficiente + Invoice inválido + Carteira não pronta + Fora do limite + É seu próprio invoice + Não suportado + Taxa %1$s + Segure para pagar + Offline + Pendente + Enviado + Veja a atividade + Aguardando a rede Remover carteira Remover carteira? Não foi possível remover a carteira diff --git a/wear/src/main/res/values-pt/strings.xml b/wear/src/main/res/values-pt/strings.xml index df275d8a12..06d7a34100 100644 --- a/wear/src/main/res/values-pt/strings.xml +++ b/wear/src/main/res/values-pt/strings.xml @@ -1,6 +1,13 @@ Sobre + Sem atividade + Recebido + Enviado + Concluído + Falha + Pendente + Atividade Próximo OK Tentar novamente @@ -11,6 +18,11 @@ Sem ligação Alternar unidade Restaurar + Fatura não criada + QR oculto + Nova fatura + Pago + Receber Carteira removida Revisar Frase inválida @@ -31,6 +43,26 @@ Nenhuma correspondência Palavra %1$d %1$d/%2$d + Continuar + Montante + %1$s – %2$s + Já paga + Fatura expirada + Pagamento falhou + Pagamento pendente + Saldo insuficiente + Fatura inválida + Carteira não pronta + Fora do intervalo + É a sua fatura + Não suportado + Taxa %1$s + Mantenha para pagar + Offline + Pendente + Enviado + Veja a atividade + À espera da rede Remover carteira Remover carteira? Não foi possível remover a carteira diff --git a/wear/src/main/res/values-ru/strings.xml b/wear/src/main/res/values-ru/strings.xml index b1a4412ac6..f64f5ed7b5 100644 --- a/wear/src/main/res/values-ru/strings.xml +++ b/wear/src/main/res/values-ru/strings.xml @@ -1,6 +1,13 @@ О приложении + Нет активности + Получено + Отправлено + Завершено + Ошибка + В ожидании + Активность Далее ОК Повторить @@ -11,6 +18,11 @@ Нет сети Сменить единицу Восстановить + Счёт не создан + QR скрыт + Новый счёт + Оплачено + Получить Кошелёк удалён Проверить Неверная фраза @@ -32,6 +44,26 @@ Нет совпадений Слово %1$d %1$d/%2$d + Далее + Сумма + %1$s – %2$s + Уже оплачен + Счёт истёк + Платёж не прошёл + Платёж в ожидании + Недостаточно средств + Неверный счёт + Кошелёк не готов + Вне диапазона + Это ваш счёт + Не поддерживается + Комиссия %1$s + Удерживайте для оплаты + Офлайн + В ожидании + Отправлено + Проверьте активность + Ожидание сети Удалить кошелёк Удалить кошелёк? Не удалось удалить кошелёк diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index ca2ea84874..6e8e41b664 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -1,6 +1,13 @@ About + No activity + Received + Sent + Completed + Failed + Pending + Activity Next OK Retry @@ -11,6 +18,11 @@ Offline Switch unit Restore + Couldn\'t create invoice + QR hidden + New invoice + Paid + Receive Wallet removed Review Invalid phrase @@ -30,6 +42,26 @@ No match Word %1$d %1$d/%2$d + Continue + Amount + %1$s – %2$s + Already paid + Invoice expired + Payment failed + Payment pending + Not enough funds + Invalid invoice + Wallet not ready + Out of range + Can\'t pay own invoice + Not supported + Fee %1$s + Hold to pay + Offline + Pending + Sent + Check activity + Waiting for network Remove wallet Remove wallet? Couldn\'t remove wallet diff --git a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt new file mode 100644 index 0000000000..0d54aad884 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt @@ -0,0 +1,31 @@ +package to.bitkit.wear.ui + +import android.content.Intent +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class LaunchRequestTest { + @Test + fun `a payment link asks for a send of the whole link`() { + for (link in listOf("lightning:lnbcrt1abc", "BITCOIN:bcrt1q?lightning=lnbcrt1abc", "spark:sprt1abc")) { + assertEquals(LaunchRequest.Send(link), LaunchRequest.from(Intent.ACTION_VIEW, link, open = null)) + } + } + + @Test + fun `the tile's extra asks for the receive QR`() { + assertEquals( + LaunchRequest.Receive, + LaunchRequest.from(Intent.ACTION_MAIN, data = null, open = LaunchRequest.OPEN_RECEIVE), + ) + } + + @Test + fun `a plain launch or another link asks for nothing`() { + assertNull(LaunchRequest.from(Intent.ACTION_MAIN, data = null, open = null)) + assertNull(LaunchRequest.from(Intent.ACTION_VIEW, data = "https://bitkit.to", open = null)) + assertNull(LaunchRequest.from(Intent.ACTION_VIEW, data = "lnbcrt1abc", open = null)) + assertNull(LaunchRequest.from(Intent.ACTION_SEND, data = "lightning:lnbcrt1abc", open = null)) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt new file mode 100644 index 0000000000..07137e4e35 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt @@ -0,0 +1,104 @@ +package to.bitkit.wear.ui.screens.activity + +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update +import org.junit.Before +import org.junit.Test +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.wear.models.PaymentState +import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.repositories.PaymentsRepo +import to.bitkit.wear.repositories.WalletRepo +import to.bitkit.wear.repositories.WalletState +import to.bitkit.wear.repositories.WalletStatus +import to.bitkit.wear.services.SparkError +import to.bitkit.wear.test.BaseUnitTest +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ActivityViewModelTest : BaseUnitTest() { + private val paymentsRepo = mock() + private val walletRepo = mock() + private val walletState = MutableStateFlow(WalletState(WalletStatus.Connecting)) + private val paymentChanges = MutableSharedFlow() + + @Before + fun setUp() { + whenever(walletRepo.walletState).thenReturn(walletState) + whenever(paymentsRepo.paymentChanges).thenReturn(paymentChanges) + } + + private fun createSut() = ActivityViewModel(paymentsRepo, walletRepo) { NOW } + + @Test + fun `the list is read once spark is connected`() = test { + whenever(paymentsRepo.recentPayments()).thenReturn(Result.success(listOf(payment("a")))) + val sut = createSut() + + verify(paymentsRepo, never()).recentPayments() + assertFalse(sut.uiState.value.isLoaded) + + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertTrue(sut.uiState.value.isLoaded) + assertEquals(listOf(payment("a")), sut.uiState.value.payments) + assertEquals(NOW, sut.uiState.value.nowSecs) + } + + @Test + fun `a payment or a sync reads the list again`() = test { + walletState.update { it.copy(status = WalletStatus.Ready) } + whenever(paymentsRepo.recentPayments()).thenReturn(Result.success(listOf(payment("a")))) + val sut = createSut() + whenever(paymentsRepo.recentPayments()).thenReturn(Result.success(listOf(payment("b"), payment("a")))) + + paymentChanges.emit(Unit) + + verify(paymentsRepo, times(2)).recentPayments() + assertEquals(listOf("b", "a"), sut.uiState.value.payments.map { it.id }) + assertEquals(payment("b"), sut.uiState.value.payment("b")) + } + + @Test + fun `the last list stays when spark cannot be read`() = test { + walletState.update { it.copy(status = WalletStatus.Ready) } + whenever(paymentsRepo.recentPayments()).thenReturn(Result.success(listOf(payment("a")))) + val sut = createSut() + whenever(paymentsRepo.recentPayments()).thenReturn(Result.failure(SparkError.NotConnected())) + + walletState.update { it.copy(status = WalletStatus.Paused) } + paymentChanges.emit(Unit) + + assertEquals(listOf(payment("a")), sut.uiState.value.payments) + } + + @Test + fun `an empty wallet loads an empty list`() = test { + walletState.update { it.copy(status = WalletStatus.Offline) } + whenever(paymentsRepo.recentPayments()).thenReturn(Result.success(emptyList())) + + val sut = createSut() + + assertTrue(sut.uiState.value.isLoaded) + assertTrue(sut.uiState.value.payments.isEmpty()) + } + + private fun payment(id: String) = WatchPayment( + id = id, + isSent = true, + amountSats = 1_000uL, + feeSats = 1uL, + timestampSecs = 1_700_000_000uL, + state = PaymentState.Completed, + ) + + private companion object { + const val NOW = 1_800_000_000L + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt new file mode 100644 index 0000000000..82e5eab92e --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt @@ -0,0 +1,139 @@ +package to.bitkit.wear.ui.screens.receive + +import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doSuspendableAnswer +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.wear.models.PaymentState +import to.bitkit.wear.models.ReceiveError +import to.bitkit.wear.models.ReceiveInvoice +import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.repositories.PaymentsRepo +import to.bitkit.wear.repositories.WalletRepo +import to.bitkit.wear.repositories.WalletState +import to.bitkit.wear.repositories.WalletStatus +import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wear.ui.screens.home.DisplayAmount +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.seconds + +class ReceiveViewModelTest : BaseUnitTest() { + private val paymentsRepo = mock() + private val walletRepo = mock() + private val walletState = MutableStateFlow(WalletState(WalletStatus.Ready, 0uL, hasSynced = true)) + + @Before + fun setUp() { + whenever(walletRepo.walletState).thenReturn(walletState) + } + + private val created = mutableListOf() + + private fun createSut() = ReceiveViewModel(paymentsRepo, walletRepo) { NOW }.also { created += it } + + /** An unpaid invoice is replaced forever, so the view models stop before the test drains its scheduler. */ + override fun onTestEnd() = created.forEach { it.viewModelScope.cancel() } + + @Test + fun `shows the uppercased invoice once the wallet is ready`() = test { + walletState.update { it.copy(status = WalletStatus.Connecting) } + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + + val sut = createSut() + + assertTrue(sut.uiState.value.isLoading) + verify(paymentsRepo, never()).createInvoice() + + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + assertFalse(sut.uiState.value.isLoading) + } + + @Test + fun `a paid invoice turns into the check with its amount`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).thenReturn(payment(21_000uL)) + + val sut = createSut() + + assertNull(sut.uiState.value.qrContent) + assertEquals(DisplayAmount("₿", "21 000"), sut.uiState.value.paidAmount) + } + + @Test + fun `a new invoice replaces the paid one on refresh`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).thenReturn(payment(21_000uL)) + val sut = createSut() + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + + sut.onRefreshClick() + + assertNull(sut.uiState.value.paidAmount) + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + verify(paymentsRepo, times(2)).createInvoice() + } + + @Test + fun `an invoice is replaced shortly before it expires`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + createSut() + verify(paymentsRepo, times(1)).createInvoice() + + testScheduler.advanceTimeBy(LIFETIME.seconds - ReceiveViewModel.EXPIRY_MARGIN - 1.seconds) + verify(paymentsRepo, times(1)).createInvoice() + + testScheduler.advanceTimeBy(2.seconds) + verify(paymentsRepo, times(2)).createInvoice() + } + + @Test + fun `a failed invoice shows the error until retried`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.failure(ReceiveError.NotReady())) + val sut = createSut() + + assertTrue(sut.uiState.value.isError) + assertNull(sut.uiState.value.qrContent) + + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + sut.onRefreshClick() + + assertFalse(sut.uiState.value.isError) + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + } + + private fun invoice() = ReceiveInvoice(BOLT11, PAYMENT_HASH, (NOW + LIFETIME).toULong()) + + private fun payment(amountSats: ULong) = WatchPayment( + id = "receipt", + isSent = false, + amountSats = amountSats, + feeSats = 0uL, + timestampSecs = NOW.toULong(), + state = PaymentState.Completed, + ) + + private companion object { + const val BOLT11 = "lnbcrt1invoice" + const val PAYMENT_HASH = "ab12" + const val NOW = 1_800_000_000L + const val LIFETIME = 3_600L + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt new file mode 100644 index 0000000000..6efc171996 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt @@ -0,0 +1,307 @@ +package to.bitkit.wear.ui.screens.send + +import androidx.lifecycle.SavedStateHandle +import app.cash.turbine.test +import breez_sdk_spark.PrepareSendPaymentResponse +import com.synonym.bitkitcore.LnurlPayData +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.update +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.data.WatchSettings +import to.bitkit.wear.models.FxRate +import to.bitkit.wear.models.PaymentState +import to.bitkit.wear.models.PreparedSend +import to.bitkit.wear.models.SendError +import to.bitkit.wear.models.SendRequest +import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.repositories.CurrencyRepo +import to.bitkit.wear.repositories.PaymentsRepo +import to.bitkit.wear.repositories.WalletRepo +import to.bitkit.wear.repositories.WalletState +import to.bitkit.wear.repositories.WalletStatus +import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wear.ui.Routes +import to.bitkit.wear.ui.screens.home.DisplayAmount +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.seconds + +class SendViewModelTest : BaseUnitTest() { + private val paymentsRepo = mock() + private val walletRepo = mock() + private val currencyRepo = mock() + private val settingsStore = mock() + private val walletState = MutableStateFlow(WalletState(WalletStatus.Ready, 100_000uL, hasSynced = true)) + + @Before + fun setUp() { + whenever(walletRepo.walletState).thenReturn(walletState) + whenever(currencyRepo.rates).thenReturn(MutableStateFlow(emptyList())) + whenever(settingsStore.data).thenReturn(flowOf(WatchSettings())) + } + + private fun createSut() = SendViewModel( + SavedStateHandle(mapOf(Routes.SEND_INPUT to INPUT)), + paymentsRepo, + walletRepo, + currencyRepo, + settingsStore, + ) + + @Test + fun `the input is read only once the wallet is ready`() = test { + walletState.update { it.copy(status = WalletStatus.Connecting) } + stubInvoice(prepared()) + + val sut = createSut() + + assertEquals(SendStep.Loading, sut.uiState.value.step) + verify(paymentsRepo, never()).parse(any()) + + walletState.update { it.copy(status = WalletStatus.Ready) } + + verify(paymentsRepo).parse(INPUT) + assertIs(sut.uiState.value.step) + } + + @Test + fun `an invoice with an amount goes straight to review without a small fee`() = test { + stubInvoice(prepared(amountSats = 21_000uL, feeSats = 3uL)) + + val sut = createSut() + + val step = assertIs(sut.uiState.value.step) + assertEquals(DisplayAmount("₿", "21 000"), step.amount) + assertNull(step.fee) + assertEquals("Coffee", step.payee) + assertTrue(sut.uiState.value.isHoldEnabled) + } + + @Test + fun `a fee of at least one percent shows on review`() = test { + stubInvoice(prepared(amountSats = 1_000uL, feeSats = 10uL)) + + val sut = createSut() + + val step = assertIs(sut.uiState.value.step) + assertEquals(DisplayAmount("₿", "10"), step.fee) + } + + @Test + fun `nothing is sent before the hold completes`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Completed))) + + val sut = createSut() + verify(paymentsRepo, never()).send(any()) + + sut.onHoldComplete() + + verify(paymentsRepo).send(prepared) + } + + @Test + fun `the quickpay hook sends without the hold`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(prepared)).thenReturn(true) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Completed))) + + createSut() + + verify(paymentsRepo).send(prepared) + } + + @Test + fun `offline disables the hold and a completed hold sends nothing`() = test { + stubInvoice(prepared()) + val sut = createSut() + + walletState.update { it.copy(status = WalletStatus.Offline) } + + assertFalse(sut.uiState.value.isHoldEnabled) + assertTrue(sut.uiState.value.isOffline) + sut.onHoldComplete() + verify(paymentsRepo, never()).send(any()) + assertIs(sut.uiState.value.step) + } + + @Test + fun `a sent payment shows the check and then closes the flow`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Completed))) + val sut = createSut() + + sut.effects.test { + sut.onHoldComplete() + assertEquals(SendStep.Done(SendResult.Sent, DisplayAmount("₿", "21 000")), sut.uiState.value.step) + expectNoEvents() + + testScheduler.advanceTimeBy(SendViewModel.SENT_CLOSE_DELAY + 1.seconds) + assertEquals(SendEffect.Close, awaitItem()) + } + } + + @Test + fun `a payment that did not settle shows as pending`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Pending))) + val sut = createSut() + + sut.onHoldComplete() + + assertEquals(SendResult.Pending, assertIs(sut.uiState.value.step).result) + } + + @Test + fun `an unknown outcome never shows as a failure`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.failure(SendError.Unknown())) + val sut = createSut() + + sut.onHoldComplete() + + assertEquals(SendResult.Unknown, assertIs(sut.uiState.value.step).result) + } + + @Test + fun `a failed send shows its reason`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.failure(SendError.Failed())) + val sut = createSut() + + sut.onHoldComplete() + + assertEquals(SendStep.Failed(SendFailure.Failed), sut.uiState.value.step) + } + + @Test + fun `a slow send says it is waiting for the network`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + + sut.onHoldComplete() + assertEquals(SendStep.Sending(isWaiting = false), sut.uiState.value.step) + assertTrue(sut.uiState.value.isBusy) + + testScheduler.advanceTimeBy(SendViewModel.WAITING_HINT_DELAY + 1.seconds) + assertEquals(SendStep.Sending(isWaiting = true), sut.uiState.value.step) + } + + @Test + fun `an own invoice is refused before the hold`() = test { + whenever(paymentsRepo.parse(INPUT)).thenReturn(Result.failure(SendError.OwnInvoice())) + + val sut = createSut() + + assertEquals(SendStep.Failed(SendFailure.OwnInvoice), sut.uiState.value.step) + verify(paymentsRepo, never()).prepare(any(), anyOrNull()) + } + + @Test + fun `a short balance is refused before the hold`() = test { + whenever(paymentsRepo.parse(INPUT)).thenReturn(Result.success(INVOICE)) + whenever(paymentsRepo.prepare(INVOICE, null)) + .thenReturn(Result.failure(SendError.InsufficientBalance(shortfallSats = 500uL))) + + val sut = createSut() + + assertEquals(SendStep.Failed(SendFailure.Insufficient), sut.uiState.value.step) + } + + @Test + fun `an amountless invoice asks for the amount and prices the typed one`() = test { + val request = SendRequest.Invoice(BOLT11, amountSats = null, description = null) + whenever(paymentsRepo.parse(INPUT)).thenReturn(Result.success(request)) + whenever(paymentsRepo.prepare(request, 2_100uL)).thenReturn(Result.success(prepared(amountSats = 2_100uL))) + val sut = createSut() + + assertEquals(SendStep.Amount(), sut.uiState.value.step) + verify(paymentsRepo, never()).prepare(any(), anyOrNull()) + + sut.onAmountChange("2a1 00") + assertEquals("2100", sut.uiState.value.amountText) + sut.onAmountConfirm() + + verify(paymentsRepo).prepare(request, 2_100uL) + assertIs(sut.uiState.value.step) + } + + @Test + fun `an amount outside the lnurl range is refused without pricing`() = test { + val request = SendRequest.Lnurl(lnurl(), minSats = 10uL, maxSats = 1_000uL, payee = "satoshi@pay.example") + whenever(paymentsRepo.parse(INPUT)).thenReturn(Result.success(request)) + val sut = createSut() + assertEquals(SendStep.Amount(minSats = 10uL, maxSats = 1_000uL), sut.uiState.value.step) + + sut.onAmountChange("5000") + sut.onAmountConfirm() + + assertEquals(SendStep.Amount(minSats = 10uL, maxSats = 1_000uL, isOutOfRange = true), sut.uiState.value.step) + verify(paymentsRepo, never()).prepare(any(), anyOrNull()) + + sut.onAmountChange("500") + assertFalse(assertIs(sut.uiState.value.step).isOutOfRange) + } + + private suspend fun stubInvoice(prepared: PreparedSend) { + whenever(paymentsRepo.parse(INPUT)).thenReturn(Result.success(INVOICE)) + whenever(paymentsRepo.prepare(INVOICE, null)).thenReturn(Result.success(prepared)) + } + + private fun prepared(amountSats: ULong = 21_000uL, feeSats: ULong = 0uL) = PreparedSend( + amountSats = amountSats, + feeSats = feeSats, + payee = null, + response = mock(), + paymentHash = "ab12", + transferKey = null, + ) + + private fun payment(state: PaymentState) = WatchPayment( + id = "send", + isSent = true, + amountSats = 21_000uL, + feeSats = 0uL, + timestampSecs = 1_800_000_000uL, + state = state, + ) + + private fun lnurl() = LnurlPayData( + uri = "lnurl1abc", + callback = "https://pay.example/lnurlp/satoshi/callback", + minSendable = 10_000uL, + maxSendable = 1_000_000uL, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + + private companion object { + const val BOLT11 = "lnbcrt1invoice" + const val INPUT = "lightning:$BOLT11" + val INVOICE = SendRequest.Invoice(BOLT11, amountSats = 21_000uL, description = "Coffee") + } +} From dc6476c150dacf65269dc6ec495192fbee7ad017 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 02:16:59 -0300 Subject: [PATCH 08/33] docs: describe wear payments screens and their journeys Co-Authored-By: Claude Opus 5.5 --- changelog.d/next/2105.added.md | 1 + docs/wear.md | 55 ++++++++++++++++-- journeys/wear/README.md | 74 ++++++++++++++++++++++-- journeys/wear/activity-list.xml | 21 +++++++ journeys/wear/receive-paid.xml | 20 +++++++ journeys/wear/receive-qr.xml | 22 +++++++ journeys/wear/send-deeplink-bolt11.xml | 21 +++++++ journeys/wear/send-hold-cancel.xml | 22 +++++++ journeys/wear/send-insufficient.xml | 18 ++++++ journeys/wear/send-own-invoice-guard.xml | 22 +++++++ journeys/wear/tile-balance.xml | 23 ++++++++ 11 files changed, 290 insertions(+), 9 deletions(-) create mode 100644 changelog.d/next/2105.added.md create mode 100644 journeys/wear/activity-list.xml create mode 100644 journeys/wear/receive-paid.xml create mode 100644 journeys/wear/receive-qr.xml create mode 100644 journeys/wear/send-deeplink-bolt11.xml create mode 100644 journeys/wear/send-hold-cancel.xml create mode 100644 journeys/wear/send-insufficient.xml create mode 100644 journeys/wear/send-own-invoice-guard.xml create mode 100644 journeys/wear/tile-balance.xml diff --git a/changelog.d/next/2105.added.md b/changelog.d/next/2105.added.md new file mode 100644 index 0000000000..9eb866eccf --- /dev/null +++ b/changelog.d/next/2105.added.md @@ -0,0 +1 @@ +Added receiving with a QR code, paying payment links with a hold to pay, recent activity and a balance tile to the Wear OS app, and the phone and the watch now refuse to pay Spark invoices their own wallet created. diff --git a/docs/wear.md b/docs/wear.md index 4e7f93ef28..41272506a5 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -76,8 +76,9 @@ Breez SDK, with no LDK node, no Room database and no Firebase. The phone is only `NfcMonitor` (the NFC adapter's state) and `ForegroundMonitor` (the process lifecycle: whether the app is on screen). - `ui`: one `MainActivity` with `testTagsAsResourceId`, a `SwipeDismissableNavHost` with the routes Onboarding, - the Restore graph, Wallet removed, Home, About and Not supported, and the M3 Expressive theme (black background, - Brand orange, Inter Tight). The splash screen stays while the first screen is picked, for at most about a second; + the Restore graph, Wallet removed, Home, About, Receive QR, Send, Activity detail and Not supported, and the M3 + Expressive theme (black background, Brand orange, Inter Tight). `LaunchRequest` reads what an intent asks for + beyond opening the app: a payment link or the tile's Receive. The splash screen stays while the first screen is picked, for at most about a second; after that the loading ring shows until it is. When the wallet storage cannot be recovered at launch, the start error (`WatchStartError` with `WatchStartRetry`) shows instead of a first screen. @@ -89,7 +90,7 @@ On-screen copy stays short: a title or one line of at most about six words per s ## Screens and visual system - **Home pager.** Home is a horizontal pager (`HorizontalPagerScaffold` with a page indicator) that opens on the - Balance page; Settings is the next page. `HOME_PAGES` in `HomePage.kt` lists the pages in swipe order, so a page + Balance page; Receive, Activity and Settings follow, in that order. `HOME_PAGES` in `HomePage.kt` lists the pages in swipe order, so a page is added in one line. The pager leaves the left edge of the first page to swipe-to-dismiss, which leaves the app. There is no Send page or button: a send starts from outside the app (phone handoff, NFC or a `lightning:` link). The pager composes only the page on screen, so Home itself, above the pager, leaves for onboarding or the Wallet @@ -150,12 +151,51 @@ On-screen copy stays short: a title or one line of at most about six words per s disconnected, the app keeps hold of it so the next lock, pause or wipe tries again: each of them disconnects whatever the wallet's status says, as does a start that finds the watch locked. Ambient mode is not the background: the app stays on screen and connected. +- **Receive.** The Receive page is one large round QR button (`WatchReceiveOpen`); it has no amount entry. It opens + the receive QR (`WatchReceiveQr`): an amountless invoice, uppercased so the code uses QR's alphanumeric mode, black + on white with the standard four-module quiet zone, error correction L, filling the largest square inside the round + screen (1/√2 of its width). Each module is one bitmap pixel scaled up without smoothing (zxing, as on the phone). + While the QR shows, the screen stays on at full brightness; both end when it leaves. The invoice is made once the + wallet is ready, under the loading ring; a failure shows one line and a retry (`WatchReceiveError`, + `WatchReceiveRetry`). An invoice is replaced by a new one a minute before it expires. Paid, the QR turns into a + check with the amount (`WatchReceivePaid`, `WatchReceivePaidAmount`) and a firm click (the `LongPress` haptic), unlike + the confirm pattern that ends a send; a tap on the check shows a new invoice. In ambient mode the QR is replaced by + a dimmed QR icon (`WatchReceiveHidden`). Debug builds log each invoice shown (`Showing invoice`), which is how the + journeys read it. +- **Send.** There is no Send page or button. A `lightning:`, `bitcoin:` or `spark:` link opens the app + (`MainActivity` is `singleTop`, so a link reaches the open app) and the send flow above Home; without a wallet, + or during the restore, the link is dropped. The flow waits for the wallet to be ready (the loading ring, with + "Offline" while it is offline), reads the input and prices the send (see Payments), all before the hold. An input + without an amount, an amountless invoice, a Spark address or an LNURL with a range, gets a minimal amount entry + (the number keyboard, the LNURL range below it); Receive never has one. + - Review: the amount in the balance's large style, fiat below in the small style, the fee only when it is at + least 1 % of the amount, and one line naming the payee when the input names one. The pay button is the edge + button, "Hold to pay" (`WatchSendHold`). + - Hold to pay: holding the button fills a ring around the bezel (`HoldToPayRing`, the geometry of `BezelLoading`) + over 1.2 s, with a light tick (`SegmentTick`) at each quarter and the confirm haptic at the end, and only then + the payment goes out. Releasing early empties the ring; a tap never pays. Offline, or with the wallet not ready, + the button is disabled with the line "Offline". `PaymentsRepo.skipConfirmation` is asked before the hold; it is + always false until QuickPay (PR 3). + - Sending: the loading ring, with "Waiting for network" after 3 s. The screen stays on and the flow cannot be + swiped away or left with Back while the send runs. + - Result: sent shows a check, "Sent" and the amount with the confirm haptic, and closes after 2 s. A payment that + did not settle in time shows a clock and "Pending"; an outcome Spark could not report shows "Check activity", + never a failure; both close after 3 s. A refusal or a failure shows a cross, one line of at most four words and + an OK button (`WatchSendError`, `WatchSendClose`), with the reject haptic. Insufficient funds, an expired or + unreadable invoice and an own invoice end there before any hold. +- **Activity.** The Activity page lists the newest 20 payments from Spark's local list: a direction icon (or a + clock for pending, a cross for failed), the amount with its sign and how long ago (`WatchActivityItem-0` onwards). + It is read when Spark connects and after every payment or sync, and the last list stays while Spark is + disconnected. A tap opens the detail: the amount, the fee of a send, the date and time and the status + (`WatchActivityDetailAmount`, `…Fee`, `…Time`, `…Status`); Spark's list carries no payee or description. With no + payments it shows a dimmed icon and "No activity" (`WatchActivityEmpty`). Ambient mode hides the amounts. - **Settings.** A short list of icon rows: About and Remove wallet. The unit has no setting: tapping the balance is the only way to switch it, and the choice is kept in the settings store across restarts. Remove wallet asks with a one-line title and the two round ✕/✓ buttons. - **Loading.** Every wait shows `BezelLoading`: an indeterminate ring around the screen edge (test tag `BezelLoading`), with the screen's content readable inside it. It covers connecting and syncing on Balance, saving - the restored wallet, and removing the wallet. It is hidden in ambient mode. Accessibility services report only + the restored wallet, removing the wallet, making an invoice, the first activity list, and a send being read, + priced and sent. It is hidden in ambient mode. Accessibility services report only content that no node above it covers, so the full-screen ring has no semantics; its one progress node (`BezelLoading`) is a stroke-sized spot at the top of the ring, and the content beneath stays reachable by TalkBack and `android layout`. `BezelPadding` and `BezelStrokeWidth` hold the ring's padding and stroke for other edge @@ -184,7 +224,12 @@ in any other state. amount asked. - **Sending.** The send call cannot be cancelled by the screen that started it, and one send runs at a time. It returns when Spark has the payment; the result then waits up to a minute for it to settle and reports it as - pending after that. + pending after that. The send screen keeps the screen on, so the app stays on screen and connected while it waits. + **Known gap:** a wearer who leaves the app during that wait pauses the wallet 10 s later (see Background); the + settlement is then not seen and the send reports pending after the minute, although it may have completed. The + activity list shows the real state once the app is back. +- **LNURL.** LNURL-pay and Lightning addresses are covered by unit tests only: the local stack's LNURL server serves + only addresses its own wallets registered, so no journey pays one. - **Paying once.** An invoice is sent under an idempotency key derived from the wallet seed, the payment hash and the attempt number (`SparkSendKey`, the same derivation as the phone and iOS). Spark makes one transfer per key, so the same invoice sent from the watch and the phone, or twice from the watch, is paid once. Before each send diff --git a/journeys/wear/README.md b/journeys/wear/README.md index f74a770e13..a2a4e573ab 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -14,6 +14,9 @@ What `android layout` misses on the watch, verified on the API 37 emulator: listed (the balance, for one), but wait for the ring to stop before asserting on a balance that is still loading. - **The pending and hidden marks.** `WatchHomeBalancePending` has no text either, so `android layout` leaves it out; `uiautomator dump` lists it. The same goes for `RestoreHidden`, the empty screen the restore shows in ambient mode. +- **The receive QR.** `WatchReceiveQr` is an image with no text or action, so `android layout` leaves it out; + `adb shell uiautomator dump` lists it. Check it there or from a screenshot. `WatchReceiveHidden`, the dimmed icon + that replaces it in ambient mode, has a content-desc and is listed. - **Suggestion chips.** A chip's tag (`RestoreSuggestion-0`, counted from 0) is on the button and its word is a text node at the same `center`. A chip below the screen edge is not listed until the screen scrolls. - **The keyboard.** The Wear OS keyboard is a full-screen window that `android layout` does not show. It lists the @@ -85,8 +88,10 @@ A dev watch build runs Spark on regtest. Two regtest networks exist, as for the | Funding | Faucet | `./spark send`, `./spark pay` | | Physical watch | Works over Wi-Fi or LTE | Needs `adb reverse` over the Wi-Fi debugging connection, or the stack on a LAN IP | -**Recommendation: hosted regtest for every journey in this suite.** None of them needs a payment, so the only cost is -the first sync of the test wallet, which the [Restored wallet](#restored-wallet) precondition pays once. +**Recommendation: hosted regtest for every journey that makes no payment**, where the only cost is the first sync of +the test wallet, which the [Restored wallet](#restored-wallet) precondition pays once. **The payment journeys run on +the [local `./spark` stack](#local-spark-stack)**, whose funds are ours alone and which pays and makes invoices from +the command line. Run `receive-paid.xml` first: it funds the wallet the send journeys spend from. | Journey | Backend | Needs funds | | --- | --- | --- | @@ -108,6 +113,19 @@ the first sync of the test wallet, which the [Restored wallet](#restored-wallet) | `background-disconnects-spark.xml` | hosted | yes | | `nfc-hint-states.xml` | hosted, physical watch only | yes | | `screenshot-blocked.xml` | none | no | +| `receive-qr.xml` | local | no | +| `receive-paid.xml` | local | no, it funds the wallet with 50 000 sats | +| `send-deeplink-bolt11.xml` | local | yes, 2 000 sats | +| `send-hold-cancel.xml` | local | yes, 2 000 sats | +| `send-insufficient.xml` | local | yes, less than 10 000 000 sats | +| `send-own-invoice-guard.xml` | local | yes, any balance above 0 | +| `activity-list.xml` | local | yes, after `receive-paid.xml` and `send-deeplink-bolt11.xml` | +| `tile-balance.xml` | hosted or local | no | + +Paying an LNURL-pay link or a Lightning address has no journey: the local stack's LNURL server serves only the +Lightning addresses its Spark wallets registered, over plain HTTP, and nothing in it registers one. It is covered by +`PaymentsRepoTest.kt` and `SendViewModelTest.kt`, which check the range, the amount entry and the invoice the service +returns. ### Local `./spark` stack @@ -126,8 +144,8 @@ regtest. A local wallet is new to that chain, so it starts at 0. ### Funding the test wallet -The watch app has no receive screen yet, so take the deposit address or invoice from the phone app with the same -recovery phrase: restore [the test wallet](#the-test-wallet) in a phone dev build on the same Spark network, read the +On the local stack, `receive-paid.xml` funds the watch through its own receive QR. Otherwise, or for an on-chain +deposit, take the deposit address or invoice from the phone app with the same recovery phrase: restore [the test wallet](#the-test-wallet) in a phone dev build on the same Spark network, read the Spark deposit address at Settings › Advanced › Lightning Connections › Spark (`SparkDepositAddress`), fund it, then close the phone app before you start the watch again. Two live Spark instances on one seed are unsafe (#2152), so never keep both open. @@ -253,6 +271,54 @@ adb shell input keyevent KEYCODE_ENTER Tapping a filled field puts the cursor where you tapped, so deleting with `KEYCODE_DEL` alone leaves part of the word. +## Payments + +### Reading the receive invoice + +`android layout` cannot read a QR code. Debug builds log the invoice the receive QR shows, in lowercase: + +```bash +adb logcat -d -s BitkitWear | grep -o "Showing invoice '[^']*'" | tail -n 1 | cut -d "'" -f 2 +``` + +Each new invoice logs a new line (debug builds only; verified on the API 37 emulator), so the last line is the invoice on screen. + +### Holding to pay + +The review's pay button (`WatchSendHold`) pays only when held for about 1.2 s; a tap does nothing. Hold it with a +swipe that does not move, for as long as its last argument says, at the `center` that `android layout` gives for the +button: + +```bash +adb shell input swipe 2000 # held 2 s: the ring fills and the payment goes out +adb shell input swipe 500 # released after 0.5 s: the ring empties and nothing is paid +``` + +### Local invoices + +From the bitkit-docker checkout, `./spark invoice ` prints a BOLT11 invoice of Alice's node, which the watch +pays out of Spark, and `./spark pay ` pays a watch invoice from Alice (the amount is needed, the +watch's invoices are amountless). Hand an invoice to the watch as a link, never by typing it: + +```bash +adb shell am start -a android.intent.action.VIEW -d "lightning:" to.bitkit.dev +``` + +## Tiles + +The system draws a tile, so `android layout` does not list what it shows; check it from a screenshot. Add, show and +remove the Bitkit tile with the Wear OS debug broadcasts: + +```bash +adb shell am broadcast -a com.google.android.wearable.app.DEBUG_SURFACE --es operation add-tile \ + --ecn component to.bitkit.dev/to.bitkit.wear.tile.BalanceTileService +adb shell am broadcast -a com.google.android.wearable.app.DEBUG_SYSUI --es operation show-tile --ei index 0 +adb shell am broadcast -a com.google.android.wearable.app.DEBUG_SURFACE --es operation remove-tile \ + --ecn component to.bitkit.dev/to.bitkit.wear.tile.BalanceTileService +``` + +`add-tile` prints the index the tile took; pass that one to `show-tile` when other tiles are added. + ## Watch gestures Coordinates are pixels. The 227 dp screen is 454 px square (centre 227), the 192 dp screen 384 px (centre 192). diff --git a/journeys/wear/activity-list.xml b/journeys/wear/activity-list.xml new file mode 100644 index 0000000000..10bd673e18 --- /dev/null +++ b/journeys/wear/activity-list.xml @@ -0,0 +1,21 @@ + + + The Activity page, after Receive, lists the newest payments with a direction icon, the amount and how long ago; + a tap opens the detail with the amount, the fee of a send, the time and the status. Emulator and physical watch. + + Precondition: Restored wallet on the local ./spark stack after receive-paid.xml and send-deeplink-bolt11.xml, so + the newest payment is the 1 000 sat send, see journeys/wear/README.md › Local ./spark stack, on the Balance page + with the loading ring stopped. Gestures are written for the 454 px screen. + + + Swipe the pager left twice: `adb shell input swipe 400 227 60 227 300`, wait 1 s, and again + Wait up to 10 s until "WatchActivityItem-0" is listed + Verify "WatchActivityItem-0" shows "- ₿ 1 000" and a relative time such as "1 min. ago" + Verify "WatchActivityItem-1" shows "+ ₿ 50 000" + Tap "WatchActivityItem-0" + Verify "WatchActivityDetailAmount" reads "1 000" + Verify "WatchActivityDetailStatus" reads "Completed" and "WatchActivityDetailTime" shows today's date + Swipe to dismiss from the left edge: `adb shell input swipe 20 227 400 227 300` + Verify "WatchActivityItem-0" is listed again + + diff --git a/journeys/wear/receive-paid.xml b/journeys/wear/receive-paid.xml new file mode 100644 index 0000000000..4608234e12 --- /dev/null +++ b/journeys/wear/receive-paid.xml @@ -0,0 +1,20 @@ + + + Paying the receive QR's invoice turns the QR into a check with the amount, with a firm haptic; a tap on the check + shows a new invoice. This also funds the wallet for the send journeys. Emulator and physical watch. + + Precondition: Restored wallet on the local ./spark stack, see journeys/wear/README.md › Local ./spark stack and + › Restored wallet, on the Balance page with the loading ring stopped. Gestures are written for the 454 px screen. + The haptic cannot be checked over adb; feel it on a physical watch. + + + Swipe the pager left once: `adb shell input swipe 400 227 60 227 300` + Tap "WatchReceiveOpen" and wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) + Read the invoice from the log as in README › Reading the receive invoice and note it as <invoice> + Run `../bitkit-docker/spark pay <invoice> 50000` from this repo's parent checkout + Wait up to 20 s until "WatchReceivePaid" is listed + Verify "WatchReceivePaidAmount" reads "50 000" + Tap "WatchReceivePaid" and wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" + Read the invoice from the log again and verify it differs from <invoice> + + diff --git a/journeys/wear/receive-qr.xml b/journeys/wear/receive-qr.xml new file mode 100644 index 0000000000..5d212bd43d --- /dev/null +++ b/journeys/wear/receive-qr.xml @@ -0,0 +1,22 @@ + + + The Receive page opens a full-screen QR of an amountless invoice; ambient mode hides the QR and waking the watch + shows it again. Emulator and physical watch. + + Precondition: Restored wallet on the local ./spark stack, see journeys/wear/README.md › Local ./spark stack and + › Restored wallet, on the Balance page with the loading ring stopped, and the always-on screen on (README › Watch + gestures). Gestures are written for the 454 px screen; scale them as in README › What differs. The QR content is + not in `android layout`: README › Reading the receive invoice takes it from the log. + + + Swipe the pager left once: `adb shell input swipe 400 227 60 227 300` + Verify the Receive page: "WatchReceiveOpen" is listed + Tap "WatchReceiveOpen" and wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) + Verify from a screenshot that a black-on-white QR code fills the middle of the screen + Read the invoice from the log as in README › Reading the receive invoice and verify it starts with "lnbcrt" + Run `adb shell input keyevent KEYCODE_SLEEP` and wait 3 s + Verify "WatchReceiveHidden" is listed with the content-desc "QR hidden" + Run `adb shell input keyevent KEYCODE_WAKEUP` and wait 2 s + Verify "WatchReceiveHidden" is not listed and a screenshot shows the QR code again + + diff --git a/journeys/wear/send-deeplink-bolt11.xml b/journeys/wear/send-deeplink-bolt11.xml new file mode 100644 index 0000000000..3e101b7130 --- /dev/null +++ b/journeys/wear/send-deeplink-bolt11.xml @@ -0,0 +1,21 @@ + + + A `lightning:` link to a BOLT11 invoice opens the review with the amount; holding the pay button fills the ring + around the bezel and pays; the check shows "Sent" and the flow closes by itself after about 2 s. Emulator and + physical watch. + + Precondition: Restored wallet on the local ./spark stack with at least 2 000 sats (run receive-paid.xml first), + see journeys/wear/README.md › Local ./spark stack, with the app open on the Balance page and the loading ring + stopped. README › Holding to pay has the hold gesture. + + + Run `../bitkit-docker/spark invoice 1000` and note the BOLT11 invoice it prints as <invoice> + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` + Wait up to 10 s until "WatchSendHold" is listed + Verify "WatchSendAmount" reads "1 000" and "WatchSendAmountSymbol" reads "₿" + Hold "WatchSendHold" for 2 s as in README › Holding to pay + Wait up to 15 s until "WatchSendSent" is listed + Verify "WatchSendResultAmount" reads "1 000" + Wait 4 s and verify the Balance page: "WatchHomeBalance" is listed and "WatchSendSent" is not + + diff --git a/journeys/wear/send-hold-cancel.xml b/journeys/wear/send-hold-cancel.xml new file mode 100644 index 0000000000..ab5734af98 --- /dev/null +++ b/journeys/wear/send-hold-cancel.xml @@ -0,0 +1,22 @@ + + + A tap on the pay button, or a hold released before the ring is full, pays nothing: the review stays and the + balance does not change. Emulator and physical watch. + + Precondition: Restored wallet on the local ./spark stack with at least 2 000 sats, see + journeys/wear/README.md › Local ./spark stack, with the app open on the Balance page and the loading ring stopped. + README › Holding to pay has the gestures. + + + Note the text of "WatchHomeBalance" as <balance> + Run `../bitkit-docker/spark invoice 1000` and note the BOLT11 invoice it prints as <invoice> + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` + Wait up to 10 s until "WatchSendHold" is listed + Tap "WatchSendHold" once + Wait 3 s and verify "WatchSendHold" is still listed and "WatchSendSending" is not + Hold "WatchSendHold" for 0.5 s as in README › Holding to pay, then release + Wait 3 s and verify "WatchSendHold" is still listed and "WatchSendSending" is not + Swipe to dismiss from the left edge: `adb shell input swipe 20 227 400 227 300` + Verify "WatchHomeBalance" still reads <balance> + + diff --git a/journeys/wear/send-insufficient.xml b/journeys/wear/send-insufficient.xml new file mode 100644 index 0000000000..03572b41a0 --- /dev/null +++ b/journeys/wear/send-insufficient.xml @@ -0,0 +1,18 @@ + + + An invoice for more than the balance is refused before the hold: the review never shows, only a cross with "Not + enough funds" and one button, which returns to Home. Emulator and physical watch. + + Precondition: Restored wallet on the local ./spark stack with less than 10 000 000 sats, see + journeys/wear/README.md › Local ./spark stack, with the app open on the Balance page and the loading ring stopped. + + + Run `../bitkit-docker/spark invoice 10000000` and note the BOLT11 invoice it prints as <invoice> + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` + Wait up to 10 s until "WatchSendError" is listed + Verify "WatchSendError" reads "Not enough funds" + Verify "WatchSendHold" is not listed + Tap "WatchSendClose" + Verify the Balance page: "WatchHomeBalance" is listed + + diff --git a/journeys/wear/send-own-invoice-guard.xml b/journeys/wear/send-own-invoice-guard.xml new file mode 100644 index 0000000000..0c851676c2 --- /dev/null +++ b/journeys/wear/send-own-invoice-guard.xml @@ -0,0 +1,22 @@ + + + The watch refuses to pay an invoice it created itself (the self-send guard, docs/wear.md › Self-send guard): the + invoice of its own Receive page, opened as a `lightning:` link on the same watch, ends on "Can't pay own invoice" + before any hold. Emulator and physical watch. + + Precondition: Restored wallet on the local ./spark stack with a balance above 0, see + journeys/wear/README.md › Local ./spark stack, on the Balance page with the loading ring stopped. Gestures are + written for the 454 px screen. + + + Swipe the pager left once: `adb shell input swipe 400 227 60 227 300` + Tap "WatchReceiveOpen" and wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) + Read the invoice from the log as in README › Reading the receive invoice and note it as <invoice> + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` + Wait up to 10 s until "WatchSendError" is listed + Verify "WatchSendError" reads "Can't pay own invoice" + Verify "WatchSendHold" is not listed + Tap "WatchSendClose" + Verify the Balance page: "WatchHomeBalance" is listed + + diff --git a/journeys/wear/tile-balance.xml b/journeys/wear/tile-balance.xml new file mode 100644 index 0000000000..df6fd81753 --- /dev/null +++ b/journeys/wear/tile-balance.xml @@ -0,0 +1,23 @@ + + + The Bitkit tile shows the balance the app last loaded and a Receive button that opens the app on the receive + QR. Emulator and physical watch. + + Precondition: Restored wallet, see journeys/wear/README.md › Restored wallet, its balance loaded on the Balance + page with the loading ring stopped. README › Tiles has the commands that add and show a tile. Tiles are drawn by + the system, so `android layout` does not list their content: check them from a screenshot. The tile without a + wallet ("open the app") and with a balance not loaded yet (the Bitkit mark only) are covered by `TileStateTest.kt` + and the tile preview. + + + Note the text of "WatchHomeBalance" as <balance> + Add the tile as in README › Tiles + Show the tile as in README › Tiles and wait 3 s + Verify from a screenshot that the tile shows "₿ <balance>" and a round QR button below it + Tap the QR button at the point the screenshot shows + Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) + Swipe to dismiss from the left edge: `adb shell input swipe 20 227 400 227 300` + Verify the Balance page: "WatchHomeBalance" is listed + Remove the tile as in README › Tiles + + From e8a7e72533c5eca2744dc456cd9bbbc9f8e69547 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 02:18:17 -0300 Subject: [PATCH 09/33] docs: leave the wear tile for a later pr Co-Authored-By: Claude Opus 5.5 --- changelog.d/next/2105.added.md | 2 +- docs/wear.md | 2 +- journeys/wear/README.md | 16 ---------------- journeys/wear/tile-balance.xml | 23 ----------------------- 4 files changed, 2 insertions(+), 41 deletions(-) delete mode 100644 journeys/wear/tile-balance.xml diff --git a/changelog.d/next/2105.added.md b/changelog.d/next/2105.added.md index 9eb866eccf..0ae274f3db 100644 --- a/changelog.d/next/2105.added.md +++ b/changelog.d/next/2105.added.md @@ -1 +1 @@ -Added receiving with a QR code, paying payment links with a hold to pay, recent activity and a balance tile to the Wear OS app, and the phone and the watch now refuse to pay Spark invoices their own wallet created. +Added receiving with a QR code, paying payment links with a hold to pay, and recent activity to the Wear OS app, and the phone and the watch now refuse to pay Spark invoices their own wallet created. diff --git a/docs/wear.md b/docs/wear.md index 41272506a5..6efa21253f 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -78,7 +78,7 @@ Breez SDK, with no LDK node, no Room database and no Firebase. The phone is only - `ui`: one `MainActivity` with `testTagsAsResourceId`, a `SwipeDismissableNavHost` with the routes Onboarding, the Restore graph, Wallet removed, Home, About, Receive QR, Send, Activity detail and Not supported, and the M3 Expressive theme (black background, Brand orange, Inter Tight). `LaunchRequest` reads what an intent asks for - beyond opening the app: a payment link or the tile's Receive. The splash screen stays while the first screen is picked, for at most about a second; + beyond opening the app: a payment link. The splash screen stays while the first screen is picked, for at most about a second; after that the loading ring shows until it is. When the wallet storage cannot be recovered at launch, the start error (`WatchStartError` with `WatchStartRetry`) shows instead of a first screen. diff --git a/journeys/wear/README.md b/journeys/wear/README.md index a2a4e573ab..ed1698a956 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -120,7 +120,6 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `send-insufficient.xml` | local | yes, less than 10 000 000 sats | | `send-own-invoice-guard.xml` | local | yes, any balance above 0 | | `activity-list.xml` | local | yes, after `receive-paid.xml` and `send-deeplink-bolt11.xml` | -| `tile-balance.xml` | hosted or local | no | Paying an LNURL-pay link or a Lightning address has no journey: the local stack's LNURL server serves only the Lightning addresses its Spark wallets registered, over plain HTTP, and nothing in it registers one. It is covered by @@ -304,21 +303,6 @@ watch's invoices are amountless). Hand an invoice to the watch as a link, never adb shell am start -a android.intent.action.VIEW -d "lightning:" to.bitkit.dev ``` -## Tiles - -The system draws a tile, so `android layout` does not list what it shows; check it from a screenshot. Add, show and -remove the Bitkit tile with the Wear OS debug broadcasts: - -```bash -adb shell am broadcast -a com.google.android.wearable.app.DEBUG_SURFACE --es operation add-tile \ - --ecn component to.bitkit.dev/to.bitkit.wear.tile.BalanceTileService -adb shell am broadcast -a com.google.android.wearable.app.DEBUG_SYSUI --es operation show-tile --ei index 0 -adb shell am broadcast -a com.google.android.wearable.app.DEBUG_SURFACE --es operation remove-tile \ - --ecn component to.bitkit.dev/to.bitkit.wear.tile.BalanceTileService -``` - -`add-tile` prints the index the tile took; pass that one to `show-tile` when other tiles are added. - ## Watch gestures Coordinates are pixels. The 227 dp screen is 454 px square (centre 227), the 192 dp screen 384 px (centre 192). diff --git a/journeys/wear/tile-balance.xml b/journeys/wear/tile-balance.xml deleted file mode 100644 index df6fd81753..0000000000 --- a/journeys/wear/tile-balance.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - The Bitkit tile shows the balance the app last loaded and a Receive button that opens the app on the receive - QR. Emulator and physical watch. - - Precondition: Restored wallet, see journeys/wear/README.md › Restored wallet, its balance loaded on the Balance - page with the loading ring stopped. README › Tiles has the commands that add and show a tile. Tiles are drawn by - the system, so `android layout` does not list their content: check them from a screenshot. The tile without a - wallet ("open the app") and with a balance not loaded yet (the Bitkit mark only) are covered by `TileStateTest.kt` - and the tile preview. - - - Note the text of "WatchHomeBalance" as <balance> - Add the tile as in README › Tiles - Show the tile as in README › Tiles and wait 3 s - Verify from a screenshot that the tile shows "₿ <balance>" and a round QR button below it - Tap the QR button at the point the screenshot shows - Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) - Swipe to dismiss from the left edge: `adb shell input swipe 20 227 400 227 300` - Verify the Balance page: "WatchHomeBalance" is listed - Remove the tile as in README › Tiles - - From c9996b72f425f786608433b9dd485267db43e13c Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 02:56:20 -0300 Subject: [PATCH 10/33] fix: keep wear send keys across retries, fail closed on unknown Co-Authored-By: Claude Fable 5.2 --- .../to/bitkit/wear/data/OwnInvoiceStore.kt | 11 + .../to/bitkit/wear/data/UncertainSendStore.kt | 111 ++++++ .../java/to/bitkit/wear/di/SecurityModule.kt | 6 + .../java/to/bitkit/wear/models/Payments.kt | 27 +- .../bitkit/wear/repositories/PaymentsRepo.kt | 188 ++++++++-- .../bitkit/wear/services/WatchSparkService.kt | 30 +- .../wear/ui/screens/send/SendViewModel.kt | 29 +- wear/src/main/res/values-ar/strings.xml | 2 +- wear/src/main/res/values-b+es+419/strings.xml | 2 +- wear/src/main/res/values-ca/strings.xml | 2 +- wear/src/main/res/values-cs/strings.xml | 2 +- wear/src/main/res/values-de/strings.xml | 2 +- wear/src/main/res/values-el/strings.xml | 2 +- wear/src/main/res/values-es-rES/strings.xml | 2 +- wear/src/main/res/values-es/strings.xml | 2 +- wear/src/main/res/values-fr/strings.xml | 2 +- wear/src/main/res/values-it/strings.xml | 2 +- wear/src/main/res/values-nl/strings.xml | 2 +- wear/src/main/res/values-pl/strings.xml | 2 +- wear/src/main/res/values-pt-rBR/strings.xml | 2 +- wear/src/main/res/values-pt/strings.xml | 2 +- wear/src/main/res/values-ru/strings.xml | 2 +- wear/src/main/res/values/strings.xml | 2 +- .../bitkit/wear/data/OwnInvoiceStoreTest.kt | 4 + .../wear/data/UncertainSendStoreTest.kt | 145 ++++++++ .../wear/repositories/PaymentsRepoTest.kt | 340 +++++++++++++++++- .../wear/services/WatchSparkServiceTest.kt | 42 +++ .../wear/ui/screens/send/SendViewModelTest.kt | 46 ++- 28 files changed, 929 insertions(+), 82 deletions(-) create mode 100644 wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt create mode 100644 wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt diff --git a/wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt b/wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt index d3308e3e10..9a85e98806 100644 --- a/wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt +++ b/wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt @@ -16,6 +16,9 @@ interface OwnInvoiceStore { /** Remembers the invoice with [paymentHash], in hex, until [expiresAtSecs], its expiry in epoch seconds. */ suspend fun add(paymentHash: String, expiresAtSecs: ULong) + /** Forgets the invoice with [paymentHash], in hex of either case, as when it was never handed out. */ + suspend fun remove(paymentHash: String) + /** Whether [paymentHash], in hex of either case, is an unexpired invoice of this wallet. */ suspend fun contains(paymentHash: String): Boolean } @@ -53,6 +56,14 @@ class SettingsOwnInvoiceStore internal constructor( } } + override suspend fun remove(paymentHash: String) { + dataStore.edit { prefs -> + val invoices = decode(prefs[key]) + if (paymentHash.lowercase() !in invoices) return@edit + prefs[key] = (invoices - paymentHash.lowercase()).mapTo(HashSet()) { "${it.key}$SEPARATOR${it.value}" } + } + } + override suspend fun contains(paymentHash: String): Boolean { val expiresAt = decode(dataStore.data.first()[key])[paymentHash.lowercase()] ?: return false return expiresAt > nowSecs() diff --git a/wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt b/wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt new file mode 100644 index 0000000000..4f7ab445fe --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt @@ -0,0 +1,111 @@ +package to.bitkit.wear.data + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringSetPreferencesKey +import kotlinx.coroutines.flow.first +import javax.inject.Inject +import javax.inject.Singleton + +/** + * A send this watch handed to Spark under the idempotency [key], whose outcome it has not learned. [sparkAddress] is + * set for a transfer to a Spark address, and [expiresAtSecs] for an invoice: its expiry in epoch seconds. + */ +data class UncertainSend( + val key: String, + val sparkAddress: String? = null, + val expiresAtSecs: ULong? = null, +) + +/** + * The sends this watch handed to Spark and has not seen the end of. Each is noted before it goes out and dropped once + * Spark shows its payment or refuses it unsent, so a send that is still here may have paid: the app was closed during + * it, or it failed without a trace. A retry then goes out under the same key, which Spark pays once. + */ +interface UncertainSendStore { + /** Notes [send] before it goes out. Returns whether its key was noted already, by an earlier attempt. */ + suspend fun begin(send: UncertainSend): Boolean + + /** Drops the send under [key], whose outcome is known. */ + suspend fun settle(key: String) + + /** The key of the noted transfer to [sparkAddress], in either case, or null when there is none. */ + suspend fun transferKey(sparkAddress: String): String? +} + +/** + * [UncertainSendStore] in the watch's settings file, so the wallet's wipe clears it with the settings. An invoice's + * send is dropped a day after the invoice expired, and at most [MAX_SENDS] are kept: the newest ones. + */ +@Singleton +class SettingsUncertainSendStore internal constructor( + private val dataStore: DataStore, + private val nowSecs: () -> ULong, +) : UncertainSendStore { + companion object { + const val MAX_SENDS = 100 + + /** How long after its invoice expired a send is still kept, in seconds. */ + const val EXPIRED_KEPT_SECS = 86_400uL + private const val SEPARATOR = '|' + private const val FIELDS = 4 + private const val MILLIS_PER_SEC = 1_000L + } + + @Inject + constructor(dataStore: DataStore) : + this(dataStore, { (System.currentTimeMillis() / MILLIS_PER_SEC).toULong() }) + + private val key = stringSetPreferencesKey("uncertain_sends") + + override suspend fun begin(send: UncertainSend): Boolean { + val now = nowSecs() + var wasNoted = false + dataStore.edit { prefs -> + val sends = decode(prefs[key]) + wasNoted = sends.any { it.send.key == send.key } + if (wasNoted) return@edit + prefs[key] = sends + .filter { it.send.expiresAtSecs?.let { expiresAt -> expiresAt + EXPIRED_KEPT_SECS > now } != false } + .plus(Entry(send.copy(sparkAddress = send.sparkAddress?.lowercase()), now)) + .sortedByDescending { it.startedAtSecs } + .take(MAX_SENDS) + .mapTo(HashSet()) { it.encode() } + } + return wasNoted + } + + override suspend fun settle(key: String) { + dataStore.edit { prefs -> + val sends = decode(prefs[this.key]) + if (sends.none { it.send.key == key }) return@edit + prefs[this.key] = sends.filter { it.send.key != key }.mapTo(HashSet()) { it.encode() } + } + } + + override suspend fun transferKey(sparkAddress: String): String? { + val address = sparkAddress.lowercase() + return decode(dataStore.data.first()[key]).firstOrNull { it.send.sparkAddress == address }?.send?.key + } + + private class Entry(val send: UncertainSend, val startedAtSecs: ULong) { + fun encode(): String = listOf( + send.key, + send.sparkAddress.orEmpty(), + send.expiresAtSecs?.toString().orEmpty(), + startedAtSecs.toString(), + ).joinToString(SEPARATOR.toString()) + } + + private fun decode(entries: Set?): List = entries.orEmpty().mapNotNull { entry -> + val fields = entry.split(SEPARATOR).takeIf { it.size == FIELDS } ?: return@mapNotNull null + val startedAt = fields[3].toULongOrNull() ?: return@mapNotNull null + val send = UncertainSend( + key = fields[0], + sparkAddress = fields[1].takeIf { it.isNotEmpty() }, + expiresAtSecs = fields[2].toULongOrNull(), + ) + Entry(send, startedAt) + } +} diff --git a/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt b/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt index 7f5651e14d..4a929673d6 100644 --- a/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt +++ b/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt @@ -21,6 +21,8 @@ import to.bitkit.wear.data.NfcMonitor import to.bitkit.wear.data.OwnInvoiceStore import to.bitkit.wear.data.ProcessForegroundMonitor import to.bitkit.wear.data.SettingsOwnInvoiceStore +import to.bitkit.wear.data.SettingsUncertainSendStore +import to.bitkit.wear.data.UncertainSendStore import to.bitkit.wear.data.WipeMarker import to.bitkit.wear.data.settingsDataStore import to.bitkit.wear.env.Env @@ -74,6 +76,10 @@ abstract class SecurityModule { @Singleton abstract fun bindOwnInvoiceStore(store: SettingsOwnInvoiceStore): OwnInvoiceStore + @Binds + @Singleton + abstract fun bindUncertainSendStore(store: SettingsUncertainSendStore): UncertainSendStore + @Binds @Singleton abstract fun bindSelfSendGuard(guard: WalletSelfSendGuard): SelfSendGuard diff --git a/wear/src/main/java/to/bitkit/wear/models/Payments.kt b/wear/src/main/java/to/bitkit/wear/models/Payments.kt index 8a1206ab3e..e0ccf599e8 100644 --- a/wear/src/main/java/to/bitkit/wear/models/Payments.kt +++ b/wear/src/main/java/to/bitkit/wear/models/Payments.kt @@ -62,8 +62,15 @@ class PreparedSend internal constructor( internal val response: PrepareSendPaymentResponse, /** The invoice's payment hash, or null for a Spark address. */ internal val paymentHash: String?, - /** The idempotency key of a send without a payment hash, made once so a repeated send pays once. */ - internal val transferKey: String?, + /** When the invoice expires, in epoch seconds, or null for a Spark address. */ + internal val expiresAtSecs: ULong?, + /** The Spark address a transfer pays, or null for an invoice. */ + internal val sparkAddress: String?, + /** + * The idempotency key a transfer to [sparkAddress] goes out under, made once so a repeated send pays once, + * unless an earlier transfer to the address is still in doubt: then its key is used again. + */ + internal val transferKey: String, ) { val totalSats: ULong get() = amountSats + feeSats } @@ -81,8 +88,8 @@ data class WatchPayment( ) /** - * Why an input cannot be paid, or a send did not go through. Every case but [Unknown] means nothing left the wallet - * for this request. + * Why an input cannot be paid, or a send did not go through. Every case but [Unknown], [AlreadyPaid] and [InFlight] + * means nothing left the wallet for this request. */ sealed class SendError(message: String, cause: Throwable? = null) : AppError(message, cause) { /** The wallet is not connected and synced, so it neither prices nor sends. */ @@ -109,18 +116,20 @@ sealed class SendError(message: String, cause: Throwable? = null) : AppError(mes /** The balance does not cover the amount and its fee; [shortfallSats] is what is missing, when known. */ class InsufficientBalance(val shortfallSats: ULong?) : SendError("The balance is '$shortfallSats' sats short") - /** This wallet already paid the invoice. */ - class AlreadyPaid : SendError("The invoice is already paid") + /** This wallet already paid the invoice, or an earlier transfer to the Spark address went through after all. */ + class AlreadyPaid : SendError("The request is already paid") - /** A send of this invoice is still under way, from the watch or the phone. */ - class InFlight : SendError("A payment of this invoice is under way") + /** A send of this request is still under way, from the watch or the phone. */ + class InFlight : SendError("A payment of this request is under way") /** Spark refused or failed the payment. */ class Failed(cause: Throwable? = null) : SendError("The payment failed", cause) /** * The send was handed to Spark and its outcome could not be learned: it may have been paid. Never shown as a - * plain failure; the activity list tells once Spark lists it, and sending the same invoice again cannot pay twice. + * plain failure; the activity list tells once Spark lists it. Sending the same request again from this watch + * goes out under the same idempotency key, an invoice's derived from its payment hash and a Spark address's kept + * until its outcome is known, so it cannot pay twice. */ class Unknown(cause: Throwable? = null) : SendError("The payment's outcome is not known yet", cause) } diff --git a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt index d36cd21bb1..64c6efb282 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -6,7 +6,6 @@ import breez_sdk_spark.Payment import breez_sdk_spark.PaymentDetails import breez_sdk_spark.PaymentStatus import breez_sdk_spark.PaymentType -import breez_sdk_spark.PrepareSendPaymentResponse import breez_sdk_spark.SdkEvent import breez_sdk_spark.SdkException import breez_sdk_spark.SendPaymentMethod @@ -14,7 +13,11 @@ import com.synonym.bitkitcore.LightningInvoice import com.synonym.bitkitcore.LnurlPayData import com.synonym.bitkitcore.Scanner import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow @@ -29,6 +32,8 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.wear.data.OwnInvoiceStore +import to.bitkit.wear.data.UncertainSend +import to.bitkit.wear.data.UncertainSendStore import to.bitkit.wear.di.IoDispatcher import to.bitkit.wear.ext.runSuspendCatching import to.bitkit.wear.models.PaymentState @@ -43,7 +48,6 @@ import to.bitkit.wear.services.SelfSendGuard import to.bitkit.wear.services.WatchSparkService import to.bitkit.wear.utils.Logger import java.net.URI -import java.util.Collections import java.util.UUID import javax.inject.Inject import javax.inject.Singleton @@ -61,6 +65,7 @@ class PaymentsRepo @Inject constructor( private val inputDecoder: InputDecoder, private val selfSendGuard: SelfSendGuard, private val ownInvoiceStore: OwnInvoiceStore, + private val uncertainSendStore: UncertainSendStore, ) { companion object { private const val TAG = "PaymentsRepo" @@ -75,6 +80,12 @@ class PaymentsRepo @Inject constructor( /** How long [send] waits for a payment that Spark took to settle, before it reports it as pending. */ val SETTLE_TIMEOUT = 60.seconds + /** How long [send] waits for the sync that brings Spark's list up to date before it picks a key. */ + val SYNC_TIMEOUT = 20.seconds + + /** How long [send] waits for Spark to take a payment, before it reports its outcome as unknown. */ + val SEND_TIMEOUT = 60.seconds + /** Every bitcoin there will be, in sats: no amount is above it. */ private const val MAX_SATS = 2_100_000_000_000_000uL @@ -90,8 +101,11 @@ class PaymentsRepo @Inject constructor( private val sendMutex = Mutex() - /** Keys of sends whose outcome was not learned, so a later refusal under the same key is not read as unsent. */ - private val uncertainKeys: MutableSet = Collections.synchronizedSet(HashSet()) + /** Sends run here, so the screen that started one cannot cancel it by closing. */ + private val sendScope = CoroutineScope(SupervisorJob() + ioDispatcher) + + /** The SDK's send call of the last send, which can outlive it when it stalls. Guarded by [sendMutex]. */ + private var sendCall: Job? = null /** Emits whenever Spark reports a payment or a sync, so the activity list reads [recentPayments] again. */ val paymentChanges: Flow get() = sparkService.events.map { } @@ -115,6 +129,13 @@ class PaymentsRepo @Inject constructor( val details = (sparkService.parse(bolt11) as InputType.Bolt11Invoice).v1 // Remembered before it is shown, so the watch never pays an invoice it handed out. ownInvoiceStore.add(details.paymentHash, details.expiresAt) + // A wipe that began meanwhile clears the store before or after the add, so the wiped wallet's invoice + // is taken out again and never shown. + if (!isReady() || sparkService.isWiping) { + runSuspendCatching { ownInvoiceStore.remove(details.paymentHash) } + .onFailure { Logger.warn("Failed to forget an invoice made during a wipe", it, context = TAG) } + throw ReceiveError.NotReady() + } ReceiveInvoice(bolt11, details.paymentHash, details.expiresAt) }.onFailure { Logger.error("Failed to create an invoice", it, context = TAG) @@ -208,7 +229,9 @@ class PaymentsRepo @Inject constructor( * request it fetches the invoice of that amount from the service. Fails with a [SendError]: * [SendError.NotReady], [SendError.AmountRequired], [SendError.AmountOutOfRange], [SendError.Expired], * [SendError.OwnInvoice], [SendError.InsufficientBalance], [SendError.Invalid] when an LNURL service answers with - * an invoice of another amount, and [SendError.Failed] when Spark cannot price it. Nothing is paid here. + * an invoice of another amount, [SendError.AlreadyPaid] and [SendError.InFlight] for a Spark address whose earlier + * transfer of unknown outcome Spark now lists, and [SendError.Failed] when Spark cannot price it. Nothing is paid + * here. */ suspend fun prepare(request: SendRequest, amountSats: ULong? = null): Result = withContext(ioDispatcher) { @@ -222,10 +245,18 @@ class PaymentsRepo @Inject constructor( } is SendRequest.Lnurl -> { ensureAmount(amount, request.minSats, request.maxSats) - prepare(lnurlInvoice(request, amount), amount, isAmountInRequest = true, request.payee) + prepare( + paymentRequest = lnurlInvoice(request, amount), + amountSats = amount, + isAmountInRequest = true, + payee = request.payee, + exactMsats = amount * MSATS_PER_SAT, + ) } is SendRequest.SparkAddress -> { ensureAmount(amount, 1uL, MAX_SATS) + // Told before the review, so the wearer never holds to pay a transfer that already went out. + earlierTransferKey(request.address) prepare(request.address, amount, isAmountInRequest = false, request.payee) } } @@ -254,21 +285,34 @@ class PaymentsRepo @Inject constructor( amountSats: ULong, isAmountInRequest: Boolean, payee: String?, + exactMsats: ULong? = null, ): PreparedSend { ensureNotOwn(paymentRequest) val response = runSuspendCatching { sparkService.prepareSend(paymentRequest, amountSats.takeIf { !isAmountInRequest }) }.getOrElse { throw it.toSendError() } - val (feeSats, paymentHash) = when (val method = response.paymentMethod) { - is SendPaymentMethod.Bolt11Invoice -> method.feeSats() to method.invoiceDetails.paymentHash + val method = response.paymentMethod + val (feeSats, invoice) = when (method) { + is SendPaymentMethod.Bolt11Invoice -> method.feeSats() to method.invoiceDetails is SendPaymentMethod.SparkAddress -> method.fee.toLong().toULong() to null else -> throw SendError.Unsupported() } - val balanceSats = sparkService.getInfo().balanceSats + // Spark pays what the invoice asks to the millisat, which whole sats can hide by up to 999 msat. + if (exactMsats != null && invoice?.amountMsat != exactMsats) throw SendError.Invalid() + val balanceSats = runSuspendCatching { sparkService.getInfo().balanceSats } + .getOrElse { throw SendError.NotReady() } val totalSats = amountSats + feeSats if (totalSats > balanceSats) throw SendError.InsufficientBalance(totalSats - balanceSats) - val transferKey = if (paymentHash == null) UUID.randomUUID().toString() else null - return PreparedSend(amountSats, feeSats, payee, response, paymentHash, transferKey) + return PreparedSend( + amountSats = amountSats, + feeSats = feeSats, + payee = payee, + response = response, + paymentHash = invoice?.paymentHash, + expiresAtSecs = invoice?.expiresAt, + sparkAddress = paymentRequest.takeIf { invoice == null }, + transferKey = UUID.randomUUID().toString(), + ) } /** @@ -286,33 +330,55 @@ class PaymentsRepo @Inject constructor( sparkTransferFeeSats?.takeIf { sparkService.prefersSpark } ?: lightningFeeSats /** - * Pays [prepared] and returns the payment: [PaymentState.Completed], or [PaymentState.Pending] when Spark took - * it and it did not settle within [SETTLE_TIMEOUT]. Once Spark has the send, the caller cannot cancel it. Fails - * with a [SendError]: [SendError.NotReady], [SendError.AlreadyPaid], [SendError.InFlight] (also while another - * send runs), [SendError.Expired], [SendError.InsufficientBalance], [SendError.Failed], and [SendError.Unknown] - * when the payment may have gone out. + * Pays [prepared] and returns the payment as Spark made it: [PaymentState.Completed], or [PaymentState.Pending] + * when Spark took it and it did not settle within [SETTLE_TIMEOUT]. The send does not run in the caller's scope: + * a caller that goes away neither cancels it nor loses its bookkeeping. Fails with a [SendError]: + * [SendError.NotReady], also when Spark cannot be reached to bring its list up to date, [SendError.AlreadyPaid], + * [SendError.InFlight] (also while another send runs, or Spark still holds the call of one that stalled), + * [SendError.Expired], [SendError.InsufficientBalance], [SendError.Failed], and [SendError.Unknown] when the + * payment may have gone out. * * An invoice is sent under the idempotency key the phone derives for it too, so Spark pays it once however often - * and from whichever device it is sent; each attempt Spark lists as failed moves to the next key. + * and from whichever device it is sent; each attempt Spark lists as failed moves to the next key. A Spark address + * has no such key, so the key of a transfer to it is kept in [UncertainSendStore] until its outcome is known, and + * a retry goes out under the same key. Every send is noted there before it goes out, so a refusal that follows an + * attempt of unknown outcome, also one the app was closed during, is never read as nothing sent. */ - suspend fun send(prepared: PreparedSend): Result = withContext(ioDispatcher) { + suspend fun send(prepared: PreparedSend): Result = sendScope.async { runSuspendCatching { if (!sendMutex.tryLock()) throw SendError.InFlight() try { + if (sendCall?.isActive == true) throw SendError.InFlight() if (!isReady()) throw SendError.NotReady() - val key = prepared.transferKey ?: invoiceKey(checkNotNull(prepared.paymentHash)) - sendWatched(prepared.response, key).toWatchPayment() + val address = prepared.sparkAddress + val key = if (address != null) { + earlierTransferKey(address) ?: prepared.transferKey + } else { + syncForSend() + invoiceKey(checkNotNull(prepared.paymentHash)) + } + sendWatched(prepared, key).toWatchPayment() } finally { sendMutex.unlock() } }.onFailure { Logger.error("Failed to send a payment", it, context = TAG) } + }.await() + + /** + * Syncs with Spark, so its list shows what the phone sent from the same wallet as far as Spark's operators tell. + * A sync that does not reach Spark in [SYNC_TIMEOUT] refuses the send. + */ + private suspend fun syncForSend() { + val sync = withTimeoutOrNull(SYNC_TIMEOUT) { runSuspendCatching { sparkService.syncWallet() }.getOrNull() } + if (sync?.hasReachedSpark != true) throw SendError.NotReady() } /** * The key of the next attempt at the invoice with [paymentHash], after Spark's list shows that no earlier send of - * it completed or is still pending. A list that cannot be read refuses the send. + * it completed or is still pending. A list that cannot be read, or a key that cannot be derived because Spark + * disconnected, refuses the send. */ private suspend fun invoiceKey(paymentHash: String): String { val listed = runSuspendCatching { sparkService.listPayments() }.getOrElse { throw SendError.NotReady() } @@ -320,13 +386,43 @@ class PaymentsRepo @Inject constructor( if (PaymentStatus.COMPLETED in states) throw SendError.AlreadyPaid() if (PaymentStatus.PENDING in states) throw SendError.InFlight() val failed = listed.filter { it.status == PaymentStatus.FAILED }.mapTo(HashSet()) { it.id } + fun key(attempt: Int) = runCatching { sparkService.sendKey(paymentHash, attempt) } + .getOrElse { throw SendError.NotReady() } var attempt = 0 - while (sparkService.sendKey(paymentHash, attempt) in failed) attempt++ - return sparkService.sendKey(paymentHash, attempt) + while (key(attempt) in failed) attempt++ + return key(attempt) + } + + /** + * The key a transfer to the Spark [address] has to go out under again, or null when a new key will do: no earlier + * transfer to the address is noted with an outcome never learned. When one is, Spark's synced list decides: a + * transfer it shows completed is not sent again ([SendError.AlreadyPaid], once, as the wearer was never told), + * one it shows pending is under way ([SendError.InFlight]), one it shows failed is over, and one it does not show + * goes out again under its key, which pays once. A store or a list that cannot be read refuses the send. + */ + private suspend fun earlierTransferKey(address: String): String? { + val earlier = runSuspendCatching { uncertainSendStore.transferKey(address) } + .getOrElse { throw SendError.Failed(it) } + ?: return null + syncForSend() + val listed = runSuspendCatching { sparkService.listPayments().firstOrNull { it.id == earlier } } + .getOrElse { throw SendError.NotReady() } + return when (listed?.status) { + PaymentStatus.COMPLETED -> { + settle(earlier) + throw SendError.AlreadyPaid() + } + PaymentStatus.PENDING -> throw SendError.InFlight() + PaymentStatus.FAILED -> { + settle(earlier) + null + } + null -> earlier + } } /** Sends under [key] while already listening for the payment's outcome, which can arrive before the call ends. */ - private suspend fun sendWatched(response: PrepareSendPaymentResponse, key: String): Payment = coroutineScope { + private suspend fun sendWatched(prepared: PreparedSend, key: String): Payment = coroutineScope { val settled = MutableStateFlow>(emptyMap()) val watcher = launch(start = CoroutineStart.UNDISPATCHED) { sparkService.events.mapNotNull { it.payment() } @@ -334,14 +430,27 @@ class PaymentsRepo @Inject constructor( .collect { payment -> settled.update { it + (payment.id to payment) } } } try { - val sent = runSuspendCatching { sparkService.send(response, key) }.getOrElse { recoverSend(it, key) } + // Noted before it goes out, so a send the app is closed during is known to be in doubt afterwards. + val wasUncertain = runSuspendCatching { + uncertainSendStore.begin(UncertainSend(key, prepared.sparkAddress, prepared.expiresAtSecs)) + }.getOrElse { throw SendError.Failed(it) } + // The SDK call cannot be cancelled, so it runs beside this wait, which gives up on a call that stalls. + val call = sendScope.async { runSuspendCatching { sparkService.send(prepared.response, key) } } + sendCall = call + val result = withTimeoutOrNull(SEND_TIMEOUT) { call.await() } + ?: Result.failure(SendError.Unknown()) + val sent = result.getOrElse { recoverSend(it, key, wasUncertain) } + // Spark lists the payment from here on, so the list tells its outcome. + settle(key) val payment = if (sent.status == PaymentStatus.PENDING) { withTimeoutOrNull(SETTLE_TIMEOUT) { settled.first { sent.id in it }.getValue(sent.id) } ?: sent } else { sent } if (payment.status == PaymentStatus.FAILED) throw SendError.Failed() - uncertainKeys.remove(key) + if (payment.amount.toLong().toULong() != prepared.amountSats) { + Logger.warn("Sent payment '${payment.id}' is an earlier send at another amount", context = TAG) + } Logger.info("Sent payment '${payment.id}' with status '${payment.status}'", context = TAG) payment } finally { @@ -350,19 +459,26 @@ class PaymentsRepo @Inject constructor( } /** - * What a send that threw under [key] comes to. Spark refuses an expired invoice and a short balance before - * anything goes out. Any other error can follow a transfer Spark committed, so Spark's list decides: a payment - * it shows under the key is this send, and a send it does not show is [SendError.Unknown]. + * What a send that threw under [key] comes to. Spark's list decides first: a payment it shows under the key is + * this send, also when an earlier attempt or the phone made it. Spark refuses an expired invoice and a short + * balance before anything goes out, so such a refusal is final, unless an earlier attempt under the key has an + * unknown outcome ([wasUncertain]): the refusal can follow the transfer that attempt committed. Any other error + * can follow a committed transfer too, so it is [SendError.Unknown]. */ - private suspend fun recoverSend(error: Throwable, key: String): Payment { + private suspend fun recoverSend(error: Throwable, key: String, wasUncertain: Boolean): Payment { + runSuspendCatching { sparkService.listPayments().firstOrNull { it.id == key } }.getOrNull()?.let { return it } val isRefusal = error.isInvoiceExpired() || error is SdkException.InsufficientFunds - if (isRefusal && key !in uncertainKeys) throw error.toSendError() - val listed = runSuspendCatching { sparkService.listPayments().firstOrNull { it.id == key } }.getOrNull() - if (listed == null) { - uncertainKeys.add(key) - throw SendError.Unknown(error) + if (isRefusal && !wasUncertain) { + settle(key) + throw error.toSendError() } - return listed + throw SendError.Unknown(error) + } + + /** Drops the note of the send under [key]. A note that stays only makes a later send more careful. */ + private suspend fun settle(key: String) { + runSuspendCatching { uncertainSendStore.settle(key) } + .onFailure { Logger.warn("Failed to settle the send '$key'", it, context = TAG) } } /** The wallet's newest payments, at most [limit], from Spark's local list. It needs Spark connected. */ diff --git a/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt b/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt index 3a6b523944..5ced0d3721 100644 --- a/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt +++ b/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt @@ -29,11 +29,15 @@ import breez_sdk_spark.parseSparkConfig import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.wear.env.Env import to.bitkit.wear.env.LocalSparkSettings import to.bitkit.wear.env.WalletNetwork @@ -47,6 +51,7 @@ import java.math.BigInteger import java.util.Base64 import javax.inject.Inject import javax.inject.Singleton +import kotlin.time.Duration.Companion.seconds import breez_sdk_spark.Network as SparkNetwork /** @@ -68,6 +73,9 @@ class WatchSparkService @Inject constructor( /** Leeway in sat/vB over the recommended fee that an automatic deposit claim may pay. */ private const val DEPOSIT_CLAIM_FEE_LEEWAY_SAT_PER_VB = 2uL + /** How long a [disconnect] waits for a send that Spark is taking, so it is not cut off halfway. */ + val SEND_GRACE = 10.seconds + /** * Bitkit's settings over the SDK's [defaults], as on the phone. Breez's real-time data sync server, its * Lightning address (LNURL) server and its default external input parsers stay off on every network. @@ -126,6 +134,9 @@ class WatchSparkService @Inject constructor( @Volatile private var sendKeySecret: ByteArray? = null + /** How many [send] calls the SDK is running. */ + private val runningSends = MutableStateFlow(0) + private val _events = MutableSharedFlow(extraBufferCapacity = 64) val events: SharedFlow = _events.asSharedFlow() @@ -181,7 +192,9 @@ class WatchSparkService @Inject constructor( * wipe never deletes the storage under it. */ suspend fun connect(seed: WalletSeed, wipeToken: Int): Boolean { - val secret = SparkSendKey.secret(bip39.toSeed(seed.mnemonic, seed.passphrase)) + val secret = bip39.toSeed(seed.mnemonic, seed.passphrase).let { bytes -> + SparkSendKey.secret(bytes).also { bytes.fill(0) } + } return connectWith(wipeToken, secret) { build(seed) } } @@ -238,11 +251,13 @@ class WatchSparkService @Inject constructor( } /** - * Disconnects the SDK as one step that its caller cannot cancel. A listener that cannot be removed does not stop - * the disconnect. When the disconnect itself fails, it throws and the SDK stays referenced, so the next - * [disconnect] reaches it again; a listener already removed is not removed twice. + * Disconnects the SDK as one step that its caller cannot cancel, after waiting up to [SEND_GRACE] for a running + * [send] to return. A listener that cannot be removed does not stop the disconnect. When the disconnect itself + * fails, it throws and the SDK stays referenced, so the next [disconnect] reaches it again; a listener already + * removed is not removed twice. */ suspend fun disconnect() = withContext(NonCancellable) { + withTimeoutOrNull(SEND_GRACE) { runningSends.first { it == 0 } } mutex.withLock { val current = sdk ?: return@withLock listenerId?.let { id -> @@ -334,7 +349,12 @@ class WatchSparkService @Inject constructor( } val current = requireSdk() return withContext(NonCancellable) { - current.sendPayment(SendPaymentRequest(prepared, options, idempotencyKey)).payment + runningSends.update { it + 1 } + try { + current.sendPayment(SendPaymentRequest(prepared, options, idempotencyKey)).payment + } finally { + runningSends.update { it - 1 } + } } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt index 56882e7d4b..9354ae7ef0 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt @@ -195,14 +195,24 @@ class SendViewModel @Inject constructor( return@launch } Logger.info("Finished send with outcome '$outcome'", context = TAG) - val amount = bitcoinAmount(prepared.amountSats.toLong()) - _uiState.update { it.copy(step = SendStep.Done(outcome, amount)) } - delay(if (outcome == SendResult.Sent) SENT_CLOSE_DELAY else PENDING_CLOSE_DELAY) - _effects.send(SendEffect.Close) + // The amount Spark paid, which is an earlier send's when the request was already sent at another amount. + finish(outcome, result.getOrNull()?.amountSats ?: prepared.amountSats) } } - private fun fail(error: Throwable?) { + /** Shows [result] with [amountSats] and then closes the flow. */ + private suspend fun finish(result: SendResult, amountSats: ULong) { + _uiState.update { it.copy(step = SendStep.Done(result, bitcoinAmount(amountSats.toLong()))) } + delay(if (result == SendResult.Sent) SENT_CLOSE_DELAY else PENDING_CLOSE_DELAY) + _effects.send(SendEffect.Close) + } + + /** Shows why nothing was sent. A payment that is already under way is no failure: it shows as pending. */ + private suspend fun fail(error: Throwable?) { + if (error is SendError.InFlight) { + finish(SendResult.Pending, amountSats = prepared?.amountSats ?: 0uL) + return + } _uiState.update { it.copy(step = SendStep.Failed(SendFailure.of(error))) } } @@ -238,7 +248,10 @@ sealed interface SendStep { /** The send is under way; [isWaiting] once it took longer than a moment. */ data class Sending(val isWaiting: Boolean = false) : SendStep - /** The send went out: sent, pending, or with an outcome not known yet. */ + /** + * The send went out: sent, pending, or with an outcome not known yet. Pending is also a payment of the request + * that was already under way. Only a sent payment shows its [amount]. + */ data class Done(val result: SendResult, val amount: DisplayAmount) : SendStep /** Nothing was sent, for [failure]. */ @@ -247,7 +260,7 @@ sealed interface SendStep { enum class SendResult { Sent, Pending, Unknown } -/** Why nothing was sent, with its one-line copy. */ +/** Why nothing was sent by this flow, with its one-line copy. */ enum class SendFailure(@StringRes val text: Int) { NotReady(R.string.send__error_not_ready), Invalid(R.string.send__error_invalid), @@ -257,7 +270,6 @@ enum class SendFailure(@StringRes val text: Int) { OutOfRange(R.string.send__error_out_of_range), Insufficient(R.string.send__error_insufficient), AlreadyPaid(R.string.send__error_already_paid), - InFlight(R.string.send__error_in_flight), Failed(R.string.send__error_failed), ; @@ -271,7 +283,6 @@ enum class SendFailure(@StringRes val text: Int) { is SendError.AmountOutOfRange -> OutOfRange is SendError.InsufficientBalance -> Insufficient is SendError.AlreadyPaid -> AlreadyPaid - is SendError.InFlight -> InFlight else -> Failed } } diff --git a/wear/src/main/res/values-ar/strings.xml b/wear/src/main/res/values-ar/strings.xml index 4566148638..34c9768eda 100644 --- a/wear/src/main/res/values-ar/strings.xml +++ b/wear/src/main/res/values-ar/strings.xml @@ -52,7 +52,6 @@ مدفوعة مسبقًا انتهت صلاحية الفاتورة فشل الدفع - الدفع معلق رصيد غير كافٍ فاتورة غير صالحة المحفظة غير جاهزة @@ -62,6 +61,7 @@ الرسوم %1$s اضغط مطولًا للدفع غير متصل + ادفع معلق تم الإرسال تحقق من النشاط diff --git a/wear/src/main/res/values-b+es+419/strings.xml b/wear/src/main/res/values-b+es+419/strings.xml index 8a82550475..9799c8ba09 100644 --- a/wear/src/main/res/values-b+es+419/strings.xml +++ b/wear/src/main/res/values-b+es+419/strings.xml @@ -49,7 +49,6 @@ Ya pagada Factura vencida Pago fallido - Pago pendiente Fondos insuficientes Factura no válida Wallet no lista @@ -59,6 +58,7 @@ Comisión %1$s Mantén para pagar Sin conexión + Pagar Pendiente Enviado Revisa la actividad diff --git a/wear/src/main/res/values-ca/strings.xml b/wear/src/main/res/values-ca/strings.xml index 33e56949d7..af21ae5bd0 100644 --- a/wear/src/main/res/values-ca/strings.xml +++ b/wear/src/main/res/values-ca/strings.xml @@ -49,7 +49,6 @@ Ja pagada Factura caducada El pagament ha fallat - Pagament pendent Fons insuficients Factura no vàlida Wallet no a punt @@ -59,6 +58,7 @@ Comissió %1$s Mantén per pagar Sense connexió + Paga Pendent Enviat Revisa l\'activitat diff --git a/wear/src/main/res/values-cs/strings.xml b/wear/src/main/res/values-cs/strings.xml index d98e3b0348..0418005264 100644 --- a/wear/src/main/res/values-cs/strings.xml +++ b/wear/src/main/res/values-cs/strings.xml @@ -50,7 +50,6 @@ Již zaplaceno Faktura vypršela Platba selhala - Platba se zpracovává Nedostatek prostředků Neplatná faktura Peněženka není připravena @@ -60,6 +59,7 @@ Poplatek %1$s Podržte pro platbu Offline + Zaplatit Zpracovávání Odesláno Zkontrolujte aktivitu diff --git a/wear/src/main/res/values-de/strings.xml b/wear/src/main/res/values-de/strings.xml index 23cec9c0cb..290fb3e318 100644 --- a/wear/src/main/res/values-de/strings.xml +++ b/wear/src/main/res/values-de/strings.xml @@ -48,7 +48,6 @@ Bereits bezahlt Rechnung abgelaufen Zahlung fehlgeschlagen - Zahlung ausstehend Nicht genug Guthaben Ungültige Rechnung Wallet nicht bereit @@ -58,6 +57,7 @@ Gebühr %1$s Halten zum Bezahlen Offline + Bezahlen Ausstehend Gesendet Aktivität prüfen diff --git a/wear/src/main/res/values-el/strings.xml b/wear/src/main/res/values-el/strings.xml index 7d371e62dd..7093b45f55 100644 --- a/wear/src/main/res/values-el/strings.xml +++ b/wear/src/main/res/values-el/strings.xml @@ -48,7 +48,6 @@ Ήδη πληρωμένο Το τιμολόγιο έληξε Η πληρωμή απέτυχε - Πληρωμή σε εκκρεμότητα Ανεπαρκές υπόλοιπο Μη έγκυρο τιμολόγιο Το πορτοφόλι δεν είναι έτοιμο @@ -58,6 +57,7 @@ Χρέωση %1$s Κράτα για πληρωμή Εκτός σύνδεσης + Πληρωμή Εκκρεμεί Στάλθηκε Δες τη δραστηριότητα diff --git a/wear/src/main/res/values-es-rES/strings.xml b/wear/src/main/res/values-es-rES/strings.xml index e8c1c44a2e..fc1cc812dc 100644 --- a/wear/src/main/res/values-es-rES/strings.xml +++ b/wear/src/main/res/values-es-rES/strings.xml @@ -49,7 +49,6 @@ Ya pagada Factura caducada Pago fallido - Pago pendiente Fondos insuficientes Factura no válida Wallet no lista @@ -59,6 +58,7 @@ Comisión %1$s Mantén para pagar Sin conexión + Pagar Pendiente Enviado Revisa la actividad diff --git a/wear/src/main/res/values-es/strings.xml b/wear/src/main/res/values-es/strings.xml index e8c1c44a2e..fc1cc812dc 100644 --- a/wear/src/main/res/values-es/strings.xml +++ b/wear/src/main/res/values-es/strings.xml @@ -49,7 +49,6 @@ Ya pagada Factura caducada Pago fallido - Pago pendiente Fondos insuficientes Factura no válida Wallet no lista @@ -59,6 +58,7 @@ Comisión %1$s Mantén para pagar Sin conexión + Pagar Pendiente Enviado Revisa la actividad diff --git a/wear/src/main/res/values-fr/strings.xml b/wear/src/main/res/values-fr/strings.xml index f8ae296319..3fb9b7d1a4 100644 --- a/wear/src/main/res/values-fr/strings.xml +++ b/wear/src/main/res/values-fr/strings.xml @@ -49,7 +49,6 @@ Déjà payée Facture expirée Échec du paiement - Paiement en attente Fonds insuffisants Facture invalide Wallet pas prêt @@ -59,6 +58,7 @@ Frais %1$s Maintenir pour payer Hors ligne + Payer En attente Envoyé Voir l\'activité diff --git a/wear/src/main/res/values-it/strings.xml b/wear/src/main/res/values-it/strings.xml index a00cc50b29..0603022654 100644 --- a/wear/src/main/res/values-it/strings.xml +++ b/wear/src/main/res/values-it/strings.xml @@ -49,7 +49,6 @@ Già pagata Fattura scaduta Pagamento fallito - Pagamento in sospeso Fondi insufficienti Fattura non valida Wallet non pronto @@ -59,6 +58,7 @@ Commissione %1$s Tieni premuto per pagare Offline + Paga In sospeso Inviato Controlla l\'attività diff --git a/wear/src/main/res/values-nl/strings.xml b/wear/src/main/res/values-nl/strings.xml index 592ad14625..b6cacd1d8b 100644 --- a/wear/src/main/res/values-nl/strings.xml +++ b/wear/src/main/res/values-nl/strings.xml @@ -48,7 +48,6 @@ Al betaald Factuur verlopen Betaling mislukt - Betaling in behandeling Onvoldoende saldo Ongeldige factuur Wallet niet gereed @@ -58,6 +57,7 @@ Kosten %1$s Houd vast om te betalen Offline + Betalen In behandeling Verzonden Bekijk activiteit diff --git a/wear/src/main/res/values-pl/strings.xml b/wear/src/main/res/values-pl/strings.xml index 157b5bd3c4..668cb4d627 100644 --- a/wear/src/main/res/values-pl/strings.xml +++ b/wear/src/main/res/values-pl/strings.xml @@ -50,7 +50,6 @@ Już opłacona Faktura wygasła Płatność nieudana - Płatność oczekuje Za mało środków Nieprawidłowa faktura Portfel nie jest gotowy @@ -60,6 +59,7 @@ Opłata %1$s Przytrzymaj, aby zapłacić Offline + Zapłać Oczekuje Wysłano Sprawdź aktywność diff --git a/wear/src/main/res/values-pt-rBR/strings.xml b/wear/src/main/res/values-pt-rBR/strings.xml index b29d1ea097..b0767fe0d0 100644 --- a/wear/src/main/res/values-pt-rBR/strings.xml +++ b/wear/src/main/res/values-pt-rBR/strings.xml @@ -49,7 +49,6 @@ Já pago Invoice expirado Pagamento falhou - Pagamento pendente Saldo insuficiente Invoice inválido Carteira não pronta @@ -59,6 +58,7 @@ Taxa %1$s Segure para pagar Offline + Pagar Pendente Enviado Veja a atividade diff --git a/wear/src/main/res/values-pt/strings.xml b/wear/src/main/res/values-pt/strings.xml index 06d7a34100..beaa639569 100644 --- a/wear/src/main/res/values-pt/strings.xml +++ b/wear/src/main/res/values-pt/strings.xml @@ -49,7 +49,6 @@ Já paga Fatura expirada Pagamento falhou - Pagamento pendente Saldo insuficiente Fatura inválida Carteira não pronta @@ -59,6 +58,7 @@ Taxa %1$s Mantenha para pagar Offline + Pagar Pendente Enviado Veja a atividade diff --git a/wear/src/main/res/values-ru/strings.xml b/wear/src/main/res/values-ru/strings.xml index f64f5ed7b5..5412fc2c79 100644 --- a/wear/src/main/res/values-ru/strings.xml +++ b/wear/src/main/res/values-ru/strings.xml @@ -50,7 +50,6 @@ Уже оплачен Счёт истёк Платёж не прошёл - Платёж в ожидании Недостаточно средств Неверный счёт Кошелёк не готов @@ -60,6 +59,7 @@ Комиссия %1$s Удерживайте для оплаты Офлайн + Оплатить В ожидании Отправлено Проверьте активность diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 6e8e41b664..d59e8cb050 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -48,7 +48,6 @@ Already paid Invoice expired Payment failed - Payment pending Not enough funds Invalid invoice Wallet not ready @@ -58,6 +57,7 @@ Fee %1$s Hold to pay Offline + Pay Pending Sent Check activity diff --git a/wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt index 8eef3e89d5..2176f896e0 100644 --- a/wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt +++ b/wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt @@ -22,6 +22,10 @@ class FakeOwnInvoiceStore : OwnInvoiceStore { invoices[paymentHash.lowercase()] = expiresAtSecs } + override suspend fun remove(paymentHash: String) { + invoices.remove(paymentHash.lowercase()) + } + override suspend fun contains(paymentHash: String): Boolean = paymentHash.lowercase() in invoices } diff --git a/wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt new file mode 100644 index 0000000000..388d9e60eb --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt @@ -0,0 +1,145 @@ +package to.bitkit.wear.data + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.job +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import to.bitkit.wear.test.BaseUnitTest +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** An [UncertainSendStore] in memory. */ +class FakeUncertainSendStore : UncertainSendStore { + val sends = mutableMapOf() + var failure: Throwable? = null + + override suspend fun begin(send: UncertainSend): Boolean { + failure?.let { throw it } + return sends.put(send.key, send.copy(sparkAddress = send.sparkAddress?.lowercase())) != null + } + + override suspend fun settle(key: String) { + failure?.let { throw it } + sends.remove(key) + } + + override suspend fun transferKey(sparkAddress: String): String? { + failure?.let { throw it } + return sends.values.firstOrNull { it.sparkAddress == sparkAddress.lowercase() }?.key + } +} + +/** The store against the real settings file, in a temporary directory. Each [open] is a new process. */ +class UncertainSendStoreTest : BaseUnitTest() { + private companion object { + const val ADDRESS = "sparkrt1pgssy6vty7krpze82ecm8j39gd35v35aqjjmhftc4culawsavkyh564u2uv8v0" + } + + @get:Rule + val folder = TemporaryFolder() + + private val settingsFile by lazy { File(folder.root, "datastore/settings.preferences_pb") } + private var scope: CoroutineScope? = null + private var now = 1_000uL + + @Test + fun `a noted transfer keeps its key for its address in either case, also after a restart`() = test { + assertFalse(open().first.begin(UncertainSend("key-a", sparkAddress = ADDRESS))) + close() + val sut = open().first + + assertEquals("key-a", sut.transferKey(ADDRESS)) + assertEquals("key-a", sut.transferKey(ADDRESS.uppercase())) + assertNull(sut.transferKey("sparkrt1other")) + close() + } + + @Test + fun `noting a send again tells that an earlier attempt used its key`() = test { + val sut = open().first + val send = UncertainSend("key-0", expiresAtSecs = 2_000uL) + + assertFalse(sut.begin(send)) + close() + + assertTrue(open().first.begin(send)) + close() + } + + @Test + fun `a settled send is forgotten`() = test { + val sut = open().first + sut.begin(UncertainSend("key-a", sparkAddress = ADDRESS)) + sut.begin(UncertainSend("key-0", expiresAtSecs = 2_000uL)) + + sut.settle("key-a") + sut.settle("key-0") + sut.settle("unknown") + + assertNull(sut.transferKey(ADDRESS)) + assertFalse(sut.begin(UncertainSend("key-0", expiresAtSecs = 2_000uL))) + close() + } + + @Test + fun `an invoice's send is kept for a day after the invoice expired, and a transfer for good`() = test { + val sut = open().first + sut.begin(UncertainSend("key-0", expiresAtSecs = 2_000uL)) + sut.begin(UncertainSend("key-a", sparkAddress = ADDRESS)) + + now = 2_000uL + SettingsUncertainSendStore.EXPIRED_KEPT_SECS - 1uL + sut.begin(UncertainSend("other-1", expiresAtSecs = now + 10uL)) + assertTrue(sut.begin(UncertainSend("key-0", expiresAtSecs = 2_000uL))) + + now = 2_000uL + SettingsUncertainSendStore.EXPIRED_KEPT_SECS + sut.begin(UncertainSend("other-2", expiresAtSecs = now + 10uL)) + assertFalse(sut.begin(UncertainSend("key-0", expiresAtSecs = 2_000uL))) + assertEquals("key-a", sut.transferKey(ADDRESS)) + close() + } + + @Test + fun `it keeps the newest sends when there are too many`() = test { + val sut = open().first + val count = SettingsUncertainSendStore.MAX_SENDS + 1 + + repeat(count) { + now = 1_000uL + it.toULong() + sut.begin(UncertainSend("key-$it", sparkAddress = "sparkrt1address$it")) + } + + assertNull(sut.transferKey("sparkrt1address0")) + assertEquals("key-1", sut.transferKey("sparkrt1address1")) + assertEquals("key-${count - 1}", sut.transferKey("sparkrt1address${count - 1}")) + close() + } + + @Test + fun `the wallet's wipe forgets the sends with the settings`() = test { + val (sut, settings) = open() + sut.begin(UncertainSend("key-a", sparkAddress = ADDRESS)) + + settings.finishWipe() + + assertNull(sut.transferKey(ADDRESS)) + close() + } + + private fun open(): Pair { + val opened = CoroutineScope(testDispatcher + Job()).also { scope = it } + val dataStore = settingsDataStore(opened) { settingsFile } + val settings = SettingsStore(dataStore, WipeMarker(lazy { File(folder.root, "seed") })) + return SettingsUncertainSendStore(dataStore) { now } to settings + } + + private suspend fun close() { + scope?.coroutineContext?.job?.cancelAndJoin() + scope = null + } +} diff --git a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt index 09c9a435d0..d5a3bc8cac 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -31,6 +31,8 @@ import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.wear.data.FakeOwnInvoiceStore +import to.bitkit.wear.data.FakeUncertainSendStore +import to.bitkit.wear.data.UncertainSend import to.bitkit.wear.models.PaymentState import to.bitkit.wear.models.PreparedSend import to.bitkit.wear.models.ReceiveError @@ -49,6 +51,7 @@ import to.bitkit.wear.services.SparkFixtures.SPARK_ADDRESS_HINT import to.bitkit.wear.services.SparkFixtures.invoiceInput import to.bitkit.wear.services.SparkFixtures.payment import to.bitkit.wear.services.SparkFixtures.sparkAddressInput +import to.bitkit.wear.services.SparkSync import to.bitkit.wear.services.WalletSelfSendGuard import to.bitkit.wear.services.WatchSparkService import to.bitkit.wear.test.BaseUnitTest @@ -73,6 +76,7 @@ class PaymentsRepoTest : BaseUnitTest() { private val events = MutableSharedFlow() private val walletState = MutableStateFlow(WalletState(WalletStatus.Ready, BALANCE, hasSynced = true)) private val ownInvoices = FakeOwnInvoiceStore() + private val uncertainSends = FakeUncertainSendStore() private val decoder = FakeInputDecoder() private lateinit var sut: PaymentsRepo @@ -84,6 +88,7 @@ class PaymentsRepoTest : BaseUnitTest() { whenever { sparkService.identityPubkey() }.thenReturn(IDENTITY) whenever { sparkService.getInfo() }.thenReturn(SparkFixtures.info(BALANCE)) whenever { sparkService.listPayments(anyOrNull()) }.thenReturn(emptyList()) + whenever { sparkService.syncWallet() }.thenReturn(SparkSync(error = null, syncedAtSecs = 1uL)) whenever(sparkService.sendKey(any(), any())).thenAnswer { "key-${it.arguments[1]}" } whenever { sparkService.parse(BOLT11) }.thenReturn(invoiceInput(BOLT11)) whenever { sparkService.prepareSend(eq(BOLT11), anyOrNull()) }.thenReturn(prepared()) @@ -94,6 +99,20 @@ class PaymentsRepoTest : BaseUnitTest() { decoder, WalletSelfSendGuard(sparkService, ownInvoices), ownInvoices, + uncertainSends, + ) + } + + /** A new repository over the same stores, as after the app was closed and opened again. */ + private fun restart() { + sut = PaymentsRepo( + testDispatcher, + sparkService, + walletRepo, + decoder, + WalletSelfSendGuard(sparkService, ownInvoices), + ownInvoices, + uncertainSends, ) } @@ -130,6 +149,17 @@ class PaymentsRepoTest : BaseUnitTest() { assertIs(sut.createInvoice().exceptionOrNull()) } + @Test + fun `an invoice made while the wallet is wiped is forgotten and not handed out`() = test { + whenever(sparkService.receiveBolt11(null, "", PaymentsRepo.INVOICE_EXPIRY_SECS)).doSuspendableAnswer { + walletState.update { it.copy(status = WalletStatus.Idle) } + BOLT11 + } + + assertIs(sut.createInvoice().exceptionOrNull()) + assertTrue(ownInvoices.invoices.isEmpty()) + } + @Test fun `waiting for an invoice ends with its payment and skips other payments`() = test { val paid = async { sut.awaitPaid(invoice()) } @@ -428,7 +458,7 @@ class PaymentsRepoTest : BaseUnitTest() { decoder.lnurlInvoices[15_000uL] = LNURL_BOLT11 decoder.inputs[LNURL_BOLT11] = lightning(LNURL_BOLT11, amountSats = 15uL) whenever(sparkService.parse(LNURL_BOLT11)).thenReturn(invoiceInput(LNURL_BOLT11, "cc".repeat(32))) - whenever(sparkService.prepareSend(LNURL_BOLT11, null)).thenReturn(prepared()) + whenever(sparkService.prepareSend(LNURL_BOLT11, null)).thenReturn(prepared(amountMsat = 15_000uL)) val request = SendRequest.Lnurl(lnurl(), minSats = 10uL, maxSats = 20uL, payee = "satoshi@pay.example") val prepared = sut.prepare(request, amountSats = 15uL).getOrThrow() @@ -437,6 +467,24 @@ class PaymentsRepoTest : BaseUnitTest() { assertEquals("satoshi@pay.example", prepared.payee) } + @Test + fun `an lnurl invoice that asks for millisats above the amount is refused`() = test { + decoder.lnurlInvoices[15_000uL] = LNURL_BOLT11 + decoder.inputs[LNURL_BOLT11] = lightning(LNURL_BOLT11, amountSats = 15uL) + whenever(sparkService.parse(LNURL_BOLT11)).thenReturn(invoiceInput(LNURL_BOLT11, "cc".repeat(32))) + whenever(sparkService.prepareSend(LNURL_BOLT11, null)).thenReturn(prepared(amountMsat = 15_999uL)) + val request = SendRequest.Lnurl(lnurl(), minSats = 10uL, maxSats = 20uL, payee = null) + + assertIs(sut.prepare(request, amountSats = 15uL).exceptionOrNull()) + } + + @Test + fun `a wallet that disconnects while a send is priced is not ready, not failed`() = test { + whenever(sparkService.getInfo()).doSuspendableAnswer { throw SparkError.NotConnected() } + + assertIs(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull()) + } + @Test fun `an lnurl invoice for another amount, or an expired one, is refused`() = test { val request = SendRequest.Lnurl(lnurl(), minSats = 10uL, maxSats = 20uL, payee = null) @@ -526,6 +574,73 @@ class PaymentsRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any(), any()) } + @Test + fun `an invoice is sent only after a sync that reached spark, so the list shows the phone's sends`() = test { + val prepared = preparedSend() + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.COMPLETED)) + // The watch's list lacks the phone's send of the invoice until it syncs. + whenever(sparkService.syncWallet()).doSuspendableAnswer { + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment("phone", PaymentStatus.PENDING))) + SparkSync(error = null, syncedAtSecs = 2uL) + } + + assertIs(sut.send(prepared).exceptionOrNull()) + verify(sparkService, never()).send(any(), any()) + } + + @Test + fun `a sync that brings the phone's failed attempt moves the watch to the phone's next key`() = test { + val prepared = preparedSend() + whenever(sparkService.send(any(), eq("key-1"))).thenReturn(payment("key-1", PaymentStatus.COMPLETED)) + whenever(sparkService.syncWallet()).doSuspendableAnswer { + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(payment("key-0", PaymentStatus.FAILED))) + SparkSync(error = null, syncedAtSecs = 2uL) + } + + assertTrue(sut.send(prepared).isSuccess) + verify(sparkService).send(any(), eq("key-1")) + verify(sparkService, never()).send(any(), eq("key-0")) + } + + @Test + fun `an invoice is not sent when the sync does not reach spark, fails or stalls`() = test { + val prepared = preparedSend() + + var sync: suspend () -> SparkSync = { SparkSync(error = "offline", syncedAtSecs = 1uL) } + whenever(sparkService.syncWallet()).doSuspendableAnswer { sync() } + assertIs(sut.send(prepared).exceptionOrNull()) + + sync = { SparkSync(error = null, syncedAtSecs = null) } + assertIs(sut.send(prepared).exceptionOrNull()) + + sync = { throw SparkError.NotConnected() } + assertIs(sut.send(prepared).exceptionOrNull()) + + sync = { CompletableDeferred().await() } + assertIs(sut.send(prepared).exceptionOrNull()) + assertEquals(PaymentsRepo.SYNC_TIMEOUT.inWholeMilliseconds, testScheduler.currentTime) + + verify(sparkService, never()).send(any(), any()) + } + + @Test + fun `a key that cannot be derived refuses the send as not ready`() = test { + val prepared = preparedSend() + whenever(sparkService.sendKey(any(), any())).thenAnswer { throw SparkError.NotConnected() } + + assertIs(sut.send(prepared).exceptionOrNull()) + verify(sparkService, never()).send(any(), any()) + } + + @Test + fun `a send reports the amount of the payment spark returns, also another device's at another amount`() = test { + whenever(sparkService.send(any(), eq("key-0"))) + .thenReturn(payment("key-0", PaymentStatus.COMPLETED, amountSats = 700)) + + assertEquals(700uL, sut.send(preparedSend()).getOrThrow().amountSats) + } + @Test fun `a pending send completes with the event that arrives while spark is still sending`() = test { whenever(sparkService.send(any(), eq("key-0"))).doSuspendableAnswer { @@ -585,15 +700,111 @@ class PaymentsRepoTest : BaseUnitTest() { } @Test - fun `after an unknown outcome a refusal under the same key stays unknown`() = test { - val prepared = preparedSend() + fun `after an unknown outcome a refusal under the same key stays unknown, also after a restart`() = test { var refusal: Throwable = SdkException.NetworkException("reset") whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw refusal } - sut.send(prepared) + sut.send(preparedSend()) + restart() refusal = SdkException.InsufficientFunds(null) + assertIs(sut.send(preparedSend()).exceptionOrNull()) + + refusal = SdkException.InvalidInput("invoice has expired") + assertIs(sut.send(preparedSend()).exceptionOrNull()) + } + + @Test + fun `a refusal under a key of a send the app was closed during is unknown, not unsent`() = test { + // What the store holds when the process dies inside the send call. + uncertainSends.begin(UncertainSend("key-0", expiresAtSecs = SparkFixtures.TIMESTAMP + SparkFixtures.EXPIRY)) + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw SdkException.InsufficientFunds(null) } + + assertIs(sut.send(preparedSend()).exceptionOrNull()) + } + + @Test + fun `a refusal is answered with the payment spark lists under the key`() = test { + whenever(sparkService.send(any(), any())).doSuspendableAnswer { + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment("key-0", PaymentStatus.COMPLETED))) + throw SdkException.InsufficientFunds(null) + } + + assertEquals(PaymentState.Completed, sut.send(preparedSend()).getOrThrow().state) + } + + @Test + fun `a send is noted before it goes out and forgotten once its outcome is known`() = test { + var notedDuringSend: Set? = null + whenever(sparkService.send(any(), eq("key-0"))).doSuspendableAnswer { + notedDuringSend = uncertainSends.sends.keys.toSet() + payment("key-0", PaymentStatus.COMPLETED) + } + + sut.send(preparedSend()).getOrThrow() + + assertEquals(setOf("key-0"), notedDuringSend) + assertTrue(uncertainSends.sends.isEmpty()) + } + + @Test + fun `a refusal before anything went out is forgotten, and an unknown outcome is kept`() = test { + var error: Throwable = SdkException.InsufficientFunds(null) + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw error } + + sut.send(preparedSend()) + assertTrue(uncertainSends.sends.isEmpty()) + + error = SdkException.NetworkException("reset") + sut.send(preparedSend()) + assertEquals( + UncertainSend("key-0", expiresAtSecs = SparkFixtures.TIMESTAMP + SparkFixtures.EXPIRY), + uncertainSends.sends.values.single(), + ) + } + + @Test + fun `a send that cannot be noted is not sent`() = test { + val prepared = preparedSend() + uncertainSends.failure = IllegalStateException("disk") + + assertIs(sut.send(prepared).exceptionOrNull()) + verify(sparkService, never()).send(any(), any()) + } + + @Test + fun `a send call that stalls ends as unknown, and nothing else is sent until spark returns it`() = test { + val prepared = preparedSend() + var answer = CompletableDeferred() + whenever(sparkService.send(any(), any())).doSuspendableAnswer { answer.await() } assertIs(sut.send(prepared).exceptionOrNull()) + assertEquals(PaymentsRepo.SEND_TIMEOUT.inWholeMilliseconds, testScheduler.currentTime) + assertEquals(setOf("key-0"), uncertainSends.sends.keys) + + assertIs(sut.send(prepared).exceptionOrNull()) + verify(sparkService).send(any(), any()) + + val stalled = answer + answer = CompletableDeferred(payment("key-0", PaymentStatus.COMPLETED)) + stalled.completeExceptionally(SdkException.NetworkException("reset")) + assertTrue(sut.send(prepared).isSuccess) + } + + @Test + fun `a send goes on and is settled after its caller is cancelled`() = test { + val release = CompletableDeferred() + whenever(sparkService.send(any(), any())).doSuspendableAnswer { release.await() } + val prepared = preparedSend() + val caller = launch { sut.send(prepared) } + + caller.cancel() + assertIs(sut.send(prepared).exceptionOrNull()) + release.complete(payment("key-0", PaymentStatus.COMPLETED)) + + assertTrue(uncertainSends.sends.isEmpty()) + whenever(sparkService.send(any(), any())).thenReturn(payment("key-0", PaymentStatus.COMPLETED)) + assertTrue(sut.send(prepared).isSuccess) } @Test @@ -638,6 +849,112 @@ class PaymentsRepoTest : BaseUnitTest() { verify(sparkService, never()).sendKey(any(), any()) } + @Test + fun `a spark address prepared again after an unknown outcome is sent under the same key`() = test { + val keys = stubTransfer() + var outcome: () -> Payment = { throw SdkException.NetworkException("reset") } + whenever(sparkService.send(any(), any())).thenAnswer { + keys += it.arguments[1] as String + outcome() + } + val request = SendRequest.SparkAddress(SPARK_ADDRESS) + assertIs(sut.send(sut.prepare(request, 500uL).getOrThrow()).exceptionOrNull()) + restart() + + outcome = { payment(keys.last(), PaymentStatus.COMPLETED, paymentHash = null) } + sut.send(sut.prepare(request, 500uL).getOrThrow()).getOrThrow() + + assertEquals(2, keys.size) + assertEquals(1, keys.distinct().size) + assertTrue(uncertainSends.sends.isEmpty()) + } + + @Test + fun `a spark address sent by another review after an unknown outcome keeps the first key`() = test { + val keys = stubTransfer() + whenever(sparkService.send(any(), any())).thenAnswer { + keys += it.arguments[1] as String + throw SdkException.NetworkException("reset") + } + val request = SendRequest.SparkAddress(SPARK_ADDRESS) + val first = sut.prepare(request, 500uL).getOrThrow() + val second = sut.prepare(request, 500uL).getOrThrow() + + sut.send(first) + sut.send(second) + + assertEquals(1, keys.distinct().size) + } + + @Test + fun `a spark transfer of unknown outcome that spark lists is not sent again`() = test { + val keys = stubTransfer() + whenever(sparkService.send(any(), any())).thenAnswer { + keys += it.arguments[1] as String + throw SdkException.NetworkException("reset") + } + val request = SendRequest.SparkAddress(SPARK_ADDRESS) + sut.send(sut.prepare(request, 500uL).getOrThrow()) + val key = keys.single() + + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment(key, PaymentStatus.PENDING, paymentHash = null))) + assertIs(sut.prepare(request, 500uL).exceptionOrNull()) + + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment(key, PaymentStatus.COMPLETED, paymentHash = null))) + assertIs(sut.prepare(request, 500uL).exceptionOrNull()) + assertEquals(1, keys.size) + + // Told once: the next transfer to the address is a new payment under a new key. + whenever(sparkService.send(any(), any())).thenAnswer { + keys += it.arguments[1] as String + payment(keys.last(), PaymentStatus.COMPLETED, paymentHash = null) + } + sut.send(sut.prepare(request, 500uL).getOrThrow()).getOrThrow() + assertEquals(2, keys.distinct().size) + } + + @Test + fun `a spark transfer of unknown outcome that spark lists failed is sent under a new key`() = test { + val keys = stubTransfer() + var outcome: () -> Payment = { throw SdkException.NetworkException("reset") } + whenever(sparkService.send(any(), any())).thenAnswer { + keys += it.arguments[1] as String + outcome() + } + val request = SendRequest.SparkAddress(SPARK_ADDRESS) + sut.send(sut.prepare(request, 500uL).getOrThrow()) + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment(keys.single(), PaymentStatus.FAILED, paymentHash = null))) + + outcome = { payment(keys.last(), PaymentStatus.COMPLETED, paymentHash = null) } + sut.send(sut.prepare(request, 500uL).getOrThrow()).getOrThrow() + + assertEquals(2, keys.distinct().size) + } + + @Test + fun `a spark transfer of unknown outcome is not sent again while spark cannot be asked`() = test { + val keys = stubTransfer() + whenever(sparkService.send(any(), any())).thenAnswer { + keys += it.arguments[1] as String + throw SdkException.NetworkException("reset") + } + val request = SendRequest.SparkAddress(SPARK_ADDRESS) + val prepared = sut.prepare(request, 500uL).getOrThrow() + sut.send(prepared) + + whenever(sparkService.syncWallet()).thenReturn(SparkSync(error = "offline", syncedAtSecs = 1uL)) + assertIs(sut.prepare(request, 500uL).exceptionOrNull()) + assertIs(sut.send(prepared).exceptionOrNull()) + + whenever(sparkService.syncWallet()).thenReturn(SparkSync(error = null, syncedAtSecs = 2uL)) + uncertainSends.failure = IllegalStateException("disk") + assertIs(sut.prepare(request, 500uL).exceptionOrNull()) + assertEquals(1, keys.size) + } + // endregion @Test @@ -686,8 +1003,19 @@ class PaymentsRepoTest : BaseUnitTest() { amountSats: Long = 1_000, ) = payment(id, status, PaymentType.RECEIVE, paymentHash, amountSats, feeSats = 0) - private fun prepared(sparkTransferFeeSats: ULong? = null) = PrepareSendPaymentResponse( - paymentMethod = SendPaymentMethod.Bolt11Invoice(SparkFixtures.invoice(BOLT11), sparkTransferFeeSats, FEE), + /** A Spark address of another wallet that Spark prices; returns the list the test notes its send keys in. */ + private suspend fun stubTransfer(): MutableList { + whenever(sparkService.parse(SPARK_ADDRESS)).thenReturn(sparkAddressInput(OTHER_IDENTITY)) + whenever(sparkService.prepareSend(SPARK_ADDRESS, 500uL)).thenReturn(preparedTransfer()) + return mutableListOf() + } + + private fun prepared(sparkTransferFeeSats: ULong? = null, amountMsat: ULong? = null) = PrepareSendPaymentResponse( + paymentMethod = SendPaymentMethod.Bolt11Invoice( + SparkFixtures.invoice(BOLT11, amountMsat = amountMsat), + sparkTransferFeeSats, + FEE, + ), amount = BigInteger.valueOf(500), tokenIdentifier = null, conversionEstimate = null, diff --git a/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt b/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt index 19e3feee3e..eb13ffa132 100644 --- a/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt +++ b/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt @@ -19,8 +19,12 @@ import breez_sdk_spark.SendPaymentOptions import breez_sdk_spark.SendPaymentRequest import breez_sdk_spark.SendPaymentResponse import breez_sdk_spark.TokenOptimizationConfig +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job +import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlinx.coroutines.yield import org.junit.Rule @@ -174,6 +178,44 @@ class WatchSparkServiceTest { assertTrue(isSent) } + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a disconnect waits for a running send, but no longer than its grace`() = runTest { + val sut = WatchSparkService(mock(), FakeBip39()) + val sdk = connectedSdk() + val prepared = PrepareSendPaymentResponse( + SendPaymentMethod.Bolt11Invoice(SparkFixtures.invoice(), null, 4uL), + BigInteger.valueOf(500), + null, + null, + FeePolicy.FEES_EXCLUDED, + ) + var release = CompletableDeferred() + whenever(sdk.sendPayment(any())).doSuspendableAnswer { + release.await() + SendPaymentResponse(SparkFixtures.payment("key", PaymentStatus.PENDING)) + } + sut.connectWith(assertNotNull(sut.wipeToken())) { sdk } + + val sending = launch { sut.send(prepared, "key") } + val disconnecting = launch { sut.disconnect() } + runCurrent() + verify(sdk, never()).disconnect() + release.complete(Unit) + joinAll(sending, disconnecting) + verify(sdk).disconnect() + + release = CompletableDeferred() + sut.connectWith(assertNotNull(sut.wipeToken())) { sdk } + val stalled = launch { sut.send(prepared, "key") } + runCurrent() + sut.disconnect() + assertEquals(WatchSparkService.SEND_GRACE.inWholeMilliseconds, testScheduler.currentTime) + verify(sdk, times(2)).disconnect() + release.complete(Unit) + stalled.join() + } + @Test fun `payments are listed newest first, up to the limit`() = runTest { val sut = WatchSparkService(mock(), FakeBip39()) diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt index 6efc171996..84f924d42a 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt @@ -182,6 +182,48 @@ class SendViewModelTest : BaseUnitTest() { assertEquals(SendResult.Unknown, assertIs(sut.uiState.value.step).result) } + @Test + fun `a sent payment shows the amount spark paid`() = test { + val prepared = prepared(amountSats = 5_000uL) + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Completed))) + val sut = createSut() + + sut.onHoldComplete() + + assertEquals(SendStep.Done(SendResult.Sent, DisplayAmount("₿", "21 000")), sut.uiState.value.step) + } + + @Test + fun `a payment already under way shows as pending, never as a failure`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.failure(SendError.InFlight())) + val sut = createSut() + + sut.effects.test { + sut.onHoldComplete() + assertEquals(SendResult.Pending, assertIs(sut.uiState.value.step).result) + + testScheduler.advanceTimeBy(SendViewModel.PENDING_CLOSE_DELAY + 1.seconds) + assertEquals(SendEffect.Close, awaitItem()) + } + } + + @Test + fun `a request found under way before the review shows as pending and closes`() = test { + whenever(paymentsRepo.parse(INPUT)).thenReturn(Result.success(INVOICE)) + whenever(paymentsRepo.prepare(INVOICE, null)).thenReturn(Result.failure(SendError.InFlight())) + + val sut = createSut() + + sut.effects.test { + assertEquals(SendResult.Pending, assertIs(sut.uiState.value.step).result) + testScheduler.advanceTimeBy(SendViewModel.PENDING_CLOSE_DELAY + 1.seconds) + assertEquals(SendEffect.Close, awaitItem()) + } + } + @Test fun `a failed send shows its reason`() = test { val prepared = prepared() @@ -276,7 +318,9 @@ class SendViewModelTest : BaseUnitTest() { payee = null, response = mock(), paymentHash = "ab12", - transferKey = null, + expiresAtSecs = 1_800_003_600uL, + sparkAddress = null, + transferKey = "transfer", ) private fun payment(state: PaymentState) = WatchPayment( From c3fdc8c5deae0d3006a95cabbd0c5fe3a66466ab Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 02:56:09 -0300 Subject: [PATCH 11/33] fix: fail closed in the phone's own spark invoice guard Co-Authored-By: Claude Fable 5.2 --- .../main/java/to/bitkit/data/CacheStore.kt | 15 ++++++++++----- .../java/to/bitkit/repositories/SparkRepo.kt | 17 ++++++++++++----- .../java/to/bitkit/services/SparkService.kt | 3 +++ .../to/bitkit/repositories/SparkRepoTest.kt | 19 +++++++++++++++++++ 4 files changed, 44 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index bfbc831421..00a5e40296 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -34,8 +34,11 @@ import kotlin.time.Clock */ internal const val MAX_SPARK_SEND_HASHES = 100 -/** How many unexpired invoices of the wallet's own are remembered; the ones that expire last are kept. */ -internal const val MAX_SPARK_OWN_INVOICES = 200 +/** + * How many unexpired invoices of the wallet's own are remembered; the ones that expire last are kept. Far above what + * a day of receive, contact and transfer invoices makes, as a dropped one could be paid by its own wallet. + */ +internal const val MAX_SPARK_OWN_INVOICES = 2_000 /** * How long past its invoice's expiry a send no listing shows may still be pending: no send starts after the expiry, @@ -177,10 +180,12 @@ class CacheStore internal constructor( */ suspend fun addSparkOwnInvoice(paymentHash: String, expiresAt: Long, now: Long) { store.updateData { data -> - val invoices = (data.sparkOwnInvoices + (paymentHash.lowercase() to expiresAt)).entries + val unexpired = (data.sparkOwnInvoices + (paymentHash.lowercase() to expiresAt)).entries .filter { it.value > now } - .sortedByDescending { it.value } - .take(MAX_SPARK_OWN_INVOICES) + if (unexpired.size > MAX_SPARK_OWN_INVOICES) { + Logger.warn("Dropped '${unexpired.size - MAX_SPARK_OWN_INVOICES}' unexpired own Spark invoices") + } + val invoices = unexpired.sortedByDescending { it.value }.take(MAX_SPARK_OWN_INVOICES) data.copy(sparkOwnInvoices = invoices.associate { it.key to it.value }) } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 0b67b00b1f..dcb9ec1464 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -529,7 +529,10 @@ class SparkRepo @Inject constructor( /** A withdrawal's debit already holds its fees, so it is weighed against the whole balance. */ fun canWithdraw(debitSats: ULong): Boolean = _state.value.isReady && _state.value.balanceSats >= debitSats - /** Creates a Spark invoice and remembers it as this wallet's own, which [isOwnInvoice] then recognises. */ + /** + * Creates a Spark invoice and remembers it as this wallet's own, which [isOwnInvoice] then recognises. An invoice + * that cannot be read or remembered is not handed out. + */ suspend fun createInvoice(amountSats: ULong?, description: String, expirySecs: UInt): Result = withContext(bgDispatcher) { runSuspendCatching { @@ -538,21 +541,25 @@ class SparkRepo @Inject constructor( } private suspend fun rememberOwnInvoice(bolt11: String) { - val invoice = sparkService.invoiceDetails(bolt11) ?: return + val invoice = sparkService.invoiceDetails(bolt11) ?: throw SparkError.InvoiceUnreadable() val expiresAt = SparkService.invoiceExpiresAt(invoice.timestamp, invoice.expiry) cacheStore.addSparkOwnInvoice(invoice.paymentHash, expiresAt.toEpochSeconds(), clock.now().epochSeconds) } /** * Whether [bolt11], with [paymentHash] in hex, pays this Spark wallet: an unexpired invoice this wallet remembers - * creating, or one that carries this wallet's Spark address. The second check needs Spark connected and is - * skipped without it. An invoice a paired watch created is known only once its hash was added to the cache. + * creating, or one that carries this wallet's Spark address. Remembered invoices that cannot be read count as + * own, so the invoice is refused instead of paid unchecked. The second check needs Spark connected and is skipped + * without it, as on a build or network without Spark. An invoice a paired watch created is known only once its + * hash was added to the cache. */ suspend fun isOwnInvoice(bolt11: String, paymentHash: String): Boolean = withContext(bgDispatcher) { val isRemembered = runSuspendCatching { cacheStore.hasSparkOwnInvoice(paymentHash, clock.now().epochSeconds) } .onFailure { Logger.warn("Failed to read the wallet's own Spark invoices", it, context = TAG) } + .getOrDefault(true) + isRemembered || runSuspendCatching { sparkService.carriesOwnSparkAddress(bolt11) } + .onFailure { Logger.debug("Skipped the Spark address check of an invoice: '${it.message}'", context = TAG) } .getOrDefault(false) - isRemembered || runSuspendCatching { sparkService.carriesOwnSparkAddress(bolt11) }.getOrDefault(false) } /** Returns the Lightning routing fee plus Spark's 0.25% service fee for paying [bolt11]. */ diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index b05e959780..e83a08c90c 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -425,6 +425,9 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me class WipeInProgress : SparkError("Spark wallet cannot connect while the wallet is wiped") class WipeFailed(path: String) : SparkError("Failed to delete Spark storage at '$path'") + /** An invoice Spark created that its own parser cannot read, so it cannot be remembered as the wallet's own. */ + class InvoiceUnreadable : SparkError("Spark invoice cannot be read") + /** Stored exit data Spark can never import: an exit state version it doesn't support, or one it can't read. */ class ExitStateUnimportable(cause: Throwable? = null) : SparkError("Spark can't import the exit data", cause) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index c63c5242dc..6d5ed30024 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -211,6 +211,25 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(sut.isOwnInvoice("lnbcrt1own", "ab12")) } + @Test + fun `an invoice spark's parser cannot read is not handed out`() = test { + whenever { sparkService.receiveBolt11(null, "", 3_600u) }.thenReturn("lnbcrt1own") + whenever { sparkService.invoiceDetails("lnbcrt1own") }.thenReturn(null) + val sut = createSut(cacheStore = CacheStore(InMemoryDataStore(AppCacheData()), clock)) + + assertIs(sut.createInvoice(null, "", 3_600u).exceptionOrNull()) + } + + @Test + fun `an invoice is refused as the wallet's own while its remembered invoices cannot be read`() = test { + val store = mock() + whenever { store.hasSparkOwnInvoice(any(), any()) }.doSuspendableAnswer { throw IOException("disk") } + whenever { sparkService.carriesOwnSparkAddress(any()) }.thenReturn(false) + val sut = createSut(cacheStore = store) + + assertTrue(sut.isOwnInvoice("lnbcrt1other", "cd34")) + } + @Test fun `an invoice that carries this wallet's spark address is its own without being remembered`() = test { whenever { sparkService.carriesOwnSparkAddress("lnbcrt1hint") }.thenReturn(true) From d9bdcef13c2665ca5c26dc5083569aeb2520c1ea Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 02:56:10 -0300 Subject: [PATCH 12/33] fix: harden wear send, receive and activity screens Co-Authored-By: Claude Fable 5.2 --- .../java/to/bitkit/wear/ui/LaunchRequest.kt | 14 +-- .../java/to/bitkit/wear/ui/WearNavHost.kt | 10 ++- .../screens/activity/ActivityDetailScreen.kt | 21 ++++- .../ui/screens/activity/ActivityScreen.kt | 18 +++- .../wear/ui/screens/receive/ReceiveScreen.kt | 5 +- .../ui/screens/receive/ReceiveViewModel.kt | 32 +++++-- .../bitkit/wear/ui/screens/send/SendScreen.kt | 89 +++++++++++++++++-- .../to/bitkit/wear/ui/LaunchRequestTest.kt | 18 ++-- .../screens/receive/ReceiveViewModelTest.kt | 44 ++++++++- 9 files changed, 208 insertions(+), 43 deletions(-) diff --git a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt index 0fccedb934..ac1a5fdae6 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt @@ -7,25 +7,17 @@ sealed interface LaunchRequest { /** Pay the payment input of a `lightning:`, `bitcoin:` or `spark:` link. */ data class Send(val input: String) : LaunchRequest - /** Show the receive QR, as from the tile. */ - data object Receive : LaunchRequest - companion object { - /** The extra that asks for [Receive], set by the tile. */ - const val EXTRA_OPEN = "to.bitkit.wear.OPEN" - const val OPEN_RECEIVE = "receive" - private val SEND_SCHEMES = setOf("lightning", "bitcoin", "spark") - /** The request of an intent with [action], [data] and the [open] extra, or null for a plain launch. */ - fun from(action: String?, data: String?, open: String?): LaunchRequest? { - if (open == OPEN_RECEIVE) return Receive + /** The request of an intent with [action] and [data], or null for a plain launch. */ + fun from(action: String?, data: String?): LaunchRequest? { if (action != Intent.ACTION_VIEW || data.isNullOrBlank()) return null val scheme = data.substringBefore(':', missingDelimiterValue = "").lowercase() return if (scheme in SEND_SCHEMES) Send(data) else null } fun from(intent: Intent?): LaunchRequest? = - intent?.let { from(it.action, it.dataString, it.getStringExtra(EXTRA_OPEN)) } + intent?.let { from(it.action, it.dataString) } } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt b/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt index 4813d78cc7..2357deb408 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt @@ -50,6 +50,11 @@ fun WearNavHost( LaunchedEffect(launchRequest) { val request = launchRequest ?: return@LaunchedEffect currentOnLaunchRequestHandle() + // A send under way keeps its screen: leaving it would hide the outcome of a payment that may have gone out. + if (isSending) { + Logger.info("Dropped launch request '${request::class.simpleName}' during a send", context = TAG) + return@LaunchedEffect + } navController.showLaunchRequest(request) } SwipeDismissableNavHost( @@ -169,8 +174,8 @@ private fun NavController.showRestoreWord(index: Int) { } /** - * Opens what [request] asks for above Home: the send flow of a deeplink or the receive QR. Without a wallet, or - * outside Home's back stack, such as during the restore, the request is dropped. + * Opens what [request] asks for above Home: the send flow of a deeplink. Without a wallet, or outside Home's back + * stack, such as during the restore, the request is dropped; the caller drops it while a send is under way. */ private fun NavController.showLaunchRequest(request: LaunchRequest) { val hasHome = runCatching { getBackStackEntry(Routes.HOME) }.isSuccess @@ -181,7 +186,6 @@ private fun NavController.showLaunchRequest(request: LaunchRequest) { popBackStack(Routes.HOME, inclusive = false) when (request) { is LaunchRequest.Send -> navigateTo(Routes.send(request.input)) - LaunchRequest.Receive -> navigateTo(Routes.RECEIVE_QR) } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt index 9d8214c230..a4eb0654d1 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt @@ -21,6 +21,7 @@ import androidx.wear.compose.material3.Text import to.bitkit.wear.R import to.bitkit.wear.models.PaymentState import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.ui.components.BezelLoading import to.bitkit.wear.ui.components.CenteredScreen import to.bitkit.wear.ui.components.LargeAmountRow import to.bitkit.wear.ui.components.WearPreview @@ -43,10 +44,28 @@ fun ActivityDetailScreen( modifier: Modifier = Modifier, ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() - val payment = uiState.payment(paymentId) ?: return + val payment = uiState.payment(paymentId) + if (payment == null) { + Missing(isLoading = !uiState.isLoaded, modifier = modifier) + return + } Content(payment = payment, isAmbient = isAmbient(), modifier = modifier) } +/** Stands in for a payment the list does not hold: while the list loads, or after newer payments pushed it out. */ +@Composable +private fun Missing( + isLoading: Boolean, + modifier: Modifier = Modifier, +) { + CenteredScreen( + overlay = { if (isLoading) BezelLoading() }, + modifier = modifier + ) { + DimIcon(modifier = Modifier.testTag("WatchActivityDetailMissing")) + } +} + @Composable private fun Content( payment: WatchPayment, diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt index f9af16c3e6..0970af523c 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt @@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource @@ -22,6 +23,7 @@ import androidx.wear.compose.material3.SurfaceTransformation import androidx.wear.compose.material3.Text import androidx.wear.compose.material3.lazy.transformedHeight import kotlinx.collections.immutable.persistentListOf +import kotlinx.coroutines.delay import to.bitkit.wear.R import to.bitkit.wear.models.BITCOIN_SYMBOL import to.bitkit.wear.models.PaymentState @@ -34,6 +36,8 @@ import to.bitkit.wear.ui.components.WearPreview import to.bitkit.wear.ui.components.WearPreviewDevices import to.bitkit.wear.ui.components.isAmbient import to.bitkit.wear.ui.theme.Colors +import java.time.Instant +import kotlin.time.Duration.Companion.minutes /** The size of the empty state's icon. */ private val EMPTY_ICON_SIZE = 40.dp @@ -41,6 +45,9 @@ private val EMPTY_ICON_SIZE = 40.dp /** The opacity of the icons that stand in for the list while it is empty, loading or hidden. */ private const val DIM_ALPHA = 0.4f +/** How often the relative times are counted again. */ +private val RELATIVE_TIME_TICK = 1.minutes + /** * The activity page of the home pager: the newest payments, each with its direction, amount and how long ago it * was. A tap opens its detail ([onPaymentClick]). Ambient mode hides the amounts. @@ -52,8 +59,15 @@ fun ActivityScreen( viewModel: ActivityViewModel = hiltViewModel(), ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() + // The relative times move on while the page stays open and Spark reports nothing new. + val nowSecs by produceState(uiState.nowSecs, uiState.nowSecs) { + while (true) { + delay(RELATIVE_TIME_TICK) + value = Instant.now().epochSecond + } + } Content( - uiState = uiState, + uiState = uiState.copy(nowSecs = nowSecs), isAmbient = isAmbient(), onPaymentClick = onPaymentClick, modifier = modifier @@ -155,7 +169,7 @@ private fun relativeTime(timestampSecs: Long, nowSecs: Long): String = DateUtils ).toString() @Composable -private fun DimIcon(modifier: Modifier = Modifier) { +internal fun DimIcon(modifier: Modifier = Modifier) { Icon( painter = painterResource(R.drawable.ic_history), contentDescription = null, diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveScreen.kt index 33d5847a7b..512f15cb9d 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveScreen.kt @@ -6,6 +6,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.unit.dp import androidx.wear.compose.material3.FilledIconButton import androidx.wear.compose.material3.Icon @@ -39,13 +40,15 @@ fun ReceiveScreen( ) { Icon( painter = painterResource(R.drawable.ic_qr_code), - contentDescription = null, + contentDescription = stringResource(R.string.receive__title), modifier = Modifier.size(ICON_SIZE) ) } Text( text = stringResource(R.string.receive__title), style = MaterialTheme.typography.titleSmall, + // The button says it already; read once. + modifier = Modifier.clearAndSetSemantics {} ) } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt index 8f576ba916..c45c205895 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt @@ -13,6 +13,7 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.wear.env.Env +import to.bitkit.wear.models.ReceiveInvoice import to.bitkit.wear.repositories.PaymentsRepo import to.bitkit.wear.repositories.WalletRepo import to.bitkit.wear.repositories.WalletStatus @@ -39,6 +40,12 @@ class ReceiveViewModel internal constructor( /** How long before its expiry an invoice is replaced, so a payer never scans one that is about to expire. */ val EXPIRY_MARGIN = 60.seconds + + /** + * The shortest time an invoice shows before it is replaced, so a watch whose clock runs ahead of Spark's + * does not make invoices one after another. + */ + val MIN_LIFETIME = 30.seconds } @Inject @@ -62,26 +69,39 @@ class ReceiveViewModel internal constructor( private fun refresh() { job?.cancel() job = viewModelScope.launch { + _uiState.update { ReceiveUiState(isLoading = true) } while (true) { - _uiState.update { ReceiveUiState(isLoading = true) } - walletRepo.walletState.first { it.status == WalletStatus.Ready } - val invoice = paymentsRepo.createInvoice().getOrElse { - _uiState.update { state -> state.copy(isLoading = false, isError = true) } + // The invoice on screen stays until its replacement exists, or until it is about to expire. + val isShowing = _uiState.value.qrContent != null + val replaced = if (isShowing) withTimeoutOrNull(EXPIRY_MARGIN) { create() } else null + val created = replaced ?: run { + _uiState.update { ReceiveUiState(isLoading = true) } + create() + } + val invoice = created.getOrElse { + _uiState.update { ReceiveUiState(isError = true) } return@launch } if (Env.isDebug) Logger.debug("Showing invoice '${invoice.bolt11}'", context = TAG) - _uiState.update { it.copy(qrContent = invoice.bolt11.uppercase(), isLoading = false) } + _uiState.update { ReceiveUiState(qrContent = invoice.bolt11.uppercase()) } val lifetime = (invoice.expiresAtSecs.toLong() - nowSecs()).seconds - EXPIRY_MARGIN - val paid = withTimeoutOrNull(lifetime.coerceAtLeast(0.seconds)) { paymentsRepo.awaitPaid(invoice) } + val paid = withTimeoutOrNull(lifetime.coerceAtLeast(MIN_LIFETIME)) { paymentsRepo.awaitPaid(invoice) } if (paid != null) { Logger.info("Received payment '${paid.id}'", context = TAG) _uiState.update { ReceiveUiState(paidAmount = bitcoinAmount(paid.amountSats.toLong())) } return@launch } Logger.debug("Replacing invoice '${invoice.paymentHash}' before it expires", context = TAG) + _uiState.update { it.copy(isLoading = true) } } } } + + /** Makes an invoice once the wallet is ready. */ + private suspend fun create(): Result { + walletRepo.walletState.first { it.status == WalletStatus.Ready } + return paymentsRepo.createInvoice() + } } @Immutable diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt index 665943d944..4e7bb9e501 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt @@ -15,6 +15,7 @@ import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState @@ -27,6 +28,9 @@ import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign @@ -52,6 +56,7 @@ import to.bitkit.wear.ui.components.SmallAmountRow import to.bitkit.wear.ui.components.WearPreview import to.bitkit.wear.ui.components.WearPreviewDevices import to.bitkit.wear.ui.components.amountRowGap +import to.bitkit.wear.ui.components.isAmbient import to.bitkit.wear.ui.components.rememberHoldToPayState import to.bitkit.wear.ui.screens.home.DisplayAmount import to.bitkit.wear.ui.theme.Colors @@ -65,7 +70,8 @@ private const val LOADING_ICON_ALPHA = 0.4f /** * The send flow of a deeplink: review with the hold to pay, the send under way, and its result, which closes the * flow by itself ([onClose]). The amount entry shows only for an input that names no amount. While a send is under - * way the screen stays on and cannot be left ([onBusyChange]). + * way the screen stays on and cannot be left ([onBusyChange]). In ambient mode a step with an amount hides behind a + * dimmed bolt, as no amount shows on the always-on screen. */ @Composable fun SendScreen( @@ -86,6 +92,8 @@ fun SendScreen( } } LaunchedEffect(uiState.isBusy) { currentOnBusyChange(uiState.isBusy) } + // A screen that leaves while busy must not leave the swipe to dismiss off for every other screen. + DisposableEffect(Unit) { onDispose { currentOnBusyChange(false) } } val step = uiState.step LaunchedEffect(step is SendStep.Done, step is SendStep.Failed) { when (step) { @@ -98,6 +106,7 @@ fun SendScreen( BackHandler(enabled = uiState.isBusy) {} Content( uiState = uiState, + isAmbient = isAmbient(), onAmountChange = viewModel::onAmountChange, onAmountConfirm = viewModel::onAmountConfirm, onHoldComplete = viewModel::onHoldComplete, @@ -109,13 +118,20 @@ fun SendScreen( @Composable private fun Content( uiState: SendUiState, + isAmbient: Boolean, onAmountChange: (String) -> Unit, onAmountConfirm: () -> Unit, onHoldComplete: () -> Unit, onCloseClick: () -> Unit, modifier: Modifier = Modifier, ) { - when (val step = uiState.step) { + val step = uiState.step + // The always-on screen shows no amount, typed, reviewed or sent, and nothing to hold. + if (isAmbient && (step is SendStep.Amount || step is SendStep.Review || step is SendStep.Done)) { + Hidden(modifier = modifier) + return + } + when (step) { SendStep.Loading -> Loading(isOffline = uiState.isOffline, modifier = modifier) is SendStep.Amount -> Amount( step = step, @@ -127,7 +143,8 @@ private fun Content( is SendStep.Review -> Review( step = step, isHoldEnabled = uiState.isHoldEnabled, - isOffline = !uiState.isWalletReady, + isOffline = uiState.isOffline, + isConnecting = !uiState.isWalletReady && !uiState.isOffline, onHoldComplete = onHoldComplete, modifier = modifier ) @@ -137,6 +154,17 @@ private fun Content( } } +@Composable +private fun Hidden(modifier: Modifier = Modifier) { + CenteredScreen(modifier = modifier) { + StatusIcon( + icon = R.drawable.ic_bolt, + tint = Colors.White.copy(alpha = LOADING_ICON_ALPHA), + modifier = Modifier.testTag("WatchSendHidden") + ) + } +} + @Composable private fun Loading( isOffline: Boolean, @@ -254,10 +282,12 @@ private fun Review( step: SendStep.Review, isHoldEnabled: Boolean, isOffline: Boolean, + isConnecting: Boolean, onHoldComplete: () -> Unit, modifier: Modifier = Modifier, ) { val holdState = rememberHoldToPayState(enabled = isHoldEnabled, onComplete = onHoldComplete) + val payLabel = stringResource(R.string.send__pay) CenteredScreen( edgeButton = { EdgeButton( @@ -266,12 +296,25 @@ private fun Review( enabled = isHoldEnabled, buttonSize = EdgeButtonSize.Medium, interactionSource = holdState.interactionSource, - modifier = Modifier.testTag("WatchSendHold") + modifier = Modifier + .testTag("WatchSendHold") + .semantics { + // A screen reader cannot hold, and its double tap is the click that pays nothing, so paying + // is a named action its wearer picks from the actions menu. + if (isHoldEnabled) { + customActions = listOf( + CustomAccessibilityAction(payLabel) { + onHoldComplete() + true + }, + ) + } + } ) { Text(stringResource(R.string.send__hold)) } }, - overlay = { HoldToPayRing(state = holdState) }, + overlay = { if (isConnecting) BezelLoading() else HoldToPayRing(state = holdState) }, modifier = modifier ) { BoxWithConstraints(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth()) { @@ -429,6 +472,7 @@ private fun PreviewReview() { WearPreview { Content( uiState = SendUiState(step = PreviewReviewStep, isWalletReady = true), + isAmbient = false, onAmountChange = {}, onAmountConfirm = {}, onHoldComplete = {}, @@ -443,6 +487,37 @@ private fun PreviewReviewOffline() { WearPreview { Content( uiState = SendUiState(step = PreviewReviewStep, isOffline = true), + isAmbient = false, + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewReviewConnecting() { + WearPreview { + Content( + uiState = SendUiState(step = PreviewReviewStep), + isAmbient = false, + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewAmbient() { + WearPreview { + Content( + uiState = SendUiState(step = PreviewReviewStep, isWalletReady = true), + isAmbient = true, onAmountChange = {}, onAmountConfirm = {}, onHoldComplete = {}, @@ -457,6 +532,7 @@ private fun PreviewAmount() { WearPreview { Content( uiState = SendUiState(step = SendStep.Amount(minSats = 1uL, maxSats = 100_000uL), amountText = "2100"), + isAmbient = false, onAmountChange = {}, onAmountConfirm = {}, onHoldComplete = {}, @@ -471,6 +547,7 @@ private fun PreviewSending() { WearPreview { Content( uiState = SendUiState(step = SendStep.Sending(isWaiting = true)), + isAmbient = false, onAmountChange = {}, onAmountConfirm = {}, onHoldComplete = {}, @@ -485,6 +562,7 @@ private fun PreviewSent() { WearPreview { Content( uiState = SendUiState(step = SendStep.Done(SendResult.Sent, PreviewBitcoin)), + isAmbient = false, onAmountChange = {}, onAmountConfirm = {}, onHoldComplete = {}, @@ -499,6 +577,7 @@ private fun PreviewFailed() { WearPreview { Content( uiState = SendUiState(step = SendStep.Failed(SendFailure.OwnInvoice)), + isAmbient = false, onAmountChange = {}, onAmountConfirm = {}, onHoldComplete = {}, diff --git a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt index 0d54aad884..9befd24812 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt @@ -9,23 +9,15 @@ class LaunchRequestTest { @Test fun `a payment link asks for a send of the whole link`() { for (link in listOf("lightning:lnbcrt1abc", "BITCOIN:bcrt1q?lightning=lnbcrt1abc", "spark:sprt1abc")) { - assertEquals(LaunchRequest.Send(link), LaunchRequest.from(Intent.ACTION_VIEW, link, open = null)) + assertEquals(LaunchRequest.Send(link), LaunchRequest.from(Intent.ACTION_VIEW, link)) } } - @Test - fun `the tile's extra asks for the receive QR`() { - assertEquals( - LaunchRequest.Receive, - LaunchRequest.from(Intent.ACTION_MAIN, data = null, open = LaunchRequest.OPEN_RECEIVE), - ) - } - @Test fun `a plain launch or another link asks for nothing`() { - assertNull(LaunchRequest.from(Intent.ACTION_MAIN, data = null, open = null)) - assertNull(LaunchRequest.from(Intent.ACTION_VIEW, data = "https://bitkit.to", open = null)) - assertNull(LaunchRequest.from(Intent.ACTION_VIEW, data = "lnbcrt1abc", open = null)) - assertNull(LaunchRequest.from(Intent.ACTION_SEND, data = "lightning:lnbcrt1abc", open = null)) + assertNull(LaunchRequest.from(Intent.ACTION_MAIN, data = null)) + assertNull(LaunchRequest.from(Intent.ACTION_VIEW, data = "https://bitkit.to")) + assertNull(LaunchRequest.from(Intent.ACTION_VIEW, data = "lnbcrt1abc")) + assertNull(LaunchRequest.from(Intent.ACTION_SEND, data = "lightning:lnbcrt1abc")) } } diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt index 82e5eab92e..b65c181b5e 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt @@ -103,6 +103,47 @@ class ReceiveViewModelTest : BaseUnitTest() { verify(paymentsRepo, times(2)).createInvoice() } + @Test + fun `the invoice stays on screen until its replacement exists`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + walletState.update { it.copy(status = WalletStatus.Offline) } + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice("lnbcrt1next"))) + + testScheduler.advanceTimeBy(LIFETIME.seconds - ReceiveViewModel.EXPIRY_MARGIN + 1.seconds) + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + + walletState.update { it.copy(status = WalletStatus.Ready) } + assertEquals("LNBCRT1NEXT", sut.uiState.value.qrContent) + } + + @Test + fun `an invoice that expires before the wallet is ready again leaves the screen`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + walletState.update { it.copy(status = WalletStatus.Offline) } + + testScheduler.advanceTimeBy(LIFETIME.seconds + 1.seconds) + + assertNull(sut.uiState.value.qrContent) + assertTrue(sut.uiState.value.isLoading) + } + + @Test + fun `an invoice the watch's clock takes for expired still shows for a moment`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice(lifetime = 0))) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + createSut() + + testScheduler.advanceTimeBy(ReceiveViewModel.MIN_LIFETIME - 1.seconds) + verify(paymentsRepo, times(1)).createInvoice() + + testScheduler.advanceTimeBy(2.seconds) + verify(paymentsRepo, times(2)).createInvoice() + } + @Test fun `a failed invoice shows the error until retried`() = test { whenever(paymentsRepo.createInvoice()).thenReturn(Result.failure(ReceiveError.NotReady())) @@ -119,7 +160,8 @@ class ReceiveViewModelTest : BaseUnitTest() { assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) } - private fun invoice() = ReceiveInvoice(BOLT11, PAYMENT_HASH, (NOW + LIFETIME).toULong()) + private fun invoice(bolt11: String = BOLT11, lifetime: Long = LIFETIME) = + ReceiveInvoice(bolt11, PAYMENT_HASH, (NOW + lifetime).toULong()) private fun payment(amountSats: ULong) = WatchPayment( id = "receipt", From 7d163df61117b8df7c9192da98361e8c295c3162 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 02:56:10 -0300 Subject: [PATCH 13/33] docs: update wear payments docs and journeys for review fixes Co-Authored-By: Claude Fable 5.2 --- docs/wear.md | 78 +++++++++++++++------ journeys/wear/README.md | 1 + journeys/wear/activity-list.xml | 10 ++- journeys/wear/receive-paid.xml | 9 ++- journeys/wear/receive-qr.xml | 12 ++-- journeys/wear/send-ambient-hides-amount.xml | 23 ++++++ journeys/wear/send-own-invoice-guard.xml | 5 +- 7 files changed, 103 insertions(+), 35 deletions(-) create mode 100644 journeys/wear/send-ambient-hides-amount.xml diff --git a/docs/wear.md b/docs/wear.md index 6efa21253f..f83cf514da 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -157,15 +157,17 @@ On-screen copy stays short: a title or one line of at most about six words per s screen (1/√2 of its width). Each module is one bitmap pixel scaled up without smoothing (zxing, as on the phone). While the QR shows, the screen stays on at full brightness; both end when it leaves. The invoice is made once the wallet is ready, under the loading ring; a failure shows one line and a retry (`WatchReceiveError`, - `WatchReceiveRetry`). An invoice is replaced by a new one a minute before it expires. Paid, the QR turns into a + `WatchReceiveRetry`). An invoice is replaced by a new one a minute before it expires, and it stays on screen until + the new one exists; when the wallet is not ready by then, the loading ring takes its place as it expires. An + invoice shows for at least 30 s, also when the watch's clock runs ahead. Paid, the QR turns into a check with the amount (`WatchReceivePaid`, `WatchReceivePaidAmount`) and a firm click (the `LongPress` haptic), unlike the confirm pattern that ends a send; a tap on the check shows a new invoice. In ambient mode the QR is replaced by a dimmed QR icon (`WatchReceiveHidden`). Debug builds log each invoice shown (`Showing invoice`), which is how the journeys read it. - **Send.** There is no Send page or button. A `lightning:`, `bitcoin:` or `spark:` link opens the app (`MainActivity` is `singleTop`, so a link reaches the open app) and the send flow above Home; without a wallet, - or during the restore, the link is dropped. The flow waits for the wallet to be ready (the loading ring, with - "Offline" while it is offline), reads the input and prices the send (see Payments), all before the hold. An input + during the restore, or while a send is under way, the link is dropped. The flow waits for the wallet to be ready + (the loading ring, with "Offline" while it is offline), reads the input and prices the send (see Payments), all before the hold. An input without an amount, an amountless invoice, a Spark address or an LNURL with a range, gets a minimal amount entry (the number keyboard, the LNURL range below it); Receive never has one. - Review: the amount in the balance's large style, fiat below in the small style, the fee only when it is at @@ -173,22 +175,30 @@ On-screen copy stays short: a title or one line of at most about six words per s button, "Hold to pay" (`WatchSendHold`). - Hold to pay: holding the button fills a ring around the bezel (`HoldToPayRing`, the geometry of `BezelLoading`) over 1.2 s, with a light tick (`SegmentTick`) at each quarter and the confirm haptic at the end, and only then - the payment goes out. Releasing early empties the ring; a tap never pays. Offline, or with the wallet not ready, - the button is disabled with the line "Offline". `PaymentsRepo.skipConfirmation` is asked before the hold; it is - always false until QuickPay (PR 3). + the payment goes out. Releasing early empties the ring; a tap never pays. Offline, the button is disabled with + the line "Offline"; while the wallet connects, locks or pauses, it is disabled under the loading ring. + `PaymentsRepo.skipConfirmation` is asked before the hold; it is always false until QuickPay (PR 3). + - Screen readers: a screen reader's wearer cannot hold, and the button's click pays nothing, so the button + offers "Pay" as a custom accessibility action, picked from the actions menu. The Receive button reads + "Receive". + - Ambient: the amount entry, the review and the result are replaced by a dimmed bolt (`WatchSendHidden`), so + the always-on screen shows no amount; the hold starts over when the watch wakes. - Sending: the loading ring, with "Waiting for network" after 3 s. The screen stays on and the flow cannot be swiped away or left with Back while the send runs. - Result: sent shows a check, "Sent" and the amount with the confirm haptic, and closes after 2 s. A payment that - did not settle in time shows a clock and "Pending"; an outcome Spark could not report shows "Check activity", - never a failure; both close after 3 s. A refusal or a failure shows a cross, one line of at most four words and + did not settle in time, or one that was already under way, from the watch or the phone, shows a clock and + "Pending"; an outcome Spark could not report shows "Check activity", never a failure; both close after 3 s. The + amount is the one Spark paid. A refusal or a failure shows a cross, one line of at most four words and an OK button (`WatchSendError`, `WatchSendClose`), with the reject haptic. Insufficient funds, an expired or unreadable invoice and an own invoice end there before any hold. - **Activity.** The Activity page lists the newest 20 payments from Spark's local list: a direction icon (or a clock for pending, a cross for failed), the amount with its sign and how long ago (`WatchActivityItem-0` onwards). It is read when Spark connects and after every payment or sync, and the last list stays while Spark is - disconnected. A tap opens the detail: the amount, the fee of a send, the date and time and the status - (`WatchActivityDetailAmount`, `…Fee`, `…Time`, `…Status`); Spark's list carries no payee or description. With no - payments it shows a dimmed icon and "No activity" (`WatchActivityEmpty`). Ambient mode hides the amounts. + disconnected, with its times counted again every minute. A tap opens the detail: the amount, the fee of a send, the + date and time and the status (`WatchActivityDetailAmount`, `…Fee`, `…Time`, `…Status`); Spark's list carries no payee or description. With no + payments it shows a dimmed icon and "No activity" (`WatchActivityEmpty`). A detail whose payment the list does not + hold, while it loads or after newer payments pushed it out, shows the dimmed icon (`WatchActivityDetailMissing`). + Ambient mode hides the amounts. - **Settings.** A short list of icon rows: About and Remove wallet. The unit has no setting: tapping the balance is the only way to switch it, and the choice is kept in the settings store across restarts. Remove wallet asks with a one-line title and the two round ✕/✓ buttons. @@ -221,10 +231,13 @@ in any other state. - **Pricing.** Before the hold to pay, a send is priced by Spark and checked: the amount (an amountless invoice and a Spark address need one, an LNURL amount has to be in the service's range), expiry, the self-send guard, and the balance against the amount plus its fee. The invoice an LNURL service returns has to be for exactly the - amount asked. -- **Sending.** The send call cannot be cancelled by the screen that started it, and one send runs at a time. It - returns when Spark has the payment; the result then waits up to a minute for it to settle and reports it as - pending after that. The send screen keeps the screen on, so the app stays on screen and connected while it waits. + amount asked, to the millisat as Spark reads it. +- **Sending.** A send runs in the repository's own scope, so the screen that started it cannot cancel it, also not + by closing, and one send runs at a time. An invoice's send first syncs with Spark, for up to 20 s, and is + refused when the sync does not reach Spark. The call returns when Spark has the payment; a call that stalls for + a minute ends as an unknown outcome, and nothing else is sent until Spark returns that call. The result then waits + up to a minute for the payment to settle and reports it as pending after that. A lock, a pause or a wipe waits up to 10 s for a send Spark is taking before it + disconnects. The send screen keeps the screen on, so the app stays on screen and connected while it waits. **Known gap:** a wearer who leaves the app during that wait pauses the wallet 10 s later (see Background); the settlement is then not seen and the send reports pending after the minute, although it may have completed. The activity list shows the real state once the app is back. @@ -233,12 +246,31 @@ in any other state. - **Paying once.** An invoice is sent under an idempotency key derived from the wallet seed, the payment hash and the attempt number (`SparkSendKey`, the same derivation as the phone and iOS). Spark makes one transfer per key, so the same invoice sent from the watch and the phone, or twice from the watch, is paid once. Before each send - Spark's payment list is read: an invoice it shows paid or pending is not sent again, and each attempt it shows - failed moves the send to the next key. A list that cannot be read refuses the send. The watch keeps no record of - its own; Spark's list is the record. -- **Unknown outcome.** When the send call fails after Spark may have taken the payment and Spark's list does not - show it, the result is "unknown", never "failed". The activity list tells once Spark lists it, and sending the - invoice again cannot pay twice. + the wallet syncs and Spark's payment list is read: an invoice it shows paid or pending is not sent again, and + each attempt it shows failed moves the send to the next key. A sync that does not reach Spark, or a list that + cannot be read, refuses the send. +- **Spark addresses.** A Spark address has no payment hash to derive a key from, so its transfer goes out under a + random key. `UncertainSendStore`, in the settings file the wipe clears, notes every send before it goes out and + drops it once Spark shows its payment or refuses it unsent. A transfer whose outcome was never learned, also + because the app was closed during it, keeps its key there: the next send to the same address syncs and asks + Spark's list. A transfer the list shows completed is not sent again ("Already paid", once), one it shows pending + is "Pending", one it shows failed makes way for a new key, and one it does not show goes out again under the + same key, which pays once. Without a sync that reaches Spark, nothing is sent to that address. +- **Unknown outcome.** When the send call fails or stalls after Spark may have taken the payment and Spark's list + does not show it, the result is "unknown", never "failed". The activity list tells once Spark lists it, and + sending the same request again from the watch goes out under the same key, so it cannot pay twice. A refusal + (expired, not enough funds) that follows an attempt of unknown outcome under the same key is "unknown" too, also + after the app was closed: the earlier attempt may have paid. An invoice's note is kept until a day after the + invoice expired. +- **Known gap: the phone's attempts.** The phone picks an invoice's attempt number from its own record of sends + plus Spark's list; the watch has Spark's list alone and cannot read the phone's record until the two are paired + (PR 4). The two agree whenever the watch's synced list shows the phone's sends, which is why a send needs a sync + that reached Spark. Should Spark's operators not report an attempt of the phone, the watch can derive another + attempt number than the phone: when the phone's attempt failed before it reached the operators and its next + attempt is in flight, unseen by the watch's sync, the watch's send under the first key is a second payment of + the invoice. The same holds the other way round for a send of unknown outcome on the watch that the phone's list + does not show. A transfer to a Spark address has no shared key at all: the phone and the watch each pay it when + asked. Pairing closes both by sharing the send records. - **QuickPay.** `PaymentsRepo.skipConfirmation` is the one place that decides whether a send skips the hold to pay. It is always false until the watch has QuickPay settings (PR 3). @@ -252,7 +284,9 @@ refuse with "Cannot Pay Own Invoice". Two checks recognise such a request: channel id 17592187092992000001 (`16000000x16000000x1`) when the wallet that made it had the SDK's `preferSparkOverLightning` on. - **Payment hash.** Each device remembers the payment hashes of the invoices it created on Spark until they - expire, at most 200, and refuses to pay them. The watch keeps them in its settings file, which the wallet's wipe + expire, at most 200 on the watch and 2 000 on the phone, whose invoices live a day, and refuses to pay them. An + invoice that cannot be remembered is not handed out, and the phone refuses an invoice while it cannot read the + ones it remembers. The watch keeps them in its settings file, which the wallet's wipe clears (`OwnInvoiceStore`); the phone keeps them in its cache store (`sparkOwnInvoices`). The second check exists because Bitkit creates its invoices with `preferSparkOverLightning` off: such an invoice diff --git a/journeys/wear/README.md b/journeys/wear/README.md index ed1698a956..04147a2cb9 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -117,6 +117,7 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `receive-paid.xml` | local | no, it funds the wallet with 50 000 sats | | `send-deeplink-bolt11.xml` | local | yes, 2 000 sats | | `send-hold-cancel.xml` | local | yes, 2 000 sats | +| `send-ambient-hides-amount.xml` | local | yes, 2 000 sats | | `send-insufficient.xml` | local | yes, less than 10 000 000 sats | | `send-own-invoice-guard.xml` | local | yes, any balance above 0 | | `activity-list.xml` | local | yes, after `receive-paid.xml` and `send-deeplink-bolt11.xml` | diff --git a/journeys/wear/activity-list.xml b/journeys/wear/activity-list.xml index 10bd673e18..58b7dad192 100644 --- a/journeys/wear/activity-list.xml +++ b/journeys/wear/activity-list.xml @@ -8,13 +8,17 @@ with the loading ring stopped. Gestures are written for the 454 px screen. - Swipe the pager left twice: `adb shell input swipe 400 227 60 227 300`, wait 1 s, and again + Swipe the pager left to Receive: `adb shell input swipe 400 227 60 227 300` + Wait up to 5 s until "WatchReceiveOpen" is listed + Swipe the pager left to Activity: `adb shell input swipe 400 227 60 227 300` Wait up to 10 s until "WatchActivityItem-0" is listed - Verify "WatchActivityItem-0" shows "- ₿ 1 000" and a relative time such as "1 min. ago" + Verify "WatchActivityItem-0" shows "- ₿ 1 000" + Verify "WatchActivityItem-0" shows a relative time such as "1 min. ago" Verify "WatchActivityItem-1" shows "+ ₿ 50 000" Tap "WatchActivityItem-0" Verify "WatchActivityDetailAmount" reads "1 000" - Verify "WatchActivityDetailStatus" reads "Completed" and "WatchActivityDetailTime" shows today's date + Verify "WatchActivityDetailStatus" reads "Completed" + Verify "WatchActivityDetailTime" shows today's date Swipe to dismiss from the left edge: `adb shell input swipe 20 227 400 227 300` Verify "WatchActivityItem-0" is listed again diff --git a/journeys/wear/receive-paid.xml b/journeys/wear/receive-paid.xml index 4608234e12..b28c58af0c 100644 --- a/journeys/wear/receive-paid.xml +++ b/journeys/wear/receive-paid.xml @@ -9,12 +9,15 @@ Swipe the pager left once: `adb shell input swipe 400 227 60 227 300` - Tap "WatchReceiveOpen" and wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) + Tap "WatchReceiveOpen" + Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) Read the invoice from the log as in README › Reading the receive invoice and note it as <invoice> Run `../bitkit-docker/spark pay <invoice> 50000` from this repo's parent checkout Wait up to 20 s until "WatchReceivePaid" is listed Verify "WatchReceivePaidAmount" reads "50 000" - Tap "WatchReceivePaid" and wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" - Read the invoice from the log again and verify it differs from <invoice> + Tap "WatchReceivePaid" + Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" + Read the invoice from the log again as <next> + Verify <next> differs from <invoice> diff --git a/journeys/wear/receive-qr.xml b/journeys/wear/receive-qr.xml index 5d212bd43d..0d4070ffc2 100644 --- a/journeys/wear/receive-qr.xml +++ b/journeys/wear/receive-qr.xml @@ -11,12 +11,14 @@ Swipe the pager left once: `adb shell input swipe 400 227 60 227 300` Verify the Receive page: "WatchReceiveOpen" is listed - Tap "WatchReceiveOpen" and wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) + Tap "WatchReceiveOpen" + Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) Verify from a screenshot that a black-on-white QR code fills the middle of the screen Read the invoice from the log as in README › Reading the receive invoice and verify it starts with "lnbcrt" - Run `adb shell input keyevent KEYCODE_SLEEP` and wait 3 s - Verify "WatchReceiveHidden" is listed with the content-desc "QR hidden" - Run `adb shell input keyevent KEYCODE_WAKEUP` and wait 2 s - Verify "WatchReceiveHidden" is not listed and a screenshot shows the QR code again + Run `adb shell input keyevent KEYCODE_SLEEP` + Wait up to 5 s until "WatchReceiveHidden" is listed with the content-desc "QR hidden" + Run `adb shell input keyevent KEYCODE_WAKEUP` + Wait up to 5 s until "WatchReceiveHidden" is not listed + Verify from a screenshot that the QR code shows again diff --git a/journeys/wear/send-ambient-hides-amount.xml b/journeys/wear/send-ambient-hides-amount.xml new file mode 100644 index 0000000000..8efe35c65f --- /dev/null +++ b/journeys/wear/send-ambient-hides-amount.xml @@ -0,0 +1,23 @@ + + + Ambient mode hides the amount of a send under review behind a dimmed bolt, and waking the watch shows the review + again with nothing paid. Emulator and physical watch. + + Precondition: Restored wallet on the local ./spark stack with at least 2 000 sats, see + journeys/wear/README.md › Local ./spark stack, with the app open on the Balance page, the loading ring stopped + and the always-on screen on (README › Watch gestures). + + + Run `../bitkit-docker/spark invoice 1000` and note the BOLT11 invoice it prints as <invoice> + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` + Wait up to 10 s until "WatchSendHold" is listed + Verify "WatchSendAmount" reads "1 000" + Run `adb shell input keyevent KEYCODE_SLEEP` + Wait up to 5 s until "WatchSendHidden" is listed + Verify "WatchSendAmount" is not listed + Verify "WatchSendHold" is not listed + Run `adb shell input keyevent KEYCODE_WAKEUP` + Wait up to 5 s until "WatchSendAmount" is listed + Verify "WatchSendSending" is not listed + + diff --git a/journeys/wear/send-own-invoice-guard.xml b/journeys/wear/send-own-invoice-guard.xml index 0c851676c2..ab4fa92e0f 100644 --- a/journeys/wear/send-own-invoice-guard.xml +++ b/journeys/wear/send-own-invoice-guard.xml @@ -10,13 +10,14 @@ Swipe the pager left once: `adb shell input swipe 400 227 60 227 300` - Tap "WatchReceiveOpen" and wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) + Tap "WatchReceiveOpen" + Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) Read the invoice from the log as in README › Reading the receive invoice and note it as <invoice> Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` Wait up to 10 s until "WatchSendError" is listed Verify "WatchSendError" reads "Can't pay own invoice" Verify "WatchSendHold" is not listed Tap "WatchSendClose" - Verify the Balance page: "WatchHomeBalance" is listed + Verify Home is back on the Receive page it was left on: "WatchReceiveOpen" is listed From cf84985ac339839612ede31e7925a006c2d656ca Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 03:28:12 -0300 Subject: [PATCH 14/33] fix: tag the dropped own spark invoices log Co-Authored-By: Claude Fable 5.2 --- app/src/main/java/to/bitkit/data/CacheStore.kt | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 00a5e40296..2dc9ffbd6c 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -57,6 +57,10 @@ class CacheStore internal constructor( private val store: DataStore, private val clock: Clock = Clock.System, ) { + companion object { + private const val TAG = "CacheStore" + } + @Inject constructor(@ApplicationContext context: Context) : this(context.appCacheDataStore) @@ -179,15 +183,15 @@ class CacheStore internal constructor( * device's invoices are added the same way. */ suspend fun addSparkOwnInvoice(paymentHash: String, expiresAt: Long, now: Long) { + var dropped = 0 store.updateData { data -> val unexpired = (data.sparkOwnInvoices + (paymentHash.lowercase() to expiresAt)).entries .filter { it.value > now } - if (unexpired.size > MAX_SPARK_OWN_INVOICES) { - Logger.warn("Dropped '${unexpired.size - MAX_SPARK_OWN_INVOICES}' unexpired own Spark invoices") - } + dropped = (unexpired.size - MAX_SPARK_OWN_INVOICES).coerceAtLeast(0) val invoices = unexpired.sortedByDescending { it.value }.take(MAX_SPARK_OWN_INVOICES) data.copy(sparkOwnInvoices = invoices.associate { it.key to it.value }) } + if (dropped > 0) Logger.warn("Dropped '$dropped' unexpired own Spark invoices", context = TAG) } /** Whether [paymentHash] is a Spark invoice of this wallet that has not expired at [now], in epoch seconds. */ From b9e7055b57f28f9741ab540e15c9d35abdfd1247 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 03:28:13 -0300 Subject: [PATCH 15/33] fix: tell a busy wear wallet from a pending send, harden receive and sends Co-Authored-By: Claude Fable 5.2 --- .../to/bitkit/wear/data/UncertainSendStore.kt | 29 ++-- .../java/to/bitkit/wear/models/Payments.kt | 19 ++- .../bitkit/wear/repositories/PaymentsRepo.kt | 147 ++++++++++++------ .../bitkit/wear/services/WatchSparkService.kt | 18 ++- .../ui/screens/activity/ActivityScreen.kt | 28 +++- .../ui/screens/receive/ReceiveQrScreen.kt | 72 ++++++++- .../ui/screens/receive/ReceiveViewModel.kt | 87 ++++++++--- .../bitkit/wear/ui/screens/send/SendScreen.kt | 18 ++- .../wear/ui/screens/send/SendViewModel.kt | 7 +- wear/src/main/res/values-ar/strings.xml | 2 + wear/src/main/res/values-b+es+419/strings.xml | 2 + wear/src/main/res/values-ca/strings.xml | 2 + wear/src/main/res/values-cs/strings.xml | 2 + wear/src/main/res/values-de/strings.xml | 2 + wear/src/main/res/values-el/strings.xml | 2 + wear/src/main/res/values-es-rES/strings.xml | 2 + wear/src/main/res/values-es/strings.xml | 2 + wear/src/main/res/values-fr/strings.xml | 2 + wear/src/main/res/values-it/strings.xml | 2 + wear/src/main/res/values-nl/strings.xml | 2 + wear/src/main/res/values-pl/strings.xml | 2 + wear/src/main/res/values-pt-rBR/strings.xml | 2 + wear/src/main/res/values-pt/strings.xml | 2 + wear/src/main/res/values-ru/strings.xml | 2 + wear/src/main/res/values/strings.xml | 2 + .../wear/data/UncertainSendStoreTest.kt | 50 +++--- .../wear/repositories/PaymentsRepoTest.kt | 124 ++++++++++++++- .../wear/services/WatchSparkServiceTest.kt | 18 +++ .../screens/activity/ActivityNowSecsTest.kt | 51 ++++++ .../screens/receive/ReceiveViewModelTest.kt | 94 ++++++++++- .../wear/ui/screens/send/SendReviewTest.kt | 90 +++++++++++ .../wear/ui/screens/send/SendViewModelTest.kt | 14 +- 32 files changed, 756 insertions(+), 142 deletions(-) create mode 100644 wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityNowSecsTest.kt create mode 100644 wear/src/test/java/to/bitkit/wear/ui/screens/send/SendReviewTest.kt diff --git a/wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt b/wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt index 4f7ab445fe..19f69e6795 100644 --- a/wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt +++ b/wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt @@ -9,12 +9,13 @@ import javax.inject.Inject import javax.inject.Singleton /** - * A send this watch handed to Spark under the idempotency [key], whose outcome it has not learned. [sparkAddress] is - * set for a transfer to a Spark address, and [expiresAtSecs] for an invoice: its expiry in epoch seconds. + * A send this watch handed to Spark under the idempotency [key], whose outcome it has not learned. [sparkPayee] is + * set for a transfer to a Spark address: the Spark identity public key the address encodes, in hex, which is the + * same for every spelling of a wallet's address. [expiresAtSecs] is set for an invoice: its expiry in epoch seconds. */ data class UncertainSend( val key: String, - val sparkAddress: String? = null, + val sparkPayee: String? = null, val expiresAtSecs: ULong? = null, ) @@ -30,8 +31,11 @@ interface UncertainSendStore { /** Drops the send under [key], whose outcome is known. */ suspend fun settle(key: String) - /** The key of the noted transfer to [sparkAddress], in either case, or null when there is none. */ - suspend fun transferKey(sparkAddress: String): String? + /** + * The keys of the noted transfers to the wallet with the identity key [sparkPayee], in either case, the newest + * first. More than one is noted only when an earlier one could not be dropped. + */ + suspend fun transferKeys(sparkPayee: String): List } /** @@ -68,7 +72,7 @@ class SettingsUncertainSendStore internal constructor( if (wasNoted) return@edit prefs[key] = sends .filter { it.send.expiresAtSecs?.let { expiresAt -> expiresAt + EXPIRED_KEPT_SECS > now } != false } - .plus(Entry(send.copy(sparkAddress = send.sparkAddress?.lowercase()), now)) + .plus(Entry(send.copy(sparkPayee = send.sparkPayee?.lowercase()), now)) .sortedByDescending { it.startedAtSecs } .take(MAX_SENDS) .mapTo(HashSet()) { it.encode() } @@ -84,15 +88,18 @@ class SettingsUncertainSendStore internal constructor( } } - override suspend fun transferKey(sparkAddress: String): String? { - val address = sparkAddress.lowercase() - return decode(dataStore.data.first()[key]).firstOrNull { it.send.sparkAddress == address }?.send?.key + override suspend fun transferKeys(sparkPayee: String): List { + val payee = sparkPayee.lowercase() + return decode(dataStore.data.first()[key]) + .filter { it.send.sparkPayee == payee } + .sortedByDescending { it.startedAtSecs } + .map { it.send.key } } private class Entry(val send: UncertainSend, val startedAtSecs: ULong) { fun encode(): String = listOf( send.key, - send.sparkAddress.orEmpty(), + send.sparkPayee.orEmpty(), send.expiresAtSecs?.toString().orEmpty(), startedAtSecs.toString(), ).joinToString(SEPARATOR.toString()) @@ -103,7 +110,7 @@ class SettingsUncertainSendStore internal constructor( val startedAt = fields[3].toULongOrNull() ?: return@mapNotNull null val send = UncertainSend( key = fields[0], - sparkAddress = fields[1].takeIf { it.isNotEmpty() }, + sparkPayee = fields[1].takeIf { it.isNotEmpty() }, expiresAtSecs = fields[2].toULongOrNull(), ) Entry(send, startedAt) diff --git a/wear/src/main/java/to/bitkit/wear/models/Payments.kt b/wear/src/main/java/to/bitkit/wear/models/Payments.kt index e0ccf599e8..1910b0ceb0 100644 --- a/wear/src/main/java/to/bitkit/wear/models/Payments.kt +++ b/wear/src/main/java/to/bitkit/wear/models/Payments.kt @@ -64,11 +64,14 @@ class PreparedSend internal constructor( internal val paymentHash: String?, /** When the invoice expires, in epoch seconds, or null for a Spark address. */ internal val expiresAtSecs: ULong?, - /** The Spark address a transfer pays, or null for an invoice. */ - internal val sparkAddress: String?, /** - * The idempotency key a transfer to [sparkAddress] goes out under, made once so a repeated send pays once, - * unless an earlier transfer to the address is still in doubt: then its key is used again. + * The Spark identity public key, in hex, of the wallet a transfer to a Spark address pays, or null for an + * invoice. Every spelling of a wallet's address encodes the same key. + */ + internal val sparkPayee: String?, + /** + * The idempotency key a transfer to [sparkPayee] goes out under, made once so a repeated send pays once, + * unless an earlier transfer to that wallet is still in doubt: then its key is used again. */ internal val transferKey: String, ) { @@ -119,9 +122,15 @@ sealed class SendError(message: String, cause: Throwable? = null) : AppError(mes /** This wallet already paid the invoice, or an earlier transfer to the Spark address went through after all. */ class AlreadyPaid : SendError("The request is already paid") - /** A send of this request is still under way, from the watch or the phone. */ + /** A send of this request is still under way, from the watch or the phone: Spark lists it as pending. */ class InFlight : SendError("A payment of this request is under way") + /** + * Another send holds the wallet: one that is running, or one whose call Spark has not returned yet. Nothing of + * this request was sent, and it can be tried again once that send is over. + */ + class Busy : SendError("The wallet is busy with another payment") + /** Spark refused or failed the payment. */ class Failed(cause: Throwable? = null) : SendError("The payment failed", cause) diff --git a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt index 64c6efb282..2aeda71a52 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -45,6 +45,7 @@ import to.bitkit.wear.models.SendRequest import to.bitkit.wear.models.WatchPayment import to.bitkit.wear.services.InputDecoder import to.bitkit.wear.services.SelfSendGuard +import to.bitkit.wear.services.SparkError import to.bitkit.wear.services.WatchSparkService import to.bitkit.wear.utils.Logger import java.net.URI @@ -255,9 +256,16 @@ class PaymentsRepo @Inject constructor( } is SendRequest.SparkAddress -> { ensureAmount(amount, 1uL, MAX_SATS) + val sparkPayee = sparkPayee(request.address) // Told before the review, so the wearer never holds to pay a transfer that already went out. - earlierTransferKey(request.address) - prepare(request.address, amount, isAmountInRequest = false, request.payee) + earlierTransferKey(sparkPayee) + prepare( + paymentRequest = request.address, + amountSats = amount, + isAmountInRequest = false, + payee = request.payee, + sparkPayee = sparkPayee, + ) } } }.onFailure { @@ -286,6 +294,7 @@ class PaymentsRepo @Inject constructor( isAmountInRequest: Boolean, payee: String?, exactMsats: ULong? = null, + sparkPayee: String? = null, ): PreparedSend { ensureNotOwn(paymentRequest) val response = runSuspendCatching { @@ -294,7 +303,11 @@ class PaymentsRepo @Inject constructor( val method = response.paymentMethod val (feeSats, invoice) = when (method) { is SendPaymentMethod.Bolt11Invoice -> method.feeSats() to method.invoiceDetails - is SendPaymentMethod.SparkAddress -> method.fee.toLong().toULong() to null + is SendPaymentMethod.SparkAddress -> { + // A transfer is only sent with the identity it is noted under. + if (sparkPayee == null) throw SendError.Invalid() + method.fee.toLong().toULong() to null + } else -> throw SendError.Unsupported() } // Spark pays what the invoice asks to the millisat, which whole sats can hide by up to 999 msat. @@ -310,7 +323,7 @@ class PaymentsRepo @Inject constructor( response = response, paymentHash = invoice?.paymentHash, expiresAtSecs = invoice?.expiresAt, - sparkAddress = paymentRequest.takeIf { invoice == null }, + sparkPayee = sparkPayee.takeIf { invoice == null }, transferKey = UUID.randomUUID().toString(), ) } @@ -320,12 +333,21 @@ class PaymentsRepo @Inject constructor( * A request the SDK cannot read, or a guard that cannot tell, refuses it too. */ private suspend fun ensureNotOwn(paymentRequest: String) { - val input = runSuspendCatching { sparkService.parse(paymentRequest) }.getOrElse { throw SendError.Invalid(it) } + val input = runSuspendCatching { sparkService.parse(paymentRequest) }.getOrElse { throw it.toInputError() } if (input !is InputType.Bolt11Invoice && input !is InputType.SparkAddress) throw SendError.Invalid() val isOwn = runSuspendCatching { selfSendGuard.isOwn(input) }.getOrElse { throw SendError.NotReady() } if (isOwn) throw SendError.OwnInvoice() } + /** + * The Spark identity public key the Spark [address] encodes, in lowercase hex. The `sp…` and the `spark…` + * spelling of one wallet's address give the same key, which is what an uncertain transfer is noted under. + */ + private suspend fun sparkPayee(address: String): String { + val input = runSuspendCatching { sparkService.parse(address) }.getOrElse { throw it.toInputError() } + return (input as? InputType.SparkAddress)?.v1?.identityPublicKey?.lowercase() ?: throw SendError.Invalid() + } + private fun SendPaymentMethod.Bolt11Invoice.feeSats(): ULong = sparkTransferFeeSats?.takeIf { sparkService.prefersSpark } ?: lightningFeeSats @@ -334,25 +356,27 @@ class PaymentsRepo @Inject constructor( * when Spark took it and it did not settle within [SETTLE_TIMEOUT]. The send does not run in the caller's scope: * a caller that goes away neither cancels it nor loses its bookkeeping. Fails with a [SendError]: * [SendError.NotReady], also when Spark cannot be reached to bring its list up to date, [SendError.AlreadyPaid], - * [SendError.InFlight] (also while another send runs, or Spark still holds the call of one that stalled), - * [SendError.Expired], [SendError.InsufficientBalance], [SendError.Failed], and [SendError.Unknown] when the - * payment may have gone out. + * [SendError.InFlight], [SendError.Busy] while another send runs or Spark still holds the call of one that + * stalled, [SendError.Expired], [SendError.InsufficientBalance], [SendError.Failed], and [SendError.Unknown] when + * the payment may have gone out. * * An invoice is sent under the idempotency key the phone derives for it too, so Spark pays it once however often * and from whichever device it is sent; each attempt Spark lists as failed moves to the next key. A Spark address - * has no such key, so the key of a transfer to it is kept in [UncertainSendStore] until its outcome is known, and - * a retry goes out under the same key. Every send is noted there before it goes out, so a refusal that follows an - * attempt of unknown outcome, also one the app was closed during, is never read as nothing sent. + * has no such key, so the key of a transfer to it is kept in [UncertainSendStore], under the identity key the + * address encodes, until its outcome is known, and a retry goes out under the same key. Every send is noted there + * before it goes out, so a refusal that follows an attempt of unknown outcome, also one the app was closed + * during, is never read as nothing sent. */ suspend fun send(prepared: PreparedSend): Result = sendScope.async { runSuspendCatching { - if (!sendMutex.tryLock()) throw SendError.InFlight() + // Another send holds the wallet: nothing of this request is sent, so it is not reported as under way. + if (!sendMutex.tryLock()) throw SendError.Busy() try { - if (sendCall?.isActive == true) throw SendError.InFlight() + if (sendCall?.isActive == true) throw SendError.Busy() if (!isReady()) throw SendError.NotReady() - val address = prepared.sparkAddress - val key = if (address != null) { - earlierTransferKey(address) ?: prepared.transferKey + val sparkPayee = prepared.sparkPayee + val key = if (sparkPayee != null) { + earlierTransferKey(sparkPayee) ?: prepared.transferKey } else { syncForSend() invoiceKey(checkNotNull(prepared.paymentHash)) @@ -394,31 +418,29 @@ class PaymentsRepo @Inject constructor( } /** - * The key a transfer to the Spark [address] has to go out under again, or null when a new key will do: no earlier - * transfer to the address is noted with an outcome never learned. When one is, Spark's synced list decides: a - * transfer it shows completed is not sent again ([SendError.AlreadyPaid], once, as the wearer was never told), - * one it shows pending is under way ([SendError.InFlight]), one it shows failed is over, and one it does not show - * goes out again under its key, which pays once. A store or a list that cannot be read refuses the send. + * The key a transfer to the wallet with the identity key [sparkPayee] has to go out under again, or null when a + * new key will do: no earlier transfer to it is noted with an outcome never learned. When one is, Spark's synced + * list decides: a transfer it shows completed is not sent again ([SendError.AlreadyPaid], once, as the wearer was + * never told), one it shows pending is under way ([SendError.InFlight]), one it shows failed is over, and one it + * does not show goes out again under its key, which pays once. Every noted transfer is asked about, so one that + * could not be dropped never hides another. A store or a list that cannot be read refuses the send. */ - private suspend fun earlierTransferKey(address: String): String? { - val earlier = runSuspendCatching { uncertainSendStore.transferKey(address) } + private suspend fun earlierTransferKey(sparkPayee: String): String? { + val earlier = runSuspendCatching { uncertainSendStore.transferKeys(sparkPayee) } .getOrElse { throw SendError.Failed(it) } - ?: return null + if (earlier.isEmpty()) return null syncForSend() - val listed = runSuspendCatching { sparkService.listPayments().firstOrNull { it.id == earlier } } + val listed = runSuspendCatching { sparkService.listPayments().filter { it.id in earlier } } .getOrElse { throw SendError.NotReady() } - return when (listed?.status) { - PaymentStatus.COMPLETED -> { - settle(earlier) - throw SendError.AlreadyPaid() - } - PaymentStatus.PENDING -> throw SendError.InFlight() - PaymentStatus.FAILED -> { - settle(earlier) - null - } - null -> earlier + .associate { it.id to it.status } + earlier.filter { listed[it] == PaymentStatus.FAILED }.forEach { settle(it) } + val completed = earlier.filter { listed[it] == PaymentStatus.COMPLETED } + if (completed.isNotEmpty()) { + completed.forEach { settle(it) } + throw SendError.AlreadyPaid() } + if (earlier.any { listed[it] == PaymentStatus.PENDING }) throw SendError.InFlight() + return earlier.firstOrNull { it !in listed } } /** Sends under [key] while already listening for the payment's outcome, which can arrive before the call ends. */ @@ -430,16 +452,7 @@ class PaymentsRepo @Inject constructor( .collect { payment -> settled.update { it + (payment.id to payment) } } } try { - // Noted before it goes out, so a send the app is closed during is known to be in doubt afterwards. - val wasUncertain = runSuspendCatching { - uncertainSendStore.begin(UncertainSend(key, prepared.sparkAddress, prepared.expiresAtSecs)) - }.getOrElse { throw SendError.Failed(it) } - // The SDK call cannot be cancelled, so it runs beside this wait, which gives up on a call that stalls. - val call = sendScope.async { runSuspendCatching { sparkService.send(prepared.response, key) } } - sendCall = call - val result = withTimeoutOrNull(SEND_TIMEOUT) { call.await() } - ?: Result.failure(SendError.Unknown()) - val sent = result.getOrElse { recoverSend(it, key, wasUncertain) } + val sent = sendNoted(prepared, key) // Spark lists the payment from here on, so the list tells its outcome. settle(key) val payment = if (sent.status == PaymentStatus.PENDING) { @@ -458,12 +471,41 @@ class PaymentsRepo @Inject constructor( } } + /** + * Notes the send under [key], hands it to Spark and returns the payment Spark made. The connection is held from + * the note on, so a lock or a pause does not disconnect between the note and the call. A wallet that was wiped + * or stopped being ready before the note was written sends nothing and leaves no note behind. + */ + private suspend fun sendNoted(prepared: PreparedSend, key: String): Payment { + sparkService.holdSend() + try { + // Noted before it goes out, so a send the app is closed during is known to be in doubt afterwards. + val wasUncertain = runSuspendCatching { + uncertainSendStore.begin(UncertainSend(key, prepared.sparkPayee, prepared.expiresAtSecs)) + }.getOrElse { throw SendError.Failed(it) } + // A wipe that ran meanwhile cleared the store before the note, which would outlive the wiped wallet. + if (!isReady() || sparkService.isWiping) { + if (!wasUncertain) settle(key) + throw SendError.NotReady() + } + // The SDK call cannot be cancelled, so it runs beside this wait, which gives up on a call that stalls. + val call = sendScope.async { runSuspendCatching { sparkService.send(prepared.response, key) } } + sendCall = call + val result = withTimeoutOrNull(SEND_TIMEOUT) { call.await() } + ?: Result.failure(SendError.Unknown()) + return result.getOrElse { recoverSend(it, key, wasUncertain) } + } finally { + sparkService.releaseSend() + } + } + /** * What a send that threw under [key] comes to. Spark's list decides first: a payment it shows under the key is * this send, also when an earlier attempt or the phone made it. Spark refuses an expired invoice and a short * balance before anything goes out, so such a refusal is final, unless an earlier attempt under the key has an - * unknown outcome ([wasUncertain]): the refusal can follow the transfer that attempt committed. Any other error - * can follow a committed transfer too, so it is [SendError.Unknown]. + * unknown outcome ([wasUncertain]): the refusal can follow the transfer that attempt committed. A wallet that was + * disconnected before the SDK got the call sent nothing either ([SendError.NotReady]). Any other error can follow + * a committed transfer too, so it is [SendError.Unknown]. */ private suspend fun recoverSend(error: Throwable, key: String, wasUncertain: Boolean): Payment { runSuspendCatching { sparkService.listPayments().firstOrNull { it.id == key } }.getOrNull()?.let { return it } @@ -472,6 +514,11 @@ class PaymentsRepo @Inject constructor( settle(key) throw error.toSendError() } + // Thrown by the service before it calls the SDK, so this attempt sent nothing; an earlier one keeps its note. + if (error is SparkError.NotConnected) { + if (!wasUncertain) settle(key) + throw SendError.NotReady() + } throw SendError.Unknown(error) } @@ -525,6 +572,10 @@ private fun Payment.toWatchPayment() = WatchPayment( private fun Throwable.isInvoiceExpired(): Boolean = this is SdkException.InvalidInput && v1.contains("invoice has expired", ignoreCase = true) +/** Why an input could not be read by Spark: a wallet that disconnected meanwhile is not an unreadable input. */ +private fun Throwable.toInputError(): SendError = + if (this is SparkError.NotConnected) SendError.NotReady() else SendError.Invalid(this) + private fun Throwable.toSendError(): SendError = when { this is SendError -> this isInvoiceExpired() -> SendError.Expired(this) diff --git a/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt b/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt index 5ced0d3721..efc378b6f5 100644 --- a/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt +++ b/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt @@ -134,7 +134,7 @@ class WatchSparkService @Inject constructor( @Volatile private var sendKeySecret: ByteArray? = null - /** How many [send] calls the SDK is running. */ + /** How many sends hold the connection: those between [holdSend] and [releaseSend], and running [send] calls. */ private val runningSends = MutableStateFlow(0) private val _events = MutableSharedFlow(extraBufferCapacity = 64) @@ -251,10 +251,10 @@ class WatchSparkService @Inject constructor( } /** - * Disconnects the SDK as one step that its caller cannot cancel, after waiting up to [SEND_GRACE] for a running - * [send] to return. A listener that cannot be removed does not stop the disconnect. When the disconnect itself - * fails, it throws and the SDK stays referenced, so the next [disconnect] reaches it again; a listener already - * removed is not removed twice. + * Disconnects the SDK as one step that its caller cannot cancel, after waiting up to [SEND_GRACE] for a send that + * holds the connection ([holdSend]) or runs in the SDK ([send]). A listener that cannot be removed does not stop + * the disconnect. When the disconnect itself fails, it throws and the SDK stays referenced, so the next + * [disconnect] reaches it again; a listener already removed is not removed twice. */ suspend fun disconnect() = withContext(NonCancellable) { withTimeoutOrNull(SEND_GRACE) { runningSends.first { it == 0 } } @@ -338,6 +338,14 @@ class WatchSparkService @Inject constructor( return SparkSendKey.key(secret, paymentHash, attempt) } + /** + * Holds the connection for a send that is about to go out, so a [disconnect] waits up to [SEND_GRACE] for it + * also before the SDK has the call. [releaseSend] must follow. + */ + fun holdSend() = runningSends.update { it + 1 } + + fun releaseSend() = runningSends.update { it - 1 } + /** * Sends [prepared] as one step that its caller cannot cancel, so a send is never dropped halfway. Spark makes * one payment per [idempotencyKey], a UUID that becomes the payment's id. diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt index 0970af523c..fe5ff61586 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt @@ -59,21 +59,33 @@ fun ActivityScreen( viewModel: ActivityViewModel = hiltViewModel(), ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() - // The relative times move on while the page stays open and Spark reports nothing new. - val nowSecs by produceState(uiState.nowSecs, uiState.nowSecs) { - while (true) { - delay(RELATIVE_TIME_TICK) - value = Instant.now().epochSecond - } - } Content( - uiState = uiState.copy(nowSecs = nowSecs), + uiState = uiState.copy(nowSecs = rememberNowSecs(loadedSecs = uiState.nowSecs)), isAmbient = isAmbient(), onPaymentClick = onPaymentClick, modifier = modifier ) } +/** + * The time the relative times count from, in epoch seconds: when the list was read ([loadedSecs]), moved on by a + * tick of [clock] every minute, so the times also move while the page stays open and Spark reports nothing new. A + * list read after the last tick counts from its own time at once. + */ +@Composable +internal fun rememberNowSecs( + loadedSecs: Long, + clock: () -> Long = { Instant.now().epochSecond }, +): Long { + val tickSecs by produceState(initialValue = clock()) { + while (true) { + delay(RELATIVE_TIME_TICK) + value = clock() + } + } + return maxOf(tickSecs, loadedSecs) +} + @Composable private fun Content( uiState: ActivityUiState, diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt index eaa7549ef5..4e42bfd65c 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt @@ -1,5 +1,7 @@ package to.bitkit.wear.ui.screens.receive +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column @@ -8,9 +10,16 @@ import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource @@ -26,6 +35,7 @@ import androidx.wear.compose.material3.Icon import androidx.wear.compose.material3.IconButtonDefaults import androidx.wear.compose.material3.MaterialTheme import androidx.wear.compose.material3.Text +import kotlinx.coroutines.delay import to.bitkit.wear.R import to.bitkit.wear.ui.components.BezelLoading import to.bitkit.wear.ui.components.CenteredScreen @@ -38,6 +48,7 @@ import to.bitkit.wear.ui.components.isAmbient import to.bitkit.wear.ui.modifiers.clickableAlpha import to.bitkit.wear.ui.screens.home.DisplayAmount import to.bitkit.wear.ui.theme.Colors +import kotlin.time.Duration.Companion.minutes /** The QR's side as a share of the screen: the largest square inside the round screen (1/√2). */ private const val QR_SIZE_FRACTION = 0.707f @@ -48,9 +59,14 @@ private val MARK_SIZE = 56.dp /** The opacity of the QR icon that stands in for the hidden QR in ambient mode. */ private const val HIDDEN_ALPHA = 0.4f +/** How long the QR keeps the screen on at full brightness without a touch, before it rests. */ +internal val QR_AWAKE_LIMIT = 2.minutes + /** * The receive QR, as large as the round screen allows, at full brightness and with the screen kept on while it - * shows. Ambient mode hides it. A paid invoice turns into a check with the amount and its own haptic; a tap on the + * shows. After [QR_AWAKE_LIMIT] without a touch it rests: the QR hides behind a dimmed icon and the screen may turn + * off again, so a forgotten QR does not drain the battery; a tap, or waking the watch from ambient mode, shows it + * again. Ambient mode hides it. A paid invoice turns into a check with the amount and its own haptic; a tap on the * check makes a new invoice. */ @Composable @@ -65,9 +81,23 @@ fun ReceiveQrScreen( // A firm click, unlike the confirm pattern a send ends with, so the two never feel alike. if (isPaid) haptic.performHapticFeedback(HapticFeedbackType.LongPress) } + val isAmbient = isAmbient() + var isResting by remember { mutableStateOf(false) } + var touches by remember { mutableIntStateOf(0) } + val isQrShown = uiState.qrContent != null && !isPaid && !isAmbient && !isResting + LaunchedEffect(isQrShown, touches) { + if (!isQrShown) return@LaunchedEffect + delay(QR_AWAKE_LIMIT) + isResting = true + } + // A watch that wakes from ambient mode shows the QR again, and so does the invoice after a paid one. + LaunchedEffect(isAmbient, isPaid) { if (isAmbient || isPaid) isResting = false } Content( uiState = uiState, - isAmbient = isAmbient(), + isAmbient = isAmbient, + isResting = isResting, + onQrTouch = { touches++ }, + onShowClick = { isResting = false }, onRefreshClick = viewModel::onRefreshClick, modifier = modifier ) @@ -79,13 +109,17 @@ private fun Content( isAmbient: Boolean, onRefreshClick: () -> Unit, modifier: Modifier = Modifier, + isResting: Boolean = false, + onQrTouch: () -> Unit = {}, + onShowClick: () -> Unit = {}, ) { val qrContent = uiState.qrContent val paidAmount = uiState.paidAmount when { paidAmount != null -> Paid(amount = paidAmount, onClick = onRefreshClick, modifier = modifier) qrContent != null && isAmbient -> Hidden(modifier = modifier) - qrContent != null -> Qr(content = qrContent, modifier = modifier) + qrContent != null && isResting -> Hidden(onClick = onShowClick, modifier = modifier) + qrContent != null -> Qr(content = qrContent, onTouch = onQrTouch, modifier = modifier) uiState.isError -> Error(onRetryClick = onRefreshClick, modifier = modifier) else -> CenteredScreen( overlay = { BezelLoading() }, @@ -99,12 +133,22 @@ private fun Content( @Composable private fun Qr( content: String, + onTouch: () -> Unit, modifier: Modifier = Modifier, ) { + val currentOnTouch by rememberUpdatedState(onTouch) ScreenAwake(isBright = true) BoxWithConstraints( contentAlignment = Alignment.Center, - modifier = modifier.fillMaxSize() + modifier = modifier + .fillMaxSize() + // Any touch counts as the wearer still using the QR; it is only watched, never consumed. + .pointerInput(Unit) { + awaitEachGesture { + awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) + currentOnTouch() + } + } ) { QrCode( content = content, @@ -117,11 +161,16 @@ private fun Qr( } @Composable -private fun Hidden(modifier: Modifier = Modifier) { +private fun Hidden( + modifier: Modifier = Modifier, + onClick: (() -> Unit)? = null, +) { val description = stringResource(R.string.receive__hidden) + val showLabel = stringResource(R.string.receive__show) CenteredScreen(modifier = modifier) { QrIcon( modifier = Modifier + .clickableAlpha(onClickLabel = showLabel, enabled = onClick != null, onClick = { onClick?.invoke() }) .semantics { contentDescription = description } .testTag("WatchReceiveHidden") ) @@ -225,6 +274,19 @@ private fun PreviewAmbient() { } } +@WearPreviewDevices +@Composable +private fun PreviewResting() { + WearPreview { + Content( + uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), + isAmbient = false, + onRefreshClick = {}, + isResting = true, + ) + } +} + @WearPreviewDevices @Composable private fun PreviewError() { diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt index c45c205895..2dd406e1b9 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt @@ -4,7 +4,12 @@ import androidx.compose.runtime.Immutable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.cancelChildren +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -14,6 +19,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.wear.env.Env import to.bitkit.wear.models.ReceiveInvoice +import to.bitkit.wear.models.WatchPayment import to.bitkit.wear.repositories.PaymentsRepo import to.bitkit.wear.repositories.WalletRepo import to.bitkit.wear.repositories.WalletStatus @@ -26,8 +32,8 @@ import kotlin.time.Duration.Companion.seconds /** * The receive QR: an amountless invoice made once the wallet is ready, shown until it is paid or nearly expired. - * A nearly expired invoice is replaced by a new one; a paid one turns into a check until the wearer asks for a new - * invoice. + * A nearly expired invoice is replaced by a new one and still watched until it expires; a paid one, shown or + * replaced, turns into a check until the wearer asks for a new invoice. */ @HiltViewModel class ReceiveViewModel internal constructor( @@ -46,6 +52,9 @@ class ReceiveViewModel internal constructor( * does not make invoices one after another. */ val MIN_LIFETIME = 30.seconds + + /** How long after a failure the replacement of an invoice that is still valid is tried again. */ + val RETRY_DELAY = 5.seconds } @Inject @@ -70,31 +79,59 @@ class ReceiveViewModel internal constructor( job?.cancel() job = viewModelScope.launch { _uiState.update { ReceiveUiState(isLoading = true) } - while (true) { - // The invoice on screen stays until its replacement exists, or until it is about to expire. - val isShowing = _uiState.value.qrContent != null - val replaced = if (isShowing) withTimeoutOrNull(EXPIRY_MARGIN) { create() } else null - val created = replaced ?: run { - _uiState.update { ReceiveUiState(isLoading = true) } - create() - } - val invoice = created.getOrElse { - _uiState.update { ReceiveUiState(isError = true) } - return@launch - } - if (Env.isDebug) Logger.debug("Showing invoice '${invoice.bolt11}'", context = TAG) - _uiState.update { ReceiveUiState(qrContent = invoice.bolt11.uppercase()) } - val lifetime = (invoice.expiresAtSecs.toLong() - nowSecs()).seconds - EXPIRY_MARGIN - val paid = withTimeoutOrNull(lifetime.coerceAtLeast(MIN_LIFETIME)) { paymentsRepo.awaitPaid(invoice) } - if (paid != null) { - Logger.info("Received payment '${paid.id}'", context = TAG) - _uiState.update { ReceiveUiState(paidAmount = bitcoinAmount(paid.amountSats.toLong())) } - return@launch - } - Logger.debug("Replacing invoice '${invoice.paymentHash}' before it expires", context = TAG) - _uiState.update { it.copy(isLoading = true) } + val paid = CompletableDeferred() + val watcherScope = this + val rotation = launch { rotate(watcherScope, paid) } + val payment = paid.await() + rotation.cancelAndJoin() + coroutineContext.cancelChildren() + Logger.info("Received payment '${payment.id}'", context = TAG) + _uiState.update { ReceiveUiState(paidAmount = bitcoinAmount(payment.amountSats.toLong())) } + } + } + + /** + * Shows one invoice after another, each replaced shortly before it expires. Every invoice is watched in + * [watcherScope] until it expires, also after its replacement shows, so a payer who scanned the earlier QR + * still completes [paid]. + */ + private suspend fun rotate(watcherScope: CoroutineScope, paid: CompletableDeferred) { + while (true) { + // The invoice on screen stays until its replacement exists, or until it is about to expire. + val isShowing = _uiState.value.qrContent != null + val created = (if (isShowing) replace() else null) ?: run { + _uiState.update { ReceiveUiState(isLoading = true) } + create() + } + val invoice = created.getOrElse { + _uiState.update { ReceiveUiState(isError = true) } + return } + if (Env.isDebug) Logger.debug("Showing invoice '${invoice.bolt11}'", context = TAG) + _uiState.update { ReceiveUiState(qrContent = invoice.bolt11.uppercase()) } + val expiresIn = (invoice.expiresAtSecs.toLong() - nowSecs()).seconds + val lifetime = (expiresIn - EXPIRY_MARGIN).coerceAtLeast(MIN_LIFETIME) + watcherScope.launch { + withTimeoutOrNull(expiresIn.coerceAtLeast(lifetime + EXPIRY_MARGIN)) { paymentsRepo.awaitPaid(invoice) } + ?.let { paid.complete(it) } + } + delay(lifetime) + Logger.debug("Replacing invoice '${invoice.paymentHash}' before it expires", context = TAG) + _uiState.update { it.copy(isLoading = true) } + } + } + + /** + * Makes the invoice that replaces the one on screen, trying again after a failure for as long as that one is + * valid. Null when none could be made within [EXPIRY_MARGIN]. + */ + private suspend fun replace(): Result? = withTimeoutOrNull(EXPIRY_MARGIN) { + var created = create() + while (created.isFailure) { + delay(RETRY_DELAY) + created = create() } + created } /** Makes an invoice once the wallet is ready. */ diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt index 4e7bb9e501..34adf9bcde 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt @@ -30,6 +30,7 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.CustomAccessibilityAction import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.onLongClick import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType @@ -278,7 +279,7 @@ private fun AmountField( } @Composable -private fun Review( +internal fun Review( step: SendStep.Review, isHoldEnabled: Boolean, isOffline: Boolean, @@ -300,14 +301,15 @@ private fun Review( .testTag("WatchSendHold") .semantics { // A screen reader cannot hold, and its double tap is the click that pays nothing, so paying - // is a named action its wearer picks from the actions menu. + // is a named action its wearer picks from the actions menu, or its long click: a double tap + // and hold. if (isHoldEnabled) { - customActions = listOf( - CustomAccessibilityAction(payLabel) { - onHoldComplete() - true - }, - ) + val pay = { + onHoldComplete() + true + } + customActions = listOf(CustomAccessibilityAction(payLabel, pay)) + onLongClick(label = payLabel, action = pay) } } ) { diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt index 9354ae7ef0..4ca591e902 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt @@ -207,7 +207,10 @@ class SendViewModel @Inject constructor( _effects.send(SendEffect.Close) } - /** Shows why nothing was sent. A payment that is already under way is no failure: it shows as pending. */ + /** + * Shows why nothing was sent. A payment of this request that Spark lists as under way is no failure: it shows as + * pending. A wallet busy with another send is a failure, as nothing of this request went out. + */ private suspend fun fail(error: Throwable?) { if (error is SendError.InFlight) { finish(SendResult.Pending, amountSats = prepared?.amountSats ?: 0uL) @@ -270,6 +273,7 @@ enum class SendFailure(@StringRes val text: Int) { OutOfRange(R.string.send__error_out_of_range), Insufficient(R.string.send__error_insufficient), AlreadyPaid(R.string.send__error_already_paid), + Busy(R.string.send__error_busy), Failed(R.string.send__error_failed), ; @@ -283,6 +287,7 @@ enum class SendFailure(@StringRes val text: Int) { is SendError.AmountOutOfRange -> OutOfRange is SendError.InsufficientBalance -> Insufficient is SendError.AlreadyPaid -> AlreadyPaid + is SendError.Busy -> Busy else -> Failed } } diff --git a/wear/src/main/res/values-ar/strings.xml b/wear/src/main/res/values-ar/strings.xml index 34c9768eda..7873c2a13d 100644 --- a/wear/src/main/res/values-ar/strings.xml +++ b/wear/src/main/res/values-ar/strings.xml @@ -22,6 +22,7 @@ رمز QR مخفي فاتورة جديدة مدفوع + إظهار رمز QR استلام تمت إزالة المحفظة مراجعة @@ -50,6 +51,7 @@ المبلغ %1$s – %2$s مدفوعة مسبقًا + المحفظة مشغولة انتهت صلاحية الفاتورة فشل الدفع رصيد غير كافٍ diff --git a/wear/src/main/res/values-b+es+419/strings.xml b/wear/src/main/res/values-b+es+419/strings.xml index 9799c8ba09..acc889f640 100644 --- a/wear/src/main/res/values-b+es+419/strings.xml +++ b/wear/src/main/res/values-b+es+419/strings.xml @@ -22,6 +22,7 @@ QR oculto Nueva factura Pagado + Mostrar QR Recibir Billetera eliminada Revisar @@ -47,6 +48,7 @@ Monto %1$s – %2$s Ya pagada + Wallet ocupada Factura vencida Pago fallido Fondos insuficientes diff --git a/wear/src/main/res/values-ca/strings.xml b/wear/src/main/res/values-ca/strings.xml index af21ae5bd0..523508aee0 100644 --- a/wear/src/main/res/values-ca/strings.xml +++ b/wear/src/main/res/values-ca/strings.xml @@ -22,6 +22,7 @@ QR amagat Nova factura Pagat + Mostra el QR Rebre Cartera eliminada Revisa @@ -47,6 +48,7 @@ Import %1$s – %2$s Ja pagada + Wallet ocupada Factura caducada El pagament ha fallat Fons insuficients diff --git a/wear/src/main/res/values-cs/strings.xml b/wear/src/main/res/values-cs/strings.xml index 0418005264..6edb491dde 100644 --- a/wear/src/main/res/values-cs/strings.xml +++ b/wear/src/main/res/values-cs/strings.xml @@ -22,6 +22,7 @@ QR skryt Nová faktura Zaplaceno + Zobrazit QR Přijmout Peněženka odebrána Zkontrolovat @@ -48,6 +49,7 @@ Částka %1$s – %2$s Již zaplaceno + Peněženka je zaneprázdněna Faktura vypršela Platba selhala Nedostatek prostředků diff --git a/wear/src/main/res/values-de/strings.xml b/wear/src/main/res/values-de/strings.xml index 290fb3e318..d9556e1d5a 100644 --- a/wear/src/main/res/values-de/strings.xml +++ b/wear/src/main/res/values-de/strings.xml @@ -22,6 +22,7 @@ QR versteckt Neue Rechnung Bezahlt + QR anzeigen Empfangen Wallet entfernt Prüfen @@ -46,6 +47,7 @@ Betrag %1$s – %2$s Bereits bezahlt + Wallet beschäftigt Rechnung abgelaufen Zahlung fehlgeschlagen Nicht genug Guthaben diff --git a/wear/src/main/res/values-el/strings.xml b/wear/src/main/res/values-el/strings.xml index 7093b45f55..e7cf56431e 100644 --- a/wear/src/main/res/values-el/strings.xml +++ b/wear/src/main/res/values-el/strings.xml @@ -22,6 +22,7 @@ QR κρυφό Νέο τιμολόγιο Πληρώθηκε + Εμφάνιση QR Λήψη Το πορτοφόλι αφαιρέθηκε Έλεγχος @@ -46,6 +47,7 @@ Ποσό %1$s – %2$s Ήδη πληρωμένο + Το πορτοφόλι είναι απασχολημένο Το τιμολόγιο έληξε Η πληρωμή απέτυχε Ανεπαρκές υπόλοιπο diff --git a/wear/src/main/res/values-es-rES/strings.xml b/wear/src/main/res/values-es-rES/strings.xml index fc1cc812dc..33e961a9fa 100644 --- a/wear/src/main/res/values-es-rES/strings.xml +++ b/wear/src/main/res/values-es-rES/strings.xml @@ -22,6 +22,7 @@ QR oculto Nueva factura Pagado + Mostrar QR Recibir Cartera eliminada Revisar @@ -47,6 +48,7 @@ Importe %1$s – %2$s Ya pagada + Wallet ocupada Factura caducada Pago fallido Fondos insuficientes diff --git a/wear/src/main/res/values-es/strings.xml b/wear/src/main/res/values-es/strings.xml index fc1cc812dc..33e961a9fa 100644 --- a/wear/src/main/res/values-es/strings.xml +++ b/wear/src/main/res/values-es/strings.xml @@ -22,6 +22,7 @@ QR oculto Nueva factura Pagado + Mostrar QR Recibir Cartera eliminada Revisar @@ -47,6 +48,7 @@ Importe %1$s – %2$s Ya pagada + Wallet ocupada Factura caducada Pago fallido Fondos insuficientes diff --git a/wear/src/main/res/values-fr/strings.xml b/wear/src/main/res/values-fr/strings.xml index 3fb9b7d1a4..c085870b00 100644 --- a/wear/src/main/res/values-fr/strings.xml +++ b/wear/src/main/res/values-fr/strings.xml @@ -22,6 +22,7 @@ QR masqué Nouvelle facture Payé + Afficher le QR Recevoir Wallet supprimé Vérifier @@ -47,6 +48,7 @@ Montant %1$s – %2$s Déjà payée + Wallet occupé Facture expirée Échec du paiement Fonds insuffisants diff --git a/wear/src/main/res/values-it/strings.xml b/wear/src/main/res/values-it/strings.xml index 0603022654..df085f2548 100644 --- a/wear/src/main/res/values-it/strings.xml +++ b/wear/src/main/res/values-it/strings.xml @@ -22,6 +22,7 @@ QR nascosto Nuova fattura Pagato + Mostra QR Ricevi Portafoglio rimosso Rivedi @@ -47,6 +48,7 @@ Importo %1$s – %2$s Già pagata + Wallet occupato Fattura scaduta Pagamento fallito Fondi insufficienti diff --git a/wear/src/main/res/values-nl/strings.xml b/wear/src/main/res/values-nl/strings.xml index b6cacd1d8b..7b707876cc 100644 --- a/wear/src/main/res/values-nl/strings.xml +++ b/wear/src/main/res/values-nl/strings.xml @@ -22,6 +22,7 @@ QR verborgen Nieuwe factuur Betaald + QR tonen Ontvangen Wallet verwijderd Controleren @@ -46,6 +47,7 @@ Bedrag %1$s – %2$s Al betaald + Wallet bezet Factuur verlopen Betaling mislukt Onvoldoende saldo diff --git a/wear/src/main/res/values-pl/strings.xml b/wear/src/main/res/values-pl/strings.xml index 668cb4d627..6c5a5f369c 100644 --- a/wear/src/main/res/values-pl/strings.xml +++ b/wear/src/main/res/values-pl/strings.xml @@ -22,6 +22,7 @@ QR ukryty Nowa faktura Opłacono + Pokaż QR Odbierz Portfel usunięty Sprawdź @@ -48,6 +49,7 @@ Kwota %1$s – %2$s Już opłacona + Portfel jest zajęty Faktura wygasła Płatność nieudana Za mało środków diff --git a/wear/src/main/res/values-pt-rBR/strings.xml b/wear/src/main/res/values-pt-rBR/strings.xml index b0767fe0d0..6e7ac00976 100644 --- a/wear/src/main/res/values-pt-rBR/strings.xml +++ b/wear/src/main/res/values-pt-rBR/strings.xml @@ -22,6 +22,7 @@ QR oculto Novo invoice Pago + Mostrar QR Receber Carteira removida Revisar @@ -47,6 +48,7 @@ Valor %1$s – %2$s Já pago + Carteira ocupada Invoice expirado Pagamento falhou Saldo insuficiente diff --git a/wear/src/main/res/values-pt/strings.xml b/wear/src/main/res/values-pt/strings.xml index beaa639569..1894df869b 100644 --- a/wear/src/main/res/values-pt/strings.xml +++ b/wear/src/main/res/values-pt/strings.xml @@ -22,6 +22,7 @@ QR oculto Nova fatura Pago + Mostrar QR Receber Carteira removida Revisar @@ -47,6 +48,7 @@ Montante %1$s – %2$s Já paga + Carteira ocupada Fatura expirada Pagamento falhou Saldo insuficiente diff --git a/wear/src/main/res/values-ru/strings.xml b/wear/src/main/res/values-ru/strings.xml index 5412fc2c79..76b23a3fb5 100644 --- a/wear/src/main/res/values-ru/strings.xml +++ b/wear/src/main/res/values-ru/strings.xml @@ -22,6 +22,7 @@ QR скрыт Новый счёт Оплачено + Показать QR Получить Кошелёк удалён Проверить @@ -48,6 +49,7 @@ Сумма %1$s – %2$s Уже оплачен + Кошелёк занят Счёт истёк Платёж не прошёл Недостаточно средств diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index d59e8cb050..d8d1c0078d 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -22,6 +22,7 @@ QR hidden New invoice Paid + Show QR Receive Wallet removed Review @@ -46,6 +47,7 @@ Amount %1$s – %2$s Already paid + Wallet busy Invoice expired Payment failed Not enough funds diff --git a/wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt index 388d9e60eb..fbc47f0f5f 100644 --- a/wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt +++ b/wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt @@ -11,7 +11,6 @@ import to.bitkit.wear.test.BaseUnitTest import java.io.File import kotlin.test.assertEquals import kotlin.test.assertFalse -import kotlin.test.assertNull import kotlin.test.assertTrue /** An [UncertainSendStore] in memory. */ @@ -21,7 +20,7 @@ class FakeUncertainSendStore : UncertainSendStore { override suspend fun begin(send: UncertainSend): Boolean { failure?.let { throw it } - return sends.put(send.key, send.copy(sparkAddress = send.sparkAddress?.lowercase())) != null + return sends.put(send.key, send.copy(sparkPayee = send.sparkPayee?.lowercase())) != null } override suspend fun settle(key: String) { @@ -29,16 +28,16 @@ class FakeUncertainSendStore : UncertainSendStore { sends.remove(key) } - override suspend fun transferKey(sparkAddress: String): String? { + override suspend fun transferKeys(sparkPayee: String): List { failure?.let { throw it } - return sends.values.firstOrNull { it.sparkAddress == sparkAddress.lowercase() }?.key + return sends.values.filter { it.sparkPayee == sparkPayee.lowercase() }.map { it.key }.reversed() } } /** The store against the real settings file, in a temporary directory. Each [open] is a new process. */ class UncertainSendStoreTest : BaseUnitTest() { private companion object { - const val ADDRESS = "sparkrt1pgssy6vty7krpze82ecm8j39gd35v35aqjjmhftc4culawsavkyh564u2uv8v0" + const val PAYEE = "03a1b2c3d4e5f60718293a4b5c6d7e8f9001122334455667788990aabbccddeeff" } @get:Rule @@ -49,14 +48,25 @@ class UncertainSendStoreTest : BaseUnitTest() { private var now = 1_000uL @Test - fun `a noted transfer keeps its key for its address in either case, also after a restart`() = test { - assertFalse(open().first.begin(UncertainSend("key-a", sparkAddress = ADDRESS))) + fun `a noted transfer keeps its key for its payee in either case, also after a restart`() = test { + assertFalse(open().first.begin(UncertainSend("key-a", sparkPayee = PAYEE))) close() val sut = open().first - assertEquals("key-a", sut.transferKey(ADDRESS)) - assertEquals("key-a", sut.transferKey(ADDRESS.uppercase())) - assertNull(sut.transferKey("sparkrt1other")) + assertEquals(listOf("key-a"), sut.transferKeys(PAYEE)) + assertEquals(listOf("key-a"), sut.transferKeys(PAYEE.uppercase())) + assertTrue(sut.transferKeys("02other").isEmpty()) + close() + } + + @Test + fun `every transfer noted for one payee is told, the newest first`() = test { + val sut = open().first + sut.begin(UncertainSend("key-a", sparkPayee = PAYEE)) + now += 10uL + sut.begin(UncertainSend("key-b", sparkPayee = PAYEE.uppercase())) + + assertEquals(listOf("key-b", "key-a"), sut.transferKeys(PAYEE)) close() } @@ -75,14 +85,14 @@ class UncertainSendStoreTest : BaseUnitTest() { @Test fun `a settled send is forgotten`() = test { val sut = open().first - sut.begin(UncertainSend("key-a", sparkAddress = ADDRESS)) + sut.begin(UncertainSend("key-a", sparkPayee = PAYEE)) sut.begin(UncertainSend("key-0", expiresAtSecs = 2_000uL)) sut.settle("key-a") sut.settle("key-0") sut.settle("unknown") - assertNull(sut.transferKey(ADDRESS)) + assertTrue(sut.transferKeys(PAYEE).isEmpty()) assertFalse(sut.begin(UncertainSend("key-0", expiresAtSecs = 2_000uL))) close() } @@ -91,7 +101,7 @@ class UncertainSendStoreTest : BaseUnitTest() { fun `an invoice's send is kept for a day after the invoice expired, and a transfer for good`() = test { val sut = open().first sut.begin(UncertainSend("key-0", expiresAtSecs = 2_000uL)) - sut.begin(UncertainSend("key-a", sparkAddress = ADDRESS)) + sut.begin(UncertainSend("key-a", sparkPayee = PAYEE)) now = 2_000uL + SettingsUncertainSendStore.EXPIRED_KEPT_SECS - 1uL sut.begin(UncertainSend("other-1", expiresAtSecs = now + 10uL)) @@ -100,7 +110,7 @@ class UncertainSendStoreTest : BaseUnitTest() { now = 2_000uL + SettingsUncertainSendStore.EXPIRED_KEPT_SECS sut.begin(UncertainSend("other-2", expiresAtSecs = now + 10uL)) assertFalse(sut.begin(UncertainSend("key-0", expiresAtSecs = 2_000uL))) - assertEquals("key-a", sut.transferKey(ADDRESS)) + assertEquals(listOf("key-a"), sut.transferKeys(PAYEE)) close() } @@ -111,23 +121,23 @@ class UncertainSendStoreTest : BaseUnitTest() { repeat(count) { now = 1_000uL + it.toULong() - sut.begin(UncertainSend("key-$it", sparkAddress = "sparkrt1address$it")) + sut.begin(UncertainSend("key-$it", sparkPayee = "02payee$it")) } - assertNull(sut.transferKey("sparkrt1address0")) - assertEquals("key-1", sut.transferKey("sparkrt1address1")) - assertEquals("key-${count - 1}", sut.transferKey("sparkrt1address${count - 1}")) + assertTrue(sut.transferKeys("02payee0").isEmpty()) + assertEquals(listOf("key-1"), sut.transferKeys("02payee1")) + assertEquals(listOf("key-${count - 1}"), sut.transferKeys("02payee${count - 1}")) close() } @Test fun `the wallet's wipe forgets the sends with the settings`() = test { val (sut, settings) = open() - sut.begin(UncertainSend("key-a", sparkAddress = ADDRESS)) + sut.begin(UncertainSend("key-a", sparkPayee = PAYEE)) settings.finishWipe() - assertNull(sut.transferKey(ADDRESS)) + assertTrue(sut.transferKeys(PAYEE).isEmpty()) close() } diff --git a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt index d5a3bc8cac..b9ce1c687d 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -24,6 +24,7 @@ import org.junit.Before import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.mock @@ -782,7 +783,7 @@ class PaymentsRepoTest : BaseUnitTest() { assertEquals(PaymentsRepo.SEND_TIMEOUT.inWholeMilliseconds, testScheduler.currentTime) assertEquals(setOf("key-0"), uncertainSends.sends.keys) - assertIs(sut.send(prepared).exceptionOrNull()) + assertIs(sut.send(prepared).exceptionOrNull()) verify(sparkService).send(any(), any()) val stalled = answer @@ -799,7 +800,7 @@ class PaymentsRepoTest : BaseUnitTest() { val caller = launch { sut.send(prepared) } caller.cancel() - assertIs(sut.send(prepared).exceptionOrNull()) + assertIs(sut.send(prepared).exceptionOrNull()) release.complete(payment("key-0", PaymentStatus.COMPLETED)) assertTrue(uncertainSends.sends.isEmpty()) @@ -824,12 +825,88 @@ class PaymentsRepoTest : BaseUnitTest() { whenever(sparkService.send(any(), any())).doSuspendableAnswer { release.await() } val first = async { sut.send(preparedSend()) } - assertIs(sut.send(preparedSend()).exceptionOrNull()) + assertIs(sut.send(preparedSend()).exceptionOrNull()) release.complete(payment("key-0", PaymentStatus.COMPLETED)) assertTrue(first.await().isSuccess) } + @Test + fun `while a stalled send call lives, another request is busy, not under way, and leaves no note`() = test { + val other = "lnbcrt1other" + val otherHash = "cd".repeat(32) + whenever(sparkService.parse(other)).thenReturn(invoiceInput(other, otherHash)) + whenever(sparkService.prepareSend(eq(other), anyOrNull())).thenReturn(prepared()) + val otherPrepared = sut.prepare(SendRequest.Invoice(other, 500uL, null)).getOrThrow() + whenever(sparkService.send(any(), any())).doSuspendableAnswer { CompletableDeferred().await() } + assertIs(sut.send(preparedSend()).exceptionOrNull()) + + assertIs(sut.send(otherPrepared).exceptionOrNull()) + + verify(sparkService).send(any(), any()) + assertEquals(setOf("key-0"), uncertainSends.sends.keys) + } + + @Test + fun `a wallet that disconnects after the note and before the sdk call sent nothing`() = test { + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw SparkError.NotConnected() } + + assertIs(sut.send(preparedSend()).exceptionOrNull()) + + assertTrue(uncertainSends.sends.isEmpty()) + } + + @Test + fun `a disconnect before the sdk call keeps the note of an earlier attempt of unknown outcome`() = test { + var error: Throwable = SdkException.NetworkException("reset") + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw error } + assertIs(sut.send(preparedSend()).exceptionOrNull()) + + error = SparkError.NotConnected() + assertIs(sut.send(preparedSend()).exceptionOrNull()) + + assertEquals(setOf("key-0"), uncertainSends.sends.keys) + } + + @Test + fun `a send holds the connection from its note until spark returns the call`() = test { + val order = mutableListOf() + doAnswer { order += "hold:${uncertainSends.sends.size}" }.whenever(sparkService).holdSend() + doAnswer { order += "release" }.whenever(sparkService).releaseSend() + whenever(sparkService.send(any(), any())).doSuspendableAnswer { + order += "send" + payment("key-0", PaymentStatus.COMPLETED) + } + + sut.send(preparedSend()).getOrThrow() + + assertEquals(listOf("hold:0", "send", "release"), order) + } + + @Test + fun `a send noted while the wallet is wiped is not sent and leaves no note`() = test { + val prepared = preparedSend() + var isWiping = false + whenever(sparkService.isWiping).thenAnswer { isWiping } + doAnswer { isWiping = true }.whenever(sparkService).holdSend() + + assertIs(sut.send(prepared).exceptionOrNull()) + + verify(sparkService, never()).send(any(), any()) + assertTrue(uncertainSends.sends.isEmpty()) + } + + @Test + fun `a send noted after the wallet stopped being ready is not sent and leaves no note`() = test { + val prepared = preparedSend() + doAnswer { walletState.update { it.copy(status = WalletStatus.Idle) } }.whenever(sparkService).holdSend() + + assertIs(sut.send(prepared).exceptionOrNull()) + + verify(sparkService, never()).send(any(), any()) + assertTrue(uncertainSends.sends.isEmpty()) + } + @Test fun `a spark address is sent under one key of its own, without reading the list`() = test { whenever(sparkService.parse(SPARK_ADDRESS)).thenReturn(sparkAddressInput(OTHER_IDENTITY)) @@ -886,6 +963,47 @@ class PaymentsRepoTest : BaseUnitTest() { assertEquals(1, keys.distinct().size) } + @Test + fun `the other spelling of a payee's spark address is sent under the key of its uncertain transfer`() = test { + val keys = stubTransfer() + val otherSpelling = "sprt1pgssy6vty7krpze82ecm8j39gd35v35aqjjmhftc4culawsavkyh564u2uv8v0" + whenever(sparkService.parse(otherSpelling)) + .thenReturn(sparkAddressInput(OTHER_IDENTITY.uppercase(), otherSpelling)) + whenever(sparkService.prepareSend(otherSpelling, 500uL)).thenReturn(preparedTransfer()) + whenever(sparkService.send(any(), any())).thenAnswer { + keys += it.arguments[1] as String + throw SdkException.NetworkException("reset") + } + sut.send(sut.prepare(SendRequest.SparkAddress(SPARK_ADDRESS), 500uL).getOrThrow()) + + sut.send(sut.prepare(SendRequest.SparkAddress(otherSpelling), 500uL).getOrThrow()) + + assertEquals(2, keys.size) + assertEquals(1, keys.distinct().size) + assertEquals(OTHER_IDENTITY, uncertainSends.sends.values.single().sparkPayee) + } + + @Test + fun `a failed transfer whose note could not be dropped never hides the uncertain one after it`() = test { + val keys = stubTransfer() + whenever(sparkService.send(any(), any())).thenAnswer { + keys += it.arguments[1] as String + throw SdkException.NetworkException("reset") + } + val request = SendRequest.SparkAddress(SPARK_ADDRESS) + sut.send(sut.prepare(request, 500uL).getOrThrow()) + val failed = keys.single() + // The failed transfer's note stays, as after a settings write that failed, beside the next transfer's. + val uncertain = "00000000-0000-4000-8000-000000000002" + uncertainSends.sends[uncertain] = UncertainSend(uncertain, sparkPayee = OTHER_IDENTITY) + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment(failed, PaymentStatus.FAILED, paymentHash = null))) + + sut.send(sut.prepare(request, 500uL).getOrThrow()) + + assertEquals(listOf(failed, uncertain), keys) + } + @Test fun `a spark transfer of unknown outcome that spark lists is not sent again`() = test { val keys = stubTransfer() diff --git a/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt b/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt index eb13ffa132..c7b3afd998 100644 --- a/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt +++ b/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt @@ -216,6 +216,24 @@ class WatchSparkServiceTest { stalled.join() } + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a disconnect waits for a send that holds the connection before the sdk has its call`() = runTest { + val sut = WatchSparkService(mock(), FakeBip39()) + val sdk = connectedSdk() + sut.connectWith(assertNotNull(sut.wipeToken())) { sdk } + + sut.holdSend() + val disconnecting = launch { sut.disconnect() } + runCurrent() + verify(sdk, never()).disconnect() + + sut.releaseSend() + disconnecting.join() + verify(sdk).disconnect() + assertEquals(0, testScheduler.currentTime) + } + @Test fun `payments are listed newest first, up to the limit`() = runTest { val sut = WatchSparkService(mock(), FakeBip39()) diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityNowSecsTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityNowSecsTest.kt new file mode 100644 index 0000000000..23d45b0721 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityNowSecsTest.kt @@ -0,0 +1,51 @@ +package to.bitkit.wear.ui.screens.activity + +import androidx.activity.ComponentActivity +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import kotlin.test.assertEquals + +/** The time the activity list's relative times count from. */ +@Config(sdk = [34], qualifiers = "w227dp-h227dp-round") +@RunWith(RobolectricTestRunner::class) +class ActivityNowSecsTest { + @get:Rule + val composeRule = createAndroidComposeRule() + + @Test + fun `the times count from the clock before a list is read, from a new list at once, and move on by the minute`() { + var clockSecs = NOW + var loadedSecs by mutableLongStateOf(0L) + var shown = -1L + composeRule.mainClock.autoAdvance = false + composeRule.setContent { shown = rememberNowSecs(loadedSecs = loadedSecs, clock = { clockSecs }) } + + // No list yet: never epoch 0, which would make every payment read "0 min. ago". + composeRule.runOnIdle { assertEquals(NOW, shown) } + + // A list read between two ticks counts from its own time on its first frame. + composeRule.runOnUiThread { + clockSecs = NOW + 45 + loadedSecs = NOW + 45 + Snapshot.sendApplyNotifications() + } + composeRule.mainClock.advanceTimeBy(100) + composeRule.runOnIdle { assertEquals(NOW + 45, shown) } + + clockSecs = NOW + 120 + composeRule.mainClock.advanceTimeBy(61_000) + composeRule.runOnIdle { assertEquals(NOW + 120, shown) } + } + + private companion object { + const val NOW = 1_800_000_000L + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt index b65c181b5e..05b09b5cfb 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt @@ -1,6 +1,7 @@ package to.bitkit.wear.ui.screens.receive import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow @@ -118,6 +119,95 @@ class ReceiveViewModelTest : BaseUnitTest() { assertEquals("LNBCRT1NEXT", sut.uiState.value.qrContent) } + @Test + fun `a payment of the replaced invoice still shows the check, until that invoice expires`() = test { + val paid = CompletableDeferred() + val first = invoice() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(first)) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { + if (it.arguments[0] == first) paid.await() else awaitCancellation() + } + val sut = createSut() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice("lnbcrt1next", hash = "cd34"))) + + testScheduler.advanceTimeBy(LIFETIME.seconds - ReceiveViewModel.EXPIRY_MARGIN + 30.seconds) + assertEquals("LNBCRT1NEXT", sut.uiState.value.qrContent) + + paid.complete(payment(21_000uL)) + + assertEquals(DisplayAmount("₿", "21 000"), sut.uiState.value.paidAmount) + assertNull(sut.uiState.value.qrContent) + } + + @Test + fun `a payment that arrives while the replacement is being made shows the check`() = test { + val paid = CompletableDeferred() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { paid.await() } + val sut = createSut() + walletState.update { it.copy(status = WalletStatus.Offline) } + + testScheduler.advanceTimeBy(LIFETIME.seconds - ReceiveViewModel.EXPIRY_MARGIN + 10.seconds) + paid.complete(payment(21_000uL)) + + assertEquals(DisplayAmount("₿", "21 000"), sut.uiState.value.paidAmount) + } + + @Test + fun `a replaced invoice is no longer watched once it expired`() = test { + var watched = 0 + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { + watched++ + try { + awaitCancellation() + } finally { + watched-- + } + } + createSut() + whenever(paymentsRepo.createInvoice()) + .thenReturn(Result.success(invoice("lnbcrt1next", lifetime = 2 * LIFETIME))) + + testScheduler.advanceTimeBy(LIFETIME.seconds - 1.seconds) + assertEquals(2, watched) + + testScheduler.advanceTimeBy(2.seconds) + assertEquals(1, watched) + } + + @Test + fun `a replacement that fails is tried again while the invoice on screen is valid`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.failure(ReceiveError.NotReady())) + + testScheduler.advanceTimeBy(LIFETIME.seconds - ReceiveViewModel.EXPIRY_MARGIN + 1.seconds) + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + assertFalse(sut.uiState.value.isError) + + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice("lnbcrt1next"))) + testScheduler.advanceTimeBy(ReceiveViewModel.RETRY_DELAY) + + assertEquals("LNBCRT1NEXT", sut.uiState.value.qrContent) + } + + @Test + fun `a replacement that keeps failing shows the error only once the invoice is about to expire`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.failure(ReceiveError.NotReady())) + + testScheduler.advanceTimeBy(LIFETIME.seconds - 1.seconds) + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + + testScheduler.advanceTimeBy(2.seconds) + assertTrue(sut.uiState.value.isError) + assertNull(sut.uiState.value.qrContent) + } + @Test fun `an invoice that expires before the wallet is ready again leaves the screen`() = test { whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) @@ -160,8 +250,8 @@ class ReceiveViewModelTest : BaseUnitTest() { assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) } - private fun invoice(bolt11: String = BOLT11, lifetime: Long = LIFETIME) = - ReceiveInvoice(bolt11, PAYMENT_HASH, (NOW + lifetime).toULong()) + private fun invoice(bolt11: String = BOLT11, lifetime: Long = LIFETIME, hash: String = PAYMENT_HASH) = + ReceiveInvoice(bolt11, hash, (NOW + lifetime).toULong()) private fun payment(amountSats: ULong) = WatchPayment( id = "receipt", diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendReviewTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendReviewTest.kt new file mode 100644 index 0000000000..2a38ae759e --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendReviewTest.kt @@ -0,0 +1,90 @@ +package to.bitkit.wear.ui.screens.send + +import androidx.activity.ComponentActivity +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.semantics.getOrNull +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performSemanticsAction +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.wear.ui.components.WearPreview +import to.bitkit.wear.ui.screens.home.DisplayAmount +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** The pay button of the review, as a screen reader and a plain tap reach it. */ +@Config(sdk = [34], qualifiers = "w227dp-h227dp-round") +@RunWith(RobolectricTestRunner::class) +class SendReviewTest { + @get:Rule + val composeRule = createAndroidComposeRule() + + private var pays = 0 + + @Test + fun `a tap on the pay button never pays`() { + setReview(isHoldEnabled = true) + + composeRule.onNodeWithTag("WatchSendHold").performClick() + composeRule.onNodeWithTag("WatchSendHold").performSemanticsAction(SemanticsActions.OnClick) + composeRule.waitForIdle() + + assertEquals(0, pays) + } + + @Test + fun `a screen reader pays by the named action or by a long click`() { + setReview(isHoldEnabled = true) + val config = composeRule.onNodeWithTag("WatchSendHold").fetchSemanticsNode().config + + val action = assertNotNull(config.getOrNull(SemanticsActions.CustomActions)).single() + assertEquals("Pay", action.label) + assertEquals("Pay", config.getOrNull(SemanticsActions.OnLongClick)?.label) + + composeRule.runOnUiThread { action.action() } + assertEquals(1, pays) + + composeRule.onNodeWithTag("WatchSendHold").performSemanticsAction(SemanticsActions.OnLongClick) + assertEquals(2, pays) + } + + @Test + fun `a screen reader has no way to pay while the hold is off`() { + setReview(isHoldEnabled = false) + val node = composeRule.onNodeWithTag("WatchSendHold") + val config = node.fetchSemanticsNode().config + + node.assertIsNotEnabled() + assertNull(config.getOrNull(SemanticsActions.CustomActions)) + assertNull(config.getOrNull(SemanticsActions.OnLongClick)) + assertNotNull(config.getOrNull(SemanticsProperties.Disabled)) + assertEquals(0, pays) + } + + private fun setReview(isHoldEnabled: Boolean) { + composeRule.setContent { + WearPreview { + Review( + step = SendStep.Review( + amount = DisplayAmount(symbol = "₿", text = "1 000"), + fiat = null, + fee = null, + payee = null, + ), + isHoldEnabled = isHoldEnabled, + isOffline = false, + isConnecting = !isHoldEnabled, + onHoldComplete = { pays++ }, + ) + } + } + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt index 84f924d42a..de2b35a459 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt @@ -210,6 +210,18 @@ class SendViewModelTest : BaseUnitTest() { } } + @Test + fun `a wallet busy with another send is a failure, never pending`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.failure(SendError.Busy())) + val sut = createSut() + + sut.onHoldComplete() + + assertEquals(SendStep.Failed(SendFailure.Busy), sut.uiState.value.step) + } + @Test fun `a request found under way before the review shows as pending and closes`() = test { whenever(paymentsRepo.parse(INPUT)).thenReturn(Result.success(INVOICE)) @@ -319,7 +331,7 @@ class SendViewModelTest : BaseUnitTest() { response = mock(), paymentHash = "ab12", expiresAtSecs = 1_800_003_600uL, - sparkAddress = null, + sparkPayee = null, transferKey = "transfer", ) From 1221feb3a0cea6df6405b08d86cd8c0c50695f45 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 03:28:13 -0300 Subject: [PATCH 16/33] docs: update wear payments docs and journeys for round 2 fixes Co-Authored-By: Claude Fable 5.2 --- docs/wear.md | 44 +++++++++++++++++++------- journeys/wear/README.md | 3 +- journeys/wear/activity-list.xml | 1 - journeys/wear/receive-qr-rests.xml | 21 ++++++++++++ journeys/wear/receive-qr.xml | 6 ++-- journeys/wear/send-deeplink-bolt11.xml | 7 ++-- journeys/wear/send-hold-cancel.xml | 8 +++-- 7 files changed, 68 insertions(+), 22 deletions(-) create mode 100644 journeys/wear/receive-qr-rests.xml diff --git a/docs/wear.md b/docs/wear.md index f83cf514da..075fbb938e 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -155,10 +155,15 @@ On-screen copy stays short: a title or one line of at most about six words per s the receive QR (`WatchReceiveQr`): an amountless invoice, uppercased so the code uses QR's alphanumeric mode, black on white with the standard four-module quiet zone, error correction L, filling the largest square inside the round screen (1/√2 of its width). Each module is one bitmap pixel scaled up without smoothing (zxing, as on the phone). - While the QR shows, the screen stays on at full brightness; both end when it leaves. The invoice is made once the + While the QR shows, the screen stays on at full brightness; both end when it leaves. After 2 min without a touch + the QR rests: it hides behind the dimmed QR icon (`WatchReceiveHidden`, "Show QR") and the screen may turn off + again, so a forgotten QR does not hold the screen at full brightness; a tap on the icon, or waking the watch from + ambient mode, shows it for another 2 min. The invoice is made once the wallet is ready, under the loading ring; a failure shows one line and a retry (`WatchReceiveError`, `WatchReceiveRetry`). An invoice is replaced by a new one a minute before it expires, and it stays on screen until - the new one exists; when the wallet is not ready by then, the loading ring takes its place as it expires. An + the new one exists; a replacement that fails is tried again every 5 s meanwhile, and when none exists by then, the + loading ring, or the error, takes its place as it expires. A replaced invoice is still watched until it expires, so + a payer who scanned the earlier QR gets the check too. An invoice shows for at least 30 s, also when the watch's clock runs ahead. Paid, the QR turns into a check with the amount (`WatchReceivePaid`, `WatchReceivePaidAmount`) and a firm click (the `LongPress` haptic), unlike the confirm pattern that ends a send; a tap on the check shows a new invoice. In ambient mode the QR is replaced by @@ -179,8 +184,9 @@ On-screen copy stays short: a title or one line of at most about six words per s the line "Offline"; while the wallet connects, locks or pauses, it is disabled under the loading ring. `PaymentsRepo.skipConfirmation` is asked before the hold; it is always false until QuickPay (PR 3). - Screen readers: a screen reader's wearer cannot hold, and the button's click pays nothing, so the button - offers "Pay" as a custom accessibility action, picked from the actions menu. The Receive button reads - "Receive". + offers "Pay" as a custom accessibility action, picked from the actions menu, and as its long click (a double + tap and hold); both only while the hold is enabled. `SendReviewTest` checks the three; the actions menu of + TalkBack on a watch has not been tried on a device. The Receive button reads "Receive". - Ambient: the amount entry, the review and the result are replaced by a dimmed bolt (`WatchSendHidden`), so the always-on screen shows no amount; the hold starts over when the watch wakes. - Sending: the loading ring, with "Waiting for network" after 3 s. The screen stays on and the flow cannot be @@ -188,13 +194,14 @@ On-screen copy stays short: a title or one line of at most about six words per s - Result: sent shows a check, "Sent" and the amount with the confirm haptic, and closes after 2 s. A payment that did not settle in time, or one that was already under way, from the watch or the phone, shows a clock and "Pending"; an outcome Spark could not report shows "Check activity", never a failure; both close after 3 s. The - amount is the one Spark paid. A refusal or a failure shows a cross, one line of at most four words and + amount is the one Spark paid. A request that was not sent because another send still holds the wallet shows + "Wallet busy" as a failure, never "Pending". A refusal or a failure shows a cross, one line of at most four words and an OK button (`WatchSendError`, `WatchSendClose`), with the reject haptic. Insufficient funds, an expired or unreadable invoice and an own invoice end there before any hold. - **Activity.** The Activity page lists the newest 20 payments from Spark's local list: a direction icon (or a clock for pending, a cross for failed), the amount with its sign and how long ago (`WatchActivityItem-0` onwards). It is read when Spark connects and after every payment or sync, and the last list stays while Spark is - disconnected, with its times counted again every minute. A tap opens the detail: the amount, the fee of a send, the + disconnected, with its times counted again every minute; a list just read counts from its own time. A tap opens the detail: the amount, the fee of a send, the date and time and the status (`WatchActivityDetailAmount`, `…Fee`, `…Time`, `…Status`); Spark's list carries no payee or description. With no payments it shows a dimmed icon and "No activity" (`WatchActivityEmpty`). A detail whose payment the list does not hold, while it loads or after newer payments pushed it out, shows the dimmed icon (`WatchActivityDetailMissing`). @@ -235,9 +242,11 @@ in any other state. - **Sending.** A send runs in the repository's own scope, so the screen that started it cannot cancel it, also not by closing, and one send runs at a time. An invoice's send first syncs with Spark, for up to 20 s, and is refused when the sync does not reach Spark. The call returns when Spark has the payment; a call that stalls for - a minute ends as an unknown outcome, and nothing else is sent until Spark returns that call. The result then waits - up to a minute for the payment to settle and reports it as pending after that. A lock, a pause or a wipe waits up to 10 s for a send Spark is taking before it - disconnects. The send screen keeps the screen on, so the app stays on screen and connected while it waits. + a minute ends as an unknown outcome, and nothing else is sent until Spark returns that call: another request is + refused as busy (`SendError.Busy`, "Wallet busy"), since nothing of it went out. The result then waits + up to a minute for the payment to settle and reports it as pending after that. A lock, a pause or a wipe waits up to 10 s for a send before it + disconnects, from the moment the send is noted until Spark returns its call; a wallet that is disconnected before + Spark got the call, or wiped before the note was written, sent nothing: "Wallet not ready", and no note stays. The send screen keeps the screen on, so the app stays on screen and connected while it waits. **Known gap:** a wearer who leaves the app during that wait pauses the wallet 10 s later (see Background); the settlement is then not seen and the send reports pending after the minute, although it may have completed. The activity list shows the real state once the app is back. @@ -251,11 +260,22 @@ in any other state. cannot be read, refuses the send. - **Spark addresses.** A Spark address has no payment hash to derive a key from, so its transfer goes out under a random key. `UncertainSendStore`, in the settings file the wipe clears, notes every send before it goes out and - drops it once Spark shows its payment or refuses it unsent. A transfer whose outcome was never learned, also - because the app was closed during it, keeps its key there: the next send to the same address syncs and asks - Spark's list. A transfer the list shows completed is not sent again ("Already paid", once), one it shows pending + drops it once Spark shows its payment or refuses it unsent. A transfer is noted under the Spark identity public + key its address encodes, which the `sp…` and the `spark…` spelling of one wallet's address share. A transfer whose + outcome was never learned, also because the app was closed during it, keeps its key there: the next send to the + same wallet syncs and asks Spark's list about every transfer noted for it. A transfer the list shows completed is not sent again ("Already paid", once), one it shows pending is "Pending", one it shows failed makes way for a new key, and one it does not show goes out again under the same key, which pays once. Without a sync that reaches Spark, nothing is sent to that address. +- **Reused key on a Spark address.** That a reused key pays once also for a transfer to a Spark address was read + from the SDK's source at tag 0.28.3, not tried against the operators. `SendPaymentRequest.idempotency_key` is + documented for "all Spark based transfers": a reused key returns the same payment, and the payment's id is the key. + `orchestrate_send` first returns the payment its local storage holds under the key. Otherwise the key is the + transfer id handed to the operators (`send/spark_address.rs`, `TransferService.send_transfer_inner`), and when + they refuse the submission, as for an id they already hold ("a transfer id is single-use"), + `recover_committed_transfer` asks them for that id and returns the earlier transfer. The one part the source + cannot show is that the operators refuse a second submission of an id. The watch does not lean on it alone: a + transfer goes out again under its key only after a sync that reached Spark shows no payment under it, and any + error on that send is "unknown" with the note kept, never a new key. - **Unknown outcome.** When the send call fails or stalls after Spark may have taken the payment and Spark's list does not show it, the result is "unknown", never "failed". The activity list tells once Spark lists it, and sending the same request again from the watch goes out under the same key, so it cannot pay twice. A refusal diff --git a/journeys/wear/README.md b/journeys/wear/README.md index 04147a2cb9..9311f870c3 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -16,7 +16,7 @@ What `android layout` misses on the watch, verified on the API 37 emulator: `uiautomator dump` lists it. The same goes for `RestoreHidden`, the empty screen the restore shows in ambient mode. - **The receive QR.** `WatchReceiveQr` is an image with no text or action, so `android layout` leaves it out; `adb shell uiautomator dump` lists it. Check it there or from a screenshot. `WatchReceiveHidden`, the dimmed icon - that replaces it in ambient mode, has a content-desc and is listed. + that replaces it in ambient mode and once it rests, has a content-desc and is listed. - **Suggestion chips.** A chip's tag (`RestoreSuggestion-0`, counted from 0) is on the button and its word is a text node at the same `center`. A chip below the screen edge is not listed until the screen scrolls. - **The keyboard.** The Wear OS keyboard is a full-screen window that `android layout` does not show. It lists the @@ -114,6 +114,7 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `nfc-hint-states.xml` | hosted, physical watch only | yes | | `screenshot-blocked.xml` | none | no | | `receive-qr.xml` | local | no | +| `receive-qr-rests.xml` | local | no | | `receive-paid.xml` | local | no, it funds the wallet with 50 000 sats | | `send-deeplink-bolt11.xml` | local | yes, 2 000 sats | | `send-hold-cancel.xml` | local | yes, 2 000 sats | diff --git a/journeys/wear/activity-list.xml b/journeys/wear/activity-list.xml index 58b7dad192..80116eaadb 100644 --- a/journeys/wear/activity-list.xml +++ b/journeys/wear/activity-list.xml @@ -9,7 +9,6 @@ Swipe the pager left to Receive: `adb shell input swipe 400 227 60 227 300` - Wait up to 5 s until "WatchReceiveOpen" is listed Swipe the pager left to Activity: `adb shell input swipe 400 227 60 227 300` Wait up to 10 s until "WatchActivityItem-0" is listed Verify "WatchActivityItem-0" shows "- ₿ 1 000" diff --git a/journeys/wear/receive-qr-rests.xml b/journeys/wear/receive-qr-rests.xml new file mode 100644 index 0000000000..22ff884b61 --- /dev/null +++ b/journeys/wear/receive-qr-rests.xml @@ -0,0 +1,21 @@ + + + A receive QR that is not touched for 2 min rests: it hides behind the dimmed QR icon and stops holding the screen + on at full brightness; a tap shows it again. Emulator and physical watch. + + Precondition: Restored wallet on the local ./spark stack, see journeys/wear/README.md › Local ./spark stack and + › Restored wallet, on the Balance page with the loading ring stopped, and the always-on screen on (README › Watch + gestures). Gestures are written for the 454 px screen; scale them as in README › What differs. Once the QR rests + the watch may go to ambient mode, which shows the same icon; the tap then wakes the watch, which shows the QR too. + + + Swipe the pager left once: `adb shell input swipe 400 227 60 227 300` + Tap "WatchReceiveOpen" + Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) + Wait 125 s without touching the watch + Verify "WatchReceiveHidden" is listed with the content-desc "QR hidden" + Tap "WatchReceiveHidden" + Wait up to 5 s until "WatchReceiveHidden" is not listed + Verify from a screenshot that a black-on-white QR code fills the middle of the screen + + diff --git a/journeys/wear/receive-qr.xml b/journeys/wear/receive-qr.xml index 0d4070ffc2..db2b21f4d4 100644 --- a/journeys/wear/receive-qr.xml +++ b/journeys/wear/receive-qr.xml @@ -13,12 +13,12 @@ Verify the Receive page: "WatchReceiveOpen" is listed Tap "WatchReceiveOpen" Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) - Verify from a screenshot that a black-on-white QR code fills the middle of the screen - Read the invoice from the log as in README › Reading the receive invoice and verify it starts with "lnbcrt" + Read the invoice from the log as in README › Reading the receive invoice + Verify the invoice starts with "lnbcrt" Run `adb shell input keyevent KEYCODE_SLEEP` Wait up to 5 s until "WatchReceiveHidden" is listed with the content-desc "QR hidden" Run `adb shell input keyevent KEYCODE_WAKEUP` Wait up to 5 s until "WatchReceiveHidden" is not listed - Verify from a screenshot that the QR code shows again + Verify from a screenshot that a black-on-white QR code fills the middle of the screen diff --git a/journeys/wear/send-deeplink-bolt11.xml b/journeys/wear/send-deeplink-bolt11.xml index 3e101b7130..a4ffcedaf5 100644 --- a/journeys/wear/send-deeplink-bolt11.xml +++ b/journeys/wear/send-deeplink-bolt11.xml @@ -12,10 +12,13 @@ Run `../bitkit-docker/spark invoice 1000` and note the BOLT11 invoice it prints as <invoice> Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` Wait up to 10 s until "WatchSendHold" is listed - Verify "WatchSendAmount" reads "1 000" and "WatchSendAmountSymbol" reads "₿" + Verify "WatchSendAmount" reads "1 000" + Verify "WatchSendAmountSymbol" reads "₿" Hold "WatchSendHold" for 2 s as in README › Holding to pay Wait up to 15 s until "WatchSendSent" is listed Verify "WatchSendResultAmount" reads "1 000" - Wait 4 s and verify the Balance page: "WatchHomeBalance" is listed and "WatchSendSent" is not + Wait 4 s + Verify the Balance page: "WatchHomeBalance" is listed + Verify "WatchSendSent" is not listed diff --git a/journeys/wear/send-hold-cancel.xml b/journeys/wear/send-hold-cancel.xml index ab5734af98..1d0e96946d 100644 --- a/journeys/wear/send-hold-cancel.xml +++ b/journeys/wear/send-hold-cancel.xml @@ -13,9 +13,11 @@ Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` Wait up to 10 s until "WatchSendHold" is listed Tap "WatchSendHold" once - Wait 3 s and verify "WatchSendHold" is still listed and "WatchSendSending" is not - Hold "WatchSendHold" for 0.5 s as in README › Holding to pay, then release - Wait 3 s and verify "WatchSendHold" is still listed and "WatchSendSending" is not + Wait 3 s + Verify the review stays: "WatchSendHold" is still listed + Hold "WatchSendHold" for 0.5 s and release, as in README › Holding to pay + Wait 3 s + Verify the review stays: "WatchSendHold" is still listed Swipe to dismiss from the left edge: `adb shell input swipe 20 227 400 227 300` Verify "WatchHomeBalance" still reads <balance> From 5bb830b526041bfeff7da914d5e7ba74ed2e18eb Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 03:45:31 -0300 Subject: [PATCH 17/33] fix: hide the paid amount in ambient, show a stalled retry as pending Co-Authored-By: Claude Fable 5.2 --- .../java/to/bitkit/wear/models/Payments.kt | 9 +- .../bitkit/wear/repositories/PaymentsRepo.kt | 19 +++- .../ui/screens/receive/ReceiveQrScreen.kt | 58 ++++++++---- .../wear/repositories/PaymentsRepoTest.kt | 32 ++++++- .../screens/receive/ReceiveQrContentTest.kt | 94 +++++++++++++++++++ 5 files changed, 180 insertions(+), 32 deletions(-) create mode 100644 wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt diff --git a/wear/src/main/java/to/bitkit/wear/models/Payments.kt b/wear/src/main/java/to/bitkit/wear/models/Payments.kt index 1910b0ceb0..8a605918eb 100644 --- a/wear/src/main/java/to/bitkit/wear/models/Payments.kt +++ b/wear/src/main/java/to/bitkit/wear/models/Payments.kt @@ -122,12 +122,15 @@ sealed class SendError(message: String, cause: Throwable? = null) : AppError(mes /** This wallet already paid the invoice, or an earlier transfer to the Spark address went through after all. */ class AlreadyPaid : SendError("The request is already paid") - /** A send of this request is still under way, from the watch or the phone: Spark lists it as pending. */ + /** + * A send of this request is still under way, from the watch or the phone: Spark lists it as pending, or Spark + * has not returned the watch's own call of it yet. + */ class InFlight : SendError("A payment of this request is under way") /** - * Another send holds the wallet: one that is running, or one whose call Spark has not returned yet. Nothing of - * this request was sent, and it can be tried again once that send is over. + * Another send holds the wallet: one that is running, or one of another request whose call Spark has not + * returned yet. Nothing of this request was sent, and it can be tried again once that send is over. */ class Busy : SendError("The wallet is busy with another payment") diff --git a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt index 2aeda71a52..51f9c537fc 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -108,6 +108,9 @@ class PaymentsRepo @Inject constructor( /** The SDK's send call of the last send, which can outlive it when it stalls. Guarded by [sendMutex]. */ private var sendCall: Job? = null + /** The request [sendCall] pays: its invoice's payment hash or its Spark payee. Guarded by [sendMutex]. */ + private var sendCallRequest: String? = null + /** Emits whenever Spark reports a payment or a sync, so the activity list reads [recentPayments] again. */ val paymentChanges: Flow get() = sparkService.events.map { } @@ -356,9 +359,10 @@ class PaymentsRepo @Inject constructor( * when Spark took it and it did not settle within [SETTLE_TIMEOUT]. The send does not run in the caller's scope: * a caller that goes away neither cancels it nor loses its bookkeeping. Fails with a [SendError]: * [SendError.NotReady], also when Spark cannot be reached to bring its list up to date, [SendError.AlreadyPaid], - * [SendError.InFlight], [SendError.Busy] while another send runs or Spark still holds the call of one that - * stalled, [SendError.Expired], [SendError.InsufficientBalance], [SendError.Failed], and [SendError.Unknown] when - * the payment may have gone out. + * [SendError.InFlight], also while Spark still holds the stalled call of this same request, [SendError.Busy] + * while another send runs or Spark holds the stalled call of another request, [SendError.Expired], + * [SendError.InsufficientBalance], [SendError.Failed], and [SendError.Unknown] when the payment may have gone + * out. * * An invoice is sent under the idempotency key the phone derives for it too, so Spark pays it once however often * and from whichever device it is sent; each attempt Spark lists as failed moves to the next key. A Spark address @@ -372,7 +376,11 @@ class PaymentsRepo @Inject constructor( // Another send holds the wallet: nothing of this request is sent, so it is not reported as under way. if (!sendMutex.tryLock()) throw SendError.Busy() try { - if (sendCall?.isActive == true) throw SendError.Busy() + if (sendCall?.isActive == true) { + // The stalled call is this request's own and may still pay, so it is under way, not refused. + val request = prepared.requestId() + throw if (request != null && request == sendCallRequest) SendError.InFlight() else SendError.Busy() + } if (!isReady()) throw SendError.NotReady() val sparkPayee = prepared.sparkPayee val key = if (sparkPayee != null) { @@ -491,6 +499,7 @@ class PaymentsRepo @Inject constructor( // The SDK call cannot be cancelled, so it runs beside this wait, which gives up on a call that stalls. val call = sendScope.async { runSuspendCatching { sparkService.send(prepared.response, key) } } sendCall = call + sendCallRequest = prepared.requestId() val result = withTimeoutOrNull(SEND_TIMEOUT) { call.await() } ?: Result.failure(SendError.Unknown()) return result.getOrElse { recoverSend(it, key, wasUncertain) } @@ -522,6 +531,8 @@ class PaymentsRepo @Inject constructor( throw SendError.Unknown(error) } + private fun PreparedSend.requestId(): String? = paymentHash?.lowercase() ?: sparkPayee + /** Drops the note of the send under [key]. A note that stays only makes a later send more careful. */ private suspend fun settle(key: String) { runSuspendCatching { uncertainSendStore.settle(key) } diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt index 4e42bfd65c..aa4cea0fd6 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt @@ -66,8 +66,9 @@ internal val QR_AWAKE_LIMIT = 2.minutes * The receive QR, as large as the round screen allows, at full brightness and with the screen kept on while it * shows. After [QR_AWAKE_LIMIT] without a touch it rests: the QR hides behind a dimmed icon and the screen may turn * off again, so a forgotten QR does not drain the battery; a tap, or waking the watch from ambient mode, shows it - * again. Ambient mode hides it. A paid invoice turns into a check with the amount and its own haptic; a tap on the - * check makes a new invoice. + * again, as does a tap anywhere on the resting screen. Ambient mode hides it. A paid invoice turns into a check with + * the amount and its own haptic; a tap on the check makes a new invoice. In ambient mode the check shows without + * the amount, as the always-on screen shows no amount. */ @Composable fun ReceiveQrScreen( @@ -92,7 +93,7 @@ fun ReceiveQrScreen( } // A watch that wakes from ambient mode shows the QR again, and so does the invoice after a paid one. LaunchedEffect(isAmbient, isPaid) { if (isAmbient || isPaid) isResting = false } - Content( + ReceiveQrContent( uiState = uiState, isAmbient = isAmbient, isResting = isResting, @@ -104,7 +105,7 @@ fun ReceiveQrScreen( } @Composable -private fun Content( +internal fun ReceiveQrContent( uiState: ReceiveUiState, isAmbient: Boolean, onRefreshClick: () -> Unit, @@ -116,7 +117,11 @@ private fun Content( val qrContent = uiState.qrContent val paidAmount = uiState.paidAmount when { - paidAmount != null -> Paid(amount = paidAmount, onClick = onRefreshClick, modifier = modifier) + paidAmount != null -> Paid( + amount = paidAmount.takeUnless { isAmbient }, + onClick = onRefreshClick, + modifier = modifier + ) qrContent != null && isAmbient -> Hidden(modifier = modifier) qrContent != null && isResting -> Hidden(onClick = onShowClick, modifier = modifier) qrContent != null -> Qr(content = qrContent, onTouch = onQrTouch, modifier = modifier) @@ -167,13 +172,13 @@ private fun Hidden( ) { val description = stringResource(R.string.receive__hidden) val showLabel = stringResource(R.string.receive__show) - CenteredScreen(modifier = modifier) { - QrIcon( - modifier = Modifier - .clickableAlpha(onClickLabel = showLabel, enabled = onClick != null, onClick = { onClick?.invoke() }) - .semantics { contentDescription = description } - .testTag("WatchReceiveHidden") - ) + CenteredScreen( + modifier = modifier + .clickableAlpha(onClickLabel = showLabel, enabled = onClick != null, onClick = { onClick?.invoke() }) + .semantics { contentDescription = description } + .testTag("WatchReceiveHidden") + ) { + QrIcon() } } @@ -189,10 +194,11 @@ private fun QrIcon(modifier: Modifier = Modifier) { @Composable private fun Paid( - amount: DisplayAmount, + amount: DisplayAmount?, onClick: () -> Unit, modifier: Modifier = Modifier, ) { + val isDimmed = amount == null CenteredScreen(modifier = modifier) { Column( horizontalAlignment = Alignment.CenterHorizontally, @@ -204,10 +210,10 @@ private fun Paid( Icon( painter = painterResource(R.drawable.ic_check), contentDescription = stringResource(R.string.receive__paid), - tint = Colors.Brand, + tint = if (isDimmed) Colors.White.copy(alpha = HIDDEN_ALPHA) else Colors.Brand, modifier = Modifier.size(MARK_SIZE) ) - SmallAmountRow(amount = amount, amountTag = "WatchReceivePaidAmount") + amount?.let { SmallAmountRow(amount = it, amountTag = "WatchReceivePaidAmount") } } } } @@ -242,7 +248,7 @@ private fun Error( @Composable private fun Preview() { WearPreview { - Content( + ReceiveQrContent( uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), isAmbient = false, onRefreshClick = {}, @@ -254,7 +260,7 @@ private fun Preview() { @Composable private fun PreviewPaid() { WearPreview { - Content( + ReceiveQrContent( uiState = ReceiveUiState(paidAmount = DisplayAmount(symbol = "₿", text = "21 000")), isAmbient = false, onRefreshClick = {}, @@ -262,11 +268,23 @@ private fun PreviewPaid() { } } +@WearPreviewDevices +@Composable +private fun PreviewPaidAmbient() { + WearPreview { + ReceiveQrContent( + uiState = ReceiveUiState(paidAmount = DisplayAmount(symbol = "₿", text = "21 000")), + isAmbient = true, + onRefreshClick = {}, + ) + } +} + @WearPreviewDevices @Composable private fun PreviewAmbient() { WearPreview { - Content( + ReceiveQrContent( uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), isAmbient = true, onRefreshClick = {}, @@ -278,7 +296,7 @@ private fun PreviewAmbient() { @Composable private fun PreviewResting() { WearPreview { - Content( + ReceiveQrContent( uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), isAmbient = false, onRefreshClick = {}, @@ -291,7 +309,7 @@ private fun PreviewResting() { @Composable private fun PreviewError() { WearPreview { - Content( + ReceiveQrContent( uiState = ReceiveUiState(isError = true), isAmbient = false, onRefreshClick = {}, diff --git a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt index b9ce1c687d..0d1b37963a 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -774,7 +774,7 @@ class PaymentsRepoTest : BaseUnitTest() { } @Test - fun `a send call that stalls ends as unknown, and nothing else is sent until spark returns it`() = test { + fun `a send call that stalls ends as unknown, and its request is under way until spark returns it`() = test { val prepared = preparedSend() var answer = CompletableDeferred() whenever(sparkService.send(any(), any())).doSuspendableAnswer { answer.await() } @@ -783,8 +783,9 @@ class PaymentsRepoTest : BaseUnitTest() { assertEquals(PaymentsRepo.SEND_TIMEOUT.inWholeMilliseconds, testScheduler.currentTime) assertEquals(setOf("key-0"), uncertainSends.sends.keys) - assertIs(sut.send(prepared).exceptionOrNull()) + assertIs(sut.send(prepared).exceptionOrNull()) verify(sparkService).send(any(), any()) + assertEquals(setOf("key-0"), uncertainSends.sends.keys) val stalled = answer answer = CompletableDeferred(payment("key-0", PaymentStatus.COMPLETED)) @@ -792,6 +793,23 @@ class PaymentsRepoTest : BaseUnitTest() { assertTrue(sut.send(prepared).isSuccess) } + @Test + fun `a transfer to the payee of a stalled transfer is under way, by either review, and sends nothing`() = test { + stubTransfer() + whenever(sparkService.send(any(), any())).doSuspendableAnswer { CompletableDeferred().await() } + val request = SendRequest.SparkAddress(SPARK_ADDRESS) + val first = sut.prepare(request, 500uL).getOrThrow() + assertIs(sut.send(first).exceptionOrNull()) + val noted = uncertainSends.sends.keys.toSet() + + assertIs(sut.send(first).exceptionOrNull()) + assertIs(sut.send(sut.prepare(request, 500uL).getOrThrow()).exceptionOrNull()) + assertIs(sut.send(preparedSend()).exceptionOrNull()) + + verify(sparkService).send(any(), any()) + assertEquals(noted, uncertainSends.sends.keys) + } + @Test fun `a send goes on and is settled after its caller is cancelled`() = test { val release = CompletableDeferred() @@ -836,7 +854,7 @@ class PaymentsRepoTest : BaseUnitTest() { val other = "lnbcrt1other" val otherHash = "cd".repeat(32) whenever(sparkService.parse(other)).thenReturn(invoiceInput(other, otherHash)) - whenever(sparkService.prepareSend(eq(other), anyOrNull())).thenReturn(prepared()) + whenever(sparkService.prepareSend(eq(other), anyOrNull())).thenReturn(prepared(paymentHash = otherHash)) val otherPrepared = sut.prepare(SendRequest.Invoice(other, 500uL, null)).getOrThrow() whenever(sparkService.send(any(), any())).doSuspendableAnswer { CompletableDeferred().await() } assertIs(sut.send(preparedSend()).exceptionOrNull()) @@ -1128,9 +1146,13 @@ class PaymentsRepoTest : BaseUnitTest() { return mutableListOf() } - private fun prepared(sparkTransferFeeSats: ULong? = null, amountMsat: ULong? = null) = PrepareSendPaymentResponse( + private fun prepared( + sparkTransferFeeSats: ULong? = null, + amountMsat: ULong? = null, + paymentHash: String = PAYMENT_HASH, + ) = PrepareSendPaymentResponse( paymentMethod = SendPaymentMethod.Bolt11Invoice( - SparkFixtures.invoice(BOLT11, amountMsat = amountMsat), + SparkFixtures.invoice(BOLT11, paymentHash, amountMsat = amountMsat), sparkTransferFeeSats, FEE, ), diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt new file mode 100644 index 0000000000..ec15e28161 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt @@ -0,0 +1,94 @@ +package to.bitkit.wear.ui.screens.receive + +import androidx.activity.ComponentActivity +import androidx.compose.ui.test.assertContentDescriptionEquals +import androidx.compose.ui.test.assertHasNoClickAction +import androidx.compose.ui.test.click +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.onRoot +import androidx.compose.ui.test.performTouchInput +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowSystemClock +import to.bitkit.wear.ui.components.WearPreview +import to.bitkit.wear.ui.screens.home.DisplayAmount +import kotlin.test.assertEquals +import kotlin.time.Duration.Companion.seconds +import kotlin.time.toJavaDuration + +/** What the receive QR screen shows once paid, in ambient mode and while it rests. */ +@Config(sdk = [34], qualifiers = "w227dp-h227dp-round") +@RunWith(RobolectricTestRunner::class) +class ReceiveQrContentTest { + @get:Rule + val composeRule = createAndroidComposeRule() + + private val paid = ReceiveUiState(paidAmount = DisplayAmount(symbol = "₿", text = "50 000")) + private val shown = ReceiveUiState(qrContent = "LNBCRT1TEST") + private var shows = 0 + + @Test + fun `a paid invoice shows the check with its amount`() { + setContent(paid, isAmbient = false) + + composeRule.onNodeWithTag("WatchReceivePaid").assertExists() + composeRule.onNodeWithContentDescription("Paid").assertExists() + composeRule.onNodeWithTag("WatchReceivePaidAmount", useUnmergedTree = true).assertExists() + composeRule.onNodeWithText("50 000", useUnmergedTree = true).assertExists() + } + + @Test + fun `a paid invoice in ambient mode shows the check without its amount`() { + setContent(paid, isAmbient = true) + + composeRule.onNodeWithTag("WatchReceivePaid").assertExists() + composeRule.onNodeWithContentDescription("Paid").assertExists() + composeRule.onNodeWithTag("WatchReceivePaidAmount", useUnmergedTree = true).assertDoesNotExist() + composeRule.onNodeWithText("50 000", useUnmergedTree = true).assertDoesNotExist() + composeRule.onNodeWithText("₿", useUnmergedTree = true).assertDoesNotExist() + composeRule.onNodeWithTag("WatchReceiveHidden").assertDoesNotExist() + } + + @Test + fun `a tap anywhere on the resting screen shows the qr again`() { + setContent(shown, isAmbient = false, isResting = true) + val hidden = composeRule.onNodeWithTag("WatchReceiveHidden") + + hidden.assertContentDescriptionEquals("QR hidden") + assertEquals(composeRule.onRoot().fetchSemanticsNode().size, hidden.fetchSemanticsNode().size) + // The click debounce counts from the uptime, which starts at zero here. + ShadowSystemClock.advanceBy(2.seconds.toJavaDuration()) + hidden.performTouchInput { click(percentOffset(0.5f, 0.1f)) } + composeRule.waitForIdle() + + assertEquals(1, shows) + } + + @Test + fun `the qr hidden by ambient mode takes no tap`() { + setContent(shown, isAmbient = true) + + composeRule.onNodeWithTag("WatchReceiveHidden").assertHasNoClickAction() + composeRule.onNodeWithTag("WatchReceiveQr").assertDoesNotExist() + } + + private fun setContent(uiState: ReceiveUiState, isAmbient: Boolean, isResting: Boolean = false) { + composeRule.setContent { + WearPreview { + ReceiveQrContent( + uiState = uiState, + isAmbient = isAmbient, + onRefreshClick = {}, + isResting = isResting, + onShowClick = { shows++ }, + ) + } + } + } +} From 93bb24e32fc2c9d40f6cd03e3a6f255b02b447e6 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 03:45:32 -0300 Subject: [PATCH 18/33] docs: update wear payments docs and journeys for round 3 fixes Co-Authored-By: Claude Fable 5.2 --- docs/wear.md | 11 +++++++---- journeys/wear/README.md | 5 +++-- journeys/wear/receive-paid-ambient.xml | 23 +++++++++++++++++++++++ journeys/wear/receive-qr-rests.xml | 2 +- 4 files changed, 34 insertions(+), 7 deletions(-) create mode 100644 journeys/wear/receive-paid-ambient.xml diff --git a/docs/wear.md b/docs/wear.md index 075fbb938e..5db03b5fdf 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -157,7 +157,7 @@ On-screen copy stays short: a title or one line of at most about six words per s screen (1/√2 of its width). Each module is one bitmap pixel scaled up without smoothing (zxing, as on the phone). While the QR shows, the screen stays on at full brightness; both end when it leaves. After 2 min without a touch the QR rests: it hides behind the dimmed QR icon (`WatchReceiveHidden`, "Show QR") and the screen may turn off - again, so a forgotten QR does not hold the screen at full brightness; a tap on the icon, or waking the watch from + again, so a forgotten QR does not hold the screen at full brightness; a tap anywhere on that screen, or waking the watch from ambient mode, shows it for another 2 min. The invoice is made once the wallet is ready, under the loading ring; a failure shows one line and a retry (`WatchReceiveError`, `WatchReceiveRetry`). An invoice is replaced by a new one a minute before it expires, and it stays on screen until @@ -167,7 +167,8 @@ On-screen copy stays short: a title or one line of at most about six words per s invoice shows for at least 30 s, also when the watch's clock runs ahead. Paid, the QR turns into a check with the amount (`WatchReceivePaid`, `WatchReceivePaidAmount`) and a firm click (the `LongPress` haptic), unlike the confirm pattern that ends a send; a tap on the check shows a new invoice. In ambient mode the QR is replaced by - a dimmed QR icon (`WatchReceiveHidden`). Debug builds log each invoice shown (`Showing invoice`), which is how the + a dimmed QR icon (`WatchReceiveHidden`), and an invoice paid meanwhile shows the check dimmed and without the + amount, with the same haptic, so the always-on screen shows no amount; the amount shows once the watch wakes. Debug builds log each invoice shown (`Showing invoice`), which is how the journeys read it. - **Send.** There is no Send page or button. A `lightning:`, `bitcoin:` or `spark:` link opens the app (`MainActivity` is `singleTop`, so a link reaches the open app) and the send flow above Home; without a wallet, @@ -195,7 +196,8 @@ On-screen copy stays short: a title or one line of at most about six words per s did not settle in time, or one that was already under way, from the watch or the phone, shows a clock and "Pending"; an outcome Spark could not report shows "Check activity", never a failure; both close after 3 s. The amount is the one Spark paid. A request that was not sent because another send still holds the wallet shows - "Wallet busy" as a failure, never "Pending". A refusal or a failure shows a cross, one line of at most four words and + "Wallet busy" as a failure, never "Pending"; the request whose own stalled call Spark still holds shows "Pending", + since that call may still pay. A refusal or a failure shows a cross, one line of at most four words and an OK button (`WatchSendError`, `WatchSendClose`), with the reject haptic. Insufficient funds, an expired or unreadable invoice and an own invoice end there before any hold. - **Activity.** The Activity page lists the newest 20 payments from Spark's local list: a direction icon (or a @@ -243,7 +245,8 @@ in any other state. by closing, and one send runs at a time. An invoice's send first syncs with Spark, for up to 20 s, and is refused when the sync does not reach Spark. The call returns when Spark has the payment; a call that stalls for a minute ends as an unknown outcome, and nothing else is sent until Spark returns that call: another request is - refused as busy (`SendError.Busy`, "Wallet busy"), since nothing of it went out. The result then waits + refused as busy (`SendError.Busy`, "Wallet busy"), since nothing of it went out, and the same request (the same + invoice, or a transfer to the same Spark wallet) is reported as under way (`SendError.InFlight`, "Pending"). The result then waits up to a minute for the payment to settle and reports it as pending after that. A lock, a pause or a wipe waits up to 10 s for a send before it disconnects, from the moment the send is noted until Spark returns its call; a wallet that is disconnected before Spark got the call, or wiped before the note was written, sent nothing: "Wallet not ready", and no note stays. The send screen keeps the screen on, so the app stays on screen and connected while it waits. diff --git a/journeys/wear/README.md b/journeys/wear/README.md index 9311f870c3..596c32c992 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -15,8 +15,8 @@ What `android layout` misses on the watch, verified on the API 37 emulator: - **The pending and hidden marks.** `WatchHomeBalancePending` has no text either, so `android layout` leaves it out; `uiautomator dump` lists it. The same goes for `RestoreHidden`, the empty screen the restore shows in ambient mode. - **The receive QR.** `WatchReceiveQr` is an image with no text or action, so `android layout` leaves it out; - `adb shell uiautomator dump` lists it. Check it there or from a screenshot. `WatchReceiveHidden`, the dimmed icon - that replaces it in ambient mode and once it rests, has a content-desc and is listed. + `adb shell uiautomator dump` lists it. Check it there or from a screenshot. `WatchReceiveHidden`, the screen with the + dimmed icon that replaces it in ambient mode and once it rests, has a content-desc and is listed. - **Suggestion chips.** A chip's tag (`RestoreSuggestion-0`, counted from 0) is on the button and its word is a text node at the same `center`. A chip below the screen edge is not listed until the screen scrolls. - **The keyboard.** The Wear OS keyboard is a full-screen window that `android layout` does not show. It lists the @@ -116,6 +116,7 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `receive-qr.xml` | local | no | | `receive-qr-rests.xml` | local | no | | `receive-paid.xml` | local | no, it funds the wallet with 50 000 sats | +| `receive-paid-ambient.xml` | local | no | | `send-deeplink-bolt11.xml` | local | yes, 2 000 sats | | `send-hold-cancel.xml` | local | yes, 2 000 sats | | `send-ambient-hides-amount.xml` | local | yes, 2 000 sats | diff --git a/journeys/wear/receive-paid-ambient.xml b/journeys/wear/receive-paid-ambient.xml new file mode 100644 index 0000000000..bd5c7a00eb --- /dev/null +++ b/journeys/wear/receive-paid-ambient.xml @@ -0,0 +1,23 @@ + + + An invoice paid while the watch is in ambient mode shows the check without the amount, so the always-on screen + shows no amount; waking the watch shows the amount. Emulator and physical watch. + + Precondition: Restored wallet on the local ./spark stack, see journeys/wear/README.md › Local ./spark stack and + › Restored wallet, on the Balance page with the loading ring stopped, and the always-on screen on (README › Watch + gestures). Gestures are written for the 454 px screen; scale them as in README › What differs. + + + Swipe the pager left once: `adb shell input swipe 400 227 60 227 300` + Tap "WatchReceiveOpen" + Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) + Read the invoice from the log as in README › Reading the receive invoice and note it as <invoice> + Run `adb shell input keyevent KEYCODE_SLEEP` + Wait up to 5 s until "WatchReceiveHidden" is listed + Run `../bitkit-docker/spark pay <invoice> 1000` from this repo's parent checkout + Wait up to 20 s until "WatchReceivePaid" is listed + Verify "WatchReceivePaidAmount" is not listed + Run `adb shell input keyevent KEYCODE_WAKEUP` + Wait up to 5 s until "WatchReceivePaidAmount" reads "1 000" + + diff --git a/journeys/wear/receive-qr-rests.xml b/journeys/wear/receive-qr-rests.xml index 22ff884b61..d1e8efde80 100644 --- a/journeys/wear/receive-qr-rests.xml +++ b/journeys/wear/receive-qr-rests.xml @@ -1,7 +1,7 @@ A receive QR that is not touched for 2 min rests: it hides behind the dimmed QR icon and stops holding the screen - on at full brightness; a tap shows it again. Emulator and physical watch. + on at full brightness; a tap anywhere on the screen shows it again. Emulator and physical watch. Precondition: Restored wallet on the local ./spark stack, see journeys/wear/README.md › Local ./spark stack and › Restored wallet, on the Balance page with the loading ring stopped, and the always-on screen on (README › Watch From 2432f7a55b11b2075609d2d5154923b974b7095e Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 03:48:19 -0300 Subject: [PATCH 19/33] docs: run the wear ambient paid journey after the activity list Co-Authored-By: Claude Opus 5.5 --- journeys/wear/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/journeys/wear/README.md b/journeys/wear/README.md index 596c32c992..a1d1bf84bb 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -116,13 +116,13 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `receive-qr.xml` | local | no | | `receive-qr-rests.xml` | local | no | | `receive-paid.xml` | local | no, it funds the wallet with 50 000 sats | -| `receive-paid-ambient.xml` | local | no | | `send-deeplink-bolt11.xml` | local | yes, 2 000 sats | | `send-hold-cancel.xml` | local | yes, 2 000 sats | | `send-ambient-hides-amount.xml` | local | yes, 2 000 sats | | `send-insufficient.xml` | local | yes, less than 10 000 000 sats | | `send-own-invoice-guard.xml` | local | yes, any balance above 0 | | `activity-list.xml` | local | yes, after `receive-paid.xml` and `send-deeplink-bolt11.xml` | +| `receive-paid-ambient.xml` | local | no, it funds the wallet with 1 000 sats | Paying an LNURL-pay link or a Lightning address has no journey: the local stack's LNURL server serves only the Lightning addresses its Spark wallets registered, over plain HTTP, and nothing in it registers one. It is covered by From 7744a5cd188ad6e770094a9be33f39e49380a079 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 03:48:41 -0300 Subject: [PATCH 20/33] docs: limit the wear payments changelog to the phone guard Co-Authored-By: Claude Opus 5.5 --- changelog.d/next/2105.added.md | 1 - changelog.d/next/2105.fixed.md | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) delete mode 100644 changelog.d/next/2105.added.md create mode 100644 changelog.d/next/2105.fixed.md diff --git a/changelog.d/next/2105.added.md b/changelog.d/next/2105.added.md deleted file mode 100644 index 0ae274f3db..0000000000 --- a/changelog.d/next/2105.added.md +++ /dev/null @@ -1 +0,0 @@ -Added receiving with a QR code, paying payment links with a hold to pay, and recent activity to the Wear OS app, and the phone and the watch now refuse to pay Spark invoices their own wallet created. diff --git a/changelog.d/next/2105.fixed.md b/changelog.d/next/2105.fixed.md new file mode 100644 index 0000000000..0d6905760b --- /dev/null +++ b/changelog.d/next/2105.fixed.md @@ -0,0 +1 @@ +Fixed paying an invoice that your own wallet created through Spark, which Bitkit now refuses like its other own invoices. From 708eabdaa05cc4e0366e707c2104a197acfe8355 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 06:08:07 -0300 Subject: [PATCH 21/33] docs: stop the wear screen recorder before pulling the video Co-Authored-By: Claude Opus 5.5 --- journeys/wear/README.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/journeys/wear/README.md b/journeys/wear/README.md index a1d1bf84bb..dbe37d2277 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -340,12 +340,20 @@ android screen capture -o shot.png ``` Screen recordings, up to 170 s (the recorder stops at 180 s). The recording takes the screen's own size: 454 px -square on the large emulator, 384 px on the small one. +square on the large emulator, 384 px on the small one. Start the recorder in the background, run the steps, then +stop it and wait for it to finish writing before pulling the file: a file pulled while `screenrecord` still writes +has no `moov` atom and does not play. ```bash -adb shell screenrecord --time-limit 170 /sdcard/.mp4 +adb shell 'screenrecord --time-limit 170 /sdcard/.mp4' & +REC=$! +# ... run the journey's steps ... +adb shell pkill -INT screenrecord +wait "$REC" +sleep 2 adb pull /sdcard/.mp4 adb shell rm /sdcard/.mp4 +grep -q moov .mp4 || echo ".mp4 has no moov atom: record it again" ``` The word and passphrase screens record as black frames (`FLAG_SECURE`), which is what `screenshot-blocked.xml` From 3d358f21a5459f05dbf24f15101a976374f63d5d Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 06:17:29 -0300 Subject: [PATCH 22/33] feat: add a balance tile to the wear app Co-Authored-By: Claude Opus 5.5 --- gradle/libs.versions.toml | 5 + wear/build.gradle.kts | 5 + wear/src/main/AndroidManifest.xml | 15 ++ wear/src/main/java/to/bitkit/wear/WearApp.kt | 5 + .../to/bitkit/wear/tile/BalanceTileService.kt | 156 ++++++++++++++++++ .../java/to/bitkit/wear/tile/TileState.kt | 29 ++++ .../java/to/bitkit/wear/tile/TileUpdates.kt | 39 +++++ .../java/to/bitkit/wear/ui/LaunchRequest.kt | 14 +- .../java/to/bitkit/wear/ui/WearNavHost.kt | 6 +- wear/src/main/res/drawable/tile_logo.xml | 14 ++ wear/src/main/res/drawable/tile_logo_dim.xml | 14 ++ wear/src/main/res/drawable/tile_preview.xml | 26 +++ .../java/to/bitkit/wear/tile/TileStateTest.kt | 66 ++++++++ .../to/bitkit/wear/ui/LaunchRequestTest.kt | 19 ++- 14 files changed, 403 insertions(+), 10 deletions(-) create mode 100644 wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt create mode 100644 wear/src/main/java/to/bitkit/wear/tile/TileState.kt create mode 100644 wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt create mode 100644 wear/src/main/res/drawable/tile_logo.xml create mode 100644 wear/src/main/res/drawable/tile_logo_dim.xml create mode 100644 wear/src/main/res/drawable/tile_preview.xml create mode 100644 wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 757541c425..4eea812d0e 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -15,6 +15,7 @@ navCompose = "2.9.8" room = "2.8.5" slf4j = "2.0.20" wearCompose = "1.7.2" +wearProtolayout = "1.4.2" haze = "1.7.3" [libraries] @@ -105,6 +106,10 @@ wear-compose-foundation = { module = "androidx.wear.compose:compose-foundation", wear-compose-material3 = { module = "androidx.wear.compose:compose-material3", version.ref = "wearCompose" } wear-compose-navigation = { module = "androidx.wear.compose:compose-navigation", version.ref = "wearCompose" } wear-tooling-preview = { module = "androidx.wear:wear-tooling-preview", version = "1.0.0" } +wear-tiles = { module = "androidx.wear.tiles:tiles", version = "1.6.2" } +wear-protolayout = { module = "androidx.wear.protolayout:protolayout", version.ref = "wearProtolayout" } +wear-protolayout-material3 = { module = "androidx.wear.protolayout:protolayout-material3", version.ref = "wearProtolayout" } +concurrent-futures-ktx = { module = "androidx.concurrent:concurrent-futures-ktx", version = "1.2.0" } lottie = { module = "com.airbnb.android:lottie-compose", version = "6.7.1" } charts = { module = "io.github.ehsannarmani:compose-charts", version = "1.0.0" } coil-bom = { module = "io.coil-kt.coil3:coil-bom", version.ref = "coil" } diff --git a/wear/build.gradle.kts b/wear/build.gradle.kts index b9d3c05fda..1e7e270c23 100644 --- a/wear/build.gradle.kts +++ b/wear/build.gradle.kts @@ -247,6 +247,11 @@ dependencies { implementation(libs.wear.compose.material3) implementation(libs.wear.compose.navigation) implementation(libs.wear.tooling.preview) + // Tile + implementation(libs.wear.tiles) + implementation(libs.wear.protolayout) + implementation(libs.wear.protolayout.material3) + implementation(libs.concurrent.futures.ktx) // Hilt - DI implementation(libs.hilt.android) ksp(libs.hilt.android.compiler) diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index 84492b4b6f..0d28366d37 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -75,5 +75,20 @@ + + + + + + + + + diff --git a/wear/src/main/java/to/bitkit/wear/WearApp.kt b/wear/src/main/java/to/bitkit/wear/WearApp.kt index 493d70e7c1..1682d6b450 100644 --- a/wear/src/main/java/to/bitkit/wear/WearApp.kt +++ b/wear/src/main/java/to/bitkit/wear/WearApp.kt @@ -5,6 +5,7 @@ import android.os.StrictMode import dagger.hilt.android.HiltAndroidApp import to.bitkit.wear.data.ForegroundMonitor import to.bitkit.wear.env.Env +import to.bitkit.wear.tile.TileUpdates import to.bitkit.wear.utils.Logger import javax.inject.Inject @@ -14,10 +15,14 @@ class WearApp : Application() { @Inject lateinit var foregroundMonitor: ForegroundMonitor + @Inject + lateinit var tileUpdates: TileUpdates + override fun onCreate() { if (Env.isDebug) logMainThreadBlocking() super.onCreate() if (Env.isDebug) Logger.init { filesDir } + tileUpdates.start() } /** diff --git a/wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt b/wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt new file mode 100644 index 0000000000..567d586a6f --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt @@ -0,0 +1,156 @@ +package to.bitkit.wear.tile + +import android.content.ComponentName +import androidx.compose.ui.graphics.toArgb +import androidx.concurrent.futures.SuspendToFutureAdapter +import androidx.wear.protolayout.ActionBuilders +import androidx.wear.protolayout.DeviceParametersBuilders.DeviceParameters +import androidx.wear.protolayout.DimensionBuilders.dp +import androidx.wear.protolayout.LayoutElementBuilders +import androidx.wear.protolayout.ResourceBuilders +import androidx.wear.protolayout.TimelineBuilders +import androidx.wear.protolayout.material3.ColorScheme +import androidx.wear.protolayout.material3.MaterialScope +import androidx.wear.protolayout.material3.Typography +import androidx.wear.protolayout.material3.icon +import androidx.wear.protolayout.material3.iconEdgeButton +import androidx.wear.protolayout.material3.materialScope +import androidx.wear.protolayout.material3.primaryLayout +import androidx.wear.protolayout.material3.text +import androidx.wear.protolayout.material3.textEdgeButton +import androidx.wear.protolayout.modifiers.LayoutModifier +import androidx.wear.protolayout.modifiers.clickable +import androidx.wear.protolayout.modifiers.contentDescription +import androidx.wear.protolayout.types.argb +import androidx.wear.protolayout.types.layoutString +import androidx.wear.tiles.RequestBuilders +import androidx.wear.tiles.TileBuilders +import androidx.wear.tiles.TileService +import com.google.common.util.concurrent.ListenableFuture +import dagger.hilt.android.AndroidEntryPoint +import to.bitkit.wear.R +import to.bitkit.wear.repositories.WalletRepo +import to.bitkit.wear.ui.LaunchRequest +import to.bitkit.wear.ui.MainActivity +import to.bitkit.wear.ui.screens.home.DisplayAmount +import to.bitkit.wear.ui.theme.Colors +import javax.inject.Inject +import kotlin.time.Duration.Companion.minutes + +/** + * The Bitkit tile: the balance the app loaded in this process, and an edge button that opens the receive QR. Without + * a wallet it shows the Bitkit mark and a button that opens the app. It only reads the wallet's state in memory and + * never starts the wallet, so until the app loaded the balance the dimmed mark stands in for it. + */ +@AndroidEntryPoint +class BalanceTileService : TileService() { + companion object { + private const val RESOURCES_VERSION = "2" + private const val ID_QR = "qr" + private const val ID_LOGO = "logo" + private const val ID_LOGO_DIM = "logo_dim" + private const val ID_RECEIVE = "receive" + private const val ID_OPEN = "open" + + /** How long a drawn tile stays valid without an update request, so a balance this process lost goes away. */ + private val FRESHNESS = 15.minutes + + /** The tile logo's height over its width. */ + private const val LOGO_ASPECT = 82f / 279f + + /** The share of the screen's width the Bitkit mark takes without a wallet, a little less than onboarding's. */ + private const val LOGO_WIDTH_SIGNED_OUT = 0.6f + + /** The share of the screen's width the mark takes where it stands in for a hidden balance, as on Balance. */ + private const val LOGO_WIDTH_HIDDEN = 0.4f + } + + @Inject + lateinit var walletRepo: WalletRepo + + override fun onTileRequest(requestParams: RequestBuilders.TileRequest): ListenableFuture = + SuspendToFutureAdapter.launchFuture { + val state = tileState(walletRepo.hasWallet(), walletRepo.walletState.value) + TileBuilders.Tile.Builder() + .setResourcesVersion(RESOURCES_VERSION) + .setFreshnessIntervalMillis(FRESHNESS.inWholeMilliseconds) + .setTileTimeline( + TimelineBuilders.Timeline.fromLayoutElement(layout(requestParams.deviceConfiguration, state)) + ) + .build() + } + + override fun onTileResourcesRequest( + requestParams: RequestBuilders.ResourcesRequest, + ): ListenableFuture = SuspendToFutureAdapter.launchFuture { + ResourceBuilders.Resources.Builder() + .setVersion(RESOURCES_VERSION) + .addIdToImageMapping(ID_QR, image(R.drawable.ic_qr_code)) + .addIdToImageMapping(ID_LOGO, image(R.drawable.tile_logo)) + .addIdToImageMapping(ID_LOGO_DIM, image(R.drawable.tile_logo_dim)) + .build() + } + + private fun layout(device: DeviceParameters, state: TileState) = materialScope( + context = this, + deviceConfiguration = device, + allowDynamicTheme = false, + defaultColorScheme = ColorScheme( + primary = Colors.Brand.toArgb().argb, + onPrimary = Colors.Black.toArgb().argb, + onSurface = Colors.White.toArgb().argb, + ), + ) { + when (state) { + TileState.SignedOut -> primaryLayout( + mainSlot = { logo(device, ID_LOGO, LOGO_WIDTH_SIGNED_OUT) }, + bottomSlot = { + textEdgeButton( + onClick = clickable(launchApp(openReceive = false), ID_OPEN), + labelContent = { text(getString(R.string.onboarding__restore).layoutString) }, + ) + }, + ) + is TileState.Wallet -> primaryLayout( + mainSlot = { state.balance?.let { balance(it) } ?: logo(device, ID_LOGO_DIM, LOGO_WIDTH_HIDDEN) }, + bottomSlot = { + iconEdgeButton( + onClick = clickable(launchApp(openReceive = true), ID_RECEIVE), + modifier = LayoutModifier.contentDescription(getString(R.string.receive__title)), + iconContent = { icon(ID_QR) }, + ) + }, + ) + } + } + + private fun MaterialScope.balance(amount: DisplayAmount) = text( + text = "${amount.symbol} ${amount.text}".layoutString, + typography = Typography.DISPLAY_SMALL, + color = Colors.White.toArgb().argb, + maxLines = 1, + ) + + private fun logo(device: DeviceParameters, id: String, widthShare: Float): LayoutElementBuilders.Image { + val width = device.screenWidthDp * widthShare + return LayoutElementBuilders.Image.Builder() + .setResourceId(id) + .setWidth(dp(width)) + .setHeight(dp(width * LOGO_ASPECT)) + .build() + } + + private fun launchApp(openReceive: Boolean): ActionBuilders.LaunchAction { + val activity = ComponentName(this, MainActivity::class.java) + val extras = if (openReceive) { + mapOf(LaunchRequest.EXTRA_OPEN to ActionBuilders.stringExtra(LaunchRequest.OPEN_RECEIVE)) + } else { + emptyMap() + } + return ActionBuilders.launchAction(activity, extras) + } + + private fun image(resId: Int) = ResourceBuilders.ImageResource.Builder() + .setAndroidResourceByResId(ResourceBuilders.AndroidImageResourceByResId.Builder().setResourceId(resId).build()) + .build() +} diff --git a/wear/src/main/java/to/bitkit/wear/tile/TileState.kt b/wear/src/main/java/to/bitkit/wear/tile/TileState.kt new file mode 100644 index 0000000000..245cbf1d2c --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/tile/TileState.kt @@ -0,0 +1,29 @@ +package to.bitkit.wear.tile + +import to.bitkit.wear.repositories.WalletState +import to.bitkit.wear.repositories.WalletStatus +import to.bitkit.wear.ui.screens.home.DisplayAmount +import to.bitkit.wear.ui.screens.home.bitcoinAmount +import java.util.Locale + +/** What the Bitkit tile shows. */ +sealed interface TileState { + /** No wallet on the watch: the tile only opens the app. */ + data object SignedOut : TileState + + /** A wallet with its [balance], or null while it is hidden; Receive opens the QR. */ + data class Wallet(val balance: DisplayAmount?) : TileState +} + +/** + * The tile's state for a watch that [hasWallet] in [wallet]'s state. The balance shows only once a sync of this + * process confirmed it, as on the Balance page, and never while the watch is locked; the tile never starts the wallet + * to learn it. + */ +fun tileState(hasWallet: Boolean, wallet: WalletState, locale: Locale = Locale.getDefault()): TileState { + if (!hasWallet || wallet.status in walletGoneStatuses) return TileState.SignedOut + val sats = wallet.balanceSats?.takeIf { wallet.hasSynced && wallet.status != WalletStatus.Locked }?.toLong() + return TileState.Wallet(sats?.let { bitcoinAmount(it, locale) }) +} + +private val walletGoneStatuses = setOf(WalletStatus.Removed, WalletStatus.Missing) diff --git a/wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt b/wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt new file mode 100644 index 0000000000..b2e4821edd --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt @@ -0,0 +1,39 @@ +package to.bitkit.wear.tile + +import android.content.Context +import androidx.wear.tiles.TileService +import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import to.bitkit.wear.di.IoDispatcher +import to.bitkit.wear.repositories.WalletRepo +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Asks the system to draw the tile again whenever what it shows may change: the balance, or the wallet's status, which + * also changes when a wallet is restored or removed. The first state of a process counts too, so a tile drawn by an + * earlier process drops the balance this one has not loaded. + */ +@Singleton +class TileUpdates @Inject constructor( + @ApplicationContext private val context: Context, + @IoDispatcher ioDispatcher: CoroutineDispatcher, + private val walletRepo: WalletRepo, +) { + private val scope = CoroutineScope(ioDispatcher + SupervisorJob()) + + /** Follows the wallet for the life of the process. */ + fun start() { + scope.launch { + walletRepo.walletState + .map { tileState(hasWallet = true, wallet = it) to it.status } + .distinctUntilChanged() + .collect { TileService.getUpdater(context).requestUpdate(BalanceTileService::class.java) } + } + } +} diff --git a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt index ac1a5fdae6..0fccedb934 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt @@ -7,17 +7,25 @@ sealed interface LaunchRequest { /** Pay the payment input of a `lightning:`, `bitcoin:` or `spark:` link. */ data class Send(val input: String) : LaunchRequest + /** Show the receive QR, as from the tile. */ + data object Receive : LaunchRequest + companion object { + /** The extra that asks for [Receive], set by the tile. */ + const val EXTRA_OPEN = "to.bitkit.wear.OPEN" + const val OPEN_RECEIVE = "receive" + private val SEND_SCHEMES = setOf("lightning", "bitcoin", "spark") - /** The request of an intent with [action] and [data], or null for a plain launch. */ - fun from(action: String?, data: String?): LaunchRequest? { + /** The request of an intent with [action], [data] and the [open] extra, or null for a plain launch. */ + fun from(action: String?, data: String?, open: String?): LaunchRequest? { + if (open == OPEN_RECEIVE) return Receive if (action != Intent.ACTION_VIEW || data.isNullOrBlank()) return null val scheme = data.substringBefore(':', missingDelimiterValue = "").lowercase() return if (scheme in SEND_SCHEMES) Send(data) else null } fun from(intent: Intent?): LaunchRequest? = - intent?.let { from(it.action, it.dataString) } + intent?.let { from(it.action, it.dataString, it.getStringExtra(EXTRA_OPEN)) } } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt b/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt index 2357deb408..a68932bb17 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt @@ -174,8 +174,9 @@ private fun NavController.showRestoreWord(index: Int) { } /** - * Opens what [request] asks for above Home: the send flow of a deeplink. Without a wallet, or outside Home's back - * stack, such as during the restore, the request is dropped; the caller drops it while a send is under way. + * Opens what [request] asks for above Home: the send flow of a deeplink, or the tile's receive QR. Without a wallet, + * or outside Home's back stack, such as during the restore, the request is dropped; the caller drops it while a send + * is under way. */ private fun NavController.showLaunchRequest(request: LaunchRequest) { val hasHome = runCatching { getBackStackEntry(Routes.HOME) }.isSuccess @@ -186,6 +187,7 @@ private fun NavController.showLaunchRequest(request: LaunchRequest) { popBackStack(Routes.HOME, inclusive = false) when (request) { is LaunchRequest.Send -> navigateTo(Routes.send(request.input)) + LaunchRequest.Receive -> navigateTo(Routes.RECEIVE_QR) } } diff --git a/wear/src/main/res/drawable/tile_logo.xml b/wear/src/main/res/drawable/tile_logo.xml new file mode 100644 index 0000000000..783e00ee31 --- /dev/null +++ b/wear/src/main/res/drawable/tile_logo.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/wear/src/main/res/drawable/tile_logo_dim.xml b/wear/src/main/res/drawable/tile_logo_dim.xml new file mode 100644 index 0000000000..3af4a500b0 --- /dev/null +++ b/wear/src/main/res/drawable/tile_logo_dim.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/wear/src/main/res/drawable/tile_preview.xml b/wear/src/main/res/drawable/tile_preview.xml new file mode 100644 index 0000000000..edbbb97dde --- /dev/null +++ b/wear/src/main/res/drawable/tile_preview.xml @@ -0,0 +1,26 @@ + + + + + + + + + + diff --git a/wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt b/wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt new file mode 100644 index 0000000000..206a2edf85 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt @@ -0,0 +1,66 @@ +package to.bitkit.wear.tile + +import org.junit.Test +import to.bitkit.wear.repositories.WalletState +import to.bitkit.wear.repositories.WalletStatus +import to.bitkit.wear.ui.screens.home.DisplayAmount +import java.util.Locale +import kotlin.test.assertEquals + +class TileStateTest { + @Test + fun `without a wallet the tile only opens the app`() { + assertEquals(TileState.SignedOut, tileState(hasWallet = false, WalletState(WalletStatus.Idle), Locale.US)) + } + + @Test + fun `a removed wallet signs the tile out before its seed is gone`() { + val synced = WalletState(WalletStatus.Ready, balanceSats = 1_000uL, hasSynced = true) + + assertEquals( + TileState.SignedOut, + tileState(hasWallet = true, synced.copy(status = WalletStatus.Missing), Locale.US), + ) + assertEquals( + TileState.SignedOut, + tileState(hasWallet = true, synced.copy(status = WalletStatus.Removed), Locale.US), + ) + } + + @Test + fun `a synced balance shows in bitcoin`() { + val wallet = WalletState(WalletStatus.Ready, balanceSats = 125_000uL, hasSynced = true) + + assertEquals( + TileState.Wallet(DisplayAmount("₿", "125 000")), + tileState(hasWallet = true, wallet, Locale.US), + ) + } + + @Test + fun `the balance stays hidden until a sync of this process confirmed it`() { + val notLoaded = WalletState(WalletStatus.Idle) + val unsynced = WalletState(WalletStatus.Connecting, balanceSats = 0uL, hasSynced = false) + val failed = WalletState(WalletStatus.Error, balanceSats = 5_000uL, hasSynced = false) + + assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, notLoaded, Locale.US)) + assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, unsynced, Locale.US)) + assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, failed, Locale.US)) + } + + @Test + fun `a paused or offline wallet keeps the balance it last synced`() { + val paused = WalletState(WalletStatus.Paused, balanceSats = 1_000uL, hasSynced = true) + val offline = paused.copy(status = WalletStatus.Offline) + + assertEquals(TileState.Wallet(DisplayAmount("₿", "1 000")), tileState(hasWallet = true, paused, Locale.US)) + assertEquals(TileState.Wallet(DisplayAmount("₿", "1 000")), tileState(hasWallet = true, offline, Locale.US)) + } + + @Test + fun `a locked watch hides the balance`() { + val locked = WalletState(WalletStatus.Locked, balanceSats = 1_000uL, hasSynced = true) + + assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, locked, Locale.US)) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt index 9befd24812..f105c2fbc1 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt @@ -9,15 +9,24 @@ class LaunchRequestTest { @Test fun `a payment link asks for a send of the whole link`() { for (link in listOf("lightning:lnbcrt1abc", "BITCOIN:bcrt1q?lightning=lnbcrt1abc", "spark:sprt1abc")) { - assertEquals(LaunchRequest.Send(link), LaunchRequest.from(Intent.ACTION_VIEW, link)) + assertEquals(LaunchRequest.Send(link), LaunchRequest.from(Intent.ACTION_VIEW, link, open = null)) } } + @Test + fun `the tile's extra asks for the receive QR`() { + assertEquals( + LaunchRequest.Receive, + LaunchRequest.from(Intent.ACTION_MAIN, data = null, open = LaunchRequest.OPEN_RECEIVE), + ) + } + @Test fun `a plain launch or another link asks for nothing`() { - assertNull(LaunchRequest.from(Intent.ACTION_MAIN, data = null)) - assertNull(LaunchRequest.from(Intent.ACTION_VIEW, data = "https://bitkit.to")) - assertNull(LaunchRequest.from(Intent.ACTION_VIEW, data = "lnbcrt1abc")) - assertNull(LaunchRequest.from(Intent.ACTION_SEND, data = "lightning:lnbcrt1abc")) + assertNull(LaunchRequest.from(Intent.ACTION_MAIN, data = null, open = null)) + assertNull(LaunchRequest.from(Intent.ACTION_VIEW, data = "https://bitkit.to", open = null)) + assertNull(LaunchRequest.from(Intent.ACTION_VIEW, data = "lnbcrt1abc", open = null)) + assertNull(LaunchRequest.from(Intent.ACTION_SEND, data = "lightning:lnbcrt1abc", open = null)) + assertNull(LaunchRequest.from(Intent.ACTION_MAIN, data = null, open = "send")) } } From 80fad64209a78eaf90b9530cdd217323a28bdcd5 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 06:17:29 -0300 Subject: [PATCH 23/33] docs: describe the wear balance tile and its journey Co-Authored-By: Claude Opus 5.5 --- docs/wear.md | 29 ++++++++++++++++++++++++++--- journeys/wear/README.md | 20 ++++++++++++++++++++ journeys/wear/tile-balance.xml | 23 +++++++++++++++++++++++ 3 files changed, 69 insertions(+), 3 deletions(-) create mode 100644 journeys/wear/tile-balance.xml diff --git a/docs/wear.md b/docs/wear.md index 5db03b5fdf..7f185c39c8 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -46,8 +46,8 @@ Breez SDK, with no LDK node, no Room database and no Firebase. The phone is only - **Play services components.** The Breez SDK's dependencies bring Play services' sign-in and credential components into the manifest: three activities and two services, one of them exported (`RevocationBoundService`). The watch app uses none of them, so its manifest removes them - (`tools:node="remove"`), and the merged manifest lists only `MainActivity` and the androidx startup and profile - components. The libraries themselves stay on the classpath, since Breez's classes load them. + (`tools:node="remove"`), and the merged manifest lists only `MainActivity`, the balance tile's service and the + androidx startup and profile components. The libraries themselves stay on the classpath, since Breez's classes load them. - **Main thread.** Nothing reads the disk, the network or a system service on the main thread at launch or while a screen composes. `NetworkMonitor`, `DeviceLock` and `NfcMonitor` are created empty and register with the system on the IO dispatcher; the HTTP client, the settings file and the seed directory are opened on first use there. @@ -75,10 +75,12 @@ Breez SDK, with no LDK node, no Room database and no Firebase. The phone is only client, `NetworkMonitor` (`ConnectivityManager`'s default network, online once the system validated it), `NfcMonitor` (the NFC adapter's state) and `ForegroundMonitor` (the process lifecycle: whether the app is on screen). +- `tile`: `BalanceTileService` (the balance tile), `TileState` (what it shows) and `TileUpdates` (asks the system + to draw it again). See Tile below. - `ui`: one `MainActivity` with `testTagsAsResourceId`, a `SwipeDismissableNavHost` with the routes Onboarding, the Restore graph, Wallet removed, Home, About, Receive QR, Send, Activity detail and Not supported, and the M3 Expressive theme (black background, Brand orange, Inter Tight). `LaunchRequest` reads what an intent asks for - beyond opening the app: a payment link. The splash screen stays while the first screen is picked, for at most about a second; + beyond opening the app: a payment link or the tile's Receive. The splash screen stays while the first screen is picked, for at most about a second; after that the loading ring shows until it is. When the wallet storage cannot be recovered at launch, the start error (`WatchStartError` with `WatchStartRetry`) shows instead of a first screen. @@ -170,6 +172,27 @@ On-screen copy stays short: a title or one line of at most about six words per s a dimmed QR icon (`WatchReceiveHidden`), and an invoice paid meanwhile shows the check dimmed and without the amount, with the same haptic, so the always-on screen shows no amount; the amount shows once the watch wakes. Debug builds log each invoice shown (`Showing invoice`), which is how the journeys read it. +- **Tile.** The Bitkit tile (`BalanceTileService`) uses the tiles and ProtoLayout Material 3 libraries: a primary + layout with the balance in the main slot and an edge button below. With a wallet it shows the balance in bitcoin + (white, as on the Balance page) and a round Brand orange edge button with the QR icon ("Receive" to accessibility + services), which opens the app on the receive QR: the launch intent carries the extra `to.bitkit.wear.OPEN` with + `receive`, which `LaunchRequest` reads as `Receive`, and the receive QR opens above Home, as a payment link's send + does. Without a wallet it shows the Bitkit mark and a "Restore" edge button that opens the app. Tiles cannot use + the app's fonts, so the balance is in the system font. + - The tile only reads `WalletRepo`'s state in memory and never starts the wallet, so the balance shows only once + the app loaded it in this process and a sync confirmed it, as on the Balance page; until then, and while the + watch is locked, the dimmed mark stands in for it. A removed wallet shows the signed-out tile at once. + - `TileUpdates`, started by `WearApp`, asks the system to draw the tile again whenever the balance shown or the + wallet's status changes, and once when the process starts, so a tile drawn by an earlier process drops a balance + the new one has not loaded. Each tile is fresh for 15 min, after which the system asks again; a tile drawn just + before the process died can show the last balance until then. + - Privacy: the tile shows the balance on the tile carousel, so it hides it while the wallet is disconnected + because the watch locked (`WalletStatus.Locked`). Tiles have no ambient mode: in ambient the system shows the watch face, so the app's rule that the always-on screen + shows no amount holds without code in the tile. The tile carries no secret: the receive invoice is made by the + app after the tap, never by the tile. + - The tile picker shows `tile_preview` (a drawing of the balance and the Receive button, no real amount). + `tile_logo` and `tile_logo_dim` are the mark's letters and dot without its black outline, the dim one at 40% + opacity baked into its colours, since a tile image cannot be drawn half transparent or tinted per path. - **Send.** There is no Send page or button. A `lightning:`, `bitcoin:` or `spark:` link opens the app (`MainActivity` is `singleTop`, so a link reaches the open app) and the send flow above Home; without a wallet, during the restore, or while a send is under way, the link is dropped. The flow waits for the wallet to be ready diff --git a/journeys/wear/README.md b/journeys/wear/README.md index dbe37d2277..ef46ac5b1f 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -123,6 +123,7 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `send-own-invoice-guard.xml` | local | yes, any balance above 0 | | `activity-list.xml` | local | yes, after `receive-paid.xml` and `send-deeplink-bolt11.xml` | | `receive-paid-ambient.xml` | local | no, it funds the wallet with 1 000 sats | +| `tile-balance.xml` | hosted or local | no | Paying an LNURL-pay link or a Lightning address has no journey: the local stack's LNURL server serves only the Lightning addresses its Spark wallets registered, over plain HTTP, and nothing in it registers one. It is covered by @@ -306,6 +307,25 @@ watch's invoices are amountless). Hand an invoice to the watch as a link, never adb shell am start -a android.intent.action.VIEW -d "lightning:" to.bitkit.dev ``` +## Tiles + +The system draws a tile, so `android layout` does not list what it shows; check it from a screenshot. Add, show and +remove the Bitkit tile with the Wear OS debug broadcasts: + +```bash +adb shell am broadcast -a com.google.android.wearable.app.DEBUG_SURFACE --es operation add-tile \ + --ecn component to.bitkit.dev/to.bitkit.wear.tile.BalanceTileService +adb shell am broadcast -a com.google.android.wearable.app.DEBUG_SYSUI --es operation show-tile --ei index 0 +adb shell am broadcast -a com.google.android.wearable.app.DEBUG_SURFACE --es operation remove-tile \ + --ecn component to.bitkit.dev/to.bitkit.wear.tile.BalanceTileService +``` + +`add-tile` prints the index the tile took; pass that one to `show-tile` when other tiles are added. +Wait about 5 s after `show-tile` before a screenshot: an earlier one can catch the watch face mid-transition. The +Receive edge button is at about (227, 400) on the large screen. Adding the tile again (remove, then add) makes the +system ask the app for it at once; the app also asks the system to redraw it whenever the balance or the wallet's +status changes. + ## Watch gestures Coordinates are pixels. The 227 dp screen is 454 px square (centre 227), the 192 dp screen 384 px (centre 192). diff --git a/journeys/wear/tile-balance.xml b/journeys/wear/tile-balance.xml new file mode 100644 index 0000000000..61c8817e8e --- /dev/null +++ b/journeys/wear/tile-balance.xml @@ -0,0 +1,23 @@ + + + The Bitkit tile shows the balance the app loaded and a Receive edge button that opens the app on the receive QR. + Emulator and physical watch. + + Precondition: Restored wallet, see journeys/wear/README.md › Restored wallet, its balance loaded on the Balance + page with the loading ring stopped. README › Tiles has the commands that add and show a tile. Tiles are drawn by + the system, so `android layout` does not list their content: check them from a screenshot. The tile without a + wallet (the Bitkit mark and "Restore") and with a balance not loaded yet (the dimmed mark) are covered by + `TileStateTest.kt` and the PR's screenshots. + + + Note the text of "WatchHomeBalance" as <balance> + Add the tile as in README › Tiles + Show the tile as in README › Tiles and wait 3 s + Verify from a screenshot that the tile shows "₿ <balance>" and an orange QR edge button below it + Tap the QR edge button at the point the screenshot shows + Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) + Swipe to dismiss from the left edge: `adb shell input swipe 20 227 400 227 300` + Verify the Balance page: "WatchHomeBalance" is listed + Remove the tile as in README › Tiles + + From 2c22790f7ebd92b8ee0264f62ea89ea1ba64b28d Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 07:09:33 -0300 Subject: [PATCH 24/33] chore: verify the wear tile dependencies Co-Authored-By: Claude Opus 5.5 --- gradle/verification-metadata.xml | 88 ++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index 127e3dc87d..fafa713d5c 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -1075,6 +1075,14 @@ + + + + + + + + @@ -1091,6 +1099,14 @@ + + + + + + + + @@ -2702,6 +2718,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From a83ad5505c1594bbcbbe3843ee39e59f3c262519 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 08:28:57 -0300 Subject: [PATCH 25/33] fix: accept the phone's payment link schemes on the watch Co-Authored-By: Claude Opus 5.5 --- docs/wear.md | 12 ++++-- wear/src/main/AndroidManifest.xml | 12 +++++- .../bitkit/wear/repositories/PaymentsRepo.kt | 35 ++++++++++++++-- .../java/to/bitkit/wear/ui/LaunchRequest.kt | 5 ++- .../wear/repositories/PaymentsRepoTest.kt | 40 ++++++++++++++++++- .../to/bitkit/wear/ui/LaunchRequestTest.kt | 19 ++++++++- 6 files changed, 109 insertions(+), 14 deletions(-) diff --git a/docs/wear.md b/docs/wear.md index 7f185c39c8..317889d082 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -94,7 +94,7 @@ On-screen copy stays short: a title or one line of at most about six words per s - **Home pager.** Home is a horizontal pager (`HorizontalPagerScaffold` with a page indicator) that opens on the Balance page; Receive, Activity and Settings follow, in that order. `HOME_PAGES` in `HomePage.kt` lists the pages in swipe order, so a page is added in one line. The pager leaves the left edge of the first page to swipe-to-dismiss, which leaves the app. - There is no Send page or button: a send starts from outside the app (phone handoff, NFC or a `lightning:` link). + There is no Send page or button: a send starts from outside the app (phone handoff, NFC or a payment link). The pager composes only the page on screen, so Home itself, above the pager, leaves for onboarding or the Wallet removed notice when the wallet's state says the wallet is gone. A removal therefore reaches the wearer on any page, also when the Settings page that asked for it was swiped away meanwhile. @@ -193,9 +193,13 @@ On-screen copy stays short: a title or one line of at most about six words per s - The tile picker shows `tile_preview` (a drawing of the balance and the Receive button, no real amount). `tile_logo` and `tile_logo_dim` are the mark's letters and dot without its black outline, the dim one at 40% opacity baked into its colours, since a tile image cannot be drawn half transparent or tinted per path. -- **Send.** There is no Send page or button. A `lightning:`, `bitcoin:` or `spark:` link opens the app - (`MainActivity` is `singleTop`, so a link reaches the open app) and the send flow above Home; without a wallet, - during the restore, or while a send is under way, the link is dropped. The flow waits for the wallet to be ready +- **Send.** There is no Send page or button. A `bitcoin:`, `BITCOIN:`, `lightning:`, `LIGHTNING:`, `lnurl:`, + `lnurlp:` or `spark:` link opens the app, as on the phone (Android matches schemes case-sensitively, and QR codes + often use the uppercase ones). `lnurlw:` and `lnurlc:` (LNURL withdraw and channel) are not taken: the watch only + pays. `PaymentsRepo.parse` drops `lightning:`, `lnurl:` and `lnurlp:` before decoding, as the phone's scanner + does, reads a LUD-17 `lnurlp://host/path` as `https://host/path` (`http` for an onion host) and lowercases an + all-uppercase payload. A link opens the send flow above Home (`MainActivity` is `singleTop`, so a link reaches the + open app); without a wallet, during the restore, or while a send is under way, the link is dropped. The flow waits for the wallet to be ready (the loading ring, with "Offline" while it is offline), reads the input and prices the send (see Payments), all before the hold. An input without an amount, an amountless invoice, a Spark address or an LNURL with a range, gets a minimal amount entry (the number keyboard, the LNURL range below it); Receive never has one. diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index 0d28366d37..7af945f1ac 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -70,8 +70,18 @@ - + + + + + + diff --git a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt index 51f9c537fc..61392554ae 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -93,6 +93,30 @@ class PaymentsRepo @Inject constructor( private val SPARK_ADDRESS = Regex("^(spark|sp)(rt|t|s|l)?1[02-9ac-hj-np-z]+$", RegexOption.IGNORE_CASE) private const val SPARK_SCHEME = "spark:" + /** The schemes the decoder reads an input without, as the phone's scanner strips them. */ + private val STRIPPED_SCHEMES = setOf("lightning", "lnurl", "lnurlp") + private val URI_SCHEME = Regex("^[a-zA-Z][a-zA-Z0-9+.-]*$") + private const val ONION_TLD = ".onion" + + /** + * [input] as the decoder reads it. The scheme is lowercased, and `lightning:`, `lnurl:` and `lnurlp:` are + * dropped, as the phone's scanner does. A LUD-17 `lnurlp://host/path` link becomes the LNURL-pay URL + * `https://host/path` (`http` for an onion host). A payload without a lowercase letter, as an uppercase QR + * code has, is lowercased: bech32 is read in one case, and BIP21 keys are matched lowercase. + */ + internal fun decoderInput(input: String): String { + val text = input.trim() + val scheme = text.substringBefore(':', missingDelimiterValue = "").takeIf { URI_SCHEME.matches(it) } + ?.lowercase() + val payload = if (scheme == null) text else text.substringAfter(':') + if (scheme == "lnurlp" && payload.startsWith("//")) { + val host = payload.drop(2).substringBefore('/').substringBefore('?').substringBefore(':') + return (if (host.endsWith(ONION_TLD, ignoreCase = true)) "http:" else "https:") + payload + } + val oneCase = if (payload.none { it.isLowerCase() }) payload.lowercase() else payload + return if (scheme == null || scheme in STRIPPED_SCHEMES) oneCase else "$scheme:$oneCase" + } + /** [input] without its `spark:` scheme when it has the shape of a Spark address, or null. */ internal fun sparkAddressOrNull(input: String): String? { val text = if (input.startsWith(SPARK_SCHEME, ignoreCase = true)) input.drop(SPARK_SCHEME.length) else input @@ -169,14 +193,15 @@ class PaymentsRepo @Inject constructor( /** * Reads a payment input: a BOLT11 invoice, an LNURL-pay link, a Lightning address, a BIP21 URI with a - * `lightning` parameter or a Spark address, each with or without its URI scheme. An LNURL or a Lightning address + * `lightning` parameter or a Spark address, each with or without its URI scheme, in either case (see + * [decoderInput]). An LNURL or a Lightning address * is fetched from its host. Fails with a [SendError]: [SendError.Invalid], [SendError.Unsupported], * [SendError.Expired], and [SendError.OwnInvoice] when the wallet is ready to tell. A Spark address needs the * wallet ready ([SendError.NotReady]); the other inputs are read without it, and [prepare] checks them again. */ suspend fun parse(input: String): Result = withContext(ioDispatcher) { runSuspendCatching { - val text = input.trim() + val text = decoderInput(input) val sparkAddress = sparkAddressOrNull(text) val request = if (sparkAddress != null) SendRequest.SparkAddress(sparkAddress) else decode(text) when (request) { @@ -199,8 +224,10 @@ class PaymentsRepo @Inject constructor( is Scanner.Lightning -> scanned.invoice.toRequest() is Scanner.LnurlPay -> scanned.data.toRequest(text) is Scanner.OnChain -> { - val bolt11 = scanned.invoice.params?.get("lightning") ?: throw SendError.Unsupported() - val invoice = runSuspendCatching { inputDecoder.decode(bolt11) as? Scanner.Lightning } + val bolt11 = scanned.invoice.params?.entries + ?.firstOrNull { it.key.equals("lightning", ignoreCase = true) } + ?.value ?: throw SendError.Unsupported() + val invoice = runSuspendCatching { inputDecoder.decode(decoderInput(bolt11)) as? Scanner.Lightning } .getOrElse { throw SendError.Invalid(it) } invoice?.invoice?.toRequest() ?: throw SendError.Unsupported() } diff --git a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt index 0fccedb934..484495c8fb 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt @@ -4,7 +4,7 @@ import android.content.Intent /** What an intent that opened the app asks for, beyond showing it. */ sealed interface LaunchRequest { - /** Pay the payment input of a `lightning:`, `bitcoin:` or `spark:` link. */ + /** Pay the payment input of a `bitcoin:`, `lightning:`, `lnurl:`, `lnurlp:` or `spark:` link, in any case. */ data class Send(val input: String) : LaunchRequest /** Show the receive QR, as from the tile. */ @@ -15,7 +15,8 @@ sealed interface LaunchRequest { const val EXTRA_OPEN = "to.bitkit.wear.OPEN" const val OPEN_RECEIVE = "receive" - private val SEND_SCHEMES = setOf("lightning", "bitcoin", "spark") + /** The manifest's link schemes, lowercased. `lnurlw` and `lnurlc` are left out: the watch only pays. */ + private val SEND_SCHEMES = setOf("bitcoin", "lightning", "lnurl", "lnurlp", "spark") /** The request of an intent with [action], [data] and the [open] extra, or null for a plain launch. */ fun from(action: String?, data: String?, open: String?): LaunchRequest? { diff --git a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt index 0d1b37963a..483b90ff8d 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -201,7 +201,7 @@ class PaymentsRepoTest : BaseUnitTest() { @Test fun `an invoice is read with its amount, and without one when it is amountless`() = test { - decoder.inputs["lightning:$BOLT11"] = lightning(BOLT11, amountSats = 500uL, description = "Coffee") + decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 500uL, description = "Coffee") decoder.inputs["amountless"] = lightning(BOLT11, amountSats = 0uL, description = "") assertEquals(SendRequest.Invoice(BOLT11, 500uL, "Coffee"), sut.parse(" lightning:$BOLT11 ").getOrThrow()) @@ -233,12 +233,48 @@ class PaymentsRepoTest : BaseUnitTest() { @Test fun `a lightning address is named by its address, and a fixed lnurl amount is fixed`() = test { val fixed = Scanner.LnurlPay(lnurl(minMsat = 21_000uL, maxMsat = 21_000uL)) - decoder.inputs["lightning:satoshi@pay.example"] = fixed + decoder.inputs["satoshi@pay.example"] = fixed val request = sut.parse("lightning:satoshi@pay.example").getOrThrow() assertEquals("satoshi@pay.example", request.payee) assertEquals(21uL, request.fixedAmountSats) + assertEquals("satoshi@pay.example", sut.parse("LIGHTNING:SATOSHI@PAY.EXAMPLE").getOrThrow().payee) + } + + @Test + fun `an lnurl link loses its scheme, and an uppercase one is read lowercase`() = test { + decoder.inputs["lnurl1abc"] = Scanner.LnurlPay(lnurl()) + + for (link in listOf("lnurl:lnurl1abc", "lnurl:LNURL1ABC", "LIGHTNING:LNURL1ABC", "lnurlp:lnurl1abc")) { + assertIs(sut.parse(link).getOrThrow(), link) + } + assertEquals(List(4) { "lnurl1abc" }, decoder.decoded) + } + + @Test + fun `an lnurlp link is read as its https lnurl-pay url, and an onion one as http`() = test { + decoder.inputs["https://pay.example/lnurlp/satoshi?tag=1"] = Scanner.LnurlPay(lnurl()) + decoder.inputs["http://payabc.onion/lnurlp/satoshi"] = Scanner.LnurlPay(lnurl()) + + val request = assertIs(sut.parse("lnurlp://pay.example/lnurlp/satoshi?tag=1").getOrThrow()) + assertEquals("pay.example", request.payee) + assertIs(sut.parse("LNURLP://payabc.onion/lnurlp/satoshi").getOrThrow()) + } + + @Test + fun `an uppercase bitcoin uri is paid by its LIGHTNING invoice`() = test { + val upper = "BITCOIN:BCRT1Q?LIGHTNING=${BOLT11.uppercase()}" + decoder.inputs["bitcoin:bcrt1q?lightning=$BOLT11"] = onchain(mapOf("lightning" to BOLT11)) + decoder.inputs["bitcoin:bcrt1q?LIGHTNING=${BOLT11.uppercase()}"] = + onchain(mapOf("LIGHTNING" to BOLT11.uppercase())) + decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 500uL) + + assertEquals(SendRequest.Invoice(BOLT11, 500uL, null), sut.parse(upper).getOrThrow()) + assertEquals( + SendRequest.Invoice(BOLT11, 500uL, null), + sut.parse("bitcoin:bcrt1q?LIGHTNING=${BOLT11.uppercase()}").getOrThrow(), + ) } @Test diff --git a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt index f105c2fbc1..f1c5d31f74 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt @@ -8,7 +8,16 @@ import kotlin.test.assertNull class LaunchRequestTest { @Test fun `a payment link asks for a send of the whole link`() { - for (link in listOf("lightning:lnbcrt1abc", "BITCOIN:bcrt1q?lightning=lnbcrt1abc", "spark:sprt1abc")) { + val links = listOf( + "bitcoin:bcrt1q?lightning=lnbcrt1abc", + "BITCOIN:BCRT1Q?LIGHTNING=LNBCRT1ABC", + "lightning:lnbcrt1abc", + "LIGHTNING:LNBCRT1ABC", + "lnurl:lnurl1abc", + "lnurlp://pay.example/lnurlp/satoshi", + "spark:sprt1abc", + ) + for (link in links) { assertEquals(LaunchRequest.Send(link), LaunchRequest.from(Intent.ACTION_VIEW, link, open = null)) } } @@ -29,4 +38,12 @@ class LaunchRequestTest { assertNull(LaunchRequest.from(Intent.ACTION_SEND, data = "lightning:lnbcrt1abc", open = null)) assertNull(LaunchRequest.from(Intent.ACTION_MAIN, data = null, open = "send")) } + + @Test + fun `a withdraw or channel lnurl link asks for nothing, since the watch only pays`() { + val links = listOf("lnurlw://pay.example/withdraw", "LNURLW://PAY.EXAMPLE/W", "lnurlc://pay.example/channel") + for (link in links) { + assertNull(LaunchRequest.from(Intent.ACTION_VIEW, link, open = null), link) + } + } } From 6141d99b6245705af9dc08ffaac8496f528e690e Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 08:35:09 -0300 Subject: [PATCH 26/33] feat: show a dedicated offline error when paying offline on the watch Co-Authored-By: Claude Opus 5.5 --- docs/wear.md | 16 +++-- journeys/wear/README.md | 1 + journeys/wear/send-offline-error.xml | 26 ++++++++ .../bitkit/wear/ui/screens/send/SendScreen.kt | 65 ++++++++++--------- .../wear/ui/screens/send/SendViewModel.kt | 53 ++++++++++----- wear/src/main/res/values-ar/strings.xml | 2 +- wear/src/main/res/values-b+es+419/strings.xml | 2 +- wear/src/main/res/values-ca/strings.xml | 2 +- wear/src/main/res/values-cs/strings.xml | 2 +- wear/src/main/res/values-de/strings.xml | 2 +- wear/src/main/res/values-el/strings.xml | 2 +- wear/src/main/res/values-es-rES/strings.xml | 2 +- wear/src/main/res/values-es/strings.xml | 2 +- wear/src/main/res/values-fr/strings.xml | 2 +- wear/src/main/res/values-it/strings.xml | 2 +- wear/src/main/res/values-nl/strings.xml | 2 +- wear/src/main/res/values-pl/strings.xml | 2 +- wear/src/main/res/values-pt-rBR/strings.xml | 2 +- wear/src/main/res/values-pt/strings.xml | 2 +- wear/src/main/res/values-ru/strings.xml | 2 +- wear/src/main/res/values/strings.xml | 2 +- .../wear/ui/screens/send/SendReviewTest.kt | 1 - .../wear/ui/screens/send/SendViewModelTest.kt | 62 +++++++++++++++++- 23 files changed, 186 insertions(+), 70 deletions(-) create mode 100644 journeys/wear/send-offline-error.xml diff --git a/docs/wear.md b/docs/wear.md index 317889d082..47f85a1919 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -199,8 +199,9 @@ On-screen copy stays short: a title or one line of at most about six words per s pays. `PaymentsRepo.parse` drops `lightning:`, `lnurl:` and `lnurlp:` before decoding, as the phone's scanner does, reads a LUD-17 `lnurlp://host/path` as `https://host/path` (`http` for an onion host) and lowercases an all-uppercase payload. A link opens the send flow above Home (`MainActivity` is `singleTop`, so a link reaches the - open app); without a wallet, during the restore, or while a send is under way, the link is dropped. The flow waits for the wallet to be ready - (the loading ring, with "Offline" while it is offline), reads the input and prices the send (see Payments), all before the hold. An input + open app); without a wallet, during the restore, or while a send is under way, the link is dropped. The flow waits + for the wallet to be ready (the loading ring), reads the input and prices the send (see Payments), all before the + hold. An input without an amount, an amountless invoice, a Spark address or an LNURL with a range, gets a minimal amount entry (the number keyboard, the LNURL range below it); Receive never has one. - Review: the amount in the balance's large style, fiat below in the small style, the fee only when it is at @@ -208,8 +209,15 @@ On-screen copy stays short: a title or one line of at most about six words per s button, "Hold to pay" (`WatchSendHold`). - Hold to pay: holding the button fills a ring around the bezel (`HoldToPayRing`, the geometry of `BezelLoading`) over 1.2 s, with a light tick (`SegmentTick`) at each quarter and the confirm haptic at the end, and only then - the payment goes out. Releasing early empties the ring; a tap never pays. Offline, the button is disabled with - the line "Offline"; while the wallet connects, locks or pauses, it is disabled under the loading ring. + the payment goes out. Releasing early empties the ring; a tap never pays. While the wallet connects, locks or + pauses, the button is disabled under the loading ring. + - Offline: the app pays only online. A wallet that is offline (`WalletStatus.Offline`) while a request is open and + its send has not started (on arrival, while it is read or priced, on the amount entry or on review before the + hold completes) ends the flow on its own refusal, `SendStep.Offline`: the crossed-out cloud, "Can't pay + offline" (`WatchSendOfflineError`), the reject haptic and OK (`WatchSendClose`), which closes the flow. The + request is dropped, never kept to pay when the network returns, so nothing (QuickPay included) pays it later. + Once the hold completed and the send started, going offline changes nothing: the send keeps its pending or + unknown outcome. `PaymentsRepo.skipConfirmation` is asked before the hold; it is always false until QuickPay (PR 3). - Screen readers: a screen reader's wearer cannot hold, and the button's click pays nothing, so the button offers "Pay" as a custom accessibility action, picked from the actions menu, and as its long click (a double diff --git a/journeys/wear/README.md b/journeys/wear/README.md index ef46ac5b1f..71cbb2973e 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -121,6 +121,7 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `send-ambient-hides-amount.xml` | local | yes, 2 000 sats | | `send-insufficient.xml` | local | yes, less than 10 000 000 sats | | `send-own-invoice-guard.xml` | local | yes, any balance above 0 | +| `send-offline-error.xml` | local | yes, any balance above 0 | | `activity-list.xml` | local | yes, after `receive-paid.xml` and `send-deeplink-bolt11.xml` | | `receive-paid-ambient.xml` | local | no, it funds the wallet with 1 000 sats | | `tile-balance.xml` | hosted or local | no | diff --git a/journeys/wear/send-offline-error.xml b/journeys/wear/send-offline-error.xml new file mode 100644 index 0000000000..70b9f1d143 --- /dev/null +++ b/journeys/wear/send-offline-error.xml @@ -0,0 +1,26 @@ + + + The app pays only online: a payment link opened while the watch is offline ends on its own refusal, a crossed-out + cloud and "Can't pay offline" with the reject haptic and OK, before any review or hold (docs/wear.md › Send › + Offline). OK closes the flow, and the request is dropped: it is not paid when the network returns. Emulator and + physical watch (on a watch, turn on airplane mode in its settings). + + Precondition: Restored wallet on the local ./spark stack with a balance above 0, see + journeys/wear/README.md › Local ./spark stack, on the Balance page with the loading ring stopped. Offline recipe: + README › Offline. Turn airplane mode off again if the journey stops early. + + + From the bitkit-docker checkout, run `./spark invoice 1000` (README › Local invoices) and note the invoice as <invoice> + Run `adb shell cmd connectivity airplane-mode enable` and wait 5 s + Dump `android layout` every 5 s until it lists "WatchHomeOffline", for up to 1 minute + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` + Wait up to 10 s until "WatchSendOfflineError" is listed + Verify "WatchSendOfflineError" reads "Can't pay offline" + Verify "WatchSendHold" and "WatchSendLoading" are not listed + Verify from a screenshot that a crossed-out cloud sits above the line, with one OK button below it + Tap "WatchSendClose" + Verify Home is back: "WatchHomeBalance" is listed + Run `adb shell cmd connectivity airplane-mode disable` + Dump `android layout` every 5 s until it no longer lists "WatchHomeOffline", for up to 1 minute, then verify "WatchSendOfflineError" and "WatchSendSending" are not listed + + diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt index 34adf9bcde..6c61dc80b6 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt @@ -62,7 +62,7 @@ import to.bitkit.wear.ui.components.rememberHoldToPayState import to.bitkit.wear.ui.screens.home.DisplayAmount import to.bitkit.wear.ui.theme.Colors -/** The size of the icon that tops a status: the check, the cross, the clock and the bolt while loading. */ +/** The size of the icon that tops a status: the check, the cross, the clock, the cloud and the bolt while loading. */ private val STATUS_ICON_SIZE = 48.dp /** The opacity of the bolt that shows while the send is loading or under way. */ @@ -70,8 +70,9 @@ private const val LOADING_ICON_ALPHA = 0.4f /** * The send flow of a deeplink: review with the hold to pay, the send under way, and its result, which closes the - * flow by itself ([onClose]). The amount entry shows only for an input that names no amount. While a send is under - * way the screen stays on and cannot be left ([onBusyChange]). In ambient mode a step with an amount hides behind a + * flow by itself ([onClose]). The amount entry shows only for an input that names no amount. Offline before the + * send starts, the flow ends on a refusal of its own. While a send is under way the screen stays on and cannot be + * left ([onBusyChange]). In ambient mode a step with an amount hides behind a * dimmed bolt, as no amount shows on the always-on screen. */ @Composable @@ -96,11 +97,11 @@ fun SendScreen( // A screen that leaves while busy must not leave the swipe to dismiss off for every other screen. DisposableEffect(Unit) { onDispose { currentOnBusyChange(false) } } val step = uiState.step - LaunchedEffect(step is SendStep.Done, step is SendStep.Failed) { + LaunchedEffect(step is SendStep.Done, step is SendStep.Failed, step is SendStep.Offline) { when (step) { is SendStep.Done if step.result == SendResult.Sent -> haptic.performHapticFeedback(HapticFeedbackType.Confirm) - is SendStep.Failed -> haptic.performHapticFeedback(HapticFeedbackType.Reject) + is SendStep.Failed, SendStep.Offline -> haptic.performHapticFeedback(HapticFeedbackType.Reject) else -> Unit } } @@ -133,7 +134,7 @@ private fun Content( return } when (step) { - SendStep.Loading -> Loading(isOffline = uiState.isOffline, modifier = modifier) + SendStep.Loading -> Loading(modifier = modifier) is SendStep.Amount -> Amount( step = step, text = uiState.amountText, @@ -144,14 +145,26 @@ private fun Content( is SendStep.Review -> Review( step = step, isHoldEnabled = uiState.isHoldEnabled, - isOffline = uiState.isOffline, - isConnecting = !uiState.isWalletReady && !uiState.isOffline, + isConnecting = !uiState.isWalletReady, onHoldComplete = onHoldComplete, modifier = modifier ) is SendStep.Sending -> Sending(isWaiting = step.isWaiting, modifier = modifier) is SendStep.Done -> Done(step = step, modifier = modifier) - is SendStep.Failed -> Failed(failure = step.failure, onCloseClick = onCloseClick, modifier = modifier) + is SendStep.Failed -> Refusal( + icon = R.drawable.ic_close, + text = stringResource(step.failure.text), + textTag = "WatchSendError", + onCloseClick = onCloseClick, + modifier = modifier + ) + SendStep.Offline -> Refusal( + icon = R.drawable.ic_cloud_off, + text = stringResource(R.string.send__error_offline), + textTag = "WatchSendOfflineError", + onCloseClick = onCloseClick, + modifier = modifier + ) } } @@ -167,10 +180,7 @@ private fun Hidden(modifier: Modifier = Modifier) { } @Composable -private fun Loading( - isOffline: Boolean, - modifier: Modifier = Modifier, -) { +private fun Loading(modifier: Modifier = Modifier) { CenteredScreen( overlay = { BezelLoading() }, modifier = modifier @@ -180,7 +190,6 @@ private fun Loading( tint = Colors.White.copy(alpha = LOADING_ICON_ALPHA), modifier = Modifier.testTag("WatchSendLoading") ) - if (isOffline) OfflineLine() } } @@ -282,7 +291,6 @@ private fun AmountField( internal fun Review( step: SendStep.Review, isHoldEnabled: Boolean, - isOffline: Boolean, isConnecting: Boolean, onHoldComplete: () -> Unit, modifier: Modifier = Modifier, @@ -340,10 +348,7 @@ internal fun Review( modifier = Modifier.testTag("WatchSendFee") ) } - when { - isOffline -> OfflineLine() - step.payee != null -> Line(text = step.payee, modifier = Modifier.testTag("WatchSendPayee")) - } + step.payee?.let { Line(text = it, modifier = Modifier.testTag("WatchSendPayee")) } } } @@ -405,19 +410,22 @@ private fun Done( } } +/** Nothing was sent: [icon] and the one line [text], with the one action that closes the flow. */ @Composable -private fun Failed( - failure: SendFailure, +private fun Refusal( + @DrawableRes icon: Int, + text: String, + textTag: String, onCloseClick: () -> Unit, modifier: Modifier = Modifier, ) { CenteredScreen(modifier = modifier) { - StatusIcon(icon = R.drawable.ic_close, tint = MaterialTheme.colorScheme.error) + StatusIcon(icon = icon, tint = MaterialTheme.colorScheme.error) Text( - text = stringResource(failure.text), + text = text, style = MaterialTheme.typography.titleSmall, textAlign = TextAlign.Center, - modifier = Modifier.testTag("WatchSendError") + modifier = Modifier.testTag(textTag) ) FilledTonalIconButton( onClick = onCloseClick, @@ -446,11 +454,6 @@ private fun StatusIcon( ) } -@Composable -private fun OfflineLine(modifier: Modifier = Modifier) { - Line(text = stringResource(R.string.send__offline), modifier = modifier.testTag("WatchSendOffline")) -} - @Composable private fun Line( text: String, @@ -485,10 +488,10 @@ private fun PreviewReview() { @WearPreviewDevices @Composable -private fun PreviewReviewOffline() { +private fun PreviewOffline() { WearPreview { Content( - uiState = SendUiState(step = PreviewReviewStep, isOffline = true), + uiState = SendUiState(step = SendStep.Offline), isAmbient = false, onAmountChange = {}, onAmountConfirm = {}, diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt index 4ca591e902..fdc6a2080a 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt @@ -6,6 +6,7 @@ import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow @@ -38,6 +39,8 @@ import kotlin.time.Duration.Companion.seconds * The send flow for one payment input from a deeplink: it waits for the wallet, reads the input, asks for an amount * only when the input names none, prices the send and shows it for review. The send goes out only after the hold to * pay completes, unless [PaymentsRepo.skipConfirmation] says otherwise, and the result closes the flow by itself. + * The app pays only online: a wallet that is offline before the send starts ends the flow on [SendStep.Offline], + * and the request is dropped, not kept for when the network returns. */ @HiltViewModel class SendViewModel @Inject constructor( @@ -77,18 +80,17 @@ class SendViewModel @Inject constructor( private var request: SendRequest? = null private var prepared: PreparedSend? = null + /** Reads, prices and shows the request before the send; cancelled when the wallet goes offline. */ + private var flow: Job? = null + init { + flow = viewModelScope.launch { start() } viewModelScope.launch { walletRepo.walletState.collect { wallet -> - _uiState.update { - it.copy( - isWalletReady = wallet.status == WalletStatus.Ready, - isOffline = wallet.status == WalletStatus.Offline, - ) - } + _uiState.update { it.copy(isWalletReady = wallet.status == WalletStatus.Ready) } + if (wallet.status == WalletStatus.Offline) dropOffline() } } - viewModelScope.launch { start() } } fun onAmountChange(text: String) { @@ -107,7 +109,7 @@ class SendViewModel @Inject constructor( _uiState.update { it.copy(step = step.copy(isOutOfRange = true)) } return } - viewModelScope.launch { prepare(request, amount) } + flow = viewModelScope.launch { prepare(request, amount) } } /** Sends the reviewed payment once the hold to pay completes, while the wallet is ready. */ @@ -123,8 +125,26 @@ class SendViewModel @Inject constructor( _effects.trySend(SendEffect.Close) } + /** + * Ends a flow whose send has not started on [SendStep.Offline]: on arrival, while the input is read or priced, + * during the amount entry or on review. A send already under way keeps its own outcome. + */ + private fun dropOffline() { + val step = _uiState.value.step + if (step !is SendStep.Loading && step !is SendStep.Amount && step !is SendStep.Review) return + Logger.info("Dropped a send request while offline", context = TAG) + flow?.cancel() + request = null + prepared = null + _uiState.update { it.copy(step = SendStep.Offline) } + } + + /** Shows [step] unless the flow already ended on [SendStep.Offline]. */ + private fun show(step: SendStep) { + _uiState.update { if (it.step is SendStep.Offline) it else it.copy(step = step) } + } + private suspend fun start() { - _uiState.update { it.copy(step = SendStep.Loading) } walletRepo.walletState.first { it.status == WalletStatus.Ready } val parsed = paymentsRepo.parse(input).getOrElse { fail(it) @@ -132,28 +152,29 @@ class SendViewModel @Inject constructor( } request = parsed if (parsed.fixedAmountSats == null) { - _uiState.update { it.copy(step = amountStep(parsed)) } + show(amountStep(parsed)) return } prepare(parsed, amountSats = null) } private suspend fun prepare(request: SendRequest, amountSats: ULong?) { - _uiState.update { it.copy(step = SendStep.Loading) } + show(SendStep.Loading) val result = paymentsRepo.prepare(request, amountSats).getOrElse { if (it is SendError.AmountOutOfRange && request.fixedAmountSats == null) { - _uiState.update { state -> state.copy(step = amountStep(request).copy(isOutOfRange = true)) } + show(amountStep(request).copy(isOutOfRange = true)) } else { fail(it) } return } + if (_uiState.value.step is SendStep.Offline) return prepared = result if (paymentsRepo.skipConfirmation(result)) { send(result) return } - _uiState.update { it.copy(step = review(result, request)) } + show(review(result, request)) } private suspend fun review(prepared: PreparedSend, request: SendRequest): SendStep.Review { @@ -216,7 +237,7 @@ class SendViewModel @Inject constructor( finish(SendResult.Pending, amountSats = prepared?.amountSats ?: 0uL) return } - _uiState.update { it.copy(step = SendStep.Failed(SendFailure.of(error))) } + show(SendStep.Failed(SendFailure.of(error))) } private fun amountStep(request: SendRequest): SendStep.Amount = when (request) { @@ -259,6 +280,9 @@ sealed interface SendStep { /** Nothing was sent, for [failure]. */ data class Failed(val failure: SendFailure) : SendStep + + /** Nothing was sent: the wallet went offline before the send started. The flow ends here. */ + data object Offline : SendStep } enum class SendResult { Sent, Pending, Unknown } @@ -303,7 +327,6 @@ data class SendUiState( val step: SendStep = SendStep.Loading, val amountText: String = "", val isWalletReady: Boolean = false, - val isOffline: Boolean = false, ) { /** Whether the hold to pay can start: only on review with the wallet ready. */ val isHoldEnabled: Boolean get() = step is SendStep.Review && isWalletReady diff --git a/wear/src/main/res/values-ar/strings.xml b/wear/src/main/res/values-ar/strings.xml index 7873c2a13d..8689cf9896 100644 --- a/wear/src/main/res/values-ar/strings.xml +++ b/wear/src/main/res/values-ar/strings.xml @@ -58,11 +58,11 @@ فاتورة غير صالحة المحفظة غير جاهزة خارج النطاق + لا يمكن الدفع دون اتصال لا يمكن دفع فاتورتك غير مدعوم الرسوم %1$s اضغط مطولًا للدفع - غير متصل ادفع معلق تم الإرسال diff --git a/wear/src/main/res/values-b+es+419/strings.xml b/wear/src/main/res/values-b+es+419/strings.xml index acc889f640..d1f10a669f 100644 --- a/wear/src/main/res/values-b+es+419/strings.xml +++ b/wear/src/main/res/values-b+es+419/strings.xml @@ -55,11 +55,11 @@ Factura no válida Wallet no lista Fuera de rango + No se puede pagar sin conexión Es su propia factura No compatible Comisión %1$s Mantén para pagar - Sin conexión Pagar Pendiente Enviado diff --git a/wear/src/main/res/values-ca/strings.xml b/wear/src/main/res/values-ca/strings.xml index 523508aee0..860dfe7069 100644 --- a/wear/src/main/res/values-ca/strings.xml +++ b/wear/src/main/res/values-ca/strings.xml @@ -55,11 +55,11 @@ Factura no vàlida Wallet no a punt Fora de rang + No es pot pagar sense connexió És la teva factura No compatible Comissió %1$s Mantén per pagar - Sense connexió Paga Pendent Enviat diff --git a/wear/src/main/res/values-cs/strings.xml b/wear/src/main/res/values-cs/strings.xml index 6edb491dde..c8e1d3e862 100644 --- a/wear/src/main/res/values-cs/strings.xml +++ b/wear/src/main/res/values-cs/strings.xml @@ -56,11 +56,11 @@ Neplatná faktura Peněženka není připravena Mimo rozsah + Bez připojení nelze platit Vlastní fakturu nelze zaplatit Nepodporováno Poplatek %1$s Podržte pro platbu - Offline Zaplatit Zpracovávání Odesláno diff --git a/wear/src/main/res/values-de/strings.xml b/wear/src/main/res/values-de/strings.xml index d9556e1d5a..6ebbb244b7 100644 --- a/wear/src/main/res/values-de/strings.xml +++ b/wear/src/main/res/values-de/strings.xml @@ -54,11 +54,11 @@ Ungültige Rechnung Wallet nicht bereit Außerhalb des Bereichs + Offline nicht bezahlbar Eigene Rechnung nicht bezahlbar Nicht unterstützt Gebühr %1$s Halten zum Bezahlen - Offline Bezahlen Ausstehend Gesendet diff --git a/wear/src/main/res/values-el/strings.xml b/wear/src/main/res/values-el/strings.xml index e7cf56431e..5de15f71cc 100644 --- a/wear/src/main/res/values-el/strings.xml +++ b/wear/src/main/res/values-el/strings.xml @@ -54,11 +54,11 @@ Μη έγκυρο τιμολόγιο Το πορτοφόλι δεν είναι έτοιμο Εκτός ορίων + Δεν γίνεται πληρωμή εκτός σύνδεσης Δικό σου τιμολόγιο Δεν υποστηρίζεται Χρέωση %1$s Κράτα για πληρωμή - Εκτός σύνδεσης Πληρωμή Εκκρεμεί Στάλθηκε diff --git a/wear/src/main/res/values-es-rES/strings.xml b/wear/src/main/res/values-es-rES/strings.xml index 33e961a9fa..d5d8892c48 100644 --- a/wear/src/main/res/values-es-rES/strings.xml +++ b/wear/src/main/res/values-es-rES/strings.xml @@ -55,11 +55,11 @@ Factura no válida Wallet no lista Fuera de rango + No se puede pagar sin conexión Es tu propia factura No compatible Comisión %1$s Mantén para pagar - Sin conexión Pagar Pendiente Enviado diff --git a/wear/src/main/res/values-es/strings.xml b/wear/src/main/res/values-es/strings.xml index 33e961a9fa..d5d8892c48 100644 --- a/wear/src/main/res/values-es/strings.xml +++ b/wear/src/main/res/values-es/strings.xml @@ -55,11 +55,11 @@ Factura no válida Wallet no lista Fuera de rango + No se puede pagar sin conexión Es tu propia factura No compatible Comisión %1$s Mantén para pagar - Sin conexión Pagar Pendiente Enviado diff --git a/wear/src/main/res/values-fr/strings.xml b/wear/src/main/res/values-fr/strings.xml index c085870b00..16369dae9a 100644 --- a/wear/src/main/res/values-fr/strings.xml +++ b/wear/src/main/res/values-fr/strings.xml @@ -55,11 +55,11 @@ Facture invalide Wallet pas prêt Hors limites + Paiement impossible hors ligne Votre propre facture Non pris en charge Frais %1$s Maintenir pour payer - Hors ligne Payer En attente Envoyé diff --git a/wear/src/main/res/values-it/strings.xml b/wear/src/main/res/values-it/strings.xml index df085f2548..455d808235 100644 --- a/wear/src/main/res/values-it/strings.xml +++ b/wear/src/main/res/values-it/strings.xml @@ -55,11 +55,11 @@ Fattura non valida Wallet non pronto Fuori intervallo + Impossibile pagare offline È la tua fattura Non supportato Commissione %1$s Tieni premuto per pagare - Offline Paga In sospeso Inviato diff --git a/wear/src/main/res/values-nl/strings.xml b/wear/src/main/res/values-nl/strings.xml index 7b707876cc..fe9594fcf2 100644 --- a/wear/src/main/res/values-nl/strings.xml +++ b/wear/src/main/res/values-nl/strings.xml @@ -54,11 +54,11 @@ Ongeldige factuur Wallet niet gereed Buiten bereik + Betalen kan niet offline Eigen factuur Niet ondersteund Kosten %1$s Houd vast om te betalen - Offline Betalen In behandeling Verzonden diff --git a/wear/src/main/res/values-pl/strings.xml b/wear/src/main/res/values-pl/strings.xml index 6c5a5f369c..141f583229 100644 --- a/wear/src/main/res/values-pl/strings.xml +++ b/wear/src/main/res/values-pl/strings.xml @@ -56,11 +56,11 @@ Nieprawidłowa faktura Portfel nie jest gotowy Poza zakresem + Nie można płacić offline Własna faktura Nieobsługiwane Opłata %1$s Przytrzymaj, aby zapłacić - Offline Zapłać Oczekuje Wysłano diff --git a/wear/src/main/res/values-pt-rBR/strings.xml b/wear/src/main/res/values-pt-rBR/strings.xml index 6e7ac00976..62223ee6f2 100644 --- a/wear/src/main/res/values-pt-rBR/strings.xml +++ b/wear/src/main/res/values-pt-rBR/strings.xml @@ -55,11 +55,11 @@ Invoice inválido Carteira não pronta Fora do limite + Não é possível pagar offline É seu próprio invoice Não suportado Taxa %1$s Segure para pagar - Offline Pagar Pendente Enviado diff --git a/wear/src/main/res/values-pt/strings.xml b/wear/src/main/res/values-pt/strings.xml index 1894df869b..6fe44a3ebb 100644 --- a/wear/src/main/res/values-pt/strings.xml +++ b/wear/src/main/res/values-pt/strings.xml @@ -55,11 +55,11 @@ Fatura inválida Carteira não pronta Fora do intervalo + Não é possível pagar sem ligação É a sua fatura Não suportado Taxa %1$s Mantenha para pagar - Offline Pagar Pendente Enviado diff --git a/wear/src/main/res/values-ru/strings.xml b/wear/src/main/res/values-ru/strings.xml index 76b23a3fb5..b7af04dbe9 100644 --- a/wear/src/main/res/values-ru/strings.xml +++ b/wear/src/main/res/values-ru/strings.xml @@ -56,11 +56,11 @@ Неверный счёт Кошелёк не готов Вне диапазона + Нельзя платить офлайн Это ваш счёт Не поддерживается Комиссия %1$s Удерживайте для оплаты - Офлайн Оплатить В ожидании Отправлено diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index d8d1c0078d..b42d4c16ae 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -54,11 +54,11 @@ Invalid invoice Wallet not ready Out of range + Can\'t pay offline Can\'t pay own invoice Not supported Fee %1$s Hold to pay - Offline Pay Pending Sent diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendReviewTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendReviewTest.kt index 2a38ae759e..a9f5251bdf 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendReviewTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendReviewTest.kt @@ -80,7 +80,6 @@ class SendReviewTest { payee = null, ), isHoldEnabled = isHoldEnabled, - isOffline = false, isConnecting = !isHoldEnabled, onHoldComplete = { pays++ }, ) diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt index de2b35a459..0fa916323a 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt @@ -128,17 +128,73 @@ class SendViewModelTest : BaseUnitTest() { } @Test - fun `offline disables the hold and a completed hold sends nothing`() = test { + fun `a request that arrives offline ends on the offline error without being read`() = test { + walletState.update { it.copy(status = WalletStatus.Offline) } + stubInvoice(prepared()) + + val sut = createSut() + + assertEquals(SendStep.Offline, sut.uiState.value.step) + assertFalse(sut.uiState.value.isHoldEnabled) + verify(paymentsRepo, never()).parse(any()) + } + + @Test + fun `going offline on review ends on the offline error and a completed hold sends nothing`() = test { stubInvoice(prepared()) val sut = createSut() + assertIs(sut.uiState.value.step) walletState.update { it.copy(status = WalletStatus.Offline) } + assertEquals(SendStep.Offline, sut.uiState.value.step) assertFalse(sut.uiState.value.isHoldEnabled) - assertTrue(sut.uiState.value.isOffline) sut.onHoldComplete() verify(paymentsRepo, never()).send(any()) - assertIs(sut.uiState.value.step) + } + + @Test + fun `going offline while pricing drops the request`() = test { + whenever(paymentsRepo.parse(INPUT)).thenReturn(Result.success(INVOICE)) + whenever(paymentsRepo.prepare(INVOICE, null)).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + assertEquals(SendStep.Loading, sut.uiState.value.step) + + walletState.update { it.copy(status = WalletStatus.Offline) } + + assertEquals(SendStep.Offline, sut.uiState.value.step) + } + + @Test + fun `the network coming back does not bring an offline request back`() = test { + walletState.update { it.copy(status = WalletStatus.Offline) } + stubInvoice(prepared()) + val sut = createSut() + + sut.effects.test { + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertEquals(SendStep.Offline, sut.uiState.value.step) + verify(paymentsRepo, never()).parse(any()) + verify(paymentsRepo, never()).send(any()) + sut.onHoldComplete() + sut.onCloseClick() + assertEquals(SendEffect.Close, awaitItem()) + } + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `going offline once the send started keeps its outcome`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + sut.onHoldComplete() + + walletState.update { it.copy(status = WalletStatus.Offline) } + + assertIs(sut.uiState.value.step) } @Test From 807091478c7060d75d76478515dd0b567eef3765 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 11:10:01 -0300 Subject: [PATCH 27/33] fix: show an ok edge button on wear send refusals Co-Authored-By: Claude Opus 5.5 --- .../bitkit/wear/ui/screens/send/SendScreen.kt | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt index 6c61dc80b6..f7548ea64a 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt @@ -41,9 +41,7 @@ import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.wear.compose.material3.EdgeButton import androidx.wear.compose.material3.EdgeButtonSize -import androidx.wear.compose.material3.FilledTonalIconButton import androidx.wear.compose.material3.Icon -import androidx.wear.compose.material3.IconButtonDefaults import androidx.wear.compose.material3.MaterialTheme import androidx.wear.compose.material3.Text import to.bitkit.wear.R @@ -419,7 +417,18 @@ private fun Refusal( onCloseClick: () -> Unit, modifier: Modifier = Modifier, ) { - CenteredScreen(modifier = modifier) { + CenteredScreen( + edgeButton = { + EdgeButton( + onClick = onCloseClick, + buttonSize = EdgeButtonSize.Medium, + modifier = Modifier.testTag("WatchSendClose") + ) { + Text(stringResource(R.string.common__ok)) + } + }, + modifier = modifier + ) { StatusIcon(icon = icon, tint = MaterialTheme.colorScheme.error) Text( text = text, @@ -427,16 +436,6 @@ private fun Refusal( textAlign = TextAlign.Center, modifier = Modifier.testTag(textTag) ) - FilledTonalIconButton( - onClick = onCloseClick, - shapes = IconButtonDefaults.animatedShapes(), - modifier = Modifier.testTag("WatchSendClose") - ) { - Icon( - painter = painterResource(R.drawable.ic_check), - contentDescription = stringResource(R.string.common__ok), - ) - } } } From 079208ecf6a40b77a9a46670c7c1080a3dfe8194 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 11:20:59 -0300 Subject: [PATCH 28/33] fix: keep the check drawable for wear success states Co-Authored-By: Claude Opus 5.5 --- wear/src/main/res/drawable/ic_check.xml | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 wear/src/main/res/drawable/ic_check.xml diff --git a/wear/src/main/res/drawable/ic_check.xml b/wear/src/main/res/drawable/ic_check.xml new file mode 100644 index 0000000000..cb0b2c48d7 --- /dev/null +++ b/wear/src/main/res/drawable/ic_check.xml @@ -0,0 +1,11 @@ + + + + + From 5176962df6958ee40e40678971b42d4872e674d9 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Fri, 4 Dec 2026 09:45:51 -0300 Subject: [PATCH 29/33] fix: drop invoices and send notes that a wipe began or ended during Like the balance read, an invoice or a send note was checked only for a wipe in progress, so one that outlived a whole wipe and restore passed. Both now carry the wipe token and are kept only while it is current. Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/wear/repositories/PaymentsRepo.kt | 8 +++++--- .../wear/repositories/PaymentsRepoTest.kt | 17 ++++++++++++++--- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt index 61392554ae..7d384993e3 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -153,13 +153,14 @@ class PaymentsRepo @Inject constructor( suspend fun createInvoice(): Result = withContext(ioDispatcher) { runSuspendCatching { if (!isReady()) throw ReceiveError.NotReady() + val wipeToken = sparkService.wipeToken() ?: throw ReceiveError.NotReady() val bolt11 = sparkService.receiveBolt11(amountSats = null, description = "", INVOICE_EXPIRY_SECS) val details = (sparkService.parse(bolt11) as InputType.Bolt11Invoice).v1 // Remembered before it is shown, so the watch never pays an invoice it handed out. ownInvoiceStore.add(details.paymentHash, details.expiresAt) // A wipe that began meanwhile clears the store before or after the add, so the wiped wallet's invoice - // is taken out again and never shown. - if (!isReady() || sparkService.isWiping) { + // is taken out again and never shown, also when another wallet was restored since. + if (!isReady() || !sparkService.isCurrent(wipeToken)) { runSuspendCatching { ownInvoiceStore.remove(details.paymentHash) } .onFailure { Logger.warn("Failed to forget an invoice made during a wipe", it, context = TAG) } throw ReceiveError.NotReady() @@ -512,6 +513,7 @@ class PaymentsRepo @Inject constructor( * or stopped being ready before the note was written sends nothing and leaves no note behind. */ private suspend fun sendNoted(prepared: PreparedSend, key: String): Payment { + val wipeToken = sparkService.wipeToken() ?: throw SendError.NotReady() sparkService.holdSend() try { // Noted before it goes out, so a send the app is closed during is known to be in doubt afterwards. @@ -519,7 +521,7 @@ class PaymentsRepo @Inject constructor( uncertainSendStore.begin(UncertainSend(key, prepared.sparkPayee, prepared.expiresAtSecs)) }.getOrElse { throw SendError.Failed(it) } // A wipe that ran meanwhile cleared the store before the note, which would outlive the wiped wallet. - if (!isReady() || sparkService.isWiping) { + if (!isReady() || !sparkService.isCurrent(wipeToken)) { if (!wasUncertain) settle(key) throw SendError.NotReady() } diff --git a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt index 483b90ff8d..462606a36b 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -85,6 +85,8 @@ class PaymentsRepoTest : BaseUnitTest() { @Before fun setUp() { whenever(sparkService.events).thenReturn(events) + whenever(sparkService.wipeToken()).thenReturn(0) + whenever(sparkService.isCurrent(any())).thenReturn(true) whenever(walletRepo.walletState).thenReturn(walletState) whenever { sparkService.identityPubkey() }.thenReturn(IDENTITY) whenever { sparkService.getInfo() }.thenReturn(SparkFixtures.info(BALANCE)) @@ -161,6 +163,17 @@ class PaymentsRepoTest : BaseUnitTest() { assertTrue(ownInvoices.invoices.isEmpty()) } + @Test + fun `an invoice that outlives a wipe and restore is forgotten and not handed out`() = test { + whenever(sparkService.receiveBolt11(null, "", PaymentsRepo.INVOICE_EXPIRY_SECS)).doSuspendableAnswer { + whenever(sparkService.isCurrent(0)).thenReturn(false) + BOLT11 + } + + assertIs(sut.createInvoice().exceptionOrNull()) + assertTrue(ownInvoices.invoices.isEmpty()) + } + @Test fun `waiting for an invoice ends with its payment and skips other payments`() = test { val paid = async { sut.awaitPaid(invoice()) } @@ -940,9 +953,7 @@ class PaymentsRepoTest : BaseUnitTest() { @Test fun `a send noted while the wallet is wiped is not sent and leaves no note`() = test { val prepared = preparedSend() - var isWiping = false - whenever(sparkService.isWiping).thenAnswer { isWiping } - doAnswer { isWiping = true }.whenever(sparkService).holdSend() + doAnswer { whenever(sparkService.isCurrent(0)).thenReturn(false) }.whenever(sparkService).holdSend() assertIs(sut.send(prepared).exceptionOrNull()) From d283e5b0cc9a2c519d8825711ea283e80a50ca87 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Fri, 4 Dec 2026 10:10:40 -0300 Subject: [PATCH 30/33] fix: keep a pending transfer's note until it settles The note was dropped as soon as Spark took the transfer, so a retry of one still pending after the wait found no note, went out under a new key and paid twice. A transfer has no payment hash to find it by, so the note now stays until Spark reports it completed or failed, and a retry reads it there as in flight. Co-Authored-By: Claude Opus 5.5 --- .../bitkit/wear/repositories/PaymentsRepo.kt | 5 ++-- .../wear/repositories/PaymentsRepoTest.kt | 23 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt index 7d384993e3..866bd6f04d 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -489,13 +489,14 @@ class PaymentsRepo @Inject constructor( } try { val sent = sendNoted(prepared, key) - // Spark lists the payment from here on, so the list tells its outcome. - settle(key) val payment = if (sent.status == PaymentStatus.PENDING) { withTimeoutOrNull(SETTLE_TIMEOUT) { settled.first { sent.id in it }.getValue(sent.id) } ?: sent } else { sent } + // A send still pending keeps its note: a transfer has no payment hash, so the note is the only way a retry + // to the same wallet finds it in Spark's list, as in flight, rather than paying again under a new key. + if (payment.status != PaymentStatus.PENDING) settle(key) if (payment.status == PaymentStatus.FAILED) throw SendError.Failed() if (payment.amount.toLong().toULong() != prepared.amountSats) { Logger.warn("Sent payment '${payment.id}' is an earlier send at another amount", context = TAG) diff --git a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt index 462606a36b..29d4fb4470 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -1098,6 +1098,29 @@ class PaymentsRepoTest : BaseUnitTest() { assertEquals(2, keys.distinct().size) } + @Test + fun `a spark transfer still pending after the wait is not sent again under a new key`() = test { + val keys = stubTransfer() + whenever(sparkService.send(any(), any())).thenAnswer { + keys += it.arguments[1] as String + payment(keys.last(), PaymentStatus.PENDING, paymentHash = null) + } + val request = SendRequest.SparkAddress(SPARK_ADDRESS) + val sent = sut.send(sut.prepare(request, 500uL).getOrThrow()).getOrThrow() + assertEquals(PaymentState.Pending, sent.state) + val key = keys.single() + + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment(key, PaymentStatus.PENDING, paymentHash = null))) + assertIs(sut.prepare(request, 500uL).exceptionOrNull()) + + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment(key, PaymentStatus.COMPLETED, paymentHash = null))) + assertIs(sut.prepare(request, 500uL).exceptionOrNull()) + assertEquals(1, keys.size) + assertTrue(uncertainSends.sends.isEmpty()) + } + @Test fun `a spark transfer of unknown outcome that spark lists failed is sent under a new key`() = test { val keys = stubTransfer() From 7e3d2cd4f5a39fe32534259715106d548b502c6f Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Fri, 4 Dec 2026 10:10:41 -0300 Subject: [PATCH 31/33] fix: hide the tile balance whenever the watch is locked Locking a paused wallet leaves it paused, so the tile, which hid the balance only for the locked status, kept showing it. The tile now reads the watch's own lock state as well. Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/wear/tile/BalanceTileService.kt | 17 ++++++++++- .../java/to/bitkit/wear/tile/TileState.kt | 15 +++++++--- .../java/to/bitkit/wear/tile/TileUpdates.kt | 15 ++++++---- .../java/to/bitkit/wear/tile/TileStateTest.kt | 30 ++++++++++++------- 4 files changed, 56 insertions(+), 21 deletions(-) diff --git a/wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt b/wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt index 567d586a6f..920bfd4fbf 100644 --- a/wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt +++ b/wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt @@ -28,8 +28,12 @@ import androidx.wear.tiles.TileBuilders import androidx.wear.tiles.TileService import com.google.common.util.concurrent.ListenableFuture import dagger.hilt.android.AndroidEntryPoint +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.withContext import to.bitkit.wear.R +import to.bitkit.wear.di.IoDispatcher import to.bitkit.wear.repositories.WalletRepo +import to.bitkit.wear.security.DeviceLock import to.bitkit.wear.ui.LaunchRequest import to.bitkit.wear.ui.MainActivity import to.bitkit.wear.ui.screens.home.DisplayAmount @@ -68,9 +72,20 @@ class BalanceTileService : TileService() { @Inject lateinit var walletRepo: WalletRepo + @Inject + lateinit var deviceLock: DeviceLock + + @Inject + @IoDispatcher + lateinit var ioDispatcher: CoroutineDispatcher + override fun onTileRequest(requestParams: RequestBuilders.TileRequest): ListenableFuture = SuspendToFutureAdapter.launchFuture { - val state = tileState(walletRepo.hasWallet(), walletRepo.walletState.value) + val isLocked = withContext(ioDispatcher) { + deviceLock.refresh() + deviceLock.isLocked.value + } + val state = tileState(walletRepo.hasWallet(), walletRepo.walletState.value, isLocked) TileBuilders.Tile.Builder() .setResourcesVersion(RESOURCES_VERSION) .setFreshnessIntervalMillis(FRESHNESS.inWholeMilliseconds) diff --git a/wear/src/main/java/to/bitkit/wear/tile/TileState.kt b/wear/src/main/java/to/bitkit/wear/tile/TileState.kt index 245cbf1d2c..b8c91c6487 100644 --- a/wear/src/main/java/to/bitkit/wear/tile/TileState.kt +++ b/wear/src/main/java/to/bitkit/wear/tile/TileState.kt @@ -17,12 +17,19 @@ sealed interface TileState { /** * The tile's state for a watch that [hasWallet] in [wallet]'s state. The balance shows only once a sync of this - * process confirmed it, as on the Balance page, and never while the watch is locked; the tile never starts the wallet - * to learn it. + * process confirmed it, as on the Balance page, and never while the watch [isLocked]; the tile never starts the wallet + * to learn it. The lock is read from the watch, not only from [WalletStatus.Locked]: locking a paused wallet leaves it + * [WalletStatus.Paused]. */ -fun tileState(hasWallet: Boolean, wallet: WalletState, locale: Locale = Locale.getDefault()): TileState { +fun tileState( + hasWallet: Boolean, + wallet: WalletState, + isLocked: Boolean, + locale: Locale = Locale.getDefault(), +): TileState { if (!hasWallet || wallet.status in walletGoneStatuses) return TileState.SignedOut - val sats = wallet.balanceSats?.takeIf { wallet.hasSynced && wallet.status != WalletStatus.Locked }?.toLong() + val isHidden = isLocked || wallet.status == WalletStatus.Locked + val sats = wallet.balanceSats?.takeIf { wallet.hasSynced && !isHidden }?.toLong() return TileState.Wallet(sats?.let { bitcoinAmount(it, locale) }) } diff --git a/wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt b/wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt index b2e4821edd..6dadee2458 100644 --- a/wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt +++ b/wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt @@ -6,32 +6,35 @@ import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import to.bitkit.wear.di.IoDispatcher import to.bitkit.wear.repositories.WalletRepo +import to.bitkit.wear.security.DeviceLock import javax.inject.Inject import javax.inject.Singleton /** - * Asks the system to draw the tile again whenever what it shows may change: the balance, or the wallet's status, which - * also changes when a wallet is restored or removed. The first state of a process counts too, so a tile drawn by an - * earlier process drops the balance this one has not loaded. + * Asks the system to draw the tile again whenever what it shows may change: the balance, the watch's lock, or the + * wallet's status, which also changes when a wallet is restored or removed. The first state of a process counts too, + * so a tile drawn by an earlier process drops the balance this one has not loaded. */ @Singleton class TileUpdates @Inject constructor( @ApplicationContext private val context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher, private val walletRepo: WalletRepo, + private val deviceLock: DeviceLock, ) { private val scope = CoroutineScope(ioDispatcher + SupervisorJob()) /** Follows the wallet for the life of the process. */ fun start() { scope.launch { - walletRepo.walletState - .map { tileState(hasWallet = true, wallet = it) to it.status } + combine(walletRepo.walletState, deviceLock.isLocked) { wallet, isLocked -> + tileState(hasWallet = true, wallet = wallet, isLocked = isLocked) to wallet.status + } .distinctUntilChanged() .collect { TileService.getUpdater(context).requestUpdate(BalanceTileService::class.java) } } diff --git a/wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt b/wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt index 206a2edf85..c2e89c6876 100644 --- a/wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt +++ b/wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt @@ -10,7 +10,7 @@ import kotlin.test.assertEquals class TileStateTest { @Test fun `without a wallet the tile only opens the app`() { - assertEquals(TileState.SignedOut, tileState(hasWallet = false, WalletState(WalletStatus.Idle), Locale.US)) + assertEquals(TileState.SignedOut, tile(WalletState(WalletStatus.Idle), hasWallet = false)) } @Test @@ -19,11 +19,11 @@ class TileStateTest { assertEquals( TileState.SignedOut, - tileState(hasWallet = true, synced.copy(status = WalletStatus.Missing), Locale.US), + tile(synced.copy(status = WalletStatus.Missing)), ) assertEquals( TileState.SignedOut, - tileState(hasWallet = true, synced.copy(status = WalletStatus.Removed), Locale.US), + tile(synced.copy(status = WalletStatus.Removed)), ) } @@ -33,7 +33,7 @@ class TileStateTest { assertEquals( TileState.Wallet(DisplayAmount("₿", "125 000")), - tileState(hasWallet = true, wallet, Locale.US), + tile(wallet), ) } @@ -43,9 +43,9 @@ class TileStateTest { val unsynced = WalletState(WalletStatus.Connecting, balanceSats = 0uL, hasSynced = false) val failed = WalletState(WalletStatus.Error, balanceSats = 5_000uL, hasSynced = false) - assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, notLoaded, Locale.US)) - assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, unsynced, Locale.US)) - assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, failed, Locale.US)) + assertEquals(TileState.Wallet(balance = null), tile(notLoaded)) + assertEquals(TileState.Wallet(balance = null), tile(unsynced)) + assertEquals(TileState.Wallet(balance = null), tile(failed)) } @Test @@ -53,14 +53,24 @@ class TileStateTest { val paused = WalletState(WalletStatus.Paused, balanceSats = 1_000uL, hasSynced = true) val offline = paused.copy(status = WalletStatus.Offline) - assertEquals(TileState.Wallet(DisplayAmount("₿", "1 000")), tileState(hasWallet = true, paused, Locale.US)) - assertEquals(TileState.Wallet(DisplayAmount("₿", "1 000")), tileState(hasWallet = true, offline, Locale.US)) + assertEquals(TileState.Wallet(DisplayAmount("₿", "1 000")), tile(paused)) + assertEquals(TileState.Wallet(DisplayAmount("₿", "1 000")), tile(offline)) } @Test fun `a locked watch hides the balance`() { val locked = WalletState(WalletStatus.Locked, balanceSats = 1_000uL, hasSynced = true) - assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, locked, Locale.US)) + assertEquals(TileState.Wallet(balance = null), tile(locked, isLocked = true)) } + + @Test + fun `a paused wallet on a locked watch hides the balance`() { + val paused = WalletState(WalletStatus.Paused, balanceSats = 1_000uL, hasSynced = true) + + assertEquals(TileState.Wallet(balance = null), tile(paused, isLocked = true)) + } + + private fun tile(wallet: WalletState, isLocked: Boolean = false, hasWallet: Boolean = true) = + tileState(hasWallet, wallet, isLocked, Locale.US) } From 56195b35ff591d08887265ee3d011b1e5907a5b3 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Fri, 4 Dec 2026 11:23:46 -0300 Subject: [PATCH 32/33] fix: stop waiting for a wallet whose start failed A wallet that cannot connect or sync in a fresh process ends in the error status, which nothing retries by itself, while Send, Receive and Activity waited only for Ready and loaded forever. Send now ends on its offline refusal, Receive shows its error and its retry starts the wallet again, and Activity shows the wallet error with a retry. Co-Authored-By: Claude Opus 5.5 --- .../ui/screens/activity/ActivityScreen.kt | 35 ++++++++++++++++++- .../ui/screens/activity/ActivityViewModel.kt | 12 +++++++ .../ui/screens/receive/ReceiveViewModel.kt | 16 ++++++--- .../wear/ui/screens/send/SendViewModel.kt | 8 +++-- .../screens/activity/ActivityViewModelTest.kt | 14 ++++++++ .../screens/receive/ReceiveViewModelTest.kt | 22 ++++++++++++ .../wear/ui/screens/send/SendViewModelTest.kt | 13 +++++++ 7 files changed, 111 insertions(+), 9 deletions(-) diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt index fe5ff61586..113d35897f 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt @@ -12,11 +12,14 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.wear.compose.material3.FilledTonalButton +import androidx.wear.compose.material3.FilledTonalIconButton import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.IconButtonDefaults import androidx.wear.compose.material3.ListHeader import androidx.wear.compose.material3.MaterialTheme import androidx.wear.compose.material3.SurfaceTransformation @@ -63,6 +66,7 @@ fun ActivityScreen( uiState = uiState.copy(nowSecs = rememberNowSecs(loadedSecs = uiState.nowSecs)), isAmbient = isAmbient(), onPaymentClick = onPaymentClick, + onRetryClick = viewModel::onRetryClick, modifier = modifier ) } @@ -91,10 +95,30 @@ private fun Content( uiState: ActivityUiState, isAmbient: Boolean, onPaymentClick: (String) -> Unit, + onRetryClick: () -> Unit, modifier: Modifier = Modifier, ) { when { isAmbient -> CenteredScreen(modifier = modifier) { DimIcon(modifier = Modifier.testTag("WatchActivityHidden")) } + !uiState.isLoaded && uiState.isError -> CenteredScreen(modifier = modifier) { + Text( + text = stringResource(R.string.home__error), + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.error, + textAlign = TextAlign.Center, + modifier = Modifier.testTag("WatchActivityError") + ) + FilledTonalIconButton( + onClick = onRetryClick, + shapes = IconButtonDefaults.animatedShapes(), + modifier = Modifier.testTag("WatchActivityRetry") + ) { + Icon( + painter = painterResource(R.drawable.ic_refresh), + contentDescription = stringResource(R.string.common__retry), + ) + } + } !uiState.isLoaded -> CenteredScreen(overlay = { BezelLoading() }, modifier = modifier) { DimIcon() } uiState.payments.isEmpty() -> CenteredScreen(modifier = modifier) { DimIcon() @@ -206,6 +230,7 @@ private fun Preview() { ), isAmbient = false, onPaymentClick = {}, + onRetryClick = {}, ) } } @@ -214,7 +239,15 @@ private fun Preview() { @Composable private fun PreviewEmpty() { WearPreview { - Content(uiState = ActivityUiState(isLoaded = true), isAmbient = false, onPaymentClick = {}) + Content(uiState = ActivityUiState(isLoaded = true), isAmbient = false, onPaymentClick = {}, onRetryClick = {}) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewError() { + WearPreview { + Content(uiState = ActivityUiState(isError = true), isAmbient = false, onPaymentClick = {}, onRetryClick = {}) } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt index c0ef8afca9..657b033292 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt @@ -52,6 +52,16 @@ class ActivityViewModel internal constructor( .map { } merge(connected, paymentsRepo.paymentChanges).collectLatest { load() } } + viewModelScope.launch { + walletRepo.walletState.collect { wallet -> + _uiState.update { it.copy(isError = wallet.status == WalletStatus.Error) } + } + } + } + + /** Starts the wallet again after a start that failed, which nothing else retries. */ + fun onRetryClick() { + viewModelScope.launch { walletRepo.start() } } private suspend fun load() { @@ -71,6 +81,8 @@ data class ActivityUiState( val payments: ImmutableList = persistentListOf(), /** Whether a list was read this session; until then the loading ring shows. */ val isLoaded: Boolean = false, + /** Whether the wallet could not start, so no list can be read until a retry. */ + val isError: Boolean = false, /** When the list was read, in epoch seconds, which the relative times count from. */ val nowSecs: Long = 0, ) { diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt index 2dd406e1b9..47402f1440 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt @@ -18,6 +18,7 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.wear.env.Env +import to.bitkit.wear.models.ReceiveError import to.bitkit.wear.models.ReceiveInvoice import to.bitkit.wear.models.WatchPayment import to.bitkit.wear.repositories.PaymentsRepo @@ -72,13 +73,17 @@ class ReceiveViewModel internal constructor( refresh() } - /** Makes a new invoice: after an error, and after the last one was paid. */ - fun onRefreshClick() = refresh() + /** + * Makes a new invoice: after an error, and after the last one was paid. A wallet whose start failed is started + * again first, since nothing else retries it. + */ + fun onRefreshClick() = refresh(isStartNeeded = walletRepo.walletState.value.status == WalletStatus.Error) - private fun refresh() { + private fun refresh(isStartNeeded: Boolean = false) { job?.cancel() job = viewModelScope.launch { _uiState.update { ReceiveUiState(isLoading = true) } + if (isStartNeeded) walletRepo.start() val paid = CompletableDeferred() val watcherScope = this val rotation = launch { rotate(watcherScope, paid) } @@ -134,9 +139,10 @@ class ReceiveViewModel internal constructor( created } - /** Makes an invoice once the wallet is ready. */ + /** Makes an invoice once the wallet is ready, or fails at once when the wallet could not start. */ private suspend fun create(): Result { - walletRepo.walletState.first { it.status == WalletStatus.Ready } + val wallet = walletRepo.walletState.first { it.status == WalletStatus.Ready || it.status == WalletStatus.Error } + if (wallet.status == WalletStatus.Error) return Result.failure(ReceiveError.NotReady()) return paymentsRepo.createInvoice() } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt index fdc6a2080a..82600f1ca2 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt @@ -88,7 +88,8 @@ class SendViewModel @Inject constructor( viewModelScope.launch { walletRepo.walletState.collect { wallet -> _uiState.update { it.copy(isWalletReady = wallet.status == WalletStatus.Ready) } - if (wallet.status == WalletStatus.Offline) dropOffline() + // A start that failed is not retried by itself, so the flow ends rather than wait for Ready. + if (wallet.status == WalletStatus.Offline || wallet.status == WalletStatus.Error) dropOffline() } } } @@ -126,8 +127,9 @@ class SendViewModel @Inject constructor( } /** - * Ends a flow whose send has not started on [SendStep.Offline]: on arrival, while the input is read or priced, - * during the amount entry or on review. A send already under way keeps its own outcome. + * Ends a flow whose send has not started on [SendStep.Offline], also when the wallet could not start: on arrival, + * while the input is read or priced, during the amount entry or on review. A send already under way keeps its own + * outcome. */ private fun dropOffline() { val step = _uiState.value.step diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt index 07137e4e35..a8ecf659a0 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt @@ -51,6 +51,20 @@ class ActivityViewModelTest : BaseUnitTest() { assertEquals(NOW, sut.uiState.value.nowSecs) } + @Test + fun `a wallet that fails to start shows the error, and the retry starts it again`() = test { + val sut = createSut() + + walletState.update { it.copy(status = WalletStatus.Error) } + + assertTrue(sut.uiState.value.isError) + assertFalse(sut.uiState.value.isLoaded) + + sut.onRetryClick() + + verify(walletRepo).start() + } + @Test fun `a payment or a sync reads the list again`() = test { walletState.update { it.copy(status = WalletStatus.Ready) } diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt index 05b09b5cfb..2e8d07f381 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt @@ -250,6 +250,28 @@ class ReceiveViewModelTest : BaseUnitTest() { assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) } + @Test + fun `a wallet that fails to start shows the error, and the retry starts it again`() = test { + walletState.update { WalletState(WalletStatus.Connecting) } + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + + walletState.update { it.copy(status = WalletStatus.Error) } + + assertTrue(sut.uiState.value.isError) + verify(paymentsRepo, never()).createInvoice() + + whenever(walletRepo.start()).doSuspendableAnswer { + walletState.update { it.copy(status = WalletStatus.Ready) } + Result.success(Unit) + } + sut.onRefreshClick() + + verify(walletRepo).start() + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + } + private fun invoice(bolt11: String = BOLT11, lifetime: Long = LIFETIME, hash: String = PAYMENT_HASH) = ReceiveInvoice(bolt11, hash, (NOW + lifetime).toULong()) diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt index 0fa916323a..b03d4524f0 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt @@ -127,6 +127,19 @@ class SendViewModelTest : BaseUnitTest() { verify(paymentsRepo).send(prepared) } + @Test + fun `a wallet that fails to start ends the flow instead of loading forever`() = test { + walletState.update { WalletState(WalletStatus.Connecting) } + stubInvoice(prepared()) + val sut = createSut() + assertEquals(SendStep.Loading, sut.uiState.value.step) + + walletState.update { it.copy(status = WalletStatus.Error) } + + assertEquals(SendStep.Offline, sut.uiState.value.step) + verify(paymentsRepo, never()).parse(any()) + } + @Test fun `a request that arrives offline ends on the offline error without being read`() = test { walletState.update { it.copy(status = WalletStatus.Offline) } From 4f30db5ca1b750ace26ce2db06f19914fc31b085 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Fri, 4 Dec 2026 11:23:47 -0300 Subject: [PATCH 33/33] docs: describe the wear payment screens after a failed wallet start Co-Authored-By: Claude Opus 5.5 --- docs/wear.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/wear.md b/docs/wear.md index 47f85a1919..eba6591920 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -162,7 +162,8 @@ On-screen copy stays short: a title or one line of at most about six words per s again, so a forgotten QR does not hold the screen at full brightness; a tap anywhere on that screen, or waking the watch from ambient mode, shows it for another 2 min. The invoice is made once the wallet is ready, under the loading ring; a failure shows one line and a retry (`WatchReceiveError`, - `WatchReceiveRetry`). An invoice is replaced by a new one a minute before it expires, and it stays on screen until + `WatchReceiveRetry`). A wallet that could not start (`WalletStatus.Error`) shows that error at once, and its retry + starts the wallet again before it makes the invoice. An invoice is replaced by a new one a minute before it expires, and it stays on screen until the new one exists; a replacement that fails is tried again every 5 s meanwhile, and when none exists by then, the loading ring, or the error, takes its place as it expires. A replaced invoice is still watched until it expires, so a payer who scanned the earlier QR gets the check too. An @@ -217,7 +218,8 @@ On-screen copy stays short: a title or one line of at most about six words per s offline" (`WatchSendOfflineError`), the reject haptic and OK (`WatchSendClose`), which closes the flow. The request is dropped, never kept to pay when the network returns, so nothing (QuickPay included) pays it later. Once the hold completed and the send started, going offline changes nothing: the send keeps its pending or - unknown outcome. + unknown outcome. A wallet that could not start (`WalletStatus.Error`) ends the flow the same way, since nothing + retries a failed start by itself and the flow would otherwise wait for Ready forever. `PaymentsRepo.skipConfirmation` is asked before the hold; it is always false until QuickPay (PR 3). - Screen readers: a screen reader's wearer cannot hold, and the button's click pays nothing, so the button offers "Pay" as a custom accessibility action, picked from the actions menu, and as its long click (a double @@ -240,7 +242,9 @@ On-screen copy stays short: a title or one line of at most about six words per s It is read when Spark connects and after every payment or sync, and the last list stays while Spark is disconnected, with its times counted again every minute; a list just read counts from its own time. A tap opens the detail: the amount, the fee of a send, the date and time and the status (`WatchActivityDetailAmount`, `…Fee`, `…Time`, `…Status`); Spark's list carries no payee or description. With no - payments it shows a dimmed icon and "No activity" (`WatchActivityEmpty`). A detail whose payment the list does not + payments it shows a dimmed icon and "No activity" (`WatchActivityEmpty`). A wallet that could not start before the + first list was read shows "Couldn't load wallet" and a retry that starts it again (`WatchActivityError`, + `WatchActivityRetry`). A detail whose payment the list does not hold, while it loads or after newer payments pushed it out, shows the dimmed icon (`WatchActivityDetailMissing`). Ambient mode hides the amounts. - **Settings.** A short list of icon rows: About and Remove wallet. The unit has no setting: tapping the balance is